calib-corpora / pipeline /make_readme.py
worthant's picture
Rebuild calibration corpus for DeepSeek-V4-Flash-0731 imatrix
bf3d2af verified
Raw
History Blame Contribute Delete
22.7 kB
#!/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 `<think>` 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 "
"`<script type=\"module\">` body is kept; a deterministic 1-in-7 sample keeps the whole page so the "
"scaffold stays represented.")
A("- Files used as tool results in agentic traces come from a reserved partition "
"(`sha1(path+repo) % 10 == 7`) that is excluded from the `code` and `graphics` slices, so no file content "
"is counted in two domains.")
A("")
# ---------------------------------------------------------------- splits
A("## Splits")
A("")
A(f"Split is by **document**, never by chunk, so no file has pieces on both sides.")
A("")
A(f"- `calib_train` / `calib_heldout`: key is `sha1(\"split:\" + document_id)`, heldout when "
f"`int(key, 16) % {10} == 0`. Deterministic and stable across rebuilds. Target 90/10; actual "
f"**{100*sum(r['tokens'] for r in train)/max(1,sum(r['tokens'] for r in allc)):.1f}% / "
f"{100*sum(r['tokens'] for r in held)/max(1,sum(r['tokens'] for r in allc)):.1f}%** by tokens "
f"(the split is by document count, so the token split drifts slightly).")
A(f"- `eval_neutral` is **not** a random slice of the same pool. It is drawn from sources held apart from "
f"calibration entirely: four repositories never used above "
f"({', '.join('`'+k+'`' for k in EVAL_REPOS)}), plus Wikipedia articles routed to eval by "
f"`sha1(\"wiki:\"+article_id)` before any calibration sampling. Documents already selected for calibration "
f"are additionally filtered out by id.")
A("")
# ---------------------------------------------------------------- metrics
A("## Measured metrics")
A("")
A("### Totals and vocabulary coverage")
A("")
A("Coverage is the share of the "
f"{fmt(VOCAB_SIZE)}-row embedding table observed at least N times. This is the direct proxy for "
"hash-routed expert coverage in layers 0-2.")
A("")
A("| split | documents | tokens | ids seen ≥1 | ≥10 | ≥100 |")
A("|---|---:|---:|---:|---:|---:|")
for split in ("calib_train", "calib_heldout", "eval_neutral"):
s = m[split]
c = s["coverage"]
A(f"| `{split}` | {fmt(s['docs'])} | {fmt(s['tokens'])} | "
f"{fmt(c['ge1'])} ({c['ge1_pct']:.1f}%) | {fmt(c['ge10'])} ({c['ge10_pct']:.1f}%) | "
f"{fmt(c['ge100'])} ({c['ge100_pct']:.1f}%) |")
A("")
A("### Document length in tokens")
A("")
A("| split | p50 | p90 | p99 |")
A("|---|---:|---:|---:|")
for split in ("calib_train", "calib_heldout", "eval_neutral"):
p = m[split]["percentiles"]
A(f"| `{split}` | {fmt(p['50'])} | {fmt(p['90'])} | {fmt(p['99'])} |")
A("")
A("### Acceptance criteria")
A("")
tr = m["calib_train"]
checks = [
("≥ 1,000,000 tokens in `calib_train`", tr["tokens"] >= 1_000_000, fmt(tr["tokens"])),
("≥ 60% of vocabulary seen at least once", tr["coverage"]["ge1_pct"] >= 60, f"{tr['coverage']['ge1_pct']:.1f}%"),
("p99 document length ≥ 8,000 tokens", int(tr["percentiles"]["99"]) >= 8000, fmt(int(tr["percentiles"]["99"]))),
]
A("| criterion | result | value |")
A("|---|---|---:|")
for name, ok, val in checks:
A(f"| {name} | {'**pass**' if ok else '**FAIL**'} | {val} |")
A("")
A("Per-domain tables, the full top-50 token frequency list and the raw numbers behind all of the above are in "
"`metrics.txt` and `metrics.json`.")
A("")
# ---------------------------------------------------------------- synthetic
A("## Synthetic slices")
A("")
A("Three slices are generated rather than harvested, because no public corpus exists in this model's prompt "
"format. What is real and what is not:")
A("")
A("**Agentic traces** (`pipeline/agentic.py`)")
A("")
A("- *Real*: every `read_file`, `grep` and `list_dir` result is computed from the actual cloned repository "
"at build time — verbatim file bytes, real regex matches with real line numbers, real directory listings. "
"`edit_file` anchors are exact unique substrings of the real file, so the edits would genuinely apply.")
A("- *Generated*: `run_command` outputs (vitest, pytest, cargo, cmake, eslint) are written to match each "
"tool's real output format; the dialogue and reasoning blocks are generated.")
A("- Every trace is multi-step and contains a failure followed by a recovery, since that is the shape of "
"real agent work.")
A("")
A("**Reasoning traces** (`pipeline/reasoning.py`, `pipeline/reasoning_extra.py`)")
A("")
A("- 22 topic generators across 3D maths, numerics, shading and graphics debugging. Every numeric result is "
"computed with numpy/`math` at build time, so the arithmetic inside the `<think>` blocks is correct by "
"construction rather than written by hand.")
A("")
A("**Vocabulary sweep** (`pipeline/vocab.py`)")
A("")
A("- Runs *after* the natural slices are measured, takes the set of ids still unseen, and emits compact "
"wordlists containing them. Each emitted document is re-tokenized and verified: an id only counts once it "
"has actually been observed in tokenizer output, because BPE re-merges adjacent pieces and naive "
"concatenation does not reproduce the tokens you started from.")
A("- This is the honest trade in this dataset. It buys hash-layer coverage that natural text cannot reach at "
"this budget, at the cost of a block of text that is off-distribution for the *learned* routers in layers "
"3-42. It is a single filterable domain in the manifest for exactly that reason.")
A("")
# ---------------------------------------------------------------- contam
c = meta["contamination"]
A("## Benchmark contamination")
A("")
scanned = c.get("scanned", d["candidates"])
n_rm = c["removed"]
A(f"**Checked explicitly.** Every candidate document — {fmt(scanned)} of them, calibration and eval "
f"alike — was scanned against {c['patterns']} regex families before selection. "
f"**{fmt(n_rm)} document{'' if n_rm == 1 else 's'} matched and "
f"{'was' if n_rm == 1 else 'were'} removed.**")
A("")
A("Families covered: " + ", ".join(sorted(quality.CONTAM_PATTERNS)) + ".")
A("")
A("This includes all of the sets named as disqualifying — Terminal Bench, SWE-bench, DeepSWE, GPQA, MMLU, "
"HumanEval, AIME — plus GSM8K, MATH, MBPP, LiveCodeBench, CodeContests, APPS, HellaSwag, WinoGrande, "
"TruthfulQA, BIG-Bench (including its canary GUID), BBH, IFEval, MuSR, AGIEval, C-Eval, CMMLU, ARC, "
"LAMBADA, WebArena, OSWorld, AgentBench, τ-bench, SWE-Lancer, Aider polyglot, MMMU, MathVista, MGSM and "
"DocVQA.")
A("")
A("Patterns are deliberately narrow so that ordinary code is not flagged — `DROP` only matches as "
"\"DROP benchmark\", `ARC` only as `ARC-Challenge`/`ARC-Easy`, and so on. The full pattern list, the hit "
"count and a quoted context window for every single hit are in `contamination_report.txt`, so the claim is "
"auditable rather than asserted.")
A("")
A("Two structural points also reduce exposure: no evaluation dataset was downloaded at any stage of this "
"build, and the reasoning slice is generated from parameterised derivations rather than sourced from any "
"problem set.")
A("")
# ---------------------------------------------------------------- repro
A("## Reproducing")
A("")
A("```bash")
A("# 1. tokenizer + the official prompt-format reference implementation")
A(f"hf download {MODEL_ID} \\")
A(f" --revision {MODEL_REVISION} \\")
A(" tokenizer.json tokenizer_config.json config.json \\")
A(" encoding/encoding_dsv4.py encoding/README.md \\")
A(" --local-dir ./tok")
A("")
A("# 2. source repositories (shallow clones, ~1.3 GB)")
A("bash clone.sh")
A("")
A("# 3. previous revision of this dataset, carried forward")
A("hf download AtomicChat/calib-corpora --repo-type dataset --local-dir ./existing")
A("")
A("# 4. build: collect -> generate -> dedup -> scan -> balance -> sweep -> split -> measure")
A("python pipeline/build.py --out ./out")
A("```")
A("")
A("Requires `transformers`, `tokenizers`, `datasets`, `huggingface_hub`, `numpy`. No GPU and no PyTorch — "
"tokenizer-only. The Wikipedia pull is cached to "
"`~/.cache/calib-build/wiki_cache.jsonl` after the first run; delete it to force a fresh stream.")
A("")
A("The build is deterministic given the same inputs: all sampling, splitting and generation is seeded "
"(`seed=20260731`) and every hash key is content-derived. The one source of drift between rebuilds is "
"upstream — the repositories are cloned at `--depth 1` from a moving `HEAD`, so a rebuild months later "
"picks up whatever those projects have merged since.")
A("")
# ---------------------------------------------------------------- caveats
A("## Known limitations")
A("")
A("- **Clone pinning.** Source repositories are shallow-cloned from `HEAD` rather than pinned to commit "
"SHAs, so exact byte reproduction of this revision is not possible after upstream moves. The manifests "
"record the exact path of every document, and licence and provenance are fixed regardless.")
A("- **The `vocab_sweep` trade-off** described above: it is off-distribution text bought deliberately for "
"hash-layer coverage.")
A("- **`run_command` outputs in agentic traces are generated**, not captured from real runs. File content in "
"those same traces is real.")
A("- **Reasoning is under target** at the measured share rather than the requested 10%; the generators "
"produce genuinely distinct documents and were not padded with near-duplicates to hit the number.")
A("- **Wikipedia is CC-BY-SA-4.0**, which is share-alike. The corpus as a whole is therefore mixed-licence, "
"not permissive — see the per-source table. Anything derived from `calib_train` inherits those terms.")
A("")
out = "\n".join(L) + "\n"
with open(os.path.join(OUT, "README.md"), "w", encoding="utf-8") as f:
f.write(out)
print(f"wrote {os.path.join(OUT,'README.md')} ({len(out):,} chars)")
if __name__ == "__main__":
main()