"""Proof checking logic: informal theorem + proof -> Lean skeleton -> per-step proofs -> report. Every stage is a generator yielding ("log", text) events and finally ("result", value), so the Gradio handler can stream progress while all GPU calls stay in the request thread. """ import io, re, textwrap, time import leanenv # ----------------------------------------------------------------------------- settings SKELETON_ROUNDS = 4 # Prover rounds per step: (mode, samples, max_new_tokens). Non-CoT is short and cheap; # the CoT round is longer and only runs if non-CoT found nothing. STEP_ROUNDS = [("noncot", 8, 1024), ("noncot", 8, 1024), ("cot", 4, 3072)] MAX_PAGES = 6 # Fallback when no skeleton compiles: write only the statement, then prove it whole. STATEMENT_ROUNDS = 3 DIRECT_ROUNDS = [("noncot", 8, 1024), ("cot", 4, 3072), ("cot", 4, 3072)] AUTO = ("first | omega | linarith | positivity | nlinarith | (norm_num; done) " "| (simp; done) | (ring_nf; done) | (field_simp; ring)") # ----------------------------------------------------------------------------- prompts READ_SYSTEM = """You transcribe mathematics from page images. The pages contain one or more problems, each a theorem (or claim) followed by its proof. Transcribe every problem exactly as written. Do not fix, complete or shorten the proofs. Write mathematics in plain text: ^ for powers, sqrt(x), a/b, <=, >=, !=, sum_{i=1}^{n}, Greek letters as words. Do not use LaTeX backslashes. Output nothing except blocks in exactly this format, one per problem: === PROBLEM 1 === THEOREM: PROOF: """ SKETCH_SYSTEM = """You are an expert in Lean 4 and Mathlib. You turn an informal theorem and its human proof into a Lean 4 proof SKELETON whose steps are left as placeholders. Do NOT write import, open or set_option lines. This header is added for you: {header} Output exactly one ```lean block, shaped like this: ```lean theorem main_theorem (n : ℕ) (hn : 0 < n) : := by -- Informal 1: have h1 : := by sorry -- STEP 1 -- Informal 2 (gap): have h2 : := by sorry -- STEP 2 -- Informal 3: sorry -- STEP 3 ``` Rules: 1. Exactly one theorem, named `main_theorem`, stating exactly the informal theorem: same objects, hypotheses and conclusion. Never strengthen hypotheses or weaken the conclusion. Natural-number subtraction and division truncate, so use ℤ or ℝ when the mathematics needs negatives, real division or real roots. 2. Follow the human proof step by step, one `have` per step. Where the human skipped reasoning Lean will need, add a step and mark its comment `(gap)`. Keep each step small. 3. Every placeholder is EXACTLY `sorry -- STEP k` on its own line, k = 1..N, unique. Induction / cases are allowed; every leaf goal uses the same placeholder form. 4. The last step closes the main goal. 5. Use Lean 4 Mathlib syntax only (`fun x => ...`, `Real.sqrt`, `Finset.range`), never Lean 3. 6. No other `sorry`, no `admit`, `native_decide` or `axiom`. No other definitions or lemmas. """ STATEMENT_SYSTEM = """You are an expert in Lean 4 and Mathlib. Formalise ONLY the statement of the informal theorem below; do not prove it. Do NOT write import, open or set_option lines. This header is added for you: {header} Output exactly one ```lean block containing exactly: ```lean theorem main_theorem : := by sorry ``` Rules: same objects, hypotheses and conclusion as the informal theorem; never strengthen hypotheses or weaken the conclusion. Natural-number subtraction and division truncate, so use ℤ or ℝ when the mathematics needs negatives, real division or real roots. Lean 4 Mathlib syntax only. No other declarations, no other text in the block. """ BACK_SYSTEM = """Translate the given Lean 4 theorem statement into precise plain mathematical English. Do not prove it and do not guess intent: state exactly what the Lean says, including the number types (ℕ, ℤ, ℝ) and every hypothesis. Answer in at most 3 sentences, plain text.""" PROVER_NONCOT = "Complete the following Lean 4 code:\n\n```lean4\n{}\n```" PROVER_COT = PROVER_NONCOT + """ Before producing the Lean 4 code to formally prove the given theorem, provide a detailed proof plan outlining the main proof steps and strategies. The plan should highlight key ideas, intermediate lemmas, and proof structures that will guide the construction of the final formal proof.""" # ----------------------------------------------------------------------------- text helpers MARK = re.compile(r"^([ \t]*)sorry[ \t]*--[ \t]*STEP[ \t]+(\d+)[ \t]*$") MARK_M = re.compile(MARK.pattern, re.M) INFORMAL = re.compile(r"--\s*Informal\s+(\d+)\s*(\(gap\))?\s*:\s*(.+)") BANNED = re.compile(r"\bsorry\b|\badmit\b|\bnative_decide\b|^\s*axiom\s", re.M) BLOCK = re.compile(r"===\s*PROBLEM\s+(\d+)\s*===\s*THEOREM:\s*(.*?)\s*PROOF:\s*(.*?)\s*(?====\s*PROBLEM|\Z)", re.S) HEADER_LINE = re.compile(r"^\s*(import|open|set_option)\b") def fenced(text): """Last fenced code block (any language tag), or None.""" blocks = re.findall(r"```[^\n`]*\n(.*?)```", text, re.S) return blocks[-1].strip("\n") if blocks else None def strip_header(code): return "\n".join(l for l in code.split("\n") if not HEADER_LINE.match(l)).strip("\n") def with_header(body): return leanenv.header() + "\n\n" + body.strip("\n") + "\n" def body_offset(): """Line number in with_header(body) = line number in body + body_offset().""" return leanenv.header().count("\n") + 2 def markers(code): out = {} for i, line in enumerate(code.split("\n"), 1): m = MARK.match(line) if m: out[int(m.group(2))] = (i, m.group(1)) return out def informal_steps(code): return {int(m.group(1)): ("(gap) " if m.group(2) else "") + m.group(3).strip() for m in INFORMAL.finditer(code)} def fill(code, fills): """Replace `sorry -- STEP k` lines by fills[k], re-indented to the placeholder's indent.""" out = [] for line in code.split("\n"): m = MARK.match(line) if m and int(m.group(2)) in fills: body = textwrap.dedent(fills[int(m.group(2))]).strip("\n") out.extend((m.group(1) + l) if l.strip() else l for l in body.split("\n")) else: out.append(line) return "\n".join(out) def errors_by_line(res): d = {} for e in res["errors"]: d.setdefault(e["line"], []).append(e["msg"]) return d def compiles(res, name="main_theorem"): """No errors, Lean reached the end, nothing banned. sorry is allowed.""" return (not res["timeout"] and not res["errors"] and not res["banned"] and not res["bad_axioms"] and name in res["axioms"]) def fmt_errors(res, limit=5): if res["timeout"]: return "Lean timed out." parts = [f"line {e['line']}: {e['msg'][:600]}" for e in res["errors"][:limit]] if res["banned"]: parts.append(f"banned tokens: {res['banned']}") if res["bad_axioms"]: parts.append(f"non-standard axioms: {res['bad_axioms']}") if not parts: parts.append("Lean did not elaborate `main_theorem`. " + res.get("stderr", "")[-500:]) return "\n\n".join(parts) def validate_skeleton(body): probs = [] if len(re.findall(r"^\s*(theorem|lemma|def|abbrev|instance|example)\b", body, re.M)) != 1 \ or not re.search(r"^\s*theorem\s+main_theorem\b", body, re.M): probs.append("Write exactly one declaration: `theorem main_theorem`.") ks = [int(m.group(2)) for m in MARK_M.finditer(body)] if not ks: probs.append("No `sorry -- STEP k` placeholders found.") if len(ks) != len(set(ks)): probs.append("STEP numbers must be unique.") if len(re.findall(r"\bsorry\b", body)) != len(ks): probs.append("Every `sorry` must be alone on its own line as `sorry -- STEP k`.") if re.search(r"\badmit\b|\bnative_decide\b|^\s*axiom\s", body, re.M): probs.append("Do not use admit, native_decide or axiom.") return probs def statement_of(body): m = re.search(r"theorem\s+main_theorem.*?:=\s*by", body, re.S) return m.group(0)[:-2].rstrip().rstrip(":=").rstrip() if m else "" # ----------------------------------------------------------------------------- goal -> lemma _SUP = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹", "0123456789") def _clean_names(text): # inaccessible names like x✝ or n✝¹ become x_i / n_i1 so the lemma is parseable return re.sub(r"✝([⁰¹²³⁴⁵⁶⁷⁸⁹]*)", lambda m: "_i" + m.group(1).translate(_SUP), text) def goal_to_lemma(goal, name="step_goal", doc=""): """Turn a pretty-printed goal (hypotheses + ⊢ target) into a standalone theorem statement.""" lines = [l for l in goal.strip("\n").split("\n")] entries, cur = [], None for l in lines: if not l.strip(): if cur and cur.startswith("⊢"): break # only the first goal continue if l.startswith("case "): continue if l.startswith((" ", "\t")) and cur is not None: cur += " " + l.strip() else: if cur is not None: entries.append(cur) cur = l.strip() if cur is not None: entries.append(cur) binders, target = [], None for e in entries: e = _clean_names(e) if e.startswith("⊢"): target = e[1:].strip() break if " : " not in e: continue names, typ = e.split(" : ", 1) if ":=" in typ: # let-bound variable: keep only its type typ = typ.split(":=", 1)[0].strip() if names.startswith("inst"): binders.append(f"[{typ}]") else: binders.append(f"({names} : {typ})") if target is None: return None doc_line = f"/-- {doc.strip()} -/\n" if doc.strip() else "" return f"{doc_line}theorem {name} {' '.join(binders)} :\n {target} := by\n sorry" def extract_tactics(text, name="step_goal"): """Tactic block of the prover's proof of `name`, or None.""" code = fenced(text) if not code: return None m = re.search(rf"\btheorem\s+{re.escape(name)}\b", code) or re.search(r"\b(theorem|lemma)\s+\S+", code) if not m: return None decl = code[m.start():] nxt = re.search(r"\n(?=(theorem|lemma|def|example|end|namespace|section|#)\b)", decl) if nxt: decl = decl[:nxt.start()] mb = re.search(r":=\s*by\b", decl) if mb: lines = decl[mb.end():].split("\n") first = lines[0].strip() rest = textwrap.dedent("\n".join(lines[1:])).strip("\n") tac = "\n".join(x for x in (first, rest) if x) else: mt = decl.find(":=") if mt < 0: return None term = decl[mt + 2:].strip() tac = "exact " + "\n ".join(l.strip() for l in term.split("\n")) tac = tac.strip("\n") if not tac.strip() or BANNED.search(tac) or "```" in tac: return None return tac # ----------------------------------------------------------------------------- stages def make_skeleton(models, problem): sys = SKETCH_SYSTEM.format(header=leanenv.header()) base = f"Informal theorem and proof:\n\n{problem}" body, feedback = None, None for r in range(1, SKELETON_ROUNDS + 1): msg = base if body is None else ( f"{base}\n\nYour previous skeleton:\n```lean\n{body}\n```\n\n" f"Problems found:\n{feedback}\n\nFix them and output the full corrected skeleton.") out = models.chat(sys, msg, think_tokens=3000, answer_tokens=2500, temperature=min(0.6 + 0.1 * (r - 1), 0.9)) new = fenced(out) if new is None: feedback = "Your reply had no fenced ```lean code block. Think less, and end with the code block." yield "log", f" skeleton round {r}: no code block" continue body = strip_header(new) probs = validate_skeleton(body) if probs: feedback = "\n".join(probs) yield "log", f" skeleton round {r}: format problems" continue res = leanenv.check(with_header(body)) if compiles(res): yield "log", f" skeleton round {r}: compiles with {len(markers(body))} steps" yield "result", (body, None) return feedback = fmt_errors(res) yield "log", f" skeleton round {r}: Lean errors" yield "result", (body, feedback) def probe_goals(body): """Replace every placeholder by `done`; Lean's 'unsolved goals' error shows each goal.""" mk = markers(body) off = body_offset() res = leanenv.check(with_header(fill(body, {k: "done" for k in mk}))) by_line = errors_by_line(res) goals = {} for k, (line, _) in mk.items(): msgs = by_line.get(line + off, []) goals[k] = msgs[0].replace("unsolved goals\n", "", 1) if msgs else "" return goals def try_auto(body): """One compile with the automatic tactic in every placeholder.""" mk = markers(body) off = body_offset() res = leanenv.check(with_header(fill(body, {k: AUTO for k in mk}))) bad = errors_by_line(res) proved = [k for k, (line, _) in mk.items() if line + off not in bad] if proved and not compiles(leanenv.check(with_header(fill(body, {k: AUTO for k in proved})))): proved = [k for k in proved if compiles(leanenv.check(with_header(fill(body, {k: AUTO}))))] return proved def check_candidates(skeleton, k, cands): """Check many candidate proofs of step k in ONE Lean run: each candidate goes into its own copy of the skeleton (other steps stay `sorry`). Returns the first that compiles.""" head = leanenv.header() + "\n" text, ranges = head, [] for i, c in enumerate(cands): copy = fill(skeleton, {k: c}).replace("main_theorem", f"main_theorem_c{i}", 1) start = text.count("\n") + 2 text += "\n" + copy + "\n" ranges.append((start, text.count("\n"))) res = leanenv.check(text) if res["timeout"]: return None err_lines = {e["line"] for e in res["errors"]} for i, (a, b) in enumerate(ranges): if f"main_theorem_c{i}" in res["axioms"] and not any(a <= l <= b for l in err_lines): return cands[i] return None def prove_step(models, skeleton, k, informal, goal): lemma = goal_to_lemma(goal, doc=informal) if goal else None if not lemma: yield "log", f" step {k}: could not read its goal" yield "result", (None, 0) return tried = 0 for mode, n, max_tokens in STEP_ROUNDS: prompt = (PROVER_COT if mode == "cot" else PROVER_NONCOT).format( leanenv.header() + "\n\n" + lemma) outs = models.prove(prompt, n=n, max_new_tokens=max_tokens, temperature=1.0) cands, seen = [], set() for o in outs: t = extract_tactics(o) if t and t not in seen: seen.add(t) cands.append(t) tried += len(outs) if cands: hit = check_candidates(skeleton, k, cands) if hit: yield "result", (hit, tried) return yield "log", f" step {k}: {mode} round, {len(cands)} distinct candidate(s), none compiled" yield "result", (None, tried) def _doc(text, limit=1500): """Text safe to put inside a Lean doc comment.""" return text.replace("-/", "- /").replace("/-", "/ -").strip()[:limit] def make_statement(models, problem, skeleton_body): """A compiling `theorem main_theorem ... := by sorry`. The failed skeleton's statement is tried first (no GPU); otherwise the model writes the statement alone.""" sys = STATEMENT_SYSTEM.format(header=leanenv.header()) if skeleton_body and statement_of(skeleton_body): stmt = statement_of(skeleton_body) + " := by\n sorry" if compiles(leanenv.check(with_header(stmt))): yield "log", " fallback: the skeleton's statement compiles on its own" yield "result", stmt return base = f"Informal theorem:\n\n{problem}" stmt, feedback = None, None for r in range(1, STATEMENT_ROUNDS + 1): msg = base if stmt is None else ( f"{base}\n\nYour previous statement:\n```lean\n{stmt}\n```\n\n" f"Problems found:\n{feedback}\n\nFix them and output the corrected statement.") out = models.chat(sys, msg, think_tokens=2000, answer_tokens=800, temperature=min(0.6 + 0.1 * (r - 1), 0.9)) new = fenced(out) if new is None: feedback = "Your reply had no fenced ```lean code block." yield "log", f" fallback statement round {r}: no code block" continue stmt = strip_header(new) if len(re.findall(r"^\s*(theorem|lemma|def|abbrev|instance|example)\b", stmt, re.M)) != 1 \ or not re.search(r"^\s*theorem\s+main_theorem\b", stmt, re.M) \ or len(re.findall(r"\bsorry\b", stmt)) != 1: feedback = "Write exactly one declaration, `theorem main_theorem ... := by sorry`." yield "log", f" fallback statement round {r}: format problems" continue res = leanenv.check(with_header(stmt)) if compiles(res): yield "log", f" fallback statement round {r}: compiles" yield "result", stmt return feedback = fmt_errors(res) yield "log", f" fallback statement round {r}: Lean errors" yield "result", None def prove_direct(models, stmt, problem): """Prove the whole statement with the prover, using the human proof as a hint.""" head = statement_of(stmt) skel = head + " := by\n sorry -- STEP 1" auto = try_auto(skel) if auto: yield "result", (AUTO, 0) return lemma = f"/-- {_doc(problem)} -/\n{head} := by\n sorry" tried = 0 for mode, n, max_tokens in DIRECT_ROUNDS: prompt = (PROVER_COT if mode == "cot" else PROVER_NONCOT).format( leanenv.header() + "\n\n" + lemma) outs = models.prove(prompt, n=n, max_new_tokens=max_tokens, temperature=1.0) cands, seen = [], set() for o in outs: t = extract_tactics(o, name="main_theorem") if t and t not in seen: seen.add(t) cands.append(t) tried += len(outs) if cands: hit = check_candidates(skel, 1, cands) if hit: yield "result", (hit, tried) return yield "log", f" fallback: {mode} round, {len(cands)} distinct candidate(s), none compiled" yield "result", (None, tried) def direct_fallback(models, problem, skeleton_body, report, t0): """No skeleton compiled: prove the theorem as a whole. The human steps are not checked.""" yield "log", " no skeleton compiled; falling back to proving the theorem as a whole" stmt = None for kind, val in make_statement(models, problem, skeleton_body): if kind == "log": yield kind, val else: stmt = val if not stmt: report.update(status="skeleton_failed", lean_file=with_header(skeleton_body or ""), seconds=round(time.time() - t0)) yield "result", report return report["statement_lean"] = statement_of(stmt) report["statement_back_translation"] = models.chat( BACK_SYSTEM, report["statement_lean"], think_tokens=1200, answer_tokens=300).strip() yield "log", " fallback: statement translated back; proving it whole" tac = None for kind, val in prove_direct(models, stmt, problem): if kind == "log": yield kind, val else: tac, report["samples"] = val final_body = (statement_of(stmt) + " := by\n sorry -- STEP 1") final_body = fill(final_body, {1: tac}) if tac else statement_of(stmt) + " := by\n sorry" final = leanenv.check(with_header(final_body)) report.update(status="verified_direct" if final["ok"] else "unproved", steps=[], mode="direct", lean_file=with_header(final_body), seconds=round(time.time() - t0)) yield "log", " fallback: " + ("whole proof found and verified" if final["ok"] else "no whole proof found") yield "result", report def check_problem(models, theorem, proof): """Full pipeline for one problem. Final event: ("result", report dict).""" t0 = time.time() problem = f"Theorem. {theorem}\n\nProof. {proof}" report = {"theorem": theorem, "proof": proof} body = err = None for kind, val in make_skeleton(models, problem): if kind == "log": yield kind, val else: body, err = val if err is not None or body is None: report["skeleton_error"] = err yield from direct_fallback(models, problem, body, report, t0) return report["statement_lean"] = statement_of(body) report["statement_back_translation"] = models.chat( BACK_SYSTEM, report["statement_lean"], think_tokens=1200, answer_tokens=300).strip() informal = informal_steps(body) goals = probe_goals(body) auto = try_auto(body) yield "log", f" automatic tactics closed steps {sorted(auto)}" steps = {k: {"step": k, "informal": informal.get(k, ""), "goal": goals.get(k, ""), "status": "proved_auto" if k in auto else "pending", "samples": 0} for k in sorted(markers(body))} fills = {k: AUTO for k in auto} for k in sorted(steps): if steps[k]["status"] != "pending": continue tac = None for kind, val in prove_step(models, body, k, steps[k]["informal"], steps[k]["goal"]): if kind == "log": yield kind, val else: tac, steps[k]["samples"] = val if tac: fills[k] = tac steps[k]["status"] = "proved_prover" yield "log", f" step {k}: proved by the prover" else: steps[k]["status"] = "failed" yield "log", f" step {k}: FAILED" final_body = fill(body, fills) final = leanenv.check(with_header(final_body)) if not final["ok"] and not final["sorry"]: # steps proved separately clash when combined: report honestly report["final_errors"] = fmt_errors(final) report.update(status="verified" if final["ok"] else "partial", steps=[steps[k] for k in sorted(steps)], lean_file=with_header(final_body), seconds=round(time.time() - t0)) yield "result", report # ----------------------------------------------------------------------------- PDF def render_pdf(path, scale=2.0): import pypdfium2 as pdfium pdf = pdfium.PdfDocument(path) if len(pdf) > MAX_PAGES: raise ValueError(f"PDF has {len(pdf)} pages; the limit is {MAX_PAGES}.") return [pdf[i].render(scale=scale).to_pil().convert("RGB") for i in range(len(pdf))] def parse_problems(text): probs = [] for n, thm, prf in BLOCK.findall(text): thm, prf = thm.strip(), prf.strip() if not thm: continue if not prf or prf.upper() == "NONE": prf = "(No proof given in the document. Construct a proof.)" probs.append((int(n), thm, prf)) return probs