Spaces:
Sleeping
Speed up proof generation: cache components, smaller max_tokens, two-stage retry
Browse filesThree targeted speedups for the live Space:
1. Cache LeanEnvironment + MathLibRetriever module-level in app.py. Each
solve_proof call used to spawn a fresh Lean REPL (5-15s cold) and
reload the 200MB FAISS index. Now both are built once on first use
and shared across requests. LeanEnvironment grew a threading.Lock
so concurrent verifies serialize at the Lean step but parallelize
everywhere else.
2. Lower LLM max_tokens from 1024 -> 512. Most Lean proofs are 1-5
lines; the cap rarely bites and the smaller window is ~20-30% faster.
3. Two-stage retry. On Groq, attempt 0 now uses llama-3.1-8b-instant
(~3-5x faster than 70b); subsequent attempts escalate to whichever
model the user picked in the dropdown. Skipped when the user
explicitly picks 8b or any Claude model.
LangGraphAgent gained optional `fast_model`, `lean_env`, and `retriever`
parameters so callers can opt into the new behavior; defaults preserve
the old per-call construction for scripts/run_agent.py and benchmarks.
Tests gain a `_get_components` mock so they don't pay the real Lean+FAISS
init cost; test wall time dropped from ~20s to ~0.4s.
- app.py +42 -0
- src/langgraph_agent.py +33 -7
- src/lean_verifier.py +9 -1
- src/rag_chain.py +2 -2
- tests/test_app_fuzz.py +8 -0
- tests/test_concurrent_solve.py +6 -0
|
@@ -9,6 +9,36 @@ import gradio as gr
|
|
| 9 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 10 |
|
| 11 |
from langgraph_agent import LangGraphAgent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
# ---------------------------------------------------------------------------
|
|
@@ -371,12 +401,24 @@ def solve_proof(lean_code: str, model_name: str, max_retries: int, anthropic_api
|
|
| 371 |
tmp.write(lean_code)
|
| 372 |
tmp.close()
|
| 373 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
log_buf = io.StringIO()
|
| 375 |
with _capture_stdout(log_buf):
|
| 376 |
agent = LangGraphAgent(
|
| 377 |
model_name=model_name,
|
| 378 |
max_retries=int(max_retries),
|
| 379 |
api_key=api_key,
|
|
|
|
|
|
|
|
|
|
| 380 |
)
|
| 381 |
result = agent.solve_file_detailed(tmp_path)
|
| 382 |
|
|
|
|
| 9 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 10 |
|
| 11 |
from langgraph_agent import LangGraphAgent
|
| 12 |
+
from lean_verifier import LeanEnvironment
|
| 13 |
+
from retriever import MathLibRetriever
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
# Cached heavyweight components.
|
| 18 |
+
#
|
| 19 |
+
# `LeanEnvironment` spawns a Lean REPL and loads Mathlib (5-15s cold).
|
| 20 |
+
# `MathLibRetriever` loads the ~200MB FAISS index + cross-encoder model.
|
| 21 |
+
# Without caching, every solve_proof call paid this cost. We build them once
|
| 22 |
+
# on first use and share across requests; LeanEnvironment.verify_proof has
|
| 23 |
+
# its own lock so concurrent solves serialize at the Lean step but parallel
|
| 24 |
+
# everywhere else.
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
_COMPONENT_LOCK = threading.Lock()
|
| 28 |
+
_LEAN_ENV: LeanEnvironment | None = None
|
| 29 |
+
_RETRIEVER: MathLibRetriever | None = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_components():
|
| 33 |
+
global _LEAN_ENV, _RETRIEVER
|
| 34 |
+
with _COMPONENT_LOCK:
|
| 35 |
+
if _LEAN_ENV is None:
|
| 36 |
+
print("Initializing Lean environment (one-time)…")
|
| 37 |
+
_LEAN_ENV = LeanEnvironment(use_mathlib=True)
|
| 38 |
+
if _RETRIEVER is None:
|
| 39 |
+
print("Loading FAISS retriever (one-time)…")
|
| 40 |
+
_RETRIEVER = MathLibRetriever()
|
| 41 |
+
return _LEAN_ENV, _RETRIEVER
|
| 42 |
|
| 43 |
|
| 44 |
# ---------------------------------------------------------------------------
|
|
|
|
| 401 |
tmp.write(lean_code)
|
| 402 |
tmp.close()
|
| 403 |
|
| 404 |
+
# Two-stage retry: for Groq, try the cheap 8b on attempt 0 and
|
| 405 |
+
# escalate to the user's chosen model on retry. Skip for Claude
|
| 406 |
+
# (no clear cheap counterpart) and for users who explicitly picked 8b.
|
| 407 |
+
fast_model = None
|
| 408 |
+
if not claude and model_name != "llama-3.1-8b-instant":
|
| 409 |
+
fast_model = "llama-3.1-8b-instant"
|
| 410 |
+
|
| 411 |
+
lean_env, retriever = _get_components()
|
| 412 |
+
|
| 413 |
log_buf = io.StringIO()
|
| 414 |
with _capture_stdout(log_buf):
|
| 415 |
agent = LangGraphAgent(
|
| 416 |
model_name=model_name,
|
| 417 |
max_retries=int(max_retries),
|
| 418 |
api_key=api_key,
|
| 419 |
+
fast_model=fast_model,
|
| 420 |
+
lean_env=lean_env,
|
| 421 |
+
retriever=retriever,
|
| 422 |
)
|
| 423 |
result = agent.solve_file_detailed(tmp_path)
|
| 424 |
|
|
@@ -130,9 +130,19 @@ def make_retrieve_node(retriever: MathLibRetriever):
|
|
| 130 |
return retrieve_node
|
| 131 |
|
| 132 |
|
| 133 |
-
def make_generate_node(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
def generate_node(state: ProofState) -> ProofState:
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
raw = chain.generate(
|
| 137 |
lean_code=state["lean_code"],
|
| 138 |
goals=state["goals"],
|
|
@@ -187,12 +197,17 @@ def should_continue(state: ProofState) -> str:
|
|
| 187 |
# Graph assembly
|
| 188 |
# ---------------------------------------------------------------------------
|
| 189 |
|
| 190 |
-
def build_graph(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
g = StateGraph(ProofState)
|
| 192 |
|
| 193 |
g.add_node("verify", make_verify_node(lean_env))
|
| 194 |
g.add_node("retrieve", make_retrieve_node(retriever))
|
| 195 |
-
g.add_node("generate", make_generate_node(chain))
|
| 196 |
|
| 197 |
g.set_entry_point("verify")
|
| 198 |
g.add_conditional_edges("verify", should_continue, {"retrieve": "retrieve", END: END})
|
|
@@ -213,11 +228,22 @@ class LangGraphAgent:
|
|
| 213 |
max_retries: int = 5,
|
| 214 |
index_dir: str | None = None,
|
| 215 |
api_key: str | None = None,
|
|
|
|
|
|
|
|
|
|
| 216 |
):
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
| 219 |
self._chain = RAGProofChain(model_name=model_name, api_key=api_key)
|
| 220 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
self._max_retries = max_retries
|
| 222 |
|
| 223 |
def solve_file(self, file_path: str) -> bool:
|
|
|
|
| 130 |
return retrieve_node
|
| 131 |
|
| 132 |
|
| 133 |
+
def make_generate_node(strong_chain: RAGProofChain, fast_chain: RAGProofChain | None = None):
|
| 134 |
+
"""
|
| 135 |
+
If `fast_chain` is given, attempt 0 uses it (cheaper / faster model);
|
| 136 |
+
subsequent attempts escalate to `strong_chain`. This catches the easy
|
| 137 |
+
proofs in a few hundred ms before paying for the bigger model.
|
| 138 |
+
"""
|
| 139 |
def generate_node(state: ProofState) -> ProofState:
|
| 140 |
+
if fast_chain is not None and state["attempt"] == 0:
|
| 141 |
+
chain = fast_chain
|
| 142 |
+
print("Generating proof with LLM (fast model, first attempt)…")
|
| 143 |
+
else:
|
| 144 |
+
chain = strong_chain
|
| 145 |
+
print("Generating proof with LLM…")
|
| 146 |
raw = chain.generate(
|
| 147 |
lean_code=state["lean_code"],
|
| 148 |
goals=state["goals"],
|
|
|
|
| 197 |
# Graph assembly
|
| 198 |
# ---------------------------------------------------------------------------
|
| 199 |
|
| 200 |
+
def build_graph(
|
| 201 |
+
lean_env: LeanEnvironment,
|
| 202 |
+
retriever: MathLibRetriever,
|
| 203 |
+
chain: RAGProofChain,
|
| 204 |
+
fast_chain: RAGProofChain | None = None,
|
| 205 |
+
):
|
| 206 |
g = StateGraph(ProofState)
|
| 207 |
|
| 208 |
g.add_node("verify", make_verify_node(lean_env))
|
| 209 |
g.add_node("retrieve", make_retrieve_node(retriever))
|
| 210 |
+
g.add_node("generate", make_generate_node(chain, fast_chain))
|
| 211 |
|
| 212 |
g.set_entry_point("verify")
|
| 213 |
g.add_conditional_edges("verify", should_continue, {"retrieve": "retrieve", END: END})
|
|
|
|
| 228 |
max_retries: int = 5,
|
| 229 |
index_dir: str | None = None,
|
| 230 |
api_key: str | None = None,
|
| 231 |
+
fast_model: str | None = None,
|
| 232 |
+
lean_env: LeanEnvironment | None = None,
|
| 233 |
+
retriever: MathLibRetriever | None = None,
|
| 234 |
):
|
| 235 |
+
# Reuse pre-built heavyweight components when given. This lets a hosting
|
| 236 |
+
# process (e.g. the Gradio app) cache the Lean REPL and FAISS index
|
| 237 |
+
# once at startup instead of rebuilding them on every solve_proof call.
|
| 238 |
+
self._lean_env = lean_env if lean_env is not None else LeanEnvironment(use_mathlib=True)
|
| 239 |
+
self._retriever = retriever if retriever is not None else MathLibRetriever(index_dir=index_dir)
|
| 240 |
self._chain = RAGProofChain(model_name=model_name, api_key=api_key)
|
| 241 |
+
self._fast_chain = (
|
| 242 |
+
RAGProofChain(model_name=fast_model, api_key=api_key)
|
| 243 |
+
if fast_model and fast_model != model_name
|
| 244 |
+
else None
|
| 245 |
+
)
|
| 246 |
+
self._graph = build_graph(self._lean_env, self._retriever, self._chain, self._fast_chain)
|
| 247 |
self._max_retries = max_retries
|
| 248 |
|
| 249 |
def solve_file(self, file_path: str) -> bool:
|
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
from typing import Dict, Any, List
|
| 2 |
|
| 3 |
from lean_interact import LeanREPLConfig, LeanServer, Command, TempRequireProject, LeanRequire
|
|
@@ -6,6 +7,10 @@ from lean_interact import LeanREPLConfig, LeanServer, Command, TempRequireProjec
|
|
| 6 |
class LeanEnvironment:
|
| 7 |
"""
|
| 8 |
Manages the Lean REPL environment for verifying Lean 4 proofs.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
def __init__(self, use_mathlib: bool = True, lean_version: str = "v4.8.0"):
|
|
@@ -31,6 +36,7 @@ class LeanEnvironment:
|
|
| 31 |
self.config = LeanREPLConfig(lean_version=self.lean_version)
|
| 32 |
|
| 33 |
self.server = LeanServer(self.config)
|
|
|
|
| 34 |
|
| 35 |
def verify_proof(self, lean_code: str) -> Dict[str, Any]:
|
| 36 |
"""
|
|
@@ -54,8 +60,10 @@ class LeanEnvironment:
|
|
| 54 |
|
| 55 |
# Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a
|
| 56 |
# failure result so the agent's retry loop continues instead of dying.
|
|
|
|
| 57 |
try:
|
| 58 |
-
|
|
|
|
| 59 |
except Exception as exc:
|
| 60 |
return {
|
| 61 |
"status": "failure",
|
|
|
|
| 1 |
+
import threading
|
| 2 |
from typing import Dict, Any, List
|
| 3 |
|
| 4 |
from lean_interact import LeanREPLConfig, LeanServer, Command, TempRequireProject, LeanRequire
|
|
|
|
| 7 |
class LeanEnvironment:
|
| 8 |
"""
|
| 9 |
Manages the Lean REPL environment for verifying Lean 4 proofs.
|
| 10 |
+
|
| 11 |
+
Safe to share across threads: `verify_proof` serializes concurrent calls
|
| 12 |
+
behind a lock, because the underlying LeanServer is a single-process
|
| 13 |
+
stdin/stdout pipe and would otherwise interleave commands.
|
| 14 |
"""
|
| 15 |
|
| 16 |
def __init__(self, use_mathlib: bool = True, lean_version: str = "v4.8.0"):
|
|
|
|
| 36 |
self.config = LeanREPLConfig(lean_version=self.lean_version)
|
| 37 |
|
| 38 |
self.server = LeanServer(self.config)
|
| 39 |
+
self._lock = threading.Lock()
|
| 40 |
|
| 41 |
def verify_proof(self, lean_code: str) -> Dict[str, Any]:
|
| 42 |
"""
|
|
|
|
| 60 |
|
| 61 |
# Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a
|
| 62 |
# failure result so the agent's retry loop continues instead of dying.
|
| 63 |
+
# The lock serializes concurrent requests since LeanServer is single-process.
|
| 64 |
try:
|
| 65 |
+
with self._lock:
|
| 66 |
+
response = self.server.run(Command(cmd=lean_code))
|
| 67 |
except Exception as exc:
|
| 68 |
return {
|
| 69 |
"status": "failure",
|
|
@@ -103,11 +103,11 @@ def _make_llm(model_name: str, api_key: Optional[str]):
|
|
| 103 |
- everything else → Groq (api_key optional; falls back to GROQ_API_KEY env)
|
| 104 |
"""
|
| 105 |
if model_name.startswith("claude-"):
|
| 106 |
-
kwargs = {"model": model_name, "max_tokens":
|
| 107 |
if api_key:
|
| 108 |
kwargs["anthropic_api_key"] = api_key
|
| 109 |
return ChatAnthropic(**kwargs)
|
| 110 |
-
kwargs = {"model": model_name, "max_tokens":
|
| 111 |
if api_key:
|
| 112 |
kwargs["groq_api_key"] = api_key
|
| 113 |
return ChatGroq(**kwargs)
|
|
|
|
| 103 |
- everything else → Groq (api_key optional; falls back to GROQ_API_KEY env)
|
| 104 |
"""
|
| 105 |
if model_name.startswith("claude-"):
|
| 106 |
+
kwargs = {"model": model_name, "max_tokens": 512}
|
| 107 |
if api_key:
|
| 108 |
kwargs["anthropic_api_key"] = api_key
|
| 109 |
return ChatAnthropic(**kwargs)
|
| 110 |
+
kwargs = {"model": model_name, "max_tokens": 512}
|
| 111 |
if api_key:
|
| 112 |
kwargs["groq_api_key"] = api_key
|
| 113 |
return ChatGroq(**kwargs)
|
|
@@ -124,7 +124,15 @@ class SolveProofFuzzTests(unittest.TestCase):
|
|
| 124 |
)
|
| 125 |
self._ntf_patch.start()
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
def tearDown(self):
|
|
|
|
| 128 |
self._ntf_patch.stop()
|
| 129 |
# Best-effort: clean up anything the test leaked so /tmp doesn't fill.
|
| 130 |
for path in self._captured_paths:
|
|
|
|
| 124 |
)
|
| 125 |
self._ntf_patch.start()
|
| 126 |
|
| 127 |
+
# Don't touch the real Lean REPL / FAISS retriever just because we're
|
| 128 |
+
# exercising app.solve_proof in tests — return harmless mocks.
|
| 129 |
+
self._components_patch = mock.patch.object(
|
| 130 |
+
app, "_get_components", return_value=(mock.MagicMock(), mock.MagicMock())
|
| 131 |
+
)
|
| 132 |
+
self._components_patch.start()
|
| 133 |
+
|
| 134 |
def tearDown(self):
|
| 135 |
+
self._components_patch.stop()
|
| 136 |
self._ntf_patch.stop()
|
| 137 |
# Best-effort: clean up anything the test leaked so /tmp doesn't fill.
|
| 138 |
for path in self._captured_paths:
|
|
@@ -100,6 +100,12 @@ class ConcurrentSolveTests(unittest.TestCase):
|
|
| 100 |
self._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)
|
| 101 |
self._lg_patcher.start()
|
| 102 |
self.addCleanup(self._lg_patcher.stop)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
# Snapshot pre-existing tmp .lean files so we ignore unrelated ones.
|
| 104 |
self._tmp_before = _scan_tmp_lean()
|
| 105 |
|
|
|
|
| 100 |
self._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)
|
| 101 |
self._lg_patcher.start()
|
| 102 |
self.addCleanup(self._lg_patcher.stop)
|
| 103 |
+
# Don't construct a real LeanEnvironment / FAISS retriever in tests.
|
| 104 |
+
self._components_patcher = mock.patch.object(
|
| 105 |
+
app, "_get_components", return_value=(mock.MagicMock(), mock.MagicMock())
|
| 106 |
+
)
|
| 107 |
+
self._components_patcher.start()
|
| 108 |
+
self.addCleanup(self._components_patcher.stop)
|
| 109 |
# Snapshot pre-existing tmp .lean files so we ignore unrelated ones.
|
| 110 |
self._tmp_before = _scan_tmp_lean()
|
| 111 |
|