Frontier: learning-guided search and symbolic reasoning
Current research combines symbolic engines’ guarantees with learned neural intuition. Study learned search heuristics (DeepCubeA), learning inside solvers (NeuroSAT and algorithm selection), evidence on language models as planners and generate-and-verify, program search with an evaluator (FunSearch), and neural-guided theorem proving (AlphaGeometry, AlphaProof, LeanDojo), with criteria for rigorous reading and reproduction.
After this lesson you can
- Classify neurosymbolic systems by their integration pattern.
- Train a learned heuristic and use it in batched weighted A*, measuring suboptimality.
- Build a generate-and-verify loop with a local language model and symbolic validator.
- Critically read papers, identifying baselines, metrics, contamination and ablations.
- Formulate open research questions at the intersection of search, logic and learning.
Before you start
- 10A* searchWeighted A*Pattern databaseConflict analysis and 1-UIP learningVSIDS heuristicPDDL and groundingFF heuristic and relaxed plansFirst-order resolutionPUCT selection with priorsCounterexample-guided inductive synthesis
- 00Canonical training and evaluation loop
- 15Micro framework to PyTorch correspondence
- 22Value iterationFitted Q iterationValue function approximation
- 25Message passing neural network framework
- 20Text-to-text task format and prompting
- 21Decoding loop and logits processors
- 11Random forest
Motivation: guarantees without direction and intuition without certainty
This module has built symbolic engines: A* with admissible heuristics, CDCL solvers learning clauses from conflicts, planners deriving their heuristic from a PDDL model, and resolution provers. They share a strength and a weakness. Their results are correct by construction (a plan accepted by a validator, an assignment satisfying a formula, or a proof checked step by step), and complete engines find a solution when one exists. But at each decision they use fixed, hand-designed rules, which are blind in enormous spaces. IDA* with Manhattan distance generates about 401 million nodes on average on random 15-puzzle instances; with a 576 MB additive 7-8 pattern database it generates about 37,000 (the Felner, Korf and Hanan figures from the search-at-scale lesson). The entire gain came from a better heuristic designed by a person who understood the puzzle.
Neural networks have the opposite profile. In a second, a language model proposes a block-stacking plan, an auxiliary construction for a geometry problem or the next tactic in a proof, often getting right what a human would call intuition. But it guarantees nothing: the plan may violate a precondition at step 3 and the model will present it as confidently as a correct one.
Current research at this frontier starts with a simple observation: the two weaknesses complement one another. The symbolic engine lacks knowledge of where to search; the network lacks knowledge of whether it is right. This lesson studies systems combining them and, especially, how to tell whether a particular combination really works:
- Learned heuristics. DeepCubeA learns the cost to go for Rubik’s cube and the 15-puzzle without domain knowledge and uses it inside weighted A*. You will reproduce it at small scale and measure its departure from an admissible heuristic.
- Learning inside solvers. NeuroSAT learns to search for assignments with one bit of supervision per formula; portfolios such as SATzilla learn which solver to use. You will train both.
- Language models as planners. PlanBench evidence says they plan poorly alone; LLM-Modulo makes them generate candidates checked by a symbolic validator. You will build this loop with a local model.
- Program search and theorem proving. FunSearch, GPT-f, LeanDojo, AlphaGeometry and AlphaProof use a neural generator inside a loop judged by an evaluator or formal prover.
The final part is methodological. In this field it is easy to publish an improvement that disappears against a well-configured classical baseline, after domain names are obfuscated, or when the component supposedly responsible for it is removed. You will learn to look for these gaps.
Three waves and a thesis
In his AAAI 2020 Engelmore lecture (published in AI Magazine in 2022), Henry Kautz describes AI history as alternating summers and winters, and argues that the current third summer will lead to neurosymbolic systems. D’Avila Garcez and Lamb (2023) call the same idea the “third wave”: after symbolic AI, based on explicit knowledge and reasoning, and deep learning, based on data and optimization, comes a synthesis that learns like the latter and reasons like the former. The thesis is attractive, but read it as an agenda, not a result: today’s concrete systems combine the two in very different ways, each with its own guarantees and failures.
Integration patterns
The first question for a neurosymbolic system is who decides what. Does the network propose and the engine check? Does the engine search and the network order? Does the network replace the engine? The answer determines which guarantees survive.
Kautz proposed a six-type taxonomy overlapping with this one. In D’Avila Garcez and Lamb’s reading: type 1 is deep learning with symbolic inputs and outputs (machine translation); type 2 combines a network with a symbolic solver such as MCTS, as in AlphaGo (Kautz writes Symbolic[Neuro]); type 3 is a network specialized in one task (perception) passing its output to a symbolic system specialized in another; type 4 compiles symbolic knowledge into training data; type 5 turns logical rules into soft loss constraints (Logic Tensor Networks); and type 6 puts full symbolic reasoning inside a network, which they say does not yet exist for combinatorial reasoning. Our pattern 1 is type 2; pattern 3 is type 3; pattern 5 resembles type 4 (the solver compiles its knowledge into labels). Kautz’s taxonomy does not distinguish pattern 2, generate and verify, precisely the one that has grown most with language models.
| System | Learned component | Symbolic component | Pattern |
|---|---|---|---|
| AlphaZero | network policy and value | MCTS with PUCT | 1 |
| DeepCubeA | cost to go | batched weighted A* | 1 |
| GPT-f, ReProver | candidate tactics (and value) | best-first search over proof states, verified by Metamath or Lean | 1 |
| LLM-Modulo | candidate plans | plan validator | 2 |
| FunSearch | candidate programs | evaluator that runs and scores | 2 |
| LLM+P | PDDL translation | classical planner | 3 |
| SATzilla | solver selector | complete SAT solvers | 4 |
| NeuroSAT | all reasoning | only for generating labels and checking | 5 |
Large systems combine patterns. AlphaGeometry is a symbolic deductive engine that, when stuck, asks a language model for an auxiliary construction (pattern 1, with the model generating branches). AlphaProof translates to create training problems (pattern 3) and uses AlphaZero-style search over Lean proofs (pattern 1). Classification prompts the right question: for patterns 1 or 2, correctness comes from the engine and the question is how much the network speeds it up; for 5, how often it is wrong.
Learned heuristics
Cost to go as a fixed point
Consider a finite state space with goal , deterministic actions and cost 1 per action, where the goal is reachable from every state. The optimal cost to go is the shortest distance from to the goal: from the A* lesson. It satisfies the Bellman equation
and value iteration computes it by repeatedly applying the operator on the right, , with . Here iteration has a closed form explaining much of the lab.
Proof
By induction on . For this is the definition. Suppose . At the goal, . If , its successors satisfy , with equality for one of them (the first on an optimal path). Thus
The second equality exchanges the two minima, which commute.
∎Each operator application propagates goal information one step farther, and until it reaches a state its value is an underestimate: the iterate is an improving admissible heuristic. With tables this is exact; with states a table is impossible.
Conditional copying of the target network plays the role of : each copy is approximately one value iteration. The theorem predicts a short run: with only copies, the network cannot know distances much greater than and will underestimate distant states. The paper uses , for the cube and for the 15-puzzle, checks error every iterations with , and trains for a million iterations (36 hours on two Titan V GPUs for the cube, with six more generating data: 10 billion examples). The network has dense layers of 5000 and 1000 units followed by four 1000-unit residual blocks (six for the 24-puzzle), batch normalization and ReLU, and receives a one-hot state: inputs for the 15-puzzle.
How much does it overestimate in practice? DeepCubeA’s authors compared 100,000 cubes scrambled 1 to 30 times against exact distances: the network did not overestimate in 66.8% of cases, overestimated by at most one move in 97.4%, and had mean overestimation 0.24 moves. Nearly admissible, but without a guarantee.
Batched weighted A*
Evaluating a 14-million-parameter network costs much more than a table lookup, but on a GPU evaluating one state costs nearly the same as ten thousand. DeepCubeA exploits this with a variant of A*.
Dividing by , ordering by orders by : with this is exactly weighted A* from lesson 3 with weight . With it is greedy search by ; with and , A*. The paper selected hyperparameters by grid search on 100 cubes separate from the test set ( from 0 to 1, ) and chose , for the cube and , for the 15-, 24- and 35-puzzles. Increasing and shortened solutions but usually increased time, although nodes per second also rose through parallelism.
If were admissible, the weighted A* bound would say that with cost is at most . With the paper does not discuss a stopping-rule detail. If the goal leaves OPEN in the same extraction as an optimal-path node with smaller , that node was extracted but its children have not yet been generated, breaking the bound’s argument (which requires an optimal-path node in OPEN with at least that of the goal). Minimal example: OPEN contains an optimal-path node with and a goal reached by a bad path with , and . Both are extracted, is a goal and search returns , although expanding would have led to a goal with . The bound returns if the goal is accepted only when first in its batch (then it has OPEN’s smallest and the lesson 3 argument applies). With a learned heuristic there is no bound to protect; measurement matters.
The proof varies that of weighted A* and is an exercise. Note the requirement: a uniform bound over all states. DeepCubeA’s statistics (97.4% of states overestimated by at most one move) do not supply it: they describe the test-state distribution, not all states. Search visits precisely states where the network errs, because badly underestimating a bad state puts it first in the queue.
Generalized policies for planning
DeepCubeA learns a heuristic for one domain and one size: the 15-puzzle network does not work for the 24-puzzle. Classical planning seeks more: a function working for every instance of a domain, with any number of objects. Because object count varies, a natural architecture is a graph network over state and goal atoms. Action Schema Networks by Toyer, Trevizan, Thiébaux and Xie (AAAI 2018) share weights among all instantiated actions of one PDDL schema and learn policies transferring to larger problems in the same domain. Ståhlberg, Bonet and Geffner (ICAPS 2022) train a GNN to approximate optimal value and explain when it works: what this kind of GNN distinguishes is bounded by a fragment of first-order logic with counting. They obtain optimal general policies where optimal value is definable by features in that fragment, but not where more expressive features are needed. This result predicts failure rather than merely reporting benchmark success.
Lab 1: a mini DeepCubeA for the 15-puzzle
You will train a cost-to-go network on the GPU with DAVI, compare it state by state with Manhattan distance and the additive 5-5-5 PDB from the search-at-scale lesson, and use it in BWAS. Local cells (PyTorch with CUDA) have two sizes. By default they run the paper’s 15-puzzle configuration: 5000- and 1000-unit layers with four residual blocks, batches of 10,000 states, and one million iterations, taking days on a consumer GPU. Environment variable ORYON_VERIFY_SHORT=1 selects a short version taking about ten minutes on an RTX 4060: 1000 units with two blocks, batches of 4000, and 6000 iterations. All numbers in this text come from that short run; the full run should approach the paper’s figures instead.
State representation is as in lesson 3: s[casilla] = ficha, with the blank (tile 0) in square 0 at the goal. NumPy batches everything: scrambling thousands of states at once, generating their children and evaluating classical heuristics on a state matrix. The PDB is the same code as lesson 3 plus a function evaluating it on a batch.
import os, time, json, heapq, math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
CORTO = os.environ.get("ORYON_VERIFY_SHORT") == "1" # ejecución corta de verificación
EXPORTAR = os.environ.get("ORYON_EXPORT_DIR") # si existe, guarda ahí los datos de las figuras
DEV = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)
rng = np.random.default_rng(0)
META = np.arange(16, dtype=np.int64) # s[casilla] = ficha; el hueco (0) en la casilla 0, como en la lección 3
TGT = np.full((16, 4), -1, dtype=np.int64) # casilla a la que va el hueco en cada dirección (−1: fuera del tablero)
for p in range(16):
r, c = divmod(p, 4)
for d, (dr, dc) in enumerate([(-1, 0), (1, 0), (0, -1), (0, 1)]):
if 0 <= r + dr < 4 and 0 <= c + dc < 4:
TGT[p, d] = (r + dr) * 4 + c + dc
VALIDAS = [np.flatnonzero(TGT[p] >= 0) for p in range(16)]
NVAL = np.array([len(v) for v in VALIDAS])
VAL_PAD = np.array([np.pad(v, (0, 4 - len(v)), constant_values=v[0]) for v in VALIDAS])
def mezclar(n, kmin, kmax, rng):
"""n estados obtenidos con k ~ U{kmin..kmax} movimientos aleatorios desde la meta (paseo hacia atrás)."""
s = np.tile(META, (n, 1))
hueco = np.zeros(n, dtype=np.int64)
k = rng.integers(kmin, kmax + 1, size=n)
filas = np.arange(n)
for t in range(kmax):
act = filas[t < k]
if act.size == 0:
break
b = hueco[act]
d = VAL_PAD[b, (rng.random(act.size) * NVAL[b]).astype(np.int64)]
q = TGT[b, d]
s[act, b] = s[act, q]
s[act, q] = 0
hueco[act] = q
return s, k
def hijos(s):
"""(M,16) -> (M,4,16) sucesores y máscara (M,4) de movimientos legales."""
M = s.shape[0]
b = np.argmin(s, axis=1) # casilla del hueco
q = TGT[b] # (M,4)
ok = q >= 0
c = np.repeat(s[:, None, :], 4, axis=1)
fi, di = np.nonzero(ok)
c[fi, di, b[fi]] = s[fi, q[fi, di]]
c[fi, di, q[fi, di]] = 0
return c, ok
# distancia Manhattan, vectorizada: MD[p, t] = distancia de la casilla p a la casilla meta de la ficha t
MD = np.array([[abs(p // 4 - t // 4) + abs(p % 4 - t % 4) if t else 0 for t in range(16)] for p in range(16)])
def h_manhattan(s):
return MD[np.arange(16)[None, :], s].sum(axis=1)
# PDB aditiva 5-5-5 (el código del laboratorio de la lección 3, sin cambios)
def pdb_dispersa(patron):
k = len(patron)
SH = 4 * k
dist = np.full(16 << SH, -1, dtype=np.int8)
inicio = sum(t << (4 * i) for i, t in enumerate(patron))
dist[inicio] = 0
frontera = np.array([inicio], dtype=np.int64)
nivel = 0
while frontera.size:
capa, cur = [frontera], frontera
while cur.size:
b = cur >> SH
ocupada = np.zeros((cur.size, 16), bool)
filas = np.arange(cur.size)
for i in range(k):
ocupada[filas, (cur >> (4 * i)) & 15] = True
nuevos = []
for d, ok in ((-4, b >= 4), (4, b < 12), (-1, (b & 3) > 0), (1, (b & 3) < 3)):
m = ok.copy()
m[m] = ~ocupada[filas[m], b[m] + d]
n = cur[m] + (d << SH)
n = n[dist[n] < 0]
dist[n] = nivel
nuevos.append(n)
cur = np.concatenate(nuevos)
capa.append(cur)
todos = np.concatenate(capa)
b = todos >> SH
sig = []
for i in range(k):
p = (todos >> (4 * i)) & 15
for d in (-4, 4, -1, 1):
m = p == b + d
if d == -1:
m &= (b & 3) > 0
if d == 1:
m &= (b & 3) < 3
n = todos[m] + (d << SH) - (d << (4 * i))
sig.append(n[dist[n] < 0])
frontera = np.unique(np.concatenate(sig))
dist[frontera] = nivel + 1
nivel += 1
d2 = dist.reshape(16, -1)
return np.where(d2 < 0, 127, d2).min(axis=0).astype(np.int8)
MULT = np.array([32760, 2184, 156, 12, 1])
def compactar(dispersa, k=5):
idx = np.arange(dispersa.size)
P = np.stack([(idx >> (4 * i)) & 15 for i in range(k)], axis=1)
validas = dispersa < 127
P = P[validas]
r = np.zeros(len(P), dtype=np.int64)
for i in range(k):
menores = (P[:, :i] < P[:, i:i + 1]).sum(axis=1)
r += (P[:, i] - menores) * MULT[i]
tabla = np.full(len(P), -1, dtype=np.int8)
tabla[r] = dispersa[validas]
return tabla
GRUPOS = [(1, 2, 3, 5, 6), (4, 8, 12, 9, 13), (7, 10, 11, 14, 15)]
t0 = time.perf_counter()
PDB = [compactar(pdb_dispersa(g)) for g in GRUPOS]
print(f"PDB 5-5-5 construida en {time.perf_counter() - t0:.1f} s ({sum(t.nbytes for t in PDB):,d} bytes)")
def h_pdb(s):
"""Suma de las tres tablas, para un lote de estados (M,16)."""
M = s.shape[0]
P = np.empty_like(s)
P[np.arange(M)[:, None], s] = np.arange(16)[None, :] # P[:, ficha] = casilla
h = np.zeros(M, dtype=np.int64)
for g, tab in zip(GRUPOS, PDB):
p = P[:, list(g)]
r = np.zeros(M, dtype=np.int64)
for i in range(5):
r += (p[:, i] - (p[:, :i] < p[:, i:i + 1]).sum(axis=1)) * MULT[i]
h += tab[r]
return h
s_prueba, _ = mezclar(5, 30, 30, rng)
print("Manhattan:", h_manhattan(s_prueba), " PDB:", h_pdb(s_prueba), " (la PDB domina)")npm run lab and open the connection link.For states scrambled by only 30 random moves, PDB and Manhattan often agree: tiles barely interfere. The difference emerges far from the goal, as the figure shows.
The network follows the paper’s architecture at reduced scale. Each state’s target is computed using the frozen network on its four children (illegal moves are ), and copying to the frozen network occurs only when error falls below threshold. The short version uses 0.1 instead of the paper’s 0.05: with so few iterations, a small network’s error rarely falls below 0.05 once it sees long distances, and copying would stop.
class Residual(nn.Module):
def __init__(self, d):
super().__init__()
self.f = nn.Sequential(nn.Linear(d, d), nn.BatchNorm1d(d), nn.ReLU(), nn.Linear(d, d), nn.BatchNorm1d(d))
def forward(self, x):
return F.relu(x + self.f(x))
class CosteRed(nn.Module):
"""La arquitectura de DeepCubeA: dos capas densas, bloques residuales y una salida lineal."""
def __init__(self, h1, h2, bloques):
super().__init__()
self.entrada = nn.Sequential(nn.Linear(256, h1), nn.BatchNorm1d(h1), nn.ReLU(),
nn.Linear(h1, h2), nn.BatchNorm1d(h2), nn.ReLU())
self.res = nn.Sequential(*[Residual(h2) for _ in range(bloques)])
self.salida = nn.Linear(h2, 1)
def forward(self, s): # s: (M,16) enteros
x = F.one_hot(s, 16).float().flatten(1)
return self.salida(self.res(self.entrada(x))).squeeze(1)
if CORTO: # verificación: unos minutos en una RTX 4060
CFG = dict(h1=1000, h2=1000, bloques=2, lote=4000, K=60, pasos=6000, cada=50, umbral=0.1, lr=1e-3)
else: # la configuración del artículo para el 15-puzzle (horas a días en una sola GPU de consumo)
CFG = dict(h1=5000, h2=1000, bloques=4, lote=10000, K=500, pasos=1_000_000, cada=5000, umbral=0.05, lr=1e-3)
print(CFG)
red = CosteRed(CFG["h1"], CFG["h2"], CFG["bloques"]).to(DEV)
objetivo = CosteRed(CFG["h1"], CFG["h2"], CFG["bloques"]).to(DEV)
objetivo.load_state_dict(red.state_dict())
objetivo.eval()
opt = torch.optim.Adam(red.parameters(), lr=CFG["lr"])
META_T = torch.as_tensor(META, device=DEV)
@torch.no_grad()
def J(modelo, s, trozo=40000):
"""Coste por llegar estimado, con J(meta) = 0. s: array (M,16)."""
modelo.eval()
out = []
for i in range(0, len(s), trozo):
st = torch.as_tensor(s[i:i + trozo], device=DEV)
v = modelo(st)
v[(st == META_T).all(1)] = 0.0
out.append(v)
return torch.cat(out)
def objetivos_davi(s):
"""y(s) = min_a [1 + J_e(A(s, a))], y = 0 si s es la meta (ecuación 1 de DeepCubeA)."""
c, ok = hijos(s)
v = J(objetivo, c.reshape(-1, 16)).view(len(s), 4)
v = torch.where(torch.as_tensor(ok, device=DEV), 1.0 + v, torch.full_like(v, float("inf")))
y = v.min(1).values
y[torch.as_tensor((s == META).all(1), device=DEV)] = 0.0
return y
historia, actualizaciones = [], 0
t0 = time.perf_counter()
for paso in range(1, CFG["pasos"] + 1):
s, _ = mezclar(CFG["lote"], 1, CFG["K"], rng)
y = objetivos_davi(s)
red.train()
loss = F.mse_loss(red(torch.as_tensor(s, device=DEV)), y)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
if paso % CFG["cada"] == 0:
l = loss.item()
if l < CFG["umbral"]: # la regla de DAVI: copiar solo cuando el error es pequeño
objetivo.load_state_dict(red.state_dict())
actualizaciones += 1
historia.append((paso, l, actualizaciones))
if paso % (CFG["cada"] * 10) == 0:
print(f"paso {paso:6d} pérdida {l:.3f} copias de la red objetivo {actualizaciones} {time.perf_counter() - t0:.0f} s")
print(f"entrenamiento: {time.perf_counter() - t0:.0f} s, {actualizaciones} actualizaciones de la red objetivo")npm run lab and open the connection link.The short run made 51 target-network copies in 6000 iterations. By the value-iteration theorem, 51 exact copies would suffice for distances up to 51 moves; the network is not exact, but the number of copies is the first figure to inspect when diagnosing DAVI training. Loss also does not fall monotonically: each copy changes targets, and loss rises whenever the network begins to see distances it did not previously know.
Comparison with ground truth requires . The next cell takes 300 states scrambled with between 1 and moves (half outside the training distribution), computes optimal cost using lesson 3’s IDA* with PDB, and measures all three heuristics.
NB = [[int(q) for q in TGT[p] if q >= 0] for p in range(16)]
GRUPO_DE, PUESTO = [0] * 16, [0] * 16
for gi, g in enumerate(GRUPOS):
for k_, t in enumerate(g):
GRUPO_DE[t], PUESTO[t] = gi, k_
MULT_L = [int(m) for m in MULT]
PDB_L = [t.tolist() for t in PDB]
def rango(ps):
r = 0
for i, p in enumerate(ps):
r += (p - sum(q < p for q in ps[:i])) * MULT_L[i]
return r
def ida_pdb(tablero, max_nodos=5 * 10**7):
"""IDA* con la PDB aditiva 5-5-5 (lección 3): coste óptimo C*."""
s = list(tablero)
pos = {t: p for p, t in enumerate(s)}
cas = [[pos[t] for t in g] for g in GRUPOS]
hp = [PDB_L[i][rango(cas[i])] for i in range(3)]
nodos = 0
def dfs(b, g, umbral, prev):
nonlocal nodos
h = hp[0] + hp[1] + hp[2]
if g + h > umbral:
return g + h
if h == 0 and s == list(range(16)):
return -1
m = 1 << 30
for q in NB[b]:
if q == prev:
continue
nodos += 1
t = s[q]
gi, k_ = GRUPO_DE[t], PUESTO[t]
s[b], s[q] = t, 0
viejo = hp[gi]
cas[gi][k_] = b
hp[gi] = PDB_L[gi][rango(cas[gi])]
r = dfs(q, g + 1, umbral, b)
s[q], s[b] = t, 0
cas[gi][k_] = q
hp[gi] = viejo
if r == -1:
return -1
m = min(m, r)
return m
umbral = sum(hp)
while True:
r = dfs(s.index(0), 0, umbral, -1)
if r == -1:
return umbral, nodos
umbral = r
N_EVAL = 300
s_ev, k_ev = mezclar(N_EVAL, 1, 2 * CFG["K"] if CORTO else 300, np.random.default_rng(1))
t0 = time.perf_counter()
h_opt = np.array([ida_pdb(x)[0] for x in s_ev])
print(f"C* de {N_EVAL} estados por IDA* + PDB en {time.perf_counter() - t0:.0f} s; C* medio {h_opt.mean():.1f}, máximo {h_opt.max()}")
h_md, h_pd = h_manhattan(s_ev), h_pdb(s_ev)
h_nn = J(red, s_ev).cpu().numpy()
def resumen(nombre, h):
e = h - h_opt
print(f"{nombre:10s} sobreestima en {np.mean(e > 0.5):6.1%} |error| medio {np.abs(e).mean():5.2f} "
f"h/h* medio {np.mean(h[h_opt > 0] / h_opt[h_opt > 0]):.3f} máx. sobreestimación {e.max():5.2f}")
for nombre, h in (("Manhattan", h_md), ("PDB 5-5-5", h_pd), ("aprendida", h_nn)):
resumen(nombre, h)
dentro = k_ev <= CFG["K"]
print(f"aprendida, |error| medio: {np.abs(h_nn - h_opt)[dentro].mean():.2f} con k <= K (distribución de entrenamiento), "
f"{np.abs(h_nn - h_opt)[~dentro].mean():.2f} con k > K")npm run lab and open the connection link.The 300 states have mean optimal cost 18.6 moves (maximum 49). Neither classical heuristic overestimates, as construction requires, and PDB dominates Manhattan: mean absolute error 2.38 versus 4.18, and mean 0.911 versus 0.837. The network is much more accurate (mean absolute error 1.08, mean 1.003) but not admissible: it overestimates by more than half a move in one third of states (33.3%), and in the worst case by 7.03 moves. Accuracy depends on location: for states obtained with moves, in its training distribution, mean error is 0.39; with it is 1.74.
The figure shows the shape of errors. Manhattan and PDB stay below the diagonal and move farther away as grows: they underestimate more farther from the goal, because they ignore more tile interactions. The network hugs the diagonal on nearby states and spreads to both sides on distant ones, especially hollow points. This is the price of regression: error is symmetric by design (squared loss penalizes overestimation and underestimation equally), and training does not push toward admissibility.
Now BWAS. The implementation follows the definition: OPEN is a heap of tuples , stale entries (with worse than the best known) are discarded on extraction, and the heuristic is evaluated once per iteration on all new children.
def bwas(s0, h_lote, lam, N, max_generados=10**5):
"""A* por lotes con f = lam·g + h: extrae los N nodos de menor f, evalúa h de todos sus hijos en UN lote.
Termina cuando una meta sale de OPEN para expandirse. Reabre un estado si llega por un camino más corto.
Devuelve (coste, expandidos, generados, iteraciones) o (None, ...) si agota el presupuesto."""
clave0 = s0.tobytes()
g = {clave0: 0}
abiertos = [(float(h_lote(s0[None])[0]), 0, 0, clave0, s0)]
cont, expandidos, generados, iters = 1, 0, 1, 0
meta_b = META.tobytes()
while abiertos:
lote = []
while abiertos and len(lote) < N:
f, _, gx, cl, s = heapq.heappop(abiertos)
if gx > g[cl]:
continue # entrada obsoleta: ya se encontró un camino mejor
if cl == meta_b:
return gx, expandidos, generados, iters
lote.append((gx, s))
if not lote:
break
iters += 1
expandidos += len(lote)
S = np.stack([s for _, s in lote])
c, ok = hijos(S)
nuevos, gs = [], []
for i, (gx, _) in enumerate(lote):
for d in np.flatnonzero(ok[i]):
ch = c[i, d]
cl = ch.tobytes()
if gx + 1 < g.get(cl, 1 << 30):
g[cl] = gx + 1
nuevos.append(ch)
gs.append(gx + 1)
if not nuevos:
continue
generados += len(nuevos)
H = h_lote(np.stack(nuevos)) # una sola llamada a la heurística por iteración
for ch, gx, h in zip(nuevos, gs, H):
heapq.heappush(abiertos, (lam * gx + float(h), cont, gx, ch.tobytes(), ch))
cont += 1
if generados > max_generados:
break
return None, expandidos, generados, iters
h_red = lambda S: J(red, S).cpu().numpy()
h_tab = lambda S: h_pdb(S).astype(float)
# instancias de prueba: los primeros estados de evaluación con 20 <= C* <= 40
sel = np.flatnonzero((h_opt >= 20) & (h_opt <= 40))[: (20 if CORTO else 100)]
print(f"{len(sel)} instancias, C* medio {h_opt[sel].mean():.1f}")
def experimento(h_lote, lam, N):
filas = []
t0 = time.perf_counter()
for i in sel:
c, e, gen, it = bwas(s_ev[i], h_lote, lam, N)
filas.append((c, e, gen, it))
seg = time.perf_counter() - t0
ok = [f for f in filas if f[0] is not None]
ratio = np.array([f[0] / h_opt[i] for f, i in zip(filas, sel) if f[0] is not None])
return dict(lam=lam, N=N, resueltas=len(ok), optimas=int(np.sum(np.isclose(ratio, 1))),
ratio_medio=float(ratio.mean()) if len(ratio) else None, ratio_max=float(ratio.max()) if len(ratio) else None,
gen_med=float(np.median([f[2] for f in filas])), iters_med=float(np.median([f[3] for f in filas])),
seg=seg, por_instancia=[[int(f[0]) if f[0] is not None else -1, int(f[2]), int(f[3])] for f in filas])
base = experimento(h_tab, 1.0, 1)
print(f"A* óptimo con la PDB: {base['optimas']}/{len(sel)} óptimas, mediana de generados {base['gen_med']:.1f}")
rejilla = []
for lam in ([0.2, 0.4, 0.6, 0.8, 1.0]):
for N in ([1, 10, 100, 1000]):
r = experimento(h_red, lam, N)
rejilla.append(r)
print(f"λ={lam:.1f} N={N:5d}: resueltas {r['resueltas']}/{len(sel)}, óptimas {r['optimas']}, "
f"coste/C* medio {r['ratio_medio']:.3f} (máx {r['ratio_max']:.3f}), mediana de generados {r['gen_med']:9.1f}, "
f"de iteraciones {r['iters_med']:6.1f}")
pdb_lotes = [experimento(h_tab, lam, N) for lam, N in ((0.8, 100), (0.6, 100))]
for r in pdb_lotes:
print(f"PDB con BWAS λ={r['lam']} N={r['N']}: óptimas {r['optimas']}, coste/C* medio {r['ratio_medio']:.3f}, "
f"mediana de generados {r['gen_med']:.1f}")
if EXPORTAR:
os.makedirs(EXPORTAR, exist_ok=True)
with open(os.path.join(EXPORTAR, "deepcubea.json"), "w", encoding="utf-8") as f:
json.dump(dict(cfg=CFG, hopt=h_opt.tolist(), k=k_ev.tolist(), md=h_md.tolist(), pdb=h_pd.tolist(),
red=[round(float(x), 2) for x in h_nn], sel=sel.tolist(), base=base, rejilla=rejilla,
pdb_lotes=pdb_lotes, historia=historia), f)
del red, objetivo, opt # libera la GPU para los laboratorios siguientes
torch.cuda.empty_cache()npm run lab and open the connection link.The 20 instances have mean optimal cost 27.7. Three results are visible by moving the figure’s sliders:
- The network saves many nodes. Optimal A* with PDB generates a median 366 nodes. BWAS with the network and generates 66 to 85 depending on : four or five times fewer, because a heuristic wrong by one or two moves orders OPEN almost perfectly.
- With optimality is traded away, controlled by . With , 18 of 20 solutions are optimal (mean cost 1.009 times optimum, worst 1.118); with only 11 are (mean 1.132, worst 1.765). This follows lesson 3’s weighted A* trend, although there is no bound because the heuristic is inadmissible.
- Batches buy optimality with nodes. With almost all solutions are optimal for any (all from onward), while median iterations remain 26, nearly the solution length: each iteration advances one step and the batch covers nearby alternatives. Generated nodes grow almost proportionally to (534 with , about 4370 with , about 36,800 with ), and stops mattering. With PDB as heuristic, BWAS with also generates about 4370 nodes and mean cost 1.003 times optimal.
This explains why DeepCubeA uses of ten thousand and high : on a GPU the cost is the number of iterations (network calls), not states per call, and a large batch lets an imperfect heuristic nearly always find the optimum. On the 15-puzzle the paper gets 99.4% optimal solutions with and . The other side is total cost: here A* with PDB needs far fewer nodes than large-batch BWAS, and in the paper the optimal PDB solver takes 0.002 s per instance versus DeepCubeA’s 10.28 s. Learning pays when no good PDB fits in memory: on the 24-puzzle DeepCubeA averages 19.33 s and the optimal PDB solver 4239.54 s. We do not compare this run’s times: evaluating PDB on a single state in NumPy and the network on a shared GPU mostly measures Python overhead, not algorithm cost.
Learning inside solvers
A CDCL solver makes thousands of decisions per second that do not affect correctness: which variable and polarity to branch on, when to restart and which learned clauses to delete. Earlier decisions include which solver and parameters to use for an instance. These are hand-designed heuristics tuned on benchmarks, all candidates for learning.
The opposite extreme asks a network to be the solver. We start there because this experiment best shows what a network learns when given a reasoning problem.
NeuroSAT: a learned solver with one bit of supervision
Selsam, Lamm, Bünz, Liang, de Moura and Dill (ICLR 2019) represent a CNF formula as a graph with a node per literal () and clause (), an edge between each clause and its literals, and another type of edge between each literal and its complement. Let be the incidence matrix ( if literal appears in clause ), and the operator swapping each literal row with its negation. Each literal has a vector and each clause one , stacked in and . One message-passing iteration has two halves:
where and are multilayer perceptrons applied row by row and , are LSTMs (with layer normalization in the paper), whose hidden state is omitted. Each clause sums messages from its literals; each literal sums those of its clauses and also receives its complement’s vector. After iterations, another perceptron gives a scalar vote per literal, , and their mean is the prediction, trained by cross-entropy against the “satisfiable” bit.
Three design choices explain the result:
- Exact invariances. The graph is unordered: permuting variables, clauses or literals within a clause, or negating every occurrence of a variable, gives the same prediction. The network cannot learn name-dependent shortcuts.
- Size-independent weights. Parameters describe a node’s behavior given its neighbors, so the same network applies to formulas of any size and any number of iterations .
- Data that force reasoning. Distribution generates pairs: random clauses (size , mean slightly above 4) are added until the formula becomes unsatisfiable, and the satisfiable twin is obtained by negating one literal in the last clause. The formulas differ by one literal out of about a thousand, so no superficial statistic (clause count, sizes, proportion negated) separates the classes.
With , iterations and training on with millions of problems, NeuroSAT correctly classifies 85% of an test set: 96% of unsatisfiable and 73% of satisfiable formulas. What happens inside is striking. Literal votes weakly indicate “unsatisfiable” for several iterations, until an abrupt transition makes them all confidently say “satisfiable”, after which they do not change. Project literal vectors with PCA and they are mixed before the transition, then form two clusters corresponding to an assignment: using 2-means and trying both ways of assigning true and false to clusters, the authors decode a satisfying assignment for 70% of satisfiable test problems. Trained only to predict one bit, the network has learned to search for a certificate and says “satisfiable” only after finding one. Hence it almost never says “satisfiable” for an unsatisfiable formula and is never sure one is unsatisfiable.
Since the procedure is iterative, it can run longer: on it solves 25% of satisfiable problems with four times as many iterations as in training, and under 10% with the same number. The paper itself is clear: NeuroSAT is “not competitive” with modern SAT solvers.
Lab 2: a small NeuroSAT
You will generate pairs using your own DPLL, implement NeuroSAT message passing in PyTorch, train it with one bit per formula and look inside. As in lab 1, local cells have two sizes. By default they run a configuration close to the paper: , 200,000 pairs and 20 epochs, taking hours on a consumer GPU (and minutes of CPU to generate pairs). With ORYON_VERIFY_SHORT=1 they train on 12,000 pairs for 10 epochs, around fifteen minutes on an RTX 4060. Text figures come from this short run, trained on formulas of at most 20 variables and also evaluated on 40: a harder generalization problem than the paper’s, with much less data.
The generator follows the definition of : each new clause is first checked against the last known model (if satisfied, the formula remains satisfiable without calling the solver); otherwise DPLL is called. The first cell checks both important properties: using DPLL on ten pairs, one formula is satisfiable and the other is not; all fifty differ by one literal.
import os, json, time, math, random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
CORTO = os.environ.get("ORYON_VERIFY_SHORT") == "1"
EXPORTAR = os.environ.get("ORYON_EXPORT_DIR")
DEV = "cuda" if torch.cuda.is_available() else "cpu"
def dpll(clausulas, n):
"""DPLL con propagación unitaria. Literales ±(v+1). Devuelve una asignación (lista de bool) o None."""
asig = [None] * n
def valor(l):
a = asig[abs(l) - 1]
return None if a is None else (a if l > 0 else not a)
def propagar(rastro):
cambio = True
while cambio:
cambio = False
for c in clausulas:
libres, sat = [], False
for l in c:
v = valor(l)
if v is True:
sat = True
break
if v is None:
libres.append(l)
if sat:
continue
if not libres:
return False # conflicto
if len(libres) == 1:
l = libres[0]
asig[abs(l) - 1] = l > 0
rastro.append(abs(l) - 1)
cambio = True
return True
def rec():
rastro = []
if not propagar(rastro):
for v in rastro:
asig[v] = None
return False
libre = next((v for v in range(n) if asig[v] is None), None)
if libre is None:
return True
for b in (True, False):
asig[libre] = b
if rec():
return True
asig[libre] = None
for v in rastro:
asig[v] = None
return False
return list(asig) if rec() else None
def satisface(clausulas, asig):
return all(any((l > 0) == asig[abs(l) - 1] for l in c) for c in clausulas)
def sr(n, rnd):
"""Un par de SR(n) (Selsam et al., 2019): añade cláusulas aleatorias hasta que la fórmula deja de ser
satisfacible; la última cláusula con un literal negado da la gemela satisfacible."""
clausulas, modelo = [], [rnd.random() < 0.5 for _ in range(n)]
while True:
k = 1 + (rnd.random() < 0.7)
while rnd.random() >= 0.4: # Geo(0.4) con soporte {1, 2, ...}: hasta el primer éxito
k += 1
k = min(k + 1, n) # el +1 es el primer ensayo de la geométrica
vs = rnd.sample(range(n), k)
c = [(v + 1) * (1 if rnd.random() < 0.5 else -1) for v in vs]
if any((l > 0) == modelo[abs(l) - 1] for l in c):
clausulas.append(c) # el modelo actual la cumple: sigue siendo satisfacible
continue
m = dpll(clausulas + [c], n)
if m is None:
sat = clausulas + [[-c[0]] + c[1:]] # negar un literal de la última cláusula
return sat, clausulas + [c]
modelo = [bool(x) if x is not None else False for x in m]
clausulas.append(c)
rnd = random.Random(0)
t0 = time.perf_counter()
pares = [sr(40, rnd) for _ in range(50)]
print(f"50 pares de SR(40) en {time.perf_counter() - t0:.1f} s; por fórmula, {np.mean([len(p[0]) for p in pares]):.0f} cláusulas "
f"y {np.mean([sum(map(len, p[0])) for p in pares]):.0f} literales de media")
assert all(dpll(s, 40) is not None and dpll(u, 40) is None for s, u in pares[:10]) # cada par: una sí, otra no
assert all(sum(a != b for a, b in zip(s[-1], u[-1])) == 1 and s[:-1] == u[:-1] for s, u in pares) # difieren en un literalnpm run lab and open the connection link.An formula averages about 228 clauses and 960 literals, and its twin differs by just one. No global feature (clause count, lengths, negation proportion) separates the classes: the network must examine structure.
The implementation follows the equations above. For batch training, several problems join into one graph with a sparse block-diagonal incidence matrix: message passing cannot mix problems because no edges connect them, and each problem’s prediction is the mean vote of its literals. Both twins always share a batch. Hyperparameters follow the paper (, three-hidden-layer perceptrons, , gradient clipping with global norm 0.65, batches of up to 12,000 nodes in the full configuration) with two exceptions: LSTMs lack layer normalization, and in the short version the learning rate is instead of the paper’s , which trained on millions of problems (the full configuration uses the paper’s rate).
A practical warning before training: initially the network distinguishes nothing and loss stays at , the loss from always answering 0.5. This plateau ends once it finds the first useful signal. With high learning rates it may never escape: tests of this code found left it at for hundreds of steps, while sometimes escaped and sometimes did not. If loss stays at 0.693 for several epochs, lower the rate and restart.
def comprimir(cl):
"""Una fórmula como dos arrays compactos (literales seguidos y longitudes): unas diez veces menos memoria que listas."""
return np.array([l for c in cl for l in c], np.int16), np.array([len(c) for c in cl], np.int16)
def lote(problemas):
"""Une varios problemas (fórmula comprimida, n) en un grafo: matriz de incidencia dispersa literal-cláusula
(2N x M, x_v en la fila v y ¬x_v en la v + n de su problema) e índice Flip de cada literal a su complementario."""
filas, cols, flip, grupo_lit = [], [], [], []
base_l, base_c = 0, 0
for g, ((lits, largos), n) in enumerate(problemas):
lits = lits.astype(np.int64)
filas.append(base_l + np.where(lits > 0, lits - 1, -lits - 1 + n))
cols.append(base_c + np.repeat(np.arange(len(largos)), largos))
flip.append(base_l + np.r_[np.arange(n, 2 * n), np.arange(n)])
grupo_lit.append(np.full(2 * n, g))
base_l += 2 * n
base_c += len(largos)
filas, cols = np.concatenate(filas), np.concatenate(cols)
idx = torch.from_numpy(np.stack([filas, cols]))
Mx = torch.sparse_coo_tensor(idx, torch.ones(len(filas)), (base_l, base_c)).coalesce().to(DEV)
return (Mx, torch.from_numpy(np.concatenate(flip)).to(DEV), torch.from_numpy(np.concatenate(grupo_lit)).to(DEV),
base_l, base_c)
def mlp(d, capas=3):
m = []
for _ in range(capas):
m += [nn.Linear(d, d), nn.ReLU()]
return nn.Sequential(*m, nn.Linear(d, d))
class NeuroSAT(nn.Module):
def __init__(self, d=128):
super().__init__()
self.d = d
self.L_init = nn.Parameter(torch.randn(1, d) / math.sqrt(d))
self.C_init = nn.Parameter(torch.randn(1, d) / math.sqrt(d))
self.L_msg, self.C_msg = mlp(d), mlp(d)
self.L_u = nn.LSTMCell(2 * d, d) # el artículo usa LSTM con normalización de capa
self.C_u = nn.LSTMCell(d, d)
self.L_vote = nn.Sequential(*list(mlp(d))[:-1], nn.Linear(d, 1))
def forward(self, Mx, flip, grupo, nL, nC, T, guardar=False):
L = self.L_init.expand(nL, -1).contiguous(); Lh = torch.zeros_like(L)
C = self.C_init.expand(nC, -1).contiguous(); Ch = torch.zeros_like(C)
hist = []
for _ in range(T):
C, Ch = self.C_u(torch.sparse.mm(Mx.t(), self.L_msg(L)), (C, Ch)) # cláusulas <- literales
L, Lh = self.L_u(torch.cat([torch.sparse.mm(Mx, self.C_msg(C)), L[flip]], 1), (L, Lh)) # literales <- cláusulas y complementario
if guardar:
hist.append(L.detach())
votos = self.L_vote(L).squeeze(1)
G = int(grupo.max()) + 1
logit = torch.zeros(G, device=L.device).index_add_(0, grupo, votos) / torch.bincount(grupo, minlength=G)
return logit, votos, L, hist
if CORTO:
CFG = dict(n_min=10, n_max=20, pares=12000, nodos_lote=6000, epocas=10, lr=5e-5, T=26)
else: # más cerca del artículo: SR(U(10, 40)) y su tasa de aprendizaje; el artículo entrenó con millones de problemas
CFG = dict(n_min=10, n_max=40, pares=200000, nodos_lote=12000, epocas=20, lr=2e-5, T=26)
print(CFG)
rnd = random.Random(1)
t0 = time.perf_counter()
datos = []
for _ in range(CFG["pares"]):
n = rnd.randint(CFG["n_min"], CFG["n_max"])
s, u = sr(n, rnd)
datos += [(comprimir(s), n, 1.0), (comprimir(u), n, 0.0)]
print(f"{CFG['pares']} pares generados en {time.perf_counter() - t0:.0f} s")
def lotes(datos, rnd):
orden = list(range(0, len(datos), 2))
rnd.shuffle(orden)
actual, nodos = [], 0
for i in orden:
for j in (i, i + 1): # los dos gemelos van en el mismo lote
cl, n, y = datos[j]
actual.append(datos[j]); nodos += 2 * n + len(cl[1])
if nodos >= CFG["nodos_lote"]:
yield actual
actual, nodos = [], 0
if actual:
yield actual
torch.manual_seed(0)
modelo = NeuroSAT().to(DEV)
opt = torch.optim.Adam(modelo.parameters(), lr=CFG["lr"], weight_decay=1e-10)
t0 = time.perf_counter()
for ep in range(CFG["epocas"]):
perdidas, aciertos, total = [], 0, 0
for b in lotes(datos, rnd):
Mx, flip, grupo, nL, nC = lote([(cl, n) for cl, n, _ in b])
y = torch.tensor([t for _, _, t in b], device=DEV)
logit, *_ = modelo(Mx, flip, grupo, nL, nC, CFG["T"])
loss = F.binary_cross_entropy_with_logits(logit, y)
opt.zero_grad(set_to_none=True)
loss.backward()
nn.utils.clip_grad_norm_(modelo.parameters(), 0.65)
opt.step()
perdidas.append(loss.item()); aciertos += int(((logit > 0).float() == y).sum()); total += len(b)
print(f"época {ep + 1}: pérdida {np.mean(perdidas):.3f}, acierto en entrenamiento {aciertos / total:.1%}, {time.perf_counter() - t0:.0f} s")npm run lab and open the connection link.In the short run the first epoch ends still on the plateau (loss 0.689, accuracy 52.4%); the network escapes during the second: 74.9% at its end and 90.1% after the tenth. This is training accuracy; what matters is performance on new, larger formulas.
from sklearn.cluster import KMeans
@torch.no_grad()
def evaluar(problemas, T):
"""Predicción y decodificación (2-medias sobre los embeddings de literales, como en el artículo)."""
modelo.eval()
Mx, flip, grupo, nL, nC = lote([(comprimir(cl), n) for cl, n in problemas])
logit, _, L, _ = modelo(Mx, flip, grupo, nL, nC, T)
L = L.cpu().numpy()
pred, resueltos, base = (logit > 0).cpu().numpy(), [], 0
for cl, n in problemas:
E = L[base:base + 2 * n]; base += 2 * n
km = KMeans(2, n_init=3, random_state=0).fit(E)
c1, c2 = km.cluster_centers_
pos, neg = E[:n], E[n:]
a = (np.linalg.norm(pos - c1, axis=1) + np.linalg.norm(neg - c2, axis=1)
< np.linalg.norm(pos - c2, axis=1) + np.linalg.norm(neg - c1, axis=1))
resueltos.append(satisface(cl, list(a)) or satisface(cl, list(~a))) # se prueban las dos asignaciones
return pred, np.array(resueltos)
rnd_t = random.Random(99)
N_TEST = 100 if CORTO else 500
prueba = {n: [sr(n, rnd_t) for _ in range(N_TEST)] for n in (10, 20, 40)}
tabla = {}
for n, ps in prueba.items():
sat = [(s, n) for s, _ in ps]; uns = [(u, n) for _, u in ps]
for T in (26, 100, 400):
ps_, rs = evaluar(sat, T)
pu, _ = evaluar(uns, T)
tabla[(n, T)] = dict(acc=float((ps_.sum() + (~pu).sum()) / (2 * len(ps))), acc_sat=float(ps_.mean()),
acc_unsat=float((~pu).mean()), resueltos=float(rs.mean()))
print(f"SR({n:2d}), T = {T:3d}: acierto {tabla[(n, T)]['acc']:.1%} (sat {ps_.mean():.1%}, unsat {(~pu).mean():.1%}), "
f"asignación decodificada en el {rs.mean():.1%} de las satisfacibles")npm run lab and open the connection link.The cell evaluates 100 new pairs each of , and with 26, 100 and 400 iterations. To decode, it clusters literal vectors with 2-means, assigns true to one cluster’s literals and tries both orientations; an assignment counts only if it satisfies the formula, checkable in linear time. Results are overall accuracy; parenthesized satisfiable and unsatisfiable accuracy; and fraction of satisfiable formulas with decoded assignment:
| 95.5 % (91 / 100); 92 % | 97.0 % (94 / 100); 94 % | 97.5 % (95 / 100); 95 % | |
| 83.0 % (71 / 95); 72 % | 91.5 % (87 / 96); 87 % | 94.0 % (89 / 99); 89 % | |
| 69.5 % (75 / 64); 54 % | 73.0 % (86 / 60); 75 % | 78.0 % (94 / 62); 87 % |
Four observations, all consistent with the paper:
- More iterations, more solved problems. On , twice the largest training size, decoded satisfiable formulas rise from 54% with the training’s 26 iterations to 87% with 400. The network learned an iterative procedure; more time takes it farther, as with in the paper.
- Inside its distribution, “satisfiable” comes with a certificate. On and , the fraction with decoded assignment nearly matches satisfiable accuracy (even exceeding it twice: sometimes the model is already in the vectors before the vote says so): when the network correctly says “satisfiable”, it found the model. Not so on : at 26 iterations it classifies 75% of satisfiable formulas correctly but decodes only 54%, so some correct guesses lack a model.
- Outside its distribution it also errs in the other direction. On and it almost never says “satisfiable” for an unsatisfiable formula (95% to 100% accuracy on these), but on it does so for over a third. These errors fail the filter: no satisfying assignment can be decoded from an unsatisfiable formula. If “satisfiable” is accepted only with a checked model, NeuroSAT never lies; sometimes it simply does not answer.
- “Unsatisfiable” has no certificate. Even when correct, the network gives no proof the formula has no model; a complete solver does (a resolution refutation, as CDCL produces).
import z3 # pip install z3-solver; su núcleo SAT es un CDCL (lecciones 12 a 14)
def cdcl_z3(cl, n):
x = [z3.Bool(f"x{v}") for v in range(n)]
s = z3.SolverFor("QF_FD")
s.add([z3.Or([x[abs(l) - 1] if l > 0 else z3.Not(x[abs(l) - 1]) for l in c]) for c in cl])
return s.check() == z3.sat
for n in (20, 40):
t0 = time.perf_counter()
ok_dpll = all(dpll(s, n) is not None and dpll(u, n) is None for s, u in prueba[n])
t_dpll = time.perf_counter() - t0
t0 = time.perf_counter()
ok_z3 = all(cdcl_z3(s, n) and not cdcl_z3(u, n) for s, u in prueba[n])
t_z3 = time.perf_counter() - t0
t0 = time.perf_counter()
evaluar([(s, n) for s, _ in prueba[n]], 26); evaluar([(u, n) for _, u in prueba[n]], 26)
if DEV == "cuda":
torch.cuda.synchronize()
t_nn = time.perf_counter() - t0
print(f"SR({n}), {2 * N_TEST} problemas: DPLL {t_dpll:.2f} s (todos correctos: {ok_dpll}); CDCL de Z3 {t_z3:.2f} s "
f"(todos correctos: {ok_z3}); NeuroSAT con 26 iteraciones y la decodificación {t_nn:.2f} s, sin certificar ninguna insatisfacible")npm run lab and open the connection link.Comparison with complete solvers leaves no doubt. The first cell’s DPLL and Z3’s CDCL decide all 200 and all 200 problems without error, with each answer backed by a checked model or exhaustive search equivalent to a refutation. NeuroSAT, with 26 GPU iterations and decoding, is faster than neither in this run (on , about twenty times slower than DPLL; absolute shared-GPU times vary greatly and Z3’s includes building formulas from Python), and errs on 17% and 30% of problems. The paper concludes likewise: NeuroSAT is interesting for what it reveals about what networks can learn, not as a solver.
@torch.no_grad()
def trayectoria(cl, n, T):
Mx, flip, grupo, nL, nC = lote([(comprimir(cl), n)])
_, _, _, hist = modelo(Mx, flip, grupo, nL, nC, T, guardar=True)
pasos = []
prev = None
for t, L in enumerate(hist, 1):
E = L.cpu().numpy().astype(np.float64)
votos = modelo.L_vote(L).squeeze(1).cpu().numpy()
Ec = E - E.mean(0)
U, S, Vt = np.linalg.svd(Ec, full_matrices=False)
P = Ec @ Vt[:2].T # PCA a 2D de los 2n embeddings de esta iteración
if prev is not None: # signos alineados con la iteración anterior (solo estética)
for j in range(2):
if np.dot(P[:, j], prev[:, j]) < 0:
P[:, j] *= -1
prev = P
km = KMeans(2, n_init=3, random_state=0).fit(E)
c1, c2 = km.cluster_centers_
a = (np.linalg.norm(E[:n] - c1, axis=1) + np.linalg.norm(E[n:] - c2, axis=1)
< np.linalg.norm(E[:n] - c2, axis=1) + np.linalg.norm(E[n:] - c1, axis=1))
insat = min(sum(not any((l > 0) == a[abs(l) - 1] for l in c) for c in cl),
sum(not any((l > 0) == (not a[abs(l) - 1]) for l in c) for c in cl))
var = S[:2] ** 2 / (S ** 2).sum()
pasos.append(dict(p=np.round(P, 3).tolist(), votos=np.round(votos, 3).tolist(), media=float(votos.mean()),
insat=int(insat), asig=a.astype(int).tolist(), var=np.round(var, 3).tolist()))
return pasos
elegida = None
for s, _ in prueba[20]:
tr = trayectoria(s, 20, 60)
primero = next((t for t, p in enumerate(tr, 1) if p["insat"] == 0), None)
if primero is not None and 8 <= primero <= 40:
elegida = (s, tr, primero)
break
if elegida:
s, tr, primero = elegida
print(f"fórmula de SR(20) con {len(s)} cláusulas: la asignación decodificada la satisface desde la iteración {primero}; "
f"voto medio {tr[primero - 2]['media']:.2f} en la anterior y {tr[-1]['media']:.2f} en la 60")
if EXPORTAR:
os.makedirs(EXPORTAR, exist_ok=True)
with open(os.path.join(EXPORTAR, "neurosat.json"), "w", encoding="utf-8") as f:
json.dump(dict(n=20, clausulas=s, pasos=tr, primero=primero, cfg=CFG,
tabla={f"{n}-{T}": v for (n, T), v in tabla.items()}), f)npm run lab and open the connection link.The last cell follows the network on a satisfiable formula with 130 clauses for 60 iterations, saving at each step the PCA projection of 40 literal vectors, votes and assignment from clustering. The figure shows these data. Dynamics match the paper: for eight iterations mean vote is negative and, with fluctuations, increasingly so ( to : weakly “unsatisfiable”), while decoded assignments leave 3 to 6 clauses unsatisfied. At the ninth the assignment satisfies all 130 clauses, although the vote remains negative (); at the twelfth it becomes positive, rises rapidly (3.56 at the fourteenth) and stabilizes at 8.51. Initially mixed vectors form two separated stationary groups: the network found a fixed point encoding the model.
Branching and other learned decisions
The practical question is whether what a network learns can improve an industrial solver without removing its guarantees. NeuroCore (Selsam and Bjørner, 2019) uses a NeuroSAT variant trained to predict variables in a formula’s unsatisfiable core, periodically querying it to adjust VSIDS scores; between queries the solver operates normally. With the standard 5000-second limit, modified MiniSat solves 10% more SAT Competition 2018 problems, Glucose 11% more and Z3 6% more; on difficult scheduling problems Glucose solves 20% more with a one-hour limit. For mixed-integer programming, Khalil and others (2016) and Gasse and others (2019) learn to imitate strong branching, a very good but expensive branching rule, with models costing a fraction. The latter uses a graph network on the variable-constraint bipartite representation, the same idea as NeuroSAT, inside SCIP.
The common pattern: the network does not decide, it suggests; the solver retains propagation, clause learning and certification. Improvements are measured as what they are: problems solved within a time limit versus the same solver without the network.
Per-instance algorithm selection
No SAT solver dominates all instances: local search wins on satisfiable random formulas and cannot solve unsatisfiable ones; CDCL wins on structured ones. Predicting the fastest solver from cheap formula features yields a per-instance portfolio. SATzilla (Xu, Hutter, Hoos and Leyton-Brown, JAIR 2008) uses empirical hardness models: regression models predicting each solver’s time from dozens of features (sizes, ratios, variable-clause graph statistics, and probes: very short unit-propagation and local-search runs). In the 2007 SAT Competition, SATzilla versions won three gold medals, one silver and one bronze, competing with the same solvers they combined.
Lab 3 reproduces the idea on a small scale, with three solvers from the module: the lesson 11 DPLL, a minimal CDCL with 1-UIP analysis and WalkSAT local search. To avoid dependence on the browser clock, cost is measured in clause visits, a deterministic counter incremented whenever a solver examines a clause. Each run has a 30,000-visit cap; hitting it means failure and incurs penalized PAR10 cost (ten times the cap), as in competitions.
import random, time
import numpy as np
TOPE = 30_000 # presupuesto de visitas a cláusulas por ejecución; quien lo agota no resuelve
def aleatoria(n, alfa, rnd):
return [[v * rnd.choice((1, -1)) for v in rnd.sample(range(1, n + 1), 3)] for _ in range(int(alfa * n))]
def nucleo_oculto(n, rnd):
"""Una parte aleatoria fácil y satisfacible sobre x1..x(n-6) y, aparte, un núcleo insatisfacible pequeño: las
ocho cláusulas de 3 literales sobre x(n-5), x(n-4), x(n-3), que van detrás en el orden fijo del DPLL."""
m = n - 6
cl = aleatoria(m, 2.5, rnd)
a, b, c = n - 5, n - 4, n - 3
cl += [[a * s1, b * s2, c * s3] for s1 in (1, -1) for s2 in (1, -1) for s3 in (1, -1)]
return cl
def plantada(n, alfa, rnd):
"""3-SAT con solución plantada: solo se aceptan cláusulas que la cumplen (siempre satisfacible)."""
x = [rnd.random() < 0.5 for _ in range(n + 1)]
cl = []
while len(cl) < int(alfa * n):
c = [v * rnd.choice((1, -1)) for v in rnd.sample(range(1, n + 1), 3)]
if any((l > 0) == x[abs(l)] for l in c):
cl.append(c)
return cl
class SinPresupuesto(Exception):
pass
def dpll(cl, n):
"""DPLL de la lección 11, sin aprendizaje: ramifica en la primera variable libre (orden fijo)."""
asig = [0] * (n + 1)
visitas = 0
def propagar(rastro):
nonlocal visitas
cambio = True
while cambio:
cambio = False
for c in cl:
visitas += 1
libre, nlibres, sat = 0, 0, False
for l in c:
v = asig[abs(l)]
if v == 0:
libre, nlibres = l, nlibres + 1
elif (v > 0) == (l > 0):
sat = True
break
if sat:
continue
if nlibres == 0:
return False
if nlibres == 1:
asig[abs(libre)] = 1 if libre > 0 else -1
rastro.append(abs(libre))
cambio = True
if visitas > TOPE:
raise SinPresupuesto
return True
def rec():
rastro = []
if propagar(rastro):
v = next((i for i in range(1, n + 1) if asig[i] == 0), 0)
if v == 0:
return True
for b in (1, -1):
asig[v] = b
if rec():
return True
asig[v] = 0
for v in rastro:
asig[v] = 0
return False
try:
r = rec()
except SinPresupuesto:
return None, TOPE
return r, visitas
def cdcl(cl, n):
"""CDCL mínimo: propagación por recorrido, análisis 1-UIP, salto no cronológico y actividad tipo VSIDS."""
cl = [list(c) for c in cl]
asig, nivel, razon = [0] * (n + 1), [0] * (n + 1), [None] * (n + 1)
act = [0.0] * (n + 1)
rastro, inc, visitas = [], 1.0, 0
def valor(l):
v = asig[abs(l)]
return 0 if v == 0 else (1 if (v > 0) == (l > 0) else -1)
def asignar(l, d, r):
asig[abs(l)] = 1 if l > 0 else -1
nivel[abs(l)], razon[abs(l)] = d, r
rastro.append(abs(l))
def propagar(d):
nonlocal visitas
cambio = True
while cambio:
cambio = False
for c in cl:
visitas += 1
libres, sat = [], False
for l in c:
v = valor(l)
if v == 1:
sat = True
break
if v == 0:
libres.append(l)
if sat:
continue
if not libres:
return c
if len(libres) == 1:
asignar(libres[0], d, c)
cambio = True
if visitas > TOPE:
raise SinPresupuesto
return None
d = 0
try:
while True:
conf = propagar(d)
if conf is not None:
if d == 0:
return False, visitas
aprendida, vistos, cont = [], set(), 0 # 1-UIP: resolver hacia atrás por el rastro
c, i = conf, len(rastro) - 1
while True:
for l in c:
v = abs(l)
if v not in vistos and nivel[v] > 0:
vistos.add(v)
act[v] += inc
if nivel[v] == d:
cont += 1
else:
aprendida.append(l)
while rastro[i] not in vistos:
i -= 1
v = rastro[i]
cont -= 1
if cont == 0:
aprendida.append(-v if asig[v] > 0 else v)
break
c = [l for l in razon[v] if abs(l) != v]
i -= 1
inc *= 1.05
salto = max((nivel[abs(l)] for l in aprendida[:-1]), default=0)
while rastro and nivel[rastro[-1]] > salto: # salto no cronológico
v = rastro.pop()
asig[v], razon[v] = 0, None
cl.append(aprendida)
d = salto
asignar(aprendida[-1], d, aprendida)
continue
libres = [v for v in range(1, n + 1) if asig[v] == 0]
if not libres:
return True, visitas
v = max(libres, key=lambda u: act[u])
d += 1
asignar(-v, d, None) # primero la fase negativa
except SinPresupuesto:
return None, TOPE
def walksat(cl, n, p=0.5, semilla=0):
"""WalkSAT (lección 11): incompleto; si no encuentra modelo antes del tope, no dice nada."""
rnd = random.Random(semilla)
x = [rnd.random() < 0.5 for _ in range(n + 1)]
apar = [[] for _ in range(n + 1)]
for j, c in enumerate(cl):
for l in c:
apar[abs(l)].append(j)
ncier = [sum((l > 0) == x[abs(l)] for l in c) for c in cl]
insat = {j for j, k in enumerate(ncier) if k == 0}
visitas = len(cl)
while insat:
if visitas > TOPE:
return None, TOPE
c = cl[rnd.choice(tuple(insat))]
def rompe(v):
return sum(1 for j in apar[v] if ncier[j] == 1 and any(abs(l) == v and (l > 0) == x[v] for l in cl[j]))
visitas += sum(len(apar[abs(l)]) for l in c)
b = {abs(l): rompe(abs(l)) for l in c}
v = rnd.choice(list(b)) if (min(b.values()) > 0 and rnd.random() < p) else min(b, key=b.get)
x[v] = not x[v]
for j in apar[v]:
k = sum((l > 0) == x[abs(l)] for l in cl[j])
ncier[j] = k
if k == 0:
insat.add(j)
else:
insat.discard(j)
return True, visitas
rnd = random.Random(7)
FAMILIAS = [("aleatoria α=3.5", lambda: (aleatoria(50, 3.5, rnd), 50)),
("umbral α=4.26", lambda: (aleatoria(40, 4.26, rnd), 40)),
("aleatoria α=5.5", lambda: (aleatoria(30, 5.5, rnd), 30)),
("núcleo oculto", lambda: (nucleo_oculto(36, rnd), 36)),
("plantada α=4.5", lambda: (plantada(50, 4.5, rnd), 50))]
INST = [(nombre, *gen()) for _ in range(24) for nombre, gen in FAMILIAS]
print(len(INST), "instancias")
t0 = time.perf_counter()
R = {"DPLL": [dpll(c, n) for _, c, n in INST]}
print(f"DPLL: {time.perf_counter() - t0:.2f} s")The five families give each solver a niche: underconstrained random 3-SAT (, almost all satisfiable), near threshold (, half and half), overconstrained (, mostly unsatisfiable), formulas with planted solutions, and a structured hidden core: an easy satisfiable random part plus an unsatisfiable core of eight clauses over three variables placed last in the order. DPLL’s fixed order and chronological backtracking refute the core once per assignment of the easy part; none of the 24 instances fits its budget.
t0 = time.perf_counter()
R["CDCL"] = [cdcl(c, n) for _, c, n in INST]
print(f"CDCL: {time.perf_counter() - t0:.2f} s")CDCL is deliberately minimal: it propagates by scanning every clause (without watched literals), learns the 1-UIP clause, backjumps nonchronologically and chooses the highest-activity free variable, without restarts or deletion. That suffices for the hidden core: the first core conflict produces a clause on its variables, backjumping goes directly to their assignment level, and activity puts them first.
t0 = time.perf_counter()
R["WalkSAT"] = [walksat(c, n) for _, c, n in INST]
print(f"WalkSAT: {time.perf_counter() - t0:.2f} s")
for (f, c, n), a, b in zip(INST, R["DPLL"], R["CDCL"]):
assert a[0] is None or b[0] is None or a[0] == b[0] # los completos no se contradicen
SOLVERS = list(R)
PAR10 = 10 * TOPE
coste = np.array([[R[s][i][1] if R[s][i][0] is not None else PAR10 for s in SOLVERS] for i in range(len(INST))])
fam = np.array([f for f, _, _ in INST])
for f, _ in FAMILIAS:
m = fam == f
print(f"{f:16s}", " ".join(f"{s}: resuelve {np.sum(coste[m, j] < PAR10):2d}/24, mediana {np.median(coste[m, j]):7.0f}"
for j, s in enumerate(SOLVERS)),
" mejor:", {s: int(np.sum(np.argmin(coste[m], 1) == j)) for j, s in enumerate(SOLVERS)})The table argues for portfolios. WalkSAT is best on 21 of 24 underconstrained and 16 of 24 planted formulas, with median 2840 and 5899 visits, but solves no unsatisfiable ones: it is incomplete. CDCL solves all overconstrained and hidden-core formulas, which DPLL never solves. Near threshold there is no clear winner: 10 instances for CDCL, 9 for WalkSAT and 5 for DPLL. No single solver approaches an oracle always choosing the best.
Features imitate SATzilla at reduced scale: sizes and ratio , clause lengths, positive-literal proportion, degree statistics in variable-clause and variable graphs (variables are neighbors if they share a clause), and a 1500-visit local-search probe that solves the instance itself if it finds a model. Probe cost is always added to portfolio cost: features are not free. The classifier is a random forest predicting the cheapest solver, evaluated with family-stratified cross-validation.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
SONDA = 1500 # presupuesto de la sonda de búsqueda local (SATzilla también usa sondas: «probing features»)
def sonda(cl, n):
"""WalkSAT con un tope pequeño: si resuelve, la instancia está resuelta; si no, cuánto se acercó."""
global TOPE
viejo, TOPE = TOPE, SONDA
try:
ok, gasto = walksat(cl, n, semilla=1)
finally:
TOPE = viejo
return ok is True, gasto
def caracteristicas(cl, n):
m = len(cl)
grado = np.zeros(n + 1)
vecinos = [set() for _ in range(n + 1)]
pos = []
for c in cl:
vs = [abs(l) for l in c]
for v in vs:
grado[v] += 1
vecinos[v].update(vs)
pos.append(sum(l > 0 for l in c) / len(c))
g = grado[1:] / m
gv = np.array([len(vecinos[v]) - 1 for v in range(1, n + 1)]) / n
resuelta, gasto = sonda(cl, n)
return [n, m, m / n, np.mean([len(c) for c in cl]), np.mean(pos), np.std(pos),
g.mean(), g.std(), g.min(), g.max(), gv.mean(), gv.std(), float(resuelta)], resuelta, gasto
NOMBRES = ["n", "m", "m/n", "long. media", "frac. positivos", "desv. positivos", "grado medio", "desv. grado",
"grado mín.", "grado máx.", "grado VG medio", "desv. grado VG", "sonda resuelve"]
t0 = time.perf_counter()
F = [caracteristicas(c, n) for _, c, n in INST]
X = np.array([f[0] for f in F]); sonda_ok = np.array([f[1] for f in F]); sonda_coste = np.array([f[2] for f in F])
y = np.argmin(coste, axis=1) # etiqueta: el resolvedor más barato
print(f"características en {time.perf_counter() - t0:.2f} s; la sonda resuelve {sonda_ok.sum()} instancias")
pred = np.zeros(len(INST), dtype=int)
for tr, te in StratifiedKFold(5, shuffle=True, random_state=0).split(X, fam):
rf = RandomForestClassifier(200, random_state=0).fit(X[tr], y[tr])
pred[te] = rf.predict(X[te])
idx = np.arange(len(INST))
coste_port = np.where(sonda_ok, sonda_coste, sonda_coste + coste[idx, pred]) # la sonda se paga siempre
resuelve_port = sonda_ok | (coste[idx, pred] < PAR10)
sbs = int(np.argmin(coste.mean(0)))
vbs = coste.min(1)
print(f"{'':28s}{'PAR10 medio':>12s}{'resueltas':>11s}")
for nombre, c, r in [(f"cada uno: {s}", coste[:, j], coste[:, j] < PAR10) for j, s in enumerate(SOLVERS)] + [
("portfolio (validación cruzada)", coste_port, resuelve_port), ("oráculo (VBS)", vbs, vbs < PAR10)]:
print(f"{nombre:28s}{c.mean():12.0f}{r.sum():8d}/{len(INST)}")
hueco = (coste[:, sbs].mean() - coste_port.mean()) / (coste[:, sbs].mean() - vbs.mean())
print(f"mejor resolvedor único (SBS): {SOLVERS[sbs]}; el portfolio cierra el {hueco:.0%} del hueco entre el SBS y el oráculo")
print(f"elige el mejor en el {np.mean(pred == y):.0%} de las instancias")
rf = RandomForestClassifier(200, random_state=0).fit(X, y)
print("características más usadas:", ", ".join(f"{NOMBRES[i]} ({rf.feature_importances_[i]:.2f})"
for i in np.argsort(-rf.feature_importances_)[:4]))
for f, _ in FAMILIAS:
m = fam == f
print(f" {f:16s} portfolio {coste_port[m].mean():7.0f} {SOLVERS[sbs]} {coste[m, sbs].mean():7.0f} oráculo {vbs[m].mean():7.0f}")The best single solver is CDCL, with mean PAR10 36,547 visits and 109 of 120 instances solved. The portfolio reduces this to 30,751 and solves 111; an oracle reaches 13,920 and 117. Thus the portfolio closes only 26% of the gap between best single solver and oracle, although it identifies the cheapest solver on 72% of instances. Family breakdown explains why. On underconstrained and planted formulas the portfolio clearly wins by learning to send them to WalkSAT (5578 versus CDCL’s 34,374 on underconstrained). Near threshold it loses: 99,010 versus CDCL alone at 75,288. There the correct class depends on satisfiability, which no cheap feature predicts, and each unsatisfiable formula sent to WalkSAT incurs the full penalty. On hidden core it pays for the probe (4481 versus 2981).
Two lessons. First, errors do not cost the same: choosing WalkSAT for an unsatisfiable formula costs ten times the cap, while choosing CDCL for an easy satisfiable formula costs a few thousand visits. A classifier minimizing errors does not minimize cost; later SATzilla versions therefore used cost-sensitive classifiers. Second, measure a portfolio against the best single solver and the oracle, and report the fraction of the gap closed. Accuracy of 72% sounds good, yet here it leaves three quarters of the opportunity unused.
What actually worked
In perspective, the balance is clear. What reached solvers people use is learning around the solver: per-instance selection (SATzilla and successors), automatic parameter configuration and portfolios. Learned suggestions inside search produce moderate real gains when they respect the engine, as with NeuroCore. End-to-end learned solvers such as NeuroSAT are valuable scientific instruments (showing a network can discover search from one bit), but do not compete on speed or reliability: they cannot certify unsatisfiability and accuracy falls with size.
Language models as planners
Evidence: PlanBench and obfuscation
When large language models appeared, many papers showed reasonable plans for everyday tasks. The problem is that everyday tasks cannot distinguish planning from remembering: coffee-making plans are in training corpora. Valmeekam, Marquez, Olmo, Sreedharan and Kambhampati built PlanBench to separate the two: generate random instances of international planning competition domains (blocksworld, logistics), request a plan in natural language or PDDL, and check it with VAL, the standard plan validator. PlanBench evaluates eight capabilities (plan generation, optimal-cost planning, verification, execution reasoning, robustness to reformulated goals, reuse, replanning and generalization); the first matters here.
Its key control is Mystery Blocksworld: the same domain with action and predicate names replaced by unrelated (or random) words. A classical planner sees exactly the same problem: only symbols. A genuinely planning model should too. Results (Valmeekam and others, NeurIPS 2023) for GPT-4 on 600 natural-language block instances:
| Configuration | Blocksworld | Mystery Blocksworld (misleading obfuscation) |
|---|---|---|
| No examples | 210/600 (34.6 %) | 1/600 (0.16 %) |
| One example | 206/600 (34.3 %) | 26/600 (4.3 %) |
With random names, zero of 600 without examples. In logistics, 28 of 200 with one example (14%). The paper reports roughly 12% mean GPT-4 autonomous-generation success across domains. The drop under obfuscation is key: if performance depends on names like “pick-up” and “stack”, the model relies on what it knows about blocks rather than the action model in the prompt.
The paper tests the other side too: using VAL to feed back to the model. For 50 failed GPT-4 instances, it returns the first plan error (an unmet precondition or goal) and requests another, up to 15 times. It solves 41 of 50 in blocks (82%, averaging 3.68 rounds among successes), 35 of 50 in logistics (70%, 3.31 rounds), and only 5 of 50 in Mystery Blocksworld (10%, 7.0 rounds).
LLM-Modulo: generate and verify
The paper’s two-part thesis: autoregressive language models cannot plan or verify their own plans “by themselves”, but are useful approximate sources of knowledge and candidates in a framework with external verifiers. Correctness is gained: a plan accepted by a correct validator is valid. Completeness is not: if the generator never proposes a valid plan, the loop cannot find one, while a complete classical planner would.
The basic calculation is a Bernoulli experiment. If each attempt independently produces a valid plan with probability and the verifier is perfect, attempts until first success are geometric:
Feedback breaks independence, and that is its value: a precise diagnosis (“step 3 requires to be clear”) can raise the next attempt’s probability above . If it does not, the feedback loop is no better than independent samples and costs more because each round lengthens context. This comparison should always be made, as the lab does.
LLM+P: the model as translator
Pattern 3 offers another division. LLM+P (Liu and others, 2023) gives the model one natural-language problem and its PDDL translation, asks it to translate a new problem, and solves the resulting PDDL with Fast Downward (optimal SEQ-OPT-FDSS-1 configuration and, after a 200-second timeout, LAMA). In seven competition domains with 20 generated problems each, optimal blocksworld plans were 90% with LLM+P versus 15% direct model planning (30% including correct nonoptimal plans) and 0% (5%) with Tree of Thoughts. Without the translation example, LLM+P fell to 0% in every domain: failures were malformed problem files (a missing initial condition), not the planner. Translation also failed in domains with complex spatial relations: Floortile, 0% for all five methods. LLM+P moves risk from planning to translation, which is easier to inspect but equally capable of ruining the result.
Lab 4: generate and verify with a local language model
You will build the smallest meaningful LLM-Modulo loop: a local language model proposes blocksworld plans, a symbolic validator built from scratch checks them, and its first error returns to the model as a new request. Three comparisons make it an experiment: with and without feedback, against repeated samples without feedback (the same number of plans), and with obfuscated domain names. The classical planner is breadth-first search, finding optimal plans in milliseconds at these sizes.
The domain is the four-action one from the classical planning lesson, expressed as STRIPS facts. The model receives a natural-language prompt, as in PlanBench: action descriptions with preconditions and effects, a solved three-block example and the problem. The obfuscated version changes actions to zorp, blick, quan and drel, and predicates to nonsense phrases (“a tarns b”, “calm holds”), as in Mystery Blocksworld: validator and breadth-first search see exactly the same problem. The generator is Qwen2.5-3B-Instruct (3090 million parameters, about 6.2 GB in bfloat16; with less GPU memory, change MODELO to the 0.5B version), using greedy decoding in the loop and temperature 0.7 for independent samples. The short run uses 6 instances with 3 and 6 with 4 blocks, at most 4 plans in the loop and 16 independent samples per instance; the full run uses 50 instances each of 3, 4 and 5 blocks, 10 plans and 32 samples.
import os, re, json, time, random, itertools
from collections import deque
CORTO = os.environ.get("ORYON_VERIFY_SHORT") == "1"
EXPORTAR = os.environ.get("ORYON_EXPORT_DIR")
def estado_de_torres(torres):
"""torres: lista de listas de abajo arriba -> conjunto de hechos STRIPS."""
h = {("handempty",)}
for t in torres:
h.add(("ontable", t[0]))
for a, b in zip(t[1:], t[:-1]):
h.add(("on", a, b))
h.add(("clear", t[-1]))
return frozenset(h)
def acciones(bloques):
"""Las cuatro acciones del dominio de la lección 20, instanciadas: (nombre, args, pre, add, del)."""
A = []
for x in bloques:
A.append(("pick-up", (x,), {("clear", x), ("ontable", x), ("handempty",)},
{("holding", x)}, {("clear", x), ("ontable", x), ("handempty",)}))
A.append(("put-down", (x,), {("holding", x)}, {("clear", x), ("handempty",), ("ontable", x)}, {("holding", x)}))
for y in bloques:
if x != y:
A.append(("stack", (x, y), {("holding", x), ("clear", y)},
{("on", x, y), ("clear", x), ("handempty",)}, {("holding", x), ("clear", y)}))
A.append(("unstack", (x, y), {("on", x, y), ("clear", x), ("handempty",)},
{("holding", x), ("clear", y)}, {("on", x, y), ("clear", x), ("handempty",)}))
return {(a[0], a[1]): a for a in A}
def plan_optimo(s0, meta, A):
"""Búsqueda en anchura: plan más corto (el espacio es pequeño con 3 a 6 bloques)."""
padre = {s0: None}
cola = deque([s0])
while cola:
s = cola.popleft()
if meta <= s:
plan = []
while padre[s]:
s, a = padre[s]
plan.append(a)
return plan[::-1]
for (n, args), (_, _, pre, add, dele) in A.items():
if pre <= s:
t = (s - dele) | add
if t not in padre:
padre[t] = (s, (n, args))
cola.append(t)
return None
def instancia(n, rnd):
"""Configuración inicial y meta aleatorias (particiones aleatorias en torres) con al menos un 'on' por cumplir."""
def torres():
b = [chr(97 + i) for i in range(n)]
rnd.shuffle(b)
ts, i = [], 0
while i < n:
k = rnd.randint(1, n - i)
ts.append(b[i:i + k])
i += k
return ts
while True:
s0 = estado_de_torres(torres())
meta = frozenset(h for h in estado_de_torres(torres()) if h[0] == "on")
if meta and not meta <= s0:
return s0, meta
# --- lenguaje: nombres normales u ofuscados (al estilo de Mystery Blocksworld de PlanBench) ---
NORMAL = dict(acc={"pick-up": "pick-up", "put-down": "put-down", "stack": "stack", "unstack": "unstack"},
on="{0} is on top of {1}", ontable="{0} is on the table", clear="{0} is clear",
handempty="the hand is empty", holding="the hand is holding {0}")
OFUSCADO = dict(acc={"pick-up": "zorp", "put-down": "blick", "stack": "quan", "unstack": "drel"},
on="{0} tarns {1}", ontable="{0} is vesk", clear="{0} is lumo",
handempty="calm holds", holding="griff {0}")
def describe(h, L):
return L[h[0]].format(*h[1:])
def dominio(L):
a = L["acc"]
d = lambda f, *x: L[f].format(*x)
return (f"I am manipulating objects. The actions I can do are:\n"
f"({a['pick-up']} X): requires {d('clear', 'X')}, {d('ontable', 'X')} and {d('handempty')}. "
f"Afterwards {d('holding', 'X')}; {d('clear', 'X')}, {d('ontable', 'X')} and {d('handempty')} stop being true.\n"
f"({a['put-down']} X): requires {d('holding', 'X')}. Afterwards {d('clear', 'X')}, {d('ontable', 'X')} "
f"and {d('handempty')}; {d('holding', 'X')} stops being true.\n"
f"({a['stack']} X Y): requires {d('holding', 'X')} and {d('clear', 'Y')}. Afterwards {d('on', 'X', 'Y')}, "
f"{d('clear', 'X')} and {d('handempty')}; {d('holding', 'X')} and {d('clear', 'Y')} stop being true.\n"
f"({a['unstack']} X Y): requires {d('on', 'X', 'Y')}, {d('clear', 'X')} and {d('handempty')}. Afterwards "
f"{d('holding', 'X')} and {d('clear', 'Y')}; {d('on', 'X', 'Y')}, {d('clear', 'X')} and {d('handempty')} stop being true.\n")
def enunciado(s0, meta, L):
ini = "; ".join(sorted(describe(h, L) for h in s0))
obj = "; ".join(sorted(describe(h, L) for h in meta))
return f"Initial state: {ini}.\nGoal: {obj}."
def plan_a_texto(plan, L):
return "\n".join(f"({L['acc'][n]} {' '.join(args)})" for n, args in plan)
def validar(texto, s0, meta, A, L):
"""Devuelve (válido, mensaje). Señala el PRIMER error: acción ilegible, precondición violada o meta incumplida."""
inv = {v: k for k, v in L["acc"].items()}
pasos = re.findall(r"\(([a-z\-]+)((?:\s+[a-z])+)\s*\)", texto.lower())
if not pasos:
return False, "I could not find any action in your answer. Write one action per line, like (" + L["acc"]["pick-up"] + " a)."
s = s0
for i, (n, args) in enumerate(pasos, 1):
args = tuple(args.split())
clave = (inv.get(n), args)
if clave not in A:
return False, f"Step {i}, ({n} {' '.join(args)}), is not a valid action of this domain."
_, _, pre, add, dele = A[clave]
falta = sorted(pre - s)
if falta:
return False, (f"Step {i}, ({n} {' '.join(args)}), cannot be applied: it requires "
+ " and ".join(describe(h, L) for h in falta) + ", which is false at that point.")
s = (s - dele) | add
falta = sorted(meta - s)
if falta:
return False, ("All actions are applicable, but at the end the goal is not reached: "
+ " and ".join(describe(h, L) for h in falta) + " is false.")
return True, f"Valid plan with {len(pasos)} actions."
rnd = random.Random(0)
TAMANOS = [3, 4] if CORTO else [3, 4, 5]
POR_TAMANO = 6 if CORTO else 50
INSTANCIAS = []
for n in TAMANOS:
for _ in range(POR_TAMANO):
s0, meta = instancia(n, rnd)
A = acciones([chr(97 + i) for i in range(n)])
t0 = time.perf_counter()
p = plan_optimo(s0, meta, A)
INSTANCIAS.append(dict(n=n, s0=s0, meta=meta, A=A, opt=p, t_bfs=time.perf_counter() - t0))
# el validador acepta los planes óptimos y rechaza uno al que se le quita la primera acción
assert all(validar(plan_a_texto(x["opt"], NORMAL), x["s0"], x["meta"], x["A"], NORMAL)[0] for x in INSTANCIAS)
assert all(validar(plan_a_texto(x["opt"], OFUSCADO), x["s0"], x["meta"], x["A"], OFUSCADO)[0] for x in INSTANCIAS)
x = INSTANCIAS[0]
print(validar(plan_a_texto(x["opt"][1:], NORMAL), x["s0"], x["meta"], x["A"], NORMAL))
for n in TAMANOS:
sub = [x for x in INSTANCIAS if x["n"] == n]
print(f"{n} bloques: {len(sub)} instancias, plan óptimo medio {sum(len(x['opt']) for x in sub) / len(sub):.1f} acciones, "
f"BFS {1000 * max(x['t_bfs'] for x in sub):.1f} ms como mucho")npm run lab and open the connection link.The validator supplies guarantees, so it is tested first: it accepts all optimal instance plans with normal and obfuscated names, and rejects a plan missing its first action, identifying the failed precondition (“Step 1, (stack b a), cannot be applied: it requires the hand is holding b”). Like VAL in PlanBench, it reports only the first error: after an inapplicable action the state is undefined. Breadth-first search solves every instance optimally in at most one millisecond; optimal plans average 6.0 actions with three blocks and 5.7 with four (goals are random and the four-block ones happened to be easier).
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import gc
MODELO = "Qwen/Qwen2.5-3B-Instruct" # unos 6.2 GB en bfloat16; con menos memoria, "Qwen/Qwen2.5-0.5B-Instruct"
for viejo in ("red", "objetivo", "opt", "modelo"): # si vienes de los laboratorios 1 y 2 en la misma sesión, libera sus redes
globals().pop(viejo, None)
gc.collect()
torch.cuda.empty_cache()
print(f"memoria libre en la GPU: {torch.cuda.mem_get_info()[0] / 2**30:.1f} GB")
tok = AutoTokenizer.from_pretrained(MODELO)
lm = AutoModelForCausalLM.from_pretrained(MODELO, dtype=torch.bfloat16, device_map="cuda")
lm.eval()
print(f"{MODELO}: {sum(p.numel() for p in lm.parameters()) / 1e9:.2f} miles de millones de parámetros")
EJEMPLO = None
def mensajes_iniciales(x, L):
ej = EJEMPLO
sis = "You are a careful planner. Answer only with the plan, one action per line, and nothing else."
u = (dominio(L) + "\nHere is an example.\n" + enunciado(ej["s0"], ej["meta"], L) + "\nPlan:\n"
+ plan_a_texto(ej["opt"], L) + "\n\nNow solve this problem.\n" + enunciado(x["s0"], x["meta"], L) + "\nPlan:")
return [{"role": "system", "content": sis}, {"role": "user", "content": u}]
@torch.no_grad()
def generar(msgs, n_bloques, k=1, semilla=0):
"""k = 1: decodificación voraz. k > 1: k muestras independientes (temperatura 0.7) en un solo lote.
Tope de 16 (n + 1) tokens: sobra para cualquier plan razonable (cada acción ocupa unos 6 tokens)."""
ids = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda")
torch.manual_seed(semilla)
muestreo = k > 1
out = lm.generate(**ids, max_new_tokens=16 * (n_bloques + 1), do_sample=muestreo, num_return_sequences=k,
temperature=0.7 if muestreo else None, top_p=0.95 if muestreo else None, top_k=None,
pad_token_id=tok.eos_token_id)
nuevos = out[:, ids["input_ids"].shape[1]:]
textos = tok.batch_decode(nuevos, skip_special_tokens=True)
ntok = int((nuevos != tok.eos_token_id).sum())
return (textos[0] if k == 1 else textos), ntok
def bucle(x, L, rondas):
"""Generar y verificar con realimentación (como en PlanBench): hasta `rondas` planes; cada error vuelve al modelo."""
msgs = mensajes_iniciales(x, L)
traza, tokens = [], 0
for r in range(rondas):
txt, nt = generar(msgs, x["n"])
tokens += nt
ok, msg = validar(txt, x["s0"], x["meta"], x["A"], L)
traza.append(dict(plan=txt.strip(), ok=ok, msg=msg))
if ok:
return True, r + 1, tokens, traza
msgs = msgs + [{"role": "assistant", "content": txt},
{"role": "user", "content": msg + " Please give a new complete plan from the initial state."}]
return False, rondas, tokens, traza
def intentos_independientes(x, L, k, semilla):
"""Generar y verificar SIN realimentación: k muestras independientes. Devuelve qué muestras son válidas y la
primera válida (o None)."""
textos, ntok = generar(mensajes_iniciales(x, L), x["n"], k=k, semilla=semilla)
validas = [validar(t, x["s0"], x["meta"], x["A"], L)[0] for t in textos]
return validas, next((t.strip() for t, v in zip(textos, validas) if v), None), ntok
rnd_ej = random.Random(123)
s0, meta = instancia(3, rnd_ej)
A3 = acciones(["a", "b", "c"])
EJEMPLO = dict(s0=s0, meta=meta, opt=plan_optimo(s0, meta, A3))
print(enunciado(EJEMPLO["s0"], EJEMPLO["meta"], NORMAL))
print(plan_a_texto(EJEMPLO["opt"], NORMAL))npm run lab and open the connection link.The example is the same for all instances: three blocks and an optimal four-action plan starting by dismantling a tower. The experiment compares two ways to spend generator compute. The feedback loop uses greedy decoding and after each rejection adds the plan and validator message to the conversation, requesting a new complete plan: PlanBench’s VAL scheme. Independent samples request the same prompt times at temperature 0.7 without feedback and retain any validator-accepted plan. If feedback helps, a loop with plans should beat independent samples; otherwise the validator’s information adds nothing for this model.
RONDAS = 4 if CORTO else 10 # planes como mucho en el bucle con realimentación
K_IND = 16 if CORTO else 32 # muestras independientes por instancia
resultados = {}
t0 = time.perf_counter()
for nombre, L in (("normal", NORMAL), ("ofuscado", OFUSCADO)):
filas = []
for i, x in enumerate(INSTANCIAS):
ok, r, ntok, traza = bucle(x, L, RONDAS)
validas, muestra, ntok_ind = intentos_independientes(x, L, K_IND, semilla=i)
filas.append(dict(n=x["n"], ok=ok, rondas=r, tokens=ntok, tokens_ind=ntok_ind, traza=traza,
ind=sum(validas), ind_r=any(validas[:RONDAS]), muestra=muestra, opt=len(x["opt"]),
enunciado=enunciado(x["s0"], x["meta"], L), plan_opt=plan_a_texto(x["opt"], L)))
resultados[nombre] = filas
print(f"--- nombres {'normales' if nombre == 'normal' else 'ofuscados'} ({time.perf_counter() - t0:.0f} s)")
for n in TAMANOS:
sub = [f for f in filas if f["n"] == n]
print(f" {n} bloques ({len(sub)}): primer intento {sum(f['traza'][0]['ok'] for f in sub)}, "
f"bucle con realimentación (<= {RONDAS} planes) {sum(f['ok'] for f in sub)}, "
f"alguna de {RONDAS} muestras {sum(f['ind_r'] for f in sub)}, alguna de {K_IND} muestras {sum(f['ind'] > 0 for f in sub)} "
f"(válidas: {sum(f['ind'] for f in sub)} de {K_IND * len(sub)} muestras)")
errores = [ronda["msg"].split(",")[0] if ronda["msg"].startswith("Step") else ronda["msg"][:40]
for f in filas for ronda in f["traza"] if not ronda["ok"]]
primer_paso = sum(e == "Step 1" for e in errores)
print(f" {len(errores)} planes rechazados en los bucles; en {primer_paso} el error está ya en la primera acción")
for nombre, filas in resultados.items():
ok = [f for f in filas if f["muestra"]]
if ok:
largo = [len(re.findall(r"\(", f["muestra"])) / f["opt"] for f in ok]
print(f"{nombre}: muestras válidas con {sum(largo) / len(largo):.2f} veces las acciones del plan óptimo de media")
print(f"{nombre}: tokens generados por instancia: {sum(f['tokens'] for f in filas) / len(filas):.0f} en el bucle, "
f"{sum(f['tokens_ind'] for f in filas) / len(filas):.0f} en las {K_IND} muestras")
if EXPORTAR: # datos de la figura: tasas por tamaño y algunos ejemplos con su traza completa
out = dict(modelo=MODELO.split("/")[-1], rondas=RONDAS, k_ind=K_IND, agg={}, ejemplos={})
for nombre, filas in resultados.items():
out["agg"][nombre] = {str(n): dict(total=len(sub), primer=sum(f["traza"][0]["ok"] for f in sub),
bucle=sum(f["ok"] for f in sub), ind_r=sum(f["ind_r"] for f in sub),
ind=sum(f["ind"] > 0 for f in sub))
for n in TAMANOS for sub in [[f for f in filas if f["n"] == n]]}
# primero las instancias con alguna muestra válida o un éxito en el bucle; después, una fallida por tamaño
ej = [f for f in filas if f["ok"] or f["muestra"]]
for n in TAMANOS:
x = next((f for f in filas if f["n"] == n and not f["ok"] and not f["muestra"]), None)
if x is not None:
ej.append(x)
out["ejemplos"][nombre] = [{k: f[k] for k in ("n", "enunciado", "plan_opt", "opt", "ok", "rondas", "traza",
"muestra", "ind")} for f in ej[:8]]
os.makedirs(EXPORTAR, exist_ok=True)
with open(os.path.join(EXPORTAR, "loop.json"), "w", encoding="utf-8") as f:
json.dump(out, f, ensure_ascii=False)
del lm
torch.cuda.empty_cache()npm run lab and open the connection link.The short run’s result is striking and deserves careful reading:
- The model does not plan. None of 12 instances is solved on the first attempt with either normal or obfuscated names, nor does the four-plan loop solve any. Of the 48 plans rejected in normal-name loops, 35 fail at the first action: the model proposes
(pick-up d)whendis on another block, or(unstack a b)whenahas another block on top. The problem is not long plans but failure to respect preconditions written in the prompt. - Feedback does not help this generator. After the validator message the model changes plans but does not correct them: figure traces repeat an error, exchange one failure for another or lengthen the plan so failure occurs later. Compare GPT-4 in PlanBench, rising from 34% to 82% with the same type of message. Feedback is only as useful as what the generator can do with it.
- Sampling and verification find something. With 16 independent samples per instance, the validator accepts 6 of 192 normal-name samples (3.1%), distributed over 2 of 12 instances, both with four blocks; accepted plans have exactly optimal length. With 4 samples, one instance succeeds. The validator turns an almost-always-wrong generator into a procedure that is correct whenever it returns something.
- Obfuscation shuts it down. With nonsense names, 0 of 192 samples are valid. As with Mystery Blocksworld, the model’s few successes rely on what it knows about “pick-up” and “stack”, not the prompt’s preconditions.
- The classical planner optimally solves all 12 instances in at most one millisecond each.
Two methodological cautions. With 12 instances, “0 of 12” does not mean a zero rate: the exact 95% confidence interval for 0 successes out of 12 extends to 26%. The full configuration (150 instances, 10 plans per loop, 32 samples) gives finer estimates. Cost matters too: with normal names, the loop generated a mean 121 tokens per instance and 16 samples 437. Samples cost more tokens and less waiting time because they are generated in one batch.
Program search with an evaluator: FunSearch
FunSearch (Romera-Paredes and others, Nature 2024) applies generate-and-verify to a different object: it searches for a program that constructs a solution, not a solution itself. The user writes a Python skeleton with a function to evolve (for example priority(v, n), deciding the order of adding vectors to a set) and an evaluate function that runs and scores the program. A code language model (Codey, from PaLM 2) receives two good database programs in score order in its prompt and writes a new version; evaluators run it, discard failures and nonterminating programs, and store the rest with scores. For diversity, the database is divided into separately evolving islands; periodically the worst half are emptied and repopulated by cloning the best from the others, a genetic-algorithm island model.
For cap set (the largest subset of without three collinear points), FunSearch found a 512-element set in dimension , exceeding the previous best, and by searching a more restricted program space (admissible sets) improved the asymptotic capacity lower bound from 2.2180 to 2.2202. In online bin packing it found heuristics better than first fit and best fit on OR1–OR4 benchmarks and Weibull-distributed instances. Two details matter. First, cost: results use on the order of model samples, and only 4 of 140 dimension-8 cap-set experiments reached 512. Second, the guarantee: correctness comes from the evaluator checking that the generated set is a cap set, not the model. The model biases toward short readable programs, yielding programs people can understand and generalize by hand, unlike a raw solution.
This is the same loop as counterexample-guided synthesis from the Z3 lesson, with two changes: a language model replaces the solver as generator, and the verifier scores instead of returning a counterexample.
Neural-guided theorem proving
The problem and division of work
An interactive prover (Lean, Isabelle, Coq, Metamath) maintains a proof state: assumptions and remaining goals. The user applies tactics, small programs transforming the state (introducing a variable, rewriting using a lemma, induction), and the prover’s kernel checks each step. Finding a proof searches a tree with effectively infinite branching: tactics can contain arbitrary terms. Classical automated provers, such as the resolution systems in lesson 16, struggle in that space. These systems share pattern 1: a network proposes tactics or steps and a formal prover verifies each, making every found proof correct.
GPT-f and LeanDojo
GPT-f (Polu and Sutskever, 2020) trains a transformer to generate the next Metamath proof step and uses it in best-first search with a learned value retrained on proofs the system finds itself (a form of expert iteration). It proves 56.22% of held-out test theorems versus 21.16% for the previous best, MetaGen-IL. Its results table illustrates cumulative ablation: a 160-million-parameter transformer reaches 28.96%, 700 million reaches 31.58%, web-math pretraining 42.56%, iterated value 47.21%, and more search compute (32 attempts per theorem) 56.50%, all on validation. It also contributed 23 shorter proofs accepted into Metamath’s main library.
LeanDojo (Yang and others, NeurIPS 2023) is open infrastructure for Lean: it extracts mathlib data, enables Python interaction with the prover, and annotates premises (library lemmas) used at each step. Its prover ReProver adds retrieval: before generating a tactic, it finds the most relevant accessible premises and puts them in context. The benchmark has 98,734 theorems and two splits, random and novel_premises, where every test proof uses at least one premise absent from all training proofs. Percentage of theorems proved (Pass@1):
| Method | Random | novel_premises |
|---|---|---|
tidy (mathlib heuristic tactic, no learning) | 23.8 | 5.3 |
| GPT-4 generating tactics | 29.0 | 7.4 |
| ReProver without retrieval | 47.6 | 23.2 |
| ReProver | 51.2 | 26.3 |
Three methodological lessons in one table: a nonlearned baseline (tidy) solves nearly a quarter of the random split; a difficult split halves everyone’s performance because random splitting rewards memorizing which premises are used; and the authors caution that GPT-4 performs much worse “although it may have seen the true proofs through data contamination”.
AlphaGeometry and AlphaGeometry2
Olympiad geometry has its own problem: almost no formal proofs to train on. AlphaGeometry (Trinh, Wu, Le, He and Luong, Nature 2024) avoids this by generating millions of synthetic theorems and proofs: sample random figures, use a symbolic engine to deduce everything that follows, and extract each conclusion’s minimal proof. When a proof needs points absent from the statement, those points are auxiliary constructions, used to train a language model. At inference the deductive engine (DD+AR: geometric-rule deduction plus algebraic reasoning about angles, ratios and distances) tries to close the proof; if it cannot, the model proposes a construction and the engine tries again.
On 30 recent olympiad problems expressible in its language (IMO-AG-30), AlphaGeometry solves 25 versus 10 for the prior best. AlphaGeometry2 (Chervonyi and others, 2025) extends the language (covering 88% of IMO geometry problems from 2000 to 2024, versus 66%), accelerates the symbolic engine (over 300 times in its speed test) and uses a Gemini-based model with several knowledge-sharing search trees; it solves 42 of the 50 IMO geometry problems from 2000 to 2024 (84%, versus 54% for the first version). The paper’s table is an excellent baseline lesson:
| System | IMO-AG-50 | IMO-AG-30 |
|---|---|---|
| Deductive engine alone (AG1) | 14 | 14 |
| Deductive engine alone (AG2) | 16 | 15 |
| Wu’s method (algebra, no learning) plus AG1 engine | 21 | |
| AlphaGeometry (AG1) | 27 | 25 |
| AlphaGeometry2 | 42 | 30 |
| Average gold medalist | 40.9 | 25.9 |
The symbolic engine alone solves over half of AG1’s solved problems, and a 1978 algebraic method combined with it (Sinha and others, 2024) reaches 21 of 30. The language model’s contribution is real (14 to 25), but measurable only because the table includes those rows.
AlphaProof: AlphaZero over Lean proofs
AlphaProof (Hubert, Mehta, Sartran and others, Nature 2025) applies the AlphaZero recipe to Lean. State is the Lean proof state, actions are tactics (text strings), and reward comes from completing a proof. A 3000-million-parameter encoder-decoder network jointly produces candidate tactics (policy) and return estimate (value), guiding tree search with AND nodes when a tactic splits a goal into independent subgoals. To obtain enough training problems, autoformalization translates about 1 million natural-language statements into about 80 million formal problems (pattern 3 serving pattern 1). For the hardest problems it adds test-time reinforcement learning: generate millions of problem variants and train a specialized network on them.
At IMO 2024, with the five nongeometry problems manually formalized by experts, AlphaProof solved three (P1, P2 and P6, the last the competition’s hardest, solved by only five contestants), and AlphaGeometry 2 solved geometry problem P4: 28 points, equivalent to a silver medal. Each AlphaProof solution needed 2 to 3 days of test-time learning. Read this with three facts in view: humans formalized statements (though a separate experiment showed the autoformalizer also correctly formalized P1, P2 and P6), compute took days versus contestants’ nine hours, and proofs were checked by Lean’s kernel, so correctness does not depend on trusting the model.
Open questions
- Systematic generalization. NeuroSAT extrapolates somewhat to larger formulas with more iterations; DeepCubeA cannot move from 15- to 24-puzzle without retraining; lab 1 network mean error increases more than fourfold (0.39 to 1.74 moves) on states farther than its training distribution. What architectures and data produce procedures that work out of distribution? Ståhlberg, Bonet and Geffner suggest the answer involves architectural logical expressiveness, not just more data.
- Verifying reasoning without a perfect verifier. The lesson’s positive results rely on correct, cheap verifiers: VAL, Lean’s kernel, FunSearch’s evaluator. With an approximate verifier (a judging model or incomplete tests), the calculation changes: if it accepts an invalid plan with probability and a valid one with probability , the fraction of accepted plans that are valid is , which can be low for small even if is small. This is the imperfect verifier problem in reasoning models.
- Inference compute. AlphaProof uses days per problem; FunSearch a million samples; GPT-f gains nine points with 32 attempts per theorem. When is spending compute on more search better than on a larger model? This is compute-optimal test time, with a measurable answer in domains with exact verifiers.
- Attribution. How much success comes from neural versus symbolic components? AlphaGeometry answers with an ablation; many papers do not.
How to read and reproduce a paper in the field
Almost all papers at this frontier compare a new system with something. A fair comparison answers:
- Coverage, not just quality. What fraction of instances does each method solve under the same time limit? A method finding shorter plans on 60% of instances it solves, but solving fewer, is not better.
- Time and expansions on the same hardware. Expanded nodes compare heuristics; time compares systems. A neural heuristic reduces expansions but makes each more costly: DeepCubeA generates about 3.85 million nodes and averages 10.28 s on 15-puzzle, versus about 32,200 nodes and 0.002 s for the additive-PDB optimal solver, which is always optimal (DeepCubeA is optimal 99.4% of the time). On 24-puzzle, however, DeepCubeA takes 19.33 s versus 4239.54 s. Both results are true and only together show where learning helps.
- Strong, well-configured classical baselines. Is it compared with Fast Downward using LAMA, modern CDCL, the symbolic engine alone, Wu’s method? With recommended configurations and the same budget? Otherwise improvement may reflect a weak baseline.
- Contamination. Could the model have seen test instances or solutions? Planning competition domains, mathlib and IMO problems are online. Controls include name obfuscation, splits such as
novel_premises, instances generated after the model cutoff, and contamination detection. - Ablations. What happens without the network (engine alone), without the engine (network alone), or replacing the network with a classical heuristic? Without these rows the source of improvement is unknown (ablation study).
- Total compute. Training plus inference, sample count, feedback rounds and GPU hours. Ten percent more solved problems for 100 times the compute may or may not be worthwhile, but must be reported.
For reproduction: first run the classical baseline on your machine with its best configuration; then the paper’s system with its code and seeds; only then your variants under the same budget (strong baselines).
Common mistakes
Exercises
Step 1 of 4. What fact about OPEN do you need?
bwas(s0, h_lote, lam, N) for the 8-puzzle: OPEN sorted by ; each iteration extract up to valid entries with smallest (discard stale ones), stop if one is the goal, otherwise generate all their children and evaluate all new children in one call to h_lote. Reopen a state when reached by a shorter path. Return (camino, expandidos, iteraciones). Tests check optimality with , at most one heuristic call per iteration, that batches reduce iterations, and bound with .import heapq
META = (0, 1, 2, 3, 4, 5, 6, 7, 8) # 8-puzzle: s[casilla] = ficha, el hueco (0) en la casilla 0
def vecinos(s):
"""Sucesores de s (deslizar una ficha al hueco); cada movimiento cuesta 1."""
b = s.index(0)
r, c = divmod(b, 3)
out = []
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
if 0 <= r + dr < 3 and 0 <= c + dc < 3:
q = (r + dr) * 3 + c + dc
t = list(s)
t[b], t[q] = t[q], 0
out.append(tuple(t))
return out
def bwas(s0, h_lote, lam, N):
"""A* ponderado por lotes con f = lam * g + h.
h_lote(lista_de_estados) -> lista de valores: llámala UNA vez por iteración, con todos los hijos nuevos.
En cada iteración extrae de OPEN hasta N entradas de menor f; si una es la meta, termina.
Reabre un estado si llega a él por un camino más corto.
Devuelve (camino, expandidos, iteraciones), con camino = [s0, ..., META].
"""
# tu código
return None, 0, 0More than one answer may be correct.
More than one answer may be correct.
Summary
- Five integration patterns: guidance within search (AlphaZero, DeepCubeA, GPT-f, AlphaProof), generate and verify (LLM-Modulo, FunSearch), translation (LLM+P), learning inside the solver (SATzilla, NeuroCore), and end-to-end approximation (NeuroSAT). Only the last gives up all guarantees.
- DAVI learns cost to go by approximate value iteration over states scrambled from the goal. Each target-network copy is one value-iteration step, and explains why short training underestimates distant states. The resulting heuristic is inadmissible; BWAS (, batches of nodes) trades optimality for parallel evaluation.
- A heuristic with on all states yields solutions of cost ; network error statistics on a sample do not establish that hypothesis.
- NeuroSAT learns from one bit per formula a procedure searching for assignments; literal vectors split into two groups when it finds one. It cannot certify unsatisfiability or compete with CDCL. Per-instance selection, configuration and suggestions respecting the engine do reach solvers.
- Language models plan poorly alone (worse with obfuscated names). A correct validator guarantees every accepted plan is valid, but not that one is found: feedback takes GPT-4 from 34% to 82% in PlanBench and does not rescue a 3000-million-parameter model that succeeds rarely, only with repeated sampling. The honest comparison is against independent sampling and a classical planner on success, quality and compute.
- FunSearch, GPT-f, ReProver, AlphaGeometry and AlphaProof share a neural generator and formal judge. Their tables teach how to read the field: nonlearned baselines, difficult splits, engine ablations and inference compute.