File size: 11,079 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
"""I1 stage 2 (short product SFT from the stage-1 model): one tool call per turn, abstention with the REAL tool set, product tasks.
Fixes two data defects of stage 1 (found 2026-11-30):
  * 63% of the Studio conversations with calls had several calls in one assistant turn -> split into single-call steps, each
    followed by its own real result (the results are unchanged; a turn whose results cannot be paired with its calls is dropped)
  * the 132k "tools offered, answer directly" rows never offered web_search / calculator / ... -> new abstention rows do
Mix: studio (split), E5 search/docs/repair/toolworld/slayer_md, red-team fix, identity, abstention with real tools, and a replay
of stage-1 chat / math / single-call tool rows so nothing is forgotten. Held-out cases of stage 1 stay out.
  python build_i2.py --i1 data/i1 --studio /workspace/i1src/extra/studio.jsonl --out data/i2
"""
import argparse
import hashlib
import json
import random
import re
from collections import Counter, defaultdict
from datetime import date, timedelta
from pathlib import Path

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from tokenizers import Tokenizer

from build_i1 import alias, eval_texts, repeats_call
from build_s3 import SCHEMA, Decon, clean
from chatfmt import Fmt
from live_eval import SYS, TOOLS

CAP = {"repair": 2500, "fix": 4000, "docs": 1900, "search": 2900, "toolworld": 1600, "slayer_md": 1500, "identity": 872}   # distinct rows per component
REPLAY = {"s3:chat:pl": 7000, "s3:chat:en": 6000, "s3:math_pl": 3000, "s3:math_en": 2000, "s3:math_aug": 1000, "s3:tool": 5000, "s3:agent": 3000,
          "s3:arith": 1000, "s3:logic": 800, "s3:poquad": 1500, "s3:squad": 800, "s3:know": 1500}
ABSTAIN_SRC = {"s3:instruct": 4000, "s3:humor": 1500, "s3:safety": 2500, "s3:multiturn": 7000, "s3:poquad": 2500, "s3:squad": 1000, "s3:chat:pl": 6000, "s3:chat:en": 5000}
SYSX = {"pl": [SYS["pl"], "Jesteś Slayer, lokalny asystent AI. Pomagasz krótko i konkretnie, po polsku lub angielsku — tak, jak pisze użytkownik. Narzędzi używaj tylko w razie potrzeby.",
               "Jesteś pomocnym asystentem Slayer. Odpowiadasz w języku rozmówcy, zwięźle. Gdy potrzebujesz danych z plików, internetu albo obliczeń, użyj narzędzia.", ""],
        "en": [SYS["en"], "You are Slayer, a local AI assistant. Help briefly and concretely, in Polish or English. Use tools only when needed.", ""]}


def split_calls(msgs):
    out, i = [], 0
    while i < len(msgs):
        m = msgs[i]
        cs = m.get("tool_calls") or []
        if m["role"] == "assistant" and len(cs) > 1:
            res = []
            j = i + 1
            while j < len(msgs) and msgs[j]["role"] == "tool":
                res.append(msgs[j])
                j += 1
            if len(res) != len(cs):
                return None
            for k, (c, r) in enumerate(zip(cs, res)):
                out += [{**m, "content": m.get("content", "") if k == 0 else "", "tool_calls": [c]}, r]
            i = j
        else:
            out.append(m)
            i += 1
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--i1", default="data/i1")
    ap.add_argument("--studio", default="/workspace/i1src/extra/studio.jsonl")
    ap.add_argument("--decon", default="data/s3decon")
    ap.add_argument("--out", default="data/i2")
    ap.add_argument("--tokenizer", default="ckpt/tokenizer.json")
    ap.add_argument("--studio-repeat", type=int, default=3)
    a = ap.parse_args()
    rnd = random.Random("i2-build")
    f = Fmt(Tokenizer.from_file(a.tokenizer))
    dec, banned, st = Decon(a.decon), eval_texts(), Counter()
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    held = {json.dumps([m["content"] for m in json.loads(l)["messages"] if m["role"] == "user"], ensure_ascii=False)
            for l in open(Path(a.i1) / "heldout.jsonl", encoding="utf-8")}
    rows = []

    def add(comp, msgs, tools, lang, src, n=1):
        ids, lab = f.render(msgs, tools or [])
        if len(ids) > 4096:
            st[f"too_long:{comp}"] += 1
            return
        nc = sum(len(m.get("tool_calls") or []) for m in msgs)
        rid = comp + "-" + hashlib.sha1(json.dumps(msgs, 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": src, "comp": comp, "language": lang, "is_tool": nc > 0, "n_target": int(sum(v != -100 for v in lab)), "n_calls": nc}
        for k in range(n):
            rows.append(rec if k == 0 else {**rec, "id": f"{rid}#r{k}"})
        st[f"rows:{comp}"] += n

    for l in open(a.studio, encoding="utf-8"):
        x = json.loads(l)
        for m in x["messages"]:
            if m.get("content"):
                m["content"] = clean(m["content"])
        if json.dumps([m["content"] for m in x["messages"] if m["role"] == "user"], ensure_ascii=False) in held:
            st["studio_heldout_skipped"] += 1
            continue
        users = " ".join(" ".join((m["content"] or "").lower().split()) for m in x["messages"] if m["role"] == "user")
        if any(b in users for b in banned) or dec.hit([m["content"] for m in x["messages"] if m.get("content") and m["role"] in ("user", "assistant")]):
            st["studio_eval_overlap"] += 1
            continue
        par = any(len(m.get("tool_calls") or []) > 1 for m in x["messages"])
        msgs = split_calls(x["messages"])
        if msgs is None:
            st["studio_unpairable"] += 1
            continue
        if repeats_call([c for m in msgs for c in (m.get("tool_calls") or [])]):
            st["studio_repeat"] += 1
            continue
        st["studio_parallel_split"] += par
        for k in range(a.studio_repeat):              # each copy is a different view: tool names / arguments renamed in some copies
            y = {"messages": msgs, "tools": x["tools"]}
            if k and x["tools"]:
                y, _ = alias(y, rnd)
            add("studio", y["messages"], y["tools"], x.get("lang", ""), x["source"])

    t = pq.read_table(Path(a.i1) / "train.parquet").to_pylist()
    by = defaultdict(list)
    for r in t:
        if "#r" not in r["id"]:
            by[r["comp"]].append(r)
    for c, n in CAP.items():
        xs = by[c]
        rnd.shuffle(xs)
        rows += xs[:n]
        st[f"rows:{c}"] += len(xs[:n])
    tok = f.tok
    used = set()
    for c, n in REPLAY.items():
        xs = by[c]
        rnd.shuffle(xs)
        k = 0
        for r in xs:
            if k >= n:
                break
            if r["is_tool"]:                           # replay only single-call turns
                m = np.frombuffer(r["loss_mask"], dtype=np.uint8)
                s = tok.decode(np.frombuffer(r["input_ids"], dtype=np.uint16)[m > 0].tolist(), skip_special_tokens=False)
                if any(x.count("<tool_call>") > 1 for x in s.split("<|im_end|>")):
                    continue
            rows.append(r)
            used.add(r["id"])
            k += 1
        st[f"rows:replay:{c}"] += k

    # abstention with the real tool set: same conversation, real tools offered, answered directly
    sys_head = [f.ims] + f.enc("system\n")
    names = list(TOOLS)
    d0 = date(2026, 11, 1)
    # requests that a real web_search / calculator SHOULD serve must not become abstention examples
    needs = re.compile(r"(wyszukaj|poszukaj|sprawdź w|znajdź w|w internecie|aktualn|dzisiaj|najnowsz|kurs |pogod|oblicz|ile to|policz|search|look up|latest|current|today|weather|calculate|"
                       r"exchange rate|\bwho (is|was)\b|\bkto (jest|był)\b|\bw którym roku\b|\bin which year\b|\bile (wynosi|ma|jest)\b|how many|\d\s*[\*\+×/÷-]\s*\d)", re.I)
    for c, n in ABSTAIN_SRC.items():
        xs = [r for r in by[c] if r["id"] not in used]
        rnd.shuffle(xs)
        k = 0
        for r in xs:
            if k >= n:
                break
            ids = np.frombuffer(r["input_ids"], dtype=np.uint16).tolist()
            if ids[1:1 + len(sys_head)] == sys_head or r["n_tokens"] > 2600:
                continue
            m = np.frombuffer(r["loss_mask"], dtype=np.uint8).tolist()
            ctx = tok.decode([x for x, y in zip(ids, m) if not y], skip_special_tokens=False)
            if needs.search(ctx) and c not in ("s3:poquad", "s3:squad"):
                st[f"abstain_skipped_needs_tool:{c}"] += 1
                continue
            lang = "pl" if re.search(r"[ąćęłńśźż]", ctx) else "en"
            ts = rnd.sample(names, rnd.randint(2, 6))
            if "web_search" not in ts and rnd.random() < 0.7:
                ts.append("web_search")
            if rnd.random() < 0.4 and "calculator" not in ts:
                ts.append("calculator")
            rnd.shuffle(ts)
            day = (d0 + timedelta(days=rnd.randint(0, 120))).isoformat()
            s = rnd.choice(SYSX[lang])
            note = (f"Data: {day}. Sieć: online." if lang == "pl" else f"Date: {day}. Network: online.") if rnd.random() < 0.7 else ""
            txt = "\n\n".join(x for x in (s, note, f.tools_block([TOOLS[x] for x in ts])) if x)
            ins = sys_head + f.enc(txt) + [f.ime] + f.nl
            ids2, m2 = ids[:1] + ins + ids[1:], m[:1] + [0] * len(ins) + m[1:]
            if len(ids2) > 4096:
                continue
            rows.append({**r, "id": r["id"] + "+realtools", "input_ids": np.array(ids2, dtype=np.uint16).tobytes(), "loss_mask": np.array(m2, dtype=np.uint8).tobytes(),
                         "n_tokens": len(ids2), "comp": "abstain_real:" + c})
            k += 1
        st[f"rows:abstain_real:{c}"] += k
    rnd.shuffle(rows)
    pq.write_table(pa.Table.from_pylist([{k: r[k] for k in SCHEMA.names} for r in rows], schema=SCHEMA), out / "train.parquet", compression="zstd", row_group_size=20000)
    (out / "val.parquet").write_bytes((Path(a.i1) / "val.parquet").read_bytes())
    (out / "heldout.jsonl").write_bytes((Path(a.i1) / "heldout.jsonl").read_bytes())
    tg = Counter()
    par = 0
    for r in rows:
        tg[r["comp"].split(":")[0] if not r["comp"].startswith("s3:") else "replay"] += r["n_target"]
        if r["is_tool"]:
            m = np.frombuffer(r["loss_mask"], dtype=np.uint8)
            s = tok.decode(np.frombuffer(r["input_ids"], dtype=np.uint16)[m > 0].tolist(), skip_special_tokens=False)
            par += any(x.count("<tool_call>") > 1 for x in s.split("<|im_end|>"))
    st["train:records"], st["train:tokens"], st["train:target_tokens"] = len(rows), sum(r["n_tokens"] for r in rows), sum(r["n_target"] for r in rows)
    st["train:tool_records"], st["rows_with_parallel_calls"] = sum(r["is_tool"] for r in rows), par
    for k, v in tg.items():
        st[f"train:target_by_comp:{k}"] = v
    (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=0))


if __name__ == "__main__":
    main()