"""E5 SFT mix = new data (SLAYER.md conversations, offline-search trajectories, tool repair, document reading) + replay of the E3 training mix (data/s3), plus a held-out set of new-data cases for on-policy rollouts / DPO and for the E5 report. New data is decontaminated against the CodeSOTA eval index like s3; held-out cases never enter training. python build_e5.py --gen /workspace/e5gen --synth /workspace/e5synth --s3 data/s3 --decon /workspace/s3decon --out data/e5 \ [--replay-tokens 50e6 --heldout-frac 0.02] """ from __future__ import annotations import argparse import glob import hashlib import json import random from collections import Counter from pathlib import Path import numpy as np import pyarrow as pa import pyarrow.parquet as pq from tokenizers import Tokenizer from build_s3 import SCHEMA, Decon, clean from chatfmt import Fmt import doc_tools as DT def as_agent_md(x): """Same conversation with the instruction file called AGENT.md (teaches: read whichever instruction file is listed).""" y = json.loads(json.dumps(x, ensure_ascii=False).replace("SLAYER.md", "AGENT.md")) y["instr"] = "AGENT.md" return y AGENT_RULES = { "en": [["Use web_search only for current facts you do not know.", "Look things up only when the files do not answer the question."], ["Never call a tool that is not listed in the environment.", "Use only the tools listed in the environment."], ["If a tool returns an error, fix the arguments and try once more.", "After a tool error, correct the call once; if it fails again, tell the user."], ["Do not repeat the same tool call.", "One call per piece of information is enough."], ["SLAYER.md has priority over this file.", "If this file and SLAYER.md disagree, follow SLAYER.md."]], "pl": [["Używaj web_search tylko do aktualnych faktów, których nie znasz.", "Szukaj w sieci tylko wtedy, gdy pliki nie odpowiadają na pytanie."], ["Nie wywołuj narzędzi, których nie ma w środowisku.", "Korzystaj wyłącznie z narzędzi wypisanych w środowisku."], ["Gdy narzędzie zwróci błąd, popraw argumenty i spróbuj jeszcze raz.", "Po błędzie narzędzia popraw wywołanie raz; jeśli znowu się nie uda, powiedz o tym użytkownikowi."], ["Nie powtarzaj tego samego wywołania.", "Jedno wywołanie na jedną informację wystarczy."], ["SLAYER.md ma pierwszeństwo przed tym plikiem.", "Gdy ten plik i SLAYER.md się różnią, stosuj SLAYER.md."]]} def agent_md(rnd, lang, with_slayer=True): rules = [rnd.choice(r) for r in AGENT_RULES[lang][:-1] if rnd.random() < 0.8] + ([rnd.choice(AGENT_RULES[lang][-1])] if with_slayer else []) rules = rules or [rnd.choice(AGENT_RULES[lang][1])] head = ("## Rola\nJesteś agentem Slayer w tej aplikacji.\n\n## Zasady\n" if lang == "pl" else "## Role\nYou are the Slayer agent in this app.\n\n## Rules\n") return "# AGENT.md\n" + head + "\n".join("- " + r for r in rules) def with_agent_md(x, rnd): """SLAYER.md (team/user-level rules, highest priority) + AGENT.md (this agent's instructions, a plug-in below SLAYER.md): the model reads SLAYER.md first, then AGENT.md, then answers.""" msgs = x["messages"] k = next((i for i, m in enumerate(msgs) if m["role"] == "tool" and '"SLAYER.md"' in (m.get("content") or "")), None) if k is None or msgs[0]["role"] != "system" or ": SLAYER.md" not in msgs[0]["content"]: return x, False lang = x.get("lang") if x.get("lang") in ("pl", "en") else "pl" ag = agent_md(rnd, lang) docs = dict(x.get("docs") or {"SLAYER.md": x.get("slayer_md") or ""}) docs["AGENT.md"] = ag msgs[0]["content"] = msgs[0]["content"].replace(": SLAYER.md", ": SLAYER.md, AGENT.md", 1) call = {"role": "assistant", "content": "", "tool_calls": [{"name": "read_doc", "arguments": json.dumps({"name": "AGENT.md"})}], "trainable": True} res = {"role": "tool", "content": json.dumps(DT.execute("read_doc", {"name": "AGENT.md"}, docs), ensure_ascii=False)} msgs[k + 1:k + 1] = [call, res] x["docs"], x["both"] = docs, True return x, True def agent_only(x, rnd): """Only AGENT.md exists (no SLAYER.md): read it first, then do exactly what the original conversation did (honest answer without project info / web search / tool calls).""" msgs = x["messages"] if "SLAYER.md" in json.dumps(msgs, ensure_ascii=False) or x.get("docs"): return x, False i = next((k for k, m in enumerate(msgs) if m["role"] == "user"), None) if i is None or sum(len(m.get("tool_calls") or []) for m in msgs) > 4: return x, False lang = x.get("lang") if x.get("lang") in ("pl", "en") else "pl" docs = {"AGENT.md": agent_md(rnd, lang, with_slayer=False)} if msgs[0]["role"] == "system": rest, _ = DT.strip_workspace(msgs[0]["content"]) msgs[0]["content"] = rest # add_env lists the files from x["docs"] names = [t["function"]["name"] if "function" in t else t["name"] for t in (x.get("tools") or [])] if "read_doc" not in names: x["tools"] = [DT.READ_DOC] + list(x.get("tools") or []) call = {"role": "assistant", "content": "", "tool_calls": [{"name": "read_doc", "arguments": json.dumps({"name": "AGENT.md"})}], "trainable": True} res = {"role": "tool", "content": json.dumps(DT.execute("read_doc", {"name": "AGENT.md"}, docs), ensure_ascii=False)} msgs[i + 1:i + 1] = [call, res] x["docs"], x["instr"], x["agent_only"] = docs, "AGENT.md", True return x, True def add_env(x): """Every new-data conversation starts with the environment note (tools + files), as in the chat app.""" names = [t["function"]["name"] if "function" in t else t["name"] for t in (x.get("tools") or [])] lang = x.get("lang") if x.get("lang") in ("pl", "en") else "pl" msgs = x["messages"] sys0 = msgs[0] if msgs and msgs[0]["role"] == "system" else None rest, files = DT.strip_workspace(sys0["content"]) if sys0 else ("", None) if files is None: if (x.get("docs") and "list_docs" in names and any(m.get("tool_calls") and (m["tool_calls"][0].get("function") or m["tool_calls"][0]).get("name") == "list_docs" for m in msgs if m["role"] == "assistant")): files = None # the example teaches list_docs: do not reveal the names up front else: files = sorted((x.get("docs") or {}).keys()) if x.get("docs") else [] note = DT.env_note(names, files, lang) content = note + ("\n\n" + rest if rest else "") if sys0: sys0["content"] = content else: msgs.insert(0, {"role": "system", "content": content}) def main(): ap = argparse.ArgumentParser() ap.add_argument("--gen", required=True) ap.add_argument("--synth", required=True) ap.add_argument("--s3", required=True) ap.add_argument("--decon", default="", help="CodeSOTA decontamination index dir (skipped if empty or missing)") ap.add_argument("--out", required=True) ap.add_argument("--tokenizer", default="/workspace/ckpt/tokenizer.json") ap.add_argument("--replay-tokens", type=float, default=50e6) ap.add_argument("--heldout-frac", type=float, default=0.02) ap.add_argument("--heldout-max", type=int, default=400, help="per component") a = ap.parse_args() rnd = random.Random("e5-build") f = Fmt(Tokenizer.from_file(a.tokenizer)) dec = Decon(a.decon) if a.decon and (Path(a.decon) / "bench_index.npz").exists() else None print("decontamination:", "on" if dec else "OFF (no index)") out = Path(a.out) (out / "eval").mkdir(parents=True, exist_ok=True) comps = {} for p in sorted(glob.glob(str(Path(a.gen) / "*.jsonl"))): c = Path(p).name.split(".")[0] comps.setdefault(c, []).extend(json.loads(l) for l in open(p, encoding="utf-8")) for c in ("repair", "docs"): comps[c] = [json.loads(l) for l in open(Path(a.synth) / f"{c}.jsonl", encoding="utf-8")] stats, rows, held = Counter(), {"train": [], "val": []}, [] for comp, xs in comps.items(): rnd.shuffle(xs) n_held = min(a.heldout_max, max(20, int(len(xs) * a.heldout_frac))) for j, x in enumerate(xs): r = rnd.random() if comp == "slayer_md" and r < 0.25: x, ok = with_agent_md(x, rnd) stats[f"slayer+agent_md:{comp}"] += ok elif comp in ("slayer_md", "search", "docs") and r < 0.40 and "SLAYER.md" in json.dumps(x["messages"], ensure_ascii=False): x = as_agent_md(x) stats[f"agent_md_renamed:{comp}"] += 1 if comp in ("slayer_md", "search", "toolworld") and rnd.random() < 0.25 and ( comp != "slayer_md" or x.get("mode") == "absent") and ( comp != "toolworld" or any(m.get("tool_calls") for m in x["messages"])): x, ok = agent_only(x, rnd) stats[f"agent_md_without_slayer:{comp}"] += ok x.setdefault("task", comp) add_env(x) for m in x["messages"]: if m.get("content"): m["content"] = clean(m["content"]) if j < n_held: held.append(x) stats[f"heldout:{comp}"] += 1 continue h = dec and dec.hit([m["content"] for m in x["messages"] if m.get("content") and m["role"] in ("user", "assistant")]) if h: stats[f"decon:{comp}"] += 1 continue ids, lab = f.render(x["messages"], x.get("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] split = "val" if j < n_held + max(10, n_held // 2) else "train" rows[split].append({"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": f"e5:{comp}", "comp": comp, "language": x.get("lang", ""), "is_tool": n_calls > 0, "n_target": int(sum(v != -100 for v in lab)), "n_calls": n_calls}) stats[f"{split}:{comp}"] += 1 new_tokens = sum(r["n_tokens"] for r in rows["train"]) for split in ("train", "val"): base = pq.read_table(Path(a.s3) / f"{split}.parquet").to_pylist() rnd.shuffle(base) budget, got = (a.replay_tokens if split == "train" else a.replay_tokens / 100), 0 for r in base: if got >= budget: break rows[split].append({**r, "comp": "replay:" + r["comp"]}) got += r["n_tokens"] stats[f"{split}:replay_tokens"] = got 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"], stats[f"{split}:tokens"] = len(xs), sum(r["n_tokens"] for r in xs) stats[f"{split}:tool_records"] = sum(r["is_tool"] for r in xs) stats["train:new_tokens"] = new_tokens with open(out / "heldout.jsonl", "w", encoding="utf-8") as fo: for x in held: fo.write(json.dumps(x, ensure_ascii=False) + "\n") for fn in ("chat_prompts.jsonl", "tool_replay.jsonl"): src = Path(a.s3) / "eval" / fn if src.exists(): (out / "eval" / fn).write_bytes(src.read_bytes()) (out / "manifest.json").write_text(json.dumps({"args": vars(a), "stats": dict(sorted(stats.items()))}, indent=1), encoding="utf-8") print(json.dumps(dict(sorted(stats.items())), indent=1)) if __name__ == "__main__": main()