Slayer1B-1.09-Instruct-26.11: weights, card, notes, training code, manifests and results (history squashed; training data not published)
6071ec5 Download training/code/build_s3.py from SlayerLab/Slayer1B-1.09-Instruct-26.11: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/SlayerLab/Slayer1B-1.09-Instruct-26.11/resolve/main/training/code/build_s3.py
- Command line
-
hf download hf://SlayerLab/Slayer1B-1.09-Instruct-26.11/training/code/build_s3.py
-
curl -L -o build_s3.py https://huggingface.co/SlayerLab/Slayer1B-1.09-Instruct-26.11/resolve/main/training/code/build_s3.py
13 kB
| """s3 = s3_base (prepare.py, unified chat + tool layer, 200M-target budget) + math/logic/agent/QA/safety/teacher data. | |
| * base rows: agentic tool rows limited to <= 3 calls (as s2); chat rows whose longest assistant turn is > --max-chat-turn | |
| tokens are dropped (long, list-heavy answers taught a 1B model form without content); 12k chat rows get a tool list | |
| and keep their direct answer (tools available != must call, as s2). | |
| * every added conversation is decontaminated (13-gram >= 50% of an item, or exact string) against the eval splits of all | |
| CodeSOTA tasks (bench_decon_index.py), rendered with chatfmt (loss on assistant turns only), <= 4096 tokens. | |
| * repeats: a component can be repeated (whole copies, different order per epoch via train.py shuffling). | |
| python build_s3.py --base data/s3_base --gen /workspace/s3gen --synth /workspace/s3synth --src /workspace/s3src \ | |
| --decon /workspace/s3decon --out data/s3 [--tokenizer ...] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import glob | |
| import hashlib | |
| import json | |
| import random | |
| import re | |
| 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 xxhash | |
| from tokenizers import Tokenizer | |
| from chatfmt import Fmt | |
| import s3_synth as S3 | |
| import synth_tools as ST | |
| 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())]) | |
| WORD = re.compile(r"\w+") | |
| # component -> repeat factor (whole copies). Math is the priority of s3. | |
| REPEAT = {"math_en": 2, "math_pl": 2, "math_aug": 1, "arith": 1, "logic": 1, "agent": 1, "know": 1, "multiturn": 1, "safety": 1, | |
| "instruct": 2, "humor": 1, "poquad": 1, "squad": 1} | |
| class Decon: | |
| def __init__(self, d): | |
| z = np.load(Path(d) / "bench_index.npz") | |
| self.G, self.O, self.L, self.E, self.EO = z["G"], z["O"], z["L"], z["E"], z["EO"] | |
| self.items = json.loads((Path(d) / "bench_items.json").read_text()) | |
| def hit(self, texts): | |
| gs = set() | |
| for t in texts: | |
| w = WORD.findall((t or "").lower())[:3000] | |
| gs |= {xxhash.xxh64_intdigest(" ".join(w[i:i + 13]).encode()) for i in range(max(0, len(w) - 12))} | |
| nt = " ".join(unicodedata.normalize("NFKC", t or "").lower().split()) | |
| if 30 <= len(nt) <= 2000: | |
| h = np.uint64(int(hashlib.sha256(nt.encode()).hexdigest()[:16], 16)) | |
| j = np.searchsorted(self.E, h) | |
| if j < self.E.size and self.E[j] == h: | |
| return "exact:" + self.items[int(self.EO[j])] | |
| if not gs: | |
| return None | |
| a = np.fromiter(gs, dtype=np.uint64) | |
| pos = np.searchsorted(self.G, a) | |
| pos[pos >= self.G.size] = 0 | |
| own = self.O[pos[self.G[pos] == a]] | |
| if own.size: | |
| u, c = np.unique(own, return_counts=True) | |
| frac = c / np.maximum(self.L[u], 1) | |
| k = int(np.argmax(frac)) | |
| if frac[k] >= 0.5 and self.L[u[k]] >= 3: | |
| return "ngram13:" + self.items[int(u[k])] | |
| return None | |
| def clean(t): | |
| return "\n".join(line.rstrip() for line in t.strip().splitlines()) | |
| def max_span(mask: np.ndarray) -> int: | |
| best = cur = 0 | |
| for v in mask: | |
| cur = cur + 1 if v else 0 | |
| best = max(best, cur) | |
| return best | |
| def poquad(src, rnd, n_conv): | |
| d = json.load(open(Path(src) / "clarin-pl__poquad/poquad-train.json", encoding="utf-8")) | |
| out = [] | |
| for art in d["data"]: | |
| for p in art["paragraphs"]: | |
| qs = [q for q in p["qas"] if q.get("answers") or q.get("is_impossible")] | |
| if not qs or len(p["context"]) > 3500: | |
| continue | |
| rnd.shuffle(qs) | |
| qs = qs[: rnd.randint(1, 3)] | |
| msgs = [] | |
| for i, q in enumerate(qs): | |
| if q.get("is_impossible") or not q.get("answers"): | |
| ans = "W tym tekście nie ma informacji, która pozwalałaby odpowiedzieć na to pytanie." | |
| else: | |
| g = q["answers"][0].get("generative_answer") or q["answers"][0]["text"] | |
| ans = g[0].upper() + g[1:] + ("" if g.endswith((".", "!", "?")) else ".") | |
| u = (rnd.choice(["Przeczytaj tekst i odpowiedz na pytanie.", "Na podstawie tekstu odpowiedz krótko.", "Odpowiedz na pytanie, korzystając z tekstu."]) | |
| + f"\n\nTekst: {p['context']}\n\nPytanie: {q['question']}") if i == 0 else q["question"] | |
| msgs += [{"role": "user", "content": u}, {"role": "assistant", "content": ans}] | |
| out.append({"lang": "pl", "messages": msgs, "source": "poquad"}) | |
| rnd.shuffle(out) | |
| return out[:n_conv] | |
| def squad(src, rnd, n_conv): | |
| rows = pq.read_table(glob.glob(str(Path(src) / "rajpurkar__squad_v2/squad_v2/train-*.parquet"))[0]).to_pylist() | |
| by = defaultdict(list) | |
| for r in rows: | |
| by[r["context"]].append(r) | |
| ctxs = list(by) | |
| rnd.shuffle(ctxs) | |
| out = [] | |
| for c in ctxs[: n_conv]: | |
| qs = by[c] | |
| rnd.shuffle(qs) | |
| msgs = [] | |
| for i, q in enumerate(qs[: rnd.randint(1, 3)]): | |
| t = q["answers"]["text"] if isinstance(q["answers"], dict) else [] | |
| ans = (t[0][0].upper() + t[0][1:] + ".") if t else "The text does not say." | |
| u = (rnd.choice(["Read the text and answer the question.", "Answer briefly using the passage.", "Based on the text, answer the question."]) | |
| + f"\n\nText: {c}\n\nQuestion: {q['question']}") if i == 0 else q["question"] | |
| msgs += [{"role": "user", "content": u}, {"role": "assistant", "content": ans}] | |
| out.append({"lang": "en", "messages": msgs, "source": "squad_v2"}) | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--base", required=True) | |
| ap.add_argument("--gen", required=True) | |
| ap.add_argument("--synth", required=True) | |
| ap.add_argument("--src", required=True) | |
| ap.add_argument("--decon", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--tokenizer", default="/workspace/ckpt/tokenizer.json") | |
| ap.add_argument("--max-chat-turn", type=int, default=1024) | |
| ap.add_argument("--max-agentic-calls", type=int, default=3) | |
| ap.add_argument("--chat-with-tools", type=int, default=12000) | |
| ap.add_argument("--n-poquad", type=int, default=25000) | |
| ap.add_argument("--n-squad", type=int, default=12000) | |
| ap.add_argument("--val-frac", type=float, default=0.01) | |
| ap.add_argument("--added-frac", type=float, default=1.0, help="random fraction of every added component kept (budget cut)") | |
| ap.add_argument("--repeat", default="", help='JSON overrides of REPEAT, e.g. {"math_en": 3}') | |
| a = ap.parse_args() | |
| if a.repeat: | |
| REPEAT.update(json.loads(a.repeat)) | |
| out = Path(a.out) | |
| (out / "eval").mkdir(parents=True, exist_ok=True) | |
| f = Fmt(Tokenizer.from_file(a.tokenizer)) | |
| dec = Decon(a.decon) | |
| rnd = random.Random("s3-build") | |
| stats = Counter() | |
| sys_head = [f.ims] + f.enc("system\n") | |
| # ---------------- added conversations | |
| added = defaultdict(list) | |
| for p in sorted(glob.glob(str(Path(a.gen) / "*.jsonl"))): | |
| comp = Path(p).name.split(".")[0] | |
| for line in open(p, encoding="utf-8"): | |
| r = json.loads(line) | |
| for m in r["messages"]: | |
| m["content"] = clean(m["content"]) | |
| added[comp].append({"lang": r["lang"], "messages": r["messages"], "source": f"qwen3_8b:{r['source']}", "tools": None}) | |
| for comp in ("arith", "logic", "agent"): | |
| for line in open(Path(a.synth) / f"{comp}.jsonl", encoding="utf-8"): | |
| r = json.loads(line) | |
| added[comp].append({"lang": r["lang"], "messages": r["messages"], "source": f"s3_synth:{r['kind']}", "tools": r.get("tools")}) | |
| added["poquad"] = [{**x, "tools": None} for x in poquad(a.src, rnd, a.n_poquad)] | |
| added["squad"] = [{**x, "tools": None} for x in squad(a.src, rnd, a.n_squad)] | |
| rows = {"train": [], "val": []} | |
| for comp, xs in added.items(): | |
| rnd.shuffle(xs) | |
| xs = xs[: max(1, int(len(xs) * a.added_frac))] | |
| stats[f"available:{comp}"] = len(added[comp]) | |
| n_val = max(20, int(len(xs) * a.val_frac)) | |
| for j, x in enumerate(xs): | |
| texts = [m["content"] for m in x["messages"] if m.get("content")] | |
| h = dec.hit(texts) | |
| if h: | |
| stats[f"decon:{comp}:{h.split(':')[0]}:{h.split(':')[1]}"] += 1 | |
| continue | |
| ids, lab = f.render(x["messages"], x["tools"] or []) | |
| if len(ids) > 4096: | |
| stats[f"too_long:{comp}"] += 1 | |
| continue | |
| n_calls = sum(len(m.get("tool_calls") or []) for m in x["messages"]) | |
| rid = comp + "-" + hashlib.sha1(json.dumps(x["messages"], ensure_ascii=False).encode()).hexdigest()[:16] | |
| rec = {"id": rid, "input_ids": np.array(ids, dtype=np.uint16).tobytes(), "loss_mask": np.array([v != -100 for v in lab], dtype=np.uint8).tobytes(), | |
| "n_tokens": len(ids), "source": x["source"], "comp": comp, "language": x["lang"], "is_tool": n_calls > 0, | |
| "n_target": int(sum(v != -100 for v in lab)), "n_calls": n_calls} | |
| split = "val" if j < n_val else "train" | |
| for k in range(REPEAT.get(comp, 1) if split == "train" else 1): | |
| rows[split].append(rec if k == 0 else {**rec, "id": f"{rid}#r{k}"}) | |
| stats[f"{split}:{comp}"] += 1 | |
| # ---------------- base rows | |
| for split in ("train", "val"): | |
| base = pq.read_table(Path(a.base) / f"{split}.parquet").to_pylist() | |
| chat_idx = [i for i, r in enumerate(base) if not r["is_tool"]] | |
| rnd.shuffle(chat_idx) | |
| convert = set(chat_idx[: a.chat_with_tools if split == "train" else a.chat_with_tools // 50]) | |
| for i, r in enumerate(base): | |
| m = np.frombuffer(r["loss_mask"], dtype=np.uint8) | |
| if r["is_tool"] and r["n_calls"] > a.max_agentic_calls: | |
| stats[f"base:{split}:dropped_long_chain"] += 1 | |
| continue | |
| if not r["is_tool"] and max_span(m) > a.max_chat_turn: | |
| stats[f"base:{split}:dropped_long_answer"] += 1 | |
| continue | |
| if i in convert: | |
| ids = np.frombuffer(r["input_ids"], dtype=np.uint16).tolist() | |
| if list(ids[1:1 + len(sys_head)]) != sys_head: | |
| names = rnd.sample(list(ST.TOOLS), rnd.randint(2, 4)) | |
| ins = sys_head + f.enc(f.tools_block([{"name": n, **ST.TOOLS[n]} for n in names])) + [f.ime] + f.nl | |
| ids2, m2 = ids[:1] + ins + ids[1:], m.tolist()[:1] + [0] * len(ins) + m.tolist()[1:] | |
| if len(ids2) <= 4096: | |
| r = {**r, "id": r["id"] + "+tools", "input_ids": np.array(ids2, dtype=np.uint16).tobytes(), | |
| "loss_mask": np.array(m2, dtype=np.uint8).tobytes(), "n_tokens": len(ids2), "comp": r["comp"] + "+tools_no_call"} | |
| stats[f"base:{split}:chat_with_tools"] += 1 | |
| rows[split].append({k: r[k] for k in SCHEMA.names}) | |
| stats[f"base:{split}:kept"] += 1 | |
| for split, xs in rows.items(): | |
| pq.write_table(pa.Table.from_pylist(xs, schema=SCHEMA), out / f"{split}.parquet", compression="zstd", row_group_size=20000) | |
| stats[f"{split}:records"] = len(xs) | |
| stats[f"{split}:tokens"] = sum(r["n_tokens"] for r in xs) | |
| stats[f"{split}:target_tokens"] = sum(r["n_target"] for r in xs) | |
| stats[f"{split}:tool_records"] = sum(r["is_tool"] for r in xs) | |
| tg = Counter() | |
| for r in xs: | |
| tg[r["comp"].split("+")[0]] += r["n_target"] | |
| for k, v in tg.items(): | |
| stats[f"{split}:target_by_comp:{k}"] = v | |
| for fn in ("chat_prompts.jsonl", "tool_replay.jsonl"): | |
| src = Path(a.base) / "eval" / fn | |
| if src.exists(): | |
| (out / "eval" / fn).write_bytes(src.read_bytes()) | |
| def sha(p): | |
| return hashlib.sha256(Path(p).read_bytes()).hexdigest() | |
| man = {"derived_from": str(a.base), "args": vars(a), "repeat": REPEAT, "stats": dict(sorted(stats.items())), | |
| "files": {p.name: sha(p) for p in [out / "train.parquet", out / "val.parquet"]}} | |
| (out / "manifest.json").write_text(json.dumps(man, indent=1), encoding="utf-8") | |
| print(json.dumps(man["stats"], indent=1)) | |
| if __name__ == "__main__": | |
| main() | |