File size: 13,302 Bytes
53d5fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""I1 SFT mix (Slayer1B-1.10 Instruct, run 1) = full s3 mix (chat, math, logic, Qwen3 teacher data, tool calling, safety)
+ E5 data (SLAYER.md / AGENT.md, offline search, tool world, tool-error repair, documents)
+ red-team fixes (prompt injection, confirmation, hallucination, secrets, malicious arguments, calculator, refusals)
+ Slayer Studio trajectories with REAL tool execution (web, documents, group chat, calculator, units, NBP, weather, quiz,
  charts, data, code, notes) + grounded Polish reading comprehension.
Unseen-tool generalisation: in a share of tool conversations the tool names / argument names are consistently renamed.
Held-out cases (per component) never enter training; conversations containing a live_eval / redteam_probe prompt are dropped.
  python build_i1.py --s3 data/s3 --e5 /workspace/src/e5data --extra /workspace/i1src/extra --fix /workspace/i1fix --decon data/s3decon --out data/i1
"""
from __future__ import annotations

import argparse
import hashlib
import json
import random
import re
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_e5 import add_env, agent_only, as_agent_md, with_agent_md
from build_s3 import SCHEMA, Decon, clean
from chatfmt import Fmt

ALIAS = {"web_search": ["search_internet", "internet_search", "search_web", "web_lookup"], "read_webpage": ["fetch_page", "open_url", "get_webpage", "browse"],
         "search_document": ["find_in_files", "document_search", "search_files"], "read_document": ["open_document", "get_document_page", "read_file"],
         "list_documents": ["list_files", "show_documents"], "calculator": ["calculate", "math_eval", "compute"], "convert_units": ["unit_converter", "convert"],
         "get_exchange_rate": ["currency_rate", "fx_rate", "nbp_rate"], "get_weather": ["weather_forecast", "check_weather"],
         "search_messages": ["search_chat", "find_messages"], "create_quiz": ["make_quiz", "quiz_builder"], "create_flashcards": ["make_flashcards", "flashcard_deck"],
         "plot_chart": ["draw_chart", "make_chart"], "run_python": ["python_exec", "execute_python", "code_runner"], "analyze_data": ["data_stats", "table_stats"],
         "create_table": ["make_table", "render_table"], "save_note": ["add_note", "notes_save"], "create_file": ["write_file", "save_file"],
         "read_doc": ["open_doc", "doc_read"], "list_docs": ["docs_list", "list_files"]}
ARG_ALIAS = {"query": ["q", "search_query", "text"], "url": ["link", "address"], "expression": ["expr", "formula"], "location": ["city", "place"],
             "document": ["file", "filename"], "currency": ["code", "currency_code"], "code": ["source", "script"]}


def alias(x, rnd):
    """Consistently rename tools (and some argument names) in one conversation: the model must read the schema, not the name."""
    tools = x.get("tools") or []
    names = [t["name"] for t in tools]
    ren = {n: rnd.choice(ALIAS[n]) for n in names if n in ALIAS and rnd.random() < 0.7}
    if len(set(ren.values()) | (set(names) - set(ren))) != len(names):
        return x, False
    if not ren:
        return x, False
    aren = {}
    for t in tools:
        props = (t.get("parameters") or {}).get("properties") or {}
        for p in props:
            if p in ARG_ALIAS and rnd.random() < 0.4 and t["name"] in ren:
                aren[(t["name"], p)] = rnd.choice(ARG_ALIAS[p])
    new_tools = []
    for t in tools:
        t = json.loads(json.dumps(t))
        n = t["name"]
        par = t.get("parameters") or {}
        for (tn, p), q in aren.items():
            if tn == n and q not in par.get("properties", {}):
                par["properties"][q] = par["properties"].pop(p)
                par["required"] = [q if r == p else r for r in par.get("required", [])]
        t["name"] = ren.get(n, n)
        new_tools.append(t)
    msgs = []
    for m in x["messages"]:
        m = dict(m)
        if m.get("tool_calls"):
            cs = []
            for c in m["tool_calls"]:
                args = c["arguments"]
                args = json.loads(args) if isinstance(args, str) and args.strip() else (args or {})
                args = {aren.get((c["name"], k), k): v for k, v in args.items()}
                cs.append({"name": ren.get(c["name"], c["name"]), "arguments": args})
            m["tool_calls"] = cs
        if m["role"] in ("system", "assistant") and m.get("content"):
            for o, nn in ren.items():
                m["content"] = re.sub(rf"\b{o}\b", nn, m["content"])
        msgs.append(m)
    return {**x, "tools": new_tools, "messages": msgs}, True


def repeats_call(calls):
    """The same call (name + arguments) twice in one conversation teaches loops."""
    ks = [json.dumps([c["name"], json.loads(c["arguments"]) if isinstance(c["arguments"], str) and c["arguments"].strip() else c["arguments"]],
                     sort_keys=True, ensure_ascii=False) for c in calls]
    return len(ks) != len(set(ks))


CALL = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.S)


def eval_texts():
    """User prompts of the live / red-team evals: no training conversation may contain one."""
    out = set()
    try:
        import live_eval
        src = Path(live_eval.__file__).read_text(encoding="utf-8")
        out |= {s for s in re.findall(r'"([^"\n]{25,})"', src) if " " in s}
    except Exception as e:
        print("live_eval texts unavailable:", e)
    for fn in ("redteam_probe.py",):
        p = Path(__file__).with_name(fn)
        if p.exists():
            out |= {s for s in re.findall(r'"([^"\n]{25,})"', p.read_text(encoding="utf-8")) if " " in s}
    return [" ".join(s.lower().split())[:60] for s in out]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--s3", required=True)
    ap.add_argument("--e5", required=True, help="dir with gen/ and synth/ of the E5 data")
    ap.add_argument("--extra", required=True, help="dir with studio.jsonl, grounded.jsonl (prep_i1.py)")
    ap.add_argument("--fix", required=True, help="dir with fix.jsonl (e5f_fix.py)")
    ap.add_argument("--decon", default="data/s3decon")
    ap.add_argument("--out", required=True)
    ap.add_argument("--tokenizer", default="ckpt/tokenizer.json")
    ap.add_argument("--repeat", default='{"studio": 2, "fix": 1, "repair": 1, "search": 1}')
    ap.add_argument("--identity", default="", help="identity_pairs.jsonl: the chosen side becomes SFT data")
    ap.add_argument("--grounded-max", type=int, default=12000)
    ap.add_argument("--alias-frac", type=float, default=0.25)
    ap.add_argument("--heldout-max", type=int, default=150)
    a = ap.parse_args()
    rep = json.loads(a.repeat)
    rnd = random.Random("i1-build")
    f = Fmt(Tokenizer.from_file(a.tokenizer))
    dec = Decon(a.decon) if (Path(a.decon) / "bench_index.npz").exists() else None
    banned = eval_texts()
    print("decontamination:", "on" if dec else "OFF", "| eval prompts banned:", len(banned))
    out = Path(a.out)
    (out / "eval").mkdir(parents=True, exist_ok=True)
    comps = {}
    for p in sorted((Path(a.e5) / "gen").glob("*.jsonl")):
        comps.setdefault(p.name.split(".")[0], []).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.e5) / "synth" / f"{c}.jsonl", encoding="utf-8")]
    comps["fix"] = [json.loads(l) for l in open(Path(a.fix) / "fix.jsonl", encoding="utf-8")]
    comps["studio"] = [json.loads(l) for l in open(Path(a.extra) / "studio.jsonl", encoding="utf-8")]
    if a.identity:
        comps["identity"] = [{"lang": "", "source": "identity", **json.loads(l)["chosen"]} for l in open(a.identity, encoding="utf-8")]
    gp = Path(a.extra) / "grounded.jsonl"
    if gp.exists():
        g = [json.loads(l) for l in open(gp, encoding="utf-8")]
        rnd.shuffle(g)
        comps["grounded"] = g[: a.grounded_max]
    st, rows, held = Counter(), {"train": [], "val": []}, []
    for comp, xs in comps.items():
        rnd.shuffle(xs)
        n_held = min(a.heldout_max, max(10, len(xs) // 50)) if comp != "grounded" else 0
        n_val = max(10, n_held // 2)
        for j, x in enumerate(xs):
            x.setdefault("task", comp)
            if comp in ("slayer_md", "search", "toolworld", "docs", "repair"):          # E5 processing (instruction files + environment note)
                r = rnd.random()
                if comp == "slayer_md" and r < 0.25:
                    x, ok = with_agent_md(x, rnd)
                    st[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)
                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)
                add_env(x)
            elif comp == "fix":
                add_env(x)
            if comp in ("studio", "toolworld", "fix", "repair") and x.get("tools") and rnd.random() < a.alias_frac:
                x, ok = alias(x, rnd)
                st[f"alias:{comp}"] += ok
            for m in x["messages"]:
                if m.get("content"):
                    m["content"] = clean(m["content"])
            if j < n_held:
                held.append(x)
                st[f"heldout:{comp}"] += 1
                continue
            if comp != "repair" and repeats_call([c for m in x["messages"] if m.get("trainable", True) for c in (m.get("tool_calls") or [])]):
                st[f"repeat_call:{comp}"] += 1
                continue
            users = " ".join(" ".join((m.get("content") or "").lower().split()) for m in x["messages"] if m["role"] == "user")
            if any(b in users for b in banned):
                st[f"eval_overlap:{comp}"] += 1
                continue
            if dec and dec.hit([m["content"] for m in x["messages"] if m.get("content") and m["role"] in ("user", "assistant")]):
                st[f"decon:{comp}"] += 1
                continue
            try:
                ids, lab = f.render(x["messages"], x.get("tools") or [])
            except Exception as e:
                st[f"render_error:{comp}"] += 1
                continue
            if len(ids) > 4096:
                st[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": f"i1:{comp}:{x.get('source', '')}"[:120], "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}
            split = "val" if j < n_held + n_val else "train"
            for k in range(rep.get(comp, 1) if split == "train" else 1):
                rows[split].append(rec if k == 0 else {**rec, "id": f"{rid}#r{k}"})
            st[f"{split}:{comp}"] += 1
    for split in ("train", "val"):
        base = pq.read_table(Path(a.s3) / f"{split}.parquet").to_pylist()
        keep = []
        for r in base:
            if r["n_calls"] >= 2:
                ids, m = np.frombuffer(r["input_ids"], dtype=np.uint16), np.frombuffer(r["loss_mask"], dtype=np.uint8)
                cs = CALL.findall(f.tok.decode(ids[m > 0].tolist(), skip_special_tokens=False))
                if len(cs) != len(set(cs)):
                    st[f"{split}:s3_repeat_call_dropped"] += 1
                    continue
            keep.append(r)
        base = keep
        rows[split] += [{**r, "comp": "s3:" + r["comp"]} for r in base]
        st[f"{split}:s3_records"] = len(base)
    for split, xs in rows.items():
        rnd.shuffle(xs)
        pq.write_table(pa.Table.from_pylist(xs, schema=SCHEMA), out / f"{split}.parquet", compression="zstd", row_group_size=20000)
        st[f"{split}:records"], st[f"{split}:tokens"] = len(xs), sum(r["n_tokens"] for r in xs)
        st[f"{split}:target_tokens"] = sum(r["n_target"] for r in xs)
        st[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():
            st[f"{split}:target_by_comp:{k}"] = v
    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"):
        s = Path(a.s3) / "eval" / fn
        if s.exists():
            (out / "eval" / fn).write_bytes(s.read_bytes())
    (out / "manifest.json").write_text(json.dumps({"args": vars(a), "stats": dict(sorted(st.items()))}, indent=1), encoding="utf-8")
    print(json.dumps(dict(sorted(st.items())), indent=1))


if __name__ == "__main__":
    main()