calib-corpora / tools /pool_import.py
worthant's picture
Restructure into a pool + per-model builds; add Muse-Glimmer-30B build
c9faf30 verified
Raw History Blame Contribute Delete
8.01 kB
"""Move the flat DeepSeek-era corpus into the pool, losslessly.
python tools/pool_import.py
`calib_train.txt` was written by `pipeline/build.py` as documents joined with a
blank line, in ascending `id` order, and `calib_train.manifest.jsonl` records
each document's character count in that same order. That makes the split exact
rather than heuristic: this script asserts the reconstruction re-joins to the
original file byte for byte and refuses to write anything if it does not.
Nothing at the repository root is modified. `calib_heldout.txt` is deliberately
*not* imported: it is a measurement split, and putting it in the pool would let
a later build calibrate on it.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import poollib as P
# legacy domain -> (pool category, subdirectory, shard name, synthetic)
DOMAIN_MAP = {
"code": ("code", "", "legacy-dsv4", False),
"graphics": ("graphics", "", "legacy-dsv4", False),
"structured": ("structured", "", "legacy-dsv4", False),
"longctx": ("longctx", "", "legacy-dsv4", False),
"general": ("multilingual", "", "legacy-dsv4-wikipedia", False),
"agentic": ("agentic", "synthetic", "legacy-dsv4-rendered", True),
"reasoning": ("reasoning", "synthetic", "legacy-dsv4-rendered", True),
"vocab_sweep": ("vocab_sweep", "synthetic", "legacy-dsv4-rendered", True),
}
# Domains whose text is DeepSeek chat markup. Kept for provenance, never
# usable as calibration for another model: the markup would tokenise as literal
# punctuation and calibrate nothing the target model ever emits.
DSV4_RENDERED = {"agentic", "reasoning"}
# vocab_sweep is a function of the tokenizer, not a corpus. The DeepSeek sweep
# is kept but a build regenerates its own.
TOKENIZER_BOUND = {"vocab_sweep"}
def split_flat(txt_path: str, manifest_path: str) -> list[tuple[dict, str]]:
recs = [json.loads(l) for l in open(manifest_path, encoding="utf-8") if l.strip()]
if recs != sorted(recs, key=lambda r: r["id"]):
raise SystemExit(f"{manifest_path}: not in ascending id order; "
"the offset reconstruction assumes pipeline/build.py ordering")
text = open(txt_path, encoding="utf-8").read()
out, pos = [], 0
for i, r in enumerate(recs):
doc = text[pos:pos + r["chars"]]
pos += r["chars"]
if i < len(recs) - 1:
if text[pos:pos + 2] != "\n\n":
raise SystemExit(f"{txt_path}: expected blank-line separator after "
f"document {i} ({r['id']}), found {text[pos:pos+4]!r}")
pos += 2
# the writer appended a single trailing newline
out.append((r, doc))
if text[pos:] != "\n":
raise SystemExit(f"{txt_path}: unexpected trailing bytes {text[pos:][:40]!r}")
rejoined = "\n\n".join(d for _, d in out) + "\n"
if rejoined != text:
raise SystemExit(f"{txt_path}: reconstruction is not byte-identical")
return out
def git_sha(repo_root: str) -> str:
try:
return subprocess.run(["git", "-C", repo_root, "rev-parse", "HEAD"],
capture_output=True, text=True, check=True).stdout.strip()
except Exception:
return "unknown"
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--repo", default=P.REPO_ROOT)
args = ap.parse_args()
root = args.repo
sha = git_sha(root)
train = split_flat(os.path.join(root, "calib_train.txt"),
os.path.join(root, "calib_train.manifest.jsonl"))
print(f"calib_train.txt -> {len(train)} documents, reconstruction byte-identical")
buckets: dict[str, list[P.Record]] = {}
unmapped: list[dict] = []
for r, text in train:
dom = r["domain"]
if dom not in DOMAIN_MAP:
unmapped.append(r)
continue
cat, sub, shard, synth = DOMAIN_MAP[dom]
render = "dsv4" if dom in DSV4_RENDERED else "text"
prov = {
"imported_from": "calib_train.txt",
"import_commit": sha,
"legacy_domain": dom,
"legacy_content_domain": r.get("content_domain", dom),
"legacy_id": r["id"],
"legacy_tokens_deepseek_v4": r.get("tokens", 0),
"legacy_split": r.get("split", "calib_train"),
}
if dom in DSV4_RENDERED:
prov["excluded_from_builds"] = (
"text is rendered in DeepSeek-V4 chat markup (<|DSML|...>, "
"<|User|>, <think>); those byte sequences are not special tokens "
"for any other tokenizer. The equivalent conversations are "
"regenerated structurally by tools/gen_agentic.py and "
"tools/gen_reasoning.py.")
if dom in TOKENIZER_BOUND:
prov["excluded_from_builds"] = (
"a vocabulary sweep is a function of the tokenizer it was built "
"for (DeepSeek-V4, 129,280 rows). tools/vocab_sweep.py "
"regenerates it for the target model.")
rec = P.Record(
category=cat, domain=dom, source=r["source"], license=r["license"],
license_url="", path=r["path"], lang=r["lang"], origin=r["origin"],
text=text, synthetic=synth, render=render, provenance=prov,
)
key = os.path.join(cat, sub, shard + ".jsonl") if sub else os.path.join(cat, shard + ".jsonl")
buckets.setdefault(key, []).append(rec)
if unmapped:
# Never dropped: anything without a mapping lands in pool/unsorted with
# the reason attached, so it can be triaged rather than lost.
recs = []
for r, text in train:
if r in unmapped:
recs.append(P.Record(
category="unsorted", domain=r["domain"], source=r["source"],
license=r["license"], path=r["path"], lang=r["lang"],
origin=r["origin"], text=text,
provenance={"imported_from": "calib_train.txt",
"import_commit": sha,
"reason": f"legacy domain {r['domain']!r} has no pool category"},
))
buckets["unsorted/legacy-dsv4-unmapped.jsonl"] = recs
total = 0
for key in sorted(buckets):
n = P.write_jsonl(os.path.join(P.POOL_ROOT, key), buckets[key])
chars = sum(len(r.text) for r in buckets[key])
total += n
print(f" pool/{key:52} {n:5} docs {chars:9,} chars")
print(f" {total} documents written, {len(unmapped)} unmapped")
# eval_neutral is copied into eval/neutral with provenance attached; the
# file at the repository root is left exactly as it is because the existing
# measurements are keyed to it.
ev = split_flat(os.path.join(root, "eval_neutral.txt"),
os.path.join(root, "eval_neutral.manifest.jsonl"))
erecs = [P.Record(
category="code", domain=r["domain"], source=r["source"],
license=r["license"], license_url="", path=r["path"], lang=r["lang"],
origin=r["origin"], text=text,
provenance={"imported_from": "eval_neutral.txt", "import_commit": sha,
"legacy_id": r["id"],
"note": "the flat file was renamed to eval/code/eval_code.txt and kept "
"byte-identical; measurement showed it is a code corpus, not "
"neutral prose. This is a categorised copy with provenance"},
) for r, text in ev]
n = P.write_jsonl(os.path.join(P.EVAL_ROOT, "code", "eval-code-legacy.jsonl"), erecs)
print(f"eval_neutral.txt -> eval/code/eval-code-legacy.jsonl {n} docs")
return 0
if __name__ == "__main__":
sys.exit(main())