File size: 14,310 Bytes
17cb132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""
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())