"""Build a per-model calibration set from the pool under a recipe. python tools/build.py --recipe recipes/muse-glimmer-30b.yaml Deterministic: same pool, same recipe, same seed, same bytes out. Ordering never depends on dictionary iteration or on the filesystem — documents are selected by a seeded shuffle of an id-sorted list, and the output is written in that order. Dialogue records are rendered here, not in the pool, so the special-token sequences in the output are this model's and nobody else's. Records marked `render: dsv4` or carrying `provenance.excluded_from_builds` are skipped with a reason; they stay in the pool as history. """ from __future__ import annotations import argparse import hashlib import json import os import random import subprocess import sys from collections import defaultdict HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import glimmer_fmt as G # default renderer; see FORMATTERS below # chat.format in the recipe -> renderer module. A recipe with no chat.format # builds exactly as it did before this was added. FORMATTERS = { "auto": "auto_fmt", "glimmer": "glimmer_fmt", "nemotron": "nemotron_fmt", } import poollib as P BUILD_VERSION = "build.py/1.0" DOC_SEP = "\n\n" def load_recipe(path: str) -> dict: try: import yaml with open(path, encoding="utf-8") as f: return yaml.safe_load(f) except ImportError: raise SystemExit("PyYAML is required to read recipes") def preflight(recipe: dict, repo: str) -> None: """Everything that can be wrong before a single token is read. Each check names the file it wanted, why, and the command that fixes it. A traceback from deep inside a tokenizer says none of that. """ problems = [] name = recipe.get("name") if not name: problems.append("the recipe has no `name`. It sets the build directory " "and selects the vocabulary sweep, so it is required.") chat = recipe.get("chat", {}) fmt = chat.get("format", "glimmer") if fmt not in FORMATTERS: problems.append( "chat.format is %r, which is not a renderer.\n" " known renderers: %s" % (fmt, ", ".join(sorted(FORMATTERS)))) if fmt == "auto": md = os.environ.get("FOUNDRY_MODEL_DIR", "/src") if not os.path.isdir(md): problems.append( "chat.format is `auto`, which renders through the model's own\n" " chat template, but there are no weights at %s.\n" " fix: export FOUNDRY_MODEL_DIR=/path/to/original/weights\n" " or download them: get_upstream" % md) tok_path = (recipe.get("model") or {}).get("tokenizer") if not tok_path: problems.append("model.tokenizer is not set in the recipe.") elif not os.path.isfile(tok_path): problems.append( "no tokenizer at %s\n" " Token budgets cannot be counted without it.\n" " fix: download the original weights (get_upstream), or point\n" " model.tokenizer at where they already are." % tok_path) pool_dir = os.path.join(repo, "pool") if not os.path.isdir(pool_dir): problems.append("no pool at %s" % pool_dir) elif not any(f.endswith(".jsonl") for _, _, fs in os.walk(pool_dir) for f in fs): problems.append( "the pool at %s holds no .jsonl files.\n" " A clone without git-lfs brings down pointer stubs.\n" " fix: git lfs pull, or run check_pool then fix_pool" % pool_dir) if problems: print("cannot build %s\n" % (recipe.get("name") or "this recipe"), file=sys.stderr) for i, p in enumerate(problems, 1): print(" %d. %s\n" % (i, p), file=sys.stderr) raise SystemExit(1) sweep = os.path.join(repo, "pool", "vocab_sweep", "synthetic", "%s.jsonl" % name) if not os.path.isfile(sweep): print("WARNING: no vocabulary sweep at %s" % sweep) print(" The vocab_sweep share will come out empty and the") print(" corpus will silently lose it. Generate it first:") print(" python tools/vocab_sweep.py --tokenizer %s --name %s" % (tok_path, name)) print() def usable(rec: dict) -> tuple[bool, str]: if rec.get("render") == "dsv4": return False, "render=dsv4 (DeepSeek markup, not portable)" why = (rec.get("provenance") or {}).get("excluded_from_builds") if why: return False, why return True, "" def make_renderer(recipe: dict): chat = recipe.get("chat", {}) fmt_name = chat.get("format", "glimmer") if fmt_name not in FORMATTERS: raise SystemExit("unknown chat.format %r; known: %s" % (fmt_name, ", ".join(sorted(FORMATTERS)))) import importlib F = importlib.import_module(FORMATTERS[fmt_name]) def render(rec: dict) -> str: prov = rec.get("provenance") or {} return F.render( rec["messages"], tools=rec.get("tools"), reasoning_strength=rec.get("reasoning_strength") or F.DEFAULT_REASONING, knowledge_cutoff=chat.get("knowledge_cutoff", F.DEFAULT_KNOWLEDGE_CUTOFF), current_date=chat.get("current_date"), namespace_descriptions=prov.get("namespace_descriptions"), add_generation_prompt=False, add_bos=chat.get("add_bos_per_document", True), ) return render def seeded_order(recs: list[dict], seed: int) -> list[dict]: """Shuffle reproducibly: sort by id, then permute with a seeded RNG.""" out = sorted(recs, key=lambda r: r["id"]) random.Random(seed).shuffle(out) return out def truncate_to_tokens(text: str, tok: P.TargetTokenizer, lo: int, hi: int) -> str | None: """A contiguous prefix of `text` between lo and hi tokens, cut on a line boundary so the document stays unbroken prose/code rather than ending mid-token.""" n = tok.count(text) if n < lo: return None if n <= hi: return text lines = text.split("\n") # one batched encode rather than a tokenizer call per line; the per-line # counts only have to be close enough to find the cut, and the result is # re-counted exactly below per_line = [len(ids) + 1 for ids in tok.encode_batch(lines)] keep, acc = [], 0 for ln, c in zip(lines, per_line): if acc + c > hi: break keep.append(ln) acc += c body = "\n".join(keep) n = tok.count(body) while n > hi and keep: keep = keep[:int(len(keep) * 0.95) or len(keep) - 1] body = "\n".join(keep) n = tok.count(body) return body if n >= lo else None def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--recipe", required=True) ap.add_argument("--out", default=None) ap.add_argument("--repo", default=P.REPO_ROOT) args = ap.parse_args() recipe = load_recipe(args.recipe) preflight(recipe, args.repo) name = recipe["name"] seed = int(recipe.get("seed", 0)) model = recipe["model"] out_dir = args.out or os.path.join(args.repo, "builds", name) os.makedirs(out_dir, exist_ok=True) tok = P.TargetTokenizer(model["tokenizer"], n_vocab=model.get("vocab_size")) render_chat = make_renderer(recipe) print(f"recipe {name} seed {seed} tokenizer {model['tokenizer']}") docs = P.load_pool() docs = [d for d in docs if not d["_shard"].startswith(os.path.join("pool", "_quarantine"))] # The vocabulary sweep is a function of the tokenizer, so it is sharded one # file per target model: pool/vocab_sweep/synthetic/.jsonl. # auto-select ours and drop every other model's sweep, so adding a model # never requires editing the recipes that already exist. SWEEP_DIR = "pool/vocab_sweep/synthetic/" mine = SWEEP_DIR + name + ".jsonl" before = len(docs) docs = [d for d in docs if not (lambda s: s.startswith(SWEEP_DIR) and s != mine)(d["_shard"].replace(os.sep, "/"))] dropped = before - len(docs) if dropped: print(f"vocab sweep: using {mine}, dropped {dropped:,} documents from other models' sweeps") # escape hatch for anything else that is model-specific shard_deny = (recipe.get("pool") or {}).get("shard_deny") or [] if shard_deny: before = len(docs) docs = [d for d in docs if not any(s in d["_shard"].replace(os.sep, "/") for s in shard_deny)] print(f"shard_deny: dropped {before - len(docs):,} documents from {len(shard_deny)} pattern(s)") skipped: dict[str, int] = defaultdict(int) pool: dict[str, list[dict]] = defaultdict(list) for d in docs: ok, why = usable(d) if not ok: skipped[why] += 1 continue pool[d["category"]].append(d) print(f"pool: {sum(len(v) for v in pool.values()):,} usable documents") for why, n in sorted(skipped.items(), key=lambda kv: -kv[1]): print(f" skipped {n:5} {why[:96]}") # ------------------------------------------------------------ calib_train spec = recipe["calib_train"] target = int(spec["target_tokens"]) shares = spec["shares"] total_share = sum(shares.values()) # No single document may dominate its slice. An amalgamated single-header or # a generated search index is one file, and left uncapped one of them takes # 30-60% of a category -- the imatrix then describes that file rather than # the category. Overridable per category because a longctx document is # supposed to be large. frac = dict(spec.get("max_doc_fraction") or {}) default_frac = float(frac.pop("default", 0.05)) chosen: list[tuple[dict, str, int]] = [] actual: dict[str, int] = {} oversize: list[tuple[str, str, str, int]] = [] print(f"\ncalib_train: target {target:,} tokens") for cat in sorted(shares): budget = int(target * shares[cat] / total_share) cap = int(budget * float(frac.get(cat, default_frac))) cands = seeded_order(pool.get(cat, []), seed + sum(map(ord, cat))) got, taken, skipped_big = 0, 0, 0 for d in cands: if got >= budget: break text = render_chat(d) if d.get("render") == "chat" else d["text"] n = tok.count(text) if n == 0: continue if n > cap: skipped_big += 1 oversize.append((cat, d["source"], d["path"], n)) continue chosen.append((d, text, n)) got += n taken += 1 actual[cat] = got avail = "" if got >= budget * 0.98 else " <-- pool exhausted" big = f" ({skipped_big} over the {cap:,}-token cap)" if skipped_big else "" print(f" {cat:13} target {budget:9,} got {got:9,} in {taken:5} docs{avail}{big}") if oversize: print(f"\n {len(oversize)} documents skipped as too large for their slice:") for cat, src, path, n in sorted(oversize, key=lambda t: -t[3])[:8]: print(f" {cat:12} {n:8,} tok {src[:16]:16} {path[:52]}") chosen = sorted(chosen, key=lambda t: (t[0]["category"], t[0]["id"])) random.Random(seed).shuffle(chosen) total_tokens = sum(n for _, _, n in chosen) body = DOC_SEP.join(t for _, t, _ in chosen) + "\n" train_path = os.path.join(out_dir, "calib_train.txt") with open(train_path, "w", encoding="utf-8") as f: f.write(body) print(f" wrote {train_path} {len(chosen):,} docs {total_tokens:,} tokens " f"({len(body):,} chars)") with open(os.path.join(out_dir, "calib_train.manifest.jsonl"), "w", encoding="utf-8") as f: for d, text, n in chosen: f.write(json.dumps({ "id": d["id"], "category": d["category"], "source": d["source"], "license": d["license"], "path": d["path"], "lang": d["lang"], "origin": d["origin"], "synthetic": d.get("synthetic", False), "render": d.get("render", "text"), "reasoning_strength": d.get("reasoning_strength", ""), "tokens": n, "chars": len(text), "shard": d["_shard"], }, ensure_ascii=False) + "\n") # ---------------------------------------------------------- calib_longctx lspec = recipe.get("calib_longctx") long_docs: list[tuple[dict, str, int]] = [] if lspec: lo, hi = int(lspec["doc_tokens_min"]), int(lspec["doc_tokens_max"]) ltarget = int(lspec["target_tokens"]) used = {d["id"] for d, _, _ in chosen} cands = seeded_order( [d for c in lspec.get("sources", ["longctx"]) for d in pool.get(c, []) if d["id"] not in used], seed + 977) got = 0 print(f"\ncalib_longctx: target {ltarget:,} tokens, " f"documents of {lo:,}-{hi:,} tokens, unbroken") for d in cands: if got >= ltarget: break text = render_chat(d) if d.get("render") == "chat" else d["text"] cut = truncate_to_tokens(text, tok, lo, hi) if cut is None: continue n = tok.count(cut) long_docs.append((d, cut, n)) got += n lpath = os.path.join(out_dir, "calib_longctx.txt") with open(lpath, "w", encoding="utf-8") as f: f.write(DOC_SEP.join(t for _, t, _ in long_docs) + "\n") lens = sorted(n for _, _, n in long_docs) print(f" wrote {lpath} {len(long_docs)} docs {got:,} tokens " f"min {lens[0]:,} max {lens[-1]:,}" if lens else " no documents qualified") with open(os.path.join(out_dir, "calib_longctx.manifest.jsonl"), "w", encoding="utf-8") as f: for d, text, n in long_docs: f.write(json.dumps({ "id": d["id"], "category": d["category"], "source": d["source"], "license": d["license"], "path": d["path"], "origin": d["origin"], "tokens": n, "chars": len(text), "shard": d["_shard"], }, ensure_ascii=False) + "\n") # ----------------------------------------------------------------- manifest shard_hashes = {} for p in P.shard_paths(P.POOL_ROOT): shard_hashes[os.path.relpath(p, args.repo)] = { "sha256": P.sha256_file(p), "bytes": os.path.getsize(p), "documents": sum(1 for _ in P.read_jsonl(p)), } lens = sorted(n for _, _, n in chosen) def pct(q: float) -> int: return lens[min(len(lens) - 1, int(q * len(lens)))] if lens else 0 by_cat_docs = defaultdict(int) by_cat_tok = defaultdict(int) synth_tok = 0 for d, _, n in chosen: by_cat_docs[d["category"]] += 1 by_cat_tok[d["category"]] += n if d.get("synthetic"): synth_tok += n manifest = { "build": name, "built_at": recipe.get("chat", {}).get("current_date"), "build_tool_version": BUILD_VERSION, "recipe": {"path": os.path.relpath(args.recipe, args.repo), "sha256": P.sha256_file(args.recipe), "seed": seed}, "model": model, "tokenizer": { "path": model["tokenizer"], "sha256": P.sha256_file(model["tokenizer"]), "rows": tok.n_vocab, "pre_tokenizer": model.get("pre_tokenizer", "llama4"), }, "llama_cpp": { "commit": model.get("llama_cpp_commit", ""), "note": "llama-imatrix must be given --parse-special or the chat " "markup in calib_train.txt is tokenised as literal text " "(parse_special defaults to false in that tool)", }, "calib_train": { "path": "calib_train.txt", "sha256": P.sha256_file(train_path), "bytes": os.path.getsize(train_path), "documents": len(chosen), "tokens": total_tokens, "target_tokens": target, "document_separator": DOC_SEP, "shares_requested_percent": {k: round(100.0 * v / total_share, 3) for k, v in sorted(shares.items())}, "shares_actual_percent": {k: round(100.0 * by_cat_tok[k] / total_tokens, 3) for k in sorted(by_cat_tok)}, "documents_by_category": dict(sorted(by_cat_docs.items())), "tokens_by_category": dict(sorted(by_cat_tok.items())), "synthetic_tokens": synth_tok, "synthetic_percent": round(100.0 * synth_tok / total_tokens, 3), "document_tokens": { "p50": pct(0.50), "p90": pct(0.90), "p95": pct(0.95), "p99": pct(0.99), "max": lens[-1] if lens else 0, "min": lens[0] if lens else 0, }, }, "pool_sources": dict(sorted(shard_hashes.items())), } if long_docs: llens = sorted(n for _, _, n in long_docs) manifest["calib_longctx"] = { "path": "calib_longctx.txt", "sha256": P.sha256_file(os.path.join(out_dir, "calib_longctx.txt")), "documents": len(long_docs), "tokens": sum(llens), "document_tokens": {"min": llens[0], "p50": llens[len(llens) // 2], "max": llens[-1]}, "contiguous": True, } with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8") as f: json.dump(manifest, f, indent=2, ensure_ascii=False) f.write("\n") print(f"\nwrote {os.path.join(out_dir, 'manifest.json')}") print(json.dumps(manifest["calib_train"]["shares_actual_percent"], indent=2)) return 0 if __name__ == "__main__": sys.exit(main())