Instructions to use ramankrishna10/npc-reason with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use ramankrishna10/npc-reason with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf ramankrishna10/npc-reason:Q4_K_M # Run inference directly in the terminal: llama cli -hf ramankrishna10/npc-reason:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf ramankrishna10/npc-reason:Q4_K_M # Run inference directly in the terminal: llama cli -hf ramankrishna10/npc-reason:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf ramankrishna10/npc-reason:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf ramankrishna10/npc-reason:Q4_K_M
Use Docker
docker model run hf.co/ramankrishna10/npc-reason:Q4_K_M
- Llama new
- LM Studio
- Jan
- vLLM
How to use ramankrishna10/npc-reason with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "ramankrishna10/npc-reason" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ramankrishna10/npc-reason", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/ramankrishna10/npc-reason:Q4_K_M
- Ollama
How to use ramankrishna10/npc-reason with Ollama:
ollama run hf.co/ramankrishna10/npc-reason:Q4_K_M
- Unsloth Desktop
- Docker Model Runner
How to use ramankrishna10/npc-reason with Docker Model Runner:
docker model run hf.co/ramankrishna10/npc-reason:Q4_K_M
- Lemonade
How to use ramankrishna10/npc-reason with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull ramankrishna10/npc-reason:Q4_K_M
Run and chat with the model
lemonade run user.npc-reason-Q4_K_M
List all available models
lemonade list
- Atomic Chat
verifier + eval harness + reports + locks + usage
Browse filesFiles changed (22)
- USAGE.mdAdded+67
- eval/EVAL.lockAdded+6
- eval/_eval_meta.jsonAdded+30
- eval/eval_set.jsonlAdded
- eval/run_eval.pyAdded+112
- locks/BASELINE.lockAdded+40
- locks/RL_RESULT.lockAdded+7
- locks/SFT_RESULT.lockAdded+6
- locks/TRAINSET.lockAdded+29
- prereg/PREREG.lockAdded+5
- prereg/PREREG.mdAdded+52
- reports/baseline.mdAdded+52
- reports/dispatch1_complete.mdAdded+40
- reports/dispatch2_complete.mdAdded+36
- reports/dispatch3_complete.mdAdded+44
- reports/dispatch4_complete.mdAdded+48
- reports/fidelity_result.jsonAdded+30
- reports/gguf_fidelity.mdAdded+33
- reports/sft_result.mdAdded+53
- tests/test_verifier.pyAdded+159
- verifier/VERIFIER.lockAdded+8
- verifier/step_verifier.pyAdded+300
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# NPC Reason 1.5B - Usage
NPC Reason emits math reasoning where every load-bearing step is a checkable `<<EXPR = RESULT>>`assertion. You prompt for the format, then run the included verifier on the output to confirm thechain mechanically. The verifiable-rate is not the model's opinion; it is re-executed by code.
## 1. The prompt (use this format instruction verbatim)
```Solve this math problem. For EVERY load-bearing arithmetic step, write the computation as aninline checkable assertion in the exact form <<EXPR = RESULT>>, where EXPR is the arithmeticexpression and RESULT is its value (for example <<3*8 = 24>>). If a quantity is reused, you mayname it, e.g. let total = <<3*8 = 24>>, and reference it later as <<total + 6 = 30>>. Do notassert any number that drives the answer without wrapping it in <<...>>. End with the finalanswer as \boxed{ANSWER}, and make sure it equals the result of your last <<...>> step.
Problem: <your problem here>```
Apply the model's chat template (single user turn) and decode greedily (temperature 0) forreproducible chains.
## 2. Run it
**vLLM (bf16 merged model):**```pythonfrom vllm import LLM, SamplingParamsfrom transformers import AutoTokenizertok = AutoTokenizer.from_pretrained("npc-reason") # merged model dirllm = LLM(model="npc-reason", dtype="bfloat16")prompt = tok.apply_chat_template( [{"role": "user", "content": FORMAT_INSTRUCTION.format(problem=problem)}], tokenize=False, add_generation_prompt=True)out = llm.generate([prompt], SamplingParams(temperature=0.0, max_tokens=1024))chain = out[0].outputs[0].text```
**llama.cpp / GGUF (recommended quant per gguf_fidelity.md):**```pythonfrom llama_cpp import Llamallm = Llama(model_path="npc-reason-q8_0.gguf", n_gpu_layers=99, n_ctx=2048)out = llm.create_chat_completion( messages=[{"role": "user", "content": FORMAT_INSTRUCTION.format(problem=problem)}], temperature=0.0, max_tokens=1024)chain = out["choices"][0]["message"]["content"]```
## 3. Verify the chain (this is the point)
```pythonfrom verifier.step_verifier import verify_chain # shipped with the model, frozen d5d146cfrec = verify_chain(chain, gold_answer=known_answer) # gold optionalprint(rec["verifiable"]) # every load-bearing step re-executed AND composesprint(rec["correct"]) # final answer == gold (independent axis)print(rec["verified_and_correct"]) # bothprint(rec["failures"]) # which step broke and why, if any```
A chain is VERIFIABLE only if every `<<EXPR=RESULT>>` re-executes correctly under SymPy and thefinal answer composes from the last step. Filler assertions that do not drive the answer do notcount. If `verifiable` is False, inspect `failures`; do not trust the chain.
## 4. Honest expectations
- ~77% of format-prompt chains verify; ~23% are the unverified tail. Always check.- Math-first (arithmetic and arithmetic-reducible word problems). Not a general chat model.- The SFT model is statistically equivalent to the shipped RL model and is included as a fallback.123456{ "files": { "eval/eval_set.jsonl": "e1573cabaf44010555ef1138cbeda17bc43deb8121524cde23d94413a5d69753", "eval/_eval_meta.json": "8d99764e00d564035fcc1cf361c7e44d45783623288763fe679477e8670fc88f" }}123456789101112131415161718192021222324252627282930{ "seed": 20260615, "n_total": 500, "sources": [ { "name": "openai/gsm8k", "config": "main", "split": "test", "n": 300, "selection": "Random(SEED).shuffle -> first N" }, { "name": "HuggingFaceH4/MATH-500", "split": "test", "n": 200, "selection": "Random(SEED+1).shuffle -> first N" } ], "schema": [ "id", "source", "problem", "gold", "level", "subject" ], "frozen": true, "note": "Evaluation only. Never training data. Decontaminate training against this.", "eval_set_sha256": "e1573cabaf44010555ef1138cbeda17bc43deb8121524cde23d94413a5d69753"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Stage 4 — evaluate NPC-Reason-SFT on the FROZEN eval, vs the frozen baseline + PREREG.
Same EVAL.lock, same greedy decoding (temp 0, seed 0, max_tokens 12288) as the baseline =apples-to-apples. Scores with the frozen verifier. Grades the pre-registered bars honestly."""
import jsonimport sysimport timefrom pathlib import Path
from transformers import AutoTokenizerfrom vllm import LLM, SamplingParams
HERE = Path(__file__).resolve().parentROOT = HERE.parentsys.path.insert(0, str(ROOT))from verifier.step_verifier import verify_chain # FROZEN
MERGED = str(ROOT / "sft" / "merged")MAX_TOKENS = 12288MAX_MODEL_LEN = 16384
PLAIN_INSTRUCTION = ( "Solve this math problem. Show your work step by step, then give the final answer " "on the last line as \\boxed{{ANSWER}}.\n\nProblem: {problem}")FORMAT_INSTRUCTION = ( "Solve this math problem. For EVERY load-bearing arithmetic step, write the " "computation as an inline checkable assertion in the exact form <<EXPR = RESULT>>, " "where EXPR is the arithmetic expression and RESULT is its value (for example " "<<3*8 = 24>>). If a quantity is reused, you may name it, e.g. " "let total = <<3*8 = 24>>, and reference it later as <<total + 6 = 30>>. Do not " "assert any number that drives the answer without wrapping it in <<...>>. End with " "the final answer as \\boxed{{ANSWER}}, and make sure it equals the result of your " "last <<...>> step.\n\nProblem: {problem}")
def load_eval(): return [json.loads(l) for l in (ROOT / "eval" / "eval_set.jsonl").open()]
def rate(recs, k): return round(100 * sum(1 for r in recs if r[k]) / len(recs), 2) if recs else 0.0
def main(): rows = load_eval() tok = AutoTokenizer.from_pretrained(MERGED) variants = {"plain": PLAIN_INSTRUCTION, "format": FORMAT_INSTRUCTION} jobs = [] for v, tmpl in variants.items(): for r in rows: p = tok.apply_chat_template([{"role": "user", "content": tmpl.format(problem=r["problem"])}], tokenize=False, add_generation_prompt=True) jobs.append((v, r, p))
llm = LLM(model=MERGED, dtype="bfloat16", max_model_len=MAX_MODEL_LEN, gpu_memory_utilization=0.85, seed=0) sp = SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS, seed=0) t0 = time.time() outs = llm.generate([j[2] for j in jobs], sp) gen_s = round(time.time() - t0, 1)
per = {"plain": [], "format": []} raw = HERE / "eval_raw.jsonl" with raw.open("w") as f: for (v, r, _), o in zip(jobs, outs): text = o.outputs[0].text rec = verify_chain(text, gold_answer=r["gold"]) slim = {"verifiable": rec["verifiable"], "correct": bool(rec["correct"]), "verified_and_correct": bool(rec["verified_and_correct"]), "n_assertions": rec["n_assertions"]} per[v].append(slim) f.write(json.dumps({"id": r["id"], "variant": v, "gold": r["gold"], "output": text, "verifier": slim}, ensure_ascii=False) + "\n")
summary = {v: {"n": len(rs), "verifiable_rate": rate(rs, "verifiable"), "accuracy": rate(rs, "correct"), "verified_and_correct": rate(rs, "verified_and_correct"), "mean_assertions": round(sum(x["n_assertions"] for x in rs) / len(rs), 2)} for v, rs in per.items()}
base = json.load(open(ROOT / "baseline" / "BASELINE.lock"))["summary"] bf = base["format"] sf = summary["format"]
# PREREG bars (b5a49437): +15pp v&c over format baseline; verifiable >=90%; acc regress <=5pp. lift = round(sf["verified_and_correct"] - bf["verified_and_correct"], 2) acc_delta = round(sf["accuracy"] - bf["accuracy"], 2) grade = { "primary_lift_vc_pp": lift, "primary_SUPPORTED": lift >= 15.0, "verifiable_rate": sf["verifiable_rate"], "verifiable_SUPPORTED": sf["verifiable_rate"] >= 90.0, "accuracy_delta_pp": acc_delta, "accuracy_guard_SUPPORTED": acc_delta >= -5.0, } grade["ALL_THREE"] = all([grade["primary_SUPPORTED"], grade["verifiable_SUPPORTED"], grade["accuracy_guard_SUPPORTED"]]) rl_gate = grade["ALL_THREE"] or sf["verifiable_rate"] >= 90.0
result = {"model": MERGED, "decoding": {"greedy": True, "max_tokens": MAX_TOKENS, "seed": 0}, "gen_seconds": gen_s, "summary": summary, "baseline_format": bf, "prereg_grade": grade, "rl_gate_cleared": rl_gate} (HERE / "eval_result.json").write_text(json.dumps(result, indent=2)) print(json.dumps({"summary": summary, "grade": grade, "rl_gate": rl_gate}, indent=2))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940{ "files": { "baseline/baseline_results.json": "873c466ed7d6bd23b5088dd03b6edc69f2e5888f3246a4dd9df241923fda85c8", "baseline/raw_outputs.jsonl": "57a9e724ad0e71993f6c4abfdb970029d352d53aeb9adabb37162e809b86b024" }, "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", "decoding": { "strategy": "greedy", "temperature": 0.0, "max_tokens": 12288, "max_model_len": 16384, "seed": 0, "deterministic": true }, "summary": { "plain": { "n": 500, "verifiable_rate": 0.0, "accuracy": 59.8, "verified_and_correct": 0.0, "mean_assertions_per_chain": 0.0 }, "format": { "n": 500, "verifiable_rate": 0.0, "accuracy": 61.6, "verified_and_correct": 0.0, "mean_assertions_per_chain": 0.0 } }, "references": { "VERIFIER.lock": { "verifier/step_verifier.py": "d5d146cfbb9a69e162c1a80a330c942b195bfd6d0a0961ae480cc1875989613b" }, "EVAL.lock": { "eval/eval_set.jsonl": "e1573cabaf44010555ef1138cbeda17bc43deb8121524cde23d94413a5d69753", "eval/_eval_meta.json": "8d99764e00d564035fcc1cf361c7e44d45783623288763fe679477e8670fc88f" } }}1234567{ "files": { "rl/rl_eval_result.json": "d443b4b2c3da8a16c906c687f9d76befbfe0063008b42df8251a602c65302997", "rl/rl_eval_raw.jsonl": "50ba30b5d305c3339c5bc710a446ff6cda8d2060fc3c529cf0a056ba0d4792d7", "rl/RL_DATA.lock": "aa26db37d0245e9ec0057959b20056123148ef6bfdbfb2f740ac20d326a54c4b" }}123456{ "files": { "eval/eval_result.json": "095c87775e77c89af55f64a2fd644ceeabfc52c57c7f3e31754575867f3e1be7", "eval/eval_raw.jsonl": "aaa36cb7de26bd4366040aa86a5564009bafa22136b8a2241f656fd6bfd28b7c" }}1234567891011121314151617181920212223242526272829{ "files": { "data/sft_train.jsonl": "39ee5e9920f480736f42c80acd3ff76a1e62cc1cb250b0dace94fda239e3e68f" }, "count": 7546, "filter_stats": { "raw_chains": 13245, "kept": 7546, "surplus_held": 0, "decontam_dropped": 0, "rejects": { "no_assertions": 3894, "bad_arithmetic": 1211, "non_composing": 387, "wrong_answer": 206, "dup_problem": 1 }, "keep_rate_pct": 56.97, "cap": 20000 }, "verifier_ref": { "verifier/step_verifier.py": "d5d146cfbb9a69e162c1a80a330c942b195bfd6d0a0961ae480cc1875989613b" }, "eval_ref": { "eval/eval_set.jsonl": "e1573cabaf44010555ef1138cbeda17bc43deb8121524cde23d94413a5d69753", "eval/_eval_meta.json": "8d99764e00d564035fcc1cf361c7e44d45783623288763fe679477e8670fc88f" }, "criterion": "verifiable AND correct, decontaminated vs EVAL.lock, dedup by problem text"}12345{ "files": { "reports/PREREG.md": "b5a49437c93e733d49d32b9078f1964bdcef29d41c1148d40f6c54d53493959e" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# NPC Reason — Pre-registration of lift criteria (FROZEN before any training)
Committed in Dispatch 1, before any SFT / distillation / RL exists. Same discipline asBigBugAI v2: the success bars are fixed in advance so the eventual before/after delta meanssomething. These bars are deltas/targets chosen on principle; they do NOT depend on themeasured baseline values (recorded separately in `reports/baseline.md` / `BASELINE.lock`),so there is no possibility of tuning the bars to the baseline.
The comparator for the primary bar is the base model's **FORMAT-PROMPT** number — the honestquestion is "did training add something that prompting the base alone could not?", not"did training beat a base that was never asked for the format?".
## Metrics (all from the frozen mechanical verifier, VERIFIER.lock)
- **verifiable-rate** — fraction of chains that are mechanically VERIFIABLE (≥1 load-bearing `<<EXPR=RESULT>>` assertion, all assertions verify, final answer composes).- **accuracy** — fraction whose final answer equals gold (independent of verifiable).- **verified-and-correct** — fraction that are BOTH verifiable AND correct. This is the headline.
## Committed criteria
1. **Primary (lift).** SFT NPC Reason must raise **verified-and-correct** by **≥ +15 percentage points absolute** over the base model's **format-prompt** verified-and-correct rate.
2. **Verifiable-rate target.** NPC Reason must reach **verifiable-rate ≥ 90%**. The project's purpose is near-total mechanical grounding of load-bearing steps; a specialized model should emit the checkable format almost always.
3. **Accuracy guard (no regression trade).** NPC Reason **accuracy** must not regress by more than **5 percentage points** versus the base model's **format-prompt** accuracy. Verifiability must not be bought by sacrificing correctness — both axes matter.
SFT passes Dispatch 2 only if (1) AND (2) AND (3) all hold.
4. **RL gating (later dispatch).** The RL phase is gated on SFT meeting criteria 1–3. RL's own criteria will be pre-registered at that time, evaluated against a held-out slice never used for SFT model selection. The verifier (VERIFIER.lock) is the RL reward and must remain byte-identical.
## Honesty clause
Report whatever the numbers say. A **null** — training fails to beat the format-promptbaseline on the primary bar — is a valid, publishable finding, consistent with this being areal experiment and not a foregone conclusion. The bars above are not moved after results areseen; if they are missed, that is the result.
## Frozen references
- Verifier: `verifier/VERIFIER.lock`- Eval set: `eval/EVAL.lock`- Baseline: `baseline/BASELINE.lock`- This pre-registration: `reports/PREREG.lock` (sha256 of this file).12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# NPC Reason — Baseline (untouched base, FROZEN)
Base: **deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B** (MIT), untouched, **greedy / deterministic**(temperature 0.0, max_tokens 12288, seed 0).Eval: **500** problems (GSM8K test + MATH-500), EVAL.lock `e1573cabaf440105…`.Verifier: VERIFIER.lock `d5d146cfbb9a69e1…` (pure-code, frozen).Generation wall-clock: 556.4s for 1000 chains (both prompts).
| | plain-prompt | format-prompt ||--------------------------|---------------:|---------------:|| verifiable-rate (%) | 0.0 | 0.0 || accuracy (%) | 59.8 | 61.6 || verified-and-correct (%) | 0.0 | 0.0 || mean assertions/chain | 0.0 | 0.0 |
## Prompts (verbatim)
**plain:**```Solve this math problem. Show your work step by step, then give the final answer on the last line as \boxed{{ANSWER}}.
Problem: {problem}```
**format-requesting:**```Solve this math problem. For EVERY load-bearing arithmetic step, write the computation as an inline checkable assertion in the exact form <<EXPR = RESULT>>, where EXPR is the arithmetic expression and RESULT is its value (for example <<3*8 = 24>>). If a quantity is reused, you may name it, e.g. let total = <<3*8 = 24>>, and reference it later as <<total + 6 = 30>>. Do not assert any number that drives the answer without wrapping it in <<...>>. End with the final answer as \boxed{{ANSWER}}, and make sure it equals the result of your last <<...>> step.
Problem: {problem}```
## Reading this honestly
- The **format-prompt** column is the comparator for training: it is the ceiling the base can reach by prompting alone. The pre-registered primary bar (+15pp verified-and-correct) is over THIS column, not over plain.- The base's verifiable-rate is whatever the table says — measured, not assumed. If it is already high under format-prompt, the project's framing must reflect the real (smaller) delta.- R1-Distill is a reasoning model; vendor recommends temp 0.6, but greedy is used here for a reproducible frozen baseline (repetition is possible; reported as-is).
This baseline is FROZEN (BASELINE.lock). Every training dispatch compares against exactly these numbers.
## Greedy no-answer note (honest)
83/500 format-prompt chains (and a similar share of plain) produced NO extractable finalanswer within the 12,288-token budget — these are R1-Distill greedy **repetition loops**(the vendor recommends temperature 0.6 for exactly this reason). We keep GREEDY for areproducible frozen baseline and count these as wrong; accuracy here is therefore a FLOOR.Raising the budget 4096->12288 only moved no-answer 95->83, confirming the cause isdegeneration, not truncation. The SAME greedy decoding will be applied to NPC Reason aftertraining, so the before/after comparison is apples-to-apples (and training is expected toreduce the looping). A prior 4096-token run is archived at baseline/baseline_results.trunc4096.json.12345678910111213141516171819202122232425262728293031323334353637383940=== NPC Reason — Dispatch 1: Verifier + Frozen Baseline ===
Verifier: mechanical <<EXPR=RESULT>> checker (SymPy), pure-code, no LLM judgment. VERIFIER.lock d5d146cf… (also the later RL reward signal). tests: correct / arithmetic-error / fluency-trap / non-composing / verifiable-but-wrong / correct-but-unverifiable / variable-binding / unbound-fail-closed / tolerance(exact+1e-6) / extraction — 14/14 pass.Eval: 500 problems = 300 GSM8K(test) + 200 MATH-500, held-out & frozen. EVAL.lock e1573cab… ; meta records sources/splits/seed(20260615). Never training data.Baseline: DeepSeek-R1-Distill-Qwen-1.5B (MIT), untouched, greedy/deterministic (seed 0, max_tokens 12288, ctx 16384). 1000 chains in 556s. BASELINE.lock frozen.
plain-prompt format-prompt verifiable-rate 0.0% 0.0% <-- base never emits <<...>> (1/500 contain "<<") accuracy 59.8% 61.6% (floor; greedy repetition leaves 83/500 fmt no-answer) verified-and-correct 0.0% 0.0% mean assertions/chain 0.0 0.0
Reading: The base does NOT produce mechanically-checkable steps, even when explicitly asked (format-prompt verifiable-rate is 0%, not just plain). The project's headline delta is therefore real and large-headroom: any verifiable-rate NPC Reason reaches is lift over ~0. Accuracy is a separate axis (~60%) and is the guard, not the goal.
Prereg: FROZEN before training (PREREG.lock b5a49437…). Bars committed: 1. primary: verified-and-correct +>=15pp over format baseline (i.e. >=15%) 2. verifiable-rate >= 90% 3. accuracy must not regress > 5pp below format accuracy 61.6% (i.e. >= 56.6%) 4. RL gated on SFT passing 1-3; RL criteria pre-registered later. Honesty clause: a null (training fails to beat format baseline) is a valid finding.
Next: Dispatch 2 = generate DeepSeek-V4 verifiable <<...>> chains, code-filter against VERIFIER.lock, SFT-distill into R1-Distill-1.5B; decontaminate against EVAL.lock.GPU: inference only; A40 ~4.5GB peak. No training performed this dispatch.
Notes: - Re-ran baseline at 12288 tokens (from 4096) to remove a truncation artifact; 4096 run archived at baseline/baseline_results.trunc4096.json. verifiable-rate 0% in BOTH runs (robust). Verifier frozen BEFORE both baseline runs (not tuned to them). - R1-Distill greedy repetition (vendor recommends temp 0.6) leaves ~17% of chains without a final answer; counted wrong, so accuracy is a floor. Same decoding will apply post-training -> apples-to-apples.123456789101112131415161718192021222324252627282930313233343536=== NPC Reason — Dispatch 2: V4 Corpus + SFT Distill ===
Corpus: 13,245 V4 (deepseek-v4-flash) chains from TRAIN splits (GSM8K-train + MATH-train 7 subj) -> mechanically filtered against FROZEN verifier (verifiable AND correct) -> 7,546 kept (keep rate 56.97%). TRAINSET.lock frozen. reject breakdown: no_assertions 3894 (29%, mostly non-arithmetic MATH) · bad_arithmetic 1211 (9%) · non_composing 387 · wrong_answer 206 · dup 1 decontam vs EVAL.lock: 0 overlap (train/test disjoint by construction) Finding: the strong teacher emits ungrounded/wrong chains ~43% of the time on this distribution; all rejected before training (the strict-basis move).
SFT: R1-Distill-1.5B + LoRA r64 (7 modules, 73.9M = 3.99% trainable), batch1 x accum16, 3 epochs, seq 1024 constant-pad (0.03% truncated), sdpa + gradient checkpointing. train loss 0.538 -> 0.075, eval 0.311, runtime 2h31m. Merged model saved (3.5GB).
Result: (format-prompt, vs frozen baseline, greedy, frozen verifier) verifiable 76.8% (base 0.0) · accuracy 65.8% (base 61.6) · verified+correct 58.0% (base 0.0) mean assertions/chain 3.44 (base 0.0)
PREREG: lift +58.0pp verified-and-correct -> SUPPORTED (bar +15pp) verifiable-rate 76.8% -> NOT SUPPORTED (bar 90%) accuracy delta +4.2pp (improved) -> SUPPORTED (bar: no regress >5pp) => 2 of 3 SUPPORTED; all-three gate not met.
RL gate: WARRANTED via the high-signal condition (76.8% verifiable / 58% v&c gives the verifier-reward RL dense signal); all-three bar NOT cleared (verifiable < 90 is the explicit RL target). Not a null — a large real lift missing one of three bars.
Honest: Thesis validated — distilling ONLY verifier-confirmed chains took the model from 0% mechanically-checkable reasoning to 76.8% verifiable / 58% verified-and-correct, with accuracy rising not falling. The grounding transferred; the remaining ~23% unverifiable tail is the RL phase's job.
Decisions np-007..np-010 · all frozen locks intact · eval decontaminated · SFT_RESULT.lock frozenNext: Dispatch 3 = RLVR/GRPO with the frozen verifier as reward, target verifiable-rate >=90%, RL criteria pre-registered against a held-out slice never used for SFT selection.1234567891011121314151617181920212223242526272829303132333435363738394041424344=== NPC Reason — Dispatch 3: RLVR / GRPO ===
Reward: frozen verifier d5d146cf (byte-identical to baseline/SFT), correctness-gated (verifiable&correct=1.0 | correct-only=0.3 | wrong=0.0), hack-guards + stats active.RL data: 5,499 train-split prompts = problems.jsonl MINUS sft_train ids (SFT-rejected; gold known; disjoint from SFT-selection). RL-dev 200 (never eval). decontam vs EVAL.lock = 0 overlap. RL_DATA.lock frozen.GRPO: from SFT (PEFT LoRA r32, ref=base w/ adapter disabled), use_vllm=False (TRL1.6 vs vLLM0.23 mismatch avoided), KL beta=0.08, LR 2e-6, group 8, max_steps 300. best-ckpt by RL-dev verified-and-correct kept.Stability: STABLE — KL 0.0001-0.0004 throughout, no length runaway, no mode collapse, no early-stop trip. (Run hit a transient error at step 260; the best checkpoint is step 200, predates it, unaffected.) This is the regime the 5 prior RL runs never reached: a hard verifier reward trains a small model stably. Dev (hard SFT-rejected tail, 400-tok cap — pessimistic proxy): v&c 0.292 -> 0.323.
Result (format-prompt, frozen EVAL.lock, greedy, frozen verifier): base SFT NPC-Reason-RL verifiable 0.0% 76.8% 76.2% (RL vs SFT -0.6pp) accuracy 61.6% 65.8% 66.6% (RL vs SFT +0.8pp) verified+corr 0.0% 58.0% 59.6% (RL vs SFT +1.6pp)
PREREG (final NPC Reason = RL): primary lift verified-and-correct vs base = +59.6pp -> SUPPORTED (bar +15) verifiable-rate = 76.2% -> NOT SUPPORTED (bar 90%) accuracy guard vs base = +5.0pp -> SUPPORTED (no regress) => 2 of 3 SUPPORTED — same as SFT; RL did NOT move criterion-2 (90% verifiable).
Shipped: NPC Reason = the RL model (rl/merged) — marginally best on the headline metric (verified-and-correct 59.6 vs SFT 58.0) and accuracy (66.6 vs 65.8); verifiable a hair lower (76.2 vs 76.8). Honest magnitude: ~+1.6pp v&c on n=500 (~8 problems) — a small but consistent-direction win, NOT a decisive one. SFT model retained as the near-equal fallback.
Honest: RLVR with the frozen verifier reward was STABLE and added a small refinement, but the SFT distillation did the heavy lifting (0 -> 76.8% verifiable). RL could not push verifiable past ~77% under the deliberately conservative (anti-instability) config; the 90% bar is unmet. Per the dispatch, we did NOT crank LR/steps chasing 90% into the instability that killed prior runs — a stable +1.6pp beats an unstable collapse. Not a null (RL > SFT on the headline), but close to one, and reported as such.
Decisions np-011..np-014 · all 6 prior locks intact · eval untouched until final · RL_RESULT.lock frozenProject arc: base 0% verifiable -> SFT 76.8% (distill) -> RL 76.2%/59.6% v&c (stable refinement). The verifier-grounding transferred; orchestration of the 90% bar is the open frontier.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748=== NPC Reason - Dispatch 4: Packaging + Card ===
GGUF: f16 / q8_0 / q4_K_M of the shipped RL model (rl/merged), built with llama.cpp (CUDA). Decision-fidelity vs bf16 on 100 frozen-eval problems (greedy, frozen verifier d5d146cf): f16 dVC +0.0 OK q8_0 dVC +0.0 OK <- RECOMMENDED (behaviorally lossless, 1.9 GB) q4_K_M dVC +6.0 DRIFTS (exceeds +/-2pp) -> flagged, NOT recommended The Fin Nano lesson reproduced: q4 is structurally valid but changes decisions under quant noise. Do not pick a quant on file size alone. (reports/gguf_fidelity.md)
Card: MODEL_CARD.md - full base/SFT/RL arc (verifiable 0 -> 76.8 -> 76.2; v&c 0 -> 58.0 -> 59.6; accuracy 61.6 -> 65.8 -> 66.6), distillation-did-the-heavy-lifting, RLVR-stable-but-small (~tied with SFT), 90% verifiable bar NOT met (stated as the open limitation), verifier d5d146cf documented as BOTH the metric AND the reward, MIT/V4 lineage, attribution Rama Krishna Bachu / Bottensor / ORCID 0009-0000-1298-0681. No overclaiming, no em dashes. USAGE.md - format prompt + vLLM/GGUF run + how to run the verifier on outputs.
Release tree (release/, 22 curated text files; model + GGUF binaries referenced separately): MODEL_CARD.md, USAGE.md verifier/ (step_verifier.py + VERIFIER.lock) <- the product: users verify chains eval/ (run_eval.py, eval_set.jsonl, _eval_meta.json, EVAL.lock) tests/ (test_verifier.py) prereg/ (PREREG.md + PREREG.lock) locks/ (BASELINE / TRAINSET / SFT_RESULT / RL_RESULT .lock) reports/ (baseline, sft_result, dispatch1/2/3_complete, gguf_fidelity, fidelity_result.json) MODEL BINARIES (push-time): rl/merged/ (bf16, shipped) + gguf/{f16,q8_0,q4_K_M}. EXCLUDED (de-link / methodology / secrets-touching): decisions.md, data/generate_v4.py (DeepSeek API code), all *.sh run/build scripts, raw logs, reward_stats, training scripts.
Credential scan: CLEAN (HARD-HALT gate PASSED). Adversarial multi-angle audit (5 independent auditors + reconciling synthesizer, all CLEAN, independently re-verified on the host): - strict secret regex (sk-/hf_/ghp_/gho_/AKIA/xox*/AIza/BEGIN PRIVATE KEY): zero matches. - all 5 known chat-leaked key prefixes (DeepSeek / HF x2 / CoinGecko / OpenAI-style): absent. - "DEEPSEEK_API_KEY" string: absent from release/ (only in excluded generate_v4.py + decisions.md). - release .py files: local model-load + SymPy only, no os.environ/network/auth. - false-positives dismissed: SHA-256 hashes, env-var NAMES, tokenizer vocab tokens, a GSM8K "secret seasoning" word problem.
Push: NOT done (prep only, per dispatch). Preconditions before a push dispatch runs: 1. Operator supplies HF org/repo name and confirms PRIVATE. 2. Operator ROTATES the DeepSeek key (still outstanding; it passed through chat). 3. At push time, re-confirm a FULL (not sampled) credential scan against the EXACT push manifest IF model binaries (gguf/safetensors) are bundled (they live outside release/ and were sampled-clean: safetensors header no-secret, gguf strings clean). 4. Apply the same de-link discipline used for the BigBugAI HF push (no lineage docs).
Decisions np-015..np-018 logged. 7 frozen locks intact (no training/eval-logic changes this dispatch).Project complete: base 0% -> SFT 76.8% -> RL 76.2%/59.6% v&c, verifier-grounded, honestly reported.123456789101112131415161718192021222324252627282930{ "bf16_reference_n100": { "n": 100, "verifiable": 93.0, "vc": 71.0 }, "tolerance_pp": 2.0, "quants": { "f16": { "verifiable": 95.0, "vc": 71.0, "vc_delta_vs_bf16": 0.0, "fidelity_ok": true }, "q8_0": { "verifiable": 95.0, "vc": 71.0, "vc_delta_vs_bf16": 0.0, "fidelity_ok": true }, "q4_K_M": { "verifiable": 95.0, "vc": 77.0, "vc_delta_vs_bf16": 6.0, "fidelity_ok": false } }, "recommended": "q8_0", "q4_drifts": true}123456789101112131415161718192021222324252627282930313233# NPC Reason - GGUF decision-fidelity (Dispatch 4, Stage 1)
GGUFs of the shipped RL model (`rl/merged`), built with llama.cpp (CUDA). Fidelity is validated onDECISIONS, not just structure (the Fin Nano lesson: a structurally-valid quant can still drift themodel's decisions). Each quant ran the SAME 100 frozen-eval problems greedy via llama-cpp-python(`create_chat_completion`, the model's embedded chat template), scored by the FROZEN verifier(d5d146cf), and compared to the bf16 model on those exact 100 problems.
Tolerance: a quant is fidelity-OK if verified-and-correct is within +/-2pp of bf16.
| model | size | verifiable | verified-and-correct | dVC vs bf16 | fidelity ||---------|-------:|-----------:|---------------------:|------------:|----------|| bf16 | 3.5 GB | 93.0% | 71.0% | ref | ref || f16 | 3.6 GB | 95.0% | 71.0% | +0.0 | OK || **q8_0**| 1.9 GB | 95.0% | 71.0% | +0.0 | **OK (recommended)** || q4_K_M | 1.1 GB | 95.0% | 77.0% | +6.0 | DRIFTS (flagged) |
(The 100-problem subset is GSM8K-heavy, so the absolute v&c is higher than the full n=500 numberof 59.6%; fidelity here is the per-quant DELTA, which is the meaningful quantity.)
## Recommendation: q8_0
- **q8_0 is behaviorally lossless** on this product (verified-and-correct delta 0.0 vs bf16). It is half the size of f16 and reproduces the model's decisions. Use it.- **q4_K_M DRIFTS and is flagged, not recommended.** Its verified-and-correct moved +6pp (well past the +/-2pp tolerance). The direction happens to be upward on these 100, but that is a decision CHANGE under quant noise, not fidelity. Per the Fin Nano lesson, do not choose a quant on file size alone; q4_K_M's chains are not the bf16 model's chains. Use only if a 1.1 GB footprint is required and the decision drift is acceptable for the use case.- f16 is provided as the lossless reference.
Validation harness: `gguf/fidelity_eval.py` (frozen verifier, greedy, n=100). Raw:`gguf/fidelity_result.json`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# NPC Reason — SFT result vs frozen baseline + PREREG (Dispatch 2, Stage 4)
NPC-Reason-SFT = R1-Distill-1.5B + LoRA (r64), distilled on **7,546 V4 chains that the FROZENverifier confirmed verifiable AND correct**. Evaluated on the frozen EVAL.lock (500 held-outGSM8K+MATH), same greedy decoding as the baseline (apples-to-apples), scored by the frozenverifier (VERIFIER.lock d5d146cf).
## Result (format-prompt = the committed comparator)
| | base (format) | NPC-Reason-SFT | delta ||------------------------|--------------:|---------------:|--------:|| verifiable-rate | 0.0% | **76.8%** | +76.8pp || accuracy | 61.6% | **65.8%** | +4.2pp || verified-and-correct | 0.0% | **58.0%** | +58.0pp || mean assertions/chain | 0.0 | 3.44 | — |
Plain-prompt (native, no format instruction): verifiable 0.0%, accuracy 64.8%. The model emitsthe `<<EXPR=RESULT>>` format under the format prompt it was trained on, not unprompted — expected,and the format prompt is the committed comparator.
## PREREG verdict (committed bars, frozen b5a49437 — graded honestly)
| Criterion | Bar | Result | Verdict ||---|---|---|---|| 1. Primary lift (verified-and-correct over format baseline) | ≥ +15pp | **+58.0pp** | **SUPPORTED** || 2. Verifiable-rate | ≥ 90% | 76.8% | **NOT SUPPORTED** || 3. Accuracy guard (no regression > 5pp) | ≥ −5pp | **+4.2pp** (improved) | **SUPPORTED** |
**2 of 3 SUPPORTED.** The all-three gate is not met (criterion 2 missed).
## Honest read
- **The central thesis is validated, strongly.** Distilling *only mechanically-verified* teacher chains moved a model that produced **zero** checkable reasoning (0% verifiable, even when asked) to **76.8% verifiable / 58% verified-and-correct** — a +58pp jump on the headline metric, far past the +15pp bar. The grounding transferred.- **Accuracy did not regress — it rose** (+4.2pp). Verifiability was not bought by sacrificing correctness; the strict-basis corpus improved both. (Some of the rise is reduced greedy repetition vs the base; attributed, not overclaimed.)- **The one missed bar is verifiable-rate (76.8% vs 90%).** ~23% of format-prompt chains still fail full verification — a step that doesn't verify, doesn't compose, or the model reverts to prose on harder MATH items. This is exactly the gap RL-with-verifier-reward is designed to close.
## RL gate
The committed gate is: RL proceeds if SFT clears its bar **OR** produces a high verifiable-rateso RL has signal to sharpen. All-three bar: **NOT cleared** (verifiable 76.8 < 90). High-signalcondition: **MET** — 76.8% verifiable / 58% verified-and-correct gives RL (verifier = reward, thesame frozen code) dense signal to push toward ≥90%. So the RL phase is **warranted**, entered witheyes open that criterion 2 is the explicit target. A null at SFT would have been valid; this is nota null — it is a large, real lift that misses one of three bars.
Frozen: `sft/SFT_RESULT.lock`. Raw per-item outputs: `eval/eval_raw.jsonl`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Tests that prove the verifier is trustworthy (it is the metric AND the later RL reward).
Run: pytest tests/test_verifier.py -q"""
import sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from verifier.step_verifier import ( # noqa: E402 extract_final_answer, verify_assertion, verify_chain,)
# --------------------------------------------------------------------------- ## 1. correct + verifiable chain# --------------------------------------------------------------------------- #def test_correct_and_verifiable(): text = ( "Tom packs 3 bags with 8 apples each. " "So the total is <<3*8 = 24>> apples. " "The answer is \\boxed{24}." ) r = verify_chain(text, gold_answer=24) assert r["verifiable"] is True assert r["correct"] is True assert r["verified_and_correct"] is True assert r["n_assertions"] == 1 and r["n_verified"] == 1 assert r["composes_to_final"] is True
# --------------------------------------------------------------------------- ## 2. one arithmetic error -> not verifiable, the bad step flagged# --------------------------------------------------------------------------- #def test_arithmetic_error_flagged(): text = "We compute <<2 + 2 = 5>> and conclude \\boxed{5}." r = verify_chain(text, gold_answer=5) assert r["verifiable"] is False assert r["n_assertions"] == 1 and r["n_verified"] == 0 assert any("2 + 2" in f.get("expr", "") for f in r["failures"])
# --------------------------------------------------------------------------- ## 3. THE fluency trap: fluent prose, right answer, NO assertions -> not verifiable# (proves the verifier rewards mechanical grounding, not plausible text)# --------------------------------------------------------------------------- #def test_fluency_trap(): text = ( "We carefully add up all the quantities involved, and after thinking it " "through it is clear the total works out to twenty-four, so the answer is " "\\boxed{24}." ) r = verify_chain(text, gold_answer=24) assert r["has_loadbearing_assertions"] is False assert r["verifiable"] is False # no load-bearing assertions assert r["correct"] is True # final answer still matches gold assert r["verified_and_correct"] is False # the two axes are independent
# --------------------------------------------------------------------------- ## 4. steps verify but final answer does not compose from them -> not verifiable# --------------------------------------------------------------------------- #def test_non_composing_final(): text = ( "First <<10 * 2 = 20>>, then <<20 + 5 = 25>>. " "Therefore the answer is \\boxed{30}." ) r = verify_chain(text, gold_answer=30) assert r["all_assertions_verified"] is True assert r["n_verified"] == 2 assert r["composes_to_final"] is False assert r["verifiable"] is False assert any("compose" in f.get("reason", "") for f in r["failures"])
# --------------------------------------------------------------------------- ## 5a. verifiable BUT WRONG (internally consistent + composes, final != gold)# --------------------------------------------------------------------------- #def test_verifiable_but_wrong(): text = "Clearly <<2 + 2 = 4>>, so \\boxed{4}." r = verify_chain(text, gold_answer=5) assert r["verifiable"] is True assert r["correct"] is False assert r["verified_and_correct"] is False
# --------------------------------------------------------------------------- ## 5b. correct BUT UNVERIFIABLE — same as the fluency trap axis, asserted distinctly# --------------------------------------------------------------------------- #def test_correct_but_unverifiable(): text = "After some mental arithmetic the answer is \\boxed{42}." r = verify_chain(text, gold_answer=42) assert r["correct"] is True assert r["verifiable"] is False
# --------------------------------------------------------------------------- ## 6. variable binding threads forward# --------------------------------------------------------------------------- #def test_variable_binding(): text = ( "Let total = <<3 * 8 = 24>>. " "Adding the bonus: <<total + 6 = 30>>. " "So \\boxed{30}." ) r = verify_chain(text, gold_answer=30) assert r["n_assertions"] == 2 and r["n_verified"] == 2 assert r["verifiable"] is True and r["correct"] is True
# --------------------------------------------------------------------------- ## 7. fail-closed on an unbound symbol (v1 out-of-scope algebra)# --------------------------------------------------------------------------- #def test_unbound_symbol_fails_closed(): text = "We have <<x + 2 = 5>> hence \\boxed{3}." r = verify_chain(text, gold_answer=3) assert r["n_verified"] == 0 assert r["verifiable"] is False assert any("unbound" in f.get("reason", "") for f in r["failures"])
# --------------------------------------------------------------------------- ## 8. tolerance policy: exact rationals + 1e-6 float# --------------------------------------------------------------------------- #def test_exact_rational(): # decimals parse as exact rationals, so this is an EXACT match assert verify_assertion("0.1 + 0.2", "0.3", {}).ok is True
def test_float_tolerance(): r = verify_assertion("2**0.5", "1.4142135", {}) assert r.ok is True # within 1e-6 relative
def test_float_outside_tolerance(): r = verify_assertion("2**0.5", "1.41", {}) assert r.ok is False
def test_thousands_separator(): assert verify_assertion("1,000 + 234", "1,234", {}).ok is True
# --------------------------------------------------------------------------- ## 9. final-answer extraction priority# --------------------------------------------------------------------------- #def test_final_answer_extraction(): assert extract_final_answer("blah \\boxed{7} blah") == "7" assert extract_final_answer("steps...\n#### 42") == "42" assert extract_final_answer("so the answer is 13.") == "13" assert extract_final_answer("no answer here") is None
def test_unparseable_fails_closed(): r = verify_assertion("3 +* 4", "7", {}) assert r.ok is False12345678{ "files": { "verifier/step_verifier.py": "d5d146cfbb9a69e162c1a80a330c942b195bfd6d0a0961ae480cc1875989613b" }, "definition": "chain VERIFIABLE iff (a) >=1 load-bearing <<EXPR=RESULT>> assertion, (b) every assertion verifies under SymPy, (c) final answer composes from the last load-bearing step. CORRECT = final==gold (independent axis).", "tolerance_policy": "exact for integers/rationals (simplify(diff)==0); else 1e-6 relative for floats; fail-closed on unparseable/unbound/exception.", "purity": "pure code, no model/LLM judgment; reused verbatim as the RL reward later."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300"""NPC Reason — mechanical step verifier (THE core artifact).
PURE CODE. No model, no LLM judgment anywhere. This is what makes the"verifiable-rate" metric un-fakeable, and it is reused verbatim as the RL rewardsignal in a later dispatch — so it is frozen (VERIFIER.lock) the moment its tests pass.
DEFINITION (committed; see reports/PREREG.md and VERIFIER.lock): - A reasoning chain is a sequence of steps ending in a final answer. - A load-bearing numeric step carries an inline checkable assertion in the canonical form <<EXPR = RESULT>> where EXPR is an arithmetic/algebraic expression over numbers and earlier-BOUND variables, and RESULT is the claimed value. - A step is VERIFIED if a SymPy evaluation of EXPR equals RESULT within tolerance (exact for integers/rationals; 1e-6 relative for floats). - A chain is VERIFIABLE iff: (a) it has >=1 load-bearing <<...>> assertion (no bare asserted numbers drive it), (b) every such assertion VERIFIES, and (c) the final answer equals the RESULT of the last load-bearing step (the chain COMPOSES to its conclusion). - A chain is CORRECT iff its final answer equals the gold answer. CORRECT and VERIFIABLE are INDEPENDENT axes.
TOLERANCE POLICY (explicit, frozen): - Parse EXPR and RESULT with sympy.sympify (after a small, fixed normalization). - Exact branch: if simplify(EXPR_value - RESULT_value) == 0 -> VERIFIED. - Float branch: else, if both are finite numbers and |EXPR_value - RESULT_value| <= 1e-6 * max(1, |RESULT_value|) -> VERIFIED. - Otherwise NOT verified.
FAIL-CLOSED (conservative by design): - Unparseable EXPR or RESULT -> NOT verified (reason recorded). - EXPR references an UNBOUND symbol -> NOT verified (cannot confirm). - Any exception during evaluation -> NOT verified. A chain only counts VERIFIABLE if the checker can ACTUALLY confirm every load-bearing step.
VARIABLE BINDING (v1, documented): - A step may bind a name: `let total = <<3*8 = 24>>` or `total = <<3*8 = 24>>`. The name binds to the (parsed) RESULT value and is usable by later EXPRs. - Binding tests internal consistency: each later step is checked against the values the chain itself previously stated. - V1 SCOPE: assertions are concrete-valued (EXPR evaluates to a number once prior bindings are substituted). Algebra with FREE variables / equation-solving such as `<<x**2 - 4 = 0>>` with x unbound is OUT OF SCOPE for v1 and FAILS CLOSED (recorded reason: "unbound symbol"). It is noted as a verifier-v2 extension."""
from __future__ import annotations
import refrom dataclasses import dataclass, fieldfrom typing import Optional
import sympyfrom sympy import Rational, simplify, sympify
# ----------------------------------------------------------------------------- ## Patterns# ----------------------------------------------------------------------------- #
# Optional binding name, then << EXPR = RESULT >>. Non-greedy EXPR stops at the# FIRST '=' inside the brackets. Binding name must start with a letter/underscore,# so numeric tokens to the left (e.g. "2 + 2 =") are never captured as a name.ASSERTION = re.compile( r"(?:(?:let\s+)?([A-Za-z_]\w*)\s*=\s*)?<<\s*(.+?)\s*=\s*(.+?)\s*>>")
# Final-answer extractors, tried in priority order._BOXED = re.compile(r"\\boxed\{\s*([^{}]+?)\s*\}")_GSM = re.compile(r"####\s*([^\n]+)")_ANSWER_IS = re.compile( r"(?:final answer|the answer is|answer\s*[:=])\s*\$?\\?\(?\s*" r"([+-]?[\d.,/eE^*+\-() ]*\d)", re.IGNORECASE,)
# Characters/sequences to normalize before sympify._THOUSANDS = re.compile(r"(?<=\d),(?=\d{3}\b)")_NORM_REPLACE = ( (r"\times", "*"), (r"\cdot", "*"), (r"\div", "/"), (r"\left", ""), (r"\right", ""), ("^", "**"), ("%", "/100"), ("$", ""), ("×", "*"), ("÷", "/"), ("−", "-"), # unicode minus)
@dataclassclass StepResult: expr: str claimed: str ok: bool reason: str binding: Optional[str] = None
@dataclassclass ChainRecord: n_assertions: int = 0 n_verified: int = 0 has_loadbearing_assertions: bool = False all_assertions_verified: bool = False final_answer: Optional[str] = None final_answer_value: Optional[object] = None composes_to_final: bool = False verifiable: bool = False correct: Optional[bool] = None verified_and_correct: Optional[bool] = None steps: list = field(default_factory=list) failures: list = field(default_factory=list)
def as_dict(self) -> dict: return { "n_assertions": self.n_assertions, "n_verified": self.n_verified, "has_loadbearing_assertions": self.has_loadbearing_assertions, "all_assertions_verified": self.all_assertions_verified, "final_answer": self.final_answer, "composes_to_final": self.composes_to_final, "verifiable": self.verifiable, "correct": self.correct, "verified_and_correct": self.verified_and_correct, "failures": self.failures, "steps": [ {"expr": s.expr, "claimed": s.claimed, "ok": s.ok, "reason": s.reason, "binding": s.binding} for s in self.steps ], }
# ----------------------------------------------------------------------------- ## Numeric core# ----------------------------------------------------------------------------- #
def _normalize(raw: str) -> str: s = raw.strip() s = _THOUSANDS.sub("", s) # 1,234 -> 1234 (drop thousands separators) for a, b in _NORM_REPLACE: s = s.replace(a, b) # \frac{a}{b} -> ((a)/(b)) s = re.sub(r"\\d?frac\{([^{}]+)\}\{([^{}]+)\}", r"((\1)/(\2))", s) s = s.replace("\\", " ") return s.strip()
def _to_sympy(raw: str, bindings: dict): """sympify a normalized token; raises on failure (caller fails closed).""" expr = sympify(_normalize(raw), locals=bindings, rational=True) return expr
def _values_match(a, b) -> bool: """Exact for rationals/integers; 1e-6 relative for floats.""" diff = simplify(a - b) if diff == 0: return True try: if diff.free_symbols: return False fa, fb = float(a), float(b) return abs(fa - fb) <= 1e-6 * max(1.0, abs(fb)) except (TypeError, ValueError): return False
def verify_assertion(expr: str, claimed: str, bindings: dict) -> StepResult: """Evaluate one <<EXPR = RESULT>> against current bindings. Fail-closed.""" try: e = _to_sympy(expr, bindings) except Exception as ex: # noqa: BLE001 — fail closed on any parse error return StepResult(expr, claimed, False, f"unparseable expr: {ex}") try: c = _to_sympy(claimed, bindings) except Exception as ex: # noqa: BLE001 return StepResult(expr, claimed, False, f"unparseable result: {ex}")
# EXPR must reduce to a concrete value (v1 scope: no free variables). if getattr(e, "free_symbols", set()): unbound = ", ".join(sorted(str(s) for s in e.free_symbols)) return StepResult(expr, claimed, False, f"unbound symbol(s): {unbound}")
try: ok = _values_match(e, c) except Exception as ex: # noqa: BLE001 return StepResult(expr, claimed, False, f"comparison error: {ex}") reason = "verified" if ok else f"mismatch: {expr} -> {e} != {claimed}" return StepResult(expr, claimed, ok, reason)
# ----------------------------------------------------------------------------- ## Final answer# ----------------------------------------------------------------------------- #
def extract_final_answer(text: str) -> Optional[str]: """Last \\boxed{}, else last ####, else 'the answer is X'. None if absent.""" boxed = _BOXED.findall(text) if boxed: return boxed[-1].strip() gsm = _GSM.findall(text) if gsm: return gsm[-1].strip() m = list(_ANSWER_IS.finditer(text)) if m: return m[-1].group(1).strip().rstrip(".") return None
def _safe_value(raw: str, bindings: dict): try: v = _to_sympy(raw, bindings) return None if getattr(v, "free_symbols", set()) else v except Exception: # noqa: BLE001 return None
# ----------------------------------------------------------------------------- ## Chain# ----------------------------------------------------------------------------- #
def verify_chain(text: str, gold_answer=None) -> dict: """Mechanically derive every field. No judgment. Returns ChainRecord.as_dict().""" rec = ChainRecord() bindings: dict = {}
for m in ASSERTION.finditer(text): name, expr, claimed = m.group(1), m.group(2), m.group(3) res = verify_assertion(expr, claimed, bindings) res.binding = name rec.steps.append(res) rec.n_assertions += 1 if res.ok: rec.n_verified += 1 else: rec.failures.append({"expr": expr, "claimed": claimed, "reason": res.reason}) # Bind the name to the CLAIMED result value (internal-consistency semantics), # whenever the result parses to a concrete value — even if the step failed, # so downstream reasons are about the downstream step, not a cascade. if name: v = _safe_value(claimed, bindings) if v is not None: bindings[name] = v
rec.has_loadbearing_assertions = rec.n_assertions > 0 rec.all_assertions_verified = ( rec.has_loadbearing_assertions and rec.n_verified == rec.n_assertions )
# Final answer + composition. fa = extract_final_answer(text) rec.final_answer = fa fa_val = _safe_value(fa, bindings) if fa is not None else None rec.final_answer_value = fa_val
if rec.has_loadbearing_assertions and fa_val is not None: last_claimed = rec.steps[-1].claimed last_val = _safe_value(last_claimed, bindings) if last_val is not None: try: rec.composes_to_final = _values_match(fa_val, last_val) except Exception: # noqa: BLE001 rec.composes_to_final = False if not rec.composes_to_final and rec.has_loadbearing_assertions: rec.failures.append({"reason": "final answer does not compose from last step"})
rec.verifiable = ( rec.has_loadbearing_assertions and rec.all_assertions_verified and rec.composes_to_final )
# Correctness (independent axis). if gold_answer is not None: gold_val = _safe_value(str(gold_answer), {}) if fa_val is not None and gold_val is not None: try: rec.correct = _values_match(fa_val, gold_val) except Exception: # noqa: BLE001 rec.correct = False else: # Fall back to normalized string compare (handles non-numeric MATH answers). rec.correct = ( fa is not None and _normalize(fa).replace(" ", "") == _normalize(str(gold_answer)).replace(" ", "") ) rec.verified_and_correct = bool(rec.verifiable and rec.correct)
return rec.as_dict()
if __name__ == "__main__": import json import sys
blob = sys.stdin.read() print(json.dumps(verify_chain(blob), indent=2, default=str))USAGE.mdAdded+67
eval/EVAL.lockAdded+6
eval/_eval_meta.jsonAdded+30
eval/eval_set.jsonlAdded
eval/run_eval.pyAdded+112
locks/BASELINE.lockAdded+40
locks/RL_RESULT.lockAdded+7
locks/SFT_RESULT.lockAdded+6
locks/TRAINSET.lockAdded+29
prereg/PREREG.lockAdded+5
prereg/PREREG.mdAdded+52
reports/baseline.mdAdded+52
reports/dispatch1_complete.mdAdded+40
reports/dispatch2_complete.mdAdded+36
reports/dispatch3_complete.mdAdded+44
reports/dispatch4_complete.mdAdded+48
reports/fidelity_result.jsonAdded+30
reports/gguf_fidelity.mdAdded+33
reports/sft_result.mdAdded+53
tests/test_verifier.pyAdded+159
verifier/VERIFIER.lockAdded+8
verifier/step_verifier.pyAdded+300