Spaces:
Running on Zero
Running on Zero
File size: 10,531 Bytes
13e1f35 d7f867a 13e1f35 | 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 | """Lean Proof Checker: a ZeroGPU Gradio Space.
Upload a PDF of theorems + proofs (or paste one). Each proof is turned into a Lean 4 skeleton,
each step is proved by automatic tactics or an open prover model, and Lean checks everything.
ZeroGPU authorises every GPU call with a short-lived token that arrives with each browser
request, so a long job cannot run inside one request. Instead a job is a Python generator kept
on the server; a timer in the page sends a fresh request every second and each request advances
the job by at most ONE GPU call (plus any Lean work around it).
"""
import json, os, tempfile, threading, time
import gradio as gr
import leanenv
leanenv.start() # Lean + Mathlib install in the background while models load
import core # noqa: E402
import models # noqa: E402 (loads both models at startup, as ZeroGPU requires)
MAX_PROBLEMS = 10
TICK_SECONDS = 20 # max wall time per request when no GPU call happens
JOBS = {} # session hash -> job
# ----------------------------------------------------------------------------- display helpers
def lean_status_md():
s = leanenv.status()
if s["status"] == "ready":
return "**Lean + Mathlib:** ready"
if s["status"] == "failed":
return f"**Lean + Mathlib:** setup failed\n\n```\n{(s['error'] or '')[-1200:]}\n```"
return (f"**Lean + Mathlib:** {s['status']} ({s['minutes']} min). "
"The first start after the Space wakes takes about 5–10 minutes.")
def summary_md(reports):
if not reports:
return ""
rows = ["| # | Theorem | Result | Steps proved | Lean statement says |", "|---|---|---|---|---|"]
for r in reports:
steps = r.get("steps", [])
done = sum(s["status"].startswith("proved") for s in steps)
result = {"verified": "✅ verified", "partial": "⚠️ partial",
"verified_direct": "✅ verified (proved whole; human steps not checked)",
"unproved": "❌ statement formalised, no proof found",
"skeleton_failed": "❌ not formalised", "error": "❌ error"}.get(r["status"], r["status"])
cell = lambda t: str(t or "").replace("|", "/").replace("\n", " ")
rows.append(f"| {r['n']} | {cell(r['theorem'])[:120]} | {result} | "
f"{f'{done}/{len(steps)}' if steps else '–'} | {cell(r.get('statement_back_translation'))[:200]} |")
return "\n".join(rows)
def write_files(reports, outdir):
paths = []
for r in reports:
stem = f"problem_{r['n']:02d}"
if r.get("lean_file"):
p = os.path.join(outdir, stem + ".lean")
with open(p, "w") as f:
f.write(r["lean_file"])
paths.append(p)
p = os.path.join(outdir, stem + "_report.json")
with open(p, "w") as f:
json.dump(r, f, indent=2, ensure_ascii=False)
paths.append(p)
return paths or None
def emit(job):
return "\n".join(job["log"][-300:]), summary_md(job["reports"]), write_files(job["reports"], job["outdir"])
# ----------------------------------------------------------------------------- jobs
class CountingModels:
"""Same interface as `models`, but counts GPU calls so a request can stop after one."""
def __init__(self, job):
self.job, self.VL_ID, self.PROVER_ID = job, models.VL_ID, models.PROVER_ID
def _call(self, fn, *args, **kwargs):
self.job["gpu_calls"] += 1
return fn(*args, **kwargs)
def chat(self, *a, **k):
return self._call(models.chat, *a, **k)
def prove(self, *a, **k):
return self._call(models.prove, *a, **k)
def read_pages(self, *a, **k):
return self._call(models.read_pages, *a, **k)
def problems_from_pdf(m, pdf_path):
if not pdf_path:
yield "log", "Upload a PDF first."
return
pages = core.render_pdf(pdf_path)
yield "log", f"Rendered {len(pages)} page(s); reading them with {m.VL_ID}…"
text = m.read_pages(pages, core.READ_SYSTEM,
f"Transcribe all problems from these {len(pages)} page(s).",
think_tokens=2000, answer_tokens=3000)
probs = core.parse_problems(text)
if not probs:
yield "log", "No problems found. What the model read:\n" + text[:1500]
return
yield "log", f"Found {len(probs)} problem(s)."
yield "problems", probs
def problems_from_text(m, theorem, proof):
if not (theorem or "").strip():
yield "log", "Enter a theorem first."
return
proof = (proof or "").strip() or "(No proof given. Construct a proof.)"
yield "problems", [(1, theorem.strip(), proof)]
def work(job, source, args):
"""The whole job as a generator; it yields whenever there is progress to show."""
log, m = job["log"], job["models"]
while not leanenv.ready():
s = leanenv.status()
if s["status"] == "failed":
raise RuntimeError("Lean setup failed:\n" + (s["error"] or "")[-1200:])
msg = f"Waiting for Lean + Mathlib to finish installing ({s['status']}, {s['minutes']} min so far)…"
if log and log[-1].startswith("Waiting for Lean"):
log[-1] = msg
else:
log.append(msg)
yield
time.sleep(5)
problems = None
for kind, val in source(m, *args):
if kind == "log":
log.append(val)
yield
else:
problems = val
if not problems:
return
for n, thm, prf in problems[:MAX_PROBLEMS]:
log.append(f"=== Problem {n}: {thm[:100]}")
yield
report = None
try:
for kind, val in core.check_problem(m, thm, prf):
if kind == "log":
log.append(val)
yield
else:
report = val
except Exception as e:
if "ZeroGPU" in type(e).__name__ or "quota" in str(e).lower():
raise # GPU unavailable: stop the job, don't burn the rest
report = {"theorem": thm, "proof": prf, "status": "error", "error": f"{type(e).__name__}: {e}"}
log.append(f" ERROR: {type(e).__name__}: {e}")
report["n"] = n
job["reports"].append(report)
log.append(f" RESULT: {report['status']}" + (f" in {report['seconds']} s" if "seconds" in report else ""))
yield
if len(problems) > MAX_PROBLEMS:
log.append(f"Only the first {MAX_PROBLEMS} problems were checked.")
def new_job(request, source, args):
for sid in [s for s, j in JOBS.items() if time.time() - j["created"] > 6 * 3600]:
JOBS.pop(sid, None)
job = {"log": ["Starting…"], "reports": [], "gpu_calls": 0, "done": False, "created": time.time(),
"outdir": tempfile.mkdtemp(prefix="leancheck_"), "lock": threading.Lock()}
job["models"] = CountingModels(job)
job["gen"] = work(job, source, args)
JOBS[request.session_hash] = job
return emit(job) + (gr.Timer(active=True),)
def start_pdf(pdf_path, request: gr.Request):
return new_job(request, problems_from_pdf, (pdf_path,))
def start_text(theorem, proof, request: gr.Request):
return new_job(request, problems_from_text, (theorem, proof))
def tick(request: gr.Request):
"""Advance this session's job by at most one GPU call (fresh ZeroGPU token per request)."""
job = JOBS.get(request.session_hash)
if job is None or job["done"]:
return gr.skip(), gr.skip(), gr.skip(), gr.Timer(active=False)
if not job["lock"].acquire(blocking=False):
return gr.skip(), gr.skip(), gr.skip(), gr.skip()
try:
calls0, t0 = job["gpu_calls"], time.time()
while True:
try:
next(job["gen"])
except StopIteration:
job["log"].append("DONE.")
job["done"] = True
break
except Exception as e:
job["log"].append(f"STOPPED: {type(e).__name__}: {e}")
job["done"] = True
break
if job["gpu_calls"] > calls0 or time.time() - t0 > TICK_SECONDS:
break
finally:
job["lock"].release()
return emit(job) + (gr.Timer(active=not job["done"]),)
# ----------------------------------------------------------------------------- UI
with gr.Blocks(title="Lean Proof Checker") as demo:
gr.Markdown(
"# Lean Proof Checker\n"
"Upload a PDF of theorems with proofs, or paste one. Each proof is turned into a Lean 4 "
"skeleton that follows the human steps; each step is then proved by automatic tactics or by "
f"the open prover model `{models.PROVER_ID}`, and Lean 4 + Mathlib checks everything. "
f"Reading the PDF, writing the skeleton and translating statements back use `{models.VL_ID}`.\n\n"
"**Read the result with care:** *verified* means Lean accepted the proof of the Lean statement. "
"Compare the plain-English reading of that statement with your theorem.\n\n"
"GPU time comes from your daily ZeroGPU quota (sign in to use your own). Keep this tab open "
"while a job runs: the page drives it.")
status = gr.Markdown(lean_status_md())
with gr.Tab("PDF"):
pdf = gr.File(label="PDF (up to 6 pages)", file_types=[".pdf"], type="filepath")
go_pdf = gr.Button("Check the PDF", variant="primary")
with gr.Tab("Paste a theorem"):
thm = gr.Textbox(label="Theorem", lines=3, placeholder="For every integer n, 6 divides n^3 - n.")
prf = gr.Textbox(label="Proof", lines=8, placeholder="n^3 - n = (n-1)n(n+1), a product of three consecutive integers…")
go_txt = gr.Button("Check", variant="primary")
log = gr.Textbox(label="Progress", lines=16, max_lines=30, autoscroll=True)
table = gr.Markdown()
files = gr.File(label="Lean files and reports", file_count="multiple")
runner = gr.Timer(1.0, active=False)
outs = [log, table, files, runner]
go_pdf.click(start_pdf, inputs=pdf, outputs=outs, concurrency_id="start")
go_txt.click(start_text, inputs=[thm, prf], outputs=outs, concurrency_id="start")
runner.tick(tick, outputs=outs, trigger_mode="once", concurrency_id="work",
concurrency_limit=1, show_progress="hidden")
gr.Timer(15).tick(lean_status_md, outputs=status, show_progress="hidden")
demo.queue(default_concurrency_limit=1)
if __name__ == "__main__":
demo.launch()
|