"""The proof run's token ids: every source in plan/PROOF_DATA.md -> sequences in one id space. Id space (the pilot's table plus the 302 rows of plan/TABLE_ROWS.md; the ~64k trim and the aligned bands are applied later as a row remap, so ids here never change): 0..131071 language (Gemma-3 pieces via new2old; any text round-trips) 131072 + w picture word w (16,384) 147456 + w sound word (8,192) 155648 + w clip word (4,096) 159744..159747 [image] [audio] [video] [sep] 159748..160049 control rows, CTRL below, in TABLE_ROWS order Sequence shapes text text picture + text [image] 16 words [/image] caption (OBELICS keeps its page order) clip + text [video] [t0] w w w w w [t2] w ... [/video] (27 words, a stamp every 5) sound + text [audio] [t0] w*10 [t2] w*10 ... [/audio] (50 words a 10 s window) generation pair caption [gen_image] words [end_gen] and the reverse, both kept SFT user\\n ... \\nmodel\\n ... loss mask on the model turns only; [system] [think] [tools] [call] [result] rows Budgets are tokens a source; each unit (a slice of a file) takes an even share, so a source's take spans all of it. Every document passes a 13-gram filter against the benchmarks' test text (decon.npy). Output ids///part_XXXXX.npz (ids uint32, offs int64, mask uint8 for SFT) + ids/manifest.json (tokens, docs, licence a source). python3 build_ids.py decon # benchmark 13-grams, once python3 build_ids.py run knowledge # a lane (knowledge | understanding | sft) or a source name python3 build_ids.py count # seal counts over everything built """ import os for _v in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): os.environ.setdefault(_v, "1") os.environ.setdefault("SHADOW_RELEASE", "/workspace/shadow/tables") import sys, re, io, json, glob, time, random, hashlib, pathlib, zlib import multiprocessing as mp import numpy as np ROOT = pathlib.Path("/workspace/shadow"); D = ROOT / "data"; W = ROOT / "words"; OUT = ROOT / "ids" sys.path.insert(0, str(ROOT / "scripts")) # ------------------------------------------------------------------ id space N_LANG, OFF = 131072, {"image": 131072, "audio": 147456, "video": 155648} MARK = {"image": 159744, "audio": 159745, "video": 159746, "sep": 159747} CTRL_NAMES = (["[/image]", "[/audio]", "[/video]", "[speech]", "[screen]", "[page]", "[frame]", "[system]", "[think]", "[/think]", "[tools]", "[call]", "[/call]", "[result]", "[/result]", "[retrieved]", "[/retrieved]", "[archive]"] + [f"[t{i}]" for i in range(64)] + ["[point]"] + [f"[tile{i}]" for i in range(64)] + [f"[patch{i}]" for i in range(64)] + [f"[off{i}]" for i in range(16)] + ["[still]", "[blank]", "[line]"] + ["[gen_image]", "[gen_video]", "[gen_audio]", "[end_gen]", "[gen4]", "[gen5]", "[gen6]", "[gen7]"] + [f"[ctl{i}]" for i in range(64)]) assert len(CTRL_NAMES) == 302 CTRL = {n: 159748 + i for i, n in enumerate(CTRL_NAMES)} N_ROWS = 159748 + 302 END = {"image": CTRL["[/image]"], "audio": CTRL["[/audio]"], "video": CTRL["[/video]"]} GEN = {"image": CTRL["[gen_image]"], "audio": CTRL["[gen_audio]"], "video": CTRL["[gen_video]"]} BOS, EOS, SOT, EOT, NL = 2, 1, 8, 9, 10 _TOK = None def tok(): global _TOK if _TOK is None: import tok00; _TOK = tok00.Tok() return _TOK def enc(text): return tok().encode_batch([text])[0].tolist() if text else [] # ------------------------------------------------------------------ words of pictures, clips, sounds WORDS = {} def words(mod, src): k = (mod, src) if k not in WORDS: import pyarrow.parquet as pq d = {} for f in sorted(glob.glob(str(W / mod / src / "part_*.parquet"))): t = pq.read_table(f) ks = t.column("key").to_pylist(); ws = t.column("words").to_numpy(zero_copy_only=False) ss = t.column("seconds").to_pylist() if "seconds" in t.column_names else [None] * len(ks) for a, b, c in zip(ks, ws, ss): d[a] = (np.asarray(b, np.int64), c) WORDS[k] = d print(f" words {mod}/{src}: {len(d):,}", flush=True) return WORDS[k] def media(mod, w, sec=None, kind=None): """[image] words [/image]; clips and sounds carry time stamps.""" w = np.asarray(w) + OFF[mod]; out = [MARK[mod]] + ([CTRL[kind]] if kind else []) if mod == "image": out += w.tolist() elif mod == "video": step = (sec or 8.0) / len(w) for i, x in enumerate(w.tolist()): if i % 5 == 0: out.append(CTRL[f"[t{min(63, int(i * step))}]"]) out.append(x) else: # 50 words = 10 s a window, a stamp every 2 s for i, x in enumerate(w.tolist()): if i % 10 == 0: out.append(CTRL[f"[t{min(63, (i // 50) * 10 + (i % 50) // 5)}]"]) out.append(x) return out + [END[mod]] # ------------------------------------------------------------------ SFT turns THINK = re.compile(r"(.*?)\s*", re.S) def turn_ids(role, text, pre=None): """-> (ids, train). role user|model. .. -> [think]..[/think], dropped when empty.""" ids = [SOT] + enc(role + "\n") + (pre or []) if text: pos = 0 for m in THINK.finditer(text): ids += enc(text[pos:m.start()]) if m.group(1).strip(): ids += [CTRL["[think]"]] + enc(m.group(1).strip()) + [CTRL["[/think]"], NL] pos = m.end() ids += enc(text[pos:]) ids += [EOT, NL] return ids, role == "model" def chat(turns): """turns: [(role, text, pre_ids)] -> doc of segments with a mask.""" segs = [] for r, t, p in turns: ids, tr = turn_ids(r, t, p); segs.append((ids, tr)) return segs # ------------------------------------------------------------------ helpers over files def rows(f, cols=None): import pyarrow.parquet as pq pf = pq.ParquetFile(f); i = 0 for b in pf.iter_batches(batch_size=512, columns=cols): for r in b.to_pylist(): yield i, r; i += 1 def pq_slices(pattern, per=20000): import pyarrow.parquet as pq out = [] for f in sorted(glob.glob(str(D / pattern), recursive=True)): if pathlib.Path(f).name in ("fetch_index.parquet", "selected_docs.parquet"): continue # our own fetch bookkeeping n = pq.read_metadata(f).num_rows out += [(f, a, min(n, a + per)) for a in range(0, n, per)] return out def slice_rows(u, cols=None): f, a, b = u for i, r in rows(f, cols): if i >= b: break if i >= a: yield i, r def h01(s): # stable split in [0,1) return (zlib.crc32(str(s).encode()) & 0xffffffff) / 2 ** 32 def T(text, train=True): return (enc(text), train) def plain(text): return [([BOS] + enc(text) + [EOS], True)] # ------------------------------------------------------------------ knowledge def k_cosmo(u): for i, r in slice_rows(u, ["text", "audience", "format"]): if r["format"] == "textbook" and ("college" in r["audience"] or "high_school" in r["audience"]): yield plain(r["text"]) def k_content(u): for i, r in slice_rows(u, ["content"]): yield plain(r["content"]) def k_wiki(u): for i, r in slice_rows(u, ["title", "text"]): t = r["text"]; cut = t.rfind("\n", 0, 2000) yield plain(r["title"] + "\n\n" + (t[:cut] if len(t) > 2000 and cut > 300 else t[:2000])) def k_math(gsm): def f(u): for i, r in slice_rows(u, ["problem", "generated_solution", "problem_source"]): if ("gsm8k" in r["problem_source"]) == gsm: yield plain(r["problem"] + "\n\n" + r["generated_solution"]) return f def k_text(u): for i, r in slice_rows(u, ["text"]): yield plain(r["text"]) def k_code(sft): def f(u): for i, r in slice_rows(u, ["id", "input", "output", "average_test_score"]): if float(r["average_test_score"] or 0) < 0.9 or (h01(r["id"]) < 0.5) != sft: continue if sft: yield chat([("user", r["input"], None), ("model", r["output"], None)]) else: yield plain(r["input"] + "\n\n" + r["output"]) return f def k_udcode(u): for i, r in slice_rows(u, ["full_content"]): yield plain(r["full_content"]) # ------------------------------------------------------------------ understanding: pictures def fv_turns(texts): return [(t.get("user") or "", t.get("assistant") or "") for t in texts] def u_finevision(sft): def f(u): fw = words("image", "finevision"); rel = os.path.relpath(u[0], D) for i, r in slice_rows(u, ["images", "texts"]): if (h01(f"{rel}:{i}") < 0.7) == sft: continue ims = [] for j in range(len(r["images"] or [])): w = fw.get(f"{rel}:{i}:{j}") if w is not None: ims += media("image", w[0]) if not ims: continue qa = fv_turns(r["texts"] or []) if sft: tu = [] for k, (q, a) in enumerate(qa): tu += [("user", q, ims if k == 0 else None), ("model", a, None)] yield chat(tu) else: yield [([BOS] + ims, True)] + [T(q + "\n" + a + "\n\n") for q, a in qa] + [([EOS], True)] return f def u_pixmo(u): pw = words("image", "pixmo-cap") for i, r in slice_rows(u, ["image_url", "caption"]): w = pw.get(hashlib.sha1(r["image_url"].encode()).hexdigest()) if w is not None: yield [([BOS] + media("image", w[0]), True), T(r["caption"]), ([EOS], True)] def obelics_units(): import pyarrow.parquet as pq sel = pq.read_table(D / "understanding/image/obelics/selected_docs.parquet").to_pandas() out = [] for f, g in sel.groupby("file"): rs = sorted(g.row.tolist()); out += [(str(D / "understanding/image/obelics" / f), rs[k:k + 5000]) for k in range(0, len(rs), 5000)] return out def u_obelics(u): import pyarrow.parquet as pq ow = words("image", "obelics"); f, want = u; want = set(want) t = pq.read_table(f, columns=["images", "texts"]) ims, txs = t.column("images").to_pylist(), t.column("texts").to_pylist() for i in sorted(want): segs, n_img = [([BOS], True)], 0 for im, tx in zip(ims[i], txs[i]): if im: w = ow.get(hashlib.sha1(im.encode()).hexdigest()) if w is not None: segs.append((media("image", w[0]), True)); n_img += 1 elif tx: segs.append(T(tx + "\n\n")) if n_img: yield segs + [([EOS], True)] # ------------------------------------------------------------------ understanding: clips and sounds def msrvtt_caps(split): fn = {"train": "msrvtt_train_9k.json", "test": "msrvtt_test_1k.json"}[split] return {x["video"]: (x["caption"] if isinstance(x["caption"], list) else [x["caption"]]) for x in json.load(open(D / "understanding/video/msrvtt" / fn))} def single(name): # one unit: the whole source return lambda: [name] def u_msrvtt(gen): def f(u): vw = words("video", "msrvtt"); caps = msrvtt_caps("train"); rnd = random.Random(1 + gen) for k, (w, s) in vw.items(): c = caps.get(k.split("/")[-1]) if not c: continue # the 1k test clips are never used for cap in (rnd.sample(c, min(5, len(c))) if not gen else [rnd.choice(c)]): # 20 human captions a clip: 5 in understanding yield from pair("video", w, s, cap, gen) return f def pair(mod, w, s, cap, gen): """understanding: [media] caption. generation: both orders.""" m = media(mod, w, s) if not gen: yield [([BOS] + m, True), T(cap), ([EOS], True)]; return body = (np.asarray(w) + OFF[mod]).tolist() yield [([BOS], True), T(cap), ([GEN[mod]] + body + [CTRL["[end_gen]"], EOS], True)] yield [([BOS] + m, True), T(cap), ([EOS], True)] def u_llava_video_cap(u): vw = words("video", "llava-video-178k") for f in glob.glob(str(D / "understanding/video/llava-video-178k/*/*cap_processed.json")): for x in json.load(open(f)): w = vw.get(x.get("video", "")) if w is None: continue conv = x["conversations"] yield [([BOS] + media("video", w[0], w[1]), True), T(conv[1]["value"]), ([EOS], True)] def u_openvid(u): import csv vw = words("video", "openvid-1m"); caps = {} with open(D / "generation/video/openvid-1m/data/train/OpenVid-1M.csv", newline="", encoding="utf-8") as fh: for r in csv.DictReader(fh): caps[r["video"]] = r["caption"] for k, (w, s) in vw.items(): c = caps.get(k.split("/")[-1]) if c: yield from pair("video", w, s, c, True) def u_audioset(u): aw = words("audio", "audioset") for f in sorted(glob.glob(str(D / "understanding/audio/audioset/**/*.parquet"), recursive=True)): for i, r in rows(f, ["video_id", "human_labels"]): w = aw.get(r["video_id"]) if w is not None: yield [([BOS] + media("audio", w[0], w[1]), True), T(", ".join(r["human_labels"] or [])), ([EOS], True)] def u_clotho(gen): def f(u): aw = words("audio", "clotho") for g in sorted(glob.glob(str(D / "understanding/audio/clotho/**/*.parquet"), recursive=True)): for i, r in rows(g, ["index", "text"]): w = aw.get(r["index"]) if w is not None and r["text"]: yield from pair("audio", w[0], w[1], r["text"], gen) return f def u_audiocaps(u): aw = words("audio", "audiocaps") for g in sorted(glob.glob(str(D / "generation/audio/audiocaps/**/*.parquet"), recursive=True)): for i, r in rows(g, ["audiocap_id", "caption"]): w = aw.get(str(r["audiocap_id"])) if w is not None: yield from pair("audio", w[0], w[1], r["caption"], True) def wavcaps_index(): """wavcaps words by file stem ("Yb0RFKhbpFJA", "2219").""" return {pathlib.Path(k).stem: v for k, v in words("audio", "wavcaps").items()} def u_wavcaps(gen): def f(u): ww = wavcaps_index() for js in ["AudioSet_SL/as_final.json", "SoundBible/sb_final.json"]: d = json.load(open(D / "understanding/audio/wavcaps/json_files" / js)); d = d.get("data", d) for x in d: w = ww.get(pathlib.Path(str(x["id"])).stem) if w is not None and (h01(x["id"]) < 0.5) == gen: yield from pair("audio", w[0], w[1], x["caption"], gen) return f def audio_lookup(): """AudioSkills / AF names -> sound words: AudioSet 'Y.wav', WavCaps AS_SL, SoundBible.""" aset = words("audio", "audioset"); wc = wavcaps_index() def get(name): st = pathlib.Path(name).stem return wc.get(st) or (aset.get(st[1:]) if st.startswith("Y") else None) or aset.get(st) return get def conv_turns(conv, pre, tag): """LLaVA-style [{'from','value'}] with one placeholder -> [(role, text, pre)].""" out, used = [], False for c in conv: r = "user" if c["from"] in ("human", "user") else "model" v = c["value"] p = None if r == "user" and not used and pre is not None: v = re.sub(rf"<{tag}(-\d+)?>\n?", "", v); p = pre; used = True out.append((r, v, p)) return out def u_audioskills(sft): def f(u): get = audio_lookup() base = D / "understanding/audio/audioskills-xl/audioskills_xl" for js in ["AudioSet.json", "AudioSet_SL.json", "WavCaps.json", "SoundBible.json"]: if not (base / js).exists(): continue for x in json.load(open(base / js)): w = get(x["sound"] if isinstance(x["sound"], str) else x["sound"][0]) if w is None or (h01(json.dumps(x["conversations"])[:200]) < 0.5) != sft: continue m = media("audio", w[0], w[1]) if sft: yield chat(conv_turns(x["conversations"], m, "sound")) else: c = x["conversations"]; yield [([BOS] + m, True), T(c[0]["value"].replace("", "").strip() + "\n" + c[1]["value"]), ([EOS], True)] return f # ------------------------------------------------------------------ generation pairs: pictures FLUX_CAPS = ["caption_composition", "caption_entity", "caption_style", "caption_detail", "caption_original"] def u_flux(u): fw = words("image", "flux-reason-6m") for i, r in slice_rows(u, ["id"] + FLUX_CAPS): w = fw.get(r["id"]) if w is None: continue caps = [r[c] for c in FLUX_CAPS if r[c]] if not caps: continue rnd = random.Random(r["id"]) yield from pair("image", w[0], None, rnd.choice(caps), True) # ------------------------------------------------------------------ SFT def s_messages(u): """Nemotron / UltraData / smoltalk2: messages [{role, content}].""" f = u[0] if isinstance(u, tuple) else u it = slice_rows(u, ["messages"]) if isinstance(u, tuple) else ((i, json.loads(l)) for i, l in enumerate(open(f))) for i, r in it: ms = r["messages"] if isinstance(ms, str): try: ms = json.loads(ms) except Exception: import ast; ms = ast.literal_eval(ms) tu, sys_ = [], None for m in ms: role, c = m.get("role"), m.get("content") or "" c = c.replace(" /no_think", "").replace("/no_think", "") if role == "system": sys_ = c; continue if role == "user": pre = ([CTRL["[system]"]] + enc(sys_) + [NL]) if sys_ else None; sys_ = None tu.append(("user", c, pre)) elif role == "assistant": tu.append(("model", c, None)) if tu and tu[-1][0] == "model" and tu[0][0] == "user": yield chat(tu) def jsonl_units(pattern): return sorted(glob.glob(str(D / pattern), recursive=True)) def s_toucan(u): for i, r in slice_rows(u, ["messages"]): try: ms = json.loads(r["messages"]) except Exception: continue segs, sys_ = [], None for m in ms: role, c = m.get("role"), m.get("content") or "" if role == "system": decl = re.sub(r"<\|im_[a-z]+\|>", " ", c).replace("tool_declare", "").strip() sys_ = [CTRL["[tools]"]] + enc(decl) + [NL]; continue if role == "user": ids, tr = turn_ids("user", c, sys_); sys_ = None; segs.append((ids, tr)) elif role == "assistant": pre = [] calls = m.get("tool_calls") or ([m["function_call"]] if m.get("function_call") else []) body = enc(c) for tc in calls: fn = tc.get("function", tc); body += [CTRL["[call]"]] + enc(json.dumps({"name": fn.get("name"), "arguments": fn.get("arguments")})) + [CTRL["[/call]"]] segs.append(([SOT] + enc("model\n") + body + [EOT, NL], True)) elif role in ("function", "tool"): segs.append(([SOT] + enc("user\n") + [CTRL["[result]"]] + enc(c) + [CTRL["[/result]"], EOT, NL], False)) if any(t for _, t in segs): yield segs def s_toolace(u): for x in json.load(open(D / "sft/tools/toolace/data.json")): pre = [CTRL["[system]"]] + enc(x["system"]) + [NL]; segs = [] for c in x["conversations"]: r = c["from"] if r == "user": ids, tr = turn_ids("user", c["value"], pre); pre = None; segs.append((ids, tr)) elif r == "assistant": v = c["value"] body = ([CTRL["[call]"]] + enc(v) + [CTRL["[/call]"]]) if v.startswith("[") and v.endswith(")]") else enc(v) segs.append(([SOT] + enc("model\n") + body + [EOT, NL], True)) elif r == "tool": segs.append(([SOT] + enc("user\n") + [CTRL["[result]"]] + enc(c["value"]) + [CTRL["[/result]"], EOT, NL], False)) if segs: yield segs def s_xlam(u): for x in json.load(open(D / "sft/tools/xlam/xlam_function_calling_60k.json")): pre = [CTRL["[tools]"]] + enc(x["tools"]) + [NL] ids, _ = turn_ids("user", x["query"], pre) yield [(ids, False), ([SOT] + enc("model\n") + [CTRL["[call]"]] + enc(x["answers"]) + [CTRL["[/call]"], EOT, NL], True)] def s_onevision(u): ow = words("image", "llava-onevision"); rel = os.path.relpath(u[0], D) for i, r in slice_rows(u, ["conversations"]): w = ow.get(f"{rel}:{i}:0") if w is not None: yield chat(conv_turns(r["conversations"], media("image", w[0]), "image")) def s_pixmo_ask(u): pw = words("image", "pixmo-ask") for i, r in slice_rows(u, ["image_url", "question", "answer"]): w = pw.get(hashlib.sha1(r["image_url"].encode()).hexdigest()) if w is not None: yield chat([("user", r["question"].strip(), media("image", w[0])), ("model", r["answer"], None)]) def s_voice(u): vw = words("audio", "voiceassistant-400k"); rel = os.path.relpath(u[0], D) for i, r in slice_rows(u, ["question", "answer"]): w = vw.get(f"{rel}:{i}:0") if w is not None: yield chat([("user", "", media("audio", w[0], w[1], "[speech]")), ("model", r["answer"], None)]) def s_af(u): get = audio_lookup() for f in sorted(glob.glob(str(D / "sft/audio/af-chat/afchat/*.json")) + glob.glob(str(D / "sft/audio/af-think/*/*.json"))): for x in json.load(open(f)): snd = x["sound"] if isinstance(x["sound"], list) else [x["sound"]] ws = [get(s) for s in snd] if not ws or any(w is None for w in ws): continue pre = [t for w in ws for t in media("audio", w[0], w[1])] yield chat(conv_turns(x["conversations"], pre, "sound")) def s_llava_video_qa(u): vw = words("video", "llava-video-178k") for f in glob.glob(str(D / "understanding/video/llava-video-178k/*/*qa_processed.json")): for x in json.load(open(f)): w = vw.get(x.get("video", "")) if w is not None: yield chat(conv_turns(x["conversations"], media("video", w[0], w[1]), "image")) def s_video_r1(u): iw, vw = words("image", "video-r1"), words("video", "video-r1") cot = {x["problem_id"]: x for x in json.load(open(D / "sft/video/video-r1/Video-R1-COT-165k.json"))} for x in json.load(open(D / "sft/video/video-r1/Video-R1-260k.json")): p = x["path"].lstrip("./") w = (vw if x["data_type"] == "video" else iw).get(p) if w is None: continue m = media("video", w[0], w[1]) if x["data_type"] == "video" else media("image", w[0]) q = x["problem"] + ("\n" + "\n".join(x["options"]) if x.get("options") else "") c = cot.get(x["problem_id"]); ans = x["solution"] a = (c["process"] + "\n" + ans) if c else ans a = re.sub(r"", "", a) yield chat([("user", q, m), ("model", a, None)]) ASK = {"image": ["Draw {c}", "Make a picture of {c}", "Generate an image: {c}", "Can you draw this? {c}", "Create an image of {c}"], "video": ["Make a video of {c}", "Generate a short clip: {c}", "Film this: {c}", "Create a video showing {c}"], "audio": ["Make the sound of {c}", "Generate audio: {c}", "What would this sound like? Make it: {c}", "Create a sound of {c}"]} def s_gen(u): """'draw ...' -> [gen_*] words [end_gen]; captions not used by the pretraining pairs' first half.""" rnd = random.Random(7) srcs = [("image", "flux-reason-6m", None), ("video", "openvid-1m", None), ("audio", "audiocaps", None)] import csv caps = {"flux-reason-6m": {}, "openvid-1m": {}, "audiocaps": {}} for f in sorted(glob.glob(str(D / "generation/image/flux-reason-6m/**/*.parquet"), recursive=True)): for i, r in rows(f, ["id", "caption_composition"]): caps["flux-reason-6m"][r["id"]] = r["caption_composition"] with open(D / "generation/video/openvid-1m/data/train/OpenVid-1M.csv", newline="", encoding="utf-8") as fh: for r in csv.DictReader(fh): caps["openvid-1m"][r["video"]] = r["caption"] for f in sorted(glob.glob(str(D / "generation/audio/audiocaps/**/*.parquet"), recursive=True)): for i, r in rows(f, ["audiocap_id", "caption"]): caps["audiocaps"][str(r["audiocap_id"])] = r["caption"] for mod, src, _ in srcs: for k, (w, s) in words(mod, src).items(): c = caps[src].get(k.split("/")[-1] if mod == "video" else k) if not c or rnd.random() > 0.35: continue c = c.strip().rstrip("."); c = c[0].lower() + c[1:] if c[:2].istitle() else c body = (np.asarray(w) + OFF[mod]).tolist() yield [(turn_ids("user", rnd.choice(ASK[mod]).format(c=c))[0], False), ([SOT] + enc("model\n") + [GEN[mod]] + body + [CTRL["[end_gen]"], EOT, NL], True)] # ------------------------------------------------------------------ the sources M = 1_000_000 SRC = { # name: (lane, units(), docs(unit), token budget, licence, sft) "cosmopedia-v2": ("knowledge", lambda: pq_slices("knowledge/cosmopedia-v2/**/*.parquet"), k_cosmo, 300 * M, "odc-by", False), "ultra-fineweb-l3": ("knowledge", lambda: pq_slices("knowledge/ultra-fineweb-l3/**/*.parquet"), k_content, 250 * M, "apache-2.0", False), "ultra-fineweb": ("knowledge", lambda: pq_slices("knowledge/ultra-fineweb/**/*.parquet"), k_content, 150 * M, "apache-2.0", False), "wikipedia": ("knowledge", lambda: pq_slices("knowledge/wikipedia/**/*.parquet"), k_wiki, 50 * M, "cc-by-sa-3.0", False), "openmathinstruct-2-gsm8k": ("knowledge", lambda: pq_slices("knowledge/openmathinstruct-2/**/*.parquet", 100000), k_math(True), 84 * M, "cc-by-4.0", False), "openmathinstruct-2-math": ("knowledge", lambda: pq_slices("knowledge/openmathinstruct-2/**/*.parquet", 100000), k_math(False), 36 * M, "cc-by-4.0", False), "finemath": ("knowledge", lambda: pq_slices("knowledge/finemath/**/*.parquet"), k_text, 30 * M, "odc-by", False), "opencodeinstruct": ("knowledge", lambda: pq_slices("knowledge/opencodeinstruct/**/*.parquet", 50000), k_code(False), 70 * M, "cc-by-4.0", False), "ultradata-code": ("knowledge", lambda: pq_slices("knowledge/ultradata-code/**/*.parquet"), k_udcode, 30 * M, "apache-2.0", False), "obelics": ("understanding", obelics_units, u_obelics, 360 * M, "cc-by-4.0", False), "finevision": ("understanding", lambda: pq_slices("understanding/image/finevision/**/*.parquet", 5000), u_finevision(False), 300 * M, "cc-by-4.0", False), "pixmo-cap": ("understanding", lambda: pq_slices("understanding/image/pixmo-cap/**/*.parquet"), u_pixmo, 150 * M, "odc-by", False), "msrvtt": ("understanding", single("msrvtt"), u_msrvtt(False), 10 * M, "see-card", False), "llava-video-178k": ("understanding", single("llava-video"), u_llava_video_cap, 40 * M, "see-card", False), "audioset": ("understanding", single("audioset"), u_audioset, 15 * M, "cc-by-4.0", False), "clotho": ("understanding", single("clotho"), u_clotho(False), 5 * M, "see-card", False), "wavcaps": ("understanding", single("wavcaps"), u_wavcaps(False), 10 * M, "cc-by-4.0", False), "audioskills-xl": ("understanding", single("audioskills"), u_audioskills(False), 20 * M, "nvidia-other", False), "gen-flux-reason-6m": ("understanding", lambda: pq_slices("generation/image/flux-reason-6m/**/*.parquet", 5000), u_flux, 60 * M, "apache-2.0", False), "gen-openvid-1m": ("understanding", single("openvid"), u_openvid, 12 * M, "cc-by-4.0", False), "gen-msrvtt": ("understanding", single("msrvtt"), u_msrvtt(True), 3 * M, "see-card", False), "gen-audiocaps": ("understanding", single("audiocaps"), u_audiocaps, 9 * M, "cc-by-nc-4.0", False), "gen-clotho": ("understanding", single("clotho"), u_clotho(True), 2 * M, "see-card", False), "gen-wavcaps": ("understanding", single("wavcaps"), u_wavcaps(True), 4 * M, "cc-by-4.0", False), "nemotron-post-training-v1": ("sft", lambda: pq_slices("sft/talking/nemotron-post-training-v1/**/*.parquet"), s_messages, 80 * M, "cc-by-4.0", True), "ultradata-sft-2605": ("sft", lambda: jsonl_units("sft/talking/ultradata-sft-2605/**/*.jsonl"), s_messages, 60 * M, "apache-2.0", True), "smoltalk2": ("sft", lambda: pq_slices("sft/talking/smoltalk2/**/*.parquet"), s_messages, 30 * M, "see-card", True), "sft-finevision": ("sft", lambda: pq_slices("understanding/image/finevision/**/*.parquet", 5000), u_finevision(True), 90 * M, "cc-by-4.0", True), "llava-onevision": ("sft", lambda: pq_slices("sft/vision/llava-onevision/**/*.parquet", 5000), s_onevision, 40 * M, "apache-2.0", True), "pixmo-ask": ("sft", lambda: pq_slices("sft/vision/pixmo-ask/**/*.parquet", 20000), s_pixmo_ask, 20 * M, "odc-by", True), "voiceassistant-400k": ("sft", lambda: pq_slices("sft/audio/voiceassistant-400k/**/*.parquet", 5000), s_voice, 20 * M, "apache-2.0", True), "af-chat-think": ("sft", single("af"), s_af, 15 * M, "nvidia-other", True), "sft-audioskills-xl": ("sft", single("audioskills"), u_audioskills(True), 15 * M, "nvidia-other", True), "llava-video-qa": ("sft", single("llava-video-qa"), s_llava_video_qa, 25 * M, "see-card", True), "video-r1": ("sft", single("video-r1"), s_video_r1, 15 * M, "apache-2.0", True), "toucan-1.5m": ("sft", lambda: pq_slices("sft/tools/toucan-1.5m/**/*.parquet", 20000), s_toucan, 30 * M, "apache-2.0", True), "toolace": ("sft", single("toolace"), s_toolace, 8 * M, "apache-2.0", True), "xlam": ("sft", single("xlam"), s_xlam, 7 * M, "cc-by-4.0", True), "sft-opencodeinstruct": ("sft", lambda: pq_slices("knowledge/opencodeinstruct/**/*.parquet", 50000), k_code(True), 15 * M, "cc-by-4.0", True), "gen-instructions": ("sft", single("gen"), s_gen, 30 * M, "mixed", True), } # ------------------------------------------------------------------ decontamination DECON = None def ngrams(a, n=13): a = np.asarray(a, np.uint64) if len(a) < n: return np.zeros(0, np.uint64) h = np.zeros(len(a) - n + 1, np.uint64) with np.errstate(over="ignore"): for k in range(n): h = h * np.uint64(1000003) + a[k:k + len(h)] return h def clean(ids): """Dropped only when at least half of some test item's 13-grams are in the document: the test question itself is there. A shared phrase ("What is the smallest positive integer $n$ such that") is not a leak; counting any single 13-gram dropped 24% of the MATH-style half.""" global DECON if DECON is None: z = np.load(ROOT / "tables/decon.npz"); DECON = (z["h"], z["item"], z["n"]) H, I, N = DECON t = np.asarray(ids); t = t[t < N_LANG] # text only h = np.unique(ngrams(t)) if not len(h): return True j = np.searchsorted(H, h).clip(0, len(H) - 1); hit = H[j] == h if not hit.any(): return True it, k = np.unique(I[j[hit]], return_counts=True) return not (k >= np.maximum(1, 0.5 * N[it])).any() def build_decon(): from datasets import load_dataset texts = [] def add(repo, cfg, split, f): try: ds = load_dataset(repo, cfg, split=split) texts.extend(f(x) for x in ds); print(f" {repo} {cfg or ''} {split}: {len(ds)}", flush=True) except Exception as e: print(f" SKIP {repo}: {str(e)[:120]}", flush=True) # questions only: solutions and reference code share boilerplate with every maths and code # source (the first filter, built with them, dropped 35% of OpenMathInstruct's MATH half) add("openai/gsm8k", "main", "test", lambda x: x["question"]) for c in ["algebra", "counting_and_probability", "geometry", "intermediate_algebra", "number_theory", "prealgebra", "precalculus"]: add("EleutherAI/hendrycks_math", c, "test", lambda x: x["problem"]) add("cais/mmlu", "all", "test", lambda x: x["question"] + " " + " ".join(x["choices"])) for c in ["ARC-Easy", "ARC-Challenge"]: add("allenai/ai2_arc", c, "test", lambda x: x["question"] + " " + " ".join(x["choices"]["text"])) add("Rowan/hellaswag", None, "validation", lambda x: x["ctx"] + " " + " ".join(x["endings"])) add("openai/openai_humaneval", None, "test", lambda x: x["prompt"]) add("google-research-datasets/mbpp", "full", "test", lambda x: x["text"] + "\n" + "\n".join(x["test_list"])) per = [np.unique(ngrams(t)) for t in tok().encode_batch(texts)] h = np.concatenate(per + [np.zeros(0, np.uint64)]); item = np.repeat(np.arange(len(per)), [len(p) for p in per]) o = np.argsort(h, kind="stable"); h, item = h[o], item[o] first = np.r_[True, h[1:] != h[:-1]] # a 13-gram shared by items keeps its first item np.savez(ROOT / "tables/decon.npz", h=h[first], item=item[first].astype(np.int32), n=np.array([len(p) for p in per], np.int32)) print(f"decon: {len(texts):,} test items, {first.sum():,} 13-grams; a document goes when it holds half of one item", flush=True) # ------------------------------------------------------------------ worker and driver def work(args): name, ui, u, cap = args lane, _, docs_fn, _, _, sft = SRC[name] out = OUT / lane / name / f"part_{ui:05d}.npz" if out.exists(): z = np.load(out); return name, len(z["ids"]), len(z["offs"]) - 1, 0 ids, offs, mask, n_dirty, tot = [], [0], [], 0, 0 try: for segs in docs_fn(u): d = [t for s, _ in segs for t in s] if not clean(d): n_dirty += 1; continue ids += d; offs.append(len(ids)) if sft: mask += [m for s, tr in segs for m in [int(tr)] * len(s)] tot += len(d) if tot >= cap: break except Exception as e: print(f" ERR {name} unit {ui}: {type(e).__name__} {str(e)[:200]}", flush=True) out.parent.mkdir(parents=True, exist_ok=True) kw = {"mask": np.asarray(mask, np.uint8)} if sft else {} np.savez(out, ids=np.asarray(ids, np.uint32), offs=np.asarray(offs, np.int64), **kw) return name, len(ids), len(offs) - 1, n_dirty def run(sel, workers=96): names = [n for n, v in SRC.items() if v[0] == sel or n in sel.split(",")] man_p = OUT / "manifest.json"; man = json.load(open(man_p)) if man_p.exists() else {} jobs = [] for n in names: us = SRC[n][1]() random.Random(0).shuffle(us) cap = int(SRC[n][3] / max(1, len(us)) * 1.15) if len(us) > 1 else SRC[n][3] jobs += [(n, i, u, cap) for i, u in enumerate(us)] print(f"{n}: {len(us)} units, {SRC[n][3]/M:.0f}M budget, {cap/M:.2f}M a unit", flush=True) # forkserver, not fork: the parent has pyarrow's threads running, and a forked child can # inherit a held lock (the first run hung at 0% CPU). Words load lazily in each worker. random.Random(1).shuffle(jobs) t0 = time.time(); acc = {n: [0, 0, 0] for n in names} with mp.get_context("forkserver").Pool(workers, maxtasksperchild=20) as pool: for k, (n, t, d, dirty) in enumerate(pool.imap_unordered(work, jobs)): a = acc[n]; a[0] += t; a[1] += d; a[2] += dirty if k % 50 == 0 or k == len(jobs) - 1: print(time.strftime("%H:%M:%S"), f"{k+1}/{len(jobs)} units, {sum(x[0] for x in acc.values())/M:.1f}M tokens", flush=True) man = json.load(open(man_p)) if man_p.exists() else {} # re-read: another run may have written since for n in names: lane, _, _, bud, lic, sft = SRC[n] man[n] = {"lane": lane, "tokens": acc[n][0], "docs": acc[n][1], "dropped_by_13gram": acc[n][2], "budget": bud, "licence": lic, "sft": sft} print(f" {n:28s} {acc[n][0]/M:8.1f}M tokens (budget {bud/M:.0f}M) {acc[n][1]:,} docs {acc[n][2]:,} dropped", flush=True) json.dump(man, open(man_p, "w"), indent=1) print(f"DONE {sel} in {time.time()-t0:.0f}s", flush=True) def count(): c = np.zeros(N_ROWS, np.int64) for f in glob.glob(str(OUT / "*/*/part_*.npz")): c += np.bincount(np.load(f)["ids"], minlength=N_ROWS)[:N_ROWS] np.save(ROOT / "tables/counts.npy", c); print(f"counts over {c.sum():,} tokens; rows used {int((c > 0).sum()):,} of {N_ROWS:,}") if __name__ == "__main__": cmd = sys.argv[1] if cmd == "decon": build_decon() elif cmd == "run": run(sys.argv[2], int(sys.argv[3]) if len(sys.argv) > 3 else 96) elif cmd == "count": count()