"""Rebuilds data/clean-16k.jsonl (as pairs) from the training corpus SagheerLab/Arithmetic-Reasoning. python3 scripts/build_clean_set.py > build.out (about 10 minutes, downloads the 5 GB corpus shard by shard and deletes each; CPU only, no GPU, needs pyarrow + huggingface_hub) Prints PAIRS_JSON {type: [[a, b], ...]} (the operands of the 2,000 clean questions per type, in file order; the answer is a op b) and LEGACY_FLAGS_JSON [ids of the legacy-14k items that occur in the corpus]. A question is 'seen' when `a op b` (or `b op a` for + and *) occurs in the corpus as an expression in `instruction` or as a step `a op b = c` in `reasoning`.""" import os, re, sys, time, json, collections, subprocess subprocess.run([sys.executable, "-m", "pip", "install", "-q", "pyarrow", "huggingface_hub"], check=False) import numpy as np, pyarrow.parquet as pq from huggingface_hub import list_repo_files, hf_hub_download REPO = "SagheerLab/Arithmetic-Reasoning" NORM = lambda s: s.replace("×", "*").replace("x", "*").replace("÷", "/") P_INST = re.compile(r"\d+(?:\s*[+\-*×x/÷]\s*\d+)+") P_STEP = re.compile(r"(\d+)\s*([+\-*×x/÷])\s*(\d+)\s*=") P_ONE = re.compile(r"(\d+)([+\-*/])(\d+)") seen = set(); n = 0; t0 = time.time() files = sorted(f for f in list_repo_files(REPO, repo_type="dataset") if f.endswith(".parquet")) cols = None for fi, f in enumerate(files): p = hf_hub_download(REPO, f, repo_type="dataset"); pf = pq.ParquetFile(p) cols = [c for c in ("instruction", "reasoning") if c in pf.schema_arrow.names] for batch in pf.iter_batches(batch_size=20000, columns=cols): arrs = [c.to_pylist() for c in batch.columns] for row in zip(*arrs): n += 1 q = row[0] or "" for e in P_INST.findall(q): m = P_ONE.fullmatch(re.sub(r"\s+", "", NORM(e))) if m: seen.add((int(m.group(1)), m.group(2), int(m.group(3)))) if len(row) > 1 and row[1]: for a, o, b in P_STEP.findall(row[1]): seen.add((int(a), NORM(o), int(b))) os.remove(p) print(f"[scan] shard {fi+1}/{len(files)} rows {n:,} distinct single-op expressions {len(seen):,} cols {cols} {time.time()-t0:.0f}s", flush=True) cov = collections.Counter((o, len(str(a)), len(str(b))) for a, o, b in seen) print("COVERAGE_JSON", json.dumps({f"{o} {da}x{db}": c for (o, da, db), c in sorted(cov.items()) if c > 500}), flush=True) def present(a, o, b): return (a, o, b) in seen or (o in "+*" and (b, o, a) in seen) # type -> (digits of a, digits of b, operator, seed, keep the original legacy items first) TYPES = {"3ds": (3, 3, "-", 104, True), "4da": (4, 4, "+", 105, True), "5da": (5, 5, "+", 106, True), "5ds": (5, 5, "-", 108, False), "4dm": (4, 4, "*", 110, False), "5dm": (5, 5, "*", 111, False), "34m": (3, 4, "*", 113, False)} INFEASIBLE_PROBE = {"3da": (3, 3, "+", 103, True), "3dm": (3, 3, "*", 109, False)} # probed only: the training data covers (almost) the whole space DIV = ((11, 99), (101, 999)) # divisor 2-digit, quotient 3-digit, dividend = their product (1,111 .. 98,901) def draw(rng, da, db, op): a = int(rng.randint(10 ** (da - 1), 10 ** da)); b = int(rng.randint(10 ** (db - 1), 10 ** db)) if op == "-" and b > a: a, b = b, a return a, b def pick(tag, da, db, op, seed, legacy, cap=2_000_000): out, got, stats = [], set(), collections.Counter() def take(a, b, src): if (a, b) in got or (op in "+*" and (b, a) in got): stats["dup"] += 1; return if present(a, op, b): stats["in_training_" + src] += 1; return got.add((a, b)); out.append([a, b]); stats["kept_" + src] += 1 if legacy: rng = np.random.RandomState(seed) for _ in range(2000): take(*draw(rng, da, db, op), "legacy") rng = np.random.RandomState(seed + 1000); tries = 0 while len(out) < 2000 and tries < cap: tries += 1; take(*draw(rng, da, db, op), "fresh") print(f"[pick] {tag}: {len(out)} items {dict(stats)} draws {tries}", flush=True) return out res = {} for tag, (da, db, op, sd, lg) in TYPES.items(): res[tag] = pick(tag, da, db, op, sd, lg) for tag, (da, db, op, sd, lg) in INFEASIBLE_PROBE.items(): pick(tag, da, db, op, sd, lg, cap=300_000) (dl, dh), (ql, qh) = DIV rng = np.random.RandomState(112 + 1000); out, got, hit = [], set(), 0 while len(out) < 2000: y, q = int(rng.randint(dl, dh + 1)), int(rng.randint(ql, qh + 1)); x = y * q if (x, y) in got: continue if present(x, "/", y): hit += 1; continue got.add((x, y)); out.append([x, y]) res["div"] = out; print(f"[div] 2000 items, rejected {hit} that were in the training data", flush=True) for t, v in res.items(): assert len(v) == 2000 and len({tuple(p) for p in v}) == 2000, t op = "/" if t == "div" else TYPES[t][2] assert not any(present(a, op, b) for a, b in v), t # legacy 14k per-item flags (for the archive file) LEGACY_ALL = {"2da": (2, "+", 101), "2ds": (2, "-", 102), "3da": (3, "+", 103), "3ds": (3, "-", 104), "4da": (4, "+", 105), "5da": (5, "+", 106), "2dm": (2, "*", 107)} flags = [] for tag, (d, op, sd) in LEGACY_ALL.items(): rng = np.random.RandomState(sd) for k in range(2000): a, b = draw(rng, d, d, op) if present(a, op, b): flags.append(f"{tag}-{k:04d}") print("RESULT_JSON", json.dumps({"rows": n, "legacy_flagged": len(flags), "legacy_flagged_by_type": dict(collections.Counter(i.split('-')[0] for i in flags)), "sizes": {k: len(v) for k, v in res.items()}}), flush=True) print("PAIRS_JSON", json.dumps(res), flush=True) print("LEGACY_FLAGS_JSON", json.dumps(flags), flush=True)