File size: 16,226 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""E5 search trajectories on an OFFLINE index (free, unlimited, no scraping): the teacher (Qwen3, vLLM) plays the agent with

the exact web_search / open_page formats of the local chat, against a BM25 index of Wikipedia paragraphs; only trajectories

whose final answer contains the gold answer are kept.



Index: HotpotQA distractor train paragraphs (each question brings its 2 gold + 8 distractor Wikipedia paragraphs; CC-BY-SA-4.0),

PoQuAD train contexts and PolQA passages (Polish; CC-BY-4.0 / CC-BY-SA-4.0). Pages are grouped by title, served as

https://{en|pl}.wikipedia.org/wiki/<Title>.

Questions: HotpotQA (multi-hop EN), PoQuAD + PolQA (PL), each with its answer key.

Patterns: search -> answer from snippets; search -> open_page -> answer with the source url; rephrase after weak results;

two-turn "co to jest X?" -> honest "not sure" -> "wyszukaj to w internecie" -> search built from the earlier topic.



  python e5_search.py index --src /workspace/s3src --out /workspace/e5idx                (CPU)

  CUDA_VISIBLE_DEVICES=i python e5_search.py run --idx /workspace/e5idx --shard i --nshard 8 --out /workspace/e5gen

"""
from __future__ import annotations

import argparse
import hashlib
import json
import pickle
import random
import re
import time
import unicodedata
import urllib.parse
from pathlib import Path

WEB = {"name": "web_search", "description": "Search the web. Returns the top results: title, url and a short snippet.",
       "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}
OPEN = {"name": "open_page", "description": "Open a web page by its url and return its title and the beginning of its text.",
        "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}


def norm(s):
    s = unicodedata.normalize("NFKC", str(s)).lower()
    return " ".join(re.sub(r"[^\w\s]", " ", s).split())


# ------------------------------------------------------------------ index
def build_index(src, out):
    import bm25s
    from datasets import load_dataset
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    pages, qs = {}, []                     # (lang, title) -> text
    hq = load_dataset("hotpotqa/hotpot_qa", "distractor", split="train")
    for r in hq:
        for t, sents in zip(r["context"]["title"], r["context"]["sentences"]):
            pages.setdefault(("en", t), " ".join(s.strip() for s in sents))
        qs.append({"lang": "en", "q": r["question"], "gold": [r["answer"]], "src": "hotpotqa", "level": r["level"]})
    d = json.load(open(Path(src) / "clarin-pl__poquad/poquad-train.json", encoding="utf-8"))
    for art in d["data"]:
        title = art.get("title") or art["paragraphs"][0]["context"][:40]
        txt = " ".join(p["context"] for p in art["paragraphs"])
        pages.setdefault(("pl", title), txt)
        for p in art["paragraphs"]:
            for q in p["qas"]:
                if q.get("answers") and not q.get("is_impossible"):
                    a = q["answers"][0]
                    qs.append({"lang": "pl", "q": q["question"], "gold": [a.get("generative_answer") or a["text"], a["text"]], "src": "poquad"})
    try:
        pq = load_dataset("ipipan/polqa", "pairs", split="train")
        for r in pq:
            if r.get("passage_title") and r.get("passage_text"):
                key = ("pl", r["passage_title"])
                pages[key] = (pages.get(key, "") + " " + r["passage_text"]).strip()[:20000]
            if r.get("relevant") and r.get("answers"):
                ans = r["answers"] if isinstance(r["answers"], list) else [r["answers"]]
                qs.append({"lang": "pl", "q": r["question"], "gold": [str(x) for x in ans if x], "src": "polqa"})
    except Exception as e:
        print("polqa skipped:", e)
    keys = list(pages)
    corpus = [f"{t}. {pages[(l, t)][:1500]}" for l, t in keys]
    print("pages", len(keys), "questions", len(qs), flush=True)
    retr = bm25s.BM25()
    retr.index(bm25s.tokenize(corpus, stopwords=None))
    retr.save(str(out / "bm25"))
    pickle.dump({"keys": keys, "pages": pages}, open(out / "pages.pkl", "wb"))
    seen, uq = set(), []
    for q in qs:
        k = norm(q["q"])
        if k not in seen and q["gold"] and all(len(g) < 80 for g in q["gold"]):
            seen.add(k)
            uq.append(q)
    with open(out / "questions.jsonl", "w", encoding="utf-8") as f:
        for q in uq:
            f.write(json.dumps(q, ensure_ascii=False) + "\n")
    print("questions kept", len(uq))


class Index:
    def __init__(self, d):
        import bm25s
        self.r = bm25s.BM25.load(str(Path(d) / "bm25"))
        z = pickle.load(open(Path(d) / "pages.pkl", "rb"))
        self.keys, self.pages = z["keys"], z["pages"]
        self.by_url = {self.url(k): k for k in self.keys}

    @staticmethod
    def url(k):
        return f"https://{k[0]}.wikipedia.org/wiki/" + urllib.parse.quote(k[1].replace(" ", "_"))

    def search(self, q, k=5):
        import bm25s
        if not q.strip():
            return {"error": "empty query"}
        ids, scores = self.r.retrieve(bm25s.tokenize([q], stopwords=None, show_progress=False), k=k, show_progress=False)
        out = []
        for i, s in zip(ids[0], scores[0]):
            if s <= 0:
                continue
            key = self.keys[int(i)]
            txt = self.pages[key]
            out.append({"title": f"{key[1]} – Wikipedia", "url": self.url(key), "domain": f"{key[0]}.wikipedia.org", "snippet": txt[:200]})
        return {"query": q, "results": out} if out else {"query": q, "results": [], "note": "no results"}

    def open(self, u):
        key = self.by_url.get(u) or self.by_url.get(urllib.parse.unquote(u))
        if not key:
            return {"error": f"page not found: {u}"}
        return {"url": u, "title": f"{key[1]} – Wikipedia", "description": "", "text": self.pages[key][:1500]}


# ------------------------------------------------------------------ teacher agent
AGENT_SYS = {
    "en": ("You are a careful research agent with two tools:\n- web_search(query): returns up to 5 results (title, url, snippet)\n"
           "- open_page(url): returns the page text (first 1500 characters)\n"
           "Answer the user's question using ONLY information from tool results. Reply each turn with exactly one JSON object and nothing else:\n"
           '{"action": "web_search", "query": "..."} or {"action": "open_page", "url": "..."} or {"action": "answer", "text": "..."}\n'
           "Search with a precise query, open a page when the snippets are not enough, at most 4 tool calls, then answer briefly in English "
           "and name the source page (url). If the information is not found, say so."),
    "pl": ("Jesteś starannym agentem badawczym z dwoma narzędziami:\n- web_search(query): zwraca do 5 wyników (tytuł, url, opis)\n"
           "- open_page(url): zwraca tekst strony (pierwsze 1500 znaków)\n"
           "Odpowiadaj na pytanie użytkownika WYŁĄCZNIE na podstawie wyników narzędzi. W każdej turze zwróć dokładnie jeden obiekt JSON i nic więcej:\n"
           '{"action": "web_search", "query": "..."} albo {"action": "open_page", "url": "..."} albo {"action": "answer", "text": "..."}\n'
           "Szukaj precyzyjnym zapytaniem, otwórz stronę, gdy opisy nie wystarczą, najwyżej 4 wywołania, potem odpowiedz krótko po polsku "
           "i podaj stronę źródłową (url). Jeśli nie znalazłeś informacji, powiedz to.")}
NOT_SURE = {"pl": ["Nie jestem pewien, nie mam o tym wiarygodnych informacji. Mogę to wyszukać w internecie.",
                   "Nie wiem tego na pewno i nie chcę zgadywać. Jeśli chcesz, sprawdzę to w sieci."],
            "en": ["I'm not sure and I don't want to guess. I can search the web for it.", "I don't know that reliably. Want me to look it up?"]}
FOLLOW = {"pl": ["Wyszukaj to w internecie", "Sprawdź to w sieci", "No to poszukaj", "Wyszukaj proszę"], "en": ["Search the web for it", "Look it up", "Please search for it"]}


def contains_gold(text, gold):
    t = norm(text)
    return any(norm(g) and norm(g) in t for g in gold)


def run(a):
    from vllm import LLM, SamplingParams
    from chatfmt import parse_calls  # noqa: F401  (format reference)
    import synth_tools as ST
    idx = Index(a.idx)
    qs = [json.loads(l) for l in open(Path(a.idx) / "questions.jsonl", encoding="utf-8")]
    rnd = random.Random(f"e5s-{a.shard}")
    rnd.shuffle(qs)
    en = [q for q in qs if q["lang"] == "en"][: a.n_en]
    pl = [q for q in qs if q["lang"] == "pl"][: a.n_pl]
    mine = [q for i, q in enumerate(en + pl) if i % a.nshard == a.shard]
    llm = LLM("/workspace/models/Qwen3-8B", dtype="bfloat16", max_model_len=8192, gpu_memory_utilization=0.90, seed=a.shard)
    sp = SamplingParams(temperature=0.5, top_p=0.9, max_tokens=300)
    log = lambda *x: print(time.strftime("%H:%M:%S"), f"[shard {a.shard}]", *x, flush=True)
    states = [{"q": q, "msgs": [{"role": "system", "content": AGENT_SYS[q["lang"]]}, {"role": "user", "content": q["q"]}], "steps": [], "done": False} for q in mine]
    for step in range(5):
        live = [s for s in states if not s["done"]]
        if not live:
            break
        outs = llm.chat([s["msgs"] for s in live], sp, chat_template_kwargs={"enable_thinking": False}, use_tqdm=False)
        for s, o in zip(live, outs):
            t = re.sub(r"^```(json)?|```$", "", o.outputs[0].text.strip()).strip()
            try:
                act = json.loads(t[t.find("{"): t.rfind("}") + 1])
            except Exception:
                s["done"], s["fail"] = True, "parse"
                continue
            s["msgs"].append({"role": "assistant", "content": json.dumps(act, ensure_ascii=False)})
            if act.get("action") == "answer" or step == 4:
                s["answer"], s["done"] = str(act.get("text", "")), True
                continue
            if act.get("action") == "web_search":
                res = idx.search(str(act.get("query", "")))
                s["steps"].append(("web_search", {"query": str(act.get("query", ""))}, res))
            elif act.get("action") == "open_page":
                res = idx.open(str(act.get("url", "")))
                s["steps"].append(("open_page", {"url": str(act.get("url", ""))}, res))
            else:
                s["done"], s["fail"] = True, "bad_action"
                continue
            s["msgs"].append({"role": "user", "content": "Tool result: " + json.dumps(res, ensure_ascii=False)[:2500]})
        log("step", step, "live", sum(not s["done"] for s in states))
    import doc_tools as DT
    good = [s for s in states if s["steps"] and s.get("answer") and contains_gold(s["answer"], s["q"]["gold"])]
    # confident answers from memory (no tools) for a share of the questions: the masked bad first turn of a correction chain
    hal_idx = [i for i in range(len(good)) if rnd.random() < 0.3]
    hal = llm.chat([[{"role": "system", "content": "Odpowiedz pewnie i konkretnie w 1-2 zdaniach, nawet jeśli musisz zgadywać. Nie mów, że nie wiesz."
                      if good[i]["q"]["lang"] == "pl" else "Answer confidently and concretely in 1-2 sentences, even if you have to guess. Do not say you don't know."},
                     {"role": "user", "content": good[i]["q"]["q"]}] for i in hal_idx],
                   SamplingParams(temperature=0.9, top_p=0.95, max_tokens=120), chat_template_kwargs={"enable_thinking": False}, use_tqdm=False)
    hal_by = {i: o.outputs[0].text.strip() for i, o in zip(hal_idx, hal) if o.outputs[0].finish_reason == "stop"
              and not contains_gold(o.outputs[0].text, good[i]["q"]["gold"]) and not re.search(r"nie wiem|nie jestem pewn|i don.t know|not sure", o.outputs[0].text, re.I)}
    GENERIC_MD = {"pl": ["# SLAYER.md\n## Użytkownik\nMa na imię {n}. Odpowiadaj krótko, po polsku.\n## Zasady\nGdy czegoś nie wiesz, sprawdź to w sieci i podaj źródło.",
                         "# SLAYER.md\n## O mnie\nJestem {n}, piszę po polsku.\n## Preferencje\nKrótkie odpowiedzi, bez list. Podawaj link do źródła."],
                  "en": ["# SLAYER.md\n## User\nName: {n}. Answer briefly in English.\n## Rules\nIf you do not know something, look it up and cite the source."]}
    CHECK = {"pl": ["Możesz to sprawdzić?", "Na pewno? Sprawdź to.", "Możesz wyszukać te informacje?", "Sprawdź to w internecie."],
             "en": ["Can you check that?", "Are you sure? Please check.", "Can you look that up?"]}
    FIX = {"pl": "Sprawdziłem i wcześniej się pomyliłem. ", "en": "I checked, and I was wrong before. "}
    fo = open(Path(a.out) / f"search.s{a.shard}.jsonl", "w", encoding="utf-8")
    kept = 0
    for gi, s in enumerate(good):
        q, ans = s["q"], s["answer"]
        lang = q["lang"]
        nm = rnd.choice(["Marta", "Kuba", "Ola", "Paweł", "Emma", "Liam"])
        ws = rnd.choices(["none", "no_files", "slayer"], [35, 30, 35])[0]
        md = rnd.choice(GENERIC_MD[lang]).replace("{n}", nm)
        msgs = []
        if ws != "none":
            msgs.append({"role": "system", "content": DT.workspace_note(["SLAYER.md"] if ws == "slayer" else [], lang)})
        variant = "halluc" if gi in hal_by else ("two_turn" if rnd.random() < 0.2 else "direct")
        if variant == "halluc":
            msgs += [{"role": "user", "content": q["q"]}, {"role": "assistant", "content": hal_by[gi], "trainable": False}, {"role": "user", "content": rnd.choice(CHECK[lang])}]
        elif variant == "two_turn":
            msgs += [{"role": "user", "content": q["q"]}, {"role": "assistant", "content": rnd.choice(NOT_SURE[lang])}, {"role": "user", "content": rnd.choice(FOLLOW[lang])}]
        else:
            msgs.append({"role": "user", "content": q["q"]})
        if ws == "slayer":       # file listed -> read once first; it does not have the answer -> go to the web
            msgs += [{"role": "assistant", "content": "", "tool_calls": [ST.call("read_doc", {"name": "SLAYER.md"})]},
                     {"role": "tool", "content": json.dumps(DT.execute("read_doc", {"name": "SLAYER.md"}, {"SLAYER.md": md}), ensure_ascii=False)}]
        for name, args, res in s["steps"]:
            msgs.append({"role": "assistant", "content": "", "tool_calls": [ST.call(name, args)]})
            msgs.append({"role": "tool", "content": json.dumps(res, ensure_ascii=False)})
        msgs.append({"role": "assistant", "content": (FIX[lang] + ans) if variant == "halluc" else ans})
        tools = [WEB, OPEN] + ([DT.READ_DOC, DT.LIST_DOCS] if ws != "none" else [])
        tools += [{"name": n, **ST.TOOLS[n]} for n in rnd.sample(list(ST.TOOLS), rnd.randint(1, 3))]
        rnd.shuffle(tools)
        rid = hashlib.sha1(json.dumps(msgs, ensure_ascii=False).encode()).hexdigest()[:16]
        fo.write(json.dumps({"id": f"search-{rid}", "task": "search", "lang": lang, "messages": msgs, "tools": tools, "gold": q["gold"],
                             "slayer_md": md if ws == "slayer" else "", "workspace": ws, "variant": variant,
                             "source": q["src"], "teacher": "Qwen/Qwen3-8B@b968826d9c", "n_calls": len(s["steps"])}, ensure_ascii=False) + "\n")
        kept += 1
    fo.close()
    log("kept", kept, "/", len(states), "SHARD_DONE")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["index", "run"])
    ap.add_argument("--src", default="/workspace/s3src")
    ap.add_argument("--idx", default="/workspace/e5idx")
    ap.add_argument("--out", default="/workspace/e5gen")
    ap.add_argument("--shard", type=int, default=0)
    ap.add_argument("--nshard", type=int, default=8)
    ap.add_argument("--n-en", type=int, default=24000)
    ap.add_argument("--n-pl", type=int, default=24000)
    a = ap.parse_args()
    if a.cmd == "index":
        build_index(a.src, a.idx)
    else:
        Path(a.out).mkdir(parents=True, exist_ok=True)
        run(a)


if __name__ == "__main__":
    main()