Download code/mathset.py from PugarHuda/benak: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/PugarHuda/benak/resolve/main/code/mathset.py
- Command line
-
hf download hf://datasets/PugarHuda/benak/code/mathset.py
-
curl -L -o mathset.py https://huggingface.co/datasets/PugarHuda/benak/resolve/main/code/mathset.py
10.6 kB
| """Babak 1b: parallel math word problems with code-verified answers, then solved per language/condition. | |
| 1) Beam writes an Indonesian problem + Python solver (effort low); solver executed; keep if it reproduces the answer. | |
| 2) Beam translates the full prompt into 8 languages; keep only if every number survives the translation. | |
| 3) Beam solves each version (conditions C0/C2) -> data/math/runs_<effort>.jsonl with reasoning-language profile. | |
| Usage: python mathset.py gen --n 70 ; python mathset.py translate ; python mathset.py solve --effort low""" | |
| import argparse, json, math, os, random, re, subprocess, sys, tempfile | |
| from beam import chat, run_many, spent | |
| from lid import profile | |
| OUT = "data/math" | |
| LANGS = {"ind_Latn": "Indonesian", "eng_Latn": "English", "jav_Latn": "Javanese", "sun_Latn": "Sundanese", | |
| "zsm_Latn": "Malay", "tgl_Latn": "Tagalog", "ceb_Latn": "Cebuano", "vie_Latn": "Vietnamese", "tha_Thai": "Thai"} | |
| TOPICS = ["belanja dan diskon di pasar", "gaji, THR dan potongan dengan tarif yang disebut di soal", | |
| "cicilan dan bunga flat", "zakat dengan nisab dan kadar yang disebut di soal", "ongkos kirim antarpulau", | |
| "jarak, kecepatan dan zona waktu WIB/WITA/WIT", "hasil panen sawah per hektar", "modal dan untung warung", | |
| "takaran resep untuk hajatan", "arisan dan koperasi", "luas dan keliling rumah atau kolam", | |
| "peluang dan kombinatorika", "barisan dan pola tabungan", "rata-rata dan median nilai rapor", | |
| "FPB dan KPK jadwal", "sistem persamaan dari cerita umur"] | |
| ANSWER_LINE = ("Tulis jawaban akhir sebagai angka biasa (tanpa pemisah ribuan, titik untuk desimal) " | |
| "di dalam \\boxed{}.") | |
| GEN = """Buat SATU soal cerita matematika orisinal dalam bahasa Indonesia yang alami. Topik: {topic}. \ | |
| Tingkat kesulitan {d}/5 (1=SD, 3=SMP, 5=olimpiade). | |
| Aturan: semua angka/aturan yang dibutuhkan tertulis di soal; jawaban akhir tepat SATU bilangan (sebutkan pembulatan \ | |
| bila perlu); soal punya tepat satu jawaban; tulis angka dengan digit. "solver" = kode Python murni (boleh import math, \ | |
| fractions, itertools saja) yang print() HANYA jawaban akhir sebagai angka biasa. | |
| Keluarkan HANYA JSON: {{"soal": "...", "jawaban": <angka>, "solver": "..."}}""" | |
| TRANSLATE = """Translate the following Indonesian math word problem into natural, fluent {name}. Keep every number \ | |
| exactly as written with Western digits (do not convert numbers to words, do not change units or currency amounts). \ | |
| Translate the final instruction sentence too. Output ONLY the translation. | |
| {text}""" | |
| SYS = {"ind_Latn": "Berpikir dan bernalarlah langkah demi langkah dalam bahasa Indonesia."} # others from atlas templates | |
| BANNED = re.compile(r"\b(import\s+(os|sys|subprocess|socket|shutil|urllib|pathlib|ctypes|requests)|from\s+" | |
| r"(os|sys|subprocess|socket|shutil|urllib|pathlib|ctypes|requests)|open\s*\(|exec\s*\(|eval\s*\(|__import__)") | |
| def run_solver(code, timeout=10): | |
| # ponytail: denylist + timeout + temp dir, not a real sandbox; fine for our own generated snippets | |
| if BANNED.search(code): | |
| return None | |
| with tempfile.TemporaryDirectory() as d: | |
| p = os.path.join(d, "s.py"); open(p, "w", encoding="utf-8").write(code) | |
| try: | |
| r = subprocess.run([sys.executable, "-I", p], cwd=d, capture_output=True, text=True, timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| return None | |
| lines = r.stdout.strip().splitlines() | |
| return lines[-1].strip() if r.returncode == 0 and lines else None | |
| def nums(s): | |
| """Float readings of the last number in s; ambiguous '1.250' yields both 1250 and 1.25.""" | |
| if s is None: | |
| return set() | |
| s = re.sub(r"(?i)rp\.?|%|\s|\\[,!]|\$|\\text\{[^}]*\}", "", str(s)) | |
| fr = re.search(r"(-?)\\d?frac\{(-?\d+)\}\{(\d+)\}", s) | |
| if fr and int(fr.group(3)): | |
| return {(-1 if fr.group(1) else 1) * int(fr.group(2)) / int(fr.group(3))} | |
| m = re.findall(r"-?\d[\d.,]*", s) | |
| if not m: | |
| return set() | |
| t = m[-1].rstrip(".,"); c = set() | |
| if "," in t and "." in t: | |
| c.add(t.replace(".", "").replace(",", ".") if t.rfind(",") > t.rfind(".") else t.replace(",", "")) | |
| elif t.count(".") > 1 or t.count(",") > 1: | |
| c.add(t.replace(".", "").replace(",", "")) | |
| elif "." in t or "," in t: | |
| a, b = re.split(r"[.,]", t); c.add(f"{a}.{b}") | |
| if len(b) == 3: | |
| c.add(a + b) | |
| else: | |
| c.add(t) | |
| out = set() | |
| for x in c: | |
| try: | |
| out.add(float(x)) | |
| except ValueError: | |
| pass | |
| return out | |
| def same(text, answer): | |
| return any(math.isclose(v, float(answer), rel_tol=1e-4, abs_tol=0.011) for v in nums(text)) | |
| def boxed(text): | |
| i = (text or "").rfind("\\boxed{") | |
| if i < 0: | |
| return None | |
| i += 7; depth = 1; j = i | |
| while j < len(text) and depth: | |
| depth += {"{": 1, "}": -1}.get(text[j], 0); j += 1 | |
| return text[i:j - 1] if depth == 0 else None | |
| def digit_multiset(text): | |
| """Numbers in text, separator-insensitive: thousands marks dropped, decimal comma == decimal point.""" | |
| return sorted(re.sub(r"[.,](?=\d{3}\b)", "", x).replace(",", ".") | |
| for x in re.findall(r"\d[\d.,]*\d|\d", text)) | |
| def cmd_gen(a): | |
| os.makedirs(OUT, exist_ok=True) | |
| def one(i): | |
| rng = random.Random(i) | |
| topic, d = rng.choice(TOPICS), rng.choice([1, 2, 3, 3, 4, 4, 5]) | |
| r = chat([{"role": "user", "content": GEN.format(topic=topic, d=d)}], "low", 8192, tag=f"gen{i}") | |
| m = re.search(r"\{.*\}", r["content"], re.S) | |
| if not m: | |
| return {"id": i, "ok": False, "why": "unparseable"} | |
| try: | |
| spec = json.loads(m.group(0)); ans = float(spec["jawaban"]) | |
| except Exception: | |
| return {"id": i, "ok": False, "why": "unparseable"} | |
| out = run_solver(spec["solver"]) | |
| ok = out is not None and same(out, ans) | |
| return {"id": i, "ok": ok, "why": "ok" if ok else "solver_mismatch", "topic": topic, "difficulty": d, | |
| "question": spec["soal"].strip(), "answer": ans, "solver": spec["solver"], "solver_output": out} | |
| rows = [res for _, res in run_many(one, list(range(a.n)), 12, "gen") if not isinstance(res, Exception)] | |
| json.dump(sorted(rows, key=lambda x: x["id"]), open(f"{OUT}/problems.json", "w", encoding="utf-8"), | |
| ensure_ascii=False, indent=1) | |
| print(sum(r["ok"] for r in rows), "verified of", len(rows)) | |
| def cmd_translate(a): | |
| probs = [p for p in json.load(open(f"{OUT}/problems.json", encoding="utf-8")) if p["ok"]] | |
| jobs = [(p, c) for p in probs for c in LANGS if c != "ind_Latn"] | |
| def one(job): | |
| p, c = job | |
| src = f"{p['question']}\n\n{ANSWER_LINE}" | |
| r = chat([{"role": "user", "content": TRANSLATE.format(name=LANGS[c], text=src)}], "low", 4096, | |
| temperature=0.2, tag="tr") | |
| t = r["content"].strip() | |
| return {"id": p["id"], "lang": c, "text": t, "numbers_ok": digit_multiset(src) == digit_multiset(t), | |
| "lid": profile(t, c)} | |
| par = {p["id"]: {"ind_Latn": {"text": f"{p['question']}\n\n{ANSWER_LINE}", "numbers_ok": True}} for p in probs} | |
| for _, res in run_many(one, jobs, 16, "translate"): | |
| if not isinstance(res, Exception): | |
| par[res["id"]][res["lang"]] = res | |
| json.dump(par, open(f"{OUT}/parallel.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) | |
| full = [i for i, v in par.items() if all(c in v and v[c]["numbers_ok"] for c in LANGS)] | |
| print(f"{len(full)}/{len(par)} problems survive in all {len(LANGS)} languages") | |
| def cmd_solve(a): | |
| probs = {p["id"]: p for p in json.load(open(f"{OUT}/problems.json", encoding="utf-8")) if p["ok"]} | |
| par = {int(k): v for k, v in json.load(open(f"{OUT}/parallel.json", encoding="utf-8")).items()} | |
| tps = json.load(open("data/atlas/templates.json", encoding="utf-8")) | |
| ids = sorted(i for i, v in par.items() if all(c in v and v[c]["numbers_ok"] for c in LANGS))[:a.n] | |
| langs = a.langs or list(LANGS) | |
| jobs = [(i, c, cond) for i in ids for c in langs for cond in a.conds] | |
| budget = 8192 if a.effort == "low" else 32768 | |
| def one(job): | |
| i, c, cond = job | |
| msgs = [{"role": "user", "content": par[i][c]["text"]}] | |
| if cond == "C2": | |
| msgs.insert(0, {"role": "system", "content": SYS.get(c) or tps[c]["reason_instruction"]}) | |
| elif cond == "C3": # the shipped benak_lang wrapper; its primer is a reading item -> tests transfer to math | |
| from benak_lang import think_in | |
| msgs = think_in(msgs, c, primer=True) | |
| r = chat(msgs, a.effort, budget, tag="math") | |
| b = boxed(r["content"]) | |
| return {"id": i, "lang": c, "cond": cond, "effort": a.effort, "answer": probs[i]["answer"], "boxed": b, | |
| "correct": b is not None and same(b, probs[i]["answer"]), "finish_reason": r["finish_reason"], | |
| "usage": r["usage"], "reasoning": r["reasoning"], "content": r["content"], | |
| "lid": profile(r["reasoning"], c), "lid_answer": profile(r["content"], c), | |
| "topic": probs[i]["topic"], "difficulty": probs[i]["difficulty"], "route": r.get("route"), "served_model": r.get("model"), "latency_s": r.get("latency_s")} | |
| rows = [res for _, res in run_many(one, jobs, 16, f"math-{a.effort}") if not isinstance(res, Exception)] | |
| path = f"{OUT}/runs_{a.effort}.jsonl" | |
| merged = {} | |
| if os.path.exists(path): # merge: a run with other --conds/--langs must not erase earlier rows | |
| for l in open(path, encoding="utf-8"): | |
| d = json.loads(l); merged[(d["id"], d["lang"], d["cond"])] = d | |
| for r in rows: | |
| merged[(r["id"], r["lang"], r["cond"])] = r | |
| with open(path, "w", encoding="utf-8") as f: | |
| f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in merged.values()) | |
| print(f"{len(rows)}/{len(jobs)} solved-rows written; spent ${spent()}") | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(); ap.add_argument("cmd", choices=["gen", "translate", "solve"]) | |
| ap.add_argument("--n", type=int, default=70); ap.add_argument("--effort", default="low") | |
| ap.add_argument("--conds", nargs="+", default=["C0", "C2"]); ap.add_argument("--langs", nargs="+") | |
| a = ap.parse_args() | |
| {"gen": cmd_gen, "translate": cmd_translate, "solve": cmd_solve}[a.cmd](a) | |