#!/usr/bin/env python3 """Render README.md from the build's own metrics, so every number in the document comes from the artefacts rather than being transcribed by hand.""" from __future__ import annotations import json import os import sys from collections import defaultdict sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import quality from dsv4 import MODEL_ID, MODEL_REVISION, VOCAB_SIZE from sources import EVAL_REPOS, REPOS OUT = sys.argv[1] if len(sys.argv) > 1 else "out" DOMAIN_DESC = { "graphics": "three.js scenes/materials/loaders/post-processing, WebGL & WebGPU, GLSL & WGSL shaders, animation timelines, procedural generation, 3D maths", "agentic": "multi-turn tool-calling traces in the model's own DSML chat format: read/edit files, run commands, read output, recover from a failure", "code": "whole real source files — TypeScript, JavaScript, Python, Rust, C++ — plus configs, tests and build scripts", "longctx": "documents of 8k tokens and up (large real files, plus same-directory module bundles built to 8k-16k) to exercise the CSA/HCA compression path", "reasoning": "step-by-step worked problems with reasoning kept inside `` blocks: 3D maths, numerics, algorithms, graphics debugging", "general": "multilingual Wikipedia across 30 languages, plus markdown/tables/unicode from the previous revision", "structured": "JSON, YAML, TOML and SQL from the repositories, real `git log -p` diff patches, and the most regex-dense real sources", "vocab_sweep": "synthetic wordlists that carry the tail of the vocabulary; exists purely to cover the hash-routed layers", "eval_code": "held-apart repositories used only for eval_neutral", } def load(name): with open(os.path.join(OUT, name), encoding="utf-8") as f: return json.load(f) def manifest(split): rows = [] p = os.path.join(OUT, f"{split}.manifest.jsonl") if not os.path.isfile(p): return rows with open(p, encoding="utf-8") as f: for ln in f: rows.append(json.loads(ln)) return rows def fmt(n): return f"{n:,}" def domain_rows(rows): agg = defaultdict(lambda: {"docs": 0, "tokens": 0}) for r in rows: a = agg[r["domain"]] a["docs"] += 1 a["tokens"] += r["tokens"] total = sum(a["tokens"] for a in agg.values()) or 1 return agg, total def source_rows(rows): agg = defaultdict(lambda: {"docs": 0, "tokens": 0, "license": ""}) for r in rows: a = agg[r["source"]] a["docs"] += 1 a["tokens"] += r["tokens"] a["license"] = r["license"] total = sum(a["tokens"] for a in agg.values()) or 1 return agg, total def main(): m = load("metrics.json") train, held, ev = manifest("calib_train"), manifest("calib_heldout"), manifest("eval_neutral") allc = train + held meta = m["meta"] L = [] A = L.append A("---") A("license: other") A("language:\n- en\n- zh\n- ru\n- ja\n- ar\n- multilingual") A("tags:\n- imatrix\n- quantization\n- calibration\n- gguf\n- deepseek-v4\n- three.js\n- webgl") A("task_categories:\n- text-generation") A("---") A("") A("# calib-corpora — imatrix calibration corpus for DeepSeek-V4-Flash-0731") A("") A(f"Calibration text for building the importance matrix (imatrix) behind the dynamic GGUF quant line of " f"[`{MODEL_ID}`](https://huggingface.co/{MODEL_ID}).") A("") A("An imatrix is activation statistics collected by running the model over a corpus. The corpus decides which " "weights the model treats as important, and therefore which weights get more bits. **This corpus is " "deliberately not general web text** — it is weighted toward 3D/graphics code generation and agentic " "tool-calling, because that is what these quants are for.") A("") # ---------------------------------------------------------------- why A("## Why this composition") A("") A("Three properties of this model drive the design, all confirmed against its `config.json`:") A("") A(f"| property | value | consequence for calibration |") A(f"|---|---|---|") A(f"| `n_routed_experts` / `num_experts_per_tok` | 256 / 6 | Any single expert sees ~2.3% of tokens. A dense-model-sized corpus gives most experts too few samples to be meaningful, so the budget has to be an order of magnitude larger. |") A(f"| `num_hash_layers` | 3 | In the first three MoE layers the expert is chosen by a fixed hash of the **token id**, not by a learned gate. Coverage there depends on *vocabulary breadth*, not on volume — an unseen token id means a never-activated expert, no matter how much text you feed it. |") A(f"| `compress_ratios` | alternating 4/128 over 43 layers | The CSA/HCA compression path is barely exercised by short chunks, so a real long-document slice is required rather than concatenated short ones. |") A("") A("The vocabulary is the binding constraint. It has " f"{fmt(VOCAB_SIZE)} embedding rows, and by script the base vocabulary is 56.1% Latin, 27.6% CJK, " "4.1% Cyrillic, 2.4% Arabic, 1.0% Thai, 0.9% Hangul, 0.7% Hebrew, 0.5% Greek, 0.4% Hiragana, " "0.2% Devanagari. **Covering every Latin token in the vocabulary would still only reach 55.5%** of the " "embedding table, so a 60% coverage target is unreachable from English source code alone. That is why " "there is a 30-language Wikipedia slice and an explicit vocabulary sweep.") A("") # ---------------------------------------------------------------- files A("## Files") A("") A("| file | documents | tokens | purpose |") A("|---|---:|---:|---|") for split, rows, purpose in ( ("calib_train", train, "fed to `llama-imatrix`"), ("calib_heldout", held, "same distribution, **not** used for the imatrix — for measuring generalisation"), ("eval_neutral", ev, "disjoint neutral text and code, no overlap with calibration"), ): A(f"| `{split}.txt` | {fmt(len(rows))} | {fmt(sum(r['tokens'] for r in rows))} | {purpose} |") A("") A("Each `.txt` is flat UTF-8 with documents separated by a blank line, sharded at 500 MB (the corpus fits in " "one shard per split). Alongside each is a `*.manifest.jsonl` giving one record per document — id, domain, " "source, license, path, language, token count, character count — in the same order the documents appear in " "the `.txt`. The manifest exists because the flat format cannot express document boundaries unambiguously: " "many documents legitimately contain blank lines of their own.") A("") A("`legacy/` holds the previous revision of this dataset verbatim. Its content was re-split, deduplicated " "against the new material and carried forward into the build rather than discarded.") A("") # ---------------------------------------------------------------- mix A("## Composition") A("") A(f"Shares are of **tokens**, not documents, over `calib_train` + `calib_heldout` " f"({fmt(sum(r['tokens'] for r in allc))} tokens).") A("") agg, total = domain_rows(allc) A("| domain | target | actual | documents | tokens | what it is |") A("|---|---:|---:|---:|---:|---|") targets = {"graphics": "35%", "agentic": "15%", "code": "15%", "longctx": "10%", "reasoning": "10%", "general": "10%", "structured": "5%", "vocab_sweep": "—"} for dom in sorted(agg, key=lambda k: -agg[k]["tokens"]): a = agg[dom] A(f"| `{dom}` | {targets.get(dom,'—')} | {100*a['tokens']/total:.1f}% | {fmt(a['docs'])} | " f"{fmt(a['tokens'])} | {DOMAIN_DESC.get(dom,'')} |") A("") A("**Deviations from target are reported, not corrected.** Notes on the ones that matter:") A("") A("- `longctx` is defined by *length*, not by topic: any document of 8k tokens or more is counted here " "whatever its subject. Most of it is graphics code, so the effective graphics share is higher than the " "`graphics` row alone suggests. The origin breakdown is in the manifest under `content_domain`.") A("- `vocab_sweep` is over and above the seven requested domains. It is synthetic and is kept as its own " "domain so it can be filtered out via the manifest by anyone who wants to A/B an imatrix without it.") A("") # ---------------------------------------------------------------- sources A("### Sources and licences") A("") sagg, stotal = source_rows(allc) A("| source | licence | documents | tokens | share |") A("|---|---|---:|---:|---:|") for s in sorted(sagg, key=lambda k: -sagg[k]["tokens"]): a = sagg[s] A(f"| `{s}` | {a['license']} | {fmt(a['docs'])} | {fmt(a['tokens'])} | {100*a['tokens']/stotal:.1f}% |") A("") A("Every repository was shallow-cloned and had its `LICENSE` file read before use. " "**`patriciogonzalezvivo/thebookofshaders` was cloned, inspected and dropped**: its licence is " "all-rights-reserved (*\"You cannot host, display, distribute or share this Work in any form\"*), so none " "of it appears here despite being an obvious fit for the domain.") A("") A("Synthetic slices (`synthetic/agentic:*`, `synthetic/reasoning:*`, `synthetic/vocab-sweep`) are generated " "by the build scripts in `pipeline/`. The agentic traces embed **verbatim file content from the listed " "repositories** as tool results, so they inherit those repositories' licences; the surrounding dialogue is " "generated. See [Synthetic slices](#synthetic-slices).") A("") # ---------------------------------------------------------------- tokenizer A("## Tokenizer") A("") A(f"- Model: [`{MODEL_ID}`](https://huggingface.co/{MODEL_ID})") A(f"- Revision: `{MODEL_REVISION}`") A(f"- `vocab_size`: {fmt(VOCAB_SIZE)} (from `config.json`; this is the denominator for all coverage numbers " f"below — it is the size of the embedding table, and therefore the domain the layer-0-2 hash router " f"indexes into)") A("") A("Counting is done with special tokens **parsed, not escaped** — the equivalent of `llama-imatrix " "--parse-special`. `<|begin▁of▁sentence|>` becomes id 0 rather than a run of literal characters. This " "matters for the agentic and reasoning slices, which are full of them.") A("") A("> **The model ships no `chat_template`.** `tokenizer_config.json` has no such field and there is no " "`chat_template.jinja` in the repo, so `apply_chat_template()` does not work. The authoritative prompt " "format is the reference implementation at `encoding/encoding_dsv4.py` in the model repo, and this build " "imports it directly rather than reimplementing it. Its own test suite (`encoding/test_encoding_dsv4.py`, " "4 cases) passes against the pinned revision, and all chat-formatted documents here are produced by " "`encode_messages(...)` from that file.") A("") # ---------------------------------------------------------------- dedup d = meta["dedup"] A("## Deduplication") A("") A(f"- **Exact:** SHA-256 over the document with trailing intra-line whitespace normalised. " f"{fmt(d['exact'])} documents removed.") A(f"- **Near:** MinHash + LSH banding. {d['num_perm']} permutations, {quality.BANDS} bands × " f"{quality.ROWS} rows, shingles of {d['shingle_k']} whitespace-delimited tokens. " f"**Jaccard threshold {d['threshold']}** — the banding is chosen so the LSH S-curve is centred there " f"(({1}/{quality.BANDS})^(1/{quality.ROWS}) ≈ 0.80). Longest document in each cluster is kept. " f"{fmt(d['near'])} documents removed.") A(f"- **Combined drop rate: {d['rate_pct']:.2f}%** of {fmt(d['candidates'])} candidate documents.") A("") A("Two structural steps prevent duplication that document-level dedup cannot see:") A("") A("- three.js and webgl-fundamentals ship thousands of example pages sharing an identical ~600-byte HTML " "head. Bodies genuinely differ, so MinHash does not flag them. For most example pages only the " "`