MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / src / mojollama / mojo_engine / extract_zaya_weights.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Extract ZAYA1-8B weights from Q8_0 GGUF to .bin files for Mojo engine. |
| 4 | |
| 5 | Output: /tmp/weights_zaya/*.bin — one file per weight matrix. |
| 6 | - Q8_0 matmul weights: raw Q8_0 bytes (34 bytes per 32-element block) |
| 7 | - F32 norm/scale/bias weights: raw f32 bytes |
| 8 | - Expert weights: packed 3D Q8_0 tensors, one file per expert group |
| 9 | """ |
| 10 | import sys, os, json, struct |
| 11 | import numpy as np |
| 12 | sys.path.insert(0, '/onedev-workspace/work/src/mojollama/kernels') |
| 13 | import gguf |
| 14 | |
| 15 | GGUF_PATH = '/tmp/models/ZAYA1-8B-Q8_0.gguf' |
| 16 | OUT_DIR = '/tmp/weights_zaya' |
| 17 | |
| 18 | # Architecture constants |
| 19 | NE = 2048 # hidden_size |
| 20 | NH = 8 # num_attention_heads |
| 21 | NK = 2 # num_key_value_heads |
| 22 | HD = 128 # head_dim |
| 23 | NL = 80 # num_hidden_layers |
| 24 | N_EXP = 16 # num_experts |
| 25 | N_EXP_USED = 1 # moe_router_topk |
| 26 | FF = 4096 # expert intermediate (gate+up combined) |
| 27 | NV = 262147 # vocab_size |
| 28 | ROPE_DIM = 64 |
| 29 | RPE_THETA = 5000000.0 |
| 30 | |
| 31 | # Q8_0 constants |
| 32 | QK = 32 # block size |
| 33 | QB = 34 # bytes per block (2 scale + 32 quants) |
| 34 | |
| 35 | def dump_raw_bin(tensor_data: bytes, path: str): |
| 36 | os.makedirs(os.path.dirname(path), exist_ok=True) |
| 37 | with open(path, 'wb') as f: |
| 38 | f.write(tensor_data) |
| 39 | print(f" {os.path.basename(path)}: {len(tensor_data)} bytes") |
| 40 | |
| 41 | def make_tensor_map(reader): |
| 42 | return {t.name: t for t in reader.tensors} |
| 43 | |
| 44 | def extract_tensor_raw(tensor_map, tensor_name: str) -> bytes: |
| 45 | t = tensor_map.get(tensor_name) |
| 46 | if t is None: |
| 47 | return None |
| 48 | data = t.data |
| 49 | # numpy memmap or ndarray |
| 50 | if hasattr(data, 'tobytes'): |
| 51 | return data.tobytes() |
| 52 | return bytes(data) |
| 53 | |
| 54 | def extract_f32_as_f16(tensor_map, tensor_name: str) -> bytes: |
| 55 | t = tensor_map.get(tensor_name) |
| 56 | if t is None: |
| 57 | return None |
| 58 | arr = np.array(t.data, dtype=np.float32) |
| 59 | f16_arr = arr.astype(np.float16) |
| 60 | return f16_arr.tobytes() |
| 61 | |
| 62 | def extract_f32_raw(tensor_map, tensor_name: str) -> bytes: |
| 63 | t = tensor_map.get(tensor_name) |
| 64 | if t is None: |
| 65 | return None |
| 66 | arr = np.array(t.data, dtype=np.float32) |
| 67 | return arr.tobytes() |
| 68 | |
| 69 | def main(): |
| 70 | os.makedirs(OUT_DIR, exist_ok=True) |
| 71 | reader = gguf.GGUFReader(GGUF_PATH) |
| 72 | |
| 73 | print(f"=== Extracting ZAYA1-8B weights from GGUF ===") |
| 74 | |
| 75 | # ─── Global weights ─── |
| 76 | print("\n--- Global ---") |
| 77 | |
| 78 | # token_embd.weight: [2048, 262147] Q8_0 → token_embd_weight.bin (raw Q8_0) |
| 79 | raw = extract_tensor_raw(reader, 'token_embd.weight') |
| 80 | if raw: |
| 81 | dump_raw_bin(raw, f'{OUT_DIR}/token_embd_weight.bin') |
| 82 | |
| 83 | # output_norm.weight: [2048] F32 → output_norm_weight.bin |
| 84 | raw = extract_f32_raw(reader, 'output_norm.weight') |
| 85 | if raw: |
| 86 | dump_raw_bin(raw, f'{OUT_DIR}/output_norm_weight.bin') |
| 87 | |
| 88 | # ─── Per-layer weights ─── |
| 89 | for l in range(NL): |
| 90 | prefix = f'blk.{l}' |
| 91 | |
| 92 | # Every layer has these: |
| 93 | tensors_every = [ |
| 94 | ('attn_norm.weight', f'attn_norm_weight.bin', 'f32'), |
| 95 | ('res_scale_hs.weight', f'res_scale_hs_weight.bin', 'f32'), |
| 96 | ('res_scale_hs.bias', f'res_scale_hs_bias.bin', 'f32'), |
| 97 | ('res_scale_res.weight', f'res_scale_res_weight.bin', 'f32'), |
| 98 | ('res_scale_res.bias', f'res_scale_res_bias.bin', 'f32'), |
| 99 | ] |
| 100 | |
| 101 | if l % 2 == 0: # Attention layer |
| 102 | tensors_specific = [ |
| 103 | ('attn_q.weight', f'attn_q_weight.bin', 'q8'), |
| 104 | ('attn_k.weight', f'attn_k_weight.bin', 'q8'), |
| 105 | ('attn_output.weight', f'attn_output_weight.bin', 'q8'), |
| 106 | # CCA weights (extracted but not used in simple GQA path) |
| 107 | ('cca_val_proj1.weight', f'cca_val_proj1_weight.bin', 'q8'), |
| 108 | ('cca_val_proj2.weight', f'cca_val_proj2_weight.bin', 'q8'), |
| 109 | ('cca_conv_grp.weight', f'cca_conv_grp_weight.bin', 'raw'), |
| 110 | ('cca_conv_grp.bias', f'cca_conv_grp_bias.bin', 'f32'), |
| 111 | ('cca_k_scale.weight', f'cca_k_scale_weight.bin', 'f32'), |
| 112 | ('ssm_conv1d.weight', f'ssm_conv1d_weight.bin', 'raw'), |
| 113 | ('ssm_conv1d.bias', f'ssm_conv1d_bias.bin', 'f32'), |
| 114 | ] |
| 115 | else: # MoE layer |
| 116 | tensors_specific = [ |
| 117 | ('ffn_norm.weight', f'ffn_norm_weight.bin', 'f32'), |
| 118 | ('ffn_gate_inp.weight', f'ffn_gate_inp_weight.bin', 'f32'), |
| 119 | ('ffn_gate_inp.bias', f'ffn_gate_inp_bias.bin', 'f32'), |
| 120 | ('ffn_gate.weight', f'ffn_gate_weight.bin', 'q8'), |
| 121 | ('ffn_gate.bias', f'ffn_gate_bias.bin', 'f32'), |
| 122 | ('zaya_router_mlp2.weight', f'zaya_router_mlp2_weight.bin', 'q8'), |
| 123 | ('zaya_router_mlp2.bias', f'zaya_router_mlp2_bias.bin', 'f32'), |
| 124 | ('zaya_router_mlp4.weight', f'zaya_router_mlp4_weight.bin', 'q8'), |
| 125 | ('zaya_router_biases.weight', f'zaya_router_biases_weight.bin', 'f32'), |
| 126 | ('zaya_router_eda.weight', f'zaya_router_eda_weight.bin', 'f32'), |
| 127 | ('ffn_gate_up_exps.weight', f'ffn_gate_up_exps_weight.bin', 'q8'), |
| 128 | ('ffn_down_exps.weight', f'ffn_down_exps_weight.bin', 'q8'), |
| 129 | ] |
| 130 | |
| 131 | for tensor_suffix, out_name, dtype in tensors_every + tensors_specific: |
| 132 | tensor_name = f'{prefix}.{tensor_suffix}' |
| 133 | fn = f'{OUT_DIR}/blk_{l}_{out_name}' |
| 134 | |
| 135 | if dtype == 'q8': |
| 136 | raw = extract_tensor_raw(reader, tensor_name) |
| 137 | elif dtype == 'f32': |
| 138 | raw = extract_f32_raw(reader, tensor_name) |
| 139 | else: |
| 140 | raw = extract_tensor_raw(reader, tensor_name) |
| 141 | |
| 142 | if raw: |
| 143 | dump_raw_bin(raw, fn) |
| 144 | else: |
| 145 | print(f" MISSING: {tensor_name}") |
| 146 | |
| 147 | # ─── Write metadata ─── |
| 148 | meta = { |
| 149 | 'hidden_size': NE, |
| 150 | 'num_attention_heads': NH, |
| 151 | 'num_key_value_heads': NK, |
| 152 | 'head_dim': HD, |
| 153 | 'num_hidden_layers': NL, |
| 154 | 'num_experts': N_EXP, |
| 155 | 'expert_used_count': N_EXP_USED, |
| 156 | 'expert_intermediate_size': FF, |
| 157 | 'vocab_size': NV, |
| 158 | 'rope_dim': ROPE_DIM, |
| 159 | 'rope_theta': RPE_THETA, |
| 160 | 'max_seq_len': 128, |
| 161 | 'quant': 'Q8_0', |
| 162 | } |
| 163 | with open(f'{OUT_DIR}/meta.json', 'w') as f: |
| 164 | json.dump(meta, f, indent=2) |
| 165 | print(f"\nMetadata written to {OUT_DIR}/meta.json") |
| 166 | print("Done!") |
| 167 | |
| 168 | if __name__ == '__main__': |
| 169 | main() |