"""Build the Slayer1B SFT data (rendered token ids + loss masks) and held-out eval sets from the unified index. python prepare.py configs/s1_toolcall.yaml [--workers 14] Inputs: /training/index/*.parquet (metadata), the general-talk shards (local) and the agentic tool-calling shards (hf:// paths resolved through SAF_HF_MIRROR). Output: /slayer1b/data//{train,val}.parquet, eval/{chat_prompts,tool_replay}.jsonl, manifest.json. Deterministic for a given config. """ from __future__ import annotations import argparse import fnmatch import hashlib import json import multiprocessing as mp import os import re import sys import unicodedata from collections import Counter, defaultdict from pathlib import Path import numpy as np import pyarrow as pa import pyarrow.parquet as pq import yaml HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) sys.path.insert(0, str(HERE.parents[1] / "slayer-agentic-foundation-en" / "src")) from chatfmt import Fmt # noqa: E402 UNIFIED = HERE.parent TOKENIZER = Path(os.environ.get("SLAYER_TOKENIZER", str(UNIFIED.parent / "slayer-general-talk-pl-en/_research/slayer1b/tutorials/runtime/tokenizer.json"))) WORD = re.compile(r"\w+") SLAYER_EVAL = { # benchmarks reported on the Slayer1B-1.09 card (revisions from its model-index) + GSM8K/SST-2 (TRAINING_LOG) "arc": ("allenai/ai2_arc", "210d026faf9955653af8916fad021475a3f00453", ["ARC-Challenge/test-00000-of-00001.parquet", "ARC-Easy/test-00000-of-00001.parquet"]), "hellaswag": ("Rowan/hellaswag", "218ec52e09a7e7462a5400043bb9a69a41d06b76", ["data/validation-00000-of-00001.parquet"]), "piqa": ("baber/piqa", "142f6d7367fd9877f0fb3b5734ea6a545f54cdd1", ["piqa_validation.parquet", "piqa_test.parquet"]), "winogrande": ("allenai/winogrande", "01e74176c63542e6b0bcb004dcdea22d94fb67b5", ["winogrande_xl/validation-00000-of-00001.parquet"]), "boolq": ("aps/super_glue", "3de24cf8022e94f4ee4b9d55a6f539891524d646", ["boolq/validation-00000-of-00001.parquet"]), "openbookqa": ("allenai/openbookqa", "388097ea7776314e93a529163e0fea805b8a6454", ["main/test-00000-of-00001.parquet"]), "belebele_pl": ("facebook/belebele", "7899cdfa4e1e0d733fd77c848e2c273cb1d32be2", ["data/pol_Latn.jsonl"]), "hellaswag_pl": ("Eurolingua/hellaswagx", "c38911a204759866dbcde35eeb584c36caf11a8b", ["hellaswag_PL_validation.jsonl"]), "mmlu_pl": ("Eurolingua/mmlux", "7fb62cf05c1ce9ea550dbfd2ea6c145204344882", "hendrycks_*_PL_test.jsonl"), "gsm8k": ("openai/gsm8k", "740312add88f", ["main/test-00000-of-00001.parquet"]), "sst2": ("nyu-mll/glue", "bcdcba79d07b", ["sst2/validation-00000-of-00001.parquet"]), } def norm(s): return " ".join(unicodedata.normalize("NFKC", s or "").lower().split()) def grams13(text, cap=3000): import xxhash w = WORD.findall((text or "").lower())[:cap] return {xxhash.xxh64_intdigest(" ".join(w[i:i + 13]).encode()) for i in range(max(0, len(w) - 12))} def _strings(v, out): if isinstance(v, str): if len(v) >= 30: out.append(v) elif isinstance(v, list): for x in v: _strings(x, out) elif isinstance(v, dict): for x in v.values(): _strings(x, out) def build_bench_index(dst: Path) -> dict: import fnmatch as fm from huggingface_hub import HfApi, hf_hub_download api = HfApi() gram_owner, item_len, exact, items, meta = {}, [], {}, [], {} for name, (repo, rev, files) in SLAYER_EVAL.items(): info = api.dataset_info(repo, revision=rev) if isinstance(files, str): files = sorted(s.rfilename for s in info.siblings if fm.fnmatch(s.rfilename, files)) n = 0 for f in files: p = hf_hub_download(repo, f, repo_type="dataset", revision=info.sha, local_dir=str(dst / "bench" / name)) rows = pq.read_table(p).to_pylist() if p.endswith(".parquet") else [json.loads(l) for l in open(p, encoding="utf-8") if l.strip()] for r in rows: texts = [] _strings(r, texts) if not texts: continue k = len(items) items.append(name) n += 1 g = set() for t in texts: g |= grams13(t) nt = norm(t) if 30 <= len(nt) <= 2000: exact.setdefault(int(hashlib.sha256(nt.encode()).hexdigest()[:16], 16), k) item_len.append(len(g)) for h in g: gram_owner.setdefault(h, k) meta[name] = {"repo": repo, "revision": info.sha, "files": files, "items": n} G = np.array(sorted(gram_owner), dtype=np.uint64) np.savez(dst / "bench_index.npz", G=G, O=np.array([gram_owner[int(h)] for h in G], dtype=np.int32), L=np.array(item_len, dtype=np.int32), E=np.array(sorted(exact), dtype=np.uint64), EO=np.array([exact[h] for h in sorted(exact)], dtype=np.int32)) (dst / "bench_items.json").write_text(json.dumps(items), encoding="utf-8") return meta # ---------------------------------------------------------------- worker W = {} def _init(cfg, idx_path, items_path): from tokenizers import Tokenizer W["cfg"] = cfg W["fmt"] = Fmt(Tokenizer.from_file(str(TOKENIZER))) d = np.load(idx_path) W.update(G=d["G"], O=d["O"], L=d["L"], E=d["E"], EO=d["EO"], items=json.loads(Path(items_path).read_text(encoding="utf-8"))) def _open(shard): if shard.startswith("hf://"): return open(Path(os.environ["SAF_HF_MIRROR"]) / shard.split("@", 1)[1].split("/", 1)[1], "rb") return open(shard, "rb") def contaminated(texts) -> str | None: gs = set() for t in texts: gs |= grams13(t) nt = norm(t) if 30 <= len(nt) <= 2000: h = np.uint64(int(hashlib.sha256(nt.encode()).hexdigest()[:16], 16)) j = np.searchsorted(W["E"], h) if j < W["E"].size and W["E"][j] == h: return "exact:" + W["items"][int(W["EO"][j])] if not gs: return None a = np.fromiter(gs, dtype=np.uint64) pos = np.searchsorted(W["G"], a) pos[pos >= W["G"].size] = 0 own = W["O"][pos[W["G"][pos] == a]] if own.size: u, c = np.unique(own, return_counts=True) frac = c / np.maximum(W["L"][u], 1) k = int(np.argmax(frac)) if frac[k] >= 0.5 and W["L"][u[k]] >= 3: return f"ngram13:{W['items'][int(u[k])]}:{frac[k]:.2f}" return None def tool_ok(r, tf) -> str | None: if r["tool_protocol"] != "structured" or not r["tools"]: return "not_structured_tools" if len(r["tools"]) > tf["max_tools_declared"]: return "too_many_tools" calls = [c for m in r["messages"] for c in (m["tool_calls"] or [])] if not tf["min_calls"] <= len(calls) <= tf["max_calls"]: return "call_count" if tf["require_valid_calls"] and any((not c["arguments_valid_json"]) or c["declared"] is False or c["schema_valid"] is False for c in calls): return "invalid_call" if any(m["role"] == "assistant" and m["tool_calls"] and not m["trainable"] for m in r["messages"]): return "masked_call_turn" last = r["messages"][-1] if tf["require_final_text_answer"] and not (last["role"] == "assistant" and not last["tool_calls"] and (last["content"] or "").strip()): return "no_final_answer" return None def process(task): shard, rg, wanted = task cfg, fmt = W["cfg"], W["fmt"] with _open(shard) as fh: rows = pq.ParquetFile(fh).read_row_group(rg).to_pylist() out = [] for j in wanted: r = rows[j] is_tool = r["source"] in cfg["tool_sources"] why = tool_ok(r, cfg["tool_filter"]) if is_tool else None if why: out.append({"id": r["id"], "drop": "tool:" + why}) continue ids, lab = fmt.render(r["messages"], r["tools"] if is_tool else []) if len(ids) > cfg["max_tokens"]: out.append({"id": r["id"], "drop": "over_max_tokens"}) continue prompts = [m["content"] or "" for m in r["messages"] if m["role"] in ("system", "user")][:6] c = contaminated(prompts) if c: out.append({"id": r["id"], "drop": "contamination", "flag": c}) continue out.append({"id": r["id"], "n_tokens": len(ids), "n_target": sum(1 for x in lab if x != -100), "n_calls": sum(len(m["tool_calls"] or []) for m in r["messages"])}) return out def process_keyed(task): return task[0], task[1], process(task) def render_selected(task): shard, rg, wanted = task fmt = W["fmt"] with _open(shard) as fh: rows = pq.ParquetFile(fh).read_row_group(rg).to_pylist() res = [] for j in wanted: r = rows[j] is_tool = r["source"] in W["cfg"]["tool_sources"] ids, lab = fmt.render(r["messages"], r["tools"] if is_tool else []) res.append({"id": r["id"], "input_ids": np.array(ids, dtype=np.uint16).tobytes(), "loss_mask": np.array([x != -100 for x in lab], dtype=np.uint8).tobytes(), "n_tokens": len(ids)}) return res def _h(seed, *p): return int.from_bytes(hashlib.sha256("|".join([seed, *map(str, p)]).encode()).digest()[:8], "little") def main(): ap = argparse.ArgumentParser() ap.add_argument("config") ap.add_argument("--workers", type=int, default=14) a = ap.parse_args() cfg = yaml.safe_load(Path(a.config).read_text(encoding="utf-8")) out = UNIFIED / "slayer1b" / "data" / cfg["name"] (out / "eval").mkdir(parents=True, exist_ok=True) print("benchmark index ...", flush=True) if (out / "bench_meta.json").exists() and (out / "bench_index.npz").exists(): bench = json.loads((out / "bench_meta.json").read_text(encoding="utf-8")) else: bench = build_bench_index(out) (out / "bench_meta.json").write_text(json.dumps(bench, indent=1), encoding="utf-8") idx = pq.read_table(UNIFIED / "training" / "index" / "slayer-general-talk-pl-en.parquet").to_pylist() + \ [r for r in pq.read_table(UNIFIED / "training" / "index" / "slayer-agentic-foundation-en.parquet").to_pylist() if r["source"] in cfg["tool_sources"]] why = Counter() cand = [] for r in idx: if r["source"] in cfg["exclude_sources"]: why["source_excluded"] += 1 continue if r["source"] in cfg["exclude_private_in_sources"] and r["release_tier"] == "private": why["closed_teacher_prompts"] += 1 continue if r["release_tier"] not in cfg["allow_tiers"] or r["legal_status"] not in ("approved", "approved_with_obligations"): why["tier_or_status"] += 1 continue if cfg["exclude_weights_obligations"] and r["weights_obligations"]: why["weights_obligation"] += 1 continue if any(fnmatch.fnmatch(f, p) for f in r["quality_flags"] for p in cfg["exclude_quality_flags"]): why["flag"] += 1 continue if r["quality_score"] is not None and r["quality_score"] < cfg["min_quality_score"]: why["quality"] += 1 continue sr = next((int(f.rsplit("x", 1)[1]) for f in r["quality_flags"] if f.startswith("shared_response_x")), 0) if sr > cfg["shared_response_cap"] and _h(cfg["seed"], "sr", r["id"]) % sr >= cfg["shared_response_cap"]: why["shared_response_cap"] += 1 continue cand.append(r) by_rg = defaultdict(list) for r in cand: by_rg[(r["shard"], r["row_group"])].append(r["row_in_group"]) tasks = [(s, g, w) for (s, g), w in by_rg.items()] print(f"candidates {len(cand)} in {len(tasks)} row groups; excluded {dict(why)}", flush=True) res = {} cache = out / "pass1_cache.jsonl" # resumable: one line per finished row group done = set() if cache.exists(): for line in open(cache, encoding="utf-8"): d = json.loads(line) done.add((d["shard"], d["rg"])) for x in d["rows"]: res[x["id"]] = x todo = [t_ for t_ in tasks if (t_[0], t_[1]) not in done] print(f"pass1 cached row groups {len(done)}, to do {len(todo)}", flush=True) with open(cache, "a", encoding="utf-8") as cf, mp.get_context("spawn").Pool(a.workers, initializer=_init, initargs=(cfg, str(out / "bench_index.npz"), str(out / "bench_items.json"))) as pool: for i, (s_, g_, part) in enumerate(pool.imap_unordered(process_keyed, todo, chunksize=2)): cf.write(json.dumps({"shard": s_, "rg": g_, "rows": part}) + "\n") for x in part: res[x["id"]] = x if i % 500 == 0: cf.flush() print(f" pass1 {i}/{len(todo)}", flush=True) drops = Counter(x["drop"] for x in res.values() if "drop" in x) cont = Counter(x["flag"].split(":")[1] for x in res.values() if x.get("drop") == "contamination") meta = {r["id"]: r for r in cand} ok = [meta[i] | res[i] for i in res if "drop" not in res[i]] del meta, res, cand, idx, by_rg, tasks # pass 2 needs the memory (Windows workers are separate processes) import gc gc.collect() # ---- selection (train split): prompt-cluster cap, token budgets per component / language seed = cfg["seed"] pools = defaultdict(list) for r in ok: comp = "tool" if r["source"] in cfg["tool_sources"] else "chat" key = comp if comp == "tool" else ("chat:" + (r["language"] if r["language"] in ("pl", "en", "pl+en") else "en")) pools[(r["split"], key)].append(r) total = cfg["total_target_tokens"] bud = {"tool": total * cfg["shares"]["tool"]} for lang, s in cfg["chat_language_shares"].items(): bud["chat:" + lang] = total * cfg["shares"]["chat"] * s selected, stats, carry = [], {}, 0.0 for key in ["tool", "chat:pl+en", "chat:pl", "chat:en"]: b = bud[key] + carry pool = sorted(pools[("train", key)], key=lambda r: _h(seed, key, r["id"])) seen, got, n = Counter(), 0, 0 for r in pool: k = r["task_cluster_id"] or r["id"] if seen[k] >= cfg["prompt_cluster_cap"]: continue if got >= b: break seen[k] += 1 got += r["n_target"] n += 1 selected.append({**r, "comp": key}) carry = max(0.0, b - got) if key != "tool" else 0.0 stats[key] = {"budget": int(bud[key]), "selected_target": got, "records": n, "available_target": sum(r["n_target"] for r in pools[("train", key)])} val = [] for key in ["tool", "chat:pl", "chat:en", "chat:pl+en"]: pool = sorted(pools[("validation", key)], key=lambda r: _h(seed, "val", key, r["id"])) share = 0.5 if key == "tool" else 0.5 * cfg["chat_language_shares"][key.split(":")[1]] val += [{**r, "comp": key} for r in pool[: int(cfg["validation_examples"] * share)]] # ---- pass 2: render selected rows and write for name, rows in (("train", selected), ("val", val)): by = defaultdict(list) for r in rows: by[(r["shard"], r["row_group"])].append(r["row_in_group"]) info = {r["id"]: r for r in rows} schema = pa.schema([("id", pa.string()), ("input_ids", pa.binary()), ("loss_mask", pa.binary()), ("n_tokens", pa.int64()), ("source", pa.string()), ("comp", pa.string()), ("language", pa.string()), ("is_tool", pa.bool_()), ("n_target", pa.int64()), ("n_calls", pa.int64())]) w = pq.ParquetWriter(out / f".{name}.parquet.tmp", schema, compression="zstd") # streamed; train.py shuffles with mp.get_context("spawn").Pool(min(a.workers, int(os.environ.get("PREP_PASS2_WORKERS", "6"))), initializer=_init, initargs=(cfg, str(out / "bench_index.npz"), str(out / "bench_items.json"))) as pool: for part in pool.imap_unordered(render_selected, [(s, g, w_) for (s, g), w_ in by.items()], chunksize=1): recs = [] for x in part: r = info[x["id"]] recs.append({**x, "source": r["source"], "comp": r["comp"], "language": r["language"], "is_tool": r["comp"] == "tool", "n_target": r["n_target"], "n_calls": r["n_calls"]}) if recs: w.write_table(pa.Table.from_pylist(recs, schema=schema)) w.close() os.replace(out / f".{name}.parquet.tmp", out / f"{name}.parquet") # ---- held-out eval prompts (test split): chat and tool-call replay chat_eval, tool_eval = [], [] test_tool = sorted(pools[("test", "tool")], key=lambda r: _h(seed, "te", r["id"]))[:400] test_chat = sorted(pools[("test", "chat:pl")], key=lambda r: _h(seed, "tc", r["id"]))[:150] + \ sorted(pools[("test", "chat:en")], key=lambda r: _h(seed, "tc", r["id"]))[:150] for rows, dst in ((test_tool, tool_eval), (test_chat, chat_eval)): by = defaultdict(list) for r in rows: by[(r["shard"], r["row_group"])].append(r) for (s, g), rs in by.items(): with _open(s) as fh: rg = pq.ParquetFile(fh).read_row_group(g).to_pylist() for r in rs: rec = rg[r["row_in_group"]] msgs = rec["messages"] k = next(i for i, m in enumerate(msgs) if m["role"] == "assistant") ctx = [{"role": m["role"], "content": m["content"]} for m in msgs[:k]] item = {"id": rec["id"], "source": rec["source"], "language": rec.get("language") or "en", "messages": ctx} if dst is tool_eval: first = msgs[k] item["tools"] = [{"name": t["name"], "description": t["description"], "parameters": t["parameters"]} for t in rec["tools"]] item["expected_call"] = [{"name": c["name"], "arg_keys": sorted(json.loads(c["arguments"]).keys())} for c in (first["tool_calls"] or [])] item["reference_text"] = first["content"] dst.append(item) for fn, rows in (("chat_prompts.jsonl", chat_eval), ("tool_replay.jsonl", tool_eval)): with open(out / "eval" / fn, "w", encoding="utf-8") as f: for x in rows: f.write(json.dumps(x, ensure_ascii=False) + "\n") def sha(p): h = hashlib.sha256() with open(p, "rb") as f: while b := f.read(1 << 22): h.update(b) return h.hexdigest() tr = pq.read_table(out / "train.parquet", columns=["comp", "n_tokens", "n_target", "is_tool", "source"]).to_pylist() man = {"config": cfg, "tokenizer": str(TOKENIZER), "tokenizer_sha256": sha(TOKENIZER), "benchmarks_scanned": bench, "excluded_before_render": dict(why), "dropped_at_render": dict(drops), "contamination_removed_by_benchmark": dict(cont), "selection": stats, "train": {"records": len(tr), "tokens": sum(x["n_tokens"] for x in tr), "target_tokens": sum(x["n_target"] for x in tr), "tool_records": sum(x["is_tool"] for x in tr), "by_source": dict(Counter(x["source"] for x in tr))}, "val_records": len(val), "eval": {"chat_prompts": len(chat_eval), "tool_replay": len(tool_eval)}, "files": {p.name: sha(p) for p in [out / "train.parquet", out / "val.parquet", out / "eval" / "chat_prompts.jsonl", out / "eval" / "tool_replay.jsonl"]}} (out / "manifest.json").write_text(json.dumps(man, indent=2, ensure_ascii=False), encoding="utf-8") print(json.dumps({k: man[k] for k in ("selection", "train", "dropped_at_render", "contamination_removed_by_benchmark")}, indent=1)) if __name__ == "__main__": main()