File size: 11,669 Bytes
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b41d212
 
 
 
 
 
 
 
 
 
 
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b04d69
 
 
 
 
 
 
 
 
 
 
 
 
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b04d69
 
 
 
 
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b04d69
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b04d69
 
 
 
 
 
 
2c52e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python3
"""Aggregate the per-shard manifests of a mixed-Q2 V4.1 expert checkpoint into one manifest and README.

Reads ``plan.json`` plus every ``quant-*.safetensors.manifest.json`` written by
``v41_quant_experts.py convert`` and writes ``manifest.json`` and ``README.md`` into the
artifact directory. Pure aggregation over recorded digests: it does not read the weights.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from datetime import UTC, datetime
from pathlib import Path

LLAMA_COMMIT = "465e49b9cea78a68b9c244ffb48d0ee24a82873d"

README_TEMPLATE = """# DeepSeek-V4.1-Flash mixed-Q2 expert checkpoint ({stamp})

Quantised derivative of `{repo}` revision `{revision}`, produced on a 32-vCPU Runpod CPU pod
with the pinned llama.cpp ggml reference quantisers (`{llama_commit}`).

## What this is

The released checkpoint stores routed experts as MXFP4: 16 bytes of packed E2M1 values plus
one E8M0 scale byte per 32 weights (4.25 bits/weight). This artifact decodes exactly those
blocks and stores the 40 main-layer routed expert matrices as ggml blocks:

| projection | ggml type | bits/weight | tensors | weights |
|---|---|---:|---:|---:|
| gate/up `w1`, `w3` | IQ2_XXS | 2.0625 | {n_iq2} | {w_iq2} |
| down `w2` | Q2_K | 2.625 | {n_q2k} | {w_q2k} |

Block geometry (blocks run along the input/reduction dimension; ggml lists `ne` fastest-first, so
the same bytes are `ne=[in, out]`):

| tensor | logical out x in | ggml type | blocks/row | bytes/row | first block offset |
|---|---|---:|---:|---:|---|
| `w1.weight`, `w3.weight` | 2304 x 5120 | IQ2_XXS | 20 | 1320 | 0 |
| `w2.weight` | 5120 x 2304 | Q2_K | 9 | 756 | 0 |

Each expert tensor is a contiguous row-major sequence of those rows, so a carrier can read
20 blocks per row for gate/up and 9 per row for down with no extra permutation.

Total quantised payload **{quant_bytes} GB** for **{quant_weights}** routed weights
({bits} bits/weight average). With the non-routed weights held at native precision and the
Engram tables resident on the host, this fits one B200 180 GB or two RTX PRO 6000 96 GB cards.

Quantisation is **not imatrix-based**. No activation calibration was collected and no
importance matrix was consumed: IQ2_XXS was called with a constant unit importance vector
(the unweighted reference path). That is a deliberate recipe choice, not a calibrated one.

## Contents

| group | tensors | bytes |
|---|---:|---:|
{preserved_rows}

Every tensor other than the requantised experts is copied byte-for-byte from the source with
its original dtype string (`F8_E4M3`, `F8_E8M0`, `BF16`, `F32`, `I8`). Requantised expert
tensors keep their original names and are stored as `U8` block bytes; the per-tensor ggml
type, byte shape and block geometry are recorded in `manifest.json` and in each shard
manifest. MTP/DSpark expert tensors stay at native precision because DSpark stays disabled.

The four large Engram tensors (`layers.1.engram.embed.*`, `layers.14.engram.embed.*`,
{external_bytes} GB) are **not** copied: the release plan keeps Engram rows and scales native
on host storage. `manifest.json` records their source shard, byte range and source digest so a
loader can attach them from the immutable source revision. The 46,080 MXFP4 scale tensors of
the requantised experts ({dropped_bytes} GB) are dropped because IQ2_XXS and Q2_K carry their
own scales; their source digests are recorded as well.

## Layout

| output shard | source shard | tensors | bytes |
|---|---|---:|---:|
{shard_rows}
| **total** | | **{total_tensors}** | **{total_bytes} GB** |

`plan.json` holds the full tensor map (source shard, byte range, role, output shard, output
offset, output shape and type). Each `quant-*.safetensors` shard has a matching
`.manifest.json` with per-tensor source and output SHA-256 digests.

## Verification

```bash
python3 v41_quant_experts.py verify --out <this directory> --sample 0    # all digests
python3 v41_quant_audit.py --source <source dir> --out <this directory> \
    --json audit.json                                                    # fidelity sample
```

`audit.json` reports cosine similarity and relative RMS error of the dequantised blocks
against the MXFP4 source decode, computed with the independent gguf-py dequantisers from the
same pinned llama.cpp revision. With `--ggml-lib` it also recomputes the quantisation and
reports whether the stored digests are reproducible.

## Reproducibility

{environment_rows}

The ggml reference quantisers are deterministic for a given build and CPU target (repeated
recomputation reproduces the stored digests), but they are **not** bit-identical across SIMD
architectures: the ARM NEON and x86 AVX-512 paths select different codepoints in the IQ2_XXS
grid and can differ in Q2_K rounding. Re-running on a different architecture reproduces the
recipe, not these exact bytes. Reproduce or audit with the pinned commit above and the same
CPU class, or treat a differing digest as expected and compare fidelity through `audit.json`.

## Limits

This is a weights artifact. No V4.1 quantised runtime exists in the workspace, so nothing
here has been executed end to end and none of these numbers are behavioural results. The
blocks are the inputs a fused-kernel carrier needs; executing them requires new kernels for
IQ2_XXS/Q2_K experts plus host-resident Engram lookup.
"""


def human_gb(value: int) -> str:
    return f"{value / 1e9:,.2f}"


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--repo", default="deepseek-ai/DeepSeek-V4.1-Flash")
    parser.add_argument("--stamp", default=None)
    parser.add_argument("--check", action="store_true", help="fail if any planned shard is missing")
    parser.add_argument(
        "--environment",
        type=Path,
        help="JSON file describing the execution environment (CPU, SIMD, host, pod) to embed",
    )
    args = parser.parse_args()

    out = args.out
    plan = json.loads((out / "plan.json").read_text())
    role_by_name: dict[str, str] = {}
    type_by_name: dict[str, str] = {}
    for shard in plan["shards"]:
        for tensor in shard["tensors"]:
            role_by_name[tensor["name"]] = tensor["role"]
            if tensor["role"] == "quantised":
                type_by_name[tensor["name"]] = tensor["ggml_type"]

    per_type: dict[str, dict[str, int]] = {}
    per_role: dict[str, dict[str, int]] = {}
    shard_rows = []
    digest_index = []
    total_output_bytes = 0
    manifests = sorted(
        (json.loads(p.read_text()) for p in out.glob("quant-*.safetensors.manifest.json")),
        key=lambda m: m["output_shard"],
    )
    for manifest in manifests:
        shard_digest = hashlib.sha256()
        data_bytes = 0
        for tensor in sorted(manifest["tensors"], key=lambda t: t["name"]):
            role = role_by_name.get(tensor["name"], "unknown")
            per_role.setdefault(role, {"tensors": 0, "bytes": 0})
            per_role[role]["tensors"] += 1
            per_role[role]["bytes"] += tensor["output_bytes"]
            if role == "quantised":
                type_name = type_by_name[tensor["name"]]
                entry = per_type.setdefault(type_name, {"tensors": 0, "bytes": 0})
                entry["tensors"] += 1
                entry["bytes"] += tensor["output_bytes"]
            total_output_bytes += tensor["output_bytes"]
            data_bytes += tensor["output_bytes"]
            shard_digest.update(tensor["name"].encode())
            shard_digest.update(tensor["output_sha256"].encode())
        shard_rows.append(
            (
                manifest["output_shard"],
                manifest["source_shard"],
                len(manifest["tensors"]),
                manifest["file_bytes"],
            )
        )
        digest_index.append(
            {
                "output_shard": manifest["output_shard"],
                "source_shard": manifest["source_shard"],
                "tensors": len(manifest["tensors"]),
                "file_bytes": manifest["file_bytes"],
                "data_bytes": data_bytes,
                "digest_of_shard_digests": shard_digest.hexdigest(),
            }
        )

    expected = {s["output_shard"] for s in plan["shards"]}
    produced = {m["output_shard"] for m in manifests}
    missing = sorted(expected - produced)
    totals = plan["totals"]
    record = {
        "artifact": "DeepSeek-V4.1-Flash mixed-Q2 routed experts",
        "created_at_utc": args.stamp or datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "source": {
            "repo": args.repo,
            "revision": plan["source_revision"],
            "tensors": totals["source_tensors"],
        },
        "recipe": plan["recipe"],
        "importance": plan["importance"],
        "quantiser": f"llama.cpp ggml reference quantisers, commit {LLAMA_COMMIT}",
        "totals": {
            **totals,
            "shards_planned": len(expected),
            "shards_produced": len(produced),
            "missing_shards": missing,
            "unexpected_shards": sorted(produced - expected),
            "bytes_by_role": per_role,
            "quantised_bytes_by_type": per_type,
            "output_bytes_from_manifests": total_output_bytes,
        },
        "environment": json.loads(args.environment.read_text()) if args.environment else {},
        "external_native": plan["external"],
        "dropped_expert_scales": len(plan["dropped"]),
        "shards": digest_index,
    }
    (out / "manifest.json").write_text(json.dumps(record, indent=1) + "\n")

    role_rows = "\n".join(
        f"| {role} | {values['tensors']:,} | {human_gb(values['bytes'])} |"
        for role, values in sorted(per_role.items())
    )
    shard_rows_md = "\n".join(
        f"| `{name}` | `{source}` | {tensors:,} | {human_gb(file_bytes)} |"
        for name, source, tensors, file_bytes in shard_rows
    )
    iq2 = per_type.get("IQ2_XXS", {"tensors": 0, "bytes": 0})
    q2k = per_type.get("Q2_K", {"tensors": 0, "bytes": 0})
    readme = README_TEMPLATE.format(
        stamp=record["created_at_utc"],
        repo=args.repo,
        revision=plan["source_revision"],
        llama_commit=LLAMA_COMMIT,
        n_iq2=f"{iq2['tensors']:,}",
        n_q2k=f"{q2k['tensors']:,}",
        w_iq2=f"{(iq2['bytes'] // 66) * 256:,}",
        w_q2k=f"{(q2k['bytes'] // 84) * 256:,}",
        quant_bytes=human_gb(totals["quantised_bytes"]),
        quant_weights=f"{totals['quantised_logical_weights']:,}",
        bits=round(8 * totals["quantised_bytes"] / totals["quantised_logical_weights"], 4),
        preserved_rows=role_rows,
        external_bytes=human_gb(totals["external_bytes"]),
        dropped_bytes=human_gb(totals["dropped_bytes"]),
        environment_rows="\n".join(
            f"- {key}: `{value}`"
            for key, value in sorted(
                (json.loads(args.environment.read_text()) if args.environment else {}).items()
            )
        )
        or "- not recorded",
        shard_rows=shard_rows_md,
        total_tensors=sum(len(m["tensors"]) for m in manifests),
        total_bytes=human_gb(sum(m["file_bytes"] for m in manifests)),
    )
    (out / "README.md").write_text(readme)
    print(
        json.dumps({k: v for k, v in record["totals"].items() if not isinstance(v, dict)}, indent=1)
    )
    print(json.dumps({"by_role": per_role, "by_type": per_type}, indent=1))
    if missing:
        print(f"WARNING missing shards: {len(missing)}")
    return 1 if (missing and args.check) else 0


if __name__ == "__main__":
    raise SystemExit(main())