Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/kernels/dsv4/convert_dsv4_to_gguf.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / kernels / dsv4 / convert_dsv4_to_gguf.py` 482 lines · 19104 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """ 3 Convert Intel/DeepSeek-V4-Flash-W4A16-AutoRound to MojoLlama GGUF. 4 5 Streaming converter: processes one tensor at a time, downloads shards progressively. 6 Dequantizes W4A16 (AutoRound/GPTQ) → FP32 → re-quantizes to Q8_0 in GGUF. 7 8 Usage: 9 python3 convert_dsv4_to_gguf.py /tmp/models/deepseek-v4-flash-w4a16.gguf 10 """ 11 import os, sys, json, time, math, struct, gc 12 import numpy as np 13 from huggingface_hub import hf_hub_download, get_safetensors_metadata 14 from safetensors import safe_open 15 16 # ─── GGUF constants ─── 17 GGUF_MAGIC = 0x46554747 # "GGUF" 18 GGUF_VERSION = 3 19 20 # GGUF key types 21 GGUF_TYPE_UINT8 = 0; GGUF_TYPE_INT8 = 1; GGUF_TYPE_UINT16 = 2; GGUF_TYPE_INT16 = 3 22 GGUF_TYPE_UINT32 = 4; GGUF_TYPE_INT32 = 5; GGUF_TYPE_FLOAT32 = 6; GGUF_TYPE_BOOL = 7 23 GGUF_TYPE_STRING = 8; GGUF_TYPE_ARRAY = 9; GGUF_TYPE_UINT64 = 10; GGUF_TYPE_INT64 = 11 24 GGUF_TYPE_FLOAT64 = 12 25 26 # Quant types 27 GGML_TYPE_F32 = 0; GGML_TYPE_I32 = 26; GGML_TYPE_Q8_0 = 8 28 29 QK8_0 = 32 30 31 def pack_q8_0(arr_f32): 32 """Convert F32 block to Q8_0: scale (f16) + 32 int8 values.""" 33 n = arr_f32.shape[0] 34 assert n == QK8_0 35 amax = np.max(np.abs(arr_f32)) 36 if amax == 0: 37 scale = 0.0 38 d_i32 = np.zeros(n, dtype=np.int8) 39 else: 40 scale = amax / 127.0 41 d_i32 = np.clip(np.round(arr_f32 / scale), -128, 127).astype(np.int8) 42 # f16 scale 43 scale_f16 = np.float32(scale).view(np.uint16) 44 return scale_f16, d_i32 45 46 def quantize_q8_0(data): 47 """Quantize [N] F32 → Q8_0 bytes. N must be multiple of 32.""" 48 N = data.shape[0] 49 if N % QK8_0 != 0: 50 pad = QK8_0 - (N % QK8_0) 51 data = np.pad(data, (0, pad)) 52 blocks = data.reshape(-1, QK8_0) 53 result = bytearray() 54 for block in blocks: 55 f16_scale, i8_vals = pack_q8_0(block) 56 result += struct.pack('> shifts) & 0xF) # [in//8, 8, out] 76 w = w.reshape(in_features, out_features).astype(np.float32) 77 # Unpack qzeros 78 z = ((qzeros[:, :, None] >> shifts) & 0xF) # [in//g, out//8, 8] 79 z = z.reshape(n_groups, out_features).astype(np.float32) + 1.0 80 # BF16 -> F32 81 s = scales.astype(np.float32) 82 # Dequantize 83 w = w.reshape(n_groups, group_size, out_features) 84 deq = (w - z[:, None, :]) * s[:, None, :] 85 return deq.reshape(in_features, out_features).T.copy() # [out, in] 86 87 class GGUFWriter: 88 """Minimal GGUF writer.""" 89 def __init__(self, path): 90 self.file = open(path, 'wb') 91 self.tensor_start = None 92 self._write_header() 93 94 def _write_header(self): 95 self.file.write(struct.pack(' (shard_file, dtype, shape) 212 for fname, fmeta in meta.files_metadata.items(): 213 for tname, tinfo in fmeta.tensors.items(): 214 shard_map[tname] = (fname, tinfo.dtype, tinfo.shape) 215 216 print(f"Total tensors: {len(shard_map)}") 217 print(f"Total parameters: {meta.parameter_count}") 218 219 # Model config 220 config = { 221 "general.architecture": "deepseek_v4", 222 "general.name": "DeepSeek-V4-Flash-W4A16-AutoRound", 223 "general.file_type": GGML_TYPE_Q8_0, 224 "general.quantization_version": 2, 225 "deepseek_v4.block_count": 43, 226 "deepseek_v4.context_length": `1048576`, 227 "deepseek_v4.embedding_length": 4096, 228 "deepseek_v4.feed_forward_length": 2048, 229 "deepseek_v4.attention.head_count": 64, 230 "deepseek_v4.attention.head_count_kv": 1, 231 "deepseek_v4.attention.key_length": 512, 232 "deepseek_v4.attention.layer_norm_rms_epsilon": 1e-6, 233 "deepseek_v4.rope.freq_base": 10000.0, 234 "deepseek_v4.rope.dimension_count": 64, 235 "deepseek_v4.rope.scaling.type": "yarn", 236 "deepseek_v4.rope.scaling.factor": 16, 237 "deepseek_v4.rope.scaling.original_max_position_embeddings": 65536, 238 "deepseek_v4.rope.scaling.beta_fast": 32, 239 "deepseek_v4.rope.scaling.beta_slow": 1, 240 "deepseek_v4.vocab_size": 129280, 241 "deepseek_v4.expert_count": 256, 242 "deepseek_v4.expert_used_count": 6, 243 "deepseek_v4.expert_feed_forward_length": 2048, 244 "deepseek_v4.n_shared_experts": 1, 245 "deepseek_v4.n_hash_layers": 3, 246 "deepseek_v4.q_lora_rank": 1024, 247 "deepseek_v4.o_lora_rank": 1024, 248 "deepseek_v4.o_groups": 8, 249 "deepseek_v4.hc_mult": 4, 250 "deepseek_v4.head_dim": 512, 251 "deepseek_v4.rope_head_dim": 64, 252 "deepseek_v4.sliding_window": 128, 253 "deepseek_v4.n_mtp_layers": 1, 254 "deepseek_v4.swiglu_limit": 10.0, 255 "deepseek_v4.score_func": "sqrtsoftplus", 256 "deepseek_v4.route_scale": 1.5, 257 "deepseek_v4.compress_rope_theta": 160000, 258 "deepseek_v4.index_n_heads": 64, 259 "deepseek_v4.index_head_dim": 128, 260 "deepseek_v4.index_topk": 512, 261 "deepseek_v4.hc_sinkhorn_iters": 20, 262 "deepseek_v4.hc_eps": 1e-6, 263 } 264 265 # Compress ratios 266 compress_ratios = [0, 0, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 267 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 268 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 0] 269 config["deepseek_v4.compress_ratios"] = compress_ratios 270 271 print(f"Creating GGUF: {save_path}") 272 writer = GGUFWriter(save_path) 273 274 # Write metadata keys 275 for key, value in config.items(): 276 if isinstance(value, list): 277 writer.write_metadata_kv(key, value, GGUF_TYPE_ARRAY) 278 else: 279 writer.write_metadata_kv(key, value) 280 281 writer.finalize_metadata() 282 283 # Count tensors first to set n_tensors 284 tensor_list = [] 285 for tname in sorted(shard_map.keys()): 286 fname, dtype, shape = shard_map[tname] 287 # Skip if not a weight (only .qweight, .qzeros, .scales, .weight, .bias, .ape, etc.) 288 if max_layers is not None: 289 if tname.startswith("layers."): 290 layer_id = int(tname.split(".")[1]) 291 if layer_id >= max_layers: 292 continue 293 tensor_list.append((tname, fname, dtype, shape)) 294 295 # We'll convert each W4A16 weight to Q8_0 296 # Non-quantized weights (BF16 embed, F32 head, etc.) stay F32 297 298 # Pre-compute tensor sizes 299 tensor_offsets = {} 300 current_offset = 0 301 302 # Actually, let's do this more efficiently - process and write sequentially 303 print(f"Processing {len(tensor_list)} tensors...") 304 305 writer.n_tensors = len(tensor_list) 306 # Seek back and write n_tensors 307 writer.file.seek(8) # After magic + version 308 writer.file.write(struct.pack('