| """Build the three measurement corpora. |
| |
| python tools/build_eval.py --build builds/muse-glimmer-30b \ |
| --raw-eval /workspace/calib-build/raw_eval \ |
| --wiki /workspace/calib-build/wiki_cache.jsonl \ |
| --wikitext /workspace/calib-build/wikitext |
| |
| Three corpora, each sized so that llama-perplexity at ctx 4096 scores a useful |
| number of positions. That tool evaluates the second half of every context |
| window, so a corpus of N tokens yields floor(N/4096) chunks and half that many |
| times 4096 scored positions -- the corpus has to be twice the size of the |
| measurement you actually want. |
| |
| eval/neutral prose, no code, many scripts |
| eval/code source code; the previous eval_neutral.txt renamed and kept |
| byte-identical for comparability, plus an extension |
| eval/agentic conversations in the model's own markup |
| |
| Selection is by exclusion. A document enters a corpus only if it shares no |
| 13-gram with the calibration files, with wikitext, or with the eval corpora |
| already built. Ordering is fixed and the whole thing is seeded, so a rerun |
| produces the same bytes. |
| |
| One consequence worth stating plainly: llama-perplexity has no --parse-special |
| (the flag is registered for LLAMA_EXAMPLE_IMATRIX only). The special tokens |
| eval/agentic is required to contain will therefore be scored as their literal |
| characters, which is a different measurement from what the model sees at |
| inference. eval/neutral and eval/code are asserted free of those strings so |
| they are unaffected. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import copy |
| import glob |
| import json |
| import os |
| import random |
| import sys |
| import unicodedata |
| from collections import Counter, defaultdict |
|
|
| import numpy as np |
|
|
| HERE = os.path.dirname(os.path.abspath(__file__)) |
| sys.path.insert(0, HERE) |
| sys.path.insert(0, os.path.join(os.path.dirname(HERE), "pipeline")) |
|
|
| import glimmer_fmt as G |
| import poollib as P |
|
|
| SEED = 20260810 |
| NGRAM = 13 |
| CTX = 4096 |
| TARGET_LO, TARGET_HI = 350_000, 400_000 |
| DOC_SEP = "\n\n" |
| SPECIALS = ("<|start|>", "<|message|>", "<|eot|>", "<|eom|>", "<|patch|>", |
| "<|begin_of_text|>", "<|end_of_text|>", "<|video|>") |
| MAX_DUP_LINE_PERCENT = 2.0 |
|
|
| |
| |
| |
| EXTRA_EVAL_REPOS = { |
| "got": ("https://github.com/sindresorhus/got", "MIT"), |
| "jinja": ("https://github.com/pallets/jinja", "BSD-3-Clause"), |
| "rust-regex": ("https://github.com/rust-lang/regex", "MIT OR Apache-2.0"), |
| "googletest": ("https://github.com/google/googletest", "BSD-3-Clause"), |
| "black": ("https://github.com/psf/black", "MIT"), |
| "express": ("https://github.com/expressjs/express", "MIT"), |
| "tokio-bytes": ("https://github.com/tokio-rs/bytes", "MIT"), |
| } |
|
|
| |
| SCRIPTS = [ |
| ("Latin", [(0x0041, 0x024F), (0x1E00, 0x1EFF)]), |
| ("Cyrillic", [(0x0400, 0x04FF), (0x0500, 0x052F)]), |
| ("Greek", [(0x0370, 0x03FF), (0x1F00, 0x1FFF)]), |
| ("Arabic", [(0x0600, 0x06FF), (0x0750, 0x077F), (0xFB50, 0xFDFF)]), |
| ("Hebrew", [(0x0590, 0x05FF)]), |
| ("Armenian", [(0x0530, 0x058F)]), |
| ("Georgian", [(0x10A0, 0x10FF), (0x1C90, 0x1CBF)]), |
| ("Devanagari", [(0x0900, 0x097F)]), |
| ("Bengali", [(0x0980, 0x09FF)]), |
| ("Tamil", [(0x0B80, 0x0BFF)]), |
| ("Thai", [(0x0E00, 0x0E7F)]), |
| ("Myanmar", [(0x1000, 0x109F)]), |
| ("Ethiopic", [(0x1200, 0x137F)]), |
| ("Han", [(0x4E00, 0x9FFF), (0x3400, 0x4DBF), (0xF900, 0xFAFF)]), |
| ("Hiragana", [(0x3040, 0x309F)]), |
| ("Katakana", [(0x30A0, 0x30FF)]), |
| ("Hangul", [(0xAC00, 0xD7AF), (0x1100, 0x11FF), (0x3130, 0x318F)]), |
| ] |
|
|
|
|
| def script_of(ch: str) -> str | None: |
| cp = ord(ch) |
| if not ch.isalpha(): |
| return None |
| for name, ranges in SCRIPTS: |
| for lo, hi in ranges: |
| if lo <= cp <= hi: |
| return name |
| return "Other" |
|
|
|
|
| def script_mix(text: str) -> dict: |
| c = Counter() |
| for ch in text: |
| s = script_of(ch) |
| if s: |
| c[s] += 1 |
| tot = sum(c.values()) or 1 |
| return {k: round(100.0 * v / tot, 2) for k, v in c.most_common()} |
|
|
|
|
| def duplicate_line_share(text: str, min_len: int = 0, |
| ignore_lines: set | None = None) -> tuple[float, list]: |
| lines = [ln for ln in text.split("\n") if len(ln.strip()) >= min_len and ln.strip()] |
| if ignore_lines: |
| lines = [ln for ln in lines if ln not in ignore_lines] |
| if not lines: |
| return 0.0, [] |
| c = Counter(lines) |
| dup = sum(n - 1 for n in c.values() if n > 1) |
| return 100.0 * dup / len(lines), c.most_common(8) |
|
|
|
|
| class Excluder: |
| """Everything a new eval document must not overlap. |
| |
| Two tiers on purpose. The static side holds wikitext plus the calibration |
| files -- about a hundred million 13-grams -- and is sorted once. The |
| dynamic side holds what has been accepted so far and grows one document at |
| a time; keeping it a plain set avoids re-sorting the hundred million on |
| every acceptance, which is the difference between seconds and hours. |
| """ |
|
|
| def __init__(self, ignore: set[int] | None = None) -> None: |
| self.static = P.ShingleIndex(NGRAM) |
| self.dynamic: set[int] = set() |
| self.sources: list[str] = [] |
| |
| |
| |
| |
| |
| self.ignore = ignore or set() |
|
|
| def add_static(self, text: str | None, label: str, |
| hashes: np.ndarray | None = None) -> None: |
| if hashes is not None: |
| self.static.add_hashes(hashes) |
| else: |
| self.static.add(text) |
| self.sources.append(label) |
|
|
| def freeze(self) -> "Excluder": |
| self.static.finalise() |
| return self |
|
|
| def add_text(self, text: str, label: str) -> None: |
| self.dynamic.update(int(x) for x in P.shingles(text, NGRAM) |
| if int(x) not in self.ignore) |
|
|
| def overlap(self, text: str) -> int: |
| h = P.shingles(text, NGRAM) |
| if h.size == 0: |
| return 0 |
| if self.ignore: |
| h = np.array([x for x in h.tolist() if x not in self.ignore], |
| dtype=np.uint64) |
| if h.size == 0: |
| return 0 |
| n = int(self.static.contains(h).sum()) |
| if n: |
| return n |
| if self.dynamic: |
| n += sum(1 for x in h.tolist() if x in self.dynamic) |
| return n |
|
|
|
|
| def take_until(cands, excl: Excluder, tok, lo: int, hi: int, label: str, |
| max_dup_percent: float | None = None, |
| allow_intra_repeat: bool = False): |
| """Greedily accept documents that overlap nothing already accepted. |
| |
| `max_dup_percent` additionally rejects a document whose lines are mostly |
| already in the corpus, which is how the duplicate-line ceiling is met |
| without editing anybody's text. |
| |
| `allow_intra_repeat` says the zero-overlap rule applies only *between* |
| corpora, not inside one. Generated conversations necessarily repeat their |
| own framing, and enforcing zero within a corpus rejected 613 of 615 |
| candidates; repetition inside a corpus is what the duplicate-line ceiling |
| is for. |
| """ |
| out, total, rejected, dup_rejected = [], 0, 0, 0 |
| seen_lines: Counter = Counter() |
| n_lines = n_dup = 0 |
| for d in cands: |
| if total >= lo: |
| break |
| text = d["text"] |
| if excl.overlap(text): |
| rejected += 1 |
| continue |
| n = tok.count(text) |
| if n == 0 or total + n > hi: |
| continue |
| if max_dup_percent is not None: |
| lines = [ln for ln in text.split("\n") if ln.strip()] |
| add_dup = sum(1 for ln in lines if seen_lines[ln] > 0) |
| if n_lines + len(lines) and \ |
| 100.0 * (n_dup + add_dup) / (n_lines + len(lines)) > max_dup_percent: |
| dup_rejected += 1 |
| continue |
| seen_lines.update(lines) |
| n_lines += len(lines) |
| n_dup += add_dup |
| out.append((d, text, n)) |
| total += n |
| if not allow_intra_repeat: |
| excl.add_text(text, label) |
| if allow_intra_repeat: |
| for _, text, _ in out: |
| excl.add_text(text, label) |
| extra = f", {dup_rejected} rejected for duplicate lines" if dup_rejected else "" |
| print(f" {len(out)} documents accepted, {rejected} rejected for overlap" |
| f"{extra}, {total:,} tokens") |
| return out, total |
|
|
|
|
| def write_corpus(path: str, docs, manifest_path: str, extra_head: str = "") -> str: |
| body = extra_head + DOC_SEP.join(t for _, t, _ in docs) + "\n" |
| os.makedirs(os.path.dirname(path), exist_ok=True) |
| with open(path, "w", encoding="utf-8") as f: |
| f.write(body) |
| with open(manifest_path, "w", encoding="utf-8") as f: |
| for d, text, n in docs: |
| f.write(json.dumps({ |
| "id": d.get("id", ""), "source": d["source"], "path": d["path"], |
| "license": d.get("license", ""), "lang": d.get("lang", ""), |
| "origin": d.get("origin", ""), "tokens": n, "chars": len(text), |
| }, ensure_ascii=False) + "\n") |
| return body |
|
|
|
|
| def measure(name: str, path: str, tok, must_have_specials: bool, |
| template_lines: set | None = None) -> dict: |
| text = open(path, encoding="utf-8").read() |
| ids = tok.encode(text) |
| chunks = len(ids) // CTX |
| scored = chunks * (CTX // 2) |
| c = Counter(ids) |
| dup, top = duplicate_line_share(text) |
| dup_sig, _ = duplicate_line_share(text, min_len=12) |
| dup_notmpl, _ = duplicate_line_share(text, ignore_lines=template_lines) |
| present = [s for s in SPECIALS if s in text] |
| ok_specials = bool(present) if must_have_specials else not present |
| out = { |
| "corpus": name, "path": os.path.relpath(path, P.REPO_ROOT), |
| "tokens": len(ids), "chars": len(text), |
| "chunks_at_ctx_4096": chunks, "scored_positions": scored, |
| "vocab_rows": tok.n_vocab, |
| "vocab_covered": len(c), |
| "vocab_covered_percent": round(100.0 * len(c) / tok.n_vocab, 3), |
| "duplicate_line_percent": round(dup, 2), |
| "duplicate_line_percent_len_ge_12": round(dup_sig, 2), |
| "duplicate_line_percent_excluding_chat_template": round(dup_notmpl, 2), |
| "top_repeated_lines": [[l, n] for l, n in top], |
| "script_mix_percent": script_mix(text), |
| "special_tokens_present": present, |
| "special_token_rule_ok": ok_specials, |
| } |
| print(f"\n--- {name} ---") |
| print(f" {len(ids):,} tokens, {chunks} chunks at ctx {CTX}, " |
| f"{scored:,} scored positions") |
| print(f" vocabulary: {len(c):,} of {tok.n_vocab:,} rows " |
| f"({100.0*len(c)/tok.n_vocab:.2f}%)") |
| print(f" duplicate lines: {dup:.2f}% (>=12 chars: {dup_sig:.2f}%" |
| f"{f', excl. chat template: {dup_notmpl:.2f}%' if template_lines else ''})") |
| print(f" scripts: {json.dumps(out['script_mix_percent'])[:150]}") |
| print(f" special tokens {'present' if present else 'absent'} " |
| f"-> rule {'ok' if ok_specials else 'VIOLATED'}") |
| return out |
|
|
|
|
| def main() -> int: |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--build", required=True) |
| ap.add_argument("--raw-eval", required=True) |
| ap.add_argument("--wiki", required=True) |
| ap.add_argument("--wikitext", required=True) |
| ap.add_argument("--tokenizer", required=True) |
| ap.add_argument("--repo", default=P.REPO_ROOT) |
| args = ap.parse_args() |
|
|
| rng = random.Random(SEED) |
| tok = P.TargetTokenizer(args.tokenizer) |
| eval_root = os.path.join(args.repo, "eval") |
|
|
| |
| legacy_src = os.path.join(args.repo, "eval_neutral.txt") |
| legacy_dst = os.path.join(eval_root, "code", "eval_code.txt") |
| os.makedirs(os.path.dirname(legacy_dst), exist_ok=True) |
| if os.path.exists(legacy_src) and not os.path.exists(legacy_dst): |
| with open(legacy_src, encoding="utf-8") as f: |
| legacy_text = f.read() |
| with open(legacy_dst, "w", encoding="utf-8") as f: |
| f.write(legacy_text) |
| print(f"eval_neutral.txt -> eval/code/eval_code.txt " |
| f"({len(legacy_text):,} chars, byte-identical)") |
| else: |
| legacy_text = open(legacy_dst, encoding="utf-8").read() |
| print(f" legacy corpus: {tok.count(legacy_text):,} tokens under this tokenizer") |
|
|
| |
| print("\nbuilding exclusion index") |
| dummy = [{"type": "function", "function": { |
| "name": "ns.fn", "description": "d", |
| "parameters": {"type": "object", "properties": {}}}}] |
| |
| |
| |
| |
| |
| scaffolds = [G.render([{"role": "user", "content": ""}, |
| {"role": "assistant", "content": ""}], |
| tools=t, reasoning_strength=rs, |
| knowledge_cutoff="2026-01-04", current_date="2026-08-10") |
| for rs in G.REASONING_STRENGTHS for t in (dummy, None)] |
| scaffold = scaffolds[0] |
| template_grams = {int(x) for sc in scaffolds for x in P.shingles(sc, NGRAM)} |
| print(f" {len(template_grams)} {NGRAM}-grams belong to the chat template " |
| f"itself and are excluded from every comparison") |
| forbidden = Excluder(ignore=template_grams) |
| for f in ("calib_train.txt", "calib_longctx.txt"): |
| p = os.path.join(args.build, f) |
| if os.path.exists(p): |
| forbidden.add_static(open(p, encoding="utf-8").read(), f) |
| print(f" + {f}") |
| import pyarrow.parquet as pq |
| wt_parts = [] |
| for f in sorted(glob.glob(os.path.join(args.wikitext, "**", "*.parquet"), |
| recursive=True)): |
| wt_parts.append(P.shingles("\n".join(pq.read_table(f).column("text").to_pylist()), |
| NGRAM)) |
| forbidden.add_static(None, "wikitext-103-raw-v1", |
| hashes=np.unique(np.concatenate(wt_parts))) |
| del wt_parts |
| print(" + wikitext-103-raw-v1") |
|
|
| import sources as S |
| results = [] |
|
|
| |
| |
| |
| print("\n[eval/code] extending") |
| forbidden.add_static(legacy_text, "eval/code/eval_code.txt") |
| forbidden.freeze() |
| print(f" {len(forbidden.static):,} distinct {NGRAM}-grams in the static " |
| f"exclusion set ({', '.join(forbidden.sources)})") |
| legacy_paths = {(r["source"], r["path"]) |
| for r in P.read_jsonl(os.path.join(args.repo, |
| "eval_neutral.manifest.jsonl"))} |
| code_docs, agentic_pool = [], [] |
| all_eval_repos = {r: (u, l) for r, (u, l, _) in S.EVAL_REPOS.items()} |
| all_eval_repos.update(EXTRA_EVAL_REPOS) |
| |
| |
| |
| GROUNDING_REPOS = {"rust-regex", "googletest", "black", "tokio-bytes"} |
| for repo in sorted(all_eval_repos): |
| url, lic = all_eval_repos[repo] |
| root = os.path.join(args.raw_eval, repo) |
| if not os.path.isdir(root): |
| print(f" ! missing eval clone: {repo}") |
| continue |
| for rel, lang, text in sorted(S.walk_repo(root, repo), key=lambda t: t[0]): |
| if (repo, rel) in legacy_paths: |
| continue |
| d = {"id": P.make_id(repo, rel, text), "source": repo, "path": rel, |
| "license": lic, "lang": lang, "origin": "repo_file", "text": text, |
| "upstream": url} |
| (agentic_pool if repo in GROUNDING_REPOS else code_docs).append(d) |
| code_docs.sort(key=lambda d: (d["source"], d["path"])) |
| rng.shuffle(code_docs) |
| need_lo = max(0, TARGET_LO - tok.count(legacy_text)) |
| need_hi = max(0, TARGET_HI - tok.count(legacy_text)) |
| ext, ext_tok = take_until(code_docs, forbidden, tok, need_lo, need_hi, "eval/code") |
| write_corpus(os.path.join(eval_root, "code", "eval_code_ext.txt"), ext, |
| os.path.join(eval_root, "code", "eval_code_ext.manifest.jsonl")) |
| with open(os.path.join(eval_root, "code", "eval_code_full.txt"), "w", |
| encoding="utf-8") as f: |
| f.write(legacy_text.rstrip("\n") + DOC_SEP + |
| DOC_SEP.join(t for _, t, _ in ext) + "\n") |
| results.append(measure("eval/code", os.path.join(eval_root, "code", |
| "eval_code_full.txt"), tok, False)) |
|
|
| |
| print("\n[eval/neutral] multilingual prose") |
| wiki = [json.loads(l) for l in open(args.wiki, encoding="utf-8")] |
| by_lang = defaultdict(list) |
| for r in wiki: |
| by_lang[r["lang"]].append(r) |
| |
| |
| NONLATIN = {"zh", "ja", "ko", "ru", "uk", "ar", "fa", "he", "el", "hi", "bn", |
| "ta", "ka", "hy", "my", "am", "th"} |
| order = sorted(by_lang, key=lambda l: (l not in NONLATIN, l)) |
| for l in order: |
| by_lang[l].sort(key=lambda r: r["id"]) |
| interleaved = [] |
| i = 0 |
| while any(by_lang[l][i:i + 1] for l in order): |
| for l in order: |
| if i < len(by_lang[l]): |
| r = by_lang[l][i] |
| interleaved.append({"id": r["id"], "source": r["source"], |
| "path": r["path"], "license": r.get("license", "CC-BY-SA-4.0"), |
| "lang": r["lang"], "origin": "wikipedia", |
| "text": r["text"]}) |
| i += 1 |
| neutral, n_tok = take_until(interleaved, forbidden, tok, TARGET_LO, TARGET_HI, |
| "eval/neutral", max_dup_percent=MAX_DUP_LINE_PERCENT) |
| write_corpus(os.path.join(eval_root, "neutral", "eval_neutral.txt"), neutral, |
| os.path.join(eval_root, "neutral", "eval_neutral.manifest.jsonl")) |
| r = measure("eval/neutral", os.path.join(eval_root, "neutral", "eval_neutral.txt"), |
| tok, False) |
| r["languages"] = len({d["lang"] for d, _, _ in neutral}) |
| print(f" languages: {r['languages']}") |
| results.append(r) |
|
|
| |
| print("\n[eval/agentic] native markup") |
| import gen_agentic_eval as GAE |
| convs = GAE.build(120, SEED + 7) |
| convs += GAE.build_grounded(agentic_pool, min(len(agentic_pool), 900), SEED + 11) |
| print(f" {len(convs)} candidate conversations " |
| f"({len(agentic_pool)} held-out files available for grounding)") |
| ag_docs = [] |
| for c in convs: |
| text = G.render(c["messages"], tools=c["tools"], |
| reasoning_strength=c["reasoning_strength"], |
| knowledge_cutoff="2026-01-04", current_date="2026-08-10", |
| namespace_descriptions=GAE.NS_DESCRIPTIONS, add_bos=True) |
| ag_docs.append({ |
| "id": P.make_id("eval-agentic", f"{c['scenario']}/{c['index']}", text), |
| "source": f"synthetic/eval-agentic:{c['scenario']}", |
| "path": f"eval_agentic/{c['scenario']}/{c['index']:04d}", |
| "license": "CC0-1.0 (generated; quoted file excerpts keep their upstream licence)", |
| "lang": "chat", "origin": "synth_agentic_eval", "text": text, |
| "grounded_in": c.get("grounded_in", ""), |
| "reasoning_strength": c["reasoning_strength"]}) |
| agentic, a_tok = take_until(ag_docs, forbidden, tok, TARGET_LO, TARGET_HI, |
| "eval/agentic", allow_intra_repeat=True) |
| write_corpus(os.path.join(eval_root, "agentic", "eval_agentic.txt"), agentic, |
| os.path.join(eval_root, "agentic", "eval_agentic.manifest.jsonl")) |
| tmpl_lines = {ln for sc in scaffolds for ln in sc.split("\n") if ln.strip()} |
| r = measure("eval/agentic", |
| os.path.join(eval_root, "agentic", "eval_agentic.txt"), tok, True, |
| template_lines=tmpl_lines) |
| r["reasoning_strengths"] = dict(Counter(d.get("reasoning_strength", "") |
| for d, _, _ in agentic)) |
| print(f" reasoning strengths: {r['reasoning_strengths']}") |
| results.append(r) |
|
|
| |
| print("\n[cross-checks] 13-gram intersections") |
| files = { |
| "calib_train": os.path.join(args.build, "calib_train.txt"), |
| "calib_longctx": os.path.join(args.build, "calib_longctx.txt"), |
| "eval/code (full)": os.path.join(eval_root, "code", "eval_code_full.txt"), |
| "eval/code (extension only)": os.path.join(eval_root, "code", "eval_code_ext.txt"), |
| "eval/neutral": os.path.join(eval_root, "neutral", "eval_neutral.txt"), |
| "eval/agentic": os.path.join(eval_root, "agentic", "eval_agentic.txt"), |
| } |
| sh = {k: np.unique(P.shingles(open(v, encoding="utf-8").read(), NGRAM)) |
| for k, v in files.items() if os.path.exists(v)} |
| matrix = {} |
| names = list(sh) |
| |
| |
| contained = {("eval/code (full)", "eval/code (extension only)"), |
| ("calib_train", "calib_longctx")} |
| ignore = template_grams |
| for i, a in enumerate(names): |
| for b in names[i + 1:]: |
| inter = np.intersect1d(sh[a], sh[b], assume_unique=True) |
| n = int(inter.size) |
| n_adj = int(sum(1 for x in inter.tolist() if x not in ignore)) |
| matrix[f"{a} ^ {b}"] = {"shared": n, "excluding_chat_template": n_adj} |
| if (a, b) in contained or (b, a) in contained: |
| note = " (containment, expected)" |
| elif n_adj: |
| note = " <-- NON-ZERO" |
| else: |
| note = "" |
| print(f" {a:28} ^ {b:28} {n:7} raw {n_adj:7} adj{note}") |
| out = {"corpora": results, "intersections": matrix, "ngram": NGRAM, |
| "ctx": CTX, "tokenizer": args.tokenizer} |
| with open(os.path.join(eval_root, "eval-report.json"), "w", encoding="utf-8") as f: |
| json.dump(out, f, indent=2, ensure_ascii=False) |
| f.write("\n") |
| print(f"\nwrote {os.path.join(eval_root, 'eval-report.json')}") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|