okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/pack_gguf.py - the engine's pack for a DeepSeek-V4.1 GGUF (unsloth's DeepSeek-V4.1-Flash-1017 UD-Q8_K_XL 4and the like: dense BF16, routed experts MXFP4, Engram tables MXFP8 or Q6_K), beside the model's files (no weights 5copied). 6 7python tools/ds4/pack_gguf.py --model ~/models/DeepSeek-V4.1-Flash-1017-GGUF/UD-Q8_K_XL 8 9writes <model>/maya-ds4/ in pack.py's format, so the engine reads both: 10ds4.txt the geometry under config.json's names (the GGUF's deepseek41.* keys translated), model_dir, format gguf 11tensors.txt every tensor under the checkpoint's names: `file <i> <name>` lines, then 12`t <name> <dtype> <file> <offset> <bytes> <dims...>` - dims outermost first (torch order: a matrix is 13[out][in]), dtype BF16 / F32 / MXFP4 / MXFP8 (ggml's block layouts, 32 values a block); the routed 14experts as one tensor a layer and role ([n_exp][out][in]) 15engram.bin the Engram hash tables, from the GGUF's metadata (pack.py's layout; no tokenizers package needed) 16tokenizer/ the server's tokenizer from the GGUF's vocabulary and merges (pre "deepseek3"), and its chat template 17 18A GGUF has no DSpark drafter: drafter_pack.py makes it from DeepSeek's checkpoint into ../dspark/, and the pack takes it 19from there when it is present. Nor a vision tower: vision_pack.py makes it from DeepSeek's checkpoint into ../vision/ 20(--vision: another folder), and the pack takes it and its geometry (vision.<key>, image_token_id) from there when it is 21present; without it the engine reads text only. 22 23A quant that leaves the two Engram tables out (v1.1.16's Maya-S; Maya's quants hold them since) takes them from a set 24of GGUF files that holds them, beside it: --engram, else ../Engram/ (unsloth's MXFP8 shard of them, where setups before 25v1.1.17 put it) when it is whole. 26""" 27from __future__import annotations 28 29import argparse 30import json 31import os 32import pathlib 33import re 34import struct 35import sys 36 37TYPES = {0 : ("F32" ,1 ,4 ),1 : ("F16" ,1 ,2 ),8 : ("Q8_0" ,32 ,34 ),30 : ("BF16" ,1 ,2 ),39 : ("MXFP4" ,32 ,17 ), 3867 : ("MXFP8" ,32 ,33 ),# ggml type -> (name, values a block, bytes a block); 67: unsloth's fork 3943 : ("MXFP8" ,32 ,33 ),# llama.cpp's own id (unsloth's GGUFs from 2026-10-19 on) 40# the low-bit expert types (the Maya quants' experts; the engine's ds4_iq kernels) 4110 : ("Q2_K" ,256 ,84 ),11 : ("Q3_K" ,256 ,110 ),12 : ("Q4_K" ,256 ,144 ),13 : ("Q5_K" ,256 ,176 ), 4214 : ("Q6_K" ,256 ,210 ),16 : ("IQ2_XXS" ,256 ,66 ),17 : ("IQ2_XS" ,256 ,74 ),18 : ("IQ3_XXS" ,256 ,98 ), 4320 : ("IQ4_NL" ,32 ,18 ),21 : ("IQ3_S" ,256 ,110 ),22 : ("IQ2_S" ,256 ,82 ),23 : ("IQ4_XS" ,256 ,136 ), 44# the two 1.x-bit types the IST-DAS 2.00 set uses: device kernels since 2026-10-23 (ds4_iq.cu), so packs with 45# them load and run entirely on the card. (The integer metadata tensors - engram_token_map and the like - stay 46# OUT of this table on purpose: the pack tool skips a tensor whose type it does not know, which is exactly right 47# for them, and adding them here made them "unmapped" instead.) 4819 : ("IQ1_S" ,256 ,50 ),29 : ("IQ1_M" ,256 ,56 ), 49# the trellis types (tools/trellis/tqenc.hpp; 145 / 146 are the agentionai fork's ggml ids, 224-227 Strata's own) 50145 : ("TQK6" ,128 ,26 ),146 : ("TQK7" ,128 ,30 ),224 : ("TQK5X" ,128 ,22 ),225 : ("TQK4X" ,128 ,18 ), 51226 : ("TQK5T" ,128 ,22 ),227 : ("TQK4T" ,128 ,18 )} 52# the Engram set a quant without the tables takes them from by default, beside it (or inside its folder): unsloth's 53# MXFP8 shard of them, where setups before v1.1.17 put it for Maya-S (--engram: any other) 54ENGRAM_SETS = ("Engram" ,) 55 56 57class Gguf : 58"""One GGUF shard's metadata and tensor infos (offsets absolute in the file).""" 59 60def __init__ (self ,path :pathlib .Path ): 61self .path = path 62with path .open ("rb" )as f : 63self .f = f 64magic = f .read (4 ) 65if magic != b"GGUF" : 66raise SystemExit ("%s: not a GGUF file" % path ) 67self .version ,nt ,nkv = struct .unpack ("<IQQ" ,f .read (20 )) 68self .kv = {} 69for _ in range (nkv ): 70k = self ._str () 71self .kv [k ]= self ._val (struct .unpack ("<I" ,f .read (4 ))[0 ]) 72self .tensors = [] 73for _ in range (nt ): 74name = self ._str () 75nd = struct .unpack ("<I" ,f .read (4 ))[0 ] 76dims = list (struct .unpack ("<%dQ" % nd ,f .read (8 * nd ))) 77typ ,off = struct .unpack ("<IQ" ,f .read (12 )) 78self .tensors .append ((name ,typ ,dims ,off )) 79align = int (self .kv .get ("general.alignment" ,32 )) 80pos = f .tell () 81self .data_start = (pos + align - 1 )// align * align 82del self .f 83 84def _str (self ): 85n = struct .unpack ("<Q" ,self .f .read (8 ))[0 ] 86return self .f .read (n ).decode ("utf-8" ,"replace" ) 87 88def _val (self ,t ): 89fmt = {0 :"B" ,1 :"b" ,2 :"H" ,3 :"h" ,4 :"I" ,5 :"i" ,6 :"f" ,7 :"?" ,10 :"Q" ,11 :"q" ,12 :"d" } 90if t in fmt : 91n = struct .calcsize (fmt [t ]) 92return struct .unpack ("<" + fmt [t ],self .f .read (n ))[0 ] 93if t == 8 : 94return self ._str () 95if t == 9 : 96at ,n = struct .unpack ("<IQ" ,self .f .read (12 )) 97if at in fmt : 98n_b = struct .calcsize (fmt [at ]) 99return list (struct .unpack ("<%d%s" % (n ,fmt [at ]),self .f .read (n * n_b ))) 100return [self ._val (at )for _ in range (n )] 101raise SystemExit ("%s: metadata type %d" % (self .path ,t )) 102 103 104# GGUF name (blk.N. stripped) -> the checkpoint's name under layers.N. (pack.py / the engine) 105LAYER = { 106"attn_norm.weight" :"attn_norm.weight" , 107"attn_sinks.weight" :"attn.attn_sink" , 108"attn_q_a.weight" :"attn.wq_a.weight" , 109"attn_q_a_norm.weight" :"attn.q_norm.weight" , 110"attn_q_b.weight" :"attn.wq_b.weight" , 111"attn_kv.weight" :"attn.wkv.weight" , 112"attn_kv_a_norm.weight" :"attn.kv_norm.weight" , 113"attn_output_a.weight" :"attn.wo_a.slice" ,# one entry a group (the engine's slices) 114"attn_output_b.weight" :"attn.wo_b.weight" , 115"attn_compressor_kv.weight" :"attn.compressor.wkv.weight" , 116"attn_compressor_gate.weight" :"attn.compressor.wgate.weight" , 117"attn_compressor_norm.weight" :"attn.compressor.norm.weight" , 118"indexer.attn_q_b.weight" :"attn.indexer.wq_b.weight" , 119"indexer.attn_k.weight" :"attn.indexer.wk.weight" , 120"indexer.k_norm.weight" :"attn.indexer.k_norm.weight" , 121"indexer.proj.weight" :"attn.indexer.weights_proj.weight" , 122"hc_attn_fn.weight" :"hc_attn_fn" , 123"hc_attn_base.weight" :"hc_attn_base" , 124"hc_attn_scale.weight" :"hc_attn_scale" , 125"hc_ffn_fn.weight" :"hc_ffn_fn" , 126"hc_ffn_base.weight" :"hc_ffn_base" , 127"hc_ffn_scale.weight" :"hc_ffn_scale" , 128"ffn_norm.weight" :"ffn_norm.weight" , 129"ffn_gate_inp.weight" :"ffn.gate.weight" , 130"exp_probs_b.bias" :"ffn.gate.bias" , 131"exp_probs_b_vl.bias" :"ffn.gate.bias_vl" , 132"ffn_gate_shexp.weight" :"ffn.shared_experts.w1.weight" , 133"ffn_up_shexp.weight" :"ffn.shared_experts.w3.weight" , 134"ffn_down_shexp.weight" :"ffn.shared_experts.w2.weight" , 135"ffn_gate_exps.weight" :"ffn.experts.w1" ,# [n_exp][ff][dim]: one entry an expert 136"ffn_up_exps.weight" :"ffn.experts.w3" , 137"ffn_down_exps.weight" :"ffn.experts.w2" ,# [n_exp][dim][ff] 138"engram_embd.weight" :"engram.embed.weight" , 139"engram_kv.weight" :"engram.wkv.weight" , 140"engram_gate.weight" :"engram.gate.weight" ,# q_weight * k_weight, folded by the converter 141# the IST-DAS sets keep q and k apart (the engine multiplies them at load) and the projection as engram_wkv 142"engram_wkv.weight" :"engram.wkv.weight" , 143"engram_q.weight" :"engram.q_weight" , 144"engram_k.weight" :"engram.k_weight" , 145} 146GLOBAL = {"token_embd.weight" :"embed.weight" ,"output_norm.weight" :"norm.weight" ,"output.weight" :"head.weight" } 147 148 149ALIASES = { 150# the same quantity under another key: llama.cpp's / unsloth's spelling -> the alternative (the IST-DAS sets write 151# the engine's own names into the GGUF and keep deepseek41.engram_* instead of the dotted Engram keys) 152"attention.kv_source_layers" : ("kv_source_layer_ids" ,), 153"attention.indexer.source_layers" : ("index_source_layer_ids" ,), 154"attention.indexer.candidate_source_layer" : ("attention.candidate_source_layer_id" ,), 155"attention.indexer.candidate_top_k_blocks" : ("attention.candidate_topk_blocks" ,), 156"attention.indexer.candidate_block_size" : ("attention.candidate_block_size" ,), 157"dspark.target_layers" : ("dspark_target_layer_ids" ,), 158"dspark.block_size" : ("dspark_block_size" ,), 159"dspark.noise_token_id" : ("dspark_noise_token_id" ,), 160"dspark.markov_rank" : ("dspark_markov_rank" ,), 161"dspark.expert_count" : ("dspark_n_routed_experts" ,), 162"dspark.expert_used_count" : ("dspark_num_experts_per_tok" ,), 163"engram.layers" : ("engram_layer_ids" ,), 164} 165 166 167def geometry (kv :dict ,vocab :int )-> dict : 168"""config.json's text_config names (what the engine reads) from the GGUF's deepseek41.* keys.""" 169a = kv ["general.architecture" ] 170 171def g (k ,d = None ): 172v = kv .get ("%s.%s" % (a ,k )) 173if v is None : 174for alt in ALIASES .get (k , ()): 175v = kv .get ("%s.%s" % (a ,alt )) 176if v is not None : 177break 178return d if v is None else v 179nl = g ("block_count" ) 180ratios = list (g ("attention.compress_ratios" , [])) 181out = { 182"vocab_size" :vocab , 183"hidden_size" :g ("embedding_length" ), 184"num_hidden_layers" :nl , 185"num_attention_heads" :g ("attention.head_count" ), 186"head_dim" :g ("attention.key_length" ), 187"qk_rope_head_dim" :g ("rope.dimension_count" ), 188"q_lora_rank" :g ("attention.q_lora_rank" ), 189"o_lora_rank" :g ("attention.output_lora_rank" ), 190"o_groups" :g ("attention.output_group_count" ), 191"n_routed_experts" :g ("expert_count" ), 192"num_experts_per_tok" :g ("expert_used_count" ), 193"moe_intermediate_size" :g ("expert_feed_forward_length" ), 194"sliding_window" :g ("attention.sliding_window" ), 195"hc_mult" :g ("hyper_connection.count" ), 196"hc_sinkhorn_iters" :g ("hyper_connection.sinkhorn_iterations" ), 197"hc_eps" :g ("hyper_connection.epsilon" ), 198"index_n_heads" :g ("attention.indexer.head_count" ), 199"index_head_dim" :g ("attention.indexer.key_length" ), 200"index_topk" :g ("attention.indexer.top_k" ), 201"candidate_source_layer_id" :g ("attention.indexer.candidate_source_layer" ), 202"candidate_topk_blocks" :g ("attention.indexer.candidate_top_k_blocks" ), 203"candidate_block_size" :g ("attention.indexer.candidate_block_size" ), 204"rope_scaling.original_max_position_embeddings" :g ("rope.scaling.original_context_length" ), 205"rope_scaling.factor" :g ("rope.scaling.factor" ), 206"rope_scaling.beta_fast" :g ("rope.scaling.yarn_beta_fast" ), 207"rope_scaling.beta_slow" :g ("rope.scaling.yarn_beta_slow" ), 208"eos_token_id" :kv .get ("tokenizer.ggml.eos_token_id" ,1 ), 209"rms_norm_eps" :g ("attention.layer_norm_rms_epsilon" ), 210"routed_scaling_factor" :g ("expert_weights_scale" ), 211"swiglu_limit" : (g ("swiglu_clamp_exp" )or [0.0 ])[0 ], 212"rope_theta" :g ("rope.freq_base" ), 213"compress_rope_theta" :g ("attention.compress_rope_freq_base" ), 214"compress_ratios" :ratios , 215"kv_source_layer_ids" :list (g ("attention.kv_source_layers" , [])), 216"index_source_layer_ids" :list (g ("attention.indexer.source_layers" , [])), 217"engram_layer_ids" :list (g ("engram.layers" , [])), 218"max_position_embeddings" :g ("context_length" ), 219"dspark_block_size" :g ("dspark.block_size" ,0 ), 220"dspark_noise_token_id" :g ("dspark.noise_token_id" ,0 ), 221"dspark_markov_rank" :g ("dspark.markov_rank" ,0 ), 222"dspark_n_routed_experts" :g ("dspark.expert_count" ,0 ), 223"dspark_num_experts_per_tok" :g ("dspark.expert_used_count" ,0 ), 224"dspark_target_layer_ids" :list (g ("dspark.target_layers" , [])), 225 } 226clamp = g ("swiglu_clamp_exp" )or [] 227if clamp and any (abs (c - clamp [0 ])> 1e-6 for c in clamp ): 228raise SystemExit ("swiglu_clamp_exp differs between layers %s: the engine takes one swiglu_limit" % clamp [:8 ]) 229return out 230 231 232def ple_to_engram (kv :dict ): 233"""llama.cpp's own names for the Engram metadata (unsloth's GGUFs from 2026-10-19 on: ple.*, the hash heads' offsets 234counted across the layers' tables) -> the engram.* keys this pack reads (each layer's offsets from its own table).""" 235a = kv .get ("general.architecture" ) 236g = lambda k ,d = None :kv .get ("%s.%s" % (a ,k ),d )# noqa: E731 237if g ("engram.layers" )or not g ("ple.layers" ): 238return 239layers ,ngram ,heads = list (g ("ple.layers" )),g ("ple.ngram_size" ),g ("ple.heads_per_ngram" ) 240offs ,sizes = list (g ("ple.head_offsets" )),list (g ("ple.head_vocab_sizes" )) 241cols = (ngram - 1 )* heads 242if len (offs )!= len (layers )* cols or len (sizes )!= len (offs ): 243raise SystemExit ("ple: %d head offsets, %d sizes for %d layers x %d columns" % 244 (len (offs ),len (sizes ),len (layers ),cols )) 245per ,rows = [], [] 246for i in range (len (layers )): 247o ,s = offs [i * cols :(i + 1 )* cols ],sizes [i * cols :(i + 1 )* cols ] 248per += [x - o [0 ]for x in o ] 249rows .append (o [- 1 ]+ s [- 1 ]- o [0 ]) 250for k ,v in (("layers" ,layers ), ("max_ngram_size" ,ngram ), ("head_count" ,heads ), 251 ("head_dim" ,g ("embedding_length_per_layer_input" )), ("multipliers" ,list (g ("ple.layer_multipliers" ))), 252 ("primes" ,sizes ), ("offsets" ,per ), ("num_embeddings" ,rows )): 253kv ["%s.engram.%s" % (a ,k )]= v 254 255 256def int_tensors_to_engram (gs ,kv :dict ): 257"""The IST-DAS sets carry the Engram's hash parameters as integer tensors of the first shard (engram_token_map I32, 258engram_primes / engram_offsets / engram_multipliers I64, one row a layer) instead of metadata: read them into the 259engram.* keys this pack reads (when the metadata does not have them already).""" 260a = kv .get ("general.architecture" ) 261want = {"engram_token_map.weight" : ("token_map" ,"i" ,4 ),"engram_primes.weight" : ("primes" ,"q" ,8 ), 262"engram_offsets.weight" : ("offsets" ,"q" ,8 ),"engram_multipliers.weight" : ("multipliers" ,"q" ,8 )} 263for g in gs : 264for name ,typ ,dims ,off in g .tensors : 265if name not in want : 266continue 267key ,fmt ,sz = want [name ] 268if "%s.engram.%s" % (a ,key )in kv : 269continue 270n = 1 271for d in dims : 272n *= d 273with g .path .open ("rb" )as f : 274f .seek (g .data_start + off ) 275kv ["%s.engram.%s" % (a ,key )]= list (struct .unpack ("<%d%s" % (n ,fmt ),f .read (n * sz ))) 276# the IST-DAS spelling of the Engram's scalar keys -> the dotted ones this pack reads 277for dotted ,theirs in (("engram.layers" ,"engram.layer_ids" ), ("engram.max_ngram_size" ,"engram_max_ngram_size" ), 278 ("engram.head_count" ,"engram_n_heads" ), ("engram.head_dim" ,"engram_head_dim" ), 279 ("engram.pad_token_id" ,"engram_pad_token_id" )): 280if "%s.%s" % (a ,dotted )not in kv and "%s.%s" % (a ,theirs )in kv : 281kv ["%s.%s" % (a ,dotted )]= kv ["%s.%s" % (a ,theirs )] 282 283 284def split_ple (g :Gguf ,kv :dict ): 285"""llama.cpp's one Engram tensor (per_layer_token_embd: every layer's table, one after the other) -> each layer's 286own blk.N.engram_embd as the earlier GGUFs had it: the same bytes, read in place.""" 287a = kv ["general.architecture" ] 288ple = [t for t in g .tensors if t [0 ]== "per_layer_token_embd.weight" ] 289if not ple : 290return 291name ,typ ,dims ,off = ple [0 ] 292layers ,rows = kv .get ("%s.engram.layers" % a , []),kv .get ("%s.engram.num_embeddings" % a , []) 293if len (dims )!= 2 or typ not in TYPES or len (rows )!= len (layers )or sum (rows )!= dims [1 ]: 294raise SystemExit ("%s: %s %s does not split in the Engram layers %s of %s rows" % (g .path .name ,name ,dims ,layers , 295rows )) 296_ ,per ,bpb = TYPES [typ ] 297row = dims [0 ]// per * bpb 298parts ,start = [],0 299for il ,n in zip (layers ,rows ): 300parts .append (("blk.%d.engram_embd.weight" % il ,typ , [dims [0 ],n ],off + start * row )) 301start += n 302g .tensors = [t for t in g .tensors if t [0 ]!= name ]+ parts 303 304 305def short (g :Gguf ): 306"""Why a GGUF file is shorter than its own tensor directory says (a download still running), or None.""" 307need = g .data_start 308for _ ,typ ,dims ,off in g .tensors : 309if typ in TYPES : 310_ ,per ,bpb = TYPES [typ ] 311nel = 1 312for d in dims : 313nel *= d 314need = max (need ,g .data_start + off + nel // per * bpb ) 315have = g .path .stat ().st_size 316return None if have >= need else "%s: %d of %d bytes" % (g .path .name ,have ,need ) 317 318 319def find_mmproj (model :pathlib .Path ): 320"""The DeepSeek vision tower beside the model (an automatic find, no --mmproj): an mmproj*.gguf in the model's parent folder whose projector IS 321deepseek41v. The folder is shared with other families' files (Qwen keeps its own mmproj-Qwen3.8-Flash-Next-BF16.gguf there, projector 322qwen3vl_merger): those are never taken, and never an error - the pack is made without a vision tower. A file named with --mmproj is checked 323strictly in main().""" 324for p in sorted (model .parent .glob ("mmproj*.gguf" )): 325try : 326if Gguf (p ).kv .get ("clip.projector_type" )== "deepseek41v" : 327return p 328except (OSError ,ValueError ,SystemExit ,struct .error ): 329continue 330return None 331 332 333def is_engram_file (g )-> bool : 334"""The Engram table's GGUF: general.architecture 'engram' (the first release) or 'deepseek41-engram' (ISTA-DASLab's final files).""" 335arch = str (g .kv .get ("general.architecture" )or "" ) 336return arch == "engram" or arch .endswith ("-engram" ) 337 338 339def model_kv (gs ): 340"""The metadata of the model: of the first group whose architecture IS deepseek41 - never an Engram file's, whatever order they come in.""" 341return next ((g .kv for g in gs if g .kv .get ("general.architecture" )== "deepseek41" ),None ) 342 343 344def engram_set (model :pathlib .Path ,explicit :str | None ): 345"""The Engram tables' GGUF set for a quant that leaves them out: (its folder, its files read), or (None, []). 346explicit (--engram): that folder, whole; else the first whole one of ENGRAM_SETS beside the quant or in its 347folder - one not whole yet (its download still running) is passed over.""" 348dirs = ([pathlib .Path (explicit ).expanduser ().resolve ()]if explicit else 349 [d for n in ENGRAM_SETS for d in (model / n ,model .parent / n )]) 350for d in dirs : 351paths = [d ]if d .is_file ()else sorted (d .glob ("*.gguf" ))if d .is_dir ()else []# (--engram: a folder, or the one file) 352if not paths : 353if explicit : 354raise SystemExit ("%s: no .gguf files (--engram: the folder of the Engram tables' GGUF set)" % d ) 355continue 356try : 357egs = [Gguf (p )for p in paths ] 358why = next ((w for w in map (short ,egs )if w ),None ) 359except (Exception ,SystemExit )as e :# noqa: BLE001 - a header cut short raises anything 360why = str (e )or type (e ).__name__ 361if why is None : 362return d ,egs 363if explicit : 364raise SystemExit ("%s: not whole (%s)" % (d ,why )) 365"%s: not whole (%s) - not used" % (d ,why )) 366return None , [] 367 368 369def write_engram (out :pathlib .Path ,kv :dict ,vocab :int ): 370a = kv ["general.architecture" ] 371g = lambda k ,d = None :kv .get ("%s.%s" % (a ,k ),d )# noqa: E731 372layers = list (g ("engram.layers" , [])) 373if not layers : 374return 0 ,0 375ngram ,heads ,hd = g ("engram.max_ngram_size" ),g ("engram.head_count" ),g ("engram.head_dim" ) 376tm = list (g ("engram.token_map" )) 377mult ,primes ,offs = list (g ("engram.multipliers" )),list (g ("engram.primes" )),list (g ("engram.offsets" )) 378cols = (ngram - 1 )* heads 379nl = len (layers ) 380if len (mult )!= nl * ngram or len (primes )!= nl * cols or len (offs )!= nl * cols : 381raise SystemExit ("engram: %d multipliers, %d primes, %d offsets for %d layers x %d columns (ngram %d)" % 382 (len (mult ),len (primes ),len (offs ),nl ,cols ,ngram )) 383pad = int (tm [g ("engram.pad_token_id" )]) 384full = tm + [0 ]* max (0 ,vocab - len (tm )) 385with out .open ("wb" )as f : 386f .write (struct .pack ("<4s6i" ,b"DSE1" ,vocab ,nl ,ngram ,heads ,hd ,pad )) 387f .write (struct .pack ("<%di" % vocab ,* full [:vocab ])) 388f .write (struct .pack ("<%dq" % len (mult ),* mult )) 389f .write (struct .pack ("<%dq" % len (primes ),* primes )) 390f .write (struct .pack ("<%dq" % len (offs ),* offs )) 391return nl ,cols 392 393 394def write_tokenizer (out :pathlib .Path ,kv :dict ,template :str | None ): 395tokens = kv ["tokenizer.ggml.tokens" ] 396types = kv .get ("tokenizer.ggml.token_type" )or [1 ]* len (tokens ) 397merges = kv .get ("tokenizer.ggml.merges" )or [] 398if len (set (tokens ))!= len (tokens ): 399raise SystemExit ("the GGUF's vocabulary has duplicate token strings" ) 400out .mkdir (parents = True ,exist_ok = True ) 401 (out / "vocab.json" ).write_text (json .dumps ({t :i for i ,t in enumerate (tokens )},ensure_ascii = False ), 402encoding = "utf-8" ) 403 (out / "merges.txt" ).write_text ("\n" .join (merges ),encoding = "utf-8" ) 404 (out / "token_type.json" ).write_text (json .dumps ([int (t )for t in types ])) 405special = {"bos" :int (kv .get ("tokenizer.ggml.bos_token_id" ,0 )),"eos" :int (kv .get ("tokenizer.ggml.eos_token_id" ,1 )), 406"pad" :int (kv .get ("tokenizer.ggml.padding_token_id" ,2 ))} 407 (out / "tokenizer.json" ).write_text (json .dumps ({"pre" :"deepseek3" ,"special_ids" :special },indent = 1 )) 408if template : 409 (out / "chat_template.jinja" ).write_text (template ,encoding = "utf-8" ) 410 411 412def main ()-> int : 413ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 414ap .add_argument ("--model" ,required = True ,help = "the directory of the GGUF's shards" ) 415ap .add_argument ("--out" ,help = "default: <model>/maya-ds4" ) 416ap .add_argument ("--vision" ,help = "vision_pack.py's folder (default: <model>/../vision; taken when it is there)" ) 417ap .add_argument ("--dspark-gguf" ,help = "unsloth's DSpark drafter GGUF (dspark-*-Q8_0.gguf, architecture dflash): its three " 418"blocks become mtp.0-2 beside the trunk's tensors (default: the first dspark-*.gguf " 419"in <model>/.. when there is one)" ) 420ap .add_argument ("--mmproj" ,help = "unsloth's vision tower GGUF (mmproj-*.gguf, clip / deepseek41v): its tensors become the " 421"checkpoint's vision.* / aligner.* (default: the first mmproj*.gguf in <model>/.. whose projector is deepseek41v; other families' are ignored)" ) 422ap .add_argument ("--tq-experts" ,nargs = "+" ,help = "folders tq_convert.py wrote (tq.json + tq-L<layer>.bin): the routed experts of the layers " 423"listed there are read from it as trellis types (TQK5X ..), the others keep their MXFP4" ) 424ap .add_argument ("--dense-override" ,action = "append" ,help = "a folder dense_requant.py wrote (dense.json + dense.bin): its tensors replace the same-named " 425"dense matrices of the GGUF (K-quants of the attention / shared experts)" ) 426ap .add_argument ("--override-experts" ,nargs = "+" ,help = "requantized GGUF folders, each DIR or DIR:roles (requant_gguf.py output): their routed experts replace the main " 427"model's for --override-roles (gate,up,down) in --override-layers (default all): mixed-bit packs" ) 428ap .add_argument ("--override-roles" ,default = "down" ) 429ap .add_argument ("--override-layers" ,default = "" ) 430ap .add_argument ("--tq-layers" ,help = "only these layers (comma list) of the --tq-experts folders" ) 431ap .add_argument ("--drafter" ,help = "the DSpark drafter's .json (drafter_pack.py's; default <model>/../dspark/dspark.json)" ) 432ap .add_argument ("--dspark-noise-token" ,type = int ,help = "the drafter's noise token id (dspark_noise_token_id), for a quant " 433"whose GGUF does not state it (the IST-DAS sets): DeepSeek-V4.1-Flash's is 128799" ) 434ap .add_argument ("--dspark-markov-rank" ,type = int ,help = "the markov head's rank (dspark_markov_rank); default: the drafter's " 435"markov tensor shape" ) 436ap .add_argument ("--skip-tensors" ,help = "a regex of the GGUF's tensor names to leave out (a --dense-override supplies them " 437"instead): e.g. attn_output_a, for a quant that stores the grouped wo_a as one " 438"interleaved 3-D tensor instead of o_groups matrices" ) 439ap .add_argument ("--engram" ,help = "the folder of the Engram tables' GGUF set, for a quant that leaves them out " 440"(default: <model>/../Engram, when it is whole)" ) 441ap .add_argument ("--engram-meta" ,help = "a GGUF whose metadata carries the Engram's hash parameters (llama.cpp's ple.* / " 442"engram.*: layers, head offsets, vocab sizes, multipliers, token map), for a quant whose own " 443"shards leave them out (the IST-DAS sets name the Engram only in deepseek41.engram_* keys and " 444"carry no token map); the tables themselves still come from --engram" ) 445ap .add_argument ("--shards" ,nargs = "+" ,help = "the GGUF's files in --model (default: every .gguf there - one " 446"model's; the setup names them: a folder may hold an earlier layout)" ) 447a = ap .parse_args () 448model = pathlib .Path (a .model ).expanduser ().resolve () 449out = pathlib .Path (a .out ).expanduser ()if a .out else model / "maya-ds4" 450shards = [model / n for n in a .shards ]if a .shards else sorted (model .glob ("*.gguf" )) 451if not shards or not all (p .is_file ()for p in shards ): 452raise SystemExit ("%s: no .gguf files" % model if not shards else 453"%s: not there" % next (p for p in shards if not p .is_file ())) 454gs = [Gguf (p )for p in shards ] 455if not a .shards :# a folder's *.gguf: the Engram table (architecture 'engram', today 'deepseek41-engram') is not a model shard 456keep = [i for i ,g in enumerate (gs )if not is_engram_file (g )] 457shards ,gs = [shards [i ]for i in keep ], [gs [i ]for i in keep ] 458if not gs : 459raise SystemExit ("%s: no model shards (only an Engram table)" % model ) 460kv = model_kv (gs ) 461if kv is None : 462arch = next ((g .kv .get ("general.architecture" )for g in gs ),None ) 463raise SystemExit ("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model ,arch )) 464split = int (kv .get ("split.count" ,1 )) 465if split != len (shards ): 466counts = sorted ({m .group (1 )for m in (re .search (r"-of-(\d{5})\.gguf$" ,p .name )for p in shards )if m }) 467raise SystemExit ("%s: %d of the %d shards are here" % (model ,len (shards ),split )if len (counts )< 2 else 468"%s: the shards of more than one GGUF split (-of-%s): name the model's own with --shards" % 469 (model ,", -of-" .join (counts ))) 470# a quant whose shards leave the Engram's metadata out (the IST-DAS sets: deepseek41.engram_* only, no token map): 471# the hash parameters come from --engram-meta, a GGUF of the same model that still has llama.cpp's ple.* / engram.* 472if a .engram_meta : 473mg = Gguf (pathlib .Path (a .engram_meta ).expanduser ().resolve ()) 474for k ,v in mg .kv .items (): 475if ".engram." in k or ".ple." in k or k .endswith (".embedding_length_per_layer_input" ): 476kv .setdefault (k ,v ) 477ple_to_engram (kv ) 478for g in gs : 479split_ple (g ,kv ) 480# the Engram tables may come from a shared set of GGUF files beside the quant (the same tensor names: engram_set) - 481# its engram tensors fill in the ones the quant's shards leave out, its engram metadata too. v1.1.16's Maya-S: 482# unsloth's UD-Q8_K_XL shard that holds only the tables, as it is (00008 of 9; before 2026-10-19 shards 00008 and 483# 00009 of 10, a table each), so no shard count is checked - every Engram layer's tables must be found, below. 484# Looked for only when the quant's shards leave some out. 485have = {t [0 ]for g in gs for t in g .tensors } 486arch = kv ["general.architecture" ] 487int_tensors_to_engram (gs ,kv ) 488layers = kv .get ("%s.engram.layers" % arch , []) 489# An official IST-DAS set (helcig/tmp-oct26-2) carries the Engram gate/kv as their own k, q, wkv tensors and a 3-D attn_output_a, and the 490# plain recipe (--engram --engram-meta --dspark-gguf, no --skip-tensors, no --dense-override) packs them as they are. Rebuilding them 491# (engram_fold.py + a wo_a override) gave a pack with garbage output on the final 2.00 set (P2003, 2026-10-23), and the pack still loads, 492# so it fails in the user's chat, not at install. Say so before it is built. 493if any (n .endswith (".engram_wkv.weight" )for n in have )and (a .skip_tensors or a .dense_override ): 494sys .stderr .write ("pack_gguf: WARNING: this looks like an official IST-DAS set (it has engram_k/q/wkv tensors) and --skip-tensors / " 495"--dense-override are used. The official sets pack correctly WITHOUT them; a pack rebuilt with them produced " 496"garbage text on the final 2.00 set. Drop both unless you are testing exactly that.\n" ) 497 498def has_part (il ,part ,names ): 499if "blk.%d.%s.weight" % (il ,part )in names : 500return True 501if part == "engram_kv" : 502return "blk.%d.engram_wkv.weight" % il in names 503if part == "engram_gate" : 504return "blk.%d.engram_q.weight" % il in names and "blk.%d.engram_k.weight" % il in names 505return False 506lacking = not layers or any (not has_part (il ,part ,have ) 507for il in layers for part in ("engram_embd" ,"engram_kv" ,"engram_gate" )) 508eg_dir ,egs = engram_set (model ,a .engram )if lacking or a .engram else (None , []) 509eg_from = {} 510if eg_dir is not None : 511eshards = [g .path for g in egs ] 512for g in egs : 513for k ,v in g .kv .items (): 514if ".engram." in k or ".ple." in k or k .endswith (".embedding_length_per_layer_input" ): 515kv .setdefault (k ,v ) 516ple_to_engram (kv ) 517for g in egs : 518split_ple (g ,kv ) 519for p ,g in zip (eshards ,egs ): 520picked = [t for t in g .tensors if re .match (r"blk\.\d+\.engram_" ,t [0 ])and t [0 ]not in have ] 521picked = [t for t in picked if t [0 ].endswith ("engram_embd.weight" )or not has_part ( 522int (t [0 ].split ("." )[1 ]),"engram_kv" if t [0 ].endswith ("engram_kv.weight" )else "engram_gate" ,have )] 523 524if picked : 525g .tensors = picked 526eg_from [p ]= g 527# what the --dense-override folders supply: a tensor they provide is not "missing" here even though neither the quant's 528# shards nor an Engram set carry it (engram_fold.py supplies the Engram gate and kv from the quant's own k/q/wkv, 2026-10-23) 529# the GGUF part names -> the engine's names (LAYER maps "engram_kv.weight" -> "engram.kv.weight") 530ov_names = set () 531for dsrc in (a .dense_override or []): 532try : 533ov_names |= set (json .loads ((pathlib .Path (dsrc ).expanduser ().resolve ()/ "dense.json" ).read_text ()).keys ()) 534except (OSError ,ValueError ): 535pass 536for il in kv .get ("%s.engram.layers" % arch , []): 537for part in ("engram_embd" ,"engram_kv" ,"engram_gate" ): 538nm = "blk.%d.%s.weight" % (il ,part ) 539# a dense override names tensors the way the pack does, not the way the GGUF does 540eng_nm = "layers.%d.%s" % (il ,LAYER [part + ".weight" ]) 541if (not has_part (il ,part ,have )and eng_nm not in ov_names 542and not any (t [0 ]== nm for g in eg_from .values ()for t in g .tensors )): 543raise SystemExit ("%s: missing - not in the quant's shards nor in an Engram set (--engram, or " 544"<model>/../Engram/: unsloth's UD-Q8_K_XL shard of the Engram tables)" % nm ) 545rel = lambda p :os .path .relpath (p ,model ).replace (os .sep ,"/" )# noqa: E731 546gs_all = gs + list (eg_from .values ()) 547names = [g .path .name for g in gs ]+ [rel (p )for p in eg_from ] 548 549tensors ,unknown ,skipped = [], [], [] 550skip_re = re .compile (a .skip_tensors )if a .skip_tensors else None 551for fi ,g in enumerate (gs_all ): 552for name ,typ ,dims ,off in g .tensors : 553if skip_re is not None and skip_re .search (name ): 554skipped .append ("%s (asked for)" % name ) 555continue 556if typ not in TYPES : 557if typ in (24 ,25 ,26 ,27 ,28 ):# I8 / I16 / I32 / I64 / F64: metadata carried as tensors, not weights 558skipped .append ("%s (type %d)" % (name ,typ ))# (the IST-DAS sets' engram_token_map.weight) 559continue 560raise SystemExit ("%s: %s has ggml type %d, which the engine does not read" % (g .path .name ,name ,typ )) 561tname ,per ,bpb = TYPES [typ ] 562nel = 1 563for d in dims : 564nel *= d 565if dims [0 ]% per : 566raise SystemExit ("%s: %s rows of %d are not whole %s blocks" % (g .path .name ,name ,dims [0 ],tname )) 567nbytes = nel // per * bpb 568m = re .match (r"blk\.(\d+)\.(.+)$" ,name ) 569if m and m .group (2 )in LAYER : 570ck = "layers.%s.%s" % (m .group (1 ),LAYER [m .group (2 )]) 571elif name in GLOBAL : 572ck = GLOBAL [name ] 573else : 574unknown .append (name ) 575continue 576shape = list (reversed (dims ))# ggml ne0 innermost -> torch order, outermost first 577base = g .data_start + off 578if ck .endswith (".attn.wo_a.slice" ): 579# [o_groups * o_lora][in] -> o_groups entries of [o_lora][in] (group g: rows g * o_lora ..) 580n = int (kv ["%s.attention.output_group_count" % kv ["general.architecture" ]]) 581if len (shape )== 3 and shape [0 ]== n :# (the IST-DAS sets: [groups][o_lora][in] in one tensor) 582shape = [shape [0 ]* shape [1 ],shape [2 ]] 583if len (shape )!= 2 or shape [0 ]% n : 584raise SystemExit ("%s: %s %s does not split in %d groups" % (g .path .name ,name ,shape ,n )) 585part = nbytes // n 586for i in range (n ): 587tensors .append (("%s.%d.weight" % (ck ,i ),tname ,fi ,base + i * part ,part , 588 [shape [0 ]// n ,shape [1 ]])) 589continue 590if ".ffn.experts." in ck : 591# [n_exp][out][in] -> an entry an expert: layers.N.ffn.experts.E.w1.weight 592n ,part = shape [0 ],nbytes // shape [0 ] 593pre ,role = ck .rsplit ("." ,1 ) 594for i in range (n ): 595tensors .append (("%s.%d.%s.weight" % (pre ,i ,role ),tname ,fi ,base + i * part ,part ,shape [1 :])) 596continue 597tensors .append ((ck ,tname ,fi ,base ,nbytes ,shape )) 598if unknown : 599raise SystemExit ("tensors the pack does not map (%d): %s" % (len (unknown ),", " .join (unknown [:12 ]))) 600if skipped : 601"not weights, left out (%d): %s" % (len (skipped ),", " .join (skipped [:8 ]))) 602# the DSpark drafter (drafter_pack.py's dspark.bin beside the quants' folders, from DeepSeek's checkpoint): its 603# three blocks as mtp.0-2, so the engine drafts with them 604files = names 605if eg_from : 606"Engram tables from %s (%d shards)" % (eg_dir ,len (eg_from ))) 607# experts of a second requantized model replace the main one's for some roles / layers (the byte layouts are per tensor: any mix of types) 608n_ov = 0 609for spec in (a .override_experts or []): 610dpath ,_ ,drl = spec .partition (":" ) 611od = pathlib .Path (dpath ).expanduser ().resolve () 612roles_ov = {"gate" :"w1" ,"up" :"w3" ,"down" :"w2" } 613want = {roles_ov [r ]for r in (drl or a .override_roles ).split ("," )} 614lay_ov = None 615if a .override_layers : 616lay_ov = set () 617for part in a .override_layers .split ("," ): 618lo ,_ ,hi = part .partition ("-" ) 619lay_ov .update (range (int (lo ),int (hi or lo )+ 1 )) 620ogs = [Gguf (pth )for pth in sorted (od .glob ("*.gguf" ))] 621new = [] 622for og in ogs : 623try : 624orel = os .path .relpath (og .path ,model ).replace (os .sep ,"/" ) 625except ValueError : 626raise SystemExit ("%s must be on the model's drive" % od ) 627files .append (orel ) 628ofi = len (files )- 1 629for name ,typ ,dims ,off in og .tensors : 630m = re .match (r"blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$" ,name ) 631if not m or typ not in TYPES : 632continue 633il ,role = int (m .group (1 )), {"gate" :"w1" ,"up" :"w3" ,"down" :"w2" }[m .group (2 )] 634if role not in want or (lay_ov is not None and il not in lay_ov ): 635continue 636tname ,per ,bpb = TYPES [typ ] 637nel = 1 638for d in dims : 639nel *= d 640nbytes = nel // per * bpb 641shape = list (reversed (dims )) 642n ,part = shape [0 ],nbytes // shape [0 ] 643for i in range (n ): 644new .append (("layers.%d.ffn.experts.%d.%s.weight" % (il ,i ,role ),tname ,ofi ,og .data_start + off + i * part ,part ,shape [1 :])) 645names_new = {t [0 ]for t in new } 646tensors [:]= [t for t in tensors if t [0 ]not in names_new ]+ new 647n_ov += len (new ) 648"experts overridden from %s: %d tensors (roles %s, layers %s)" % (od ,len (new ),drl or a .override_roles ,a .override_layers or "all" )) 649# dense matrices requantized by dense_requant.py replace the GGUF's BF16 ones 650n_dense = 0 651for dsrc in (a .dense_override or []): 652dd = pathlib .Path (dsrc ).expanduser ().resolve () 653dj = json .loads ((dd / "dense.json" ).read_text ()) 654try : 655relf = os .path .relpath (dd / "dense.bin" ,model ).replace (os .sep ,"/" ) 656except ValueError : 657raise SystemExit ("%s must be on the model's drive" % dd ) 658if relf not in files : 659files .append (relf ) 660dfi = files .index (relf ) 661pos = {t [0 ]:i for i ,t in enumerate (tensors )} 662n_here = n_add = 0 663for name , (tname ,fname ,off ,nb ,shape )in dj .items (): 664if name not in pos : 665# a tensor the quant leaves out (a --skip-tensors'd one, or a set that stores it under another layout): 666# the override supplies it 667tensors .append ((name ,tname ,dfi ,off ,nb ,shape )) 668pos [name ]= len (tensors )- 1 669n_add += 1 670continue 671tensors [pos [name ]]= (name ,tname ,dfi ,off ,nb ,shape ) 672n_here += 1 673n_dense += n_here + n_add 674"dense override from %s: %d tensors replaced, %d added (a later folder wins)" % (dd ,n_here ,n_add )) 675# the DSpark drafter from unsloth's GGUF (architecture dflash): blk.N.* -> mtp.N.*, the head tensors under the 676# checkpoint's names (fc -> main_proj, enc.output_norm -> main_norm, output_norm -> norm of the last block, 677# conf_proj -> confidence_head.proj, markov_w1 / w2 -> markov_head.embed / head) 678ds_path = pathlib .Path (a .dspark_gguf ).expanduser ().resolve ()if a .dspark_gguf else next ( 679iter (sorted (model .parent .glob ("dspark-*.gguf" ))),None ) 680dspark_gguf = False 681if ds_path is not None : 682if not ds_path .is_file (): 683raise SystemExit ("%s: no DSpark GGUF there" % ds_path ) 684dg = Gguf (ds_path ) 685if dg .kv .get ("general.architecture" )!= "dflash" : 686raise SystemExit ("%s: not a DSpark (dflash) GGUF" % ds_path ) 687# the engine's dspark.* geometry: a quant built by another tool (the IST-DAS sets) leaves it out, the drafter 688# carries all of it except the noise token (a model constant) and the markov head's rank (the tensor's shape) 689for k ,dk in (("block_size" ,"block_size" ), ("expert_count" ,"expert_count" ), 690 ("expert_used_count" ,"expert_used_count" ), ("target_layers" ,"target_layers" )): 691v = dg .kv .get ("dflash." + dk ) 692if v is not None : 693kv .setdefault ("%s.dspark.%s" % (arch ,k ),v ) 694if a .dspark_noise_token is not None : 695kv .setdefault ("%s.dspark.noise_token_id" % arch ,int (a .dspark_noise_token )) 696if a .dspark_markov_rank is not None : 697kv .setdefault ("%s.dspark.markov_rank" % arch ,int (a .dspark_markov_rank )) 698else : 699for name ,typ ,dims ,off in dg .tensors : 700if "markov" in name and len (dims )== 2 : 701kv .setdefault ("%s.dspark.markov_rank" % arch ,int (dims [0 ])) 702break 703nb = int (dg .kv ["dflash.block_count" ]) 704files .append (rel (ds_path )) 705fi = len (files )- 1 706HEAD = {"fc.weight" :"mtp.0.main_proj.weight" ,"enc.output_norm.weight" :"mtp.0.main_norm.weight" , 707"output_norm.weight" :"mtp.%d.norm.weight" % (nb - 1 ), 708"conf_proj.weight" :"mtp.%d.confidence_head.proj.weight" % (nb - 1 ), 709"markov_w1.weight" :"mtp.%d.markov_head.embed.weight" % (nb - 1 ), 710"markov_w2.weight" :"mtp.%d.markov_head.head.weight" % (nb - 1 )} 711groups = int (kv ["%s.attention.output_group_count" % kv ["general.architecture" ]]) 712bad = [] 713for name ,typ ,dims ,off in dg .tensors : 714if typ not in TYPES : 715raise SystemExit ("%s: %s has ggml type %d, which the engine does not read" % (ds_path .name ,name ,typ )) 716tname ,per ,bpb = TYPES [typ ] 717nel = 1 718for d in dims : 719nel *= d 720nbytes = nel // per * bpb 721m = re .match (r"blk\.(\d+)\.(.+)$" ,name ) 722if m and m .group (2 )in LAYER : 723ck = "mtp.%s.%s" % (m .group (1 ),LAYER [m .group (2 )]) 724elif name in HEAD : 725ck = HEAD [name ] 726else : 727bad .append (name ) 728continue 729shape = list (reversed (dims )) 730base = dg .data_start + off 731if ck .endswith (".attn.wo_a.slice" ): 732part = nbytes // groups 733for i in range (groups ): 734tensors .append (("%s.%d.weight" % (ck ,i ),tname ,fi ,base + i * part ,part , [shape [0 ]// groups ,shape [1 ]])) 735elif ".ffn.experts." in ck : 736n ,part = shape [0 ],nbytes // shape [0 ] 737pre ,role = ck .rsplit ("." ,1 ) 738for i in range (n ): 739tensors .append (("%s.%d.%s.weight" % (pre ,i ,role ),tname ,fi ,base + i * part ,part ,shape [1 :])) 740else : 741tensors .append ((ck ,tname ,fi ,base ,nbytes ,shape )) 742if bad : 743raise SystemExit ("DSpark GGUF tensors the pack does not map (%d): %s" % (len (bad ),", " .join (bad [:12 ]))) 744dspark_gguf = True 745"DSpark drafter from %s: %d blocks" % (ds_path .name ,nb )) 746# the vision tower from unsloth's mmproj GGUF (clip, projector deepseek41v): llama.cpp's names -> the checkpoint's; 747# the F32 norms / biases / marker rows are read as BF16 by the engine; mlp.w1 is the file's gate and up 748mm_path = pathlib .Path (a .mmproj ).expanduser ().resolve ()if a .mmproj else find_mmproj (model ) 749mm_geo = {} 750if mm_path is not None : 751if not mm_path .is_file (): 752raise SystemExit ("%s: no mmproj GGUF there" % mm_path ) 753mg = Gguf (mm_path ) 754if mg .kv .get ("clip.projector_type" )!= "deepseek41v" : 755raise SystemExit ("%s: not a DeepSeek-V4.1 vision GGUF (projector %r)" % (mm_path ,mg .kv .get ("clip.projector_type" ))) 756files .append (rel (mm_path )) 757fi = len (files )- 1 758FIX = {"v.patch_embd.weight" :"vision.patch_embed.proj.weight" ,"v.patch_embd.bias" :"vision.patch_embed.proj.bias" , 759"v.post_ln.weight" :"vision.norm.weight" ,"mm.1.weight" :"aligner.w1.weight" ,"mm.1.bias" :"aligner.w1.bias" , 760"mm.2.weight" :"aligner.w2.weight" ,"mm.2.bias" :"aligner.w2.bias" ,"v.token_embd.img_start" :"image_start" , 761"v.image_newline" :"image_newline" ,"v.token_embd.img_end" :"image_end" } 762BLK = {"ln1.weight" :"norm1.weight" ,"ln2.weight" :"norm2.weight" ,"attn_qkv.weight" :"attn.wqkv.weight" , 763"attn_qkv.bias" :"attn.wqkv.bias" ,"attn_out.weight" :"attn.wo.weight" ,"attn_out.bias" :"attn.wo.bias" , 764"ffn_gate.weight" :"mlp.gate.weight" ,"ffn_up.weight" :"mlp.up.weight" ,"ffn_down.weight" :"mlp.w2.weight" } 765bad = [] 766for name ,typ ,dims ,off in mg .tensors : 767if typ not in TYPES : 768raise SystemExit ("%s: %s has ggml type %d, which the engine does not read" % (mm_path .name ,name ,typ )) 769tname ,per ,bpb = TYPES [typ ] 770nel = 1 771for d in dims : 772nel *= d 773m = re .match (r"v\.blk\.(\d+)\.(.+)$" ,name ) 774if m and m .group (2 )in BLK : 775ck = "vision.blocks.%s.%s" % (m .group (1 ),BLK [m .group (2 )]) 776elif name in FIX : 777ck = FIX [name ] 778else : 779bad .append (name ) 780continue 781shape = list (reversed (dims )) 782if name == "v.patch_embd.weight" :# conv [out][3][14][14] -> [out][3 * 14 * 14], the same bytes 783shape = [shape [0 ],nel // shape [0 ]] 784tensors .append ((ck ,tname ,fi ,mg .data_start + off ,nel // per * bpb ,shape )) 785if bad : 786raise SystemExit ("mmproj tensors the pack does not map (%d): %s" % (len (bad ),", " .join (bad [:12 ]))) 787k = lambda n ,d = None :mg .kv .get ("clip.vision." + n ,d )# noqa: E731 788toks = kv .get ("tokenizer.ggml.tokens" , []) 789img_id = next ((i for i ,t in enumerate (toks )if t == "<|deepseek_image|>" ),None ) 790if img_id is None : 791raise SystemExit ("the vocabulary has no <|deepseek_image|> token" ) 792mm_geo = {"vision.num_hidden_layers" :k ("block_count" ),"vision.hidden_size" :k ("embedding_length" ), 793"vision.num_attention_heads" :k ("attention.head_count" ),"vision.intermediate_size" :k ("feed_forward_length" ), 794"vision.patch_size" :k ("patch_size" ),"vision.downsample_ratio" :k ("projector.scale_factor" ), 795"vision.rope_theta" :10000 ,"vision.max_image_tokens" :1024 ,"vision.min_pixels" :k ("image_min_pixels" ), 796"image_token_id" :img_id } 797"vision tower from %s: %d blocks, image token %d" % (mm_path .name ,mm_geo ["vision.num_hidden_layers" ],img_id )) 798# trellis experts from tq_convert.py: per layer the three roles stacked [n_exp][rows][row bytes] in one file 799tq_layers = [] 800if a .tq_experts : 801by_layer ,tq_dirs = {}, {} 802for d in a .tq_experts : 803tqd = pathlib .Path (d ).expanduser ().resolve () 804for key ,ent in json .loads ((tqd / "tq.json" ).read_text ()).items (): 805m = re .match (r"layers\.(\d+)\.ffn\.experts\.(w[123])$" ,key ) 806if not m : 807raise SystemExit ("tq.json: %s is not a layer's expert role" % key ) 808by_layer .setdefault (int (m .group (1 )), {})[m .group (2 )]= ent 809tq_dirs [(int (m .group (1 )),m .group (2 ))]= tqd 810if a .tq_layers : 811keep = {int (x )for x in a .tq_layers .split ("," )} 812by_layer = {il :r for il ,r in by_layer .items ()if il in keep } 813TQTYPES = {v [0 ]:k for k ,v in TYPES .items ()} 814for il ,roles in sorted (by_layer .items ()): 815if sorted (roles )!= ["w1" ,"w2" ,"w3" ]: 816raise SystemExit ("tq.json: layer %d lacks a role (has %s)" % (il ,sorted (roles ))) 817if len ({r [0 ]for r in roles .values ()})!= 1 or roles ["w1" ][0 ]!= roles ["w3" ][0 ]: 818raise SystemExit ("tq.json: layer %d: gate and up must be one type" % il ) 819drop = re .compile (r"layers\.%d\.ffn\.experts\.\d+\.w[123]\.weight$" % il ) 820kept = [t for t in tensors if not drop .match (t [0 ])] 821if len (kept )== len (tensors ): 822raise SystemExit ("layer %d has no routed experts in the GGUF to replace" % il ) 823tensors [:]= kept 824for role , (tname ,fname ,off ,total ,shape )in roles .items (): 825if tname not in TQTYPES : 826raise SystemExit ("tq.json: unknown type %s" % tname ) 827n_exp ,rows ,cols = shape 828per = total // n_exp 829f = tq_dirs [(il ,role )]/ fname 830if not f .is_file ()or f .stat ().st_size < off + total : 831raise SystemExit ("%s: missing or short" % f ) 832try : 833relf = os .path .relpath (f ,model ).replace (os .sep ,"/" ) 834except ValueError : 835raise SystemExit ("%s must be on the model's drive" % f ) 836if relf not in files : 837files .append (relf ) 838fi = files .index (relf ) 839for e in range (n_exp ): 840tensors .append (("layers.%d.ffn.experts.%d.%s.weight" % (il ,e ,role ),tname ,fi ,off + e * per ,per , [rows ,cols ])) 841tq_layers .append (il ) 842"trellis experts from %s: layers %s" % (", " .join (a .tq_experts ),tq_layers )) 843drafter = pathlib .Path (a .drafter ).expanduser ().resolve ()if a .drafter else model .parent / "dspark" / "dspark.json" 844if a .drafter and not drafter .is_file (): 845raise SystemExit ("%s: no drafter there" % drafter ) 846drafter_in = (drafter .is_file ()and drafter .with_suffix (".bin" ).is_file ())and not dspark_gguf 847if drafter_in : 848files .append (rel (drafter .with_suffix (".bin" ))) 849groups = int (kv ["%s.attention.output_group_count" % kv ["general.architecture" ]]) 850for name ,dt ,off ,nb ,shape in json .loads (drafter .read_text ())["tensors" ]: 851if name .endswith (".attn.wo_a.weight" ):# (one entry a group, as the trunk's) 852for i in range (groups ): 853tensors .append (("%s.slice.%d.weight" % (name [:- len (".weight" )],i ),dt ,len (files )- 1 , 854off + i * (nb // groups ),nb // groups , [shape [0 ]// groups ,shape [1 ]])) 855continue 856tensors .append ((name ,dt ,len (files )- 1 ,off ,nb ,shape )) 857# the vision tower (vision_pack.py's vision.bin, from DeepSeek's checkpoint): its tensors under the checkpoint's 858# names, the picture span's marker rows, and the geometry config.json gives them 859vdir = pathlib .Path (a .vision ).expanduser ().resolve ()if a .vision else model .parent / "vision" 860vision = {} 861if (vdir / "vision.json" ).is_file ()and (vdir / "vision.bin" ).is_file (): 862try : 863rel = os .path .relpath (vdir / "vision.bin" ,model ).replace (os .sep ,"/" ) 864except ValueError :# (Windows: another drive) 865raise SystemExit ("%s: the vision folder must be on the model's drive" % vdir ) 866if " " in rel : 867raise SystemExit ("%s: the vision folder's path relative to the model has a space" % vdir ) 868files .append (rel ) 869info = json .loads ((vdir / "vision.json" ).read_text ()) 870for name ,dt ,off ,nb ,shape in info ["tensors" ]: 871tensors .append ((name ,dt ,len (files )- 1 ,off ,nb ,shape )) 872vision = info ["config" ] 873if mm_geo and not vision : 874vision = mm_geo 875vocab = next (t [5 ][0 ]for t in tensors if t [0 ]== "embed.weight" ) 876geo = geometry (kv ,vocab ) 877 878out .mkdir (parents = True ,exist_ok = True ) 879with (out / "ds4.txt" ).open ("w" )as f : 880for k ,v in geo .items (): 881if v is None : 882continue 883if isinstance (v ,bool ): 884v = int (v ) 885f .write ("%s %s\n" % (k ,"," .join (str (x )for x in v )if isinstance (v ,list )else v )) 886for k ,v in vision .items (): 887f .write ("%s %s\n" % (k ,v )) 888f .write ("format gguf\n" ) 889f .write ("model_dir %s\n" % model ) 890with (out / "tensors.txt" ).open ("w" )as f : 891for i ,name in enumerate (files ): 892f .write ("file %d %s\n" % (i ,name )) 893for name ,dt ,fi ,off ,nb ,shape in tensors : 894f .write ("t %s %s %d %d %d %s\n" % (name ,dt ,fi ,off ,nb ," " .join (map (str ,shape )))) 895nl ,cols = write_engram (out / "engram.bin" ,kv ,vocab ) 896# the server's chat template: the GGUF's own (unsloth's, byte-identical to DeepSeek's encoding.py on the 9 cases we 897# checked: chat, thinking, effort, system, multi-turn, tools, tool results). Project Maya's tools/ds4/chat_template.jinja 898# lost the tool associations and later system instructions (their #299), so it is NOT used here. 899template = kv .get ("tokenizer.chat_template" ) 900if not template : 901sys .exit ("%s: the GGUF has no tokenizer.chat_template; refusing to fall back to the old Maya template (#299)" % model ) 902write_tokenizer (out / "tokenizer" ,kv ,template ) 903by = {} 904for t in tensors : 905by [t [1 ]]= by .get (t [1 ],0 )+ t [4 ] 906extras = [w for w ,there in (("the DSpark drafter" ,drafter_in or dspark_gguf ), ("the vision tower" ,bool (vision )), ("trellis experts in layers %s" % tq_layers ,bool (tq_layers )), ("%d dense matrices requantized" % n_dense ,bool (n_dense )), ("%d experts from %s" % (n_ov ,a .override_experts ),bool (n_ov )))if there ] 907"%s: %d tensors in %d files (%s), Engram %d layers x %d hash columns%s -> %s" % 908 (model .name ,len (tensors ),len (files ),", " .join ("%s %.1f GB" % (k ,v / 1e9 )for k ,v in sorted (by .items ())), 909nl ,cols ,"" .join (", " + w for w in extras ),out )) 910return 0 911 912 913if __name__ == "__main__" : 914sys .exit (main ())