Jay Glidden commited on
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- datasets/dpo_dataset.jsonl +0 -0
- datasets/manifest.json +21 -0
- datasets/sft_dataset.jsonl +3 -0
- datasets/verdict_log.jsonl +0 -0
- scripts/Dockerfile +23 -0
- scripts/benchmark_mode3_lean.py +270 -0
- scripts/day1_bootstrap.py +361 -0
- scripts/day2_sft.py +161 -0
- scripts/mode3_verify.py +184 -0
- scripts/onstart.sh +26 -0
- scripts/pi_office_symbolic_sandbox.py +259 -0
- scripts/pod_status.sh +20 -0
- scripts/run_checks.py +130 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
datasets/sft_dataset.jsonl filter=lfs diff=lfs merge=lfs -text
|
datasets/dpo_dataset.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
datasets/manifest.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "Qwen/Qwen2.5-Math-7B-Instruct",
|
| 3 |
+
"problems_processed": 6125,
|
| 4 |
+
"candidates_per_problem": 4,
|
| 5 |
+
"verdict_taxonomy": {
|
| 6 |
+
"degenerate": 10591,
|
| 7 |
+
"verified": 10001,
|
| 8 |
+
"no_result": 3342,
|
| 9 |
+
"crash": 95,
|
| 10 |
+
"wrong_caught": 458,
|
| 11 |
+
"gate_refused": 4,
|
| 12 |
+
"ambiguous": 9
|
| 13 |
+
},
|
| 14 |
+
"sft_pairs": 10001,
|
| 15 |
+
"dpo_pairs": 230,
|
| 16 |
+
"generation_time_s": 4172.2,
|
| 17 |
+
"total_wall_time_s": 6145.7,
|
| 18 |
+
"cost_estimate_usd_4090": 0.6,
|
| 19 |
+
"early_stopped": true,
|
| 20 |
+
"gate_note": "Gate A: run benchmark_mode3_lean.py (PI_OFFICE_NLG_MODEL=Qwen/Qwen2.5-Math-7B-Instruct) on the pod before SFT."
|
| 21 |
+
}
|
datasets/sft_dataset.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7051cc2009813fd94098056d4962002575d439e67d784bb2c26c116b735f8b8c
|
| 3 |
+
size 16103070
|
datasets/verdict_log.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/Dockerfile
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pi Office Math Bootstrap — multi-base Dockerfile
|
| 2 |
+
#
|
| 3 |
+
# Check image (local, fast): docker build --build-arg BASE=python:3.11-slim -t pi-office-math:check .
|
| 4 |
+
# Run image (pod, vllm base): docker build --build-arg BASE=vllm/vllm-openai:v0.26.0-x86_64 -t pi-office-math:run .
|
| 5 |
+
|
| 6 |
+
ARG BASE=python:3.11-slim
|
| 7 |
+
FROM ${BASE}
|
| 8 |
+
|
| 9 |
+
# Runtime deps (vllm/transformers/torch are already in the vllm base;
|
| 10 |
+
# harmless extra in the check base)
|
| 11 |
+
RUN pip install --no-cache-dir datasets sympy==1.14
|
| 12 |
+
|
| 13 |
+
WORKDIR /workspace
|
| 14 |
+
|
| 15 |
+
# The six-file dependency surface (nothing else from the repo)
|
| 16 |
+
COPY day1_bootstrap.py pi_office_symbolic_sandbox.py mode3_verify.py benchmark_mode3_lean.py ./
|
| 17 |
+
COPY benchmark_data/math500/test.jsonl benchmark_data/math500/
|
| 18 |
+
COPY benchmark_data/aime/test.jsonl benchmark_data/aime/
|
| 19 |
+
COPY run_checks.py ./
|
| 20 |
+
|
| 21 |
+
# Default: run the integration check suite.
|
| 22 |
+
# Override: docker run <image> python3 day1_bootstrap.py --dry-run 20
|
| 23 |
+
CMD ["python3", "run_checks.py"]
|
scripts/benchmark_mode3_lean.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Lean Mode 3 benchmark: MATH-500 through the symbolic sandbox ONLY.
|
| 3 |
+
|
| 4 |
+
Deliberately does NOT import pi_office_agentic_api (no frozen intent model
|
| 5 |
+
resident) - the 4B NLG model + the sandbox are the entire footprint, which
|
| 6 |
+
stays under the 16GB ceiling over long runs. Modes 1/2 are bypassed.
|
| 7 |
+
|
| 8 |
+
Correctness is verified in-run by sympy simplify-difference against the
|
| 9 |
+
MATH-500 ground truth (LaTeX parsed by sympy). The trust guarantee: no
|
| 10 |
+
result is ever presented as correct without that verification; anything
|
| 11 |
+
unverifiable is counted as uncertain, never claimed.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
ROOT = Path(__file__).resolve().parent
|
| 24 |
+
DATASET = ROOT / os.environ.get(
|
| 25 |
+
"PI_OFFICE_MODE3_DATASET", "benchmark_data/math500/test.jsonl"
|
| 26 |
+
)
|
| 27 |
+
OUTPUT = ROOT / os.environ.get(
|
| 28 |
+
"PI_OFFICE_MODE3_OUTPUT", "results/math500_mode3_lean_run.jsonl"
|
| 29 |
+
)
|
| 30 |
+
REPORT = ROOT / "results" / "math500_mode3_lean_report.json"
|
| 31 |
+
|
| 32 |
+
os.environ.setdefault("PI_OFFICE_NLG_MODEL", "lmstudio-community/Qwen3-VL-4B-Instruct-MLX-4bit")
|
| 33 |
+
|
| 34 |
+
def _backend_load(model_path: str, adapter_path: str | None = None):
|
| 35 |
+
"""Model loading with backend switch: mlx (default, local) or
|
| 36 |
+
transformers (CUDA pods)."""
|
| 37 |
+
backend = os.environ.get("PI_OFFICE_MODE3_BACKEND", "mlx")
|
| 38 |
+
if backend == "transformers":
|
| 39 |
+
import torch
|
| 40 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 41 |
+
|
| 42 |
+
from transformers import AutoConfig
|
| 43 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 44 |
+
# arch-based loading: VL models (e.g. Qwen3VLForConditionalGeneration)
|
| 45 |
+
# are not AutoModelForCausalLM-loadable
|
| 46 |
+
cfg = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
| 47 |
+
cls = getattr(__import__("transformers"), cfg.architectures[0])
|
| 48 |
+
try:
|
| 49 |
+
# transformers v5 renamed torch_dtype -> dtype
|
| 50 |
+
model = cls.from_pretrained(
|
| 51 |
+
model_path, dtype=torch.bfloat16, trust_remote_code=True)
|
| 52 |
+
except TypeError:
|
| 53 |
+
model = cls.from_pretrained(
|
| 54 |
+
model_path, torch_dtype=torch.bfloat16,
|
| 55 |
+
trust_remote_code=True)
|
| 56 |
+
# single-GPU pod: explicit .cuda() avoids the accelerate dependency
|
| 57 |
+
model = model.to("cuda")
|
| 58 |
+
return model, tokenizer
|
| 59 |
+
from mlx_lm import load
|
| 60 |
+
|
| 61 |
+
return load(model_path, adapter_path=adapter_path)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _backend_generate(model, tokenizer, *, prompt: str, max_tokens: int = 400,
|
| 65 |
+
verbose: bool = False) -> str:
|
| 66 |
+
"""Generation with backend switch (matches the mlx_lm.generate call
|
| 67 |
+
signature used by generate_code)."""
|
| 68 |
+
backend = os.environ.get("PI_OFFICE_MODE3_BACKEND", "mlx")
|
| 69 |
+
if backend == "transformers":
|
| 70 |
+
import torch
|
| 71 |
+
|
| 72 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 73 |
+
device = next(model.parameters()).device
|
| 74 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 75 |
+
pad = (tokenizer.pad_token_id if tokenizer.pad_token_id is not None
|
| 76 |
+
else tokenizer.eos_token_id)
|
| 77 |
+
out = model.generate(**inputs, max_new_tokens=max_tokens,
|
| 78 |
+
do_sample=False, pad_token_id=pad)
|
| 79 |
+
return tokenizer.decode(out[0][inputs["input_ids"].shape[1]:],
|
| 80 |
+
skip_special_tokens=True)
|
| 81 |
+
from mlx_lm import generate
|
| 82 |
+
|
| 83 |
+
return generate(model, tokenizer, prompt=prompt, max_tokens=max_tokens,
|
| 84 |
+
verbose=verbose)
|
| 85 |
+
|
| 86 |
+
import pi_office_symbolic_sandbox as sandbox # noqa: E402
|
| 87 |
+
|
| 88 |
+
CODEGEN_SYSTEM = (
|
| 89 |
+
"You are a Python code generator for a math sandbox. Respond with ONLY a "
|
| 90 |
+
"Python script that computes the answer using sympy. Never write prose, "
|
| 91 |
+
"explanations, or reasoning -- output is executed by a machine. The "
|
| 92 |
+
"script must assign the final answer to a variable named `result`. Do NOT "
|
| 93 |
+
"print anything.\n"
|
| 94 |
+
"Here are examples of the ONLY acceptable output format:\n"
|
| 95 |
+
"Example 1 (roots):\n"
|
| 96 |
+
"import sympy as sp\n"
|
| 97 |
+
"x = sp.symbols('x')\n"
|
| 98 |
+
"result = sp.solve(x**2 - 5*x + 6, x)\n"
|
| 99 |
+
"Example 2 (limit):\n"
|
| 100 |
+
"import sympy as sp\n"
|
| 101 |
+
"x = sp.symbols('x')\n"
|
| 102 |
+
"result = sp.limit(sp.sin(x)/x, x, 0)\n"
|
| 103 |
+
"Example 3 (integral):\n"
|
| 104 |
+
"import sympy as sp\n"
|
| 105 |
+
"x = sp.symbols('x')\n"
|
| 106 |
+
"result = sp.integrate(x**2, (x, 0, 2))\n"
|
| 107 |
+
"Example 4 (combinatorics):\n"
|
| 108 |
+
"import sympy as sp\n"
|
| 109 |
+
"result = sp.binomial(31, 28)"
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def generate_code(model, tokenizer, problem: str) -> str | None:
|
| 114 |
+
messages = [
|
| 115 |
+
{"role": "system", "content": CODEGEN_SYSTEM},
|
| 116 |
+
{"role": "user", "content": problem
|
| 117 |
+
+ "\n\nRespond with ONLY Python code. No prose, no explanations, "
|
| 118 |
+
"no reasoning."},
|
| 119 |
+
]
|
| 120 |
+
try:
|
| 121 |
+
prompt = tokenizer.apply_chat_template(
|
| 122 |
+
messages, add_generation_prompt=True, tokenize=False)
|
| 123 |
+
except TypeError:
|
| 124 |
+
# mlx tokenizers do not accept tokenize=False (always return str)
|
| 125 |
+
prompt = tokenizer.apply_chat_template(
|
| 126 |
+
messages, add_generation_prompt=True)
|
| 127 |
+
text = _backend_generate(model, tokenizer, prompt=prompt,
|
| 128 |
+
max_tokens=400, verbose=False).strip()
|
| 129 |
+
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
|
| 130 |
+
if text.startswith("```"):
|
| 131 |
+
lines = text.splitlines()
|
| 132 |
+
if lines and lines[0].startswith("```"):
|
| 133 |
+
lines = lines[1:]
|
| 134 |
+
text = "\n".join(lines).strip()
|
| 135 |
+
if text.endswith("```"):
|
| 136 |
+
text = text[:-3].strip()
|
| 137 |
+
fenced = re.search(r"```(?:python)?\s*(.*?)\s*```", text, re.S)
|
| 138 |
+
code = (fenced.group(1) if fenced else text).strip()
|
| 139 |
+
try:
|
| 140 |
+
parsed = json.loads(code)
|
| 141 |
+
if isinstance(parsed, dict) and (
|
| 142 |
+
"solver_id" in parsed or "solverid" in parsed
|
| 143 |
+
):
|
| 144 |
+
return None
|
| 145 |
+
except Exception:
|
| 146 |
+
pass
|
| 147 |
+
return code
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def robust_compare(expected_latex: str, result):
|
| 151 |
+
"""Delegates to mode3_verify -- the single source of truth."""
|
| 152 |
+
from mode3_verify import strong_compare
|
| 153 |
+
|
| 154 |
+
return strong_compare(expected_latex, result)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def classify(problem: str, answer: str) -> dict:
|
| 158 |
+
record: dict = {"problem": problem[:200], "answer": answer}
|
| 159 |
+
try:
|
| 160 |
+
code = generate_code(model, tokenizer, problem)
|
| 161 |
+
if not code:
|
| 162 |
+
record["mode"] = "refused"
|
| 163 |
+
record["reason"] = "codegen_empty"
|
| 164 |
+
return record
|
| 165 |
+
execution = sandbox.execute_sympy(code, timeout=15)
|
| 166 |
+
except sandbox.SandboxRefusal as error:
|
| 167 |
+
record["mode"] = "refused"
|
| 168 |
+
record["reason"] = f"gate:{error}"
|
| 169 |
+
record["code"] = code[:300] # diagnostic: store refused code
|
| 170 |
+
return record
|
| 171 |
+
except sandbox.SandboxError as error:
|
| 172 |
+
record["mode"] = "refused"
|
| 173 |
+
record["reason"] = f"sandbox:{error}"
|
| 174 |
+
record["code"] = code[:300] # diagnostic: store failing code
|
| 175 |
+
return record
|
| 176 |
+
except Exception as error:
|
| 177 |
+
record["mode"] = "refused"
|
| 178 |
+
record["reason"] = f"codegen:{type(error).__name__}"
|
| 179 |
+
return record
|
| 180 |
+
record["mode"] = "mode3"
|
| 181 |
+
record["code"] = code[:400]
|
| 182 |
+
record["code_hash"] = execution["generated_code_sha256"][:16]
|
| 183 |
+
record["execution_hash"] = execution["execution_hash"][:16]
|
| 184 |
+
record["stdout"] = execution["stdout"][:200]
|
| 185 |
+
try:
|
| 186 |
+
parsed = json.loads(execution["stdout"])
|
| 187 |
+
result = parsed.get("result")
|
| 188 |
+
except Exception:
|
| 189 |
+
result = None
|
| 190 |
+
record["result"] = None if result is None else str(result)[:200]
|
| 191 |
+
record["correct"] = robust_compare(answer, result)
|
| 192 |
+
return record
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def main() -> int:
|
| 196 |
+
# --slice math500|aime convenience flag (env vars still override)
|
| 197 |
+
global DATASET
|
| 198 |
+
if "--slice" in sys.argv:
|
| 199 |
+
which = sys.argv[sys.argv.index("--slice") + 1]
|
| 200 |
+
mapping = {
|
| 201 |
+
"math500": "benchmark_data/math500/test.jsonl",
|
| 202 |
+
"aime": "benchmark_data/aime/test.jsonl",
|
| 203 |
+
}
|
| 204 |
+
if which not in mapping:
|
| 205 |
+
raise SystemExit(f"unknown slice {which!r}; use math500|aime")
|
| 206 |
+
DATASET = ROOT / mapping[which]
|
| 207 |
+
os.environ.setdefault("PI_OFFICE_MODE3_COUNT",
|
| 208 |
+
"100" if which == "math500" else "30")
|
| 209 |
+
problems = [
|
| 210 |
+
json.loads(line) for line in DATASET.read_text(encoding="utf-8").splitlines()
|
| 211 |
+
][: int(os.environ.get("PI_OFFICE_MODE3_COUNT", "100"))]
|
| 212 |
+
print(f"lean run: {len(problems)} problems, single model (NLG only)", flush=True)
|
| 213 |
+
started = time.time()
|
| 214 |
+
counts = {"mode3": 0, "refused": 0, "correct": 0, "wrong": 0, "uncertain": 0}
|
| 215 |
+
with OUTPUT.open("w", encoding="utf-8") as handle:
|
| 216 |
+
for index, row in enumerate(problems, 1):
|
| 217 |
+
record = classify(row["problem"], row["answer"])
|
| 218 |
+
record["index"] = index
|
| 219 |
+
record["subject"] = row.get("subject")
|
| 220 |
+
record["level"] = row.get("level")
|
| 221 |
+
handle.write(json.dumps(record, ensure_ascii=True) + "\n")
|
| 222 |
+
handle.flush()
|
| 223 |
+
counts[record["mode"]] += 1
|
| 224 |
+
if record["mode"] == "mode3":
|
| 225 |
+
c = record.get("correct")
|
| 226 |
+
if c is True:
|
| 227 |
+
counts["correct"] += 1
|
| 228 |
+
elif c is False:
|
| 229 |
+
counts["wrong"] += 1
|
| 230 |
+
else:
|
| 231 |
+
counts["uncertain"] += 1
|
| 232 |
+
if index % 25 == 0:
|
| 233 |
+
print(
|
| 234 |
+
f"[{index}/100] {time.time()-started:.0f}s executed={counts['mode3']} "
|
| 235 |
+
f"correct={counts['correct']} wrong={counts['wrong']} "
|
| 236 |
+
f"uncertain={counts['uncertain']} refused={counts['refused']}",
|
| 237 |
+
flush=True,
|
| 238 |
+
)
|
| 239 |
+
report = {
|
| 240 |
+
"schema": "pi-office/frontier-benchmark/1",
|
| 241 |
+
"benchmark": "math500",
|
| 242 |
+
"run": "mode3_lean",
|
| 243 |
+
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
| 244 |
+
"counts": counts,
|
| 245 |
+
"metrics": {
|
| 246 |
+
"execution_rate": round(counts["mode3"] / 100, 4),
|
| 247 |
+
"execution_accuracy": round(
|
| 248 |
+
counts["correct"] / counts["mode3"], 4
|
| 249 |
+
) if counts["mode3"] else None,
|
| 250 |
+
"verified_correct": counts["correct"],
|
| 251 |
+
"wrong_execution_caught": counts["wrong"],
|
| 252 |
+
"uncertain": counts["uncertain"],
|
| 253 |
+
"refused": counts["refused"],
|
| 254 |
+
"trust_guarantee": (
|
| 255 |
+
"0 results presented as correct without sympy-verified "
|
| 256 |
+
"comparison; wrong-execution-caught receipts are reported openly"
|
| 257 |
+
),
|
| 258 |
+
},
|
| 259 |
+
}
|
| 260 |
+
REPORT.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8")
|
| 261 |
+
print(json.dumps(report["metrics"], indent=1))
|
| 262 |
+
return 0
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == "__main__":
|
| 266 |
+
adapter = os.environ.get("PI_OFFICE_NLG_ADAPTER") or None
|
| 267 |
+
model, tokenizer = _backend_load(
|
| 268 |
+
os.environ["PI_OFFICE_NLG_MODEL"], adapter_path=adapter)
|
| 269 |
+
print(f"adapter: {adapter or 'none'}", flush=True)
|
| 270 |
+
raise SystemExit(main())
|
scripts/day1_bootstrap.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
day1_bootstrap.py - Cloud vLLM Verifier-Filtered Bootstrap (corrected)
|
| 3 |
+
|
| 4 |
+
Runs on a cloud GPU pod (4090 24GB, vast.ai/runpod). Generates candidate sympy
|
| 5 |
+
code for GSM8K + MATH train sets with vLLM, verifies via the local Pi Office
|
| 6 |
+
sandbox (pi_office_symbolic_sandbox.py) and the strong comparator
|
| 7 |
+
(mode3_verify.py), and emits clean SFT and DPO datasets.
|
| 8 |
+
|
| 9 |
+
Verdict taxonomy (noise-free by construction):
|
| 10 |
+
verified -> strong_compare True -> SFT pair + DPO chosen
|
| 11 |
+
wrong -> strong_compare False -> DPO rejected (gold signal)
|
| 12 |
+
crash -> SandboxError / worker exception -> DPO rejected
|
| 13 |
+
gate -> SandboxRefusal (gate refusal) -> DPO rejected
|
| 14 |
+
degenerate-> intent-JSON codegen collapse -> DPO rejected
|
| 15 |
+
uncertain -> result is None / verdict None -> EXCLUDED from both datasets
|
| 16 |
+
|
| 17 |
+
API compatibility (verified against the local repo on 2026-08-04):
|
| 18 |
+
execute_sympy(code, timeout=15) -- no max_output kwarg; raises
|
| 19 |
+
SandboxRefusal (gate) and SandboxError (execution failure).
|
| 20 |
+
strong_compare(expected, result) -- True/False/None; NEVER pass the string
|
| 21 |
+
"None" -- pass the Python None (or the parsed result value directly).
|
| 22 |
+
|
| 23 |
+
Usage:
|
| 24 |
+
python3 day1_bootstrap.py --dry-run 20
|
| 25 |
+
python3 day1_bootstrap.py
|
| 26 |
+
"""
|
| 27 |
+
import argparse
|
| 28 |
+
import ast
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import re
|
| 32 |
+
import time
|
| 33 |
+
from collections import defaultdict
|
| 34 |
+
from multiprocessing import Pool
|
| 35 |
+
|
| 36 |
+
# --- Local infrastructure (upload alongside this script) ---
|
| 37 |
+
# vllm and datasets are imported lazily inside main()/load_datasets() so the
|
| 38 |
+
# module is importable for testing without those heavy deps installed.
|
| 39 |
+
from pi_office_symbolic_sandbox import execute_sympy, SandboxError, SandboxRefusal
|
| 40 |
+
from mode3_verify import strong_compare
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _load_codgen_system() -> str:
|
| 44 |
+
"""Extract CODEGEN_SYSTEM from benchmark_mode3_lean.py WITHOUT importing
|
| 45 |
+
it (it imports mlx_lm, which is Apple-only and unavailable on the pod)."""
|
| 46 |
+
import ast as _ast
|
| 47 |
+
module = _ast.parse(open("benchmark_mode3_lean.py").read())
|
| 48 |
+
for node in module.body:
|
| 49 |
+
if isinstance(node, _ast.Assign):
|
| 50 |
+
for target in node.targets:
|
| 51 |
+
if isinstance(target, _ast.Name) and target.id == "CODEGEN_SYSTEM":
|
| 52 |
+
if isinstance(node.value, _ast.Constant) and isinstance(node.value.value, str):
|
| 53 |
+
return node.value.value
|
| 54 |
+
raise RuntimeError("CODEGEN_SYSTEM not found in benchmark_mode3_lean.py")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
CODEGEN_SYSTEM = _load_codgen_system() # byte-identical proven prompt
|
| 58 |
+
|
| 59 |
+
MODEL_NAME = "Qwen/Qwen2.5-Math-7B-Instruct"
|
| 60 |
+
MAX_TOKENS = 450
|
| 61 |
+
TEMPERATURE = 0.7
|
| 62 |
+
N_CANDIDATES = 4
|
| 63 |
+
MAX_PAIRS = 10000
|
| 64 |
+
OUT_DIR = "bootstrap_output"
|
| 65 |
+
# verification pool size; lower under memory pressure, e.g. PI_OFFICE_WORKERS=16
|
| 66 |
+
WORKERS = int(os.environ.get("PI_OFFICE_WORKERS", "32"))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def postprocess_code(text: str) -> str | None:
|
| 70 |
+
"""Same pipeline as benchmark_mode3_lean.generate_code (minus the model)."""
|
| 71 |
+
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S)
|
| 72 |
+
if text.startswith("```"):
|
| 73 |
+
lines = text.splitlines()
|
| 74 |
+
if lines and lines[0].startswith("```"):
|
| 75 |
+
lines = lines[1:]
|
| 76 |
+
text = "\n".join(lines).strip()
|
| 77 |
+
if text.endswith("```"):
|
| 78 |
+
text = text[:-3].strip()
|
| 79 |
+
fenced = re.search(r"```(?:python)?\s*(.*?)\s*```", text, re.S)
|
| 80 |
+
code = (fenced.group(1) if fenced else text).strip()
|
| 81 |
+
if not code:
|
| 82 |
+
return None
|
| 83 |
+
# prose / invalid Python -> None: the model wrote English instead of code
|
| 84 |
+
# (the 7B's dominant failure mode). Rejected before the sandbox.
|
| 85 |
+
try:
|
| 86 |
+
ast.parse(code)
|
| 87 |
+
except SyntaxError:
|
| 88 |
+
return None
|
| 89 |
+
# intent-JSON degeneracy guard (matches generate_code)
|
| 90 |
+
try:
|
| 91 |
+
parsed = json.loads(code)
|
| 92 |
+
if isinstance(parsed, dict) and (
|
| 93 |
+
"solver_id" in parsed or "solverid" in parsed
|
| 94 |
+
):
|
| 95 |
+
return None
|
| 96 |
+
except Exception:
|
| 97 |
+
pass
|
| 98 |
+
return code
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def extract_gsm8k_answer(answer_text: str) -> str:
|
| 102 |
+
"""Trailing number from a GSM8K chain-of-thought answer."""
|
| 103 |
+
match = re.findall(r"\d+", answer_text.replace(",", ""))
|
| 104 |
+
return match[-1] if match else ""
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _load_math() -> list:
|
| 108 |
+
"""MATH train rows, trying public sources first.
|
| 109 |
+
|
| 110 |
+
Verified live on 2026-08-04 (pod): hendrycks/competition_math is
|
| 111 |
+
401-GATED (metadata public, data needs auth) -- only usable with
|
| 112 |
+
HF_TOKEN. EleutherAI/hendrycks_math is public but multi-config
|
| 113 |
+
(7 subject splits), so load each config and concatenate.
|
| 114 |
+
"""
|
| 115 |
+
from datasets import load_dataset
|
| 116 |
+
|
| 117 |
+
def src_eleuther() -> list:
|
| 118 |
+
configs = ["algebra", "counting_and_probability", "geometry",
|
| 119 |
+
"intermediate_algebra", "number_theory", "prealgebra",
|
| 120 |
+
"precalculus"]
|
| 121 |
+
rows = []
|
| 122 |
+
for cfg in configs:
|
| 123 |
+
rows.extend(load_dataset("EleutherAI/hendrycks_math", cfg,
|
| 124 |
+
split="train"))
|
| 125 |
+
return rows
|
| 126 |
+
|
| 127 |
+
def src_hendrycks() -> list:
|
| 128 |
+
return list(load_dataset("hendrycks/competition_math", split="train",
|
| 129 |
+
trust_remote_code=True))
|
| 130 |
+
|
| 131 |
+
sources = [
|
| 132 |
+
("EleutherAI/hendrycks_math (7 configs, public)", src_eleuther),
|
| 133 |
+
("hendrycks/competition_math (gated, needs HF_TOKEN)", src_hendrycks),
|
| 134 |
+
]
|
| 135 |
+
errors = []
|
| 136 |
+
for label, loader in sources:
|
| 137 |
+
try:
|
| 138 |
+
rows = loader()
|
| 139 |
+
print(f"MATH source: {label} ({len(rows)} rows)")
|
| 140 |
+
return rows
|
| 141 |
+
except Exception as exc:
|
| 142 |
+
errors.append(f"{label}: {type(exc).__name__}: {str(exc)[:150]}")
|
| 143 |
+
raise RuntimeError("all MATH sources failed:\n" + "\n".join(errors))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def load_datasets() -> list[dict]:
|
| 147 |
+
"""GSM8K train + MATH train, normalized. IDs are counters -- the HF
|
| 148 |
+
datasets expose no usable id fields."""
|
| 149 |
+
from datasets import load_dataset
|
| 150 |
+
|
| 151 |
+
problems = []
|
| 152 |
+
gsm8k = load_dataset("openai/gsm8k", "main", split="train")
|
| 153 |
+
for i, row in enumerate(gsm8k):
|
| 154 |
+
problems.append({
|
| 155 |
+
"id": f"gsm8k_{i}",
|
| 156 |
+
"problem": row["question"],
|
| 157 |
+
"answer": extract_gsm8k_answer(row["answer"]),
|
| 158 |
+
})
|
| 159 |
+
print(f"GSM8K loaded: {len(problems)} problems")
|
| 160 |
+
|
| 161 |
+
math = _load_math()
|
| 162 |
+
math_start = len(problems)
|
| 163 |
+
for i, row in enumerate(math):
|
| 164 |
+
# LAST boxed answer is the final answer; solutions contain
|
| 165 |
+
# intermediate \boxed{} values too. An explicit answer field wins.
|
| 166 |
+
answer_field = row.get("answer")
|
| 167 |
+
boxed = re.findall(r"\\boxed\{([^}]+)\}", str(row.get("solution", "")))
|
| 168 |
+
if not answer_field and not boxed:
|
| 169 |
+
continue
|
| 170 |
+
problems.append({
|
| 171 |
+
"id": f"math_{i}",
|
| 172 |
+
"problem": str(row["problem"]),
|
| 173 |
+
"answer": (str(answer_field).strip() if answer_field
|
| 174 |
+
else boxed[-1].strip()),
|
| 175 |
+
})
|
| 176 |
+
print(f"MATH loaded: {len(problems) - math_start} problems")
|
| 177 |
+
return problems
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
USER_DIRECTIVE = "\n\nRespond with ONLY Python code. No prose, no explanations, no reasoning."
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def user_content(problem: str) -> str:
|
| 184 |
+
"""User turn for generation AND for the SFT pairs -- must match the
|
| 185 |
+
benchmark runner's generate_code exactly (prompt consistency)."""
|
| 186 |
+
return problem + USER_DIRECTIVE
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def verify_candidate(task: dict) -> dict:
|
| 190 |
+
"""Pool worker: sandbox + strong comparator, exception-classified."""
|
| 191 |
+
code = task["code"]
|
| 192 |
+
expected = task["expected"]
|
| 193 |
+
try:
|
| 194 |
+
execution = execute_sympy(code, timeout=15)
|
| 195 |
+
except SandboxRefusal as exc:
|
| 196 |
+
return {"verdict": False, "result": None, "reason": "gate_refused"}
|
| 197 |
+
except SandboxError as exc:
|
| 198 |
+
return {"verdict": False, "result": None,
|
| 199 |
+
"reason": f"crash:{str(exc)[:80]}"}
|
| 200 |
+
except Exception as exc:
|
| 201 |
+
return {"verdict": False, "result": None,
|
| 202 |
+
"reason": f"worker_exception:{type(exc).__name__}"}
|
| 203 |
+
try:
|
| 204 |
+
output = json.loads(execution["stdout"])
|
| 205 |
+
except Exception as exc:
|
| 206 |
+
return {"verdict": False, "result": None,
|
| 207 |
+
"reason": f"bad_stdout:{type(exc).__name__}"}
|
| 208 |
+
result = output.get("result")
|
| 209 |
+
if result is None:
|
| 210 |
+
return {"verdict": None, "result": None, "reason": "no_result"}
|
| 211 |
+
verdict = strong_compare(expected, result)
|
| 212 |
+
if verdict is None:
|
| 213 |
+
return {"verdict": None, "result": str(result), "reason": "ambiguous"}
|
| 214 |
+
return {"verdict": verdict, "result": str(result),
|
| 215 |
+
"reason": "verified" if verdict else "wrong_caught"}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main() -> int:
|
| 219 |
+
parser = argparse.ArgumentParser()
|
| 220 |
+
parser.add_argument("--dry-run", type=int, default=0)
|
| 221 |
+
args = parser.parse_args()
|
| 222 |
+
|
| 223 |
+
wall_start = time.time()
|
| 224 |
+
os.makedirs(OUT_DIR, exist_ok=True)
|
| 225 |
+
|
| 226 |
+
all_problems = load_datasets()
|
| 227 |
+
if args.dry_run > 0:
|
| 228 |
+
all_problems = all_problems[: args.dry_run]
|
| 229 |
+
print(f"Problems to process: {len(all_problems)}")
|
| 230 |
+
|
| 231 |
+
from vllm import LLM, SamplingParams
|
| 232 |
+
llm = LLM(model=MODEL_NAME, tensor_parallel_size=1,
|
| 233 |
+
gpu_memory_utilization=0.9)
|
| 234 |
+
tokenizer = llm.get_tokenizer()
|
| 235 |
+
|
| 236 |
+
prompts = []
|
| 237 |
+
for p in all_problems:
|
| 238 |
+
messages = [
|
| 239 |
+
{"role": "system", "content": CODEGEN_SYSTEM},
|
| 240 |
+
{"role": "user", "content": user_content(p["problem"])},
|
| 241 |
+
]
|
| 242 |
+
prompts.append(tokenizer.apply_chat_template(
|
| 243 |
+
messages, tokenize=False, add_generation_prompt=True))
|
| 244 |
+
|
| 245 |
+
sampling_params = SamplingParams(n=N_CANDIDATES,
|
| 246 |
+
temperature=TEMPERATURE,
|
| 247 |
+
max_tokens=MAX_TOKENS)
|
| 248 |
+
print("Generating candidates...")
|
| 249 |
+
gen_start = time.time()
|
| 250 |
+
outputs = llm.generate(prompts, sampling_params)
|
| 251 |
+
gen_time = time.time() - gen_start
|
| 252 |
+
print(f"Generation: {gen_time:.0f}s")
|
| 253 |
+
|
| 254 |
+
sft_pairs: list[dict] = []
|
| 255 |
+
dpo_pairs: list[dict] = []
|
| 256 |
+
taxonomy = defaultdict(int)
|
| 257 |
+
problem_results: dict[str, list[dict]] = defaultdict(list)
|
| 258 |
+
|
| 259 |
+
# ONE persistent verification pool -- spawning 24 workers per problem
|
| 260 |
+
# would cost ~700k process spawns over the full run.
|
| 261 |
+
pool = Pool(processes=WORKERS)
|
| 262 |
+
try:
|
| 263 |
+
problems_processed = _process_outputs(
|
| 264 |
+
outputs, all_problems, pool, sft_pairs, dpo_pairs,
|
| 265 |
+
taxonomy, problem_results)
|
| 266 |
+
finally:
|
| 267 |
+
pool.close()
|
| 268 |
+
pool.join()
|
| 269 |
+
|
| 270 |
+
manifest = {
|
| 271 |
+
"model": MODEL_NAME,
|
| 272 |
+
"problems_processed": problems_processed,
|
| 273 |
+
"candidates_per_problem": N_CANDIDATES,
|
| 274 |
+
"verdict_taxonomy": dict(taxonomy),
|
| 275 |
+
"sft_pairs": len(sft_pairs),
|
| 276 |
+
"dpo_pairs": len(dpo_pairs),
|
| 277 |
+
"generation_time_s": round(gen_time, 1),
|
| 278 |
+
"total_wall_time_s": round(time.time() - wall_start, 1),
|
| 279 |
+
"cost_estimate_usd_4090": round(
|
| 280 |
+
(time.time() - wall_start) / 3600 * 0.35, 2),
|
| 281 |
+
"early_stopped": len(sft_pairs) >= MAX_PAIRS,
|
| 282 |
+
"gate_note": "Gate A: run benchmark_mode3_lean.py (PI_OFFICE_NLG_MODEL=Qwen/Qwen2.5-Math-7B-Instruct) on the pod before SFT.",
|
| 283 |
+
}
|
| 284 |
+
with open(os.path.join(OUT_DIR, "manifest.json"), "w") as f:
|
| 285 |
+
json.dump(manifest, f, indent=2)
|
| 286 |
+
print(json.dumps(manifest, indent=2))
|
| 287 |
+
print(f"SFT: {os.path.join(OUT_DIR, 'sft_dataset.jsonl')} "
|
| 288 |
+
f"({len(sft_pairs)} pairs)")
|
| 289 |
+
print(f"DPO: {os.path.join(OUT_DIR, 'dpo_dataset.jsonl')} "
|
| 290 |
+
f"({len(dpo_pairs)} pairs)")
|
| 291 |
+
return 0
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _process_outputs(outputs, all_problems, pool, sft_pairs, dpo_pairs,
|
| 295 |
+
taxonomy, problem_results) -> None:
|
| 296 |
+
# Verify per problem, so the MAX_PAIRS early stop and the DPO pairing
|
| 297 |
+
# both work in one pass.
|
| 298 |
+
for i, output in enumerate(outputs):
|
| 299 |
+
problem = all_problems[i]
|
| 300 |
+
tasks = []
|
| 301 |
+
for candidate in output.outputs:
|
| 302 |
+
code = postprocess_code(candidate.text)
|
| 303 |
+
if code is None:
|
| 304 |
+
taxonomy["degenerate"] += 1
|
| 305 |
+
continue
|
| 306 |
+
tasks.append({"problem_id": problem["id"], "code": code,
|
| 307 |
+
"expected": problem["answer"]})
|
| 308 |
+
if not tasks:
|
| 309 |
+
continue
|
| 310 |
+
results = pool.map(verify_candidate, tasks)
|
| 311 |
+
for task, res in zip(tasks, results):
|
| 312 |
+
reason = res["reason"].split(":")[0]
|
| 313 |
+
taxonomy[reason] += 1
|
| 314 |
+
problem_results[task["problem_id"]].append({
|
| 315 |
+
"problem": problem["problem"], "code": task["code"],
|
| 316 |
+
"verdict": res["verdict"], "reason": res["reason"]})
|
| 317 |
+
for res, task in zip(results, tasks):
|
| 318 |
+
if res["verdict"] is True:
|
| 319 |
+
sft_pairs.append({
|
| 320 |
+
"messages": [
|
| 321 |
+
{"role": "system", "content": CODEGEN_SYSTEM},
|
| 322 |
+
{"role": "user", "content": user_content(problem["problem"])},
|
| 323 |
+
{"role": "assistant", "content": task["code"]},
|
| 324 |
+
]
|
| 325 |
+
})
|
| 326 |
+
print(f"[{i + 1}/{len(all_problems)}] sft_pairs={len(sft_pairs)} "
|
| 327 |
+
f"tax={dict(taxonomy)}", flush=True)
|
| 328 |
+
if len(sft_pairs) >= MAX_PAIRS:
|
| 329 |
+
print(f"Early stop at {len(sft_pairs)} verified pairs")
|
| 330 |
+
break
|
| 331 |
+
|
| 332 |
+
# DPO pairs: chosen = verified, rejected = wrong/crash/gate/degenerate
|
| 333 |
+
for pid, candidates in problem_results.items():
|
| 334 |
+
chosen = [c for c in candidates if c["verdict"] is True]
|
| 335 |
+
rejected = [c for c in candidates if c["verdict"] is False]
|
| 336 |
+
if chosen and rejected:
|
| 337 |
+
dpo_pairs.append({
|
| 338 |
+
"prompt": candidates[0]["problem"],
|
| 339 |
+
"system": CODEGEN_SYSTEM,
|
| 340 |
+
"chosen": chosen[0]["code"],
|
| 341 |
+
"rejected": rejected[0]["code"],
|
| 342 |
+
})
|
| 343 |
+
|
| 344 |
+
with open(os.path.join(OUT_DIR, "sft_dataset.jsonl"), "w") as f:
|
| 345 |
+
for pair in sft_pairs:
|
| 346 |
+
f.write(json.dumps(pair) + "\n")
|
| 347 |
+
with open(os.path.join(OUT_DIR, "dpo_dataset.jsonl"), "w") as f:
|
| 348 |
+
for pair in dpo_pairs:
|
| 349 |
+
f.write(json.dumps(pair) + "\n")
|
| 350 |
+
with open(os.path.join(OUT_DIR, "verdict_log.jsonl"), "w") as f:
|
| 351 |
+
for pid, candidates in problem_results.items():
|
| 352 |
+
for cand in candidates:
|
| 353 |
+
f.write(json.dumps({"problem_id": pid, "code": cand["code"],
|
| 354 |
+
"verdict": cand["verdict"],
|
| 355 |
+
"reason": cand["reason"]}) + "\n")
|
| 356 |
+
return i + 1 if len(sft_pairs) < MAX_PAIRS else i + 1
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
if __name__ == "__main__":
|
| 360 |
+
import sys
|
| 361 |
+
sys.exit(main())
|
scripts/day2_sft.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""day2_sft.py -- LoRA SFT on the bootstrap's verified pairs (Gate B/C).
|
| 2 |
+
|
| 3 |
+
Runs on the cloud pod (transformers + peft; no unsloth -- its wheels target
|
| 4 |
+
torch 2.4-2.6 and the pod runs torch 2.11). bf16 base + LoRA (no
|
| 5 |
+
bitsandbytes): a 4B base needs ~8GB, a 7B ~15GB -- both fit 24GB.
|
| 6 |
+
|
| 7 |
+
Usage (on the pod):
|
| 8 |
+
python3 day2_sft.py --base Qwen/Qwen3-VL-4B-Instruct \
|
| 9 |
+
--data bootstrap_output/sft_dataset.jsonl \
|
| 10 |
+
--out adapters/gate_b_4b \
|
| 11 |
+
--epochs 2 --lr 2e-4
|
| 12 |
+
python3 day2_sft.py --merge --base <base> --adapter adapters/gate_b_4b \
|
| 13 |
+
--out models/gate_b_4b_merged
|
| 14 |
+
Then benchmark with PI_OFFICE_NLG_MODEL=models/gate_b_4b_merged.
|
| 15 |
+
"""
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def build_dataset(path: str, out_dir: str) -> tuple[str, str]:
|
| 23 |
+
"""Split messages-format pairs into train/valid jsonl."""
|
| 24 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 25 |
+
rows = [json.loads(l) for l in open(path)]
|
| 26 |
+
# deterministic 5% holdout (same seed as the check-split convention)
|
| 27 |
+
valid_idx = set(
|
| 28 |
+
i for i in range(len(rows)) if hash(f"gate-{i}") % 20 == 0)
|
| 29 |
+
train_path = os.path.join(out_dir, "train.jsonl")
|
| 30 |
+
valid_path = os.path.join(out_dir, "valid.jsonl")
|
| 31 |
+
with open(train_path, "w") as tf, open(valid_path, "w") as vf:
|
| 32 |
+
for i, row in enumerate(rows):
|
| 33 |
+
line = json.dumps(row) + "\n"
|
| 34 |
+
(vf if i in valid_idx else tf).write(line)
|
| 35 |
+
print(f"dataset: {len(rows)} rows -> train {len(rows) - len(valid_idx)}, "
|
| 36 |
+
f"valid {len(valid_idx)}")
|
| 37 |
+
return train_path, valid_path
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def train(args) -> int:
|
| 41 |
+
import torch
|
| 42 |
+
from datasets import load_dataset
|
| 43 |
+
from peft import LoraConfig, get_peft_model
|
| 44 |
+
from transformers import (AutoConfig, AutoTokenizer,
|
| 45 |
+
DataCollatorForSeq2Seq, Trainer,
|
| 46 |
+
TrainingArguments)
|
| 47 |
+
|
| 48 |
+
train_path, valid_path = build_dataset(args.data, args.out)
|
| 49 |
+
train_ds = load_dataset("json", data_files=train_path, split="train")
|
| 50 |
+
valid_ds = load_dataset("json", data_files=valid_path, split="train")
|
| 51 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 52 |
+
args.base, trust_remote_code=True)
|
| 53 |
+
if tokenizer.pad_token is None:
|
| 54 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 55 |
+
|
| 56 |
+
def _template(messages):
|
| 57 |
+
# VL models sometimes keep the chat template in the processor only
|
| 58 |
+
try:
|
| 59 |
+
return tokenizer.apply_chat_template(messages, tokenize=False,
|
| 60 |
+
add_generation_prompt=False)
|
| 61 |
+
except AttributeError:
|
| 62 |
+
from transformers import AutoProcessor
|
| 63 |
+
proc = AutoProcessor.from_pretrained(
|
| 64 |
+
args.base, trust_remote_code=True)
|
| 65 |
+
return proc.apply_chat_template(messages, tokenize=False,
|
| 66 |
+
add_generation_prompt=False)
|
| 67 |
+
|
| 68 |
+
def tokenize(batch):
|
| 69 |
+
texts = [_template(m) for m in batch["messages"]]
|
| 70 |
+
enc = tokenizer(texts, truncation=True, max_length=1024,
|
| 71 |
+
padding=False)
|
| 72 |
+
enc["labels"] = enc["input_ids"].copy()
|
| 73 |
+
return enc
|
| 74 |
+
|
| 75 |
+
train_ds = train_ds.map(tokenize, batched=True, remove_columns=["messages"])
|
| 76 |
+
valid_ds = valid_ds.map(tokenize, batched=True, remove_columns=["messages"])
|
| 77 |
+
|
| 78 |
+
cfg = AutoConfig.from_pretrained(args.base, trust_remote_code=True)
|
| 79 |
+
cls = getattr(__import__("transformers"), cfg.architectures[0])
|
| 80 |
+
model = cls.from_pretrained(
|
| 81 |
+
args.base, dtype=torch.bfloat16, trust_remote_code=True)
|
| 82 |
+
peft = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
|
| 83 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
|
| 84 |
+
"gate_proj", "up_proj", "down_proj"],
|
| 85 |
+
task_type="CAUSAL_LM")
|
| 86 |
+
model = get_peft_model(model, peft)
|
| 87 |
+
model.print_trainable_parameters()
|
| 88 |
+
|
| 89 |
+
training_args = TrainingArguments(
|
| 90 |
+
output_dir=args.out,
|
| 91 |
+
per_device_train_batch_size=1,
|
| 92 |
+
per_device_eval_batch_size=1,
|
| 93 |
+
gradient_accumulation_steps=8,
|
| 94 |
+
learning_rate=args.lr,
|
| 95 |
+
num_train_epochs=args.epochs,
|
| 96 |
+
logging_steps=50,
|
| 97 |
+
save_strategy="epoch",
|
| 98 |
+
eval_strategy="epoch",
|
| 99 |
+
bf16=True,
|
| 100 |
+
report_to=[],
|
| 101 |
+
dataloader_num_workers=4,
|
| 102 |
+
remove_unused_columns=False,
|
| 103 |
+
seed=0,
|
| 104 |
+
)
|
| 105 |
+
trainer = Trainer(
|
| 106 |
+
model=model,
|
| 107 |
+
args=training_args,
|
| 108 |
+
train_dataset=train_ds,
|
| 109 |
+
eval_dataset=valid_ds,
|
| 110 |
+
data_collator=DataCollatorForSeq2Seq(
|
| 111 |
+
tokenizer, pad_to_multiple_of=8, padding=True),
|
| 112 |
+
)
|
| 113 |
+
started = time.time()
|
| 114 |
+
trainer.train()
|
| 115 |
+
trainer.save_model(args.out)
|
| 116 |
+
print(f"training done in {time.time() - started:.0f}s -> {args.out}")
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def merge(args) -> int:
|
| 121 |
+
import torch
|
| 122 |
+
from peft import PeftModel
|
| 123 |
+
from transformers import AutoConfig, AutoTokenizer
|
| 124 |
+
|
| 125 |
+
os.makedirs(args.out, exist_ok=True)
|
| 126 |
+
cfg = AutoConfig.from_pretrained(args.base, trust_remote_code=True)
|
| 127 |
+
cls = getattr(__import__("transformers"), cfg.architectures[0])
|
| 128 |
+
model = cls.from_pretrained(
|
| 129 |
+
args.base, dtype=torch.bfloat16, trust_remote_code=True)
|
| 130 |
+
model = PeftModel.from_pretrained(model, args.adapter)
|
| 131 |
+
merged = model.merge_and_unload()
|
| 132 |
+
merged.save_pretrained(args.out, safe_serialization=True)
|
| 133 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 134 |
+
args.base, trust_remote_code=True)
|
| 135 |
+
tokenizer.save_pretrained(args.out)
|
| 136 |
+
print(f"merged -> {args.out}")
|
| 137 |
+
return 0
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def main() -> int:
|
| 141 |
+
parser = argparse.ArgumentParser()
|
| 142 |
+
sub = parser.add_subparsers(dest="mode", required=True)
|
| 143 |
+
t = sub.add_parser("train")
|
| 144 |
+
t.add_argument("--base", required=True)
|
| 145 |
+
t.add_argument("--data", required=True)
|
| 146 |
+
t.add_argument("--out", required=True)
|
| 147 |
+
t.add_argument("--epochs", type=int, default=2)
|
| 148 |
+
t.add_argument("--lr", type=float, default=2e-4)
|
| 149 |
+
m = sub.add_parser("merge")
|
| 150 |
+
m.add_argument("--base", required=True)
|
| 151 |
+
m.add_argument("--adapter", required=True)
|
| 152 |
+
m.add_argument("--out", required=True)
|
| 153 |
+
args = parser.parse_args()
|
| 154 |
+
if args.mode == "train":
|
| 155 |
+
return train(args)
|
| 156 |
+
return merge(args)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
import sys
|
| 161 |
+
sys.exit(main())
|
scripts/mode3_verify.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""mode3_verify.py -- the mode-3 answer verifier (single source of truth).
|
| 2 |
+
|
| 3 |
+
Strong comparator: LaTeX-normalization layer + sympy-exact equality, with a
|
| 4 |
+
float tolerance fallback and exact-string matching for word answers.
|
| 5 |
+
Returns True (verified match), False (verified mismatch), None (genuinely
|
| 6 |
+
ambiguous -- the caller must treat this as "not certifiable").
|
| 7 |
+
|
| 8 |
+
Unit checks live in __main__; run: python3 mode3_verify.py
|
| 9 |
+
"""
|
| 10 |
+
import re
|
| 11 |
+
from fractions import Fraction # noqa: F401 (kept for clarity)
|
| 12 |
+
import sympy as sp
|
| 13 |
+
|
| 14 |
+
_SPACING_TOKENS = ("\\left", "\\right", "\\!", "\\,", "\\;", "\\quad", "\\qquad")
|
| 15 |
+
_WRAPPER = re.compile(r"\\(?:text|boxed)\{([^{}]*)\}")
|
| 16 |
+
_MIXED_NUMBER = re.compile(r"([+-]?\d+)(\\[dt]?frac\{([^{}]*)\}\{([^{}]*)\})")
|
| 17 |
+
_BRACED_FRACTION = re.compile(r"\\[dt]?frac\{([^{}]*)\}\{([^{}]*)\}")
|
| 18 |
+
_DEGREE = re.compile(r"\^?\s*\{\s*\\circ\s*\}|\^?\\circ|°|\bdegrees?\b")
|
| 19 |
+
_POW_BRACED = re.compile(r"\^\{([^{}]*)\}")
|
| 20 |
+
_FUNCTION_BRACE = re.compile(r"([a-zA-Z]+)\{([^{}]*)\}")
|
| 21 |
+
_SYMBOL_MAP = {
|
| 22 |
+
"\\pi": "pi",
|
| 23 |
+
"\\sqrt": "sqrt",
|
| 24 |
+
"\\cdot": "*",
|
| 25 |
+
"\\times": "*",
|
| 26 |
+
"\\div": "/",
|
| 27 |
+
"\\pm": "±",
|
| 28 |
+
"\\infty": "oo",
|
| 29 |
+
"\\ell": "l",
|
| 30 |
+
}
|
| 31 |
+
_THOUSAND_COMMA = re.compile(r"(?<=\d),(?=\d)")
|
| 32 |
+
_IMAG_LOWER = re.compile(r"(?<=\d)i")
|
| 33 |
+
_IMAG_IMPLICIT_MUL = re.compile(r"(?<=\d)I")
|
| 34 |
+
_TOLERANCE = 1e-9
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def normalize_latex(value) -> str:
|
| 38 |
+
"""Reduce LaTeX/plain text to a sympify-able or string-comparable form."""
|
| 39 |
+
text = str(value).strip()
|
| 40 |
+
if not text:
|
| 41 |
+
return ""
|
| 42 |
+
text = text.replace("$", "")
|
| 43 |
+
for token in _SPACING_TOKENS:
|
| 44 |
+
text = text.replace(token, "")
|
| 45 |
+
# unwrap \text{...} and \boxed{...} wrappers (repeat for nesting)
|
| 46 |
+
while True:
|
| 47 |
+
unwrapped = _WRAPPER.sub(r"\1", text)
|
| 48 |
+
if unwrapped == text:
|
| 49 |
+
break
|
| 50 |
+
text = unwrapped
|
| 51 |
+
# mixed numbers: 3\frac{1}{2} -> 3 + (1/2)
|
| 52 |
+
while True:
|
| 53 |
+
mixed = _MIXED_NUMBER.sub(lambda m: f"{m.group(1)} + ({m.group(3)}/{m.group(4)})", text)
|
| 54 |
+
if mixed == text:
|
| 55 |
+
break
|
| 56 |
+
text = mixed
|
| 57 |
+
# \frac{a}{b} -> (a/b), innermost first (loop handles nesting)
|
| 58 |
+
while True:
|
| 59 |
+
frac = _BRACED_FRACTION.sub(r"(\1/\2)", text)
|
| 60 |
+
if frac == text:
|
| 61 |
+
break
|
| 62 |
+
text = frac
|
| 63 |
+
# degree markers removed before any power handling
|
| 64 |
+
text = _DEGREE.sub("", text)
|
| 65 |
+
for token, replacement in _SYMBOL_MAP.items():
|
| 66 |
+
text = text.replace(token, replacement)
|
| 67 |
+
text = _POW_BRACED.sub(r"**(\1)", text)
|
| 68 |
+
text = text.replace("^", "**")
|
| 69 |
+
text = _FUNCTION_BRACE.sub(r"\1(\2)", text)
|
| 70 |
+
# imaginary unit: 6-5i -> 6-5I -> 6-5*I
|
| 71 |
+
text = _IMAG_LOWER.sub("I", text)
|
| 72 |
+
text = _IMAG_IMPLICIT_MUL.sub("*I", text)
|
| 73 |
+
text = _THOUSAND_COMMA.sub("", text)
|
| 74 |
+
text = re.sub(r"\s+", "", text)
|
| 75 |
+
# AIME-style leading zeros: 025 -> 25 (keep 0, 0.5, and 0x intact)
|
| 76 |
+
text = re.sub(r"^0+(?=\d)", "", text)
|
| 77 |
+
return text
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _to_expr(text: str):
|
| 81 |
+
"""sympy expression or None; ± is resolved by trying both branches."""
|
| 82 |
+
if not text:
|
| 83 |
+
return None
|
| 84 |
+
candidates = [text]
|
| 85 |
+
if "±" in text:
|
| 86 |
+
candidates = [text.replace("±", "+"), text.replace("±", "-")]
|
| 87 |
+
for candidate in candidates:
|
| 88 |
+
try:
|
| 89 |
+
return sp.sympify(candidate)
|
| 90 |
+
except Exception:
|
| 91 |
+
continue
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _pairwise_equal(left, right) -> bool | None:
|
| 96 |
+
"""Elementwise compare of sequences (root lists, tuples)."""
|
| 97 |
+
if len(left) != len(right):
|
| 98 |
+
return False
|
| 99 |
+
for a, b in zip(left, right):
|
| 100 |
+
verdict = strong_compare(a, b)
|
| 101 |
+
if verdict is not True:
|
| 102 |
+
return False
|
| 103 |
+
return True
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def strong_compare(expected, result) -> bool | None:
|
| 107 |
+
"""True / False / None (unverifiable). Exact-first, tolerance fallback."""
|
| 108 |
+
if result is None:
|
| 109 |
+
return None
|
| 110 |
+
e_text = normalize_latex(expected)
|
| 111 |
+
r_text = normalize_latex(result)
|
| 112 |
+
if e_text == r_text and e_text:
|
| 113 |
+
return True
|
| 114 |
+
e_expr = _to_expr(e_text)
|
| 115 |
+
r_expr = _to_expr(r_text)
|
| 116 |
+
if e_expr is None or r_expr is None:
|
| 117 |
+
# word answers (e.g. \text{Evelyn}): exact string is the only authority
|
| 118 |
+
if e_expr is None and r_expr is None:
|
| 119 |
+
return e_text == r_text if (e_text and r_text) else None
|
| 120 |
+
return None
|
| 121 |
+
if isinstance(e_expr, (list, tuple, sp.Tuple)) or isinstance(r_expr, (list, tuple, sp.Tuple)):
|
| 122 |
+
if isinstance(e_expr, (list, tuple, sp.Tuple)) and isinstance(r_expr, (list, tuple, sp.Tuple)):
|
| 123 |
+
return _pairwise_equal(r_expr, e_expr)
|
| 124 |
+
return False
|
| 125 |
+
try:
|
| 126 |
+
diff = sp.simplify(r_expr - e_expr)
|
| 127 |
+
if diff == 0:
|
| 128 |
+
return True
|
| 129 |
+
if diff.is_number:
|
| 130 |
+
try:
|
| 131 |
+
cdiff = complex(diff)
|
| 132 |
+
except (OverflowError, ValueError, TypeError):
|
| 133 |
+
return False
|
| 134 |
+
if cdiff.imag != 0:
|
| 135 |
+
return False
|
| 136 |
+
try:
|
| 137 |
+
scale = max(1.0, abs(float(e_expr)))
|
| 138 |
+
except (OverflowError, ValueError, TypeError):
|
| 139 |
+
return False
|
| 140 |
+
return abs(cdiff.real) <= _TOLERANCE * scale
|
| 141 |
+
return False
|
| 142 |
+
except Exception:
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def robust_compare(expected_latex: str, result):
|
| 147 |
+
"""Backward-compatible name delegating to the authority."""
|
| 148 |
+
return strong_compare(expected_latex, result)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
checks = [
|
| 153 |
+
("145^\\circ", "145", True, "degree LaTeX"),
|
| 154 |
+
("145°", "145", True, "degree symbol"),
|
| 155 |
+
("\\sqrt{51}", "sqrt(51)", True, "sqrt result string"),
|
| 156 |
+
("6 - 5i", "6 - 5*I", True, "imaginary i"),
|
| 157 |
+
("3\\frac{1}{2}", "7/2", True, "mixed number exact"),
|
| 158 |
+
("3\\frac{1}{2}", "3.5", True, "mixed number decimal"),
|
| 159 |
+
("\\frac{8}{3}", "8/3", True, "plain fraction"),
|
| 160 |
+
("\\pi", "pi", True, "pi"),
|
| 161 |
+
("\\left( 5 \\right)", "5", True, "left/right delimiters"),
|
| 162 |
+
("[1, 2]", "[1, 2]", True, "tuple compare"),
|
| 163 |
+
("\\text{Evelyn}", "Evelyn", True, "word answer"),
|
| 164 |
+
("\\boxed{28}", "28", True, "boxed wrapper"),
|
| 165 |
+
("0.1", "1/10", True, "float vs exact tolerance"),
|
| 166 |
+
("145^\\circ", "30", False, "wrong angle"),
|
| 167 |
+
("30", "29", False, "off-by-one"),
|
| 168 |
+
("5", "5i", False, "imaginary mismatch"),
|
| 169 |
+
("\\text{Evelyn}", "Bob", False, "wrong word"),
|
| 170 |
+
("[1, 2]", "[2, 1]", False, "ordered tuple mismatch"),
|
| 171 |
+
("\\sqrt{51}", "sqrt(50)", False, "wrong radical"),
|
| 172 |
+
]
|
| 173 |
+
failed = 0
|
| 174 |
+
for expected, result, want, label in checks:
|
| 175 |
+
got = strong_compare(expected, result)
|
| 176 |
+
status = "ok" if got is want else "FAIL"
|
| 177 |
+
if got is not want:
|
| 178 |
+
failed += 1
|
| 179 |
+
print(f"{status:4} | {label:30} | expected {want!s:5} got {got!s:5} | {expected!r} vs {result!r}")
|
| 180 |
+
ambiguous = strong_compare("\\sqrt{51}", None)
|
| 181 |
+
print(f"ok | None-result ambiguous | {ambiguous}")
|
| 182 |
+
assert failed == 0, f"{failed} unit checks failed"
|
| 183 |
+
assert ambiguous is None
|
| 184 |
+
print("mode3_verify: all unit checks pass")
|
scripts/onstart.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================================
|
| 3 |
+
# Pi Office Math bootstrap — vast.ai onstart script
|
| 4 |
+
# Paste this into the "Onstart" field when creating the instance.
|
| 5 |
+
# Idempotent: safe to re-run.
|
| 6 |
+
# ============================================================
|
| 7 |
+
set -x
|
| 8 |
+
|
| 9 |
+
echo "[pi-office] === installing deps ==="
|
| 10 |
+
pip install --no-cache-dir datasets sympy==1.14 2>&1 | tail -3
|
| 11 |
+
# fallback if a huggingface_hub pin conflicts with vllm's:
|
| 12 |
+
pip install --no-cache-dir "datasets<3.0" sympy==1.14 2>&1 | tail -2 || true
|
| 13 |
+
|
| 14 |
+
echo "[pi-office] === preparing workspace ==="
|
| 15 |
+
mkdir -p /workspace/benchmark_data/math500 /workspace/benchmark_data/aime
|
| 16 |
+
|
| 17 |
+
echo "[pi-office] === ready ==="
|
| 18 |
+
touch /workspace/.pi_office_ready
|
| 19 |
+
echo "Files to upload to /workspace (8 total):"
|
| 20 |
+
echo " day1_bootstrap.py pi_office_symbolic_sandbox.py mode3_verify.py"
|
| 21 |
+
echo " benchmark_mode3_lean.py run_checks.py pod_status.sh"
|
| 22 |
+
echo " benchmark_data/math500/test.jsonl benchmark_data/aime/test.jsonl"
|
| 23 |
+
echo ""
|
| 24 |
+
echo "Then run:"
|
| 25 |
+
echo " cd /workspace && python3 run_checks.py"
|
| 26 |
+
echo " python3 day1_bootstrap.py --dry-run 20"
|
scripts/pi_office_symbolic_sandbox.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""pi_office_symbolic_sandbox.py - Mode 3: secure symbolic execution.
|
| 2 |
+
|
| 3 |
+
The LLM generates a sympy script for novel math (roots, limits, integrals).
|
| 4 |
+
The sandbox executes it in an isolated subprocess and returns a
|
| 5 |
+
replayable execution receipt. The receipt certifies the EXECUTION (this
|
| 6 |
+
exact code produced this exact output), NOT that the answer is
|
| 7 |
+
mathematically proven - the code is the proof artifact.
|
| 8 |
+
|
| 9 |
+
Security model (best-effort isolation, documented):
|
| 10 |
+
- Static pre-gate: forbidden tokens are refused before execution.
|
| 11 |
+
- Subprocess: fresh interpreter, minimal env (no PATH/HOME/network vars),
|
| 12 |
+
empty temp cwd, stdin closed.
|
| 13 |
+
- Resource limits: CPU + memory via resource.setrlimit (POSIX), hard
|
| 14 |
+
timeout, stdout size cap.
|
| 15 |
+
- No network, no filesystem access to the workspace, no environment.
|
| 16 |
+
Residual risk: Python sandboxing is not absolute without containers; the
|
| 17 |
+
receipt binds query+code+stdout so any tampering is auditable.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import hashlib
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import re
|
| 26 |
+
import resource
|
| 27 |
+
import subprocess
|
| 28 |
+
import tempfile
|
| 29 |
+
import time
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
SANDBOX_VERSION = "pi-office/symbolic-sandbox/1"
|
| 33 |
+
EXECUTION_TIMEOUT_SECONDS = 15
|
| 34 |
+
MAX_OUTPUT_CHARS = 20_000
|
| 35 |
+
MAX_CODE_CHARS = 8_000
|
| 36 |
+
|
| 37 |
+
# Static pre-gate: anything dangerous is refused outright.
|
| 38 |
+
_FORBIDDEN_PATTERNS = (
|
| 39 |
+
re.compile(r"\b(__import__|importlib|builtins|__builtins__|eval|exec|compile|globals|locals)\b"),
|
| 40 |
+
re.compile(r"\b(os|sys|subprocess|socket|pathlib|shutil|ctypes|multiprocessing|pty|signal)\b"),
|
| 41 |
+
re.compile(r"\b(open|file|read|write|unlink|remove|mkdir|chmod|system|popen|spawn)\b"),
|
| 42 |
+
re.compile(r"\b(getattr|setattr|delattr)\s*\("),
|
| 43 |
+
re.compile(r"\.__class__|\.__base__|\.__subclasses__|\.__mro__|\.__globals__|\.__code__"),
|
| 44 |
+
re.compile(r"__[a-z]+__"),
|
| 45 |
+
)
|
| 46 |
+
_ALLOWED_IMPORTS = ("sympy", "fractions", "math")
|
| 47 |
+
_IMPORT_RE = re.compile(r"^\s*import\s+(\S+)", re.M)
|
| 48 |
+
_FROM_IMPORT_RE = re.compile(r"^\s*from\s+(\S+)\s+import", re.M)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class SandboxRefusal(Exception):
|
| 52 |
+
"""The generated code was refused by the static gate."""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SandboxError(Exception):
|
| 56 |
+
"""Execution failed (timeout, bad output, crash)."""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _static_gate(code: str) -> None:
|
| 60 |
+
if len(code) > MAX_CODE_CHARS:
|
| 61 |
+
raise SandboxRefusal("code exceeds size limit")
|
| 62 |
+
# Comments are not executed -- strip them before the word-pattern scan so
|
| 63 |
+
# comments mentioning read/write/file/... cannot false-positive the gate.
|
| 64 |
+
scan = re.sub(r"#[^\n]*", "", code)
|
| 65 |
+
for pattern in _FORBIDDEN_PATTERNS:
|
| 66 |
+
if pattern.search(scan):
|
| 67 |
+
raise SandboxRefusal(f"forbidden construct: {pattern.pattern[:40]}")
|
| 68 |
+
for match in _IMPORT_RE.finditer(code):
|
| 69 |
+
module = match.group(1).split(".")[0]
|
| 70 |
+
if module not in _ALLOWED_IMPORTS:
|
| 71 |
+
raise SandboxRefusal(f"forbidden import: {module}")
|
| 72 |
+
for match in _FROM_IMPORT_RE.finditer(code):
|
| 73 |
+
module = match.group(1).split(".")[0]
|
| 74 |
+
if module not in _ALLOWED_IMPORTS:
|
| 75 |
+
raise SandboxRefusal(f"forbidden import: {module}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _worker_script(code: str) -> str:
|
| 79 |
+
"""Wrap the generated code with output framing inside the subprocess."""
|
| 80 |
+
import re as _re
|
| 81 |
+
|
| 82 |
+
# Import shim: the model commonly writes `from sympy import degrees, rad`
|
| 83 |
+
# but sympy does not export them - strip those names so they resolve
|
| 84 |
+
# from the worker's `from math import *`.
|
| 85 |
+
code = _re.sub(
|
| 86 |
+
r"from sympy import ([^\n]+)",
|
| 87 |
+
lambda m: "from sympy import "
|
| 88 |
+
+ ", ".join(
|
| 89 |
+
name.strip()
|
| 90 |
+
for name in m.group(1).split(",")
|
| 91 |
+
if name.strip() not in ("degrees", "rad")
|
| 92 |
+
),
|
| 93 |
+
code,
|
| 94 |
+
)
|
| 95 |
+
return (
|
| 96 |
+
"import json, resource, sys\n"
|
| 97 |
+
"import math as _math_mod\n"
|
| 98 |
+
"try:\n"
|
| 99 |
+
" resource.setrlimit(resource.RLIMIT_CPU, (15, 15))\n"
|
| 100 |
+
" resource.setrlimit(resource.RLIMIT_AS, (2 * 1024**3, 2 * 1024**3))\n"
|
| 101 |
+
"except Exception:\n"
|
| 102 |
+
" pass\n"
|
| 103 |
+
"import sympy as sp\n"
|
| 104 |
+
"from fractions import Fraction\n"
|
| 105 |
+
"from math import *\n"
|
| 106 |
+
"rad = radians # sympy codegen commonly uses rad() for degrees\n"
|
| 107 |
+
"sympy = sp # alias for bare `sympy.` attribute calls\n"
|
| 108 |
+
"from sympy import * # bare Eq/solve/symbols/pi/sqrt/... for generated code\n"
|
| 109 |
+
"def _V(_s):\n"
|
| 110 |
+
" try:\n"
|
| 111 |
+
" return sp.sympify(_s)\n"
|
| 112 |
+
" except Exception:\n"
|
| 113 |
+
" return _s\n"
|
| 114 |
+
"import io as _io\n"
|
| 115 |
+
"_captured = _io.StringIO()\n"
|
| 116 |
+
"_old_stdout = sys.stdout\n"
|
| 117 |
+
"sys.stdout = _captured\n"
|
| 118 |
+
"_output = {}\n"
|
| 119 |
+
"_print = print # shadow-proof: user code may rebind machinery\n"
|
| 120 |
+
"_json = json\n"
|
| 121 |
+
"_sys = sys\n"
|
| 122 |
+
"try:\n"
|
| 123 |
+
+ "\n".join(" " + line for line in code.splitlines())
|
| 124 |
+
+ "\n"
|
| 125 |
+
" _output['ok'] = True\n"
|
| 126 |
+
"except Exception as _e:\n"
|
| 127 |
+
" _output['ok'] = False\n"
|
| 128 |
+
" _output['error'] = str(_e)\n"
|
| 129 |
+
"try:\n"
|
| 130 |
+
" _candidates = {}\n"
|
| 131 |
+
" for _k, _v in list(globals().items()):\n"
|
| 132 |
+
" if (\n"
|
| 133 |
+
" not _k.startswith('_') and _k not in dir(_math_mod)\n"
|
| 134 |
+
" and _k not in ('json', 'sp', 'Fraction', 'resource')\n"
|
| 135 |
+
" and not isinstance(_v, sp.Symbol)\n"
|
| 136 |
+
" and not callable(_v)\n"
|
| 137 |
+
" ):\n"
|
| 138 |
+
" _candidates[_k] = _v\n"
|
| 139 |
+
" if 'result' in dir():\n"
|
| 140 |
+
" _output['result'] = result\n"
|
| 141 |
+
" _output['candidates'] = list(_candidates.values())\n"
|
| 142 |
+
" def _jsonsafe(o):\n"
|
| 143 |
+
" if isinstance(o, dict):\n"
|
| 144 |
+
" return {str(k): _jsonsafe(v) for k, v in o.items()}\n"
|
| 145 |
+
" if isinstance(o, (list, tuple, set)):\n"
|
| 146 |
+
" return [_jsonsafe(x) for x in o]\n"
|
| 147 |
+
" if o is None or isinstance(o, (str, int, float, bool)):\n"
|
| 148 |
+
" return o\n"
|
| 149 |
+
" return str(o)\n"
|
| 150 |
+
" _sys.stdout = _old_stdout\n"
|
| 151 |
+
" _output['captured_stdout'] = _captured.getvalue()[:200]\n"
|
| 152 |
+
" _print(_json.dumps(_jsonsafe(_output)))\n"
|
| 153 |
+
"except Exception as _we:\n"
|
| 154 |
+
" # worker machinery failed (shadowed print/json/sys, deep nesting,\n"
|
| 155 |
+
" # ...): emit a self-diagnosing JSON instead of dying silently\n"
|
| 156 |
+
" try:\n"
|
| 157 |
+
" _sys.stdout = _old_stdout\n"
|
| 158 |
+
" _output['ok'] = False\n"
|
| 159 |
+
" _output['worker_error'] = repr(_we)[:200]\n"
|
| 160 |
+
" _print(_json.dumps(_jsonsafe(_output)))\n"
|
| 161 |
+
" except Exception:\n"
|
| 162 |
+
" pass\n"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def execute_sympy(
|
| 167 |
+
code: str,
|
| 168 |
+
timeout: int = EXECUTION_TIMEOUT_SECONDS,
|
| 169 |
+
) -> dict[str, object]:
|
| 170 |
+
"""Static gate, then isolated subprocess execution. Returns the
|
| 171 |
+
execution record with the sandbox receipt payload."""
|
| 172 |
+
_static_gate(code)
|
| 173 |
+
script = _worker_script(code)
|
| 174 |
+
script_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
|
| 175 |
+
started = time.monotonic()
|
| 176 |
+
|
| 177 |
+
import sys
|
| 178 |
+
import site as _site
|
| 179 |
+
import sysconfig as _sysconfig
|
| 180 |
+
|
| 181 |
+
_lib_paths = [
|
| 182 |
+
_sysconfig.get_paths().get("purelib", ""),
|
| 183 |
+
_site.getusersitepackages(),
|
| 184 |
+
]
|
| 185 |
+
env = {
|
| 186 |
+
"PYTHONHASHSEED": "0",
|
| 187 |
+
"PYTHONIOENCODING": "utf-8",
|
| 188 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 189 |
+
"PYTHONPATH": os.pathsep.join(
|
| 190 |
+
path for path in _lib_paths if path and os.path.isdir(path)
|
| 191 |
+
),
|
| 192 |
+
}
|
| 193 |
+
with tempfile.TemporaryDirectory() as workdir:
|
| 194 |
+
try:
|
| 195 |
+
completed = subprocess.run(
|
| 196 |
+
[sys.executable, "-c", script],
|
| 197 |
+
capture_output=True,
|
| 198 |
+
text=True,
|
| 199 |
+
timeout=timeout,
|
| 200 |
+
env=env,
|
| 201 |
+
cwd=workdir,
|
| 202 |
+
stdin=subprocess.DEVNULL,
|
| 203 |
+
start_new_session=True,
|
| 204 |
+
)
|
| 205 |
+
except subprocess.TimeoutExpired:
|
| 206 |
+
raise SandboxError("execution timed out") from None
|
| 207 |
+
except OSError as error:
|
| 208 |
+
raise SandboxError(f"subprocess failed: {error}") from None
|
| 209 |
+
|
| 210 |
+
elapsed_ms = int((time.monotonic() - started) * 1000)
|
| 211 |
+
output = completed.stdout.strip()
|
| 212 |
+
if len(output) > MAX_OUTPUT_CHARS:
|
| 213 |
+
raise SandboxError("output exceeds size cap")
|
| 214 |
+
try:
|
| 215 |
+
parsed = json.loads(output)
|
| 216 |
+
except (json.JSONDecodeError, TypeError) as error:
|
| 217 |
+
stderr_tail = (completed.stderr or "").strip()[-400:]
|
| 218 |
+
raise SandboxError(
|
| 219 |
+
f"output is not JSON: {error}; stderr: {stderr_tail}"
|
| 220 |
+
) from error
|
| 221 |
+
if parsed.get("ok") is not True:
|
| 222 |
+
raise SandboxError(f"generated code failed: {parsed.get('error')}")
|
| 223 |
+
|
| 224 |
+
execution_hash = hashlib.sha256(
|
| 225 |
+
f"{script_hash}|{output}".encode("utf-8")
|
| 226 |
+
).hexdigest()
|
| 227 |
+
return {
|
| 228 |
+
"execution_mode": "symbolic_sandbox",
|
| 229 |
+
"sandbox_version": SANDBOX_VERSION,
|
| 230 |
+
"generated_code_sha256": script_hash,
|
| 231 |
+
"stdout": output,
|
| 232 |
+
"execution_hash": execution_hash,
|
| 233 |
+
"elapsed_ms": elapsed_ms,
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def make_receipt(query: str, code: str, execution: dict[str, object]) -> dict[str, object]:
|
| 238 |
+
"""Bind query + code + stdout into the symbolic-execution receipt."""
|
| 239 |
+
query_hash = hashlib.sha256(query.encode("utf-8")).hexdigest()
|
| 240 |
+
receipt_hash = hashlib.sha256(
|
| 241 |
+
f"{query_hash}|{execution['execution_hash']}".encode("utf-8")
|
| 242 |
+
).hexdigest()
|
| 243 |
+
return {
|
| 244 |
+
"schema": "pi-office/symbolic-execution-receipt/1",
|
| 245 |
+
"protocol_version": "pi-office/verification-protocol/1",
|
| 246 |
+
"execution_mode": "symbolic_sandbox",
|
| 247 |
+
"sandbox_version": SANDBOX_VERSION,
|
| 248 |
+
"query_sha256": query_hash,
|
| 249 |
+
"generated_code_sha256": execution["generated_code_sha256"],
|
| 250 |
+
"stdout": execution["stdout"],
|
| 251 |
+
"execution_hash": execution["execution_hash"],
|
| 252 |
+
"receipt_sha256": receipt_hash,
|
| 253 |
+
"elapsed_ms": execution["elapsed_ms"],
|
| 254 |
+
"certification": (
|
| 255 |
+
"execution-certified: this exact generated code deterministically "
|
| 256 |
+
"produced this exact output in the sandbox; the code is the "
|
| 257 |
+
"replayable proof artifact. NOT a claim of mathematical proof."
|
| 258 |
+
),
|
| 259 |
+
}
|
scripts/pod_status.sh
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# pod_status.sh — one-shot pod diagnostics for triage.
|
| 3 |
+
# Run: bash pod_status.sh (then paste the output back)
|
| 4 |
+
echo "=== GPU ==="
|
| 5 |
+
nvidia-smi --query-gpu=name,memory.total,memory.used,driver_version --format=csv 2>&1 | head -3
|
| 6 |
+
echo "=== Python ==="
|
| 7 |
+
python3 --version
|
| 8 |
+
which python3
|
| 9 |
+
echo "=== Key packages ==="
|
| 10 |
+
pip list 2>/dev/null | grep -iE "^(vllm|torch|transformers|datasets|sympy|huggingface)"
|
| 11 |
+
echo "=== Disk ==="
|
| 12 |
+
df -h /workspace 2>/dev/null | tail -1
|
| 13 |
+
echo "=== Files (expect 7) ==="
|
| 14 |
+
for f in day1_bootstrap.py pi_office_symbolic_sandbox.py mode3_verify.py \
|
| 15 |
+
benchmark_mode3_lean.py run_checks.py \
|
| 16 |
+
benchmark_data/math500/test.jsonl benchmark_data/aime/test.jsonl; do
|
| 17 |
+
if [ -f "/workspace/$f" ]; then echo "OK $f"; else echo "MISS $f"; fi
|
| 18 |
+
done
|
| 19 |
+
echo "=== Env ==="
|
| 20 |
+
env | grep -E "PI_OFFICE|HF_TOKEN|CUDA" | sed 's/HF_TOKEN=.*/HF_TOKEN=<set>/' || echo "(none set)"
|
scripts/run_checks.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
run_checks.py — the integration test suite for the Pi Office Math bootstrap.
|
| 3 |
+
|
| 4 |
+
Runs inside the Docker container (check or run image). Verifies every
|
| 5 |
+
integration point between the sandbox, verifier, worker logic, and dataset
|
| 6 |
+
utilities — everything EXCEPT vLLM generation itself (which requires a GPU).
|
| 7 |
+
|
| 8 |
+
Exit 0 = all pass. Exit 1 = at least one failure.
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
import sys
|
| 12 |
+
import traceback
|
| 13 |
+
|
| 14 |
+
import day1_bootstrap as d
|
| 15 |
+
|
| 16 |
+
failures = []
|
| 17 |
+
total = 0
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def check(label, condition, detail=""):
|
| 21 |
+
global total
|
| 22 |
+
total += 1
|
| 23 |
+
status = "PASS" if condition else "FAIL"
|
| 24 |
+
print(f"{status} | {label}")
|
| 25 |
+
if not condition:
|
| 26 |
+
failures.append(f"{label}: {detail}")
|
| 27 |
+
return condition
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# --- postprocess_code (5 checks) ---
|
| 31 |
+
check("postprocess: fence strip",
|
| 32 |
+
d.postprocess_code("```python\nresult = 5\n```") == "result = 5")
|
| 33 |
+
check("postprocess: think tag strip",
|
| 34 |
+
d.postprocess_code("<think>let me solve</think>\nresult = 5") == "result = 5")
|
| 35 |
+
check("postprocess: intent-JSON degeneracy guard",
|
| 36 |
+
d.postprocess_code('{"solver_id": "x"}') is None)
|
| 37 |
+
check("postprocess: empty -> None",
|
| 38 |
+
d.postprocess_code("") is None)
|
| 39 |
+
check("postprocess: plain code passthrough",
|
| 40 |
+
d.postprocess_code("result = 5") == "result = 5")
|
| 41 |
+
check("postprocess: prose rejected (7B failure mode)",
|
| 42 |
+
d.postprocess_code("To find the answer, we first compute x, then y.") is None)
|
| 43 |
+
check("postprocess: indented code kept",
|
| 44 |
+
d.postprocess_code("if x == 1:\n result = 2") == "if x == 1:\n result = 2")
|
| 45 |
+
|
| 46 |
+
# --- extract_gsm8k_answer (2 checks) ---
|
| 47 |
+
check("gsm8k: trailing number",
|
| 48 |
+
d.extract_gsm8k_answer("Natalia sold 48/2 = <<48/2=24>> clips. She sold 72.") == "72")
|
| 49 |
+
check("gsm8k: thousand comma stripped",
|
| 50 |
+
d.extract_gsm8k_answer("answer: 1,250") == "1250")
|
| 51 |
+
|
| 52 |
+
# --- verify_candidate (6 checks: real sandbox + strong_compare) ---
|
| 53 |
+
# Load a known-verified pair from the MATH-500 bootstrap for the True case.
|
| 54 |
+
# In the container we don't have results/ — craft synthetic cases instead.
|
| 55 |
+
cases = [
|
| 56 |
+
("verified (real compute)",
|
| 57 |
+
{"code": "import sympy as sp\nx = sp.symbols('x')\nresult = sp.solve(x**2 - 5*x + 6, x)", "expected": "[2, 3]"},
|
| 58 |
+
True, "verified"),
|
| 59 |
+
("crash (division by zero)",
|
| 60 |
+
{"code": "result = 1/0", "expected": "5"},
|
| 61 |
+
False, "crash"),
|
| 62 |
+
("gate refusal (__import__)",
|
| 63 |
+
{"code": "result = __import__('os').system('ls')", "expected": "5"},
|
| 64 |
+
False, "gate"),
|
| 65 |
+
("no result (None class)",
|
| 66 |
+
{"code": "x = 5", "expected": "5"},
|
| 67 |
+
None, "no_result"),
|
| 68 |
+
("wrong-caught (numeric mismatch)",
|
| 69 |
+
{"code": "result = 30", "expected": "145"},
|
| 70 |
+
False, "wrong_caught"),
|
| 71 |
+
("word-vs-number mismatch",
|
| 72 |
+
{"code": "result = 5", "expected": "\\text{Evelyn}"},
|
| 73 |
+
False, "wrong_caught"),
|
| 74 |
+
]
|
| 75 |
+
for label, task, want_v, want_r in cases:
|
| 76 |
+
try:
|
| 77 |
+
got = d.verify_candidate(task)
|
| 78 |
+
ok_v = got["verdict"] is want_v
|
| 79 |
+
ok_r = got["reason"].startswith(want_r)
|
| 80 |
+
check(f"verify_candidate: {label}",
|
| 81 |
+
ok_v and ok_r,
|
| 82 |
+
f"want verdict={want_v} reason={want_r}, got verdict={got['verdict']} reason={got['reason']}")
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
check(f"verify_candidate: {label}", False,
|
| 85 |
+
f"EXCEPTION {type(exc).__name__}: {exc}")
|
| 86 |
+
|
| 87 |
+
# --- CODEGEN_SYSTEM is the proven prompt (byte-identical) ---
|
| 88 |
+
try:
|
| 89 |
+
import benchmark_mode3_lean as b
|
| 90 |
+
check("CODEGEN_SYSTEM byte-identical to proven prompt",
|
| 91 |
+
d.CODEGEN_SYSTEM == b.CODEGEN_SYSTEM,
|
| 92 |
+
"prompt text drifted from benchmark_mode3_lean")
|
| 93 |
+
except Exception as exc:
|
| 94 |
+
check("CODEGEN_SYSTEM import", False, str(exc))
|
| 95 |
+
|
| 96 |
+
# --- strong_compare direct spot-checks (the authority) ---
|
| 97 |
+
from mode3_verify import strong_compare
|
| 98 |
+
check("strong_compare: degree normalization",
|
| 99 |
+
strong_compare("145^\\circ", "145") is True)
|
| 100 |
+
check("strong_compare: mixed number",
|
| 101 |
+
strong_compare("3\\frac{1}{2}", "7/2") is True)
|
| 102 |
+
check("strong_compare: imaginary unit",
|
| 103 |
+
strong_compare("6 - 5i", "6 - 5*I") is True)
|
| 104 |
+
check("strong_compare: leading zeros (AIME)",
|
| 105 |
+
strong_compare("025", "25") is True)
|
| 106 |
+
|
| 107 |
+
# --- dataset loading (regression: pod failure on 2026-08-04 -- hendrycks
|
| 108 |
+
# needs trust_remote_code; lighteval/MATH is 401-gated) ---
|
| 109 |
+
try:
|
| 110 |
+
loaded = d.load_datasets()
|
| 111 |
+
check("datasets: GSM8K + MATH train load",
|
| 112 |
+
len(loaded) > 100 and
|
| 113 |
+
all(p["id"] and p["problem"] and p["answer"] for p in loaded[:50]),
|
| 114 |
+
f"got {len(loaded)} problems; sample answers: "
|
| 115 |
+
f"{[p['answer'][:12] for p in loaded[:3]]}")
|
| 116 |
+
except Exception as exc:
|
| 117 |
+
check("datasets: GSM8K + MATH train load", False,
|
| 118 |
+
f"EXCEPTION {type(exc).__name__}: {str(exc)[:200]}")
|
| 119 |
+
|
| 120 |
+
# --- summary ---
|
| 121 |
+
print(f"\n{'=' * 50}")
|
| 122 |
+
if failures:
|
| 123 |
+
print(f"RESULT: {len(failures)} FAILURES out of {total} checks")
|
| 124 |
+
for f in failures:
|
| 125 |
+
print(f" FAIL: {f}")
|
| 126 |
+
sys.exit(1)
|
| 127 |
+
else:
|
| 128 |
+
print(f"RESULT: ALL {total} CHECKS PASS — integration verified")
|
| 129 |
+
print("(vLLM generation itself requires a GPU and is tested via --dry-run 20)")
|
| 130 |
+
sys.exit(0)
|