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.
Files changed (6)
8 unmodified lines91011121314356 unmodified lines3713723733743753763773783793803813828 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))from langgraph_agent import LangGraphAgent# ---------------------------------------------------------------------------356 unmodified linestmp.write(lean_code)tmp.close()log_buf = io.StringIO()with _capture_stdout(log_buf):agent = LangGraphAgent(model_name=model_name,max_retries=int(max_retries),api_key=api_key,)result = agent.solve_file_detailed(tmp_path)8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344356 unmodified lines4014024034044054064074084094104114124134144154164174184194204214224234248 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))from langgraph_agent import LangGraphAgentfrom lean_verifier import LeanEnvironmentfrom retriever import MathLibRetriever# ---------------------------------------------------------------------------# Cached heavyweight components.## `LeanEnvironment` spawns a Lean REPL and loads Mathlib (5-15s cold).# `MathLibRetriever` loads the ~200MB FAISS index + cross-encoder model.# Without caching, every solve_proof call paid this cost. We build them once# on first use and share across requests; LeanEnvironment.verify_proof has# its own lock so concurrent solves serialize at the Lean step but parallel# everywhere else.# ---------------------------------------------------------------------------_COMPONENT_LOCK = threading.Lock()_LEAN_ENV: LeanEnvironment | None = None_RETRIEVER: MathLibRetriever | None = Nonedef _get_components():global _LEAN_ENV, _RETRIEVERwith _COMPONENT_LOCK:if _LEAN_ENV is None:print("Initializing Lean environment (one-time)…")_LEAN_ENV = LeanEnvironment(use_mathlib=True)if _RETRIEVER is None:print("Loading FAISS retriever (one-time)…")_RETRIEVER = MathLibRetriever()return _LEAN_ENV, _RETRIEVER# ---------------------------------------------------------------------------356 unmodified linestmp.write(lean_code)tmp.close()# Two-stage retry: for Groq, try the cheap 8b on attempt 0 and# escalate to the user's chosen model on retry. Skip for Claude# (no clear cheap counterpart) and for users who explicitly picked 8b.fast_model = Noneif not claude and model_name != "llama-3.1-8b-instant":fast_model = "llama-3.1-8b-instant"lean_env, retriever = _get_components()log_buf = io.StringIO()with _capture_stdout(log_buf):agent = LangGraphAgent(model_name=model_name,max_retries=int(max_retries),api_key=api_key,fast_model=fast_model,lean_env=lean_env,retriever=retriever,)result = agent.solve_file_detailed(tmp_path)
129 unmodified lines13013113213313413513613713848 unmodified lines18718818919019119219319419519619719814 unmodified lines213214215216217218219220221222223129 unmodified linesreturn retrieve_nodedef make_generate_node(chain: RAGProofChain):def generate_node(state: ProofState) -> ProofState:print("Generating proof with LLM…")raw = chain.generate(lean_code=state["lean_code"],goals=state["goals"],48 unmodified lines# Graph assembly# ---------------------------------------------------------------------------def build_graph(lean_env: LeanEnvironment, retriever: MathLibRetriever, chain: RAGProofChain):g = StateGraph(ProofState)g.add_node("verify", make_verify_node(lean_env))g.add_node("retrieve", make_retrieve_node(retriever))g.add_node("generate", make_generate_node(chain))g.set_entry_point("verify")g.add_conditional_edges("verify", should_continue, {"retrieve": "retrieve", END: END})14 unmodified linesmax_retries: int = 5,index_dir: str | None = None,api_key: str | None = None,):self._lean_env = LeanEnvironment(use_mathlib=True)self._retriever = MathLibRetriever(index_dir=index_dir)self._chain = RAGProofChain(model_name=model_name, api_key=api_key)self._graph = build_graph(self._lean_env, self._retriever, self._chain)self._max_retries = max_retriesdef solve_file(self, file_path: str) -> bool:129 unmodified lines13013113213313413513613713813914014114214314414514614714848 unmodified lines19719819920020120220320420520620720820921021121221314 unmodified lines228229230231232233234235236237238239240241242243244245246247248249129 unmodified linesreturn retrieve_nodedef make_generate_node(strong_chain: RAGProofChain, fast_chain: RAGProofChain | None = None):"""If `fast_chain` is given, attempt 0 uses it (cheaper / faster model);subsequent attempts escalate to `strong_chain`. This catches the easyproofs in a few hundred ms before paying for the bigger model."""def generate_node(state: ProofState) -> ProofState:if fast_chain is not None and state["attempt"] == 0:chain = fast_chainprint("Generating proof with LLM (fast model, first attempt)…")else:chain = strong_chainprint("Generating proof with LLM…")raw = chain.generate(lean_code=state["lean_code"],goals=state["goals"],48 unmodified lines# Graph assembly# ---------------------------------------------------------------------------def build_graph(lean_env: LeanEnvironment,retriever: MathLibRetriever,chain: RAGProofChain,fast_chain: RAGProofChain | None = None,):g = StateGraph(ProofState)g.add_node("verify", make_verify_node(lean_env))g.add_node("retrieve", make_retrieve_node(retriever))g.add_node("generate", make_generate_node(chain, fast_chain))g.set_entry_point("verify")g.add_conditional_edges("verify", should_continue, {"retrieve": "retrieve", END: END})14 unmodified linesmax_retries: int = 5,index_dir: str | None = None,api_key: str | None = None,fast_model: str | None = None,lean_env: LeanEnvironment | None = None,retriever: MathLibRetriever | None = None,):# Reuse pre-built heavyweight components when given. This lets a hosting# process (e.g. the Gradio app) cache the Lean REPL and FAISS index# once at startup instead of rebuilding them on every solve_proof call.self._lean_env = lean_env if lean_env is not None else LeanEnvironment(use_mathlib=True)self._retriever = retriever if retriever is not None else MathLibRetriever(index_dir=index_dir)self._chain = RAGProofChain(model_name=model_name, api_key=api_key)self._fast_chain = (RAGProofChain(model_name=fast_model, api_key=api_key)if fast_model and fast_model != model_nameelse None)self._graph = build_graph(self._lean_env, self._retriever, self._chain, self._fast_chain)self._max_retries = max_retriesdef solve_file(self, file_path: str) -> bool:
1232 unmodified lines6789101119 unmodified lines31323334353617 unmodified lines5455565758596061from typing import Dict, Any, Listfrom lean_interact import LeanREPLConfig, LeanServer, Command, TempRequireProject, LeanRequire2 unmodified linesclass LeanEnvironment:"""Manages the Lean REPL environment for verifying Lean 4 proofs."""def __init__(self, use_mathlib: bool = True, lean_version: str = "v4.8.0"):19 unmodified linesself.config = LeanREPLConfig(lean_version=self.lean_version)self.server = LeanServer(self.config)def verify_proof(self, lean_code: str) -> Dict[str, Any]:"""17 unmodified lines# Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a# failure result so the agent's retry loop continues instead of dying.try:response = self.server.run(Command(cmd=lean_code))except Exception as exc:return {"status": "failure",12342 unmodified lines7891011121314151619 unmodified lines3637383940414217 unmodified lines60616263646566676869import threadingfrom typing import Dict, Any, Listfrom lean_interact import LeanREPLConfig, LeanServer, Command, TempRequireProject, LeanRequire2 unmodified linesclass LeanEnvironment:"""Manages the Lean REPL environment for verifying Lean 4 proofs.Safe to share across threads: `verify_proof` serializes concurrent callsbehind a lock, because the underlying LeanServer is a single-processstdin/stdout pipe and would otherwise interleave commands."""def __init__(self, use_mathlib: bool = True, lean_version: str = "v4.8.0"):19 unmodified linesself.config = LeanREPLConfig(lean_version=self.lean_version)self.server = LeanServer(self.config)self._lock = threading.Lock()def verify_proof(self, lean_code: str) -> Dict[str, Any]:"""17 unmodified lines# Guard: LeanServer can raise on disconnect / crash / OOM. Surface as a# failure result so the agent's retry loop continues instead of dying.# The lock serializes concurrent requests since LeanServer is single-process.try:with self._lock:response = self.server.run(Command(cmd=lean_code))except Exception as exc:return {"status": "failure",
102 unmodified lines103104105106107108109110111112113102 unmodified lines- everything else → Groq (api_key optional; falls back to GROQ_API_KEY env)"""if model_name.startswith("claude-"):kwargs = {"model": model_name, "max_tokens": 1024}if api_key:kwargs["anthropic_api_key"] = api_keyreturn ChatAnthropic(**kwargs)kwargs = {"model": model_name, "max_tokens": 1024}if api_key:kwargs["groq_api_key"] = api_keyreturn ChatGroq(**kwargs)102 unmodified lines103104105106107108109110111112113102 unmodified lines- everything else → Groq (api_key optional; falls back to GROQ_API_KEY env)"""if model_name.startswith("claude-"):kwargs = {"model": model_name, "max_tokens": 512}if api_key:kwargs["anthropic_api_key"] = api_keyreturn ChatAnthropic(**kwargs)kwargs = {"model": model_name, "max_tokens": 512}if api_key:kwargs["groq_api_key"] = api_keyreturn ChatGroq(**kwargs)
123 unmodified lines124125126127128129130123 unmodified lines)self._ntf_patch.start()def tearDown(self):self._ntf_patch.stop()# Best-effort: clean up anything the test leaked so /tmp doesn't fill.for path in self._captured_paths:123 unmodified lines124125126127128129130131132133134135136137138123 unmodified lines)self._ntf_patch.start()# Don't touch the real Lean REPL / FAISS retriever just because we're# exercising app.solve_proof in tests — return harmless mocks.self._components_patch = mock.patch.object(app, "_get_components", return_value=(mock.MagicMock(), mock.MagicMock()))self._components_patch.start()def tearDown(self):self._components_patch.stop()self._ntf_patch.stop()# Best-effort: clean up anything the test leaked so /tmp doesn't fill.for path in self._captured_paths:
99 unmodified lines10010110210310410599 unmodified linesself._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)self._lg_patcher.start()self.addCleanup(self._lg_patcher.stop)# Snapshot pre-existing tmp .lean files so we ignore unrelated ones.self._tmp_before = _scan_tmp_lean()99 unmodified lines10010110210310410510610710810911011199 unmodified linesself._lg_patcher = mock.patch.object(app, "LangGraphAgent", _DummyAgent)self._lg_patcher.start()self.addCleanup(self._lg_patcher.stop)# Don't construct a real LeanEnvironment / FAISS retriever in tests.self._components_patcher = mock.patch.object(app, "_get_components", return_value=(mock.MagicMock(), mock.MagicMock()))self._components_patcher.start()self.addCleanup(self._components_patcher.stop)# Snapshot pre-existing tmp .lean files so we ignore unrelated ones.self._tmp_before = _scan_tmp_lean()