"""E4 data: a light continuation of E3 aimed at the tasks where E3 dropped, plus Polish tool use. IN-DOMAIN (owner decision 2026-11-26): train splits of benchmarks that are also evaluated (test splits) are used, so results on PSC, DYK, PolEmo2-IN, CBD and MathQA after E4 measure fitted task format, not general ability, and are reported as in-domain. NC-licensed train sets (8TAGS, PPC: CC-BY-NC-SA) and LogiQA (licence "other") are not used. python e4_data.py --s3 data/s3 --decon /workspace/s3decon --out data/e4 [--replay-tokens 40e6] Components (chat format, loss on the answer): klej_psc / klej_dyk allegro/klej-psc, allegro/klej-dyk train (CC-BY-SA-3.0), prompt = the lm-eval task wording, answer Tak / Nie, classes balanced 50/50 polemo2_in allegro/klej-polemo2-in train (CC-BY-SA-4.0), answer = sentiment word cbd ptaszynski/PolishCyberbullyingDataset train (CC-BY-4.0), answer = category word (harmless class downsampled) mmlu_aux cais/mmlu auxiliary_train (MIT): question + lettered options -> "Odpowiedź/Answer: X. text", letters re-shuffled (uniform) mathqa allenai/math_qa train (Apache-2.0): problem + options -> answer letter + option text, letters re-shuffled pl_tools programmatic Polish-heavy tool loops with new tools (air_quality, sun_times, unit_convert, holiday_check), incl. tool errors and no-call turns; tools disjoint from the eval suite replay random sample of the E3 (s3) training rows, to keep chat / tool / math behaviour """ from __future__ import annotations import argparse import ast import csv import hashlib import io 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 huggingface_hub import hf_hub_download from tokenizers import Tokenizer from build_s3 import SCHEMA, Decon from chatfmt import Fmt REV = {"allegro/klej-psc": "9585582aef37e7747ef174b0ec3b74855da8bad2"} L = "ABCDE" def dl(repo, fn, rev=None): return hf_hub_download(repo, fn, repo_type="dataset", revision=rev, local_dir=f"/workspace/s3src/{repo.replace('/', '__')}") def read_csv(p, delim=","): return list(csv.DictReader(io.open(p, encoding="utf-8"), delimiter=delim)) def U(c): return {"role": "user", "content": c} def A(c): return {"role": "assistant", "content": c} def balance(xs, key, rnd, ratio=1.0): by = {} for x in xs: by.setdefault(key(x), []).append(x) m = min(len(v) for v in by.values()) out = [] for v in by.values(): rnd.shuffle(v) out += v[: int(m * ratio)] if len(by) == 2 else v[: max(m, int(len(v) * 0.5))] rnd.shuffle(out) return out def klej(rnd): out = [] psc = read_csv(dl("allegro/klej-psc", "train.csv", REV["allegro/klej-psc"])) psc = balance(psc, lambda r: int(r["label"]), rnd) for r in psc: q = (f"Tekst: \"{r['extract_text']}\"\nPodsumowanie: \"{r['summary_text']}\"\nPytanie: Czy podsumowanie dla podanego tekstu jest poprawne?\n" f"Odpowiedz krótko \"Tak\" lub \"Nie\".") out.append(("klej_psc", "pl", [U(q), A("Tak" if int(r["label"]) else "Nie")])) dyk = read_csv(dl("allegro/klej-dyk", "train.csv")) tk = "target" if "target" in dyk[0] else [k for k in dyk[0] if k not in ("question", "answer", "q_id")][0] dyk = balance(dyk, lambda r: int(r[tk]), rnd) for r in dyk: q = (f"Pytanie: \"{r['question']}\"\nSugerowana odpowiedź: \"{r['answer']}\"\nPytanie: Czy sugerowana odpowiedź na zadane pytanie jest poprawna?\n" f"Odpowiedz krótko \"Tak\" lub \"Nie\".") out.append(("klej_dyk", "pl", [U(q), A("Tak" if int(r[tk]) else "Nie")])) pe = read_csv(dl("allegro/klej-polemo2-in", "train.csv")) lab = {"__label__meta_zero": "Neutralny", "__label__meta_minus_m": "Negatywny", "__label__meta_plus_m": "Pozytywny", "__label__meta_amb": "Niejednoznaczny"} pe = [r for r in pe if r["target"] in lab] pe = balance(pe, lambda r: r["target"], rnd) for r in pe: q = f"Opinia: \"{r['sentence']}\"\nOkreśl sentyment podanej opinii: Neutralny, Negatywny, Pozytywny, Niejednoznaczny." out.append(("polemo2_in", "pl", [U(q), A(lab[r["target"]])])) cb = read_csv(dl("ptaszynski/PolishCyberbullyingDataset", "v2_training_anonymized.tsv"), "\t") cat = {"szyderstwo": "szyderstwo", "obelga": "obelga", "insynuacja": "insynuacja", "grozba": "groźba", "molestowanie": "molestowanie"} ck = "CATEGORIES" if "CATEGORIES" in cb[0] else [k for k in cb[0] if k.lower().startswith("categ")][0] tx = "TEXT" if "TEXT" in cb[0] else [k for k in cb[0] if k.lower().startswith("text")][0] cb = balance(cb, lambda r: cat.get(r[ck], "nieszkodliwa"), rnd) for r in cb: q = (f"Wypowiedź: \"{r[tx]}\"\nDo podanej wypowiedzi przyporządkuj jedną, najlepiej pasującą kategorię z podanych: nieszkodliwa, szyderstwo, " f"obelga, insynuacja, groźba, molestowanie.") out.append(("cbd", "pl", [U(q), A(cat.get(r[ck], "nieszkodliwa"))])) return out def mc(rnd, n_mmlu, n_mathqa): out = [] p = dl("cais/mmlu", "auxiliary_train/train-00000-of-00001.parquet") rows = pq.read_table(p).to_pylist() rows = [r.get("train", r) for r in rows] rnd.shuffle(rows) for r in rows[:n_mmlu]: ch, ans = list(r["choices"]), int(r["answer"]) if len(ch) < 2 or len(r["question"]) > 2500: continue order = list(range(len(ch))) rnd.shuffle(order) opts = "\n".join(f"{L[i]}. {ch[j]}" for i, j in enumerate(order)) k = order.index(ans) lang = "en" out.append(("mmlu_aux", lang, [U(f"{r['question'].strip()}\n{opts}\nAnswer with the letter of the correct option."), A(f"Answer: {L[k]}. {ch[ans]}")])) try: p = hf_hub_download("allenai/math_qa", "default/train/0000.parquet", repo_type="dataset", revision="refs/convert/parquet", local_dir="/workspace/s3src/allenai__math_qa") rows = pq.read_table(p).to_pylist() except Exception as e: print("mathqa unavailable:", e) rows = [] rnd.shuffle(rows) for r in rows[:n_mathqa]: raw = [o.strip() for o in r["options"].split(" , ")] if " , " in r["options"] else ast.literal_eval(r["options"]) opts = [] for o in raw: o = o.strip().lstrip("[").rstrip("]").strip("'\" ") if len(o) > 3 and o[1:3] == " )": opts.append(o[3:].strip()) elif len(o) > 2 and o[1] == ")": opts.append(o[2:].strip()) gold = "abcde".find(r["correct"].strip()) if len(opts) != 5 or gold < 0: continue order = list(range(5)) rnd.shuffle(order) k = order.index(gold) txt = "\n".join(f"{L[i]}. {opts[j]}" for i, j in enumerate(order)) out.append(("mathqa", "en", [U(f"{r['Problem'].strip()}\n{txt}\nAnswer with the letter of the correct option."), A(f"Answer: {L[k]}. {opts[gold]}")])) return out NEW_TOOLS = { "air_quality": {"name": "air_quality", "description": "Current air quality index (AQI) and main pollutant for a town.", "parameters": {"type": "object", "properties": {"town": {"type": "string"}}, "required": ["town"]}}, "sun_times": {"name": "sun_times", "description": "Sunrise and sunset time today for a town.", "parameters": {"type": "object", "properties": {"town": {"type": "string"}}, "required": ["town"]}}, "unit_convert": {"name": "unit_convert", "description": "Convert a value between units (km, mi, kg, lb, C, F, l, gal).", "parameters": {"type": "object", "properties": {"value": {"type": "number"}, "from_unit": {"type": "string"}, "to_unit": {"type": "string"}}, "required": ["value", "from_unit", "to_unit"]}}, "holiday_check": {"name": "holiday_check", "description": "Whether a date (YYYY-MM-DD) is a public holiday in Poland, and which one.", "parameters": {"type": "object", "properties": {"date": {"type": "string"}}, "required": ["date"]}}, } TOWNS = [("Zakopane", "Zakopanem"), ("Sopot", "Sopocie"), ("Płock", "Płocku"), ("Elbląg", "Elblągu"), ("Gniezno", "Gnieźnie"), ("Tarnów", "Tarnowie"), ("Kalisz", "Kaliszu"), ("Legnica", "Legnicy"), ("Zamość", "Zamościu"), ("Siedlce", "Siedlcach"), ("Nowy Sącz", "Nowym Sączu"), ("Suwałki", "Suwałkach")] HOL = {"2026-01-01": "Nowy Rok", "2026-01-06": "Święto Trzech Króli", "2026-05-01": "Święto Pracy", "2026-05-03": "Święto Konstytucji 3 Maja", "2026-08-15": "Wniebowzięcie NMP", "2026-11-01": "Wszystkich Świętych", "2026-11-11": "Narodowe Święto Niepodległości", "2026-12-25": "Boże Narodzenie"} CONV = {("km", "mi"): 0.621371, ("mi", "km"): 1.609344, ("kg", "lb"): 2.204623, ("lb", "kg"): 0.453592, ("l", "gal"): 0.264172} def pl_tools(rnd, n): out = [] import synth_tools as ST for _ in range(n): lang = "pl" if rnd.random() < 0.8 else "en" P = lang == "pl" k = rnd.choice(["aq", "sun", "conv", "hol", "aq_err", "two", "no_tool"]) town, loc = rnd.choice(TOWNS) need, msgs = [], [] if k in ("aq", "aq_err"): q = rnd.choice([f"Jaka jest teraz jakość powietrza w {loc}?", f"Czy w {loc} jest dziś smog? Sprawdź.", f"Sprawdź jakość powietrza w {loc}."] if P else [f"What is the air quality in {town} right now?", f"Is there smog in {town} today? Check it."]) if k == "aq": aqi = rnd.randint(12, 180) pol = rnd.choice(["PM2.5", "PM10", "NO2", "O3"]) res = {"town": town, "aqi": aqi, "main_pollutant": pol} ans = (f"W {loc} indeks jakości powietrza (AQI) wynosi {aqi}, a głównym zanieczyszczeniem jest {pol}." + (" To zła jakość powietrza – lepiej ograniczyć wyjście na zewnątrz." if aqi > 100 else "") if P else f"In {town} the air quality index (AQI) is {aqi}; the main pollutant is {pol}." + (" That is unhealthy air." if aqi > 100 else "")) else: res = {"error": rnd.choice(["station offline", "timeout"])} ans = (f"Przepraszam, nie udało się sprawdzić jakości powietrza w {loc}: narzędzie zwróciło błąd ({res['error']}). Spróbuj za chwilę." if P else f"Sorry, I could not check the air quality in {town}: the tool returned an error ({res['error']}). Please try again later.") msgs = [U(q), {"role": "assistant", "content": "", "tool_calls": [ST.call("air_quality", {"town": town})]}, {"role": "tool", "content": json.dumps(res, ensure_ascii=False)}, A(ans)] need = ["air_quality"] elif k == "sun": sr, ss = f"0{rnd.randint(5, 7)}:{rnd.randint(0, 59):02d}", f"{rnd.randint(15, 20)}:{rnd.randint(0, 59):02d}" q = rnd.choice([f"O której dziś wschodzi i zachodzi słońce w {loc}?", f"Kiedy będzie zachód słońca w {loc}?"] if P else [f"When is sunrise and sunset in {town} today?"]) msgs = [U(q), {"role": "assistant", "content": "", "tool_calls": [ST.call("sun_times", {"town": town})]}, {"role": "tool", "content": json.dumps({"town": town, "sunrise": sr, "sunset": ss})}, A(f"Dziś w {loc} słońce wschodzi o {sr}, a zachodzi o {ss}." if P else f"Today in {town} the sun rises at {sr} and sets at {ss}.")] need = ["sun_times"] elif k == "conv": (a, b), f_ = rnd.choice(list(CONV.items())) v = rnd.choice([3, 5, 10, 12, 21, 42, 100]) r = round(v * f_, 2) q = (f"Ile to jest {v} {a} w {b}? Przelicz narzędziem." if P else f"Convert {v} {a} to {b}.") msgs = [U(q), {"role": "assistant", "content": "", "tool_calls": [ST.call("unit_convert", {"value": v, "from_unit": a, "to_unit": b})]}, {"role": "tool", "content": json.dumps({"value": v, "from_unit": a, "to_unit": b, "result": r})}, A(f"{v} {a} to {str(r).replace('.', ',')} {b}." if P else f"{v} {a} is {r} {b}.")] need = ["unit_convert"] elif k == "hol": d = rnd.choice(list(HOL) + ["2026-03-17", "2026-06-10", "2026-09-22", "2026-10-05"]) h = HOL.get(d) q = (f"Czy {d} jest w Polsce dniem wolnym od pracy?" if P else f"Is {d} a public holiday in Poland?") res = {"date": d, "holiday": bool(h), "name": h} msgs = [U(q), {"role": "assistant", "content": "", "tool_calls": [ST.call("holiday_check", {"date": d})]}, {"role": "tool", "content": json.dumps(res, ensure_ascii=False)}, A((f"Tak, {d} to święto: {h}." if h else f"Nie, {d} nie jest świętem państwowym w Polsce.") if P else (f"Yes, {d} is a public holiday in Poland: {h}." if h else f"No, {d} is not a public holiday in Poland."))] need = ["holiday_check"] elif k == "two": aqi, sr, ss = rnd.randint(12, 120), f"0{rnd.randint(5, 7)}:{rnd.randint(0, 59):02d}", f"{rnd.randint(15, 20)}:{rnd.randint(0, 59):02d}" q = (f"Sprawdź jakość powietrza w {loc} i powiedz, o której zachodzi tam słońce." if P else f"Check the air quality in {town} and tell me when the sun sets there.") msgs = [U(q), {"role": "assistant", "content": "", "tool_calls": [ST.call("air_quality", {"town": town})]}, {"role": "tool", "content": json.dumps({"town": town, "aqi": aqi, "main_pollutant": "PM10"})}, {"role": "assistant", "content": "", "tool_calls": [ST.call("sun_times", {"town": town})]}, {"role": "tool", "content": json.dumps({"town": town, "sunrise": sr, "sunset": ss})}, A(f"W {loc} AQI wynosi {aqi} (główne zanieczyszczenie: PM10), a słońce zachodzi o {ss}." if P else f"In {town} the AQI is {aqi} (main pollutant PM10) and the sun sets at {ss}.")] need = ["air_quality", "sun_times"] else: q, a = rnd.choice([("Dzięki, to wszystko na dziś.", "Proszę bardzo! Miłego dnia."), ("Cześć, jak leci?", "Cześć! Wszystko dobrze, w czym mogę pomóc?"), ("Co to jest smog?", "Smog to zanieczyszczone powietrze nad miastem: mieszanina pyłów, dymu i gazów, zwykle przy bezwietrznej pogodzie."), ("Thanks, that's all for today.", "You're welcome! Have a nice day."), ("Ile to jest 2 + 2?", "2 + 2 = 4.")]) msgs = [U(q), A(a)] names = sorted(set(need)) others = [t for t in NEW_TOOLS if t not in names] rnd.shuffle(others) names += others[: rnd.randint(1, 2)] if need else others[: rnd.randint(2, 3)] rnd.shuffle(names) out.append(("pl_tools", lang, msgs, [NEW_TOOLS[t] for t in names])) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--s3", required=True) ap.add_argument("--decon", required=True) ap.add_argument("--out", required=True) ap.add_argument("--tokenizer", default="/workspace/ckpt/tokenizer.json") ap.add_argument("--n-mmlu", type=int, default=25000) ap.add_argument("--n-mathqa", type=int, default=15000) ap.add_argument("--n-tools", type=int, default=12000) ap.add_argument("--replay-tokens", type=float, default=40e6) a = ap.parse_args() rnd = random.Random("e4") f = Fmt(Tokenizer.from_file(a.tokenizer)) dec = Decon(a.decon) out = Path(a.out) (out / "eval").mkdir(parents=True, exist_ok=True) items = [(c, l, m, None) for c, l, m in klej(rnd) + mc(rnd, a.n_mmlu, a.n_mathqa)] + pl_tools(rnd, a.n_tools) stats = Counter() rows = {"train": [], "val": []} for j, (comp, lang, msgs, tools) in enumerate(items): for m in msgs: m.setdefault("trainable", m["role"] == "assistant") if comp != "pl_tools": h = dec.hit([m["content"] for m in msgs if m.get("content")]) if h: stats[f"decon:{comp}:{h.split(':')[1]}"] += 1 continue ids, lab = f.render(msgs, 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 msgs) rid = comp + "-" + hashlib.sha1(json.dumps(msgs, ensure_ascii=False).encode()).hexdigest()[:16] split = "val" if hash(rid) % 100 == 0 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"e4:{comp}", "comp": comp, "language": 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 = a.replay_tokens if split == "train" else a.replay_tokens / 100 got = 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"] = len(xs) stats[f"{split}:tokens"] = sum(r["n_tokens"] for r in xs) stats[f"{split}:target_tokens"] = sum(r["n_target"] for r in xs) stats[f"{split}:tool_records"] = sum(r["is_tool"] for r in xs) stats["train:new_tokens"] = new_tokens 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()