Module contents
Lesson 33 of 33Research 110 min

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 Rn\R^n, where simplex with Dantzig’s pivot rule visits all 2n2^n vertices before reaching optimum. With n=50n = 50 this exceeds 101510^{15} 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:

  1. 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.
  2. 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.
  3. 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 n≥1n \ge 1,

max⁡∑j=1n2n−jxjs.a.2∑j=1i−12i−jxj+xi≤5i(i=1,…,n),x≥0.\max \sum_{j=1}^n 2^{n-j} x_j \quad \text{s.a.} \quad 2\sum_{j=1}^{i-1} 2^{i-j} x_j + x_i \le 5^i \quad (i = 1, \dots, n), \qquad \vb{x} \ge \vb{0}.

The constraints say 0≤x1≤50 \le x_1 \le 5, that x2x_2 ranges from 0 to 25−4x125 - 4x_1, 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 2n2^n vertices in an order resembling Gray code: solve dimension n−1n - 1, jump to the opposite face of the last coordinate and solve dimension n−1n - 1 again in reverse. That takes 2n−12^n - 1 pivots. You will check this in the cell below for n≤10n \le 10.

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 σ→0\sigma \to 0 it recovers worst case: the adversary chooses the point and noise does not move it. When σ\sigma is large, noise dominates and the average case over Gaussians remains. For intermediate σ\sigma the adversary still chooses xˉ\bar{\vb{x}} but must win on average over a ball of radius on the order of σ\sigma 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.

InteractiveWorst case versus smoothing
Klee-Minty, n = 3012345677 pivotswith noise σ = 0.100012344 pivotsPivots versus dimension n14166425610242345678910Pivots versus σ (n = 8)14166425610241e−51e−41e−31e−21e−1
  • no noise: 2n−12^n - 1 pivots
  • with noise: mean of 24 samples (excluding unbounded)
  • range (minimum to maximum)
σ = 0.100
8
Worst case 2n−12^n - 1255
Mean with noise (22 samples)9.5
Range with noise6 to 15
Reduction27.0×
With σ=0.100\sigma = 0.100 the mean drops to 9.5 pivots in dimension 8, 27 times less than the worst case. The blue curve grows slowly with nn: the exponential path is a fragile balance.
Above, the 3-dimensional Klee–Minty cube, each coordinate divided by its maximum over the polyhedron (5i5^i without noise): numbers show the order in which Dantzig-rule simplex visits vertices from the origin. Left, without noise, it visits all; right, with coefficient noise σ\sigma, the path shortens. Below are pivots on a log scale versus dimension (without noise, 2n−12^n - 1; with noise, mean and range of 24 draws) and versus σ\sigma. Find the σ\sigma at which the exponential path breaks in dimension 10 and click ‘Otro sorteo’ (another draw) to see variation.

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 σmax⁡j∣aij∣ g\sigma\max_j\abs{a_{ij}}\,g with g∼N(0,1)g \sim \Normal(0, 1) to each coefficient in row ii of A\mat{A} (including zeros), and multiply bib_i by 1+σg1 + \sigma g. We use each row’s scale rather than the norm of (ai,bi)(\vb{a}_i, b_i) because in the Klee–Minty cube bi=5ib_i = 5^i dominates the row and the Spielman–Teng model applied directly would erase the structure of A\mat{A} for any reasonable σ\sigma. The cell reproduces the figure:

[ ]Klee–Minty with and without noiseBrowser
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 3,7,15,…,10233, 7, 15, \dots, 1023 pivots occur: 2n−12^n - 1. With noise, mean dimension-10 pivots fall from 1023 to about 122 with σ=10−4\sigma = 10^{-4}, 47 with 10−310^{-3}, 24 with 10−210^{-2} and 12 with 10−110^{-1}; 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 xx its cost is within a constant factor of any other correct algorithm on that same xx. 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 GG, its worst case over all weights on GG is, up to a constant, the best possible for that GG.

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, O(m+nlog⁡n)\bigO(m + n\log n), 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 BB, the season lasts unknown DD days, and OPT(D)=min⁡(D,B)\mathrm{OPT}(D) = \min(D, B). Buying at the start of day kk costs DD if D<kD < k and k−1+Bk - 1 + B if D≥kD \ge k; the best deterministic algorithm buys on day BB and pays at most 2−1/B2 - 1/B times optimum. Now a model predicts duration yy, with error η=∣y−D∣\eta = \abs{y - D}.

Blindly following prediction is tempting: if y≥By \ge B buy on day one; otherwise never buy. With η=0\eta = 0 you pay exactly OPT\mathrm{OPT}. But if y≥By \ge B and the season lasts one day, you pay BB for something worth 1; and if y<By < B and the season never ends, you pay DD without limit. The ratio is unbounded. Purohit, Svitkina and Kumar (NeurIPS 2018) proposed a rule with confidence parameter λ∈(0,1)\lambda \in (0, 1):

k(y)={⌈λB⌉si y≥B(la prediccioˊn dice «compra»: compra pronto, pero no el primer dıˊa),⌈B/λ⌉si y<B(dice «alquila»: alquila, pero compra si la temporada se alarga demasiado).k(y) = \begin{cases} \lceil\lambda B\rceil & \text{si } y \ge B \quad\text{(la predicción dice «compra»: compra pronto, pero no el primer día),} \\ \lceil B/\lambda\rceil & \text{si } y < B \quad\text{(dice «alquila»: alquila, pero compra si la temporada se alarga demasiado).} \end{cases}
Proof

You prove robustness and consistency in the final guided exercise. Here is the error-dependent bound. If the algorithm does not buy (D<kD < k), it pays D≤OPT+(D−B)+D \le \mathrm{OPT} + (D - B)^+, and in case y<By < B excess (D−B)+(D - B)^+ is at most D−y<ηD - y < \eta; in case y≥By \ge B it does not buy only if D<⌈λB⌉≤BD < \lceil\lambda B\rceil \le B, and then pays D=OPTD = \mathrm{OPT}. If it buys (D≥kD \ge k), there are two cases.

Case y≥By \ge B, k=⌈λB⌉k = \lceil\lambda B\rceil. It pays k−1+B<(1+λ)Bk - 1 + B < (1 + \lambda)B. If D≥BD \ge B, OPT=B\mathrm{OPT} = B and the ratio is below 1+λ1 + \lambda. If k≤D<Bk \le D < B, OPT=D\mathrm{OPT} = D and the prediction chose the wrong side: η=y−D≥B−D\eta = y - D \ge B - D. Then (1+λ)B=(1+λ)D+(1+λ)(B−D)≤(1+λ)OPT+(1+λ)η(1 + \lambda)B = (1 + \lambda)D + (1 + \lambda)(B - D) \le (1 + \lambda)\mathrm{OPT} + (1 + \lambda)\eta, and 1+λ≤1/(1−λ)1 + \lambda \le 1/(1 - \lambda) because (1+λ)(1−λ)=1−λ2≤1(1 + \lambda)(1 - \lambda) = 1 - \lambda^2 \le 1.

Case y<By < B, k=⌈B/λ⌉≥Bk = \lceil B/\lambda\rceil \ge B. It pays k−1+B<B/λ+Bk - 1 + B < B/\lambda + B and OPT=B\mathrm{OPT} = B. Again prediction chose the wrong side: η=D−y>D−B≥k−B≥B/λ−B=B(1−λ)/λ\eta = D - y > D - B \ge k - B \ge B/\lambda - B = B(1 - \lambda)/\lambda. Therefore

ALG−(1+λ)B<Bλ−λB=B(1−λ)(1+λ)λ<(1+λ) η≤η1−λ.\mathrm{ALG} - (1 + \lambda)B < \frac{B}{\lambda} - \lambda B = \frac{B(1 - \lambda)(1 + \lambda)}{\lambda} < (1 + \lambda)\,\eta \le \frac{\eta}{1 - \lambda}.

In all cases ALG≤(1+λ)OPT+η/(1−λ)\mathrm{ALG} \le (1 + \lambda)\mathrm{OPT} + \eta/(1 - \lambda); dividing by OPT\mathrm{OPT} and combining with robustness yields the stated minimum.

∎

Parameter λ\lambda quantifies the tradeoff. With λ=0.2\lambda = 0.2, a good prediction costs at most 20 % over optimum, but a bad one can approach 6 times; with λ=0.8\lambda = 0.8, 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 (1+λ)(1 + \lambda)-consistent algorithm is at least (1+1/λ)(1 + 1/\lambda)-robust (Gollapudi and Panigrahi, 2019; Wei and Zhang, 2020). The short argument: if prediction says the season is long, y≥By \ge B, and it is long, optimum is BB; to pay at most (1+λ)B(1 + \lambda)B one must buy before time λB\lambda B. But the adversary then ends the season at purchase, at t≤λBt \le \lambda B, and ratio is (t+B)/t≥1+1/λ(t + B)/t \ge 1 + 1/\lambda.

InteractiveConsistency versus robustness
Worst ALG/OPT with prediction error ≤ η12345≥ 600.5BB1.5B2Bmaximum error η1 + λ1 + 1/λConsistency versus robustness135791111.251.51.752impossible for deterministic algorithmsλ = 0.30consistency (ratio at η = 0)
  • with prediction and trust λ\lambda
  • follow prediction blindly
  • without prediction: 2−1/B2 - 1/B
  • your instance
  • frontier (1+λ, 1+1/λ)(1 + \lambda,\ 1 + 1/\lambda)
0.30
One instance
60 days
150 days
Purchase day30
ALG / OPT129 / 60 = 2.150
Error η=∣y−D∣\eta = \abs{y - D}90
Theoretical bound3.443
Measured consistency1.290
Measured robustness4.330
The prediction misses by 90 days and you pay 2.15 times the optimum, more than the guarantee without prediction (1.99). Still, the ratio stays within robustness 1+1/λ=4.331 + 1/\lambda = 4.33.
Above, the worst ratio an adversary can force when the prediction misses by at most η\eta days, computed exactly for B=100B = 100 by enumerating durations. With small λ\lambda the blue curve starts near 1 and rises to 1+1/λ1 + 1/\lambda; with λ=1\lambda = 1 it is flat at 2−1/B2 - 1/B; blind prediction (red) starts at 1 and grows without bound as error approaches BB (leaving the plot toward 0.83B0.83B). Below, the consistency–robustness plane: the curve is frontier (1+λ,1+1/λ)(1 + \lambda, 1 + 1/\lambda) and the shaded region what no deterministic algorithm can achieve. Move the instance (magenta) across BB and verify it always stays below the blue curve.

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 λ=0.5\lambda = 0.5, worst case rises from 1.491.49 at η=0\eta = 0 to 1.991.99 at error B/4B/4 and 2.982.98 when error reaches B/2B/2: 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 η\eta 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 η/OPT\eta/\mathrm{OPT} 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 kk 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 Hk=1+1/2+⋯+1/kH_k = 1 + 1/2 + \cdots + 1/k links it stops trusting the oracle and evicts randomly.

Its competitive ratio is 2+O(min⁡{η/OPT, log⁡k})2 + \bigO\big(\min\{\sqrt{\eta/\mathrm{OPT}},\ \log k\}\big); with absolute error, at most min⁡{2+25η/OPT, 4Hk}\min\{2 + 2\sqrt{5\eta/\mathrm{OPT}},\ 4H_k\}. In other words: nearly 2-consistent, degradation of order η/OPT\sqrt{\eta/\mathrm{OPT}}, and never worse than O(log⁡k)\bigO(\log k), 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 σ\sigma into phases: each is the longest segment requesting at most kk distinct pages, and the next starts with request for distinct page number k+1k + 1. 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 kk misses per phase. For optimum, let pp be the first page of phase jj and take the segment from the second request of phase jj to the first of phase j+1j + 1 inclusive. That segment requests kk distinct pages other than pp: the other k−1k - 1 of phase jj and the page opening phase j+1j + 1. At segment start pp is in OPT’s cache, which holds only kk pages, so those kk 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 FF phases, OPT≥F−1\mathrm{OPT} \ge F - 1 and ALG≤kF≤k OPT+k\mathrm{ALG} \le kF \le k\,\mathrm{OPT} + k. 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 kk to O(log⁡k)\bigO(\log k), 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 nn elements and a model predicts position pp. If you use exponential search from pp (compare at p±1,p±2,p±4,…p \pm 1, p \pm 2, p \pm 4, \dots until bracketing the key, then binary search the final interval) and the real position is distance dd from pp, you make O(log⁡(d+1))\bigO(\log(d + 1)) comparisons: with η=d\eta = d, perfect prediction costs O(1)\bigO(1) and terrible prediction O(log⁡n)\bigO(\log n), matching unadvised binary search. It is 1-consistent up to constants, robust, and degrades like log⁡η\log\eta. A learned index turns that idea into a data structure.

Learned indexes

An index over a sorted array of keys k0<k1<⋯<kn−1k_0 < k_1 < \dots < k_{n-1} answers “what is the position of key kk?” That position is exactly n F^(k)n\,\hat F(k), where F^\hat F is the keys’ empirical cumulative distribution function. A B-tree is, in this view, a piecewise-constant model of F^\hat F 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 F^\hat F.

The central observation of learned indexes is that correctness does not depend on model quality. Bounds e±e^\pm 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 ff plus at most ⌈log⁡2(e−+e++2)⌉\lceil\log_2(e^- + e^+ + 2)\rceil comparisons, and the model stores a few numbers per segment instead of a separator per block.

One model of F^\hat F 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 SS, 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.

InteractiveA learned index
position = n · F(key)0100200300400key →Binary search over the entire array8 comparisonsSearch inside the model window6 comparisons
  • keys (position versus value)
  • leaf lines and their error bands
  • search key
  • predicted position and window
Key distribution
8
250
Predicted / actual position244 / 250
Search window[185, 259)
Mean comparisons, learned5.27
Mean comparisons, binary8.72
Maximum window74
Model parameters34 numbers
An average of 5.27 comparisons versus 8.72. Increase the number of leaves so each line approximates a shorter segment of the curve.
Points are keys drawn as (value, position): their curve is nF^n\hat F. Each colored line is an index leaf with error band. Searching a key (magenta) predicts position (blue circle) and searches only between blue marks. The lower strips compare positions probed by whole-array binary search and by the index. Try the three distributions with 1, 8 and 32 leaves: when does the model stop helping, and why is lognormal harder although its curve looks smooth?

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 ε\varepsilon, 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 c(k)∈[0,1]c(k) \in [0, 1] trained to distinguish keys in the set decides first: if c(k)≥τc(k) \ge \tau, answer “present.” Since the classifier has false negatives, forbidden in a Bloom filter, set keys with c(k)<τc(k) < \tau 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.

[ ]Ski rental with predictionsBrowser
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 λ=0.2\lambda = 0.2 the ratio rises from 1.191.19 without error to 5.955.95 when error reaches BB; with λ=0.8\lambda = 0.8 from 1.791.79 to 2.242.24; with λ=1\lambda = 1 it is always 1.99=2−1/B1.99 = 2 - 1/B. Measured values stay below 1+λ1 + \lambda and 1+1/λ1 + 1/\lambda because days are integers: buying on day ⌈λB⌉\lceil\lambda B\rceil costs ⌈λB⌉−1+B\lceil\lambda B\rceil - 1 + B, one day less than in the continuous version. The last two lines check the theorem on more than seven million (D,y)(D, y) pairs: maximum slack is negative and the ratio never reaches 1+1/λ1 + 1/\lambda.

[ ]Paging with an oracle: blind or with a safety netBrowser
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 σ=512\sigma = 512 it is already worse than LRU (6008) and at σ=4096\sigma = 4096 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 4Hk OPT4H_k\,\mathrm{OPT} (H16≈3.38H_{16} \approx 3.38). The section’s pattern: the safety net costs something with a perfect oracle and saves the result otherwise.

[ ]Two-level learned index versus binary search and B-treeBrowser
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 mo(1)m^{o(1)} grows more slowly than any power mεm^\varepsilon; in this algorithm it grows faster than every power of log⁡m\log m: 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.

  1. An interior point reducing a potential. Write minimum-cost flow as linear program min⁡c⊤f\min \vb{c}\T\vb{f} with B⊤f=d\mat{B}\T\vb{f} = \vb{d} (conservation) and ue−≤fe≤ue+u^-_e \le f_e \le u^+_e. Instead of the classical logarithmic barrier, each iteration reduces potential Φ(f)=20mlog⁡(c⊤f−F∗)+∑e∈E[(ue+−fe)−α+(fe−ue−)−α],α=11000log⁡(mU),\Phi(\vb{f}) = 20m\log\big(\vb{c}\T\vb{f} - F^*\big) + \sum_{e \in E}\Big[(u^+_e - f_e)^{-\alpha} + (f_e - u^-_e)^{-\alpha}\Big], \qquad \alpha = \frac{1}{1000\log(mU)}, where F∗F^* is optimal cost. The power barrier penalizes nearly saturated edges more than a logarithm and keeps all numbers within a polylogarithmic bit count.
  2. Each step is a minimum-ratio cycle. The improvement direction is a circulation Δ\vb{\Delta} (B⊤Δ=0\mat{B}\T\vb{\Delta} = \vb{0}) minimizing g⊤Δ/∥LΔ∥1\vb{g}\T\vb{\Delta}/\norm{\mat{L}\vb{\Delta}}_1, where g\vb{g} is the gradient of Φ\Phi and L\mat{L} a diagonal of lengths. This is an ℓ1\ell_1-norm problem whose optimum is a simple cycle, instead of the ℓ2\ell_2-norm electrical flow of earlier interior-point methods. The authors show approximation factor mo(1)m^{o(1)} suffices and m1+o(1)m^{1+o(1)} steps reach optimum.
  3. Steps change little. From one iteration to the next only mo(1)m^{o(1)} 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 mo(1)m^{o(1)}.

m1+o(1)m^{1+o(1)} steps at mo(1)m^{o(1)} 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 mo(1)m^{o(1)} are enormous for practical mm, 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 dv←min⁡(dv, min⁡u→v(du+wuv))d_v \leftarrow \min\big(d_v,\ \min_{u \to v}(d_u + w_{uv})\big), and a message-passing layer with message du+wuvd_u + w_{uv}, minimum aggregation and minimum update is exactly that. A sum-aggregation network would have to learn to manufacture a minimum from sums, much harder.

[ ]A Bellman–Ford iteration is a message-passing layerBrowser
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 n×nn\times n evaluates a bilinear map encoded as an order-3 tensor Tn\mathcal{T}_n. An algorithm using RR scalar multiplications is exactly a decomposition Tn=∑r=1Rur⊗vr⊗wr\mathcal{T}_n = \sum_{r=1}^R \vb{u}_r \otimes \vb{v}_r \otimes \vb{w}_r: each summand says which combination of inputs of A\mat{A} (ur\vb{u}_r) to multiply by which combination of B\mat{B} (vr\vb{v}_r) and where to add the product in C\mat{C} (wr\vb{w}_r). Strassen’s algorithm is a rank-7 decomposition of T2\mathcal{T}_2, and since it does not use commutativity, recursive application gives exponent log⁡27\log_2 7, 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 101210^{12} possible moves in most cases, they solved it using an AlphaZero-based agent (network plus Monte Carlo tree search). Results: 4×44\times 4 matrices with 47 multiplications in modulo-2 arithmetic (Strassen twice uses 49), 5×55\times 5 with 96 modulo 2 (previous record 98), product 4×54\times 5 by 5×55\times 5 with 76 in standard arithmetic (previously 80), and variants tuned faster than Strassen on 8192×81928192\times 8192 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 5×55\times 5 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.

[ ]Strassen as a product tensor decompositionBrowser
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 4×44\times 4 algorithm with 47 products would give exponent log⁡447≈2.777\log_4 47 \approx 2.777, better than Strassen’s 2.8072.807, but only modulo 2. None is close to best theoretical bounds on ω\omega, 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 B≤CB \le C, computing min⁡(A,B,C)\min(A, B, C) is equivalent to computing min⁡(A,B)\min(A, B), 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 10610^6 model samples.

In mathematics it found a cap set (a set of Z3n\mathbb{Z}_3^n 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 4×44\times 4 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.

InteractiveEvaluator and search
01102031Comparator 1: wires 0 and 1 (select to remove)Comparator 2: wires 2 and 3 (select to remove)Comparator 3: wires 1 and 3 (select to remove)Comparator 4: wires 1 and 2 (select to remove)16 binary inputs (bit i = wire i): green sorted, red not0000: sorted1000: sorted0100: sorted1100: not sorted0010: sorted1010: sorted0110: sorted1110: not sorted0001: sorted1001: sorted0101: sorted1101: not sorted0011: sorted1011: sorted0111: sorted1111: sorted
  • comparator: minimum above, maximum below
  • comparator that never acts
  • wire with value 1 for selected input
  • unsorted binary input
Number of wires nn
Append a comparator
Comparators4
Unsorted binary inputs3 of 16
Comparators that never act0
Known minimum5
Selected input → output1100 → 1001
The network fails to sort 3 of the 16 binary inputs, so it also fails to sort all real inputs: the evaluator rejects it. Select a red cell to see the failure.
A sorting network with nn wires: each comparator puts the minimum above and maximum below. The evaluator tests the 2n2^n zero/one inputs, sufficient by the 0–1 principle to certify sorting of any input. Red boxes are unsorted inputs: click one and follow thick wires (carrying 1) to see where it stalls. Gray comparators never act and can be pruned. Fix the broken network manually; then click ‘Evolucionar’ (evolve), launching elite-plus-mutation search with this evaluator, and compare the size found with the known minimum.

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 2n2^n 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.

[ ]Evolutionary versus random sorting-network searchLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 d←min⁡(d,s)d \leftarrow \min(d, s), MAX d, s does d←max⁡(d,s)d \leftarrow \max(d, s), 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 min⁡\min and max⁡\max. If ϕ\phi is increasing, ϕ(min⁡(a,b))=min⁡(ϕ(a),ϕ(b))\phi(\min(a, b)) = \min(\phi(a), \phi(b)) and likewise for max⁡\max, so the program commutes with ϕ\phi. If it fails to sort a real input x\vb{x}, some output ii differs from the ii-th smallest of x\vb{x}; taking ϕ(t)=1[t≥θ]\phi(t) = \ind[t \ge \theta] with θ\theta between those values gives a 0–1 input it also fails to sort. Thus testing the 2n2^n 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.

[ ]Superoptimizing sort3 with MIN, MAX and MOVLocal GPU
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)}")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 (a,b,c)(a, b, c): the first three instructions compare P and Q, leaving min⁡(a,b)\min(a, b) in P, max⁡(a,b)\max(a, b) in Q and aa in S. The fourth, MIN S, P, copies min⁡(a,b)\min(a, b) into S because min⁡(a,min⁡(a,b))=min⁡(a,b)\min(a, \min(a, b)) = \min(a, b). Then P receives min⁡(a,b,c)\min(a, b, c), S becomes max⁡(min⁡(a,b),c)\max(\min(a, b), c), R receives max⁡(a,b,c)\max(a, b, c) and Q ends at min⁡(max⁡(a,b),max⁡(min⁡(a,b),c))\min\big(\max(a, b), \max(\min(a, b), c)\big), the median. The saving uses that min⁡(a,b)≤max⁡(a,b)\min(a, b) \le \max(a, b) 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.

[ ]sort4: local search from the networkLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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:

  1. 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.
  2. 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.
  3. 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.
  4. Asymptotic improvement or constant? 47 multiplications on 4×44\times 4 modulo 2 do not change ω\omega over reals; one fewer sort3 instruction means 70 % for sequences of 5 and 1.7 % on large sequences. Both can matter, but are different.
  5. 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 λ\lambda 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 4×44\times 4 matrices is unknown. Combining search with formal provers in the style of counterexample-guided synthesis is active research.

Typical mistakes

Exercises

NumericPivots on the Klee–Minty cube
With Dantzig's rule starting at the origin, how many pivots does simplex make on the Klee–Minty cube of dimension n=12n = 12?
QuizWhat smoothed analysis measures
An algorithm takes time 2N2^N on a measure-zero set of inputs and N2N^2 on all others. Bad inputs are isolated: any perturbation leaves the set. Which statement is correct?
NumericA prediction on the wrong side
Ski rental with B=100B = 100 and the Purohit, Svitkina and Kumar algorithm with λ=0.25\lambda = 0.25. The model predicts y=300y = 300 days and the season lasts D=25D = 25. What is ratio ALG/OPT\mathrm{ALG}/\mathrm{OPT}?
ProofConsistency and robustness of prediction-based rental
Prove: For λ∈(0,1)\lambda \in (0, 1), the algorithm buying at the start of day k=⌈λB⌉k = \lceil\lambda B\rceil if y≥By \ge B and day k=⌈B/λ⌉k = \lceil B/\lambda\rceil if y<By < B is (1+λ)(1 + \lambda)-consistent and (1+1/λ)(1 + 1/\lambda)-robust.
0
Recall that buying on day kk costs DD if D<kD < k and k−1+Bk - 1 + B if D≥kD \ge k, and OPT(D)=min⁡(D,B)\mathrm{OPT}(D) = \min(D, B).

Step 1 of 4. Consistency, case y=D≥By = D \ge B. What bound follows?

QuizSpace, evaluator and guarantee
Which statements about AlphaTensor, AlphaDev and FunSearch are correct?

More than one answer may be correct.

NumericLearned index versus binary search
A learned index on 10910^9 sorted keys guarantees the real position is at most 64 positions above or below the predicted one. In the worst case, how many times more key comparisons does whole-array binary search make than binary search inside the index window? Ignore model evaluation cost.
CodeA piecewise-linear learned index with error bound
Implement 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 ii to the segment starting at ss requires the slope to lie in [(i−s−ε)/(ki−ks), (i−s+ε)/(ki−ks)][(i - s - \varepsilon)/(k_i - k_s),\ (i - s + \varepsilon)/(k_i - k_s)]; 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, comp
Shift+Enter to run
QuizThe learned Bloom filter guarantee
A learned Bloom filter uses a threshold classifier and a backup Bloom filter for keys the classifier rejects. In validation its false-positive rate is 1 %. What can you assert?

More than one answer may be correct.

QuizWhat is new in nearly linear flow?
What best describes Chen and coauthors' (2022) minimum-cost flow algorithm?
QuizReading an announcement critically
A lab announces: ‘Our AI discovered a sorting algorithm 30 % faster than the standard library.’ Its release includes server timing graphs and no published code. What is needed for a solid algorithmic contribution?

More than one answer may be correct.

Summary

Key idea
Worst case is a guarantee, not a prediction; current research complements it with more realistic analyses, algorithms using predictions without losing guarantees, and searches discovering algorithms. In every case what matters is what can be proved and what has only been measured.
  • Dantzig-rule simplex makes 2n−12^n - 1 pivots on the Klee–Minty cube, but in dimension 10 relative noise 10−410^{-4} 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 ⌈λB⌉\lceil\lambda B\rceil or ⌈B/λ⌉\lceil B/\lambda\rceil gives (1+λ,1+1/λ)(1 + \lambda, 1 + 1/\lambda), 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 m1+o(1)m^{1+o(1)} using an interior-point method in ℓ1\ell_1 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.