okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
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 7python3 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 ): 30tp = pathlib .Path (path ) 31vocab = json .loads ((tp / "vocab.json" ).read_text (encoding = "utf-8" )) 32toks = [None ]* len (vocab ) 33for t ,i in vocab .items (): 34toks [i ]= t 35return ST .Tokenizer (toks , (tp / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 36json .loads ((tp / "token_type.json" ).read_text ())) 37 38 39def wiki_article (lang :str ,seed :int ): 40url = ("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 ) 42req = urllib .request .Request (url + "&_=%d" % seed ,headers = {"User-Agent" :"strata-research/1.0 (research corpus; contact via GitHub Niko1221)" }) 43d = {} 44for attempt in range (8 ): 45try : 46with urllib .request .urlopen (req ,timeout = 60 )as r : 47d = json .loads (r .read ()) 48break 49except urllib .error .HTTPError as e : 50if e .code != 429 : 51raise 52time .sleep (3 * (attempt + 1 )) 53for p in d .get ("query" , {}).get ("pages" , {}).values (): 54return p .get ("title" ,"" ),p .get ("extract" ,"" ) 55return "" ,"" 56 57 58def wiki_docs (langs ,n_each ,seed ): 59jobs = [(l ,seed * 100000 + i * 17 + k )for k ,l in enumerate (langs )for i in range (n_each )] 60out = {} 61with cf .ThreadPoolExecutor (2 )as ex : 62for (l ,s ),res in zip (jobs ,ex .map (lambda j :wiki_article (* j ),jobs )): 63title ,text = res 64if len (text )> 1500 : 65out .setdefault (l , []).append ((title ,text )) 66return out 67 68 69def code_files (dirs ,exts ,limit_bytes = 40000 ): 70files = [] 71for d in dirs : 72for p in sorted (pathlib .Path (d ).rglob ("*" )): 73if p .is_file ()and p .suffix in exts and 800 < p .stat ().st_size < 400000 : 74files .append (p ) 75return files 76 77 78def agent_transcript (rnd :random .Random )-> str : 79tools = [("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" })] 82words = ["parser" ,"cache" ,"router" ,"scheduler" ,"tokenizer" ,"config" ,"retry" ,"metrics" ,"auth" ,"index" , 83"queue" ,"loader" ,"report" ,"build" ,"deploy" ,"schema" ] 84turns = ["<|im_start|>system\nYou are a coding agent. Tools: " + 85json .dumps ([{"name" :t [0 ],"parameters" :t [1 ]}for t in tools ])+ "<|im_end|>" ] 86turns .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 )])) 90for _ in range (rnd .randint (3 ,6 )): 91name ,args = rnd .choice (tools ) 92w = rnd .choice (words ) 93a = {k : (v % w if isinstance (v ,str )and "%s" in v else v )for k ,v in args .items ()} 94turns .append ("<|im_start|>assistant\nI will check the %s first.\n<tool_call>\n%s\n</tool_call><|im_end|>" % ( 95w ,json .dumps ({"name" :name ,"arguments" :a }))) 96turns .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 ))})) 98turns .append ("<|im_start|>assistant\nDone. The %s change is in place and the tests pass.<|im_end|>" % rnd .choice (words )) 99return "\n" .join (turns ) 100 101 102def windows (tok ,text ,seg ,parse_special = False ): 103ids = tok .encode (text ,parse_special = parse_special ) 104return [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 ): 108quota = {"english" :0.25 ,"multilingual" :0.25 ,"code" :0.25 ,"agent" :0.125 ,"docs" :0.125 } 109segs = [] 110# prose / multilingual from Wikipedia (the seed decides the articles; the two splits use different seeds) 111wl = wiki_docs (["en" ],int (n * 0.25 / 2 )+ 6 ,seed ) 112ml = wiki_docs ([l for l in LANGS if l != "en" ],max (2 ,int (n * 0.25 / 15 / 2 )+ 2 ),seed + 1 ) 113titles = set () 114for 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 ])): 116pool = [] 117for title ,text in docs : 118if title in titles : 119continue 120titles .add (title ) 121pool += windows (tok ,text ,seg ) 122rnd .shuffle (pool ) 123segs += [{"name" :"%s_%03d" % (kind ,i ),"ids" :w }for i ,w in enumerate (pool [:int (n * quota [kind ])])] 124# code 125pool = [] 126for p in code_files (code_dirs , {".py" ,".cpp" ,".h" ,".hpp" ,".c" ,".cu" ,".js" ,".sh" ,".cmake" ,".rs" ,".go" }): 127try : 128pool += windows (tok ,p .read_text (encoding = "utf-8" ,errors = "ignore" )[:60000 ],seg )[:2 ] 129except Exception : 130pass 131rnd .shuffle (pool ) 132segs += [{"name" :"code_%03d" % i ,"ids" :w }for i ,w in enumerate (pool [:int (n * quota ["code" ])])] 133# docs (markdown / text of the repositories) 134pool = [] 135for d in md_dirs : 136for p in sorted (pathlib .Path (d ).rglob ("*.md" )): 137if p .stat ().st_size > 3000 : 138pool += windows (tok ,p .read_text (encoding = "utf-8" ,errors = "ignore" )[:50000 ],seg )[:2 ] 139rnd .shuffle (pool ) 140segs += [{"name" :"docs_%03d" % i ,"ids" :w }for i ,w in enumerate (pool [:int (n * quota ["docs" ])])] 141# agent transcripts (tool calls) 142pool = [] 143while len (pool )< int (n * quota ["agent" ])+ 4 : 144t = "\n" .join (agent_transcript (rnd )for _ in range (3 )) 145pool += windows (tok ,t ,seg ,parse_special = True ) 146segs += [{"name" :"agent_%03d" % i ,"ids" :w }for i ,w in enumerate (pool [:int (n * quota ["agent" ])])] 147split , {k :sum (1 for s in segs if s ["name" ].startswith (k ))for k in quota },"total" ,len (segs )) 148return {"version" :"gyro-swap-" + split ,"seg_tokens" :seg ,"segments" :segs } 149 150 151def main ()-> int : 152ap = argparse .ArgumentParser () 153ap .add_argument ("--tokenizer" ,required = True ) 154ap .add_argument ("--out" ,required = True ) 155ap .add_argument ("--seg" ,type = int ,default = 512 ) 156ap .add_argument ("--cal" ,type = int ,default = 320 ) 157ap .add_argument ("--eval" ,type = int ,default = 128 ) 158ap .add_argument ("--cal-code" ,nargs = "+" ,default = ["/data/llama.cpp/src" ,"/data/llama.cpp/tools" ,"/data/llama.cpp/gguf-py" ]) 159ap .add_argument ("--eval-code" ,nargs = "+" ,default = ["/data/llama.cpp/ggml" ,"/data/llama.cpp/examples" ,"/data/llama.cpp/tests" ]) 160ap .add_argument ("--cal-md" ,nargs = "+" ,default = ["/data/llama.cpp/docs" ]) 161ap .add_argument ("--eval-md" ,nargs = "+" ,default = ["/data/llama.cpp/tools" ,"/data/llama.cpp/examples" ]) 162a = ap .parse_args () 163tok = load_tokenizer (a .tokenizer ) 164out = pathlib .Path (a .out ) 165out .mkdir (parents = True ,exist_ok = True ) 166cal = build (tok ,"cal" ,a .cal ,a .seg ,random .Random (11 ),1 ,a .cal_code ,a .cal_md ) 167ev = 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 169heads = {tuple (s ["ids" ][:64 ])for s in cal ["segments" ]} 170ev ["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"wrote" ,out ) 174return 0 175 176 177if __name__ == "__main__" : 178sys .exit (main ())