Download v41_quant_finalize.py from apetersson/v41-quant-worker: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/apetersson/v41-quant-worker/resolve/main/v41_quant_finalize.py
- Command line
-
hf download hf://datasets/apetersson/v41-quant-worker/v41_quant_finalize.py
-
curl -L -o v41_quant_finalize.py https://huggingface.co/datasets/apetersson/v41-quant-worker/resolve/main/v41_quant_finalize.py
11.7 kB
| #!/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()) | |