okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
53.3 KiB914 linesraw
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
7    python 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:
10  ds4.txt       the geometry under config.json's names (the GGUF's deepseek41.* keys translated), model_dir, format gguf
11  tensors.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
14                experts as one tensor a layer and role ([n_exp][out][in])
15  engram.bin    the Engram hash tables, from the GGUF's metadata (pack.py's layout; no tokenizers package needed)
16  tokenizer/    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),
38         67: ("MXFP8", 32, 33),          # ggml type -> (name, values a block, bytes a block); 67: unsloth's fork
39         43: ("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)
41         10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110), 12: ("Q4_K", 256, 144), 13: ("Q5_K", 256, 176),
42         14: ("Q6_K", 256, 210), 16: ("IQ2_XXS", 256, 66), 17: ("IQ2_XS", 256, 74), 18: ("IQ3_XXS", 256, 98),
43         20: ("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.)
48         19: ("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)
50         145: ("TQK6", 128, 26), 146: ("TQK7", 128, 30), 224: ("TQK5X", 128, 22), 225: ("TQK4X", 128, 18),
51         226: ("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
60    def __init__(self, path: pathlib.Path):
61        self.path = path
62        with path.open("rb") as f:
63            self.f = f
64            magic = f.read(4)
65            if magic != b"GGUF":
66                raise SystemExit("%s: not a GGUF file" % path)
67            self.version, nt, nkv = struct.unpack("<IQQ", f.read(20))
68            self.kv = {}
69            for _ in range(nkv):
70                k = self._str()
71                self.kv[k] = self._val(struct.unpack("<I", f.read(4))[0])
72            self.tensors = []
73            for _ in range(nt):
74                name = self._str()
75                nd = struct.unpack("<I", f.read(4))[0]
76                dims = list(struct.unpack("<%dQ" % nd, f.read(8 * nd)))
77                typ, off = struct.unpack("<IQ", f.read(12))
78                self.tensors.append((name, typ, dims, off))
79            align = int(self.kv.get("general.alignment", 32))
80            pos = f.tell()
81            self.data_start = (pos + align - 1) // align * align
82        del self.f
83
84    def _str(self):
85        n = struct.unpack("<Q", self.f.read(8))[0]
86        return self.f.read(n).decode("utf-8", "replace")
87
88    def _val(self, t):
89        fmt = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
90        if t in fmt:
91            n = struct.calcsize(fmt[t])
92            return struct.unpack("<" + fmt[t], self.f.read(n))[0]
93        if t == 8:
94            return self._str()
95        if t == 9:
96            at, n = struct.unpack("<IQ", self.f.read(12))
97            if at in fmt:
98                n_b = struct.calcsize(fmt[at])
99                return list(struct.unpack("<%d%s" % (n, fmt[at]), self.f.read(n * n_b)))
100            return [self._val(at) for _ in range(n)]
101        raise 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."""
169    a = kv["general.architecture"]
170
171    def g(k, d=None):
172        v = kv.get("%s.%s" % (a, k))
173        if v is None:
174            for alt in ALIASES.get(k, ()):
175                v = kv.get("%s.%s" % (a, alt))
176                if v is not None:
177                    break
178        return d if v is None else v
179    nl = g("block_count")
180    ratios = list(g("attention.compress_ratios", []))
181    out = {
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    }
226    clamp = g("swiglu_clamp_exp") or []
227    if clamp and any(abs(c - clamp[0]) > 1e-6 for c in clamp):
228        raise SystemExit("swiglu_clamp_exp differs between layers %s: the engine takes one swiglu_limit" % clamp[:8])
229    return 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
234    counted across the layers' tables) -> the engram.* keys this pack reads (each layer's offsets from its own table)."""
235    a = kv.get("general.architecture")
236    g = lambda k, d=None: kv.get("%s.%s" % (a, k), d)  # noqa: E731
237    if g("engram.layers") or not g("ple.layers"):
238        return
239    layers, ngram, heads = list(g("ple.layers")), g("ple.ngram_size"), g("ple.heads_per_ngram")
240    offs, sizes = list(g("ple.head_offsets")), list(g("ple.head_vocab_sizes"))
241    cols = (ngram - 1) * heads
242    if len(offs) != len(layers) * cols or len(sizes) != len(offs):
243        raise SystemExit("ple: %d head offsets, %d sizes for %d layers x %d columns" %
244                         (len(offs), len(sizes), len(layers), cols))
245    per, rows = [], []
246    for i in range(len(layers)):
247        o, s = offs[i * cols:(i + 1) * cols], sizes[i * cols:(i + 1) * cols]
248        per += [x - o[0] for x in o]
249        rows.append(o[-1] + s[-1] - o[0])
250    for 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)):
253        kv["%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,
258    engram_primes / engram_offsets / engram_multipliers I64, one row a layer) instead of metadata: read them into the
259    engram.* keys this pack reads (when the metadata does not have them already)."""
260    a = kv.get("general.architecture")
261    want = {"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)}
263    for g in gs:
264        for name, typ, dims, off in g.tensors:
265            if name not in want:
266                continue
267            key, fmt, sz = want[name]
268            if "%s.engram.%s" % (a, key) in kv:
269                continue
270            n = 1
271            for d in dims:
272                n *= d
273            with g.path.open("rb") as f:
274                f.seek(g.data_start + off)
275                kv["%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
277    for 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")):
280        if "%s.%s" % (a, dotted) not in kv and "%s.%s" % (a, theirs) in kv:
281            kv["%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
286    own blk.N.engram_embd as the earlier GGUFs had it: the same bytes, read in place."""
287    a = kv["general.architecture"]
288    ple = [t for t in g.tensors if t[0] == "per_layer_token_embd.weight"]
289    if not ple:
290        return
291    name, typ, dims, off = ple[0]
292    layers, rows = kv.get("%s.engram.layers" % a, []), kv.get("%s.engram.num_embeddings" % a, [])
293    if len(dims) != 2 or typ not in TYPES or len(rows) != len(layers) or sum(rows) != dims[1]:
294        raise SystemExit("%s: %s %s does not split in the Engram layers %s of %s rows" % (g.path.name, name, dims, layers,
295                                                                                         rows))
296    _, per, bpb = TYPES[typ]
297    row = dims[0] // per * bpb
298    parts, start = [], 0
299    for il, n in zip(layers, rows):
300        parts.append(("blk.%d.engram_embd.weight" % il, typ, [dims[0], n], off + start * row))
301        start += n
302    g.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."""
307    need = g.data_start
308    for _, typ, dims, off in g.tensors:
309        if typ in TYPES:
310            _, per, bpb = TYPES[typ]
311            nel = 1
312            for d in dims:
313                nel *= d
314            need = max(need, g.data_start + off + nel // per * bpb)
315    have = g.path.stat().st_size
316    return 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
321    deepseek41v.  The folder is shared with other families' files (Qwen keeps its own mmproj-Qwen3.8-Flash-Next-BF16.gguf there, projector
322    qwen3vl_merger): those are never taken, and never an error - the pack is made without a vision tower.  A file named with --mmproj is checked
323    strictly in main()."""
324    for p in sorted(model.parent.glob("mmproj*.gguf")):
325        try:
326            if Gguf(p).kv.get("clip.projector_type") == "deepseek41v":
327                return p
328        except (OSError, ValueError, SystemExit, struct.error):
329            continue
330    return 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)."""
335    arch = str(g.kv.get("general.architecture") or "")
336    return 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."""
341    return 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, []).
346    explicit (--engram): that folder, whole; else the first whole one of ENGRAM_SETS beside the quant or in its
347    folder - one not whole yet (its download still running) is passed over."""
348    dirs = ([pathlib.Path(explicit).expanduser().resolve()] if explicit else
349            [d for n in ENGRAM_SETS for d in (model / n, model.parent / n)])
350    for d in dirs:
351        paths = [d] if d.is_file() else sorted(d.glob("*.gguf")) if d.is_dir() else []   # (--engram: a folder, or the one file)
352        if not paths:
353            if explicit:
354                raise SystemExit("%s: no .gguf files (--engram: the folder of the Engram tables' GGUF set)" % d)
355            continue
356        try:
357            egs = [Gguf(p) for p in paths]
358            why = next((w for w in map(short, egs) if w), None)
359        except (Exception, SystemExit) as e:   # noqa: BLE001 - a header cut short raises anything
360            why = str(e) or type(e).__name__
361        if why is None:
362            return d, egs
363        if explicit:
364            raise SystemExit("%s: not whole (%s)" % (d, why))
365        print("%s: not whole (%s) - not used" % (d, why))
366    return None, []
367
368
369def write_engram(out: pathlib.Path, kv: dict, vocab: int):
370    a = kv["general.architecture"]
371    g = lambda k, d=None: kv.get("%s.%s" % (a, k), d)  # noqa: E731
372    layers = list(g("engram.layers", []))
373    if not layers:
374        return 0, 0
375    ngram, heads, hd = g("engram.max_ngram_size"), g("engram.head_count"), g("engram.head_dim")
376    tm = list(g("engram.token_map"))
377    mult, primes, offs = list(g("engram.multipliers")), list(g("engram.primes")), list(g("engram.offsets"))
378    cols = (ngram - 1) * heads
379    nl = len(layers)
380    if len(mult) != nl * ngram or len(primes) != nl * cols or len(offs) != nl * cols:
381        raise 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))
383    pad = int(tm[g("engram.pad_token_id")])
384    full = tm + [0] * max(0, vocab - len(tm))
385    with out.open("wb") as f:
386        f.write(struct.pack("<4s6i", b"DSE1", vocab, nl, ngram, heads, hd, pad))
387        f.write(struct.pack("<%di" % vocab, *full[:vocab]))
388        f.write(struct.pack("<%dq" % len(mult), *mult))
389        f.write(struct.pack("<%dq" % len(primes), *primes))
390        f.write(struct.pack("<%dq" % len(offs), *offs))
391    return nl, cols
392
393
394def write_tokenizer(out: pathlib.Path, kv: dict, template: str | None):
395    tokens = kv["tokenizer.ggml.tokens"]
396    types = kv.get("tokenizer.ggml.token_type") or [1] * len(tokens)
397    merges = kv.get("tokenizer.ggml.merges") or []
398    if len(set(tokens)) != len(tokens):
399        raise SystemExit("the GGUF's vocabulary has duplicate token strings")
400    out.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),
402                                    encoding="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]))
405    special = {"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))
408    if template:
409        (out / "chat_template.jinja").write_text(template, encoding="utf-8")
410
411
412def main() -> int:
413    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
414    ap.add_argument("--model", required=True, help="the directory of the GGUF's shards")
415    ap.add_argument("--out", help="default: <model>/maya-ds4")
416    ap.add_argument("--vision", help="vision_pack.py's folder (default: <model>/../vision; taken when it is there)")
417    ap.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)")
420    ap.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)")
422    ap.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")
424    ap.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)")
426    ap.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")
428    ap.add_argument("--override-roles", default="down")
429    ap.add_argument("--override-layers", default="")
430    ap.add_argument("--tq-layers", help="only these layers (comma list) of the --tq-experts folders")
431    ap.add_argument("--drafter", help="the DSpark drafter's .json (drafter_pack.py's; default <model>/../dspark/dspark.json)")
432    ap.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")
434    ap.add_argument("--dspark-markov-rank", type=int, help="the markov head's rank (dspark_markov_rank); default: the drafter's "
435                                                          "markov tensor shape")
436    ap.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")
439    ap.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)")
441    ap.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")
445    ap.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)")
447    a = ap.parse_args()
448    model = pathlib.Path(a.model).expanduser().resolve()
449    out = pathlib.Path(a.out).expanduser() if a.out else model / "maya-ds4"
450    shards = [model / n for n in a.shards] if a.shards else sorted(model.glob("*.gguf"))
451    if not shards or not all(p.is_file() for p in shards):
452        raise 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()))
454    gs = [Gguf(p) for p in shards]
455    if not a.shards:                       # a folder's *.gguf: the Engram table (architecture 'engram', today 'deepseek41-engram') is not a model shard
456        keep = [i for i, g in enumerate(gs) if not is_engram_file(g)]
457        shards, gs = [shards[i] for i in keep], [gs[i] for i in keep]
458        if not gs:
459            raise SystemExit("%s: no model shards (only an Engram table)" % model)
460    kv = model_kv(gs)
461    if kv is None:
462        arch = next((g.kv.get("general.architecture") for g in gs), None)
463        raise SystemExit("%s: not a DeepSeek-V4.1 GGUF (architecture %r)" % (model, arch))
464    split = int(kv.get("split.count", 1))
465    if split != len(shards):
466        counts = sorted({m.group(1) for m in (re.search(r"-of-(\d{5})\.gguf$", p.name) for p in shards) if m})
467        raise 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.*
472    if a.engram_meta:
473        mg = Gguf(pathlib.Path(a.engram_meta).expanduser().resolve())
474        for k, v in mg.kv.items():
475            if ".engram." in k or ".ple." in k or k.endswith(".embedding_length_per_layer_input"):
476                kv.setdefault(k, v)
477    ple_to_engram(kv)
478    for g in gs:
479        split_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.
485    have = {t[0] for g in gs for t in g.tensors}
486    arch = kv["general.architecture"]
487    int_tensors_to_engram(gs, kv)
488    layers = 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.
493    if any(n.endswith(".engram_wkv.weight") for n in have) and (a.skip_tensors or a.dense_override):
494        sys.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
498    def has_part(il, part, names):
499        if "blk.%d.%s.weight" % (il, part) in names:
500            return True
501        if part == "engram_kv":
502            return "blk.%d.engram_wkv.weight" % il in names
503        if part == "engram_gate":
504            return "blk.%d.engram_q.weight" % il in names and "blk.%d.engram_k.weight" % il in names
505        return False
506    lacking = not layers or any(not has_part(il, part, have)
507                                for il in layers for part in ("engram_embd", "engram_kv", "engram_gate"))
508    eg_dir, egs = engram_set(model, a.engram) if lacking or a.engram else (None, [])
509    eg_from = {}
510    if eg_dir is not None:
511        eshards = [g.path for g in egs]
512        for g in egs:
513            for k, v in g.kv.items():
514                if ".engram." in k or ".ple." in k or k.endswith(".embedding_length_per_layer_input"):
515                    kv.setdefault(k, v)
516        ple_to_engram(kv)
517        for g in egs:
518            split_ple(g, kv)
519        for p, g in zip(eshards, egs):
520            picked = [t for t in g.tensors if re.match(r"blk\.\d+\.engram_", t[0]) and t[0] not in have]
521            picked = [t for t in picked if t[0].endswith("engram_embd.weight") or not has_part(
522                int(t[0].split(".")[1]), "engram_kv" if t[0].endswith("engram_kv.weight") else "engram_gate", have)]
523
524            if picked:
525                g.tensors = picked
526                eg_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")
530    ov_names = set()
531    for dsrc in (a.dense_override or []):
532        try:
533            ov_names |= set(json.loads((pathlib.Path(dsrc).expanduser().resolve() / "dense.json").read_text()).keys())
534        except (OSError, ValueError):
535            pass
536    for il in kv.get("%s.engram.layers" % arch, []):
537        for part in ("engram_embd", "engram_kv", "engram_gate"):
538            nm = "blk.%d.%s.weight" % (il, part)
539            # a dense override names tensors the way the pack does, not the way the GGUF does
540            eng_nm = "layers.%d.%s" % (il, LAYER[part + ".weight"])
541            if (not has_part(il, part, have) and eng_nm not in ov_names
542                    and not any(t[0] == nm for g in eg_from.values() for t in g.tensors)):
543                raise 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)
545    rel = lambda p: os.path.relpath(p, model).replace(os.sep, "/")  # noqa: E731
546    gs_all = gs + list(eg_from.values())
547    names = [g.path.name for g in gs] + [rel(p) for p in eg_from]
548
549    tensors, unknown, skipped = [], [], []
550    skip_re = re.compile(a.skip_tensors) if a.skip_tensors else None
551    for fi, g in enumerate(gs_all):
552        for name, typ, dims, off in g.tensors:
553            if skip_re is not None and skip_re.search(name):
554                skipped.append("%s (asked for)" % name)
555                continue
556            if typ not in TYPES:
557                if typ in (24, 25, 26, 27, 28):   # I8 / I16 / I32 / I64 / F64: metadata carried as tensors, not weights
558                    skipped.append("%s (type %d)" % (name, typ))   # (the IST-DAS sets' engram_token_map.weight)
559                    continue
560                raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (g.path.name, name, typ))
561            tname, per, bpb = TYPES[typ]
562            nel = 1
563            for d in dims:
564                nel *= d
565            if dims[0] % per:
566                raise SystemExit("%s: %s rows of %d are not whole %s blocks" % (g.path.name, name, dims[0], tname))
567            nbytes = nel // per * bpb
568            m = re.match(r"blk\.(\d+)\.(.+)$", name)
569            if m and m.group(2) in LAYER:
570                ck = "layers.%s.%s" % (m.group(1), LAYER[m.group(2)])
571            elif name in GLOBAL:
572                ck = GLOBAL[name]
573            else:
574                unknown.append(name)
575                continue
576            shape = list(reversed(dims))     # ggml ne0 innermost -> torch order, outermost first
577            base = g.data_start + off
578            if 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 ..)
580                n = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
581                if len(shape) == 3 and shape[0] == n:   # (the IST-DAS sets: [groups][o_lora][in] in one tensor)
582                    shape = [shape[0] * shape[1], shape[2]]
583                if len(shape) != 2 or shape[0] % n:
584                    raise SystemExit("%s: %s %s does not split in %d groups" % (g.path.name, name, shape, n))
585                part = nbytes // n
586                for i in range(n):
587                    tensors.append(("%s.%d.weight" % (ck, i), tname, fi, base + i * part, part,
588                                    [shape[0] // n, shape[1]]))
589                continue
590            if ".ffn.experts." in ck:
591                # [n_exp][out][in] -> an entry an expert: layers.N.ffn.experts.E.w1.weight
592                n, part = shape[0], nbytes // shape[0]
593                pre, role = ck.rsplit(".", 1)
594                for i in range(n):
595                    tensors.append(("%s.%d.%s.weight" % (pre, i, role), tname, fi, base + i * part, part, shape[1:]))
596                continue
597            tensors.append((ck, tname, fi, base, nbytes, shape))
598    if unknown:
599        raise SystemExit("tensors the pack does not map (%d): %s" % (len(unknown), ", ".join(unknown[:12])))
600    if skipped:
601        print("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
604    files = names
605    if eg_from:
606        print("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)
608    n_ov = 0
609    for spec in (a.override_experts or []):
610        dpath, _, drl = spec.partition(":")
611        od = pathlib.Path(dpath).expanduser().resolve()
612        roles_ov = {"gate": "w1", "up": "w3", "down": "w2"}
613        want = {roles_ov[r] for r in (drl or a.override_roles).split(",")}
614        lay_ov = None
615        if a.override_layers:
616            lay_ov = set()
617            for part in a.override_layers.split(","):
618                lo, _, hi = part.partition("-")
619                lay_ov.update(range(int(lo), int(hi or lo) + 1))
620        ogs = [Gguf(pth) for pth in sorted(od.glob("*.gguf"))]
621        new = []
622        for og in ogs:
623            try:
624                orel = os.path.relpath(og.path, model).replace(os.sep, "/")
625            except ValueError:
626                raise SystemExit("%s must be on the model's drive" % od)
627            files.append(orel)
628            ofi = len(files) - 1
629            for name, typ, dims, off in og.tensors:
630                m = re.match(r"blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$", name)
631                if not m or typ not in TYPES:
632                    continue
633                il, role = int(m.group(1)), {"gate": "w1", "up": "w3", "down": "w2"}[m.group(2)]
634                if role not in want or (lay_ov is not None and il not in lay_ov):
635                    continue
636                tname, per, bpb = TYPES[typ]
637                nel = 1
638                for d in dims:
639                    nel *= d
640                nbytes = nel // per * bpb
641                shape = list(reversed(dims))
642                n, part = shape[0], nbytes // shape[0]
643                for i in range(n):
644                    new.append(("layers.%d.ffn.experts.%d.%s.weight" % (il, i, role), tname, ofi, og.data_start + off + i * part, part, shape[1:]))
645        names_new = {t[0] for t in new}
646        tensors[:] = [t for t in tensors if t[0] not in names_new] + new
647        n_ov += len(new)
648        print("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
650    n_dense = 0
651    for dsrc in (a.dense_override or []):
652        dd = pathlib.Path(dsrc).expanduser().resolve()
653        dj = json.loads((dd / "dense.json").read_text())
654        try:
655            relf = os.path.relpath(dd / "dense.bin", model).replace(os.sep, "/")
656        except ValueError:
657            raise SystemExit("%s must be on the model's drive" % dd)
658        if relf not in files:
659            files.append(relf)
660        dfi = files.index(relf)
661        pos = {t[0]: i for i, t in enumerate(tensors)}
662        n_here = n_add = 0
663        for name, (tname, fname, off, nb, shape) in dj.items():
664            if 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
667                tensors.append((name, tname, dfi, off, nb, shape))
668                pos[name] = len(tensors) - 1
669                n_add += 1
670                continue
671            tensors[pos[name]] = (name, tname, dfi, off, nb, shape)
672            n_here += 1
673        n_dense += n_here + n_add
674        print("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)
678    ds_path = pathlib.Path(a.dspark_gguf).expanduser().resolve() if a.dspark_gguf else next(
679        iter(sorted(model.parent.glob("dspark-*.gguf"))), None)
680    dspark_gguf = False
681    if ds_path is not None:
682        if not ds_path.is_file():
683            raise SystemExit("%s: no DSpark GGUF there" % ds_path)
684        dg = Gguf(ds_path)
685        if dg.kv.get("general.architecture") != "dflash":
686            raise 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)
689        for k, dk in (("block_size", "block_size"), ("expert_count", "expert_count"),
690                      ("expert_used_count", "expert_used_count"), ("target_layers", "target_layers")):
691            v = dg.kv.get("dflash." + dk)
692            if v is not None:
693                kv.setdefault("%s.dspark.%s" % (arch, k), v)
694        if a.dspark_noise_token is not None:
695            kv.setdefault("%s.dspark.noise_token_id" % arch, int(a.dspark_noise_token))
696        if a.dspark_markov_rank is not None:
697            kv.setdefault("%s.dspark.markov_rank" % arch, int(a.dspark_markov_rank))
698        else:
699            for name, typ, dims, off in dg.tensors:
700                if "markov" in name and len(dims) == 2:
701                    kv.setdefault("%s.dspark.markov_rank" % arch, int(dims[0]))
702                    break
703        nb = int(dg.kv["dflash.block_count"])
704        files.append(rel(ds_path))
705        fi = len(files) - 1
706        HEAD = {"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)}
711        groups = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
712        bad = []
713        for name, typ, dims, off in dg.tensors:
714            if typ not in TYPES:
715                raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (ds_path.name, name, typ))
716            tname, per, bpb = TYPES[typ]
717            nel = 1
718            for d in dims:
719                nel *= d
720            nbytes = nel // per * bpb
721            m = re.match(r"blk\.(\d+)\.(.+)$", name)
722            if m and m.group(2) in LAYER:
723                ck = "mtp.%s.%s" % (m.group(1), LAYER[m.group(2)])
724            elif name in HEAD:
725                ck = HEAD[name]
726            else:
727                bad.append(name)
728                continue
729            shape = list(reversed(dims))
730            base = dg.data_start + off
731            if ck.endswith(".attn.wo_a.slice"):
732                part = nbytes // groups
733                for i in range(groups):
734                    tensors.append(("%s.%d.weight" % (ck, i), tname, fi, base + i * part, part, [shape[0] // groups, shape[1]]))
735            elif ".ffn.experts." in ck:
736                n, part = shape[0], nbytes // shape[0]
737                pre, role = ck.rsplit(".", 1)
738                for i in range(n):
739                    tensors.append(("%s.%d.%s.weight" % (pre, i, role), tname, fi, base + i * part, part, shape[1:]))
740            else:
741                tensors.append((ck, tname, fi, base, nbytes, shape))
742        if bad:
743            raise SystemExit("DSpark GGUF tensors the pack does not map (%d): %s" % (len(bad), ", ".join(bad[:12])))
744        dspark_gguf = True
745        print("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
748    mm_path = pathlib.Path(a.mmproj).expanduser().resolve() if a.mmproj else find_mmproj(model)
749    mm_geo = {}
750    if mm_path is not None:
751        if not mm_path.is_file():
752            raise SystemExit("%s: no mmproj GGUF there" % mm_path)
753        mg = Gguf(mm_path)
754        if mg.kv.get("clip.projector_type") != "deepseek41v":
755            raise SystemExit("%s: not a DeepSeek-V4.1 vision GGUF (projector %r)" % (mm_path, mg.kv.get("clip.projector_type")))
756        files.append(rel(mm_path))
757        fi = len(files) - 1
758        FIX = {"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"}
762        BLK = {"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"}
765        bad = []
766        for name, typ, dims, off in mg.tensors:
767            if typ not in TYPES:
768                raise SystemExit("%s: %s has ggml type %d, which the engine does not read" % (mm_path.name, name, typ))
769            tname, per, bpb = TYPES[typ]
770            nel = 1
771            for d in dims:
772                nel *= d
773            m = re.match(r"v\.blk\.(\d+)\.(.+)$", name)
774            if m and m.group(2) in BLK:
775                ck = "vision.blocks.%s.%s" % (m.group(1), BLK[m.group(2)])
776            elif name in FIX:
777                ck = FIX[name]
778            else:
779                bad.append(name)
780                continue
781            shape = list(reversed(dims))
782            if name == "v.patch_embd.weight":    # conv [out][3][14][14] -> [out][3 * 14 * 14], the same bytes
783                shape = [shape[0], nel // shape[0]]
784            tensors.append((ck, tname, fi, mg.data_start + off, nel // per * bpb, shape))
785        if bad:
786            raise SystemExit("mmproj tensors the pack does not map (%d): %s" % (len(bad), ", ".join(bad[:12])))
787        k = lambda n, d=None: mg.kv.get("clip.vision." + n, d)  # noqa: E731
788        toks = kv.get("tokenizer.ggml.tokens", [])
789        img_id = next((i for i, t in enumerate(toks) if t == "<|deepseek_image|>"), None)
790        if img_id is None:
791            raise SystemExit("the vocabulary has no <|deepseek_image|> token")
792        mm_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        print("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
799    tq_layers = []
800    if a.tq_experts:
801        by_layer, tq_dirs = {}, {}
802        for d in a.tq_experts:
803            tqd = pathlib.Path(d).expanduser().resolve()
804            for key, ent in json.loads((tqd / "tq.json").read_text()).items():
805                m = re.match(r"layers\.(\d+)\.ffn\.experts\.(w[123])$", key)
806                if not m:
807                    raise SystemExit("tq.json: %s is not a layer's expert role" % key)
808                by_layer.setdefault(int(m.group(1)), {})[m.group(2)] = ent
809                tq_dirs[(int(m.group(1)), m.group(2))] = tqd
810        if a.tq_layers:
811            keep = {int(x) for x in a.tq_layers.split(",")}
812            by_layer = {il: r for il, r in by_layer.items() if il in keep}
813        TQTYPES = {v[0]: k for k, v in TYPES.items()}
814        for il, roles in sorted(by_layer.items()):
815            if sorted(roles) != ["w1", "w2", "w3"]:
816                raise SystemExit("tq.json: layer %d lacks a role (has %s)" % (il, sorted(roles)))
817            if len({r[0] for r in roles.values()}) != 1 or roles["w1"][0] != roles["w3"][0]:
818                raise SystemExit("tq.json: layer %d: gate and up must be one type" % il)
819            drop = re.compile(r"layers\.%d\.ffn\.experts\.\d+\.w[123]\.weight$" % il)
820            kept = [t for t in tensors if not drop.match(t[0])]
821            if len(kept) == len(tensors):
822                raise SystemExit("layer %d has no routed experts in the GGUF to replace" % il)
823            tensors[:] = kept
824            for role, (tname, fname, off, total, shape) in roles.items():
825                if tname not in TQTYPES:
826                    raise SystemExit("tq.json: unknown type %s" % tname)
827                n_exp, rows, cols = shape
828                per = total // n_exp
829                f = tq_dirs[(il, role)] / fname
830                if not f.is_file() or f.stat().st_size < off + total:
831                    raise SystemExit("%s: missing or short" % f)
832                try:
833                    relf = os.path.relpath(f, model).replace(os.sep, "/")
834                except ValueError:
835                    raise SystemExit("%s must be on the model's drive" % f)
836                if relf not in files:
837                    files.append(relf)
838                fi = files.index(relf)
839                for e in range(n_exp):
840                    tensors.append(("layers.%d.ffn.experts.%d.%s.weight" % (il, e, role), tname, fi, off + e * per, per, [rows, cols]))
841            tq_layers.append(il)
842        print("trellis experts from %s: layers %s" % (", ".join(a.tq_experts), tq_layers))
843    drafter = pathlib.Path(a.drafter).expanduser().resolve() if a.drafter else model.parent / "dspark" / "dspark.json"
844    if a.drafter and not drafter.is_file():
845        raise SystemExit("%s: no drafter there" % drafter)
846    drafter_in = (drafter.is_file() and drafter.with_suffix(".bin").is_file()) and not dspark_gguf
847    if drafter_in:
848        files.append(rel(drafter.with_suffix(".bin")))
849        groups = int(kv["%s.attention.output_group_count" % kv["general.architecture"]])
850        for name, dt, off, nb, shape in json.loads(drafter.read_text())["tensors"]:
851            if name.endswith(".attn.wo_a.weight"):   # (one entry a group, as the trunk's)
852                for i in range(groups):
853                    tensors.append(("%s.slice.%d.weight" % (name[:-len(".weight")], i), dt, len(files) - 1,
854                                    off + i * (nb // groups), nb // groups, [shape[0] // groups, shape[1]]))
855                continue
856            tensors.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
859    vdir = pathlib.Path(a.vision).expanduser().resolve() if a.vision else model.parent / "vision"
860    vision = {}
861    if (vdir / "vision.json").is_file() and (vdir / "vision.bin").is_file():
862        try:
863            rel = os.path.relpath(vdir / "vision.bin", model).replace(os.sep, "/")
864        except ValueError:     # (Windows: another drive)
865            raise SystemExit("%s: the vision folder must be on the model's drive" % vdir)
866        if " " in rel:
867            raise SystemExit("%s: the vision folder's path relative to the model has a space" % vdir)
868        files.append(rel)
869        info = json.loads((vdir / "vision.json").read_text())
870        for name, dt, off, nb, shape in info["tensors"]:
871            tensors.append((name, dt, len(files) - 1, off, nb, shape))
872        vision = info["config"]
873    if mm_geo and not vision:
874        vision = mm_geo
875    vocab = next(t[5][0] for t in tensors if t[0] == "embed.weight")
876    geo = geometry(kv, vocab)
877
878    out.mkdir(parents=True, exist_ok=True)
879    with (out / "ds4.txt").open("w") as f:
880        for k, v in geo.items():
881            if v is None:
882                continue
883            if isinstance(v, bool):
884                v = int(v)
885            f.write("%s %s\n" % (k, ",".join(str(x) for x in v) if isinstance(v, list) else v))
886        for k, v in vision.items():
887            f.write("%s %s\n" % (k, v))
888        f.write("format gguf\n")
889        f.write("model_dir %s\n" % model)
890    with (out / "tensors.txt").open("w") as f:
891        for i, name in enumerate(files):
892            f.write("file %d %s\n" % (i, name))
893        for name, dt, fi, off, nb, shape in tensors:
894            f.write("t %s %s %d %d %d %s\n" % (name, dt, fi, off, nb, " ".join(map(str, shape))))
895    nl, 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.
899    template = kv.get("tokenizer.chat_template")
900    if not template:
901        sys.exit("%s: the GGUF has no tokenizer.chat_template; refusing to fall back to the old Maya template (#299)" % model)
902    write_tokenizer(out / "tokenizer", kv, template)
903    by = {}
904    for t in tensors:
905        by[t[1]] = by.get(t[1], 0) + t[4]
906    extras = [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    print("%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())),
909           nl, cols, "".join(", " + w for w in extras), out))
910    return 0
911
912
913if __name__ == "__main__":
914    sys.exit(main())