import ast, hashlib, json, random, re from collections import Counter from itertools import chain from datasets import load_dataset random.seed(42) MAX_ROWS = 42000 rows, per_qt, fps = [], Counter(), set() ds = chain(load_dataset("baharef/ToT", "tot_arithmetic", split="test", streaming=True), load_dataset("baharef/ToT", "tot_semantic", split="test", streaming=True), load_dataset("baharef/ToT", "tot_semantic_large", split="test", streaming=True)) NUM = re.compile(r"-?\d+") for r in ds: qt = r.get("question_type") or "misc" q = str(r.get("question", "")).strip() p = str(r.get("prompt", "")).strip() lab = r.get("label") if isinstance(lab, str): try: lab = ast.literal_eval(lab) except Exception: pass ans = lab.get("answer") if isinstance(lab, dict) else (lab if isinstance(lab, str) else None) if not q or not ans or len(p) > 1400: continue ans = str(ans).strip() m = NUM.search(ans.replace(",", "")) if not m: continue val = int(m.group(0)) # wrong candidates: same answer string, first number perturbed def swap(a, v): return NUM.sub(str(v), a, count=1) cands = {val} for d in (1, -1, 2, -2, 10, -10, 4, -4, 8, -8, 100, -100, 5, -5): cands.add(val + d) if len(cands) >= 4: break opts = [ans] + [swap(ans.replace(",", ""), x) for x in random.sample(sorted(cands - {val}), 3)] random.shuffle(opts) fp = hashlib.sha256(f"{p}|{q}|{ans}".encode()).hexdigest() if fp in fps: continue fps.add(fp) qq = re.sub(r"format your answer.*$", "", q, flags=re.I).strip() st = {"context": p} if p else {"context": qq} tgt = [0.0] * len(opts) ti = opts.index(ans) tgt[ti] = 1.0 gid = f"tot:{qt}:{fp[:12]}" rows.append({"state": st, "id": f"tot:{qt}:{fp[:16]}", "kind": "choice", "options": opts, "target": tgt, "question": qq + " Choose the correct answer.", "source": f"tot:{qt}", "group_id": gid}) per_qt[qt] += 1 if len(rows) >= MAX_ROWS: break random.shuffle(rows) dev = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] == "0"] train = [r for r in rows if hashlib.md5(r["group_id"].encode()).hexdigest()[0] != "0"] tg = {r["group_id"] for r in train} dev = [r for r in dev if r["group_id"] not in tg] with open("/root/alea/data/tot_train.jsonl", "w") as f: for r in train[:36000]: f.write(json.dumps(r) + "\n") with open("/root/alea/data/tot_dev.jsonl", "w") as f: for r in dev[:3500]: f.write(json.dumps(r) + "\n") print({"train": min(36000, len(train)), "dev": min(3500, len(dev)), "qtypes": dict(per_qt)})