okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
8.5 KiB178 linesraw
1"""make_corpus.py - the calibration set and the held-out evaluation set for the Gyro swap experiment.
2
3Writes two ids files in the format of tools/quant_quality.py (run / compare): `cal.ids.json` and `eval.ids.json`, every
4segment SEG tokens.  The two sets share no document: Wikipedia articles come from two different seeds with their titles
5checked against each other, code from two disjoint directory lists, agent transcripts from two seeds of a generator.
6
7  python3 tools/trellis/make_corpus.py --tokenizer packs/gyro-s/tokenizer --out DIR [--seg 512] [--cal 320] [--eval 128]
8"""
9from __future__ import annotations
10
11import argparse
12import concurrent.futures as cf
13import json
14import pathlib
15import random
16import sys
17import time
18import urllib.error
19import urllib.parse
20import urllib.request
21
22HERE = pathlib.Path(__file__).resolve().parent
23sys.path.insert(0, str(HERE.parent))
24import strata_tokenizer as ST  # noqa: E402
25
26LANGS = ["en", "de", "fr", "es", "ru", "zh", "ja", "pt", "it", "ar", "ko", "tr", "pl", "nl", "hi", "vi"]
27
28
29def load_tokenizer(path):
30    tp = pathlib.Path(path)
31    vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8"))
32    toks = [None] * len(vocab)
33    for t, i in vocab.items():
34        toks[i] = t
35    return ST.Tokenizer(toks, (tp / "merges.txt").read_text(encoding="utf-8").split("\n"),
36                        json.loads((tp / "token_type.json").read_text()))
37
38
39def wiki_article(lang: str, seed: int):
40    url = ("https://%s.wikipedia.org/w/api.php?action=query&format=json&generator=random&grnnamespace=0&grnlimit=1"
41           "&prop=extracts&explaintext=1&redirects=1&grnfilterredir=nonredirects" % lang)
42    req = urllib.request.Request(url + "&_=%d" % seed, headers={"User-Agent": "strata-research/1.0 (research corpus; contact via GitHub Niko1221)"})
43    d = {}
44    for attempt in range(8):
45        try:
46            with urllib.request.urlopen(req, timeout=60) as r:
47                d = json.loads(r.read())
48            break
49        except urllib.error.HTTPError as e:
50            if e.code != 429:
51                raise
52            time.sleep(3 * (attempt + 1))
53    for p in d.get("query", {}).get("pages", {}).values():
54        return p.get("title", ""), p.get("extract", "")
55    return "", ""
56
57
58def wiki_docs(langs, n_each, seed):
59    jobs = [(l, seed * 100000 + i * 17 + k) for k, l in enumerate(langs) for i in range(n_each)]
60    out = {}
61    with cf.ThreadPoolExecutor(2) as ex:
62        for (l, s), res in zip(jobs, ex.map(lambda j: wiki_article(*j), jobs)):
63            title, text = res
64            if len(text) > 1500:
65                out.setdefault(l, []).append((title, text))
66    return out
67
68
69def code_files(dirs, exts, limit_bytes=40000):
70    files = []
71    for d in dirs:
72        for p in sorted(pathlib.Path(d).rglob("*")):
73            if p.is_file() and p.suffix in exts and 800 < p.stat().st_size < 400000:
74                files.append(p)
75    return files
76
77
78def agent_transcript(rnd: random.Random) -> str:
79    tools = [("read_file", {"path": "src/%s.py"}), ("run_shell", {"command": "grep -rn %s ."}),
80             ("search", {"query": "%s", "limit": 5}), ("write_file", {"path": "notes/%s.md", "content": "..."}),
81             ("http_get", {"url": "https://example.org/%s"}), ("list_dir", {"path": "%s"})]
82    words = ["parser", "cache", "router", "scheduler", "tokenizer", "config", "retry", "metrics", "auth", "index",
83             "queue", "loader", "report", "build", "deploy", "schema"]
84    turns = ["<|im_start|>system\nYou are a coding agent. Tools: " +
85             json.dumps([{"name": t[0], "parameters": t[1]} for t in tools]) + "<|im_end|>"]
86    turns.append("<|im_start|>user\n%s<|im_end|>" % rnd.choice([
87        "Find where the %s is configured and fix the retry bug." % rnd.choice(words),
88        "Summarize how %s works in this repository and list the files involved." % rnd.choice(words),
89        "Add a unit test for the %s module and run it." % rnd.choice(words)]))
90    for _ in range(rnd.randint(3, 6)):
91        name, args = rnd.choice(tools)
92        w = rnd.choice(words)
93        a = {k: (v % w if isinstance(v, str) and "%s" in v else v) for k, v in args.items()}
94        turns.append("<|im_start|>assistant\nI will check the %s first.\n<tool_call>\n%s\n</tool_call><|im_end|>" % (
95            w, json.dumps({"name": name, "arguments": a})))
96        turns.append("<|im_start|>user\n<tool_response>\n%s\n</tool_response><|im_end|>" % json.dumps(
97            {"ok": True, "result": "%s: %d matches in %d files" % (w, rnd.randint(1, 40), rnd.randint(1, 9))}))
98    turns.append("<|im_start|>assistant\nDone. The %s change is in place and the tests pass.<|im_end|>" % rnd.choice(words))
99    return "\n".join(turns)
100
101
102def windows(tok, text, seg, parse_special=False):
103    ids = tok.encode(text, parse_special=parse_special)
104    return [ids[i:i + seg] for i in range(0, len(ids) - seg + 1, seg)]
105
106
107def build(tok, split: str, n: int, seg: int, rnd: random.Random, seed: int, code_dirs, md_dirs):
108    quota = {"english": 0.25, "multilingual": 0.25, "code": 0.25, "agent": 0.125, "docs": 0.125}
109    segs = []
110    # prose / multilingual from Wikipedia (the seed decides the articles; the two splits use different seeds)
111    wl = wiki_docs(["en"], int(n * 0.25 / 2) + 6, seed)
112    ml = wiki_docs([l for l in LANGS if l != "en"], max(2, int(n * 0.25 / 15 / 2) + 2), seed + 1)
113    titles = set()
114    for kind, docs in (("english", [d for v in wl.values() for d in v]),
115                       ("multilingual", [d for v in ml.values() for d in v])):
116        pool = []
117        for title, text in docs:
118            if title in titles:
119                continue
120            titles.add(title)
121            pool += windows(tok, text, seg)
122        rnd.shuffle(pool)
123        segs += [{"name": "%s_%03d" % (kind, i), "ids": w} for i, w in enumerate(pool[:int(n * quota[kind])])]
124    # code
125    pool = []
126    for p in code_files(code_dirs, {".py", ".cpp", ".h", ".hpp", ".c", ".cu", ".js", ".sh", ".cmake", ".rs", ".go"}):
127        try:
128            pool += windows(tok, p.read_text(encoding="utf-8", errors="ignore")[:60000], seg)[:2]
129        except Exception:
130            pass
131    rnd.shuffle(pool)
132    segs += [{"name": "code_%03d" % i, "ids": w} for i, w in enumerate(pool[:int(n * quota["code"])])]
133    # docs (markdown / text of the repositories)
134    pool = []
135    for d in md_dirs:
136        for p in sorted(pathlib.Path(d).rglob("*.md")):
137            if p.stat().st_size > 3000:
138                pool += windows(tok, p.read_text(encoding="utf-8", errors="ignore")[:50000], seg)[:2]
139    rnd.shuffle(pool)
140    segs += [{"name": "docs_%03d" % i, "ids": w} for i, w in enumerate(pool[:int(n * quota["docs"])])]
141    # agent transcripts (tool calls)
142    pool = []
143    while len(pool) < int(n * quota["agent"]) + 4:
144        t = "\n".join(agent_transcript(rnd) for _ in range(3))
145        pool += windows(tok, t, seg, parse_special=True)
146    segs += [{"name": "agent_%03d" % i, "ids": w} for i, w in enumerate(pool[:int(n * quota["agent"])])]
147    print(split, {k: sum(1 for s in segs if s["name"].startswith(k)) for k in quota}, "total", len(segs))
148    return {"version": "gyro-swap-" + split, "seg_tokens": seg, "segments": segs}
149
150
151def main() -> int:
152    ap = argparse.ArgumentParser()
153    ap.add_argument("--tokenizer", required=True)
154    ap.add_argument("--out", required=True)
155    ap.add_argument("--seg", type=int, default=512)
156    ap.add_argument("--cal", type=int, default=320)
157    ap.add_argument("--eval", type=int, default=128)
158    ap.add_argument("--cal-code", nargs="+", default=["/data/llama.cpp/src", "/data/llama.cpp/tools", "/data/llama.cpp/gguf-py"])
159    ap.add_argument("--eval-code", nargs="+", default=["/data/llama.cpp/ggml", "/data/llama.cpp/examples", "/data/llama.cpp/tests"])
160    ap.add_argument("--cal-md", nargs="+", default=["/data/llama.cpp/docs"])
161    ap.add_argument("--eval-md", nargs="+", default=["/data/llama.cpp/tools", "/data/llama.cpp/examples"])
162    a = ap.parse_args()
163    tok = load_tokenizer(a.tokenizer)
164    out = pathlib.Path(a.out)
165    out.mkdir(parents=True, exist_ok=True)
166    cal = build(tok, "cal", a.cal, a.seg, random.Random(11), 1, a.cal_code, a.cal_md)
167    ev = build(tok, "eval", a.eval, a.seg, random.Random(22), 2, a.eval_code, a.eval_md)
168    # no document in common: compare the first 64 tokens of every segment
169    heads = {tuple(s["ids"][:64]) for s in cal["segments"]}
170    ev["segments"] = [s for s in ev["segments"] if tuple(s["ids"][:64]) not in heads]
171    (out / "cal.ids.json").write_text(json.dumps(cal))
172    (out / "eval.ids.json").write_text(json.dumps(ev))
173    print("wrote", out)
174    return 0
175
176
177if __name__ == "__main__":
178    sys.exit(main())