Frontier: beyond worst-case analysis and AI-discovered algorithms
Current algorithm research crosses machine learning in both directions. Study beyond-worst-case analysis (smoothed analysis and universal optimality), prediction-augmented algorithms combining consistency and robustness, learned indexes, nearly linear-time maximum flow, neural algorithmic reasoning, and algorithms discovered by search guided by networks and language models: AlphaTensor, AlphaDev, FunSearch and AlphaEvolve.
After this lesson you can
- Explain smoothed analysis and universal optimality and what they add beyond worst-case analysis.
- Design an algorithm with predictions and prove its consistency and robustness for ski rental and paging.
- Implement a learned index and compare it with binary search and B-trees.
- Critically read an AI algorithm-discovery paper: search space, evaluator and guarantees.
- Identify open problems at the intersection of algorithms and machine learning.
Before you start
Motivation: an exponential algorithm that works
The simplex method solves linear programs by jumping between vertices of the feasible polyhedron, always improving the objective. In 1972 Klee and Minty constructed a polyhedron, a deformed cube in , where simplex with Dantzig’s pivot rule visits all vertices before reaching optimum. With this exceeds pivots. Since then exponential examples have been found for classical deterministic pivot rules, and superpolynomial examples even for randomized rules. Yet simplex remains among the most widely used linear-programming algorithms, and on real problems pivot count grows moderately with size.
That tension starts this lesson. Worst-case analysis used throughout the topic is a guarantee: it never misleads about what can occur. But it sometimes poorly describes what does occur, because real data are not chosen by an adversary. Current research responds in three directions, all intersecting machine learning:
- Change the measure. Smoothed analysis measures worst case after a little noise; instance and universal optimality compare against the best possible algorithm for each input or graph.
- Put learning inside the algorithm. An online algorithm can use a prediction of the future without losing its guarantee when wrong; a data structure can learn its key distribution.
- Use learning to discover algorithms. AlphaTensor, AlphaDev, FunSearch and AlphaEvolve search for new algorithms with networks and language models guided by an automatic evaluator.
Along the way you will see a major theoretical result of the decade, nearly linear-time maximum flow, and the reverse attempt to teach a network to execute algorithms. You will end with criteria for reading an “AI-discovered algorithm” announcement and a list of open problems.
Beyond the worst case
The Klee–Minty cube
The Klee–Minty version used in this lesson is, for ,
The constraints say , that ranges from 0 to , and so on: a cube whose faces tilt increasingly. Simplex starting at the origin with Dantzig’s rule (enter the variable of greatest reduced cost) visits all vertices in an order resembling Gray code: solve dimension , jump to the opposite face of the last coordinate and solve dimension again in reverse. That takes pivots. You will check this in the cell below for .
Smoothed analysis
In 2001 Spielman and Teng proposed measuring algorithm performance in the worst case after perturbing the input with a little noise. The idea is that if hard inputs are rare and fragile, data imprecision destroys them.
The definition interpolates between two classical analyses. As it recovers worst case: the adversary chooses the point and noise does not move it. When is large, noise dominates and the average case over Gaussians remains. For intermediate the adversary still chooses but must win on average over a ball of radius on the order of around it. Smoothed analysis is the best-known example of beyond-worst-case analysis: models replacing the omnipotent adversary with a more realistic one, collected by Roughgarden in Beyond the Worst-Case Analysis of Algorithms (Cambridge University Press, 2021).
The proof spans dozens of pages and is not presented here, but its core is geometric. The shadow rule projects the polyhedron onto the plane generated by the objective and an auxiliary direction and follows the edge of that shadow, a polygon. Pivot count is polygon edge count; the task is bounding its expectation under Gaussian constraints: a shadow vertex requires a constraint to form a particular angle with the plane, and noise makes many doing so at once unlikely. Bounds have improved greatly since (Vershynin, 2009; Dadush and Huiberts, 2018). The work earned Spielman and Teng the 2008 Gödel Prize.
The interactive uses Dantzig’s rule, not the shadow rule, so it illustrates the motivating phenomenon rather than the theorem. Its noise model is also explicit and different: add with to each coefficient in row of (including zeros), and multiply by . We use each row’s scale rather than the norm of because in the Klee–Minty cube dominates the row and the Spielman–Teng model applied directly would erase the structure of for any reasonable . The cell reproduces the figure:
import numpy as np
def klee_minty(n):
"""max sum 2^(n-j) x_j s.a. 2 sum_{j<i} 2^(i-j) x_j + x_i <= 5^i, x >= 0 (i, j desde 1)."""
c = np.array([2.0 ** (n - j) for j in range(1, n + 1)])
A = np.zeros((n, n))
for i in range(1, n + 1):
for j in range(1, i):
A[i - 1, j - 1] = 2 * 2.0 ** (i - j)
A[i - 1, i - 1] = 1.0
b = np.array([5.0 ** i for i in range(1, n + 1)])
return c, A, b
def simplex_dantzig(c, A, b, max_piv=100_000):
"""Símplex de tableau desde la base de holguras (exige b > 0); regla de Dantzig. Devuelve (pivotes, x, estado)."""
m, n = A.shape
T = np.zeros((m + 1, n + m + 1))
T[:m, :n], T[:m, n:n + m], T[:m, -1], T[m, :n] = A, np.eye(m), b, -c
base = list(range(n, n + m))
for piv in range(max_piv):
j = int(np.argmin(T[m, :-1]))
if T[m, j] >= -1e-9 * np.abs(c).max():
x = np.zeros(n + m); x[base] = T[:m, -1]
return piv, x[:n], "óptimo"
col = T[:m, j]
razones = np.where(col > 1e-12, T[:m, -1] / np.where(col > 1e-12, col, 1.0), np.inf)
i = int(np.argmin(razones))
if not np.isfinite(razones[i]):
return piv, None, "no acotado"
T[i] /= T[i, j]
f = T[:, j].copy(); f[i] = 0.0
T -= np.outer(f, T[i]) # elimina la columna j del resto de filas
base[i] = j
return max_piv, None, "límite"
def perturbar(c, A, b, sigma, rng):
"""Ruido gaussiano relativo a la escala de cada fila (también en los ceros); b se perturba de forma relativa."""
escala = np.abs(A).max(axis=1, keepdims=True)
return c, A + sigma * escala * rng.standard_normal(A.shape), b * (1 + sigma * rng.standard_normal(b.shape))
peor = {n: simplex_dantzig(*klee_minty(n))[0] for n in range(2, 11)}
print("sin ruido:", peor)
rng = np.random.default_rng(0)
print(f"{'n':>3} | {'σ = 0':>6} | " + " | ".join(f"σ = {s:g}".rjust(10) for s in (1e-4, 1e-3, 1e-2, 1e-1)))
for n in (4, 6, 8, 10):
fila = [peor[n]]
for s in (1e-4, 1e-3, 1e-2, 1e-1):
piv = []
for _ in range(20):
cc, AA, bb = perturbar(*klee_minty(n), s, rng)
if (bb > 0).all():
p, _, est = simplex_dantzig(cc, AA, bb)
if est == "óptimo":
piv.append(p)
fila.append(np.mean(piv))
print(f"{n:>3} | {fila[0]:>6} | " + " | ".join(f"{v:10.1f}" for v in fila[1:]))Without noise exactly pivots occur: . With noise, mean dimension-10 pivots fall from 1023 to about 122 with , 47 with , 24 with and 12 with ; they no longer double from one dimension to the next. The theorem suggests the right reading: the exponential path depends on cube faces tilting in exact proportions, and a relative error of one ten-thousandth suffices to break it in dimension 10. The table does not prove Dantzig’s rule has polynomial smoothed complexity: it measures one example. Whether any pivot rule is polynomial in the worst case remains open.
Instance optimality and universal optimality
Smoothing still measures a worst case, only for a friendlier problem. Another family of notions compares with the best algorithm on each input:
- An algorithm is instance optimal if for every input its cost is within a constant factor of any other correct algorithm on that same . This is stronger than worst-case optimality and almost always impossible as stated: an algorithm “guessing” the answer to one input solves it in constant time. Comparisons are therefore restricted. Fagin, Lotem and Naor (2003) proved their threshold algorithm for aggregating sorted lists instance-optimal against algorithms that do not guess; Afshani, Barbay and Chan (2017) gave planar convex hulls instance-optimal when input order is ignored.
- Universal optimality fixes the structural part of input and leaves the rest to the adversary. In a graph problem an algorithm is universally optimal if, for every graph , its worst case over all weights on is, up to a constant, the best possible for that .
The striking recent result is Haeupler, Hladík, Rozhoň, Tarjan and Tětek (2024): Dijkstra’s algorithm, with a new heap, is universally optimal for sorting vertices by distance from a source. The heap has the working-set property: extracting the minimum costs logarithmic time in the number of elements inserted after it, not heap size. Dijkstra’s classic worst case with a good heap, , occurs on some graphs, but on many others (a path, a tree with few branches) any algorithm can go faster because few distance orders are possible. The theorem says that on each graph, Dijkstra with this heap is as fast as the best algorithm designed for that particular graph, without knowing which it is.
Algorithms with predictions
Competitive analysis in the online algorithms lesson assumes no knowledge of the future. In practice you almost always have a model predicting it, even imperfectly. The question is how to use it without being at its mercy.
This is the framework of algorithms with predictions (learning-augmented algorithms), summarized by Mitzenmacher and Vassilvitskii in 2020 and since then a highly active algorithmic field. The guarantees pull in opposite directions: trusting a prediction moves consistency toward 1 and worsens robustness; ignoring it gives classical robustness and no improvement. Design chooses the tradeoff.
Ski rental with a prediction
Return to ski rental: rent costs 1 per day, buying costs , the season lasts unknown days, and . Buying at the start of day costs if and if ; the best deterministic algorithm buys on day and pays at most times optimum. Now a model predicts duration , with error .
Blindly following prediction is tempting: if buy on day one; otherwise never buy. With you pay exactly . But if and the season lasts one day, you pay for something worth 1; and if and the season never ends, you pay without limit. The ratio is unbounded. Purohit, Svitkina and Kumar (NeurIPS 2018) proposed a rule with confidence parameter :
Proof
You prove robustness and consistency in the final guided exercise. Here is the error-dependent bound. If the algorithm does not buy (), it pays , and in case excess is at most ; in case it does not buy only if , and then pays . If it buys (), there are two cases.
Case , . It pays . If , and the ratio is below . If , and the prediction chose the wrong side: . Then , and because .
Case , . It pays and . Again prediction chose the wrong side: . Therefore
In all cases ; dividing by and combining with robustness yields the stated minimum.
∎Parameter quantifies the tradeoff. With , a good prediction costs at most 20 % over optimum, but a bad one can approach 6 times; with , at most 80 % extra with a good prediction and never more than 2.25 times. Can we improve? Not with a deterministic algorithm: in the continuous version, every -consistent algorithm is at least -robust (Gollapudi and Panigrahi, 2019; Wei and Zhang, 2020). The short argument: if prediction says the season is long, , and it is long, optimum is ; to pay at most one must buy before time . But the adversary then ends the season at purchase, at , and ratio is .
Notice two things about the blue curve. First, it does not jump: with small error the ratio barely changes, and smooth degradation makes imperfect predictions useful. Second, for , worst case rises from at to at error and when error reaches : from there it is at the robustness ceiling, a worst case, not an average.
Paging with predictions
In paging, Belady’s offline optimum evicts the page requested latest in the future. Lykouris and Vassilvitskii (ICML 2018) assume an oracle predicting each requested page’s next request time, measuring error as the sum of absolute prediction errors.
- Blindly follow the oracle by applying Belady to predicted times. Perfect predictions are optimal, but the ratio grows linearly with and is unbounded: systematic error makes it the worst possible algorithm.
- Predictive Marker uses the marking algorithm skeleton: phases evict only unmarked pages, already guaranteeing at most times optimum. Within that freedom the oracle selects the unmarked page with latest predicted next use. It watches eviction chains (an evicted page returning within the phase forces another eviction, which may return, and so on): if a chain exceeds links it stops trusting the oracle and evicts randomly.
Its competitive ratio is ; with absolute error, at most . In other words: nearly 2-consistent, degradation of order , and never worse than , matching randomized marking without an oracle. The easiest part of the guarantee, robustness from the skeleton rather than the oracle, takes a few lines.
Proof
Divide into phases: each is the longest segment requesting at most distinct pages, and the next starts with request for distinct page number . Within a phase each miss loads a page that is marked and not evicted until phase end, so each distinct page misses at most once: at most misses per phase. For optimum, let be the first page of phase and take the segment from the second request of phase to the first of phase inclusive. That segment requests distinct pages other than : the other of phase and the page opening phase . At segment start is in OPT’s cache, which holds only pages, so those cannot all also be there; OPT evicts only on misses. Thus it misses at least once in each segment, and segments for different phases are disjoint. With phases, and . The argument never uses how the evicted page is selected: the oracle can only improve the choice within an already bounded margin.
∎The chain rule reduces that to , and 2-consistency is the paper’s hard part. The lab cell tests both.
Search with advice
The simplest example connects to what follows. Find a key in a sorted array of elements and a model predicts position . If you use exponential search from (compare at until bracketing the key, then binary search the final interval) and the real position is distance from , you make comparisons: with , perfect prediction costs and terrible prediction , matching unadvised binary search. It is 1-consistent up to constants, robust, and degrades like . A learned index turns that idea into a data structure.
Learned indexes
An index over a sorted array of keys answers “what is the position of key ?” That position is exactly , where is the keys’ empirical cumulative distribution function. A B-tree is, in this view, a piecewise-constant model of giving a coarse prediction (the block) and refining it node by node. Kraska, Beutel, Chi, Dean and Polyzotis (SIGMOD 2018) proposed replacing it with a learned model of .
The central observation of learned indexes is that correctness does not depend on model quality. Bounds are measured on indexed keys, so the window always contains the answer and search never fails; a bad model merely gives wide windows. Search costs evaluation of plus at most comparisons, and the model stores a few numbers per segment instead of a separator per block.
One model of is insufficient: the empirical distribution has structure at all scales. Kraska and coauthors used a recursive model index (RMI): a root model predicts position, that selects a next-level model among , and so on to leaves, lines with their own error bounds. With two levels and linear models, what you will implement, construction is a pair of least-squares fits.
Lognormal shows the weakness of a two-level RMI with a linear root. The root distributes keys to leaves by a line, and when most mass is concentrated in a narrow key-axis region, most fall in a few leaves that must approximate a huge curve segment with a line. The index stays correct but the maximum window explodes. Remedies: a better root (more levels or a nonlinear model, as in the original paper), or construct segments differently. Ferragina and Vinciguerra’s PGM-index (VLDB 2020) chooses segments so all have error at most , with the minimum number of segments, bounding worst-case search; the final code exercise implements a greedy version.
Comparing fairly
Kraska and coauthors reported learned indexes up to 70 % faster than cache-optimized B-trees and using an order of magnitude less memory on several real datasets. The result drew skepticism, partly because no implementation was public. Marcus, Kipf, van Renen and coauthors (VLDB 2020) built a common benchmark, SOSD, with implementations tuned by their own authors, confirming learned indexes outperform classics on their turf: read-only in-memory searches on a dense array. Outside that turf (inserts, disk keys, long strings) comparison is closer, and specific learned update structures exist, such as ALEX or dynamic PGM.
Metrics matter too. Counting comparisons favors learned indexes; the real memory cost is cache misses, and a B-tree with cache-line-sized nodes makes few, despite many comparisons. The lab cell measures both.
Learned Bloom filters
The idea also applies to Bloom filters. A classifier trained to distinguish keys in the set decides first: if , answer “present.” Since the classifier has false negatives, forbidden in a Bloom filter, set keys with are stored in a smaller backup Bloom filter, queried when the classifier says “no.” This guarantees no false negatives, as in a classical filter. What changes is false-positive rate: the classical rate applies to any absent query, whereas the learned filter’s is the classifier’s plus backup’s measured on a query distribution. Mitzenmacher (NeurIPS 2018) formalized this: the guarantee holds only if future queries resemble validation, and an adversary choosing classifier-accepted queries breaks it.
Lab 1: predictions and learned indexes
Four cells: ski rental with predictions, paging with a noisy oracle, a two-level learned index versus binary search and a B-tree, and a check that the theoretical bound holds on millions of cases.
import numpy as np
from math import ceil
def coste(k, D, B): # comprar al empezar el día k; la temporada dura D días
return D if D < k else k - 1 + B
def dia_compra(y, B, lam): # Purohit, Svitkina y Kumar (2018)
return ceil(lam * B) if y >= B else ceil(B / lam)
def peor_cociente(eta, lam, B):
"""Máximo de ALG/OPT sobre todas las duraciones D y predicciones con |y - D| <= eta."""
k_alto, k_bajo = ceil(lam * B), ceil(B / lam)
peor = 1.0
for D in range(1, k_bajo + 3):
opt = min(D, B)
if D + eta >= B: peor = max(peor, coste(k_alto, D, B) / opt) # el adversario puede predecir y >= B
if D - eta < B: peor = max(peor, coste(k_bajo, D, B) / opt) # o y < B
return peor
B = 100
print("peor ALG/OPT según el error máximo eta (B = 100)")
print(" λ | " + " | ".join(f"η = {f:g}B".rjust(9) for f in (0, 0.1, 0.25, 0.5, 1, 2)) + " | 1 + λ | 1 + 1/λ")
for lam in (0.2, 0.5, 0.8, 1.0):
fila = [peor_cociente(f * B, lam, B) for f in (0, 0.1, 0.25, 0.5, 1, 2)]
print(f" {lam:.1f} | " + " | ".join(f"{v:9.3f}" for v in fila) + f" | {1 + lam:5.2f} | {1 + 1 / lam:6.2f}")
# comprobación exhaustiva (vectorizada) de ALG <= (1 + λ) OPT + η/(1 − λ) y de la robustez 1 + 1/λ
D, y = np.meshgrid(np.arange(1, 1200), np.arange(0, 1200), indexing="ij")
OPT, ETA = np.minimum(D, B), np.abs(y - D)
holgura, rob = -np.inf, 0.0
for lam in (0.1, 0.25, 0.5, 0.75, 0.9):
k = np.where(y >= B, ceil(lam * B), ceil(B / lam))
ALG = np.where(D < k, D, k - 1 + B)
holgura = max(holgura, (ALG - ((1 + lam) * OPT + ETA / (1 - lam))).max())
rob = max(rob, ((ALG / OPT) / (1 + 1 / lam)).max())
print()
print(f"{D.size * 5:,} casos: máx. de ALG − [(1+λ)OPT + η/(1−λ)] = {holgura:.3f} (≤ 0)")
print(f"máx. de (ALG/OPT)/(1 + 1/λ) = {rob:.4f} (≤ 1)")The table shows six points on the interactive curve. With the ratio rises from without error to when error reaches ; with from to ; with it is always . Measured values stay below and because days are integers: buying on day costs , one day less than in the continuous version. The last two lines check the theorem on more than seven million pairs: maximum slack is negative and the ratio never reaches .
import numpy as np, random
from collections import OrderedDict
def proximo_uso(sec):
"""t -> instante de la siguiente petición de la misma página (n + t si no vuelve: distinto para cada t)."""
n, ultimo, prox = len(sec), {}, [0] * len(sec)
for t in range(n - 1, -1, -1):
prox[t] = ultimo.get(sec[t], n + t)
ultimo[sec[t]] = t
return prox
def lejano_en_el_futuro(sec, k, pred):
"""Belady si pred es exacto; con predicciones, «seguirlas a ciegas»: desaloja la de próximo uso predicho más lejano."""
cache, fallos = {}, 0
for t, p in enumerate(sec):
if p not in cache:
fallos += 1
if len(cache) >= k:
del cache[max(cache, key=cache.get)]
cache[p] = pred[t]
return fallos
def lru(sec, k):
cache, fallos = OrderedDict(), 0
for p in sec:
if p in cache:
cache.move_to_end(p); continue
fallos += 1
if len(cache) >= k:
cache.popitem(last=False)
cache[p] = True
return fallos
def marcado(sec, k, pred=None, semilla=0):
"""Marcado aleatorizado (pred=None) o Predictive Marker de Lykouris y Vassilvitskii: dentro de cada fase solo se
desalojan páginas no marcadas; se elige por la predicción salvo cuando una cadena de desalojos supera H_k."""
R, Hk = random.Random(semilla), sum(1 / i for i in range(1, k + 1))
cache, marcadas, fallos = {}, set(), 0
cadena_de, largo = {}, [] # página desalojada en esta fase -> su cadena; longitud de cada cadena
for t, p in enumerate(sec):
valor = pred[t] if pred is not None else 0
if p in cache:
cache[p] = valor; marcadas.add(p); continue
fallos += 1
if len(cache) >= k:
libres = [q for q in cache if q not in marcadas]
if not libres: # empieza una fase nueva
marcadas, cadena_de, largo = set(), {}, []
libres = list(cache)
if p in cadena_de: # vuelve una página desalojada en esta fase: la cadena crece
c = cadena_de.pop(p); largo[c] += 1
else: # página «limpia»: cadena nueva
c = len(largo); largo.append(1)
if pred is None or largo[c] > Hk:
v = R.choice(libres)
else:
v = max(libres, key=cache.get)
del cache[v]; cadena_de[v] = c
cache[p] = valor; marcadas.add(p)
return fallos
def generar(n, N, k, semilla):
"""Mezcla de bucles un poco mayores que la caché (malos para LRU) y ráfagas con popularidad de Zipf."""
r, sec = np.random.default_rng(semilla), []
while len(sec) < n:
if r.random() < 0.5:
L = k + int(r.integers(1, k // 2 + 2)); base = int(r.integers(0, N - L))
sec += list(range(base, base + L)) * int(r.integers(2, 5))
else:
sec += [int(v) for v in np.minimum(r.zipf(1.3, size=200), N) - 1]
return sec[:n]
k, sec = 16, generar(12_000, 400, 16, 1)
prox = proximo_uso(sec)
opt = lejano_en_el_futuro(sec, k, prox)
print(f"k = {k}, {len(sec)} peticiones. OPT (Belady) = {opt}, LRU = {lru(sec, k)}, "
f"marcado = {np.mean([marcado(sec, k, None, s) for s in range(3)]):.0f}")
print(f"{'ruido σ':>8} | {'η/OPT':>7} | {'a ciegas':>9} | {'Predictive Marker':>17}")
r = np.random.default_rng(5)
for sigma in (0, 4, 64, 512, 4096):
pred = [x + sigma * r.standard_normal() for x in prox]
eta = sum(abs(a - b) for a, b in zip(pred, prox))
print(f"{sigma:>8} | {eta / opt:>7.0f} | {lejano_en_el_futuro(sec, k, pred):>9} | {marcado(sec, k, pred):>17}")
inv = [-x for x in prox] # el peor oráculo: invierte el orden de los próximos usos
print(f"{'invertida':>8} | {'':>7} | {lejano_en_el_futuro(sec, k, inv):>9} | {marcado(sec, k, inv):>17}")The sequence mixes loops slightly larger than cache, where LRU misses every request, with bursts of uneven popularity. Belady incurs 3502 misses, LRU 5916, and randomized marking about 5504. With an exact oracle, blind following reproduces Belady (3502) and Predictive Marker has 4407: it pays for not evicting marked pages, as theory says (consistency 2, not 1). As noise grows, blind policy degrades quickly: at it is already worse than LRU (6008) and at has 8329 misses. Predictive Marker stays between 4407 and 5374, never worse than no-oracle marking in this experiment. With the inverted oracle, the worst possible, blind policy has 11020 misses, over three times optimum, and Predictive Marker 7112: worse than marking without predictions but within guarantee (). The section’s pattern: the safety net costs something with a perfect oracle and saves the result otherwise.
import numpy as np, math
def claves(tipo, n, semilla=0):
r = np.random.default_rng(semilla)
if tipo == "uniforme":
x = r.uniform(0, 1e9, n)
elif tipo == "lognormal":
x = r.lognormal(0, 2, n) * 1e6
else: # 60 grupos de anchuras muy distintas
c, w = r.uniform(0, 1e9, 60), r.uniform(1e3, 1e6, 60)
g = r.choice(60, n, p=r.dirichlet(np.ones(60)))
x = c[g] + w[g] * r.standard_normal(n)
return np.unique(np.floor(x).astype(np.int64))
def ajuste(x, y):
if len(x) == 1:
return 0.0, float(y[0])
a, b = np.polyfit(x, y, 1)
return float(a), float(b)
class RMI:
"""Índice de dos niveles: una recta raíz elige la hoja; cada hoja es una recta con su error máximo."""
def __init__(self, keys, S):
self.keys, self.n, self.S = keys, len(keys), S
x, pos = keys.astype(float) - keys[0], np.arange(len(keys))
self.x0 = float(keys[0])
self.raiz = ajuste(x, pos)
hoja = np.clip(((self.raiz[0] * x + self.raiz[1]) * S / self.n).astype(int), 0, S - 1)
self.m = np.zeros((S, 2)); self.lo = np.zeros(S, int); self.hi = np.zeros(S, int)
for j in range(S):
idx = np.nonzero(hoja == j)[0]
if len(idx):
a, b = ajuste(x[idx], idx)
e = idx - np.rint(a * x[idx] + b).astype(int)
self.m[j], self.lo[j], self.hi[j] = (a, b), max(0, -e.min()), max(0, e.max())
self.ocupacion = np.bincount(hoja, minlength=S)
def buscar(self, k):
x = float(k) - self.x0
j = min(self.S - 1, max(0, int((self.raiz[0] * x + self.raiz[1]) * self.S / self.n)))
p = int(round(self.m[j, 0] * x + self.m[j, 1]))
lo, hi = max(0, p - self.lo[j]), min(self.n, p + self.hi[j] + 1)
return busqueda_binaria(self.keys, k, lo, hi)
def bytes(self): # 2 + 2S coeficientes float64 y 2S cotas de error (int32)
return 8 * (2 + 2 * self.S) + 4 * 2 * self.S
def busqueda_binaria(keys, k, lo, hi):
comp, lineas = 0, set()
while lo < hi:
mid = (lo + hi) // 2
comp += 1; lineas.add(mid // 8) # 8 claves de 8 bytes por línea de caché de 64 B
if keys[mid] < k: lo = mid + 1
else: hi = mid
return lo, comp, len(lineas)
class BTreeEstatico:
"""B+-tree estático sobre el array ordenado: cada nodo interno guarda F separadores (F = 16: dos líneas)."""
def __init__(self, keys, F=16):
self.keys, self.F = keys, F
self.niveles = [] # de abajo arriba: separadores de cada nivel
sep = keys[::F]
while len(sep) > 1:
self.niveles.append(sep)
sep = sep[::F]
self.niveles.reverse()
def buscar(self, k):
comp, nodos, i = 0, 0, 0
for sep in self.niveles: # en cada nivel, búsqueda binaria dentro de un nodo de F separadores
lo, hi = i * self.F, min(len(sep), i * self.F + self.F)
nodos += 1
while lo < hi:
mid = (lo + hi) // 2; comp += 1
if sep[mid] <= k: lo = mid + 1
else: hi = mid
i = max(0, lo - 1)
p, c, _ = busqueda_binaria(self.keys, k, i * self.F, min(len(self.keys), i * self.F + self.F))
return p, comp + c, nodos + 1
def bytes(self):
return 8 * sum(len(s) for s in self.niveles)
n, S = 100_000, 1000
print(f"{'claves':>9} | {'binaria':>13} | {'B-tree F=16':>17} | {'RMI S=1000':>15} | {'ventana máx.':>12} | memoria B-tree / RMI")
print(f"{'':>9} | {'comp. líneas':>13} | {'comp. nodos':>17} | {'comp. líneas':>15} |")
for tipo in ("uniforme", "grupos", "lognormal"):
keys = claves(tipo, n)
kl = keys.tolist()
rmi, bt = RMI(keys, S), BTreeEstatico(keys)
q = keys[np.random.default_rng(1).integers(0, len(keys), 4000)].tolist()
rb, rr, rt = [], [], []
for k in q:
p1, c1, l1 = busqueda_binaria(kl, k, 0, len(kl)); p2, c2, l2 = rmi.buscar(k); p3, c3, l3 = bt.buscar(k)
assert kl[p1] == kl[p2] == kl[p3] == k
rb.append((c1, l1)); rr.append((c2, l2 + 2)); rt.append((c3, l3)) # +2: raíz y hoja del modelo
mb, mr, mt = np.mean(rb, 0), np.mean(rr, 0), np.mean(rt, 0)
vmax = int((rmi.lo + rmi.hi).max())
print(f"{tipo:>9} | {mb[0]:5.1f} {mb[1]:6.1f} | {mt[0]:7.1f} {mt[1]:8.1f} | {mr[0]:6.1f} {mr[1]:7.1f} | {vmax:>12} | "
f"{bt.bytes() / 1024:.0f} KiB / {rmi.bytes() / 1024:.0f} KiB")
if tipo == "lognormal":
print(f" lognormal: la hoja más llena recibe {rmi.ocupacion.max()} claves y {np.sum(rmi.ocupacion == 0)} hojas quedan vacías")All three structures find every key (checked by assert), so comparison concerns cost alone. Binary search makes about 16.7 comparisons and touches about 13.5 distinct cache lines: almost every early comparison lands far from the previous one. B-tree makes even more comparisons (17.7), but visits only 5 nodes of two lines each; that is why it is the benchmark. A learned index with 1000 leaves on uniform keys falls to 3.7 comparisons and about 3.5 lines counting model root and leaf, using 23 KiB versus 52 KiB of B-tree separators. On clustered and lognormal data, maximum window rises from 22 positions to thousands, mean rises to 8 and 10 comparisons and 7 and 9.4 lines, and on lognormal the index touches almost as many lines as the B-tree (5 two-line nodes). The interactive shows why: with lognormal one leaf receives over 43000 of 100000 keys and 643 of 1000 leaves are empty. A learned index wins when its model fits the distribution; an honest comparison must name distributions and metric.
Nearly linear-time maximum flow
Maximum flow is one of the most studied algorithmic problems, and for decades the best combinatorial algorithms (augmenting paths, blocking flow, push–relabel) remained far from linear time on general graphs. In 2022 Chen, Kyng, Liu, Peng, Probst Gutenberg and Sachdeva proved nearly linear-time maximum flow possible.
Term grows more slowly than any power ; in this algorithm it grows faster than every power of : hence “nearly linear,” not “linear” or “nearly linear up to logarithms.” The algorithm is not combinatorial in the classical sense; it is an interior-point method where each step is solved by a dynamic data structure.
- An interior point reducing a potential. Write minimum-cost flow as linear program with (conservation) and . Instead of the classical logarithmic barrier, each iteration reduces potential where is optimal cost. The power barrier penalizes nearly saturated edges more than a logarithm and keeps all numbers within a polylogarithmic bit count.
- Each step is a minimum-ratio cycle. The improvement direction is a circulation () minimizing , where is the gradient of and a diagonal of lengths. This is an -norm problem whose optimum is a simple cycle, instead of the -norm electrical flow of earlier interior-point methods. The authors show approximation factor suffices and steps reach optimum.
- Steps change little. From one iteration to the next only lengths and gradients change on average. A dynamic data structure based on low-stretch spanning trees rebuilt in parts and a recursive hierarchy of smaller graphs returns an approximate cycle in amortized time .
steps at cost per step yield the total. The structural lesson for your toolbox: continuous optimization decides what to improve and dynamic data structures make each improvement almost free. This is theoretical: the algorithm is not designed for direct implementation and constants hidden in are enormous for practical , so the maximum-flow lesson’s algorithms remain those used.
Neural algorithmic reasoning
So far learning helped an algorithm. Neural algorithmic reasoning (Veličković and Blundell, 2021) goes the other way: train a network to execute a classical algorithm step by step, hoping for a differentiable module that generalizes like the algorithm and connects to data not fitting its formal input (a graph with noisy features rather than exact weights).
The theory is algorithmic alignment by Xu and coauthors (ICLR 2020): a network learns an algorithm from fewer examples when its structure resembles the algorithm, because each module learns a simple function. The canonical example is Bellman–Ford. One iteration updates , and a message-passing layer with message , minimum aggregation and minimum update is exactly that. A sum-aggregation network would have to learn to manufacture a minimum from sums, much harder.
import numpy as np
# Un paso de Bellman-Ford es una capa de paso de mensajes con agregación mínimo:
# d_v <- min(d_v, min_{u -> v} (d_u + w_uv)) mensaje = d_u + w_uv, agregación = min, actualización = min
rng = np.random.default_rng(0)
n = 8
W = np.full((n, n), np.inf)
for u in range(n):
for v in rng.choice(n, 3, replace=False):
if u != v:
W[u, v] = rng.integers(1, 10)
def capa_min(d, W):
mensajes = d[:, None] + W # mensajes[u, v] = d_u + w_uv
return np.minimum(d, mensajes.min(axis=0))
d = np.full(n, np.inf); d[0] = 0
for _ in range(n - 1):
d = capa_min(d, W)
# referencia: Dijkstra con pesos positivos
import heapq
ref = np.full(n, np.inf); ref[0] = 0; h = [(0, 0)]
while h:
du, u = heapq.heappop(h)
if du > ref[u]: continue
for v in range(n):
if np.isfinite(W[u, v]) and du + W[u, v] < ref[v]:
ref[v] = du + W[u, v]; heapq.heappush(h, (ref[v], v))
print("n − 1 capas con agregación mínimo:", d)
print("Dijkstra: ", ref)
print("coinciden:", np.array_equal(d, ref))
# la misma capa en un grafo 4 veces mayor: con las 7 iteraciones que bastaban en el de 8 nodos ya no llega
n2 = 32
W2 = np.full((n2, n2), np.inf)
for u in range(n2):
for v in rng.choice(n2, 2, replace=False):
if u != v: W2[u, v] = rng.integers(1, 10)
def iterar(W, pasos):
d = np.full(len(W), np.inf); d[0] = 0
for _ in range(pasos):
d = capa_min(d, W)
return d
d7, d31 = iterar(W2, 7), iterar(W2, n2 - 1)
print(f"grafo de {n2} nodos: con 7 iteraciones, {int(np.sum(d7 != d31))} de {n2} distancias todavía son incorrectas;"
f" con {n2 - 1}, ninguna (¿se estabiliza antes? {np.array_equal(iterar(W2, n2 - 2), d31)})")The second part of the cell shows the field’s key problem. Even if each layer is perfect, the iteration count must grow with graph size: 7 iterations sufficient for 8 nodes leave 5 of 32 distances wrong on a graph four times larger. A network trained on small graphs learns the layer at best; at worst, a shortcut working only at those sizes.
The reference benchmark is CLRS-30 (Veličković and coauthors, ICML 2022): 30 algorithms from Cormen, Leiserson, Rivest and Stein (sorting, search, dynamic programming, graphs, strings and geometry), all expressed as graphs with “hint” trajectories (intermediate algorithm state at each step) supervising execution. Training uses 16-node graphs and out-of-distribution evaluation uses 64. In the original paper mean out-of-distribution micro-F1 of baseline networks ranged from 38.9 % (Memnet) to 50.8 % (PGN), with MPNN at 45.0 %, and huge differences across algorithms. Later work such as Ibarz and coauthors (2022) greatly improved these figures with specialized processors and training, but generalization to sizes much larger than seen remains central.
AI-discovered algorithms
The most visible direction is using networks and language models to search for new algorithms. We speak of AI-discovered algorithms when a learning-guided search produces an algorithm (or construction) improving the best known under a fixed metric. To read these papers always separate three pieces:
- Search space: what objects the system can produce and how it constructs them;
- Evaluator: the program deciding whether a candidate is correct and how good it is without human intervention;
- Result guarantee: whether correctness is proved, exhaustively checked or only tested on examples, and whether improvement is asymptotic or a constant on specific machines.
AlphaTensor: matrix products as a game
Multiplying matrices evaluates a bilinear map encoded as an order-3 tensor . An algorithm using scalar multiplications is exactly a decomposition : each summand says which combination of inputs of () to multiply by which combination of () and where to add the product in (). Strassen’s algorithm is a rank-7 decomposition of , and since it does not use commutativity, recursive application gives exponent , connected to the matrix multiplication exponent.
Fawzi and coauthors (Nature, 2022) made decomposition search a one-player game, TensorGame: state is the tensor remaining to decompose, each move subtracts a rank-1 tensor, and reaching the zero tensor in the fewest moves wins. With over possible moves in most cases, they solved it using an AlphaZero-based agent (network plus Monte Carlo tree search). Results: matrices with 47 multiplications in modulo-2 arithmetic (Strassen twice uses 49), with 96 modulo 2 (previous record 98), product by with 76 in standard arithmetic (previously 80), and variants tuned faster than Strassen on matrices on a V100 GPU and TPU v2.
Two qualifications matter. The 47 result holds only in characteristic 2, so it does not improve the exponent over reals. Days later Kauers and Moosbauer reduced modulo 2 to 95 using learning-free local search, random walks on a “flip graph” of decompositions. The guarantee, however, is as good as possible: a decomposition is checked by summing tensors, without statistical testing.
import numpy as np, itertools, math
def tensor_matmul(n):
"""T[a, b, c] = 1 si la entrada a de A por la b de B contribuye a la c de C = AB (índices aplanados por filas)."""
T = np.zeros((n * n, n * n, n * n), dtype=int)
for i, j, k in itertools.product(range(n), repeat=3):
T[i * n + j, j * n + k, i * n + k] = 1
return T
# Strassen (1969) como suma de 7 tensores de rango 1: u_r ⊗ v_r ⊗ w_r
# entradas aplanadas: A = [a11 a12 a21 a22], igual para B y C
U = np.array([[1,0,0,1],[0,0,1,1],[1,0,0,0],[0,0,0,1],[1,1,0,0],[-1,0,1,0],[0,1,0,-1]])
V = np.array([[1,0,0,1],[1,0,0,0],[0,1,0,-1],[-1,0,1,0],[0,0,0,1],[1,1,0,0],[0,0,1,1]])
Wc = np.array([[1,0,0,1],[0,0,1,-1],[0,1,0,1],[1,0,1,0],[-1,1,0,0],[0,0,0,1],[1,0,0,0]])
T2 = tensor_matmul(2)
reconstruido = np.einsum("ra,rb,rc->abc", U, V, Wc)
print("Strassen reconstruye el tensor 2x2 exactamente:", np.array_equal(reconstruido, T2),
" (rango ≤ 7; el producto ingenuo usa 8)")
# el evaluador de AlphaTensor: una descomposición válida es un algoritmo correcto, sin más pruebas
A, B = np.random.default_rng(0).integers(-9, 10, (2, 2, 2))
m = (U @ A.ravel()) * (V @ B.ravel()) # las 7 multiplicaciones
print("C con 7 productos:", (Wc.T @ m).reshape(2, 2).tolist(), " A @ B:", (A @ B).tolist())
# exponentes que da aplicar recursivamente un algoritmo n x n con r productos: n^(log_n r)
for nombre, n, r in [("ingenuo 2x2", 2, 8), ("Strassen 2x2", 2, 7), ("4x4 con 49 (Strassen dos veces)", 4, 49),
("4x4 con 47 (AlphaTensor, solo en Z2)", 4, 47), ("4x4 con 48 (AlphaEvolve, complejos)", 4, 48)]:
print(f"{nombre:38s} exponente log_{n} {r} = {math.log(r, n):.4f}")An algorithm with 47 products would give exponent , better than Strassen’s , but only modulo 2. None is close to best theoretical bounds on , below 2.372 and derived by algebraic methods (the “laser method”) impractical in practice: search improves small useful algorithms, not asymptotics.
AlphaDev: short assembly sorting routines
Mankowitz and coauthors (Nature, 2023) posed another game, AssemblyGame: an agent adds x86 assembly instructions and wins if the program is correct and fast. The evaluator checks correctness with test inputs (for sorting 3 elements, all possible sequences) and measures actual machine latency. Production results are routines sorting fixed 3, 4 and 5 elements, the base case of hybrid sorting in LLVM’s C++ standard library libc++: sort3 with 17 instructions versus 18, sort4 with 28 (matching the human reference), and sort5 with 42 versus 46. The paper reports the patch improved sorting sequences of 5 by up to 70 % and sequences over 250000 by about 1.7 %, the first change to those subroutines in over a decade.
Instructive is where the improvement lies. The agent found what the authors call the swap move: in a sorting network, if an earlier comparator already guarantees , computing is equivalent to computing , saving an instruction. It is a constant in a base case, hence its large effect on short sequences and small effect on long ones. Lab 2 reproduces it in miniature and shows exhaustive search finds it in under a second on such a small problem and proves it cannot be improved.
FunSearch: program search with a language model
Romera-Paredes and coauthors (Nature, 2024) changed the search space: instead of solutions, programs producing solutions. A code language model (Codey, PaLM 2 family, used without fine-tuning) receives two good population programs and proposes a new one; an evaluator runs it, discards failures or timeouts and scores the rest; the population lives in independently evolving islands periodically restarted from the best. This is language-model-guided evolutionary search with an executable verifier stopping model “hallucinations” entering the population. Results used on the order of model samples.
In mathematics it found a cap set (a set of with no three collinear points) of 512 elements in dimension 8, larger than known ones, and raised the lower bound on such sets’ capacity from 2.2180 to 2.2202. Algorithmically it evolved online bin-packing heuristics: on OR1–OR4 datasets, excess-bin fraction fell, for example on OR4, from 5.23 % for first fit and 4.94 % for best fit to 2.47 %, and on Weibull instances of 100000 items from 3.79 % for best fit to 0.03 %. Guarantees differ: the cap set is a concrete object anyone can check; the packing heuristic has only empirical evidence on those distributions. A real advantage is a short program a person can read and generalize.
AlphaEvolve: evolving complete code
AlphaEvolve (Novikov, Balog and coauthors, 2025) generalizes FunSearch: it evolves entire code files with Gemini models and one or more cascaded evaluators (small tests first to reject defective programs early). Widely cited results: a procedure multiplying complex matrices with 48 scalar multiplications, the first improvement over Strassen in that context in 56 years; improvements in 14 matrix multiplication cases; on over 50 open mathematical problems, matching the best known construction about 75 % and improving it about 20 % (e.g. 593 touching spheres in dimension 11 versus 592); and in Google infrastructure, a scheduling heuristic recovering on average 0.7 % of fleet compute capacity and a 23 % improvement in a compute kernel reducing Gemini training time by 1 %. These are the paper’s own results; mathematical constructions are independently verifiable, infrastructure results are not.
The interactive is the skeleton of these systems at toy scale. The search space is comparator sequences; the evaluator is the 0–1 principle for sorting networks, turning a check of cases into a proof; search uses evaluator-selected random mutations. AlphaDev or AlphaEvolve change the candidate generator (trained network, language model) and problem size, not architecture.
Lab 2: mini AlphaDev
This lab runs locally: no GPU needed, but the first search takes a couple of minutes on a desktop CPU. Three parts: search sorting networks of 3 to 8 wires with a 0–1 principle evaluator and compare random search; find the shortest routine sorting 3 registers with a minimal instruction repertoire; and try the same for 4.
import random, time
def cables_iniciales(n):
"""Cable i como entero de 2^n bits: el bit x vale el bit i de la entrada 0-1 número x."""
return [sum(((x >> i) & 1) << x for x in range(1 << n)) for i in range(n)]
def evaluar(red, n, W0):
"""Evaluador exacto por el principio 0-1: (entradas 0-1 que no ordena, comparadores que actúan alguna vez)."""
w, util = list(W0), []
for i, j in red:
a, b = w[i], w[j]
util.append(a & ~b != 0) # el comparador intercambia en alguna entrada
w[i], w[j] = a & b, a | b # mínimo arriba, máximo abajo
malas = 0
for i in range(n - 1):
malas |= w[i] & ~w[i + 1] # entradas con un 1 encima de un 0
return bin(malas).count("1"), util
def podar(red, n, W0):
while True:
_, util = evaluar(red, n, W0)
if all(util):
return red
red = [c for c, u in zip(red, util) if u]
def par(n, R):
i, j = R.sample(range(n), 2)
return (min(i, j), max(i, j))
def mutar(red, n, R):
red, r = list(red), R.random()
if r < 0.35 or not red: red.insert(R.randint(0, len(red)), par(n, R))
elif r < 0.55: del red[R.randrange(len(red))]
elif r < 0.85: red[R.randrange(len(red))] = par(n, R)
elif len(red) > 1:
a, b = R.sample(range(len(red)), 2); red[a], red[b] = red[b], red[a]
return red
def evolucion(n, presupuesto, pob=60, semilla=0):
R, W0, evals = random.Random(semilla), cables_iniciales(n), 0
def nota(red):
nonlocal evals
evals += 1
return evaluar(red, n, W0)[0] * 100 + len(red)
P = [(nota(r), r) for r in (podar([par(n, R) for _ in range(n * n)], n, W0) for _ in range(pob))]
primera = None
while evals < presupuesto:
P.sort(key=lambda t: (t[0], R.random()))
if primera is None and P[0][0] == OPTIMO[n]: primera = evals
elite = P[: pob // 5]
hijos = []
for _ in range(pob - len(elite)):
h = R.choice(elite)[1]
for _ in range(R.choice([1, 1, 2, 3])): h = mutar(h, n, R)
if evaluar(h, n, W0)[0] == 0: h = podar(h, n, W0)
hijos.append((nota(h), h))
P = elite + hijos
mejor = min(P, key=lambda t: t[0])
return len(mejor[1]), mejor[0] // 100, primera, mejor[1]
def aleatoria(n, presupuesto, largo, semilla=0):
"""Línea base: redes aleatorias de `largo` comparadores, podadas; se queda con la menor que ordena."""
R, W0, mejor, primera = random.Random(semilla), cables_iniciales(n), None, None
for e in range(1, presupuesto + 1):
red = [par(n, R) for _ in range(largo)]
if evaluar(red, n, W0)[0] == 0:
red = podar(red, n, W0)
if mejor is None or len(red) < len(mejor): mejor = red
if primera is None and len(red) == OPTIMO[n]: primera = e
return (len(mejor) if mejor else None), primera
OPTIMO = {3: 3, 4: 5, 5: 9, 6: 12, 7: 16, 8: 19} # mínimos conocidos (Knuth, TAOCP vol. 3, §5.3.4)
presupuesto = 60_000
print(f"presupuesto: {presupuesto} evaluaciones por búsqueda, 3 semillas")
print(f"{'n':>2} | {'óptimo':>6} | {'evolutiva: tamaños':>18} | {'evals hasta el óptimo':>22} | {'aleatoria: tamaños':>18} | {'evals hasta el óptimo':>22}")
t0 = time.time()
for n in (3, 4, 5, 6, 7, 8):
ev = [evolucion(n, presupuesto, semilla=s) for s in range(3)]
al = [aleatoria(n, presupuesto, largo=n * (n - 1) // 2 + 2 * n, semilla=s) for s in range(3)]
print(f"{n:>2} | {OPTIMO[n]:>6} | {str([e[0] for e in ev]):>18} | {str([e[2] for e in ev]):>22} | "
f"{str([a[0] for a in al]):>18} | {str([a[1] for a in al]):>22}")
print(f"tiempo total: {time.time() - t0:.0f} s")npm run lab and open the connection link.The result has two readings. Up to 6 wires, the problem is too easy to distinguish methods: pruned random search finds optimal networks in one to a few thousand evaluations; evolutionary search already has them in its initial population (first 60 evaluations) through 5 wires and finds 6 in hundreds. With 7 and 8 wires the difference appears: evolutionary reaches 16 comparators on 7 wires for all three seeds and 19 on 8 for one (20 and 21 for the others), while random stays at 17 or 18 and 23 or 24. First rule for reading search results: without a simple baseline under the same budget, you cannot tell whether credit belongs to method or problem.
The second part imitates AlphaDev with three register instructions: MIN d, s does , MAX d, s does , and MOV d, s copies. Registers P, Q, R hold input and must end sorted; S is temporary. A comparator costs three instructions (MOV S, P, MIN P, Q, MAX Q, S), so a 3-comparator network gives a 9-instruction program.
Again the evaluator is exact for a reason worth proving. Each register at every point computes a function of the input built only from and . If is increasing, and likewise for , so the program commutes with . If it fails to sort a real input , some output differs from the -th smallest of ; taking with between those values gives a 0–1 input it also fails to sort. Thus testing the 0–1 inputs suffices, as for networks. With that evaluator, breadth-first search over register states finds a shortest program and proves none shorter exists.
import math, random, time
# Repertorio mínimo: tres instrucciones sobre registros. Los n primeros guardan la entrada y deben acabar ordenados;
# los T siguientes son temporales y empiezan sin valor (leerlos antes de escribirlos no está permitido).
MIN, MAX, MOV = 0, 1, 2
NOMBRE = {MIN: "MIN", MAX: "MAX", MOV: "MOV"}
def problema(n):
"""Estado inicial y objetivo sobre las 2^n entradas 0-1 (bit x de un registro = su valor en la entrada x)."""
N = 1 << n
ini = [sum(((x >> i) & 1) << x for x in range(N)) for i in range(n)]
obj = [sum(1 << x for x in range(N) if bin(x).count("1") >= n - i) for i in range(n)] # i-ésimo menor
return ini, obj
def paso(r, o, d, s):
if o == MIN: r[d] = r[d] & r[s]
elif o == MAX: r[d] = r[d] | r[s]
else: r[d] = r[s]
def superoptimizar(n, T, max_largo):
"""Búsqueda en anchura sobre estados de registros: el primer programa que ordena es de longitud mínima."""
ini, obj = problema(n)
regs = n + T
instr = [(o, d, s) for o in (MIN, MAX, MOV) for d in range(regs) for s in range(regs) if d != s]
ini = tuple(ini + [None] * T)
padre, frontera = {ini: None}, [ini]
for largo in range(1, max_largo + 1):
nueva = []
for st in frontera:
for o, d, s in instr:
if st[s] is None or (o != MOV and st[d] is None):
continue
r = list(st); paso(r, o, d, s); r = tuple(r)
if r in padre:
continue
padre[r] = (st, (o, d, s)); nueva.append(r)
if list(r[:n]) == obj:
prog = []
while padre[r] is not None:
r, i = padre[r]; prog.append(i)
return prog[::-1], len(padre)
frontera = nueva
return None, len(padre)
def como_red(red, n):
"""Traduce cada comparador (i, j) a MOV t,i; MIN i,j; MAX j,t (t = primer temporal)."""
t, prog = n, []
for i, j in red:
prog += [(MOV, t, i), (MIN, i, j), (MAX, j, t)]
return prog
def correcto(prog, n, T):
ini, obj = problema(n)
r = ini + [None] * T
for o, d, s in prog:
if r[s] is None or (o != MOV and r[d] is None): return False
paso(r, o, d, s)
return r[:n] == obj
reg = lambda k: "PQRSTU"[k]
t0 = time.time()
prog, estados = superoptimizar(3, 1, 9)
print(f"sort3 como red de 3 comparadores: {len(como_red([(0, 1), (1, 2), (0, 1)], 3))} instrucciones,",
"correcta:", correcto(como_red([(0, 1), (1, 2), (0, 1)], 3), 3, 1))
print(f"sort3 mínimo con un temporal: {len(prog)} instrucciones ({estados} estados explorados, {time.time() - t0:.1f} s)")
for o, d, s in prog:
print(f" {NOMBRE[o]} {reg(d)}, {reg(s)}")npm run lab and open the connection link.Breadth-first search explores about 88000 states and finds an 8-instruction program, one fewer than the network. Read it with input : the first three instructions compare P and Q, leaving in P, in Q and in S. The fourth, MIN S, P, copies into S because . Then P receives , S becomes , R receives and Q ends at , the median. The saving uses that is already known after the first comparator: the same type of idea as AlphaDev’s swap move. Because search is exhaustive, it also proves no 7-instruction program exists with these instructions and one temporary.
def coste(prog, n, T, ini, obj):
"""Bits de salida incorrectos más una penalización por leer registros sin valor: guía la búsqueda local."""
r, pen = ini + [None] * T, 0
for o, d, s in prog:
if r[s] is None or (o != MOV and r[d] is None):
pen += 50; continue
paso(r, o, d, s)
if any(v is None for v in r[:n]): return 10**6
return pen + sum(bin(r[i] ^ obj[i]).count("1") for i in range(n))
def recocido(n, T, inicio, iters, semilla):
R = random.Random(semilla)
ini, obj = problema(n)
regs = n + T
instr = [(o, d, s) for o in (MIN, MAX, MOV) for d in range(regs) for s in range(regs) if d != s]
cur = list(inicio); c = coste(cur, n, T, ini, obj)
for it in range(iters):
nuevo = list(cur)
for _ in range(R.choice([1, 1, 2])):
nuevo[R.randrange(len(nuevo))] = R.choice(instr)
cn = coste(nuevo, n, T, ini, obj)
temp = max(0.05, 1.5 * (1 - it / iters))
if cn <= c or R.random() < math.exp((c - cn) / temp):
cur, c = nuevo, cn
if c == 0:
return cur, it
return None, iters
red4 = [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)]
base = como_red(red4, 4)
print("sort4 como red de 5 comparadores:", len(base), "instrucciones, correcta:", correcto(base, 4, 1))
t0 = time.time()
for semilla in range(4):
R = random.Random(semilla)
inicio = list(base); del inicio[R.randrange(len(inicio))] # quitar una instrucción y reparar
prog, it = recocido(4, 1, inicio, 300_000, semilla)
print(f" semilla {semilla}: {'encontrado ' + str(len(prog)) if prog else 'ningún programa de 14'}"
f" tras {it + 1 if prog else it} iteraciones")
print(f"tiempo: {time.time() - t0:.0f} s")npm run lab and open the connection link.With 4 registers the state space is much larger (each register can contain any of 166 functions of 4 variables built from minima and maxima, versus 18 for 3 variables), so here we try local search. Simulated annealing starting from the 15-instruction network minus one finds no 14-instruction program in four seeds of 300000 iterations. This does not prove none exists: a failed local search is not a lower bound. It matches AlphaDev’s sort4 result (28 instructions, same as human reference), but uses a different repertoire and cannot simply be transferred.
To go further, replace mutar with a local language model in the style of FunSearch: put the population’s two best networks in its prompt and ask for a list of comparators. The question is whether it proposes better mutations than random ones with the same evaluation budget. This snippet is not part of the lesson cells: it has only been checked to load the model and return a comparator list. To use it within evolucion, pass two elite networks instead of one, and compare the resulting table with the first cell at the same evaluation budget.
import re
from transformers import pipeline
gen = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device_map="auto")
def mutar_llm(padres, n, R):
texto = "\n".join(f"red {k}: {p}" for k, p in enumerate(padres))
prompt = (f"Estas son redes de ordenación de {n} cables, listas de comparadores (i, j) con i < j:\n{texto}\n"
f"Escribe una red nueva, parecida pero más corta, con el mismo formato. Solo la lista.")
salida = gen(prompt, max_new_tokens=200, do_sample=True, temperature=0.8)[0]["generated_text"][len(prompt):]
pares = [(int(a), int(b)) for a, b in re.findall(r"\((\d+),\s*(\d+)\)", salida)]
pares = [(min(a, b), max(a, b)) for a, b in pares if a != b and max(a, b) < n]
return pares or mutar(padres[0], n, R) # si la respuesta no se entiende, mutación aleatoria
How to evaluate these results
With the three pieces (space, evaluator, guarantee) and the labs, these questions separate an algorithmic contribution from a good headline:
- What does the evaluator guarantee? An algebraic identity (AlphaTensor) or exhaustive checking on a finite domain with a principle turning it into proof (sorting networks, sort3) is a proof. A test set is evidence. Measured latency is a measurement on particular machines, with variance.
- Is there independent verification? Ideally an object anyone can check (decomposition, cap set, program with proof) or formal verification. Internal-system improvements without code or data cannot be reproduced.
- What baseline and budget? Kauers and Moosbauer improved an AlphaTensor result in days with local search; in the lab random search matches evolution through 6 wires. Search compute cost (millions of model samples, thousands of machine hours) is part of the result.
- Asymptotic improvement or constant? 47 multiplications on modulo 2 do not change over reals; one fewer sort3 instruction means 70 % for sequences of 5 and 1.7 % on large sequences. Both can matter, but are different.
- What was discovered? An object (network, decomposition), a program generating objects (FunSearch), or a transferable idea (swap move). The last most resembles what we call a new algorithm, and is almost always extracted by a person reading what the machine found.
Open problems
The lesson also maps what is unknown. Specific questions at the intersection of algorithms and learning:
- Pivots. Is there a worst-case polynomial simplex pivot rule? Related: is polyhedron diameter polynomially bounded (polynomial Hirsch conjecture)? Is there a strongly polynomial linear-programming algorithm, ninth on Smale’s list?
- Learned predictions. Prediction-augmented theory treats prediction as given. How many samples learn a prediction with the error the algorithm requires? How combine several predictions, or adapt without knowing model quality?
- Dynamic learned indexes. Maintain worst-case guarantees with insertions and deletions and changing distributions without rebuilding the whole model.
- Practical flows. Is there a nearly linear flow version with reasonable constants, or an equally fast combinatorial one?
- Algorithmic generalization. Which architectures and supervision make a network execute an algorithm correctly on inputs far larger than training inputs?
- Certifying discoveries. Search finds upper bounds (an algorithm with 47 or 48 products), but cannot prove lower bounds. The exact rank of the tensor for matrices is unknown. Combining search with formal provers in the style of counterexample-guided synthesis is active research.
Typical mistakes
Exercises
Step 1 of 4. Consistency, case . What bound follows?
More than one answer may be correct.
construir(keys, eps), which divides the sorted array keys (distinct integers) into consecutive segments and fits each with a line pos ≈ inicio + pendiente·(k − k_inicio) having absolute error at most eps on every key, and buscar(keys, tramos, k, eps), returning (posición, comparaciones): the position of key k (which is in keys) and the number of key comparisons within the window. Represent each segment as (k_inicio, inicio, pendiente). For construction use the greedy cone method: adding key to the segment starting at requires the slope to lie in ; maintain the intersection of these intervals and start a new segment when it becomes empty. To search, locate the segment with bisect on the k_inicio values (those comparisons do not count), predict position, and binary-search [floor(pred − eps), ceil(pred + eps)] clipped to the array.import bisect, math
def construir(keys, eps):
"""Devuelve una lista de tramos (k_inicio, inicio, pendiente)."""
# tu código: método voraz del cono
n = len(keys)
pendiente = (n - 1) / (keys[-1] - keys[0]) if n > 1 else 0.0
return [(keys[0], 0, pendiente)]
def buscar(keys, tramos, k, eps):
"""Devuelve (posición de k, comparaciones dentro de la ventana)."""
# tu código: ventana acotada por eps; ahora busca en todo el array
lo, hi, comp = 0, len(keys), 0
while lo < hi:
mid = (lo + hi) // 2
comp += 1
if keys[mid] < k:
lo = mid + 1
else:
hi = mid
return lo, compMore than one answer may be correct.
More than one answer may be correct.
Summary
- Dantzig-rule simplex makes pivots on the Klee–Minty cube, but in dimension 10 relative noise already divides pivots by over 8. Smoothed analysis formalizes this: the shadow rule has polynomial smoothed complexity (Spielman and Teng). Instance and universal optimality compare with the best algorithm on each input or graph, as Dijkstra with a working-set heap.
- An algorithm with predictions seeks consistency (near 1 if prediction is right), robustness (bounded if wrong), and smooth degradation. In ski rental, buying on day or gives , optimal for deterministic algorithms; in paging, Predictive Marker combines oracle and marking.
- A learned index models the key distribution with an error bound; correctness does not depend on the model, cost does. It wins when the model fits the distribution and must be compared with tuned B-trees using several metrics.
- Minimum-cost flow is solved in time using an interior-point method in norm whose steps, minimum-ratio cycles, are maintained by a dynamic data structure.
- Neural algorithmic reasoning teaches networks to execute algorithms; alignment (Bellman–Ford as minimum message passing) helps, and generalization to larger sizes remains open.
- Read AlphaTensor, AlphaDev, FunSearch and AlphaEvolve using three questions: search space, evaluator and guarantee. Demand independent verification, baselines under the same budget, and distinguish constants from asymptotics.