Download scripts/day1_bootstrap.py from EngineeringWithJay/pi-office-math-bootstrap: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/EngineeringWithJay/pi-office-math-bootstrap/resolve/main/scripts/day1_bootstrap.py
- Command line
-
hf download hf://EngineeringWithJay/pi-office-math-bootstrap/scripts/day1_bootstrap.py
-
curl -L -o day1_bootstrap.py https://huggingface.co/EngineeringWithJay/pi-office-math-bootstrap/resolve/main/scripts/day1_bootstrap.py
14.3 kB
| """ | |
| day1_bootstrap.py - Cloud vLLM Verifier-Filtered Bootstrap (corrected) | |
| Runs on a cloud GPU pod (4090 24GB, vast.ai/runpod). Generates candidate sympy | |
| code for GSM8K + MATH train sets with vLLM, verifies via the local Pi Office | |
| sandbox (pi_office_symbolic_sandbox.py) and the strong comparator | |
| (mode3_verify.py), and emits clean SFT and DPO datasets. | |
| Verdict taxonomy (noise-free by construction): | |
| verified -> strong_compare True -> SFT pair + DPO chosen | |
| wrong -> strong_compare False -> DPO rejected (gold signal) | |
| crash -> SandboxError / worker exception -> DPO rejected | |
| gate -> SandboxRefusal (gate refusal) -> DPO rejected | |
| degenerate-> intent-JSON codegen collapse -> DPO rejected | |
| uncertain -> result is None / verdict None -> EXCLUDED from both datasets | |
| API compatibility (verified against the local repo on 2026-08-04): | |
| execute_sympy(code, timeout=15) -- no max_output kwarg; raises | |
| SandboxRefusal (gate) and SandboxError (execution failure). | |
| strong_compare(expected, result) -- True/False/None; NEVER pass the string | |
| "None" -- pass the Python None (or the parsed result value directly). | |
| Usage: | |
| python3 day1_bootstrap.py --dry-run 20 | |
| python3 day1_bootstrap.py | |
| """ | |
| import argparse | |
| import ast | |
| import json | |
| import os | |
| import re | |
| import time | |
| from collections import defaultdict | |
| from multiprocessing import Pool | |
| # --- Local infrastructure (upload alongside this script) --- | |
| # vllm and datasets are imported lazily inside main()/load_datasets() so the | |
| # module is importable for testing without those heavy deps installed. | |
| from pi_office_symbolic_sandbox import execute_sympy, SandboxError, SandboxRefusal | |
| from mode3_verify import strong_compare | |
| def _load_codgen_system() -> str: | |
| """Extract CODEGEN_SYSTEM from benchmark_mode3_lean.py WITHOUT importing | |
| it (it imports mlx_lm, which is Apple-only and unavailable on the pod).""" | |
| import ast as _ast | |
| module = _ast.parse(open("benchmark_mode3_lean.py").read()) | |
| for node in module.body: | |
| if isinstance(node, _ast.Assign): | |
| for target in node.targets: | |
| if isinstance(target, _ast.Name) and target.id == "CODEGEN_SYSTEM": | |
| if isinstance(node.value, _ast.Constant) and isinstance(node.value.value, str): | |
| return node.value.value | |
| raise RuntimeError("CODEGEN_SYSTEM not found in benchmark_mode3_lean.py") | |
| CODEGEN_SYSTEM = _load_codgen_system() # byte-identical proven prompt | |
| MODEL_NAME = "Qwen/Qwen2.5-Math-7B-Instruct" | |
| MAX_TOKENS = 450 | |
| TEMPERATURE = 0.7 | |
| N_CANDIDATES = 4 | |
| MAX_PAIRS = 10000 | |
| OUT_DIR = "bootstrap_output" | |
| # verification pool size; lower under memory pressure, e.g. PI_OFFICE_WORKERS=16 | |
| WORKERS = int(os.environ.get("PI_OFFICE_WORKERS", "32")) | |
| def postprocess_code(text: str) -> str | None: | |
| """Same pipeline as benchmark_mode3_lean.generate_code (minus the model).""" | |
| text = re.sub(r"<think>.*?</think>", "", text, flags=re.S) | |
| if text.startswith("```"): | |
| lines = text.splitlines() | |
| if lines and lines[0].startswith("```"): | |
| lines = lines[1:] | |
| text = "\n".join(lines).strip() | |
| if text.endswith("```"): | |
| text = text[:-3].strip() | |
| fenced = re.search(r"```(?:python)?\s*(.*?)\s*```", text, re.S) | |
| code = (fenced.group(1) if fenced else text).strip() | |
| if not code: | |
| return None | |
| # prose / invalid Python -> None: the model wrote English instead of code | |
| # (the 7B's dominant failure mode). Rejected before the sandbox. | |
| try: | |
| ast.parse(code) | |
| except SyntaxError: | |
| return None | |
| # intent-JSON degeneracy guard (matches generate_code) | |
| try: | |
| parsed = json.loads(code) | |
| if isinstance(parsed, dict) and ( | |
| "solver_id" in parsed or "solverid" in parsed | |
| ): | |
| return None | |
| except Exception: | |
| pass | |
| return code | |
| def extract_gsm8k_answer(answer_text: str) -> str: | |
| """Trailing number from a GSM8K chain-of-thought answer.""" | |
| match = re.findall(r"\d+", answer_text.replace(",", "")) | |
| return match[-1] if match else "" | |
| def _load_math() -> list: | |
| """MATH train rows, trying public sources first. | |
| Verified live on 2026-08-04 (pod): hendrycks/competition_math is | |
| 401-GATED (metadata public, data needs auth) -- only usable with | |
| HF_TOKEN. EleutherAI/hendrycks_math is public but multi-config | |
| (7 subject splits), so load each config and concatenate. | |
| """ | |
| from datasets import load_dataset | |
| def src_eleuther() -> list: | |
| configs = ["algebra", "counting_and_probability", "geometry", | |
| "intermediate_algebra", "number_theory", "prealgebra", | |
| "precalculus"] | |
| rows = [] | |
| for cfg in configs: | |
| rows.extend(load_dataset("EleutherAI/hendrycks_math", cfg, | |
| split="train")) | |
| return rows | |
| def src_hendrycks() -> list: | |
| return list(load_dataset("hendrycks/competition_math", split="train", | |
| trust_remote_code=True)) | |
| sources = [ | |
| ("EleutherAI/hendrycks_math (7 configs, public)", src_eleuther), | |
| ("hendrycks/competition_math (gated, needs HF_TOKEN)", src_hendrycks), | |
| ] | |
| errors = [] | |
| for label, loader in sources: | |
| try: | |
| rows = loader() | |
| print(f"MATH source: {label} ({len(rows)} rows)") | |
| return rows | |
| except Exception as exc: | |
| errors.append(f"{label}: {type(exc).__name__}: {str(exc)[:150]}") | |
| raise RuntimeError("all MATH sources failed:\n" + "\n".join(errors)) | |
| def load_datasets() -> list[dict]: | |
| """GSM8K train + MATH train, normalized. IDs are counters -- the HF | |
| datasets expose no usable id fields.""" | |
| from datasets import load_dataset | |
| problems = [] | |
| gsm8k = load_dataset("openai/gsm8k", "main", split="train") | |
| for i, row in enumerate(gsm8k): | |
| problems.append({ | |
| "id": f"gsm8k_{i}", | |
| "problem": row["question"], | |
| "answer": extract_gsm8k_answer(row["answer"]), | |
| }) | |
| print(f"GSM8K loaded: {len(problems)} problems") | |
| math = _load_math() | |
| math_start = len(problems) | |
| for i, row in enumerate(math): | |
| # LAST boxed answer is the final answer; solutions contain | |
| # intermediate \boxed{} values too. An explicit answer field wins. | |
| answer_field = row.get("answer") | |
| boxed = re.findall(r"\\boxed\{([^}]+)\}", str(row.get("solution", ""))) | |
| if not answer_field and not boxed: | |
| continue | |
| problems.append({ | |
| "id": f"math_{i}", | |
| "problem": str(row["problem"]), | |
| "answer": (str(answer_field).strip() if answer_field | |
| else boxed[-1].strip()), | |
| }) | |
| print(f"MATH loaded: {len(problems) - math_start} problems") | |
| return problems | |
| USER_DIRECTIVE = "\n\nRespond with ONLY Python code. No prose, no explanations, no reasoning." | |
| def user_content(problem: str) -> str: | |
| """User turn for generation AND for the SFT pairs -- must match the | |
| benchmark runner's generate_code exactly (prompt consistency).""" | |
| return problem + USER_DIRECTIVE | |
| def verify_candidate(task: dict) -> dict: | |
| """Pool worker: sandbox + strong comparator, exception-classified.""" | |
| code = task["code"] | |
| expected = task["expected"] | |
| try: | |
| execution = execute_sympy(code, timeout=15) | |
| except SandboxRefusal as exc: | |
| return {"verdict": False, "result": None, "reason": "gate_refused"} | |
| except SandboxError as exc: | |
| return {"verdict": False, "result": None, | |
| "reason": f"crash:{str(exc)[:80]}"} | |
| except Exception as exc: | |
| return {"verdict": False, "result": None, | |
| "reason": f"worker_exception:{type(exc).__name__}"} | |
| try: | |
| output = json.loads(execution["stdout"]) | |
| except Exception as exc: | |
| return {"verdict": False, "result": None, | |
| "reason": f"bad_stdout:{type(exc).__name__}"} | |
| result = output.get("result") | |
| if result is None: | |
| return {"verdict": None, "result": None, "reason": "no_result"} | |
| verdict = strong_compare(expected, result) | |
| if verdict is None: | |
| return {"verdict": None, "result": str(result), "reason": "ambiguous"} | |
| return {"verdict": verdict, "result": str(result), | |
| "reason": "verified" if verdict else "wrong_caught"} | |
| def main() -> int: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--dry-run", type=int, default=0) | |
| args = parser.parse_args() | |
| wall_start = time.time() | |
| os.makedirs(OUT_DIR, exist_ok=True) | |
| all_problems = load_datasets() | |
| if args.dry_run > 0: | |
| all_problems = all_problems[: args.dry_run] | |
| print(f"Problems to process: {len(all_problems)}") | |
| from vllm import LLM, SamplingParams | |
| llm = LLM(model=MODEL_NAME, tensor_parallel_size=1, | |
| gpu_memory_utilization=0.9) | |
| tokenizer = llm.get_tokenizer() | |
| prompts = [] | |
| for p in all_problems: | |
| messages = [ | |
| {"role": "system", "content": CODEGEN_SYSTEM}, | |
| {"role": "user", "content": user_content(p["problem"])}, | |
| ] | |
| prompts.append(tokenizer.apply_chat_template( | |
| messages, tokenize=False, add_generation_prompt=True)) | |
| sampling_params = SamplingParams(n=N_CANDIDATES, | |
| temperature=TEMPERATURE, | |
| max_tokens=MAX_TOKENS) | |
| print("Generating candidates...") | |
| gen_start = time.time() | |
| outputs = llm.generate(prompts, sampling_params) | |
| gen_time = time.time() - gen_start | |
| print(f"Generation: {gen_time:.0f}s") | |
| sft_pairs: list[dict] = [] | |
| dpo_pairs: list[dict] = [] | |
| taxonomy = defaultdict(int) | |
| problem_results: dict[str, list[dict]] = defaultdict(list) | |
| # ONE persistent verification pool -- spawning 24 workers per problem | |
| # would cost ~700k process spawns over the full run. | |
| pool = Pool(processes=WORKERS) | |
| try: | |
| problems_processed = _process_outputs( | |
| outputs, all_problems, pool, sft_pairs, dpo_pairs, | |
| taxonomy, problem_results) | |
| finally: | |
| pool.close() | |
| pool.join() | |
| manifest = { | |
| "model": MODEL_NAME, | |
| "problems_processed": problems_processed, | |
| "candidates_per_problem": N_CANDIDATES, | |
| "verdict_taxonomy": dict(taxonomy), | |
| "sft_pairs": len(sft_pairs), | |
| "dpo_pairs": len(dpo_pairs), | |
| "generation_time_s": round(gen_time, 1), | |
| "total_wall_time_s": round(time.time() - wall_start, 1), | |
| "cost_estimate_usd_4090": round( | |
| (time.time() - wall_start) / 3600 * 0.35, 2), | |
| "early_stopped": len(sft_pairs) >= MAX_PAIRS, | |
| "gate_note": "Gate A: run benchmark_mode3_lean.py (PI_OFFICE_NLG_MODEL=Qwen/Qwen2.5-Math-7B-Instruct) on the pod before SFT.", | |
| } | |
| with open(os.path.join(OUT_DIR, "manifest.json"), "w") as f: | |
| json.dump(manifest, f, indent=2) | |
| print(json.dumps(manifest, indent=2)) | |
| print(f"SFT: {os.path.join(OUT_DIR, 'sft_dataset.jsonl')} " | |
| f"({len(sft_pairs)} pairs)") | |
| print(f"DPO: {os.path.join(OUT_DIR, 'dpo_dataset.jsonl')} " | |
| f"({len(dpo_pairs)} pairs)") | |
| return 0 | |
| def _process_outputs(outputs, all_problems, pool, sft_pairs, dpo_pairs, | |
| taxonomy, problem_results) -> None: | |
| # Verify per problem, so the MAX_PAIRS early stop and the DPO pairing | |
| # both work in one pass. | |
| for i, output in enumerate(outputs): | |
| problem = all_problems[i] | |
| tasks = [] | |
| for candidate in output.outputs: | |
| code = postprocess_code(candidate.text) | |
| if code is None: | |
| taxonomy["degenerate"] += 1 | |
| continue | |
| tasks.append({"problem_id": problem["id"], "code": code, | |
| "expected": problem["answer"]}) | |
| if not tasks: | |
| continue | |
| results = pool.map(verify_candidate, tasks) | |
| for task, res in zip(tasks, results): | |
| reason = res["reason"].split(":")[0] | |
| taxonomy[reason] += 1 | |
| problem_results[task["problem_id"]].append({ | |
| "problem": problem["problem"], "code": task["code"], | |
| "verdict": res["verdict"], "reason": res["reason"]}) | |
| for res, task in zip(results, tasks): | |
| if res["verdict"] is True: | |
| sft_pairs.append({ | |
| "messages": [ | |
| {"role": "system", "content": CODEGEN_SYSTEM}, | |
| {"role": "user", "content": user_content(problem["problem"])}, | |
| {"role": "assistant", "content": task["code"]}, | |
| ] | |
| }) | |
| print(f"[{i + 1}/{len(all_problems)}] sft_pairs={len(sft_pairs)} " | |
| f"tax={dict(taxonomy)}", flush=True) | |
| if len(sft_pairs) >= MAX_PAIRS: | |
| print(f"Early stop at {len(sft_pairs)} verified pairs") | |
| break | |
| # DPO pairs: chosen = verified, rejected = wrong/crash/gate/degenerate | |
| for pid, candidates in problem_results.items(): | |
| chosen = [c for c in candidates if c["verdict"] is True] | |
| rejected = [c for c in candidates if c["verdict"] is False] | |
| if chosen and rejected: | |
| dpo_pairs.append({ | |
| "prompt": candidates[0]["problem"], | |
| "system": CODEGEN_SYSTEM, | |
| "chosen": chosen[0]["code"], | |
| "rejected": rejected[0]["code"], | |
| }) | |
| with open(os.path.join(OUT_DIR, "sft_dataset.jsonl"), "w") as f: | |
| for pair in sft_pairs: | |
| f.write(json.dumps(pair) + "\n") | |
| with open(os.path.join(OUT_DIR, "dpo_dataset.jsonl"), "w") as f: | |
| for pair in dpo_pairs: | |
| f.write(json.dumps(pair) + "\n") | |
| with open(os.path.join(OUT_DIR, "verdict_log.jsonl"), "w") as f: | |
| for pid, candidates in problem_results.items(): | |
| for cand in candidates: | |
| f.write(json.dumps({"problem_id": pid, "code": cand["code"], | |
| "verdict": cand["verdict"], | |
| "reason": cand["reason"]}) + "\n") | |
| return i + 1 if len(sft_pairs) < MAX_PAIRS else i + 1 | |
| if __name__ == "__main__": | |
| import sys | |
| sys.exit(main()) | |