"""Babak 3: build in-language reasoning traces where Beam got the answer right but thought in English. Beam rewrites its own correct reasoning into the target language (as visible content, which follows language instructions far better than reasoning does). Kept only if GlotLID says >= 0.8 target language AND every number of the original reasoning survives. Output: data/thinking/rewritten.jsonl (trace_source='rewritten'). Usage: python thinking.py --per-lang 60""" import argparse, json, os, re from beam import chat, run_many, spent from lid import profile LANGS = ["ind_Latn", "jav_Latn", "sun_Latn", "zsm_Latn", "tgl_Latn", "ceb_Latn", "vie_Latn", "tha_Thai"] # v2: v1 let Beam *solve* the embedded problem (251/439 outputs were just \boxed{answer}); now the text is fenced # and the task is stated as translation-only. PROMPT = """You are a translator. Translate the text inside into natural, fluent {name}. This is a translation task only: do NOT solve anything, do NOT add a final answer, do NOT shorten. Keep every step, number and calculation exactly as written. Output only the translated text, without the tags. {reasoning} """ def nums(t): t = re.sub(r"(?<=\d)[.,](?=\d{3}\b)", "", t) # drop thousands separators (1.250.000 / 1,250,000) return set(re.findall(r"\d+", t)) # ponytail: digit-run set; tolerant to 1,250 vs 1250 formatting def main(): ap = argparse.ArgumentParser(); ap.add_argument("--per-lang", type=int, default=60); a = ap.parse_args() names = {c: v["lang_name_native"] for c, v in json.load(open("data/atlas/templates.json", encoding="utf-8")).items()} par = json.load(open("data/math/parallel.json", encoding="utf-8")) runs = [json.loads(l) for l in open("data/math/runs_low.jsonl", encoding="utf-8")] pool = {} for r in runs: # correct, reasoning mostly NOT in the target language ts = r["lid"]["target_share"] if r["lang"] in LANGS and r["correct"] and r["reasoning"] and (ts is None or ts < 0.8): pool.setdefault(r["lang"], {}).setdefault(r["id"], r) # one trace per problem per language jobs = [r for l in LANGS for r in list(pool.get(l, {}).values())[:a.per_lang]] def one(r): out = chat([{"role": "user", "content": PROMPT.format(name=names[r["lang"]], reasoning=r["reasoning"])}], "low", 6000, temperature=0.2, tag="rewrite-v2") new = out["content"].strip() lid = profile(new, r["lang"]) a, b = nums(new), nums(r["reasoning"]) jac = len(a & b) / max(1, len(a | b)) # number-set Jaccard; translation may re-spell a few ordinals ok = (lid["target_share"] or 0) >= 0.8 and jac >= 0.9 return {"lang": r["lang"], "id": r["id"], "answer": r["answer"], "effort": r["effort"], "user": par[str(r["id"])][r["lang"]]["text"], "reasoning": new, "content": r["content"], "correct": ok, "lid": lid, "numbers_jaccard": round(jac, 3), "original_reasoning_lid": r["lid"], "trace_source": "rewritten"} rows = [x for _, x in run_many(one, jobs, 10, "rewrite") if not isinstance(x, Exception)] os.makedirs("data/thinking", exist_ok=True) with open("data/thinking/rewritten.jsonl", "w", encoding="utf-8") as f: f.writelines(json.dumps(x, ensure_ascii=False) + "\n" for x in rows) print(f"{sum(x['correct'] for x in rows)}/{len(rows)} rewrites kept; spent ${spent()}") if __name__ == "__main__": main()