File size: 12,020 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
"""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()