interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / convert_zaya_mxfp4.py

160 lines · 7223 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Convert ZAYA-8B MXFP4 (HF format) → llama.cpp naming for MojoLlama engine."""
3import sys, os, gguf, numpy as np
4from gguf import GGUFWriter, GGUFReader, GGMLQuantizationType as QT
5
6SRC = '/onedev-workspace/work/models/ZAYA1-8B-MXFP4.gguf'
7DST = '/onedev-workspace/work/models/ZAYA1-8B-MXFP4-converted.gguf'
8
9reader = GGUFReader(SRC)
10fields = reader.fields
11def gm(k, d=None):
12 v = fields.get(k)
13 if v is None: return d
14 p = getattr(v, 'parts', None)
15 if p:
16 d = p[-1]
17 if hasattr(d, '__iter__'):
18 vals = list(d)
19 return vals[0] if len(vals) == 1 else vals
20 return d
21 return d
22
23n_layer, n_exp = int(gm('zaya.block_count',80)), int(gm('zaya.expert_count',16))
24n_embd = int(gm('zaya.embedding_length',2048))
25n_head, n_kv_head = int(gm('zaya.attention.head_count',8)), int(gm('zaya.attention.head_count_kv',2))
26vocab = int(gm('zaya.vocab_size',262272))
27print(f'{n_layer}L {n_exp}E {n_embd}D {n_head}H')
28
29tensors = {t.name: t for t in reader.tensors}
30has = lambda n: n in tensors
31t = lambda n: tensors[n]
32
33writer = GGUFWriter(DST, 'zaya')
34writer.add_block_count(n_layer); writer.add_embedding_length(n_embd)
35writer.add_feed_forward_length(4096); writer.add_context_length(131072)
36writer.add_head_count(n_head); writer.add_head_count_kv(n_kv_head)
37writer.add_layer_norm_rms_eps(1e-5); writer.add_expert_count(n_exp)
38writer.add_expert_used_count(1); writer.add_file_type(39)
39writer.add_name('ZAYA1-8B-MXFP4-converted')
40writer.add_vocab_size(vocab); writer.add_rope_dimension_count(64)
41writer.add_rope_freq_base(5000000.0); writer.add_quantization_version(1)
42
43def _raw_shape(tsrc):
44 """Compute byte-level shape for a tensor."""
45 log = [int(s) for s in tsrc.shape]
46 qt = tsrc.tensor_type
47 if qt == 0: # F32
48 return log
49 elif qt == 1: # F16
50 return log[:-1] + [log[-1] * 2]
51 else: # Quantized — quantize the second-to-last dim (columns)
52 blk_sz = 32
53 blk_bytes = {39: 17}.get(qt, 34)
54 # For 2D: [rows, quantized_cols]
55 # For 3D (packed experts): [rows, quantized_cols, n_experts]
56 n_blk = (log[-2] + blk_sz - 1) // blk_sz if len(log) >= 2 else (log[-1] + blk_sz - 1) // blk_sz
57 if len(log) >= 3:
58 return log[:-2] + [n_blk * blk_bytes] + log[-1:]
59 else:
60 return log[:-1] + [n_blk * blk_bytes]
61
62def add(name, tsrc):
63 log_shape = [int(s) for s in tsrc.shape]
64 qt = QT(tsrc.tensor_type)
65 raw = tsrc.data.tobytes() if hasattr(tsrc.data,'tobytes') else bytes(tsrc.data)
66 arr = np.frombuffer(raw, dtype=np.uint8)
67
68 # Handle edge case: quantized tensors with last dim < block size
69 if qt not in (QT.F32, QT.F16) and len(log_shape) >= 2 and log_shape[-1] < 32:
70 f32 = gguf.dequantize(tsrc.data, tsrc.tensor_type).astype(np.float32)
71 if len(log_shape) == 2:
72 f32 = f32.reshape(log_shape)
73 add_f32(name, f32)
74 return
75
76 writer.add_tensor(name, arr, raw_shape=_raw_shape(tsrc), raw_dtype=qt)
77
78def add_f32(name, d32):
79 # Preserve 2D shape when adding
80 if len(d32.shape) >= 2:
81 writer.add_tensor(name, d32.astype(np.float32), raw_dtype=QT(0))
82 else:
83 writer.add_tensor(name, d32.astype(np.float32), raw_dtype=QT(0))
84
85# Global
86for s,d in [('model.embed_tokens.weight','token_embd.weight'),('model.final_norm.weight','output_norm.weight')]:
87 if has(s): add(d, t(s)); print(f' {s} → {d}')
88for sn in ['hidden_states_scale','hidden_states_bias','residual_scale','residual_bias']:
89 k = f'model.res_scale.{sn}'
90 if has(k):
91 d32 = gguf.dequantize(t(k).data, t(k).tensor_type).astype(np.float32).ravel()
92 pr = 'res_scale_hs' if 'hidden' in sn else 'res_scale_res'
93 sf = 'weight' if 'scale' in sn else 'bias'
94 add_f32(f'{pr}.{sf}', d32)
95
96for l in range(n_layer):
97 ps, pd = f'model.layers.{l}', f'blk.{l}'
98 even = l % 2 == 0
99 if has(f'{ps}.input_norm.weight'):
100 add(f'{pd}.attn_norm.weight', t(f'{ps}.input_norm.weight'))
101
102 if even:
103 for src_s, dst_s in [('self_attn.qkv.linear_q','attn_q'),('self_attn.qkv.linear_k','attn_k'),
104 ('self_attn.o_proj','attn_output')]:
105 if has(f'{ps}.{src_s}.weight'): add(f'{pd}.{dst_s}.weight', t(f'{ps}.{src_s}.weight'))
106 for i in [1,2]:
107 if has(f'{ps}.self_attn.qkv.val_proj{i}.weight'):
108 add(f'{pd}.cca_val_proj{i}.weight', t(f'{ps}.self_attn.qkv.val_proj{i}.weight'))
109 for sf in ['weight','bias']:
110 if has(f'{ps}.self_attn.qkv.conv_qk.0.{sf}'):
111 add(f'{pd}.ssm_conv1d.{sf}', t(f'{ps}.self_attn.qkv.conv_qk.0.{sf}'))
112 for sn in ['hidden_states_scale','hidden_states_bias']:
113 k = f'{ps}.res_scale.{sn}'
114 if has(k):
115 d32 = gguf.dequantize(t(k).data, t(k).tensor_type).astype(np.float32).ravel()
116 add_f32(f'{pd}.res_scale_hs.{"weight" if "scale" in sn else "bias"}', d32)
117 else:
118 router_map = [
119 ('zaya_block.router.rmsnorm_eda.weight', 'ffn_norm.weight'),
120 ('zaya_block.router.down_proj.weight', 'ffn_gate_inp.weight'),
121 ('zaya_block.router.down_proj.bias', 'ffn_gate_inp.bias'),
122 ('zaya_block.router.router_mlp.0.weight', 'ffn_gate.weight'),
123 ('zaya_block.router.router_mlp.0.bias', 'ffn_gate.bias'),
124 ('zaya_block.router.router_mlp.2.weight', 'zaya_router_mlp2.weight'),
125 ('zaya_block.router.router_mlp.2.bias', 'zaya_router_mlp2.bias'),
126 ('zaya_block.router.router_mlp.4.weight', 'zaya_router_mlp4.weight'),
127 ]
128 for src_s, dst_s in router_map:
129 k = f'{ps}.{src_s}'
130 if has(k): add(f'{pd}.{dst_s}', t(k))
131
132 k = f'{ps}.zaya_block.router.balancing_biases'
133 if has(k):
134 d32 = gguf.dequantize(t(k).data, t(k).tensor_type).astype(np.float32).ravel()[:17]
135 add_f32(f'{pd}.zaya_router_biases.weight', d32)
136
137 for sn in ['hidden_states_scale','hidden_states_bias','residual_scale','residual_bias']:
138 k = f'{ps}.res_scale.{sn}'
139 if has(k):
140 d32 = gguf.dequantize(t(k).data, t(k).tensor_type).astype(np.float32).ravel()
141 pr = 'res_scale_hs' if 'hidden' in sn else 'res_scale_res'
142 sf = 'weight' if 'scale' in sn else 'bias'
143 add_f32(f'{pd}.{pr}.{sf}', d32)
144
145 # Per-expert weights (store individually since GGUF can't pack MXFP4 into 3D)
146 exp_names = {}
147 for e in range(n_exp):
148 for src_w, dst_w in [('linear_fc1','ffn_gate_up_exps'),('linear_fc2','ffn_down_exps')]:
149 k = f'{ps}.zaya_block.experts.local_experts.{e}.{src_w}.weight'
150 if has(k):
151 dst = f'{pd}.{dst_w}.{e}.weight'
152 add(dst, t(k))
153 exp_names.setdefault(dst_w, []).append(dst)
154 if l % 10 == 0: print(f' L{l}/{n_layer}', flush=True)
155
156print('Writing GGUF...', flush=True)
157writer.write_header_to_file(); writer.write_kv_data_to_file()
158writer.write_tensors_to_file(); writer.close()
159sz = os.path.getsize(DST) / 1e9
160print(f'Done! {sz:.2f} GB → {DST}')