File size: 10,900 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
#!/usr/bin/env python3
"""Lean Mode 3 benchmark: MATH-500 through the symbolic sandbox ONLY.

Deliberately does NOT import pi_office_agentic_api (no frozen intent model
resident) - the 4B NLG model + the sandbox are the entire footprint, which
stays under the 16GB ceiling over long runs. Modes 1/2 are bypassed.

Correctness is verified in-run by sympy simplify-difference against the
MATH-500 ground truth (LaTeX parsed by sympy). The trust guarantee: no
result is ever presented as correct without that verification; anything
unverifiable is counted as uncertain, never claimed.
"""

from __future__ import annotations

import json
import os
import re
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent
DATASET = ROOT / os.environ.get(
    "PI_OFFICE_MODE3_DATASET", "benchmark_data/math500/test.jsonl"
)
OUTPUT = ROOT / os.environ.get(
    "PI_OFFICE_MODE3_OUTPUT", "results/math500_mode3_lean_run.jsonl"
)
REPORT = ROOT / "results" / "math500_mode3_lean_report.json"

os.environ.setdefault("PI_OFFICE_NLG_MODEL", "lmstudio-community/Qwen3-VL-4B-Instruct-MLX-4bit")

def _backend_load(model_path: str, adapter_path: str | None = None):
    """Model loading with backend switch: mlx (default, local) or
    transformers (CUDA pods)."""
    backend = os.environ.get("PI_OFFICE_MODE3_BACKEND", "mlx")
    if backend == "transformers":
        import torch
        from transformers import AutoModelForCausalLM, AutoTokenizer

        from transformers import AutoConfig
        tokenizer = AutoTokenizer.from_pretrained(model_path)
        # arch-based loading: VL models (e.g. Qwen3VLForConditionalGeneration)
        # are not AutoModelForCausalLM-loadable
        cfg = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
        cls = getattr(__import__("transformers"), cfg.architectures[0])
        try:
            # transformers v5 renamed torch_dtype -> dtype
            model = cls.from_pretrained(
                model_path, dtype=torch.bfloat16, trust_remote_code=True)
        except TypeError:
            model = cls.from_pretrained(
                model_path, torch_dtype=torch.bfloat16,
                trust_remote_code=True)
        # single-GPU pod: explicit .cuda() avoids the accelerate dependency
        model = model.to("cuda")
        return model, tokenizer
    from mlx_lm import load

    return load(model_path, adapter_path=adapter_path)


def _backend_generate(model, tokenizer, *, prompt: str, max_tokens: int = 400,
                      verbose: bool = False) -> str:
    """Generation with backend switch (matches the mlx_lm.generate call
    signature used by generate_code)."""
    backend = os.environ.get("PI_OFFICE_MODE3_BACKEND", "mlx")
    if backend == "transformers":
        import torch

        inputs = tokenizer(prompt, return_tensors="pt")
        device = next(model.parameters()).device
        inputs = {k: v.to(device) for k, v in inputs.items()}
        pad = (tokenizer.pad_token_id if tokenizer.pad_token_id is not None
               else tokenizer.eos_token_id)
        out = model.generate(**inputs, max_new_tokens=max_tokens,
                             do_sample=False, pad_token_id=pad)
        return tokenizer.decode(out[0][inputs["input_ids"].shape[1]:],
                                skip_special_tokens=True)
    from mlx_lm import generate

    return generate(model, tokenizer, prompt=prompt, max_tokens=max_tokens,
                    verbose=verbose)

import pi_office_symbolic_sandbox as sandbox  # noqa: E402

CODEGEN_SYSTEM = (
    "You are a Python code generator for a math sandbox. Respond with ONLY a "
    "Python script that computes the answer using sympy. Never write prose, "
    "explanations, or reasoning -- output is executed by a machine. The "
    "script must assign the final answer to a variable named `result`. Do NOT "
    "print anything.\n"
    "Here are examples of the ONLY acceptable output format:\n"
    "Example 1 (roots):\n"
    "import sympy as sp\n"
    "x = sp.symbols('x')\n"
    "result = sp.solve(x**2 - 5*x + 6, x)\n"
    "Example 2 (limit):\n"
    "import sympy as sp\n"
    "x = sp.symbols('x')\n"
    "result = sp.limit(sp.sin(x)/x, x, 0)\n"
    "Example 3 (integral):\n"
    "import sympy as sp\n"
    "x = sp.symbols('x')\n"
    "result = sp.integrate(x**2, (x, 0, 2))\n"
    "Example 4 (combinatorics):\n"
    "import sympy as sp\n"
    "result = sp.binomial(31, 28)"
)


def generate_code(model, tokenizer, problem: str) -> str | None:
    messages = [
        {"role": "system", "content": CODEGEN_SYSTEM},
        {"role": "user", "content": problem
         + "\n\nRespond with ONLY Python code. No prose, no explanations, "
           "no reasoning."},
    ]
    try:
        prompt = tokenizer.apply_chat_template(
            messages, add_generation_prompt=True, tokenize=False)
    except TypeError:
        # mlx tokenizers do not accept tokenize=False (always return str)
        prompt = tokenizer.apply_chat_template(
            messages, add_generation_prompt=True)
    text = _backend_generate(model, tokenizer, prompt=prompt,
                              max_tokens=400, verbose=False).strip()
    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()
    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 robust_compare(expected_latex: str, result):
    """Delegates to mode3_verify -- the single source of truth."""
    from mode3_verify import strong_compare

    return strong_compare(expected_latex, result)


def classify(problem: str, answer: str) -> dict:
    record: dict = {"problem": problem[:200], "answer": answer}
    try:
        code = generate_code(model, tokenizer, problem)
        if not code:
            record["mode"] = "refused"
            record["reason"] = "codegen_empty"
            return record
        execution = sandbox.execute_sympy(code, timeout=15)
    except sandbox.SandboxRefusal as error:
        record["mode"] = "refused"
        record["reason"] = f"gate:{error}"
        record["code"] = code[:300]  # diagnostic: store refused code
        return record
    except sandbox.SandboxError as error:
        record["mode"] = "refused"
        record["reason"] = f"sandbox:{error}"
        record["code"] = code[:300]  # diagnostic: store failing code
        return record
    except Exception as error:
        record["mode"] = "refused"
        record["reason"] = f"codegen:{type(error).__name__}"
        return record
    record["mode"] = "mode3"
    record["code"] = code[:400]
    record["code_hash"] = execution["generated_code_sha256"][:16]
    record["execution_hash"] = execution["execution_hash"][:16]
    record["stdout"] = execution["stdout"][:200]
    try:
        parsed = json.loads(execution["stdout"])
        result = parsed.get("result")
    except Exception:
        result = None
    record["result"] = None if result is None else str(result)[:200]
    record["correct"] = robust_compare(answer, result)
    return record


def main() -> int:
    # --slice math500|aime convenience flag (env vars still override)
    global DATASET
    if "--slice" in sys.argv:
        which = sys.argv[sys.argv.index("--slice") + 1]
        mapping = {
            "math500": "benchmark_data/math500/test.jsonl",
            "aime": "benchmark_data/aime/test.jsonl",
        }
        if which not in mapping:
            raise SystemExit(f"unknown slice {which!r}; use math500|aime")
        DATASET = ROOT / mapping[which]
        os.environ.setdefault("PI_OFFICE_MODE3_COUNT",
                              "100" if which == "math500" else "30")
    problems = [
        json.loads(line) for line in DATASET.read_text(encoding="utf-8").splitlines()
    ][: int(os.environ.get("PI_OFFICE_MODE3_COUNT", "100"))]
    print(f"lean run: {len(problems)} problems, single model (NLG only)", flush=True)
    started = time.time()
    counts = {"mode3": 0, "refused": 0, "correct": 0, "wrong": 0, "uncertain": 0}
    with OUTPUT.open("w", encoding="utf-8") as handle:
        for index, row in enumerate(problems, 1):
            record = classify(row["problem"], row["answer"])
            record["index"] = index
            record["subject"] = row.get("subject")
            record["level"] = row.get("level")
            handle.write(json.dumps(record, ensure_ascii=True) + "\n")
            handle.flush()
            counts[record["mode"]] += 1
            if record["mode"] == "mode3":
                c = record.get("correct")
                if c is True:
                    counts["correct"] += 1
                elif c is False:
                    counts["wrong"] += 1
                else:
                    counts["uncertain"] += 1
            if index % 25 == 0:
                print(
                    f"[{index}/100] {time.time()-started:.0f}s executed={counts['mode3']} "
                    f"correct={counts['correct']} wrong={counts['wrong']} "
                    f"uncertain={counts['uncertain']} refused={counts['refused']}",
                    flush=True,
                )
    report = {
        "schema": "pi-office/frontier-benchmark/1",
        "benchmark": "math500",
        "run": "mode3_lean",
        "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "counts": counts,
        "metrics": {
            "execution_rate": round(counts["mode3"] / 100, 4),
            "execution_accuracy": round(
                counts["correct"] / counts["mode3"], 4
            ) if counts["mode3"] else None,
            "verified_correct": counts["correct"],
            "wrong_execution_caught": counts["wrong"],
            "uncertain": counts["uncertain"],
            "refused": counts["refused"],
            "trust_guarantee": (
                "0 results presented as correct without sympy-verified "
                "comparison; wrong-execution-caught receipts are reported openly"
            ),
        },
    }
    REPORT.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps(report["metrics"], indent=1))
    return 0


if __name__ == "__main__":
    adapter = os.environ.get("PI_OFFICE_NLG_ADAPTER") or None
    model, tokenizer = _backend_load(
        os.environ["PI_OFFICE_NLG_MODEL"], adapter_path=adapter)
    print(f"adapter: {adapter or 'none'}", flush=True)
    raise SystemExit(main())