okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
34.9 KiB703 linesraw
1"""tools/nvfp4_local_pack.py - NVIDIA's Qwen3.8-Flash-Next-FP4-Local (ModelOpt, QAD) -> files Strata can pack.
2
3    python tools/nvfp4_local_pack.py convert --model <nvidia/Qwen3.8-Flash-Next-FP4-Local dir> --outfile <model.gguf>
4    python tools/nvfp4_local_pack.py ple     --model <same dir> --out <ple-nvfp4.gguf>
5    python tools/nvfp4_local_pack.py mtp     --model <same dir> --out <mtp src dir>   (then tools/mtp_pack.py, tools/mtp_rt.py)
6    python tools/nvfp4_local_pack.py pack    --model <same dir> --dense-gguf <dense.gguf> --out <pack dir>   (instead of iq_pack on a full GGUF)
7    python tools/nvfp4_local_pack.py verify  --model <same dir> --gguf <model.gguf> [--experts 6]
8    python tools/iq_pack.py --gguf <model.gguf> --out <pack dir>
9
10Nothing of NVIDIA's weights is shipped: the user downloads the checkpoint from NVIDIA's repository and this runs
11locally. What the checkpoint stores, and what is done with it:
12
13  * routed experts: NVFP4 (E2M1 codes, E4M3 scale per 16 values, F32 weight_scale_2). The block scales are stored
14    in NVIDIA's "CSF" form (config `weight_scale_encoding: "csf"`, codec byte-window4-fixed-stream-u24-exceptions/1):
15    per tensor a `.nvfp4_csf_fixed` U8 stream and a `.nvfp4_csf_exceptions` U32 stream. They are decoded here to the
16    plain E4M3 matrix (the format is documented by vLLM's loader, PR 60646, and flashinfer's b12x decoder, both
17    Apache-2.0; this is a fresh implementation of that description), and from there the ordinary ModelOpt NVFP4
18    repack of tools/nvfp4_convert.py applies, bit for bit.
19  * attention, GDN projections, shared experts, indexer: MXFP8 (E4M3 values, E8M0 scale per 32 values). They are
20    dequantized exactly to BF16 and then take the type policy of tools/nvfp4_convert.py (Q8_0 for the big ones,
21    BF16 for the small projections the BF16 kernels read). Q8_0 has the same 32-value blocks; the added error is
22    ~0.6% RMS against MXFP8's own ~3%.
23  * the 26.8 GiB n-gram (PLE) table is NVFP4 too (160 values a row: 80 B of codes, 10 E4M3 scales, one F32 for the
24    whole table). `ple` copies it row by row into a one-tensor GGUF of 90-byte rows.
25  * the MTP head (NVFP4 experts, BF16 rest) is dequantized by `mtp` into the folder form tools/mtp_pack.py reads.
26    The vision tower is not written (text first).
27"""
28from __future__ import annotations
29
30import argparse
31import json
32import pathlib
33import struct
34import sys
35import time
36
37import numpy as np
38
39HERE = pathlib.Path(__file__).resolve().parent
40sys.path.insert(0, str(HERE))
41
42# #3227: llama.cpp's converter (conversion/base.py: `from transformers import AutoConfig`) and the MXFP8 / NVFP4 decoding below need
43# these; setup installs them from requirements-nvfp4-local.txt before a prepare, and a run by hand says which one is missing.
44NEEDED_PACKAGES = ("torch", "transformers", "safetensors")
45MARKS = ("ple-nvfp4.gguf.done", "dense.gguf.done", "pack.done", "draft.done")
46
47
48def require_packages() -> None:
49    import importlib.util
50    missing = [m for m in NEEDED_PACKAGES if importlib.util.find_spec(m) is None]
51    if missing:
52        req = HERE.parent / "requirements-nvfp4-local.txt"
53        sys.exit("tools/nvfp4_local_pack.py needs the Python package%s %s, which %s not installed for %s.\n"
54                 "Install %s with:  %s -m pip install -r %s" % ("s" if len(missing) > 1 else "", ", ".join(missing),
55                                                                "are" if len(missing) > 1 else "is", sys.executable,
56                                                                "them" if len(missing) > 1 else "it", sys.executable, req))
57
58
59CSF_FIXED = ".nvfp4_csf_fixed"
60CSF_EXC = ".nvfp4_csf_exceptions"
61PLE_ROW_BYTES = 90          # 80 B of E2M1 codes + 10 E4M3 block scales, per 160-value row
62
63
64# --------------------------------------------------------------------------------------------- safetensors access
65class Checkpoint:
66    """Header-indexed, buffered access to a checkpoint's safetensors shards (raw bytes, any dtype).
67
68    Reads go through a cached file handle into a fresh buffer instead of a process-lifetime np.memmap:
69    a memmap sweep of the ~64 GB of expert bytes charges every faulted page to the PROCESS WORKING
70    SET, which Windows (and every free-RAM observer reading GlobalMemoryStatusEx) counts as used
71    until the OS trims it - the pack step then looks like a ~64 GB RAM demand while its real
72    committed need is a few GB, and under memory pressure it is the pack run itself that pays
73    (issue: the silent exit-1 mid-pack failure).
74    A cached sequential read puts the same pages in the system file cache (standby: counted as
75    available).  The returned array is a fresh WRITABLE buffer - no consumer writes (a mutator would
76    previously have hit the read-only memmap) - and reads share one handle per shard, so raw() is
77    not thread-safe, unlike the memmap it replaces.  Each shard is read as three ascending streams
78    (exceptions, weights, CSF-fixed) walked expert-ascending."""
79
80    def __init__(self, folder, partial_ok=False):
81        self.dir = pathlib.Path(folder)
82        index = self.dir / "model.safetensors.index.json"
83        if index.exists():
84            wmap = json.loads(index.read_text(encoding="utf-8"))["weight_map"]
85            files = sorted(set(wmap.values()))
86        else:
87            files = sorted(p.name for p in self.dir.glob("*.safetensors"))
88        if not files:
89            raise FileNotFoundError("no .safetensors files in " + str(self.dir))
90        self.meta: dict[str, tuple[str, str, list[int], int, int]] = {}
91        self._fh: dict[str, "object"] = {}
92        for fn in files:
93            path = self.dir / fn
94            if not path.exists() and partial_ok:
95                continue                                  # a subset of the shards (the MTP head is in two)
96            with open(path, "rb") as f:
97                n = struct.unpack("<Q", f.read(8))[0]
98                hdr = json.loads(f.read(n))
99            for k, v in hdr.items():
100                if k != "__metadata__":
101                    a, b = v["data_offsets"]
102                    self.meta[k] = (fn, v["dtype"], v["shape"], 8 + n + a, 8 + n + b)
103
104    def __contains__(self, name):
105        return name in self.meta
106
107    def dtype(self, name):
108        return self.meta[name][1]
109
110    def shape(self, name):
111        return self.meta[name][2]
112
113    def raw(self, name) -> np.ndarray:
114        fn, _, _, a, b = self.meta[name]
115        f = self._fh.get(fn)
116        if f is None:
117            f = self._fh[fn] = open(self.dir / fn, "rb")
118        buf = np.empty(b - a, dtype=np.uint8)
119        f.seek(a)
120        if f.readinto(buf) != b - a:
121            raise EOFError("%s: shard %s ended early at %d" % (name, fn, a))
122        return buf
123
124    def array(self, name, np_dtype) -> np.ndarray:
125        return self.raw(name).view(np_dtype).reshape(self.shape(name))
126
127
128# ----------------------------------------------------------------------------------------------------- CSF decoding
129def csf_decode(fixed: np.ndarray, exceptions: np.ndarray) -> np.ndarray:
130    """The CSF stream pair -> the plain E4M3 block-scale matrix as uint8 [rows, cols] (cols = K / 16).
131
132    fixed:      uint8 [rows / 16, 16 * (1 + cols / 2)]. Per slab of 16 rows: the 16 rows' base bytes, then each
133                row's cols 4-bit codes (two to a byte, low nibble first). A scale byte is base + code.
134    exceptions: uint32 words, low 24 bits = flat row * cols + col, high 8 bits = the scale byte there.
135    """
136    if fixed.dtype != np.uint8 or fixed.ndim != 2 or fixed.shape[1] % 16 or fixed.shape[1] < 32:
137        raise ValueError("invalid CSF fixed stream %s %s" % (fixed.dtype, fixed.shape))
138    if exceptions.dtype != np.uint32:
139        raise ValueError("invalid CSF exceptions dtype %s" % exceptions.dtype)
140    rows = fixed.shape[0] * 16
141    cols = (fixed.shape[1] // 16 - 1) * 2
142    bases = fixed[:, :16].reshape(rows, 1).astype(np.int16)
143    if (bases > 240).any():
144        raise ValueError("CSF row bases must be in 0..240")
145    packed = fixed[:, 16:].reshape(rows, cols // 2)
146    codes = np.stack((packed & 0xF, packed >> 4), axis=-1).reshape(rows, cols)
147    out = (bases + codes).reshape(-1)
148    words = exceptions.reshape(-1).astype(np.int64)
149    pos = words & 0xFFFFFF
150    if pos.size and int(pos.max()) >= rows * cols:
151        raise ValueError("CSF exception position out of range")
152    out[pos] = words >> 24
153    return out.astype(np.uint8).reshape(rows, cols)
154
155
156def csf_encode(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
157    """The inverse, for the tests: uint8 [rows, cols] -> (fixed, exceptions). Base = the row's most common
158    window start; whatever falls outside base..base+15 is an exception."""
159    rows, cols = scales.shape
160    assert rows % 16 == 0 and cols % 2 == 0
161    base = np.zeros(rows, np.int16)
162    for r in range(rows):
163        v = scales[r].astype(np.int16)
164        best = (-1, 0)
165        for b in range(max(0, int(v.min()) - 0), int(v.max()) + 1):
166            c = int(((v >= b) & (v <= b + 15)).sum())
167            if c > best[0]:
168                best = (c, b)
169        base[r] = min(best[1], 240)
170    code = scales.astype(np.int16) - base[:, None]
171    exc = (code < 0) | (code > 15)
172    code = np.where(exc, 0, code).astype(np.uint8)
173    pk = (code[:, 0::2] | (code[:, 1::2] << 4)).astype(np.uint8)
174    fixed = np.empty((rows // 16, 16 * (1 + cols // 2)), np.uint8)
175    for s in range(rows // 16):
176        fixed[s, :16] = base[s * 16:(s + 1) * 16].astype(np.uint8)
177        fixed[s, 16:] = pk[s * 16:(s + 1) * 16].reshape(-1)
178    pos = np.flatnonzero(exc.reshape(-1))
179    words = (pos.astype(np.uint64) | (scales.reshape(-1)[pos].astype(np.uint64) << 24)).astype(np.uint32)
180    return fixed, words
181
182
183# --------------------------------------------------------------------------------------------- MXFP8 dequantizing
184def mxfp8_dequant(values_u8: np.ndarray, scales_u8: np.ndarray):
185    """MXFP8 (E4M3 values [R, K], E8M0 scale bytes [R, K/32]) -> float32 [R, K]. Exact (4-bit significands)."""
186    import torch
187    R, K = values_u8.shape
188    if scales_u8.shape != (R, K // 32) or K % 32:
189        raise ValueError("MXFP8 shapes %s / %s" % (values_u8.shape, scales_u8.shape))
190    if (scales_u8 == 255).any():
191        raise ValueError("MXFP8 scale byte 255 (NaN) in a weight")
192    v = torch.from_numpy(np.ascontiguousarray(values_u8)).view(torch.float8_e4m3fn).to(torch.float32)
193    s = torch.from_numpy(np.exp2(scales_u8.astype(np.float32) - 127.0))
194    return (v.reshape(R, K // 32, 32) * s[:, :, None]).reshape(R, K)
195
196
197# --------------------------------------------------------------------------- the overlay on llama.cpp's tensor index
198def _orig_name(ck: Checkpoint, name: str):
199    """The converter strips `language_model.`; find the checkpoint's own name."""
200    if name in ck:
201        return name
202    for cand in (name.replace("model.", "model.language_model.", 1), "model.language_model." + name):
203        if cand in ck:
204            return cand
205    return None
206
207
208def overlay(tensors: dict, ck: Checkpoint, stats: dict, dense_only: bool = False) -> dict:
209    """Replace the CSF stream pairs by plain `weight_scale` tensors, the MXFP8 weights by BF16, and drop what
210    the PLE writer and the MTP packer own."""
211    import torch
212    out = dict(tensors)
213    if dense_only:                                  # the GGUF the engine reads the dense weights from: no experts in it
214        out = {k: v for k, v in out.items() if ".mlp.experts." not in k}
215    for name in list(out):
216        if name not in out:
217            continue
218        if name.endswith(CSF_FIXED):
219            base = name[: -len(CSF_FIXED)]                       # ...weight_scale
220            o_fix = _orig_name(ck, name)
221            o_exc = _orig_name(ck, base + CSF_EXC)
222            if o_fix is None or o_exc is None:
223                raise ValueError("CSF fixed stream without its exceptions: " + name)
224
225            def gen(o_fix=o_fix, o_exc=o_exc):
226                dec = csf_decode(ck.array(o_fix, np.uint8), ck.array(o_exc, np.uint32))
227                return torch.from_numpy(dec).view(torch.float8_e4m3fn)
228            del out[name]
229            out.pop(base + CSF_EXC, None)
230            out[base] = gen
231            stats["csf"] = stats.get("csf", 0) + 1
232        elif ".ngram_embedding." in name and (name.endswith(".weight_scale") or name.endswith(".weight_scale_2")):
233            del out[name]                                         # the PLE table has its own writer (`ple`)
234    for name in list(out):
235        if not name.endswith(".weight") or ".ngram_embedding." in name:
236            continue
237        sname = name[: -len(".weight")] + ".weight_scale"
238        o_w, o_s = _orig_name(ck, name), _orig_name(ck, sname)
239        if o_w is None or o_s is None or sname not in out:
240            continue
241        if ck.dtype(o_w) == "F8_E4M3" and ck.dtype(o_s) == "U8":     # MXFP8
242            def gen(o_w=o_w, o_s=o_s):
243                f = mxfp8_dequant(np.asarray(ck.raw(o_w)).reshape(ck.shape(o_w)), np.asarray(ck.raw(o_s)).reshape(ck.shape(o_s)))
244                return f.to(torch.bfloat16)
245            out[name] = gen
246            del out[sname]
247            stats["mxfp8"] = stats.get("mxfp8", 0) + 1
248    return out
249
250
251def install(ck: Checkpoint, stats: dict, dense_only: bool = False):
252    """Import the converter, give it nvfp4_convert's type policy, and hook the tensor index."""
253    import nvfp4_convert as base
254    base.install_policy()
255    from conversion.base import ModelBase
256    from conversion import qwen4exp as Q4
257    orig_index = ModelBase.index_tensors
258
259    def index_tensors(self, remote_hf_model_id=None):
260        return overlay(orig_index(self, remote_hf_model_id), ck, stats, dense_only)
261    ModelBase.index_tensors = index_tensors
262
263    # NVIDIA's repo keeps the shards in a `tensors/` folder that its index names; the converter only lists the top level
264    orig_parts = ModelBase.get_model_part_names
265
266    def get_model_part_names(dir_model, prefix, suffix):
267        names = orig_parts(dir_model, prefix, suffix)
268        sub = pathlib.Path(dir_model) / "tensors"
269        if not names and suffix == ".safetensors" and prefix == "model" and sub.is_dir():
270            names = sorted("tensors/" + p.name for p in sub.glob("model*.safetensors"))
271        return names
272    ModelBase.get_model_part_names = staticmethod(get_model_part_names)
273
274    cls = Q4.Qwen4ExpTextModel
275
276    def place_ple_shard(self, data_torch, name):
277        # the shards are NVFP4 here: two values a byte, so a row of 160 values is 80 bytes
278        idx = int(name.rsplit("shard_", 1)[1].split(".", 1)[0])
279        self._ple_shards[idx] = name
280        self._ple_row_dim = int(data_torch.shape[-1]) * 2
281        base.dropped_ple.append(name)
282        return []
283    cls._place_ple_shard = place_ple_shard
284    return base
285
286
287def cmd_convert(a) -> int:
288    require_packages()
289    model = pathlib.Path(a.model)
290    ck = Checkpoint(model)
291    stats: dict = {}
292    base = install(ck, stats, a.dense_only)
293    import convert_hf_to_gguf as C
294    out = pathlib.Path(a.outfile)
295    out.parent.mkdir(parents=True, exist_ok=True)
296    argv = [str(model), "--outtype", "q8_0", "--outfile", str(out)] + (["--dry-run"] if a.dry_run else [])
297    sys.argv = ["convert_hf_to_gguf.py"] + argv
298    t0 = time.time()
299    rc = C.main()
300    took = time.time() - t0
301    print("nvfp4_local_pack: done in %.0f s; CSF scale tensors decoded %d, MXFP8 weights dequantized %d, PLE shards dropped %d"
302          % (took, stats.get("csf", 0), stats.get("mxfp8", 0), len(base.dropped_ple)))
303    if not a.dry_run:
304        out.with_suffix(".manifest.json").write_text(json.dumps({
305            "source": str(model), "csf_decoded": stats.get("csf", 0), "mxfp8_dequantized": stats.get("mxfp8", 0),
306            "ple_table": "written separately: nvfp4_local_pack.py ple", "mtp": "not written", "seconds": round(took, 1)},
307            indent=2) + "\n", encoding="utf-8")
308    return rc or 0
309
310
311# ------------------------------------------------------------------------------------------------- the PLE table
312GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6
313GGML_TYPE_I8 = 24
314ALIGN = 32
315
316
317def _gs(s):
318    b = s.encode("utf-8")
319    return struct.pack("<Q", len(b)) + b
320
321
322def interleave_rows(codes: np.ndarray, scales: np.ndarray) -> np.ndarray:
323    """[n, 80] codes + [n, 10] E4M3 scale bytes -> [n, 90]: the codes, then the scales."""
324    return np.concatenate([codes, scales], axis=1)
325
326
327def cmd_ple(a) -> int:
328    model, out = pathlib.Path(a.model), pathlib.Path(a.out)
329    ck = Checkpoint(model, partial_ok=True)           # the table is in six of the shards; a folder with only those works
330    shards = {}
331    for name in ck.meta:
332        if ".ngram_embedding.shard_" in name and name.endswith(".weight"):
333            shards[int(name.rsplit(".shard_", 1)[1].split(".")[0])] = name
334    if not shards or sorted(shards) != list(range(len(shards))):
335        sys.exit("the n-gram shards are missing or not numbered 0..N-1")
336    g = [k for k in ck.meta if k.endswith(".ngram_embedding.weight_scale_2")]
337    if len(g) != 1:
338        sys.exit("expected one ngram_embedding.weight_scale_2")
339    scale2 = float(ck.array(g[0], np.float32).reshape(-1)[0])
340    rows, dim = 0, None
341    for k in range(len(shards)):
342        n = shards[k]
343        r, c = ck.shape(n)
344        if ck.dtype(n) != "U8" or c != 80 or ck.shape(n[:-6] + "weight_scale") != [r, 10]:
345            sys.exit("%s: not an NVFP4 160-value row table" % n)
346        rows += r
347    print("%d shards, %d rows x 160, global scale %.9g, %.2f GB" % (len(shards), rows, scale2, rows * PLE_ROW_BYTES / 1e9), flush=True)
348    kvs = (_gs("general.architecture") + struct.pack("<I", GGUF_TYPE_STRING) + _gs("strata-ple")
349           + _gs("general.name") + struct.pack("<I", GGUF_TYPE_STRING) + _gs("PLE n-gram table, NVFP4 as shipped")
350           + _gs("strata.ple.format") + struct.pack("<I", GGUF_TYPE_STRING) + _gs("nvfp4x16")
351           + _gs("strata.ple.scale") + struct.pack("<I", GGUF_TYPE_F32) + struct.pack("<f", scale2)
352           + _gs("strata.ple.source") + struct.pack("<I", GGUF_TYPE_STRING) + _gs(model.name))
353    # the tensor is [90, rows] I8 so one row is 90 contiguous bytes; the engine reads it by the format key
354    head = b"GGUF" + struct.pack("<IQQ", 3, 1, 5) + kvs
355    head += _gs("per_layer_token_embd.weight") + struct.pack("<I", 2) + struct.pack("<QQ", PLE_ROW_BYTES, rows)
356    head += struct.pack("<I", GGML_TYPE_I8) + struct.pack("<Q", 0)
357    head += b"\0" * ((-len(head)) % ALIGN)
358    out.parent.mkdir(parents=True, exist_ok=True)
359    tmp = out.with_suffix(out.suffix + ".part")
360    CH = 1 << 20
361    with open(tmp, "wb") as w:
362        w.write(head)
363        for k in range(len(shards)):
364            n = shards[k]
365            codes = ck.array(n, np.uint8)
366            sc = ck.array(n[:-6] + "weight_scale", np.uint8)
367            for i in range(0, codes.shape[0], CH):
368                w.write(np.ascontiguousarray(interleave_rows(codes[i:i + CH], sc[i:i + CH])).tobytes())
369            if k % 16 == 15 or k == len(shards) - 1:
370                print("  %3d/%d shards" % (k + 1, len(shards)), flush=True)
371    if tmp.stat().st_size != len(head) + rows * PLE_ROW_BYTES:
372        sys.exit("size check failed")
373    tmp.replace(out)
374    print("wrote %s (%d rows x %d B)" % (out, rows, PLE_ROW_BYTES))
375    return 0
376
377
378# ------------------------------------------------------------------------------------------------------- the MTP head
379E2M1 = np.array([0, .5, 1, 1.5, 2, 3, 4, 6, -0., -.5, -1, -1.5, -2, -3, -4, -6], np.float32)
380
381
382def e4m3_table() -> np.ndarray:
383    x = np.arange(256)
384    s, e, m = x >> 7, (x >> 3) & 15, x & 7
385    f = np.where(e == 0, np.ldexp(m / 8.0, -6), np.ldexp(1.0 + m / 8.0, e.astype(np.int32) - 7))
386    f = np.where((e == 15) & (m == 7), np.nan, f)
387    return np.where(s == 1, -f, f).astype(np.float32)
388
389
390def nvfp4_dequant(codes: np.ndarray, scales_u8: np.ndarray, scale2: float) -> np.ndarray:
391    """ModelOpt NVFP4 -> float32: codes [R, K/2] (low nibble first), E4M3 scale bytes [R, K/16], one F32."""
392    R = codes.shape[0]
393    lo, hi = codes & 15, codes >> 4
394    v = E2M1[np.stack([lo, hi], axis=-1).reshape(R, -1)]
395    sc = e4m3_table()[scales_u8]
396    return (v.reshape(R, -1, 16) * sc[:, :, None] * np.float32(scale2)).reshape(R, -1)
397
398
399def f32_to_bf16_bits(x: np.ndarray) -> np.ndarray:
400    u = np.ascontiguousarray(x, np.float32).view(np.uint32)
401    r = u + 0x7FFF + ((u >> 16) & 1)               # round to nearest even
402    return (r >> 16).astype(np.uint16)
403
404
405def cmd_mtp(a) -> int:
406    """The MTP head in tools/mtp_fetch.py's folder form (raw BF16 files + mtp-manifest.json), so tools/mtp_pack.py and
407    tools/mtp_rt.py take it as they take Qwen's own: the 31 tensors, experts fused as gate_up_proj / down_proj."""
408    import hashlib
409    ck = Checkpoint(a.model, partial_ok=True)
410    out = pathlib.Path(a.out)
411    out.mkdir(parents=True, exist_ok=True)
412    manifest = []
413
414    def put(name, bits, shape):
415        fn = name.replace("/", "_") + ".bin"
416        data = np.ascontiguousarray(bits, np.uint16)
417        (out / fn).write_bytes(data.tobytes())
418        manifest.append({"name": name, "dtype": "BF16", "shape": list(shape), "file": fn,
419                         "sha256": hashlib.sha256(data.tobytes()).hexdigest()})
420
421    for name in sorted(k for k in ck.meta if k.startswith("mtp.") and ".experts." not in k):
422        if ck.dtype(name) != "BF16":
423            sys.exit("%s is %s, expected BF16" % (name, ck.dtype(name)))
424        put(name, ck.array(name, np.uint16), ck.shape(name))
425    n_exp = 512
426    for fused, parts in (("mtp.layers.0.mlp.experts.gate_up_proj", ("gate_proj", "up_proj")),
427                         ("mtp.layers.0.mlp.experts.down_proj", ("down_proj",))):
428        rows = [ck.shape("mtp.layers.0.mlp.experts.0.%s.weight" % p)[0] for p in parts]
429        cols = ck.shape("mtp.layers.0.mlp.experts.0.%s.weight" % parts[0])[1] * 2
430        shape = [n_exp, sum(rows), cols]
431        fn = fused + ".bin"
432        with open(out / fn, "wb") as f:
433            h = hashlib.sha256()
434            for e in range(n_exp):
435                mats = []
436                for p in parts:
437                    b = "mtp.layers.0.mlp.experts.%d.%s." % (e, p)
438                    mats.append(nvfp4_dequant(np.asarray(ck.array(b + "weight", np.uint8)),
439                                              np.asarray(ck.array(b + "weight_scale", np.uint8)),
440                                              float(ck.array(b + "weight_scale_2", np.float32).reshape(-1)[0])))
441                blob = f32_to_bf16_bits(np.concatenate(mats, axis=0)).tobytes()
442                f.write(blob)
443                h.update(blob)
444        manifest.append({"name": fused, "dtype": "BF16", "shape": shape, "file": fn, "sha256": h.hexdigest()})
445        print("  %s %s" % (fused, shape), flush=True)
446    (out / "mtp-manifest.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8")
447    print("wrote %d MTP tensors to %s" % (len(manifest), out))
448    return 0
449
450
451# ------------------------------------------------------------------------------------------------------ the slim GGUF
452def cmd_slim(a) -> int:
453    """Copy a converted GGUF without its routed experts (and their .scale / .input_scale tensors): the file the engine
454    reads the dense weights from (--native / --native-dense-gguf), ~9 GB instead of ~74 GB, once experts.bin is cut."""
455    from _paths import gguf_lib
456    gguf = gguf_lib()
457    GGUFReader, GGUFWriter, VT = gguf.GGUFReader, gguf.GGUFWriter, gguf.GGUFValueType
458    rd = GGUFReader(a.gguf)
459    arch = rd.fields["general.architecture"].contents()
460    w = GGUFWriter(a.out, arch)
461    for key, f in rd.fields.items():
462        if key.startswith("GGUF.") or key == "general.architecture":
463            continue
464        vt = f.types[0]
465        w.add_key_value(key, f.contents(), vt, sub_type=f.types[-1] if vt == VT.ARRAY else None)
466    kept = skipped = 0
467    for t in rd.tensors:
468        if "_exps." in t.name:
469            skipped += 1
470            continue
471        data = np.asarray(t.data)
472        qt = t.tensor_type
473        if qt in (gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16):
474            w.add_tensor(t.name, data)
475        else:                                   # raw bytes with the type: the quantized blocks (BF16 rides as uint16)
476            raw = np.ascontiguousarray(data).view(np.uint8)
477            w.add_tensor(t.name, raw, raw_dtype=qt, raw_shape=[int(x) for x in raw.shape])
478        kept += 1
479    w.write_header_to_file()
480    w.write_kv_data_to_file()
481    w.write_tensors_to_file()
482    w.close()
483    print("slim: %d tensors kept, %d expert tensors left out -> %s" % (kept, skipped, a.out))
484    return 0
485
486
487# ------------------------------------------------------------------------------------------- the pack, without a big GGUF
488def nvfp4_blocks(weight_u8: np.ndarray, scale_u8: np.ndarray) -> np.ndarray:
489    """ModelOpt NVFP4 rows -> ggml's block_nvfp4 rows: weight [R, K/2] (two E2M1 codes a byte, element 2i low), scale [R, K/16]
490    E4M3 bytes -> [R, K/64 * 36] bytes of super-blocks `[4 UE4M3 scales | 32 code bytes]`. The same bits as llama.cpp's
491    ModelBase._nvfp4_pack (the scale's sign bit is dropped; it is 0 in every scale of this checkpoint)."""
492    R, nb = scale_u8.shape
493    w = weight_u8.reshape(R, nb, 8)
494    vals = np.stack([w & 0x0F, w >> 4], axis=-1).reshape(R, nb, 16)
495    qs = (vals[:, :, :8] | (vals[:, :, 8:] << 4)).astype(np.uint8)
496    d = (scale_u8 & 0x7F).reshape(R, nb // 4, 4)
497    qs = qs.reshape(R, nb // 4, 32)
498    return np.concatenate([d, qs], axis=-1).reshape(R, (nb // 4) * 36)
499
500
501class _VTensor:
502    """A tensor info for iq_pack: an expert tensor (or its scale) whose bytes come from the checkpoint."""
503
504    def __init__(self, name, shape, type_id, type_name, nbytes):
505        self.name, self.shape, self.type_id, self.type_name, self.offset = name, shape, type_id, type_name, 0
506        self._n = nbytes
507
508    def expected_bytes(self):
509        return self._n
510
511
512class _VGguf:
513    data_start = 0
514
515
516def experts_from_checkpoint(model, ck: Checkpoint, n_layers: int = 48, n_exp: int = 512):
517    """Give an iq_pack.Model of the dense-only GGUF the routed experts of the checkpoint as virtual tensors."""
518    from _paths import gguf_lib
519    Q = gguf_lib().GGMLQuantizationType
520    src = next(iter(model.where.values()))[3]
521    cache: dict = {}
522    base = "model.language_model.layers.%d.mlp.experts.%d.%s_proj."
523
524    def layer_role(l, role):
525        key = (l, role)
526        if key not in cache:
527            cache.clear()
528            rows = []
529            for e in range(n_exp):
530                b = base % (l, e, role)
531                dec = csf_decode(np.asarray(ck.array(b + "weight_scale" + CSF_FIXED, np.uint8)),
532                                 np.asarray(ck.array(b + "weight_scale" + CSF_EXC, np.uint32)))
533                rows.append(nvfp4_blocks(np.asarray(ck.array(b + "weight", np.uint8)), dec).reshape(-1))
534            cache[key] = (np.stack(rows),)
535        return cache[key]
536
537    # shapes in ggml order (ne0 = K, ne1 = rows, ne2 = experts)
538    geo = {"gate": (2560, 640), "up": (2560, 640), "down": (640, 2560)}
539
540    class _Mem(_VGguf):                       # a tiny tensor held in memory: iq_pack reads it like any dense one
541        pass
542
543    for l in range(n_layers):
544        for role, (k, rows) in geo.items():
545            n = "blk.%d.ffn_%s_exps.weight" % (l, role)
546            vt = _VTensor(n, [k, rows, n_exp], Q.NVFP4.value, "NVFP4", n_exp * rows * (k // 64) * 36)
547            model.where[n] = (_VGguf(), vt, None, src)
548            # the per-expert F32 scales (weight_scale_2 -> .scale, input_scale -> .input_scale), as the converter writes them
549            for suffix, key in ((".scale", "weight_scale_2"), (".input_scale", "input_scale")):
550                vals = np.array([ck.array(base % (l, e, role) + key, np.float32).reshape(-1)[0] for e in range(n_exp)], np.float32)
551                sn = "blk.%d.ffn_%s_exps%s" % (l, role, suffix)
552                raw = vals.view(np.uint8)
553                model.where[sn] = (_Mem(), _VTensor(sn, [n_exp], Q.F32.value, "F32", n_exp * 4), raw, src)
554    orig_bytes = type(model).bytes
555
556    def bytes_(name):
557        if name.startswith("blk.") and "_exps." in name:
558            if not name.endswith(".weight"):                   # the small F32 scale tensors are in memory
559                return model.where[name][2]
560            l = int(name.split(".")[1]); role = name.split("ffn_")[1].split("_exps")[0]
561            return layer_role(l, role)[0].reshape(-1)
562        return orig_bytes(model, name)
563    model.bytes = bytes_
564    return model
565
566
567def cmd_pack(a) -> int:
568    """tools/iq_pack.py on the dense-only GGUF, with the experts read from the checkpoint: experts.bin, native_experts.txt,
569    dense.bin, index.txt and the tokenizer, with no 74 GB GGUF in between."""
570    import iq_pack
571    ck = Checkpoint(a.model)
572    orig_model = iq_pack.Model
573
574    class M(orig_model):
575        def __init__(self, first):
576            super().__init__(first)
577            experts_from_checkpoint(self, ck)
578    iq_pack.Model = M
579    sys.argv = ["iq_pack.py", "--gguf", a.dense_gguf, "--out", a.out, "--experts-bin"]
580    return iq_pack.main()
581
582
583# ------------------------------------------------------------------------------------------------------- prepare (setup)
584def cmd_prepare(a) -> int:
585    """Everything setup needs from the downloaded checkpoint, each step skipped when its mark is there:
586        <out>/ple-nvfp4.gguf   the n-gram table      <out>/dense.gguf   the dense weights (no experts)
587        <out>/pack/            index.txt, dense.bin, experts.bin, native_experts.txt, tokenizer/
588        <out>/mtp/rt/          the draft layer (a Q2_0 copy of NVIDIA's MTP experts)
589    The checkpoint is read, never changed; it can be deleted afterwards (the pack and the two GGUFs hold everything)."""
590    import subprocess
591    model, out = pathlib.Path(a.model), pathlib.Path(a.out)
592    if not all((out / m).is_file() for m in MARKS):
593        require_packages()                          # before the 20 minutes of the n-gram table, not after them (#3227)
594    out.mkdir(parents=True, exist_ok=True)
595    me = [sys.executable, str(pathlib.Path(__file__).resolve())]
596    tools = pathlib.Path(__file__).resolve().parent
597
598    def run(cmd):
599        r = subprocess.run(cmd)
600        if r.returncode:
601            sys.exit("prepare: %s failed (exit %d)" % (cmd[1] if len(cmd) > 1 else cmd[0], r.returncode))
602
603    def step(name, mark, fn):
604        if mark.exists():
605            print("prepare: %s already done" % name, flush=True)
606            return
607        print("prepare: %s ..." % name, flush=True)
608        t0 = time.time()
609        fn()
610        mark.write_text("done %.0f s\n" % (time.time() - t0))
611
612    step("the n-gram table", out / "ple-nvfp4.gguf.done",
613         lambda: run(me + ["ple", "--model", str(model), "--out", str(out / "ple-nvfp4.gguf")]))
614    step("the dense weights", out / "dense.gguf.done",
615         lambda: run(me + ["convert", "--dense-only", "--model", str(model), "--outfile", str(out / "dense.gguf")]))
616    step("the experts and the pack", out / "pack.done",           # (native_experts.txt is the pack's own marker, not ours)
617         lambda: run(me + ["pack", "--model", str(model), "--dense-gguf", str(out / "dense.gguf"), "--out", str(out / "pack")]))
618
619    mtp = out / "mtp"
620
621    def draft_layer():
622        src = mtp / "src"
623        run(me + ["mtp", "--model", str(model), "--out", str(src)])
624        run([sys.executable, str(tools / "mtp_pack.py"), "--src", str(src), "--experts", "q2_0",
625             "--out", str(mtp / "mtp-q2_0.gguf")])
626        run([sys.executable, str(tools / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(mtp / "rt")])
627        import shutil
628        shutil.rmtree(src, ignore_errors=True)
629    step("the draft layer", out / "draft.done", draft_layer)
630    print("prepare: done -> %s" % out)
631    return 0
632
633# ------------------------------------------------------------------------------------------------------ verifying
634def cmd_verify(a) -> int:
635    """Experts: decode the checkpoint (CSF + ModelOpt definition) and compare with tools/strata_quants.py's dequantization of the
636    GGUF's NVFP4 blocks times the scale tensor, bit for bit (zeros normalised: ggml has one zero)."""
637    import torch
638    import nvfp4_verify as V
639    from _paths import gguf_lib
640    gguf = gguf_lib()
641    GGUFReader, Q, quants = gguf.GGUFReader, gguf.GGMLQuantizationType, gguf.quants
642    ck = Checkpoint(a.model)
643    rd = GGUFReader(a.gguf)
644    T = {t.name: t for t in rd.tensors}
645    bad = 0
646    rng = np.random.default_rng(1)
647    layers = sorted({int(k.split(".layers.")[1].split(".")[0]) for k in ck.meta if ".mlp.experts." in k and k.startswith("model.language_model")})
648    for _ in range(a.experts):
649        L = int(rng.choice(layers)); e = int(rng.integers(0, 512))
650        for proj, gname in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):
651            b = "model.language_model.layers.%d.mlp.experts.%d.%s." % (L, e, proj)
652            w = torch.from_numpy(np.array(ck.array(b + "weight", np.uint8)))
653            sc = csf_decode(ck.array(b + "weight_scale" + CSF_FIXED, np.uint8), ck.array(b + "weight_scale" + CSF_EXC, np.uint32))
654            s = torch.from_numpy(sc).view(torch.float8_e4m3fn)
655            s2 = torch.from_numpy(np.array(ck.array(b + "weight_scale_2", np.float32))).reshape(())
656            ref = V.modelopt_dequant(w, s, s2)
657            t = T["blk.%d.%s.weight" % (L, gname)]
658            blob = np.asarray(t.data)                              # [512, rows, bytes] of NVFP4 blocks
659            got = quants.dequantize(np.ascontiguousarray(blob[e]), Q.NVFP4).astype(np.float32)
660            sct = T["blk.%d.%s.scale" % (L, gname)]
661            got = got * np.float32(np.asarray(sct.data)[e])
662            same = np.array_equal((ref + np.float32(0)).view(np.uint32), (got.reshape(ref.shape) + np.float32(0)).view(np.uint32))
663            print("  layer %2d expert %3d %-9s bitwise %s" % (L, e, proj, "OK" if same else "NO"), flush=True)
664            bad += not same
665    print("RESULT:", "lossless" if not bad else "MISMATCH")
666    return 1 if bad else 0
667
668
669def main() -> int:
670    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
671    sub = ap.add_subparsers(dest="cmd", required=True)
672    c = sub.add_parser("convert")
673    c.add_argument("--model", required=True)
674    c.add_argument("--outfile", required=True)
675    c.add_argument("--dry-run", action="store_true")
676    c.add_argument("--dense-only", action="store_true",
677                   help="leave the routed experts out: the GGUF that --native-dense-gguf reads (~9 GB) beside an experts.bin")
678    p = sub.add_parser("ple")
679    p.add_argument("--model", required=True)
680    p.add_argument("--out", required=True)
681    m = sub.add_parser("mtp")
682    m.add_argument("--model", required=True)
683    m.add_argument("--out", required=True)
684    pk = sub.add_parser("pack")
685    pk.add_argument("--model", required=True)
686    pk.add_argument("--dense-gguf", required=True, help="the output of `convert --dense-only` (or `slim`)")
687    pk.add_argument("--out", required=True)
688    pr = sub.add_parser("prepare")
689    pr.add_argument("--model", required=True)
690    pr.add_argument("--out", required=True)
691    sl = sub.add_parser("slim")
692    sl.add_argument("--gguf", required=True)
693    sl.add_argument("--out", required=True)
694    v = sub.add_parser("verify")
695    v.add_argument("--model", required=True)
696    v.add_argument("--gguf", required=True)
697    v.add_argument("--experts", type=int, default=4)
698    a = ap.parse_args()
699    return {"convert": cmd_convert, "ple": cmd_ple, "mtp": cmd_mtp, "slim": cmd_slim, "pack": cmd_pack, "prepare": cmd_prepare, "verify": cmd_verify}[a.cmd](a)
700
701
702if __name__ == "__main__":
703    raise SystemExit(main())