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 / convert_zaya_to_mxfp4.py

274 lines · 10151 bytes Raw Blame History
1#!/usr/bin/env python3
2"""
3Convert Zyphra/ZAYA1-8B HuggingFace safetensors → MXFP4 GGUF.
4
5MXFP4 format (GGML type 39):
6 - 32-element blocks
7 - 16 bytes packed 4-bit two's complement mantissas
8 - 1 byte E8M0 scale per block (exponent, bias 127)
9 - Total: 17 bytes per 32 elements
10
11Usage:
12 python3 convert_zaya_to_mxfp4.py [output_dir]
13"""
14
15import os, sys, json, time, math, gc
16import numpy as np
17from pathlib import Path
18
19MXFP4_BLOCK_SIZE = 32
20MXFP4_BLOCK_BYTES = 17
21
22
23# ─── MXFP4 quantization ──────────────────────────────────────────────────────
24
25def quantize_mxfp4(arr_f32: np.ndarray) -> bytes:
26 """Vectorized MXFP4 quantization of a flat float32 array."""
27 n = arr_f32.shape[0]
28 n_blocks = (n + MXFP4_BLOCK_SIZE - 1) // MXFP4_BLOCK_SIZE
29 padded_n = n_blocks * MXFP4_BLOCK_SIZE
30
31 if n < padded_n:
32 arr_f32 = np.pad(arr_f32, (0, padded_n - n))
33
34 blocks = arr_f32.reshape(n_blocks, MXFP4_BLOCK_SIZE)
35
36 amax = np.max(np.abs(blocks), axis=1)
37 with np.errstate(divide='ignore', invalid='ignore'):
38 exp = np.floor(np.log2(amax)).astype(np.int32) + 127
39 exp = np.clip(exp, 0, 255)
40 exp[amax == 0.0] = 0
41
42 scales = np.ldexp(np.ones(n_blocks, dtype=np.float32), exp.astype(np.int32) - 127)
43
44 q = np.round(blocks / scales[:, np.newaxis]).astype(np.int32)
45 q = np.clip(q, -8, 7)
46 q[exp == 0] = 0
47
48 nibbles = np.clip(q + 8, 0, 15).astype(np.uint8)
49 packed = np.bitwise_or(nibbles[:, 0::2], nibbles[:, 1::2].astype(np.uint16) << 4).astype(np.uint8)
50
51 result = np.zeros(n_blocks * MXFP4_BLOCK_BYTES, dtype=np.uint8)
52 result.reshape(n_blocks, MXFP4_BLOCK_BYTES)[:, :16] = packed
53 result.reshape(n_blocks, MXFP4_BLOCK_BYTES)[:, 16] = exp.astype(np.uint8)
54
55 return bytes(result)
56
57
58def quantize_mxfp4_rowwise(arr_f32: np.ndarray) -> np.ndarray:
59 """Quantize float32 array to MXFP4 byte array, row by row.
60
61 For 2D [rows, cols]: quantize each row → byte shape [rows, n_blocks * 17]
62 For 1D [n]: → byte shape [1, n_blocks * 17]
63 For 3D+ [d0, d1, d2, ...]: → flatten to 2D [d0, d1*d2*...], quantize, restore shape
64 """
65 orig_ndim = arr_f32.ndim
66 if orig_ndim == 1:
67 arr_f32 = arr_f32.reshape(1, -1)
68
69 # Flatten 3D+ to 2D [rows, cols]
70 if arr_f32.ndim > 2:
71 arr_f32 = arr_f32.reshape(arr_f32.shape[0], -1)
72
73 rows, cols = arr_f32.shape
74 n_blocks_per_row = (cols + MXFP4_BLOCK_SIZE - 1) // MXFP4_BLOCK_SIZE
75 n_bytes_per_row = n_blocks_per_row * MXFP4_BLOCK_BYTES
76
77 result = np.zeros((rows, n_bytes_per_row), dtype=np.uint8)
78 for r in range(rows):
79 qbytes = quantize_mxfp4(arr_f32[r])
80 result[r] = np.frombuffer(qbytes, dtype=np.uint8)
81
82 return result
83
84
85# ─── Helpers ──────────────────────────────────────────────────────────────────
86
87def should_quantize(name: str) -> bool:
88 """Only quantize weight matrices (keep norms/biases/embeddings as F16)."""
89 skip_suffixes = [
90 'norm.weight', 'norm.bias',
91 'attn_norm.weight', 'attn_norm.bias',
92 'ffn_norm.weight', 'ffn_norm.bias',
93 'res_scale_hs.weight', 'res_scale_hs.bias',
94 'res_scale_res.weight', 'res_scale_res.bias',
95 'zaya_router_mlp2.bias', 'zaya_router_mlp4.bias',
96 'zaya_router_biases.bias',
97 'ffn_gate_inp.bias', 'ffn_gate.bias',
98 'token_embd.weight',
99 'embed_tokens.weight',
100 'output_norm.weight', 'output_norm.bias',
101 'output.weight',
102 'lm_head.weight',
103 ]
104 for suffix in skip_suffixes:
105 if name.endswith(suffix):
106 return False
107 return True
108
109
110def download_shards(repo_id: str, index_file: str, cache_dir: str = None):
111 """Download all safetensor shards."""
112 from huggingface_hub import hf_hub_download
113 import json as j
114
115 index_path = hf_hub_download(repo_id, index_file, cache_dir=cache_dir)
116 with open(index_path) as f:
117 index = j.load(f)
118
119 weight_map = index.get('weight_map', {})
120
121 shard_files = set(weight_map.values())
122 shard_paths = {}
123 for shard in shard_files:
124 shard_paths[shard] = hf_hub_download(repo_id, shard, cache_dir=cache_dir)
125
126 return weight_map, shard_paths
127
128
129# ─── Main converter ───────────────────────────────────────────────────────────
130
131def convert_zaya_to_mxfp4(output_dir: str = "models", hf_cache: str = None):
132 """Convert Zyphra/ZAYA1-8B safetensors to MXFP4 GGUF."""
133 import torch
134 from safetensors import safe_open
135 from huggingface_hub import hf_hub_download
136 from gguf import GGUFWriter
137 from gguf.constants import GGMLQuantizationType as QT
138
139 os.makedirs(output_dir, exist_ok=True)
140 output_path = os.path.join(output_dir, "ZAYA1-8B-MXFP4.gguf")
141 repo_id = "Zyphra/ZAYA1-8B"
142
143 print("=" * 60)
144 print(" Zyphra/ZAYA1-8B → MXFP4 GGUF Converter")
145 print("=" * 60)
146
147 # ─── Load config ───
148 print("\n[1/4] Loading config...")
149 config_path = hf_hub_download(repo_id, "config.json", cache_dir=hf_cache)
150 with open(config_path) as f:
151 config = json.load(f)
152
153 hidden_size = config['hidden_size']
154 n_layers = config['num_hidden_layers']
155 n_heads = config['num_attention_heads']
156 n_kv_heads = config.get('num_key_value_heads', config.get('num_query_groups', n_heads))
157 n_experts = config.get('num_experts', 16)
158 n_experts_per_tok = config.get('moe_router_topk', 1)
159 vocab_size = config['vocab_size']
160 intermediate_size = config.get('ffn_hidden_size', config.get('intermediate_size'))
161 head_dim = config.get('head_dim', hidden_size // n_heads)
162 rope_theta = config.get('rope_theta', 10000.0)
163 norm_eps = config.get('norm_epsilon', 1e-5)
164 partial_rotary = config.get('partial_rotary_factor', 0.5)
165 max_seq_len = config.get('max_position_embeddings', 131072)
166
167 print(f" Layers: {n_layers}, Heads: {n_heads}, KV: {n_kv_heads}")
168 print(f" Hidden: {hidden_size}, Intermediate: {intermediate_size}")
169 print(f" Vocab: {vocab_size}, Experts: {n_experts}")
170
171 # ─── Download ───
172 print("\n[2/4] Downloading safetensor shards...")
173 weight_map, shard_paths = download_shards(repo_id, "model.safetensors.index.json", hf_cache)
174 print(f" {len(shard_paths)} shard(s), {len(weight_map)} tensor(s)")
175
176 total_params = len(weight_map)
177 total_quantized = 0
178 total_skipped = 0
179
180 shard_handles = {name: safe_open(path, framework="pt") for name, path in shard_paths.items()}
181
182 # ─── Quantize ───
183 print("\n[3/4] Quantizing tensors to MXFP4...")
184
185 quantized_tensors = [] # (name, data_bytes, ggml_type, shape)
186 t0 = time.time()
187
188 for idx, (name, shard_name) in enumerate(weight_map.items()):
189 handle = shard_handles[shard_name]
190 tensor_pt = handle.get_tensor(name)
191 tensor = tensor_pt.to(torch.float32).numpy()
192 is_quant = should_quantize(name)
193
194 if is_quant:
195 qdata = quantize_mxfp4_rowwise(tensor)
196 ggml_type = QT.MXFP4
197 total_quantized += 1
198 else:
199 qdata = tensor.astype(np.float16).view(np.uint8)
200 ggml_type = QT.F16
201 total_skipped += 1
202
203 quantized_tensors.append((name, qdata, ggml_type))
204
205 if (idx + 1) % 20 == 0 or (idx + 1) == total_params:
206 elapsed = time.time() - t0
207 print(f" [{idx+1}/{total_params}] {name:60s} → "
208 f"{'MXFP4' if is_quant else 'F16':5s} ({elapsed:.1f}s)")
209
210 for h in shard_handles.values():
211 del h
212
213 # ─── Write GGUF ───
214 print("\n[4/4] Writing GGUF using gguf.GGUFWriter...")
215 t1 = time.time()
216
217 rope_dim = int(head_dim * partial_rotary)
218 w = GGUFWriter(output_path, "zaya")
219
220 # Metadata
221 w.add_string("general.architecture", "zaya")
222 w.add_string("general.name", "ZAYA1-8B-MXFP4")
223 w.add_string("general.description", "Zyphra ZAYA1-8B quantized to MXFP4")
224 w.add_int32("general.file_type", 39)
225 w.add_int32("general.quantization_version", 1)
226 w.add_string("general.source.huggingface", "Zyphra/ZAYA1-8B")
227 w.add_int32("zaya.block_count", n_layers)
228 w.add_int32("zaya.context_length", max_seq_len)
229 w.add_int32("zaya.embedding_length", hidden_size)
230 w.add_int32("zaya.feed_forward_length", intermediate_size)
231 w.add_int32("zaya.attention.head_count", n_heads)
232 w.add_int32("zaya.attention.head_count_kv", n_kv_heads)
233 w.add_int32("zaya.attention.head_dim", head_dim)
234 w.add_float32("zaya.attention.layer_norm_rms_epsilon", norm_eps)
235 w.add_int32("zaya.rope.dimension_count", rope_dim)
236 w.add_float32("zaya.rope.freq_base", rope_theta)
237 w.add_int32("zaya.expert_count", n_experts)
238 w.add_int32("zaya.experts_used_count", n_experts_per_tok)
239 w.add_int32("zaya.vocab_size", vocab_size)
240
241 # Tensors
242 for name, data, ggml_type in quantized_tensors:
243 if ggml_type == QT.MXFP4:
244 w.add_tensor(name, data, raw_dtype=QT.MXFP4)
245 else:
246 w.add_tensor(name, data, raw_dtype=QT.F16)
247
248 w.write_header_to_file()
249 w.write_kv_data_to_file()
250 w.write_tensors_to_file()
251 w.close()
252
253 elapsed_total = time.time() - t0
254 file_size = os.path.getsize(output_path)
255 gc.collect()
256
257 print(f"\n {'='*50}")
258 print(f" Conversion Complete")
259 print(f" {'='*50}")
260 print(f" Output: {output_path}")
261 print(f" Total tensors: {total_params}")
262 print(f" MXFP4: {total_quantized}")
263 print(f" F16: {total_skipped}")
264 print(f" File size: {file_size / 1024**3:.2f} GB")
265 print(f" Total time: {elapsed_total:.1f}s")
266 print(f" {'='*50}")
267
268 return output_path
269
270
271if __name__ == '__main__':
272 out_dir = sys.argv[1] if len(sys.argv) > 1 else "models"
273 output = convert_zaya_to_mxfp4(out_dir)
274 print(f"\nDone: {output}")