Module contents
Stage 6 of 9Research 110 min

Training AlphaZero and measuring it against the truth

Train the agent from scratch over several nights and track its progress using what few RL projects have: the percentage of optimal moves according to the solver, alongside Elo against fixed opponents. Monitor training health signals and analyze positions where the agent still makes mistakes.

After this lesson you can

  • Train from scratch with self-play and record all dynamics signals.
  • Evaluate each generation by optimal-move percentage and Elo against fixed opponents.
  • Analyze remaining errors by game phase and position type.
  • Compare the network alone with network plus search at different simulation counts.

Before you start

A curve is not a demonstration

In previous lessons you built all the pieces: the Connect 4 exact solver, the policy-value network, network-guided PUCT search, and the self-play system that turns games into training targets. What remains separates an experiment from a claim: let the system learn from random weights for hours and know what it has learned.

That is harder than it sounds, because in reinforcement learning the agent itself produces the targets. Policy loss measures how well the network imitates its own search visits; value loss measures how well it predicts outcomes of games against itself. Both can decrease while the agent becomes trapped in a poor style, because the pupil writes their own exam. That is why this project uses a solved game: Connect 4 has an oracle that answers the exact outcome of each column for any position. Almost no RL project has such a tool, and we will make full use of it.

Three questions guide the lesson, each with its own instrument:

  1. Is training healthy? Dynamics signals: losses with their floor and ceiling, entropies, game length, first-player advantage, and policy change between generations. They do not measure strength, but detect failures before they cost a GPU night.
  2. Is the agent strong? Elo against a ladder of fixed opponents, calculated once and frozen. Never only against previous versions of itself.
  3. Is it correct? The percentage of moves preserving theoretical value on a solver-labeled position set, with a confidence interval, separated by phase and with network alone versus network with search.

The final lab provides the full system at scale: a residual network with 5 blocks and 128 channels, 600 simulations per move and 5000 games per generation, the scale of the public AlphaZero.jl replication for this game. You launch it and it runs for several nights. Figures on this page use data from a short verification run of the same code (20 generations of 400 games with 100 simulations and a 4-block, 64-channel network, about 15 GPU minutes), and expected full-run results are indicated using published reference replication figures.

The experiment: what runs and what is recorded

A multi-night run must be auditable afterward. Apply everything from experiment tracking: each run has its own folder with full configuration, seed, parameter count, and a metrics file with one line per generation. Since nothing guarantees the machine will last three nights straight, after each generation the loop saves everything needed for exact resumption: weights, optimizer state, NumPy and PyTorch random-generator states (CPU and CUDA), the replay buffer with its pointer, and the previous generation’s policy on validation positions.

Exact means exact. With cuBLAS and cuDNN in deterministic mode, the lab checks that training two generations consecutively and training one, interrupting, and resuming produce the same weights bit for bit, verified with a SHA-256 digest of all tensors. If equality fails, some state is not being saved; it is better to find out in a one-minute test than after a four-in-the-morning crash.

Define the vocabulary. Generation kk is the network fθkf_{\theta_k} resulting from kk self-play and training phases; generation 0 is the random weights. In phase kk, network fθk−1f_{\theta_{k-1}} plays 400 games against itself (5000 in the full run), its positions enter the buffer, and the optimizer takes a fixed number of steps to produce fθkf_{\theta_k}. The self-play statistics in row kk therefore describe network k−1k - 1; losses describe the batches that produced network kk; and evaluations describe frozen network kk itself. Mixing these three origins in one sentence is the first error in interpreting a training dashboard.

Parallelism deserves a note. In lesson 5 one CUDA-owning server received requests from several worker processes. Here we use the other classic way of batching leaf evaluations: one process plays GG games at once, each simulation descends in all GG trees in parallel using vectorized NumPy operations, and all new leaves are evaluated in one batch. There are no queues, threads, or virtual loss, and the GPU receives batches of up to GG positions (1024 in the full configuration, 400 in the short one). On a laptop RTX 4060, this design sustains approximately 37,000 large-network evaluations per second, measured with the lab code.

Training health signals

None of these signals measures agent strength. Their role is to detect failures (a reversed sign, exploration collapse, an emptying buffer) in the first hour rather than the third day. This is the same craft as PPO policy optimization diagnostics and signal-based debugging in the continuous RL project, with one difference: here search produces policy targets, changing what each curve means. To read them, you need to know what each would be if the network had learned nothing, and for two of them the answer is a small theorem.

Policy loss has a floor

For a position ss with visit target π=π(⋅∣s)\pi = \pi(\cdot \given s) and network policy pθ=pθ(⋅∣s)p_\theta = p_\theta(\cdot \given s), both over legal moves, policy loss is cross-entropy H(π,pθ)=−∑aπ(a)log⁡pθ(a)H(\pi, p_\theta) = -\sum_a \pi(a)\log p_\theta(a).

Proof

H(π,pθ)=−∑aπ(a)log⁡π(a)+∑aπ(a)log⁡π(a)pθ(a)=H(π)+KL⁡(π ∥ pθ)H(\pi, p_\theta) = -\sum_a \pi(a)\log \pi(a) + \sum_a \pi(a)\log\frac{\pi(a)}{p_\theta(a)} = H(\pi) + \KL(\pi\,\|\,p_\theta), and KL divergence is nonnegative (Gibbs’ inequality), zero only if the distributions agree where π>0\pi > 0.

∎

The practical consequence matters. Policy loss mixes two things: what the network has not yet learned, KL⁡(π ∥ pθ)\KL(\pi \,\|\, p_\theta), and how dispersed its targets are, H(π)H(\pi), which the network cannot reduce. When search improves, its visits concentrate, H(π)H(\pi) falls, and pulls loss down even if the network has gained nothing. Conversely, more Dirichlet noise or exploration simulations raise H(π)H(\pi) and loss. The lab therefore logs H(π)H(\pi) on the same batches and the dashboard draws it as a floor: the gap is what matters.

Value loss has a ceiling

The value head predicts z∈{−1,0,1}z \in \{-1, 0, 1\}, the final outcome from the player-to-move perspective, using squared error. What error does a network that ignores the board have?

Expand the square around E[z]\E[z]: the cross term has zero expectation. Thus Var⁡(z)\Var(z), calculated on each phase’s new positions, is the error of someone knowing only outcome frequencies, and 1−MSE/Var⁡(z)1 - \text{MSE}/\Var(z) is the fraction of outcome variance explained by the network, an R2R^2. A value loss stuck at Var⁡(z)\Var(z) means the value head is not learning; the most frequent cause is a perspective error assigning each position the wrong player’s outcome, making the target pure noise to the network. If draws are rare and zz signs are balanced, Var⁡(z)≈1\Var(z) \approx 1, and value loss 0.5 already explains half the variance.

Entropy, length, and first-player advantage

Normalized entropy H(p)/log⁡∣A(s)∣H(p)/\log\abs{A(s)} is 1 for a uniform policy over the ∣A(s)∣\abs{A(s)} legal moves and 0 for a deterministic one; it is recorded as 0 by convention when only one move is legal. Distinguish three entropies: network entropy in training batches, root-prior entropy during play, and visit entropy used as targets. The first two describe the network; the third describes search with noise. A gradual decline is healthy. A plunge near zero in the first generations proves nothing good: the network is confident, but could be confident in a bad move, and a concentrated policy stops generating diverse games, filling the buffer with variations of the same game.

Mean length tells a readable story. With random weights no one blocks and games end around move 20; as the network learns to defend they lengthen toward 30 or more. A sudden shortening often indicates that one color has stopped defending.

First-player advantage has a theoretical reference. Connect 4 on a 7-by-6 board was solved independently in 1988 by James D. Allen and Victor Allis: with perfect play the first player wins by opening in the center column (Pascal Pons’ summary). But self-play does not always begin from an empty board with perfect play: opening moves are chosen with temperature 1 for diversity, and many openings are not first-player wins. The self-play first-player win fraction therefore has no target value; what should hold at the end is more precise: the final network playing itself without temperature or noise, from the empty board, should produce a first-player win, and every position in that game should preserve that theoretical value. The lab checks this with the solver from move 10.

InteractiveAlphaZero training dashboard
Accuracy against the solver (validation)
  • Network + 100 simulations
  • Network alone
50 %60 %70 %80 %90 %100 %02468101214161820random column
generation
Fraction of the 300 validation positions where the chosen move preserves theoretical value. This is the only curve measuring absolute quality. Bands are 95% Wilson intervals; overlapping bands do not necessarily order two generations.
In this run, Network + 100 simulations: 85.7 % in generation 0 and 95.3 % in generation 20.
One self-play game from phase 20
Played by network 19 with 100 simulations, Dirichlet noise, and temperature 1 for the first 12 moves. One game varies considerably; the phase’s 400-game average is in “Length.”
15162728293033344781120223910121321125614171819232425263132
34 of 34
Final: second player wins (orange) in 34 moves; the green ring marks four in a row.

Real data from the lab’s short verification run (preset “corta”: 20 generations of 400 games with 100 simulations, 4 blocks and 64 channels, 15 minutes on a laptop RTX 4060). Sample games were played afterward with each phase’s checkpoint and the same settings. Full lab training performs over one hundred times as many network evaluations; these curves show dynamics, not the final result.

Generation20
Network + 100 simulations95.3 %
Network alone88.0 %
New positions in buffer13,381
Real data from the lab's short verification run. Choose a signal in the thumbnails and navigate generations by clicking the curve. Compare policy loss with its floor H(π)H(\pi) and value loss with Var⁡(z)\Var(z): how much of each curve is learning? In 'Elo', compare the fixed ladder with chained Elo against the previous generation. Beside the curve is one self-play game from each phase, move by move: compare it with the 'Length' curve, which averages all 400 games in that phase.

What the short-run dashboard says, validating each generation on the first 300 validation positions to avoid extending it:

  • Policy loss falls because of the floor, not the gap. It goes from 1.806 nats in phase 1 to 1.112 in phase 20, a fall of 0.69. But H(π)H(\pi) falls from 1.630 to 0.899, 0.73 nats. The gap KL⁡(π ∥ pθ)\KL(\pi \,\|\, p_\theta) rises from 0.18 to 0.29 around generation 7 and returns to 0.21: the network pursues a target sharpening each generation and distance to it barely changes. Read alone, the loss curve would credit the network with all the search’s work.
  • The value head does learn. Loss falls from 0.511 to 0.312 while Var⁡(z)\Var(z) goes from 0.915 to 0.736; explained fraction 1−MSE/Var⁡(z)1 - \text{MSE}/\Var(z) rises from 0.44 to 0.58. This is approximate: loss is averaged over training batches mixing positions from several phases that the network is fitting, while Var⁡(z)\Var(z) is calculated on new positions from the phase.
  • Games lengthen and draws appear. Mean length rises from 22.4 to 33.5 moves and draws from 4.5% to 21%. Entropies decline gradually: network entropy in batches from 0.96 to 0.67; visit entropy from 0.86 to 0.54. There is no collapse.
  • Accuracy alone measures quality, and it is noisy. With random weights, the network alone gets 73.7%, like chance on those positions (72.3%); 100-simulation search already raises this to 85.7% without learning, because it sees nearby threats. At generation 20 the network alone gets 88.0% and with search 95.3%, with a Wilson interval of [92.3 %,97.2 %][92.3\,\%, 97.2\,\%] on 300 positions. Between generations 7 and 17 the search curve oscillates between 91% and 94% without a trend the interval permits us to assert.

The first-player win fraction in self-play falls from 53% to 32%. This does not contradict theory: with temperature 1 on the first 12 moves, many self-play openings are not first-player wins, and as both sides defend those positions better they become draws or second-player wins. The check with an objective target is the deterministic game from the empty board at the end of the lesson.

Measuring against the truth

Several moves can be optimal, and any counts as correct. This is the weak scale, of a solver distinguishing only win, draw, and loss: every error changes theoretical outcome, from win to draw, draw to loss, or win to loss. A strong solver, such as Pons’, also returns distance: winning in 3 moves scores more than winning in 15. On the strong scale a move can be inferior without changing outcome class, and percentages on the two scales cannot be compared. The Pons protocol classifies test positions by depth and difficulty precisely because average accuracy means nothing without knowing which positions it comes from.

Evaluation measures the agent, not the self-play explorer: no Dirichlet noise, no temperature, and a fixed tie-breaking rule (most visits; then highest prior; then smallest column). With network alone the move maximizes policy over legal moves; with search it is the most visited after a declared number of simulations.

A test set that does not lie

Building the set takes as many decisions as training, and each changes what the percentage means. The lab’s decisions:

  • Where positions come from. Imperfect games: on each move, with probability 1/2 choose a random column, otherwise use a depth-2 player (wins when possible and does not give away an immediate win). Perfect games do not work: there are too few and the agent would end up evaluated on positions it sees most often.
  • What is discarded. Positions where the player to move has an immediate win: any depth-one search gets them right and they would inflate accuracy.
  • Phases. One third in each: early (10 to 14 moves played), middle (15 to 28), and late (29 to 40), the cuts from the Pons test protocol also used by AlphaZero.jl. Positions under 10 moves are excluded for cost: without an opening book, the tree the solver must traverse in a position of 6 or 8 moves is so large that its unbounded transposition table exceeds 10 GB of memory before completion. The lab solver therefore bounds the table, yet those positions remain prohibitive.
  • Duplicates and reflections. A position and its horizontal reflection are the same problem. They are identified with a canonical key and deduplicated; validation and test are built disjoint.
  • Leakage. If a self-play position or its reflection matches one from validation or test, it is recorded but excluded from the buffer. This prevents exact overlap, not the agent seeing similar positions.
  • Validation versus test. Validation (1002 positions) is measured every generation for curves and decisions; test (another 1002) is used only at the end. If you choose the best generation by validation, validation is no longer an honest estimate.

With these rules, the baseline of choosing a random legal column gets 71.2% of test positions right, because in many positions several or all columns have the same exact value. Only 467 of the 1002 are decisive, with moves of at least two different values; the lab also reports accuracy on those, where the difference between playing and guessing correctly becomes visible.

How uncertain is a percentage?

Each test position comes from a different game and is selected before evaluation, so it is reasonable to model successes as nn independent Bernoulli trials with probability pp, the accuracy on the distribution generating positions. The Wald interval p^±zp^(1−p^)/n\hat p \pm z\sqrt{\hat p(1 - \hat p)/n} fails right where we are, near 1: with 1000 successes out of 1000 its width is zero. Wilson’s interval, seen with proportion intervals, behaves well.

Proof

Squaring, the condition is (p^−p)2≤z2np(1−p)(\hat p - p)^2 \le \frac{z^2}{n}p(1 - p), that is,

(1+z2n)p2−(2p^+z2n)p+p^2≤0.\Big(1 + \frac{z^2}{n}\Big)p^2 - \Big(2\hat p + \frac{z^2}{n}\Big)p + \hat p^2 \le 0.

The leading coefficient is positive, so the inequality holds between the two roots. Their midpoint is (2p^+z2/n)/(2(1+z2/n))=p~\big(2\hat p + z^2/n\big) / \big(2(1 + z^2/n)\big) = \tilde p, and half their distance is Δ/(2(1+z2/n))\sqrt{\Delta}/\big(2(1 + z^2/n)\big) with Δ=(2p^+z2/n)2−4(1+z2/n)p^2=4z2n(p^(1−p^)+z24n)\Delta = (2\hat p + z^2/n)^2 - 4(1 + z^2/n)\hat p^2 = \frac{4z^2}{n}\big(\hat p(1 - \hat p) + \frac{z^2}{4n}\big), which is hh. Both roots lie in [0,1][0, 1]: the polynomial is convex, equals p^2≥0\hat p^2 \ge 0 at p=0p = 0 and (1−p^)2≥0(1 - \hat p)^2 \ge 0 at p=1p = 1, and its vertex p~\tilde p lies in [0,1][0, 1] because it is a weighted average of p^\hat p and 1/21/2, with weights 11 and z2/nz^2/n. A convex parabola that is nonnegative at the endpoints of an interval and has its vertex inside it has both roots there.

∎

Two consequences for reading results. The center p~\tilde p shifts toward 1/21/2, more so as nn decreases, and the interval is not symmetric around p^\hat p. With 1000 positions resolution is limited: 960 successes yield [94.60 %,97.05 %][94.60\,\%, 97.05\,\%], almost two and a half points wide. Claiming 96.1% improves on 95.8% at that size reads noise as signal.

[ ]Wilson from scratch and with statsmodelsBrowser
import math
from statsmodels.stats.proportion import proportion_confint

def wilson(k, n, z=1.959964):
    p = k / n
    c = (p + z * z / (2 * n)) / (1 + z * z / n)
    h = z / (1 + z * z / n) * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
    return c - h, c + h

for k, n in [(960, 1000), (998, 1000), (1000, 1000), (24, 24)]:
    w = wilson(k, n)
    ref = proportion_confint(k, n, alpha=0.05, method="wilson")
    wald = k / n - 1.959964 * math.sqrt(k / n * (1 - k / n) / n)
    print(f"{k:4d}/{n:<4d} Wilson [{w[0]:.4f}, {w[1]:.4f}]  statsmodels [{ref[0]:.4f}, {ref[1]:.4f}]  "
          f"límite inferior de Wald {wald:.4f}")

The 1000 out of 1000 row is especially instructive: Wald says accuracy is exactly 1, Wilson that it is at least 0.9962. Zero errors in 1000 positions do not demonstrate a perfect agent.

Compare two generations on the same positions

To decide whether generation 18 is better than 12 there is no need to compare two intervals: both are evaluated on the same positions, and that pairing contains much more information. Classify each position into four cells according to whether one, the other, both, or neither succeeds. Those both get right or both miss say nothing about the difference; everything lies in the discordant ones: bb positions only the new one gets right and cc only the old one gets right. If they were equally good, each discordant position would fall on either side with probability 1/2, so b∼Bin⁡(b+c,1/2)b \sim \Bin(b + c, 1/2): this is the exact paired McNemar test.

[ ]Exact McNemar for two generationsBrowser
from scipy.stats import binomtest

for b, c in [(31, 14), (20, 12), (9, 3)]:
    r = binomtest(b, b + c, 0.5)
    print(f"solo acierta la nueva: {b:2d}, solo la antigua: {c:2d}  ->  "
          f"diferencia {(b - c) / 1000:+.3f} en 1000 posiciones, p bilateral = {r.pvalue:.4f}")

With 31 versus 14, the 1.7-point improvement is clear (p≈0.016p \approx 0.016); with 20 versus 12, a 0.8-point improvement cannot be distinguished from chance. Two overlapping Wilson intervals cannot establish either conclusion: pairing removes variability of common positions.

Elo against fixed opponents

Optimal-move percentage measures isolated decisions in positions we choose. A tournament measures something else: how the agent plays whole games against specific opponents, including its ability to bring play into positions it knows. This is the distinction between judging individual steps and judging the whole trajectory: an agent can get almost every isolated decision right and lose games from a single critical mistake. The measures complement each other and lesson 2’s Elo is the natural scale for the second.

The ladder. The lab uses five fixed inexpensive opponents: a random player and four minimax players with horizons 2, 4, 8, and 12 moves. Each sees forced wins and losses within its horizon (slightly farther, since it always excludes moves giving away an immediate win) and chooses randomly among equivalent moves when none is seen. Their knowledge is deterministic and tie-breaking random, so they range from “knows nothing” to “falls for no trap within 12 moves.”

Their Elo is calculated once. A round-robin tournament among the five, with all 49 two-move openings played twice with colors swapped (98 games per pair), fixes their Elo by maximum likelihood in the Bradley-Terry model, treating a draw as half a win and anchoring the random player at 0. These numbers remain frozen throughout the run.

Each generation’s Elo is then a one-unknown problem. If the agent scores sj∈{0,12,1}s_j \in \{0, \tfrac12, 1\} in game jj against an opponent with Elo RjR_j, logistic log-likelihood ℓ(x)=∑jsjlog⁡Ej+(1−sj)log⁡(1−Ej)\ell(x) = \sum_j s_j\log E_j + (1 - s_j)\log(1 - E_j) with Ej=1/(1+10(Rj−x)/400)E_j = 1/(1 + 10^{(R_j - x)/400}) has derivative

ℓ′(x)=ln⁡10400∑j(sj−Ej(x)),\ell'(x) = \frac{\ln 10}{400}\sum_j (s_j - E_j(x)),

so the estimator equates obtained and expected scores: ∑jsj=∑jEj(x^)\sum_j s_j = \sum_j E_j(\hat x). Since ∑jEj(x)\sum_j E_j(x) strictly increases with xx, the solution is unique if it exists, and exists if and only if total score is strictly between 0 and the number of games. With all games won there is no finite Elo: the model only says the agent is above the entire ladder. The confidence interval uses a percentile bootstrap resampling openings, keeping their two games together, because two games with the same opening are not independent.

[ ]Maximum-likelihood Elo against fixed opponentsBrowser
import numpy as np
from scipy.optimize import brentq

def elo_mle(scores, ratings):
    s, r = np.asarray(scores, float), np.asarray(ratings, float)
    if s.mean() in (0.0, 1.0):
        return float("inf") if s.mean() == 1 else float("-inf")
    g = lambda x: np.sum(s - 1 / (1 + 10 ** ((r - x) / 400)))
    return brentq(g, -5000, 5000)          # g es estrictamente decreciente: una sola raíz

print("75 % contra un rival de 600:", round(elo_mle([1, 1, 1, 0], [600] * 4), 2),
      "  fórmula cerrada:", round(600 + 400 * np.log10(3), 2))
rng = np.random.default_rng(0)
ratings = np.repeat([0, 440, 600, 760, 900], 98)
true = 820
scores = (rng.random(ratings.size) < 1 / (1 + 10 ** ((ratings - true) / 400))).astype(float)
print("Elo verdadero", true, " estimado", round(elo_mle(scores, ratings), 1))
print("todo ganado:", elo_mle(np.ones(10), np.full(10, 900)))

Why Elo against oneself misleads

Measuring each generation against its predecessor is tempting: no external opponents are needed and numbers always rise. Summing these differences gives chained Elo, seen in many self-play curves. It has three structural flaws:

  1. No anchor. Each link compares against a different opponent. If generation kk learns to exploit a particular weakness in k−1k - 1, it gains many points on that link even if it does not play better against anyone else.
  2. Play is not transitive. AA beating BB and BB beating CC does not imply AA beats CC; dynamics of mutually adapting learners can cycle through styles while each link appears to improve.
  3. Error accumulates. Each difference has variance; the sum of KK links has KK times as much, and with selection (publishing only versions that “win”) bias also accumulates.

The training dashboard shows both curves using actual short-run data, evaluating every other generation with 100 simulations. The ladder was fixed at 0, 351, 503, 673, and 814 points for random and horizons 2, 4, 8, and 12. Each evaluated generation beat its predecessor, scoring between 56% and 72%, so chained Elo rises at every link: from 486 at generation 0 to 1406 at 20. Against the fixed ladder the agent rises from 486 to 966 at generation 8 and then moves between 983 and 1071 with intervals about one hundred points wide overlapping between each evaluated generation and the next: it ends at 1042 [984,1099][984, 1099]. The clearest example is at the end: generation 20 scores 67% against 18 and adds 126 points to the chain, but its fixed-opponent estimate falls 29 points. Between generations 8 and 20, the chain gains 495 points and the fixed scale 75, within the noise.

AlphaZero is generalized policy iteration with search as the improvement operator: search guided by fθf_\theta produces a better policy than fθf_\theta, the network learns to imitate it, and search guided by the new network improves again. If true, in each generation network with search should be more accurate than network alone, and their gap measures how much the network has yet to absorb.

The lab measures this on the test set with the final checkpoint and 0, 16, 64, 200, and 800 simulations, always without noise and with the same tie-breaking rule. These are generation 20 short-run figures on 1002 test positions (467 decisive); chance scores 71.2%:

SimulationsAccuracyWilson 95%DecisiveEarlyMiddleLateWin to loss
0 (network alone)88.2 %[86.1, 90.1]74.7 %88.0 %86.8 %89.8 %69
1691.1 %[89.2, 92.7]80.9 %89.8 %91.3 %92.2 %51
6493.5 %[91.8, 94.9]86.1 %90.7 %94.3 %95.5 %39
20095.0 %[93.5, 96.2]89.3 %91.9 %95.8 %97.3 %27
80096.4 %[95.1, 97.4]92.3 %93.7 %96.4 %99.1 %18

Three readings. Search improves monotonically without saturation: each sweep step eliminates about one quarter of remaining errors (from 118 to 89, 65, 50, and 36), and at 800 the Wilson interval lies entirely above 95%, though by less than a tenth. Improvement differs by phase: in late positions search goes from 34 errors to 3 because the tree reaches the end of the game; in early positions only from 40 to 21 because consequences lie 25 or more moves away and the tree depends on network value. Scale matters: accuracy on decisive positions, where chance does not help, is 4 to 14 points below overall accuracy.

The errors that remain

An average percentage hides where failures occur. Slice analysis asks which subsets concentrate them and what they share. Here natural slices are game phase, severity (losing one step, win to draw or draw to loss, versus win to loss), and relationship with search: errors search corrects, errors search introduces, and errors neither network nor search sees.

InteractiveThe errors that remain
  • network policy (%)
  • visits with 800 simulations
  • W win
  • D draw
  • L loss
netvisits7106L11057L2720W337L4899L516154L650357L7exact
The network gives only 7.0 % probability to optimal moves, and search gives them 2.5 % of visits: with such a low prior, PUCT barely explores the right answer. Search fails to correct this policy error.

Final checkpoint (generation 20) of the short verification run, evaluated on 1002 test positions without noise or temperature. Exact weak-solver values from the player-to-move perspective.

Type
Phase
Severity
1 of 36
Test error rate by phase
early
12.0 % without search · 6.3 % with 800
middle
13.2 % without search · 3.6 % with 800
late
10.2 % without search · 0.9 % with 800
Phaseearly, move 14
Player to moveorange (2nd)
Best possiblewin
With 800 sim.col. 7, loss
Network alonecol. 7, loss
Chosen move visits357 of 800
Test positions where the short-run final agent chooses a suboptimal move. Above each column, network policy and search visits; below, exact solver value (W wins, D draws, L loses, from the player to move). Filter by type, phase, and severity. Look at positions where optimal moves receive little prior: can search correct them? And find those 'spoiled by search': what do they have in common?

In generation 20 of the short run, 127 test positions have some error. Network alone misses 118, and in 69 its move changes a win into a loss. With 800 simulations 36 failures remain, half one-step and half win-to-loss. Search corrects 91 network errors and spoils 9 positions the network got right; both fail on 27, 15 of them in the same column. By phase, search errors are 21 early, 12 middle, and 3 late.

The 9 spoiled positions share a feature visible in the widget: search does not hesitate. All nine were winning positions, and in 8 search concentrates between 537 and 742 of 800 visits on a column that was not the network’s favorite and loses (five times) or only draws (three). This is not just exploration: search started with the correct column as prior favorite and visited it; rather, the network’s estimated leaf values for that branch are worse than for the wrong branch, and 800 simulations suffice for the tree to commit to the error. Only 7 of the 36 search errors have under 10% prior on optimal moves: with this network value is the bottleneck more than policy.

Errors surviving search usually have one of three causes, which the widget helps distinguish:

  • Prior too low on the correct move. PUCT allocates visits in proportion to prior multiplied by a term decreasing with visits. If the network gives 1% to the only move saving the game, many simulations are needed for search to seriously try it. This is typical of an unnatural defense.
  • Poorly estimated leaf value. If vθv_\theta is systematically wrong on a type of position (long-term threats and row parity in Connect 4), the tree inherits the bias and search reinforces the network’s choice rather than correcting it.
  • Horizon. With few simulations the tree cannot see the end of a long combination. These errors do decrease with more simulations, and the sweep above separates them from the other two.

Common pathologies and how to detect them

AlphaZero training failures have recognizable dashboard signatures. The table summarizes common ones; in each case the decisive check uses the solver or a fixed position, not a loss.

PathologySignal signatureCheck
Reversed sign of zz or propagated valuevalue loss stuck at Var⁡(z)\Var(z); shortening games; accuracy not risingin a position with immediate win, vθ>0v_\theta > 0 for the player to move and search chooses that column
Exploration collapsenetwork and prior entropy near 0 in a few generations; near-zero KL between generations; frozen lengthpolicy on fixed validation positions; self-play opening diversity
Buffer overfittingpolicy loss stuck to its floor H(π)H(\pi) in batches (near-zero gap) while validation accuracy falls; KL spikes between generationsreduce steps per generation or enlarge buffer and compare with McNemar
Evaluation leakagevalidation accuracy far higher than testcount self-play positions excluded due to evaluation overlap
Evaluation with exploration activesearch accuracy systematically below network alonerepeat without noise or temperature
Inflated Elochained Elo growing faster than fixed Elofixed-opponent ladder and accuracy against solver

One case deserves detail because it is confused with success. Entropy falls near zero in the first three generations, policy loss plunges, and self-play games all become identical. It looks as if the network “already knows.” But a nearly deterministic policy from generation 2 cannot have learned answers to positions it never visits; the network committed early to a line and self-play now produces only that line. Usual causes are high learning rate with little data, disabled or poorly mixed Dirichlet noise, and zero temperature from the first move. Check accuracy on fixed positions across all phases and self-play opening diversity, as in the first exercise.

Lab

The lab is self-contained: it rewrites engine, solver, network, and PUCT in an az4 package inside ATLAS_LAB_DIR/p12-l06 (default ~/atlas-lab/p12-l06), independent of cells from other lessons. Each module is written from a cell, imported, and tested in that same cell; training and evaluation launch as separate processes (python -m az4.train, python -m az4.report), just as you would launch them from a terminal for several nights. It needs a CUDA GPU, numba for the solver, and psutil to monitor memory.

Engine and solver

Bitboards use Pons’ convention from lesson 1: p is the player-to-move’s pieces and mask all pieces. The solver is weak (win, draw, or loss) and adds three Pons ideas to alpha-beta pruning to make it viable from move 10: do not consider moves giving away an immediate win, force a block when the opponent threatens a win, and order moves by the number of threats they create. The transposition table stores lower and upper bounds. At the end of the module are fixed-horizon ladder opponents and vectorized versions used by search.

[ ]Lab folder and utilitiesLocal GPU
import importlib, json, os, shutil, subprocess, sys, time
from pathlib import Path

import numpy as np

LAB = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab')).expanduser() / 'p12-l06'
PKG = LAB / 'az4'
PKG.mkdir(parents=True, exist_ok=True)
(PKG / '__init__.py').write_text('"""AlphaZero para Conecta 4 (p12-l06)."""\n', encoding='utf-8')
if str(LAB) not in sys.path:
    sys.path.insert(0, str(LAB))


def publish(name, source):
    """Escribe az4/<name>.py y lo importa de nuevo para probarlo en esta misma sesión."""
    (PKG / f'{name}.py').write_text(source.lstrip(), encoding='utf-8')
    importlib.invalidate_caches()
    return importlib.reload(importlib.import_module(f'az4.{name}'))


def run(module, *args, timeout=None):
    """python -m az4.<module> en un proceso aparte, como desde una terminal; devuelve su salida."""
    env = {**os.environ, 'PYTHONUTF8': '1'}
    r = subprocess.run([sys.executable, '-m', f'az4.{module}', *map(str, args)], cwd=LAB, env=env,
                       capture_output=True, text=True, encoding='utf-8', timeout=timeout)
    if r.returncode:
        raise RuntimeError(f'az4.{module} terminó con código {r.returncode}:\n{r.stderr[-4000:]}')
    return r.stdout


import numba, psutil, torch
print('carpeta del laboratorio:', LAB)
print('torch', torch.__version__, '| CUDA disponible:', torch.cuda.is_available(), '| numba', numba.__version__)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Engine, solver, and fixed opponentsLocal GPU
engine = publish('engine', r'''
"""Conecta 4 en bitboards (convención de Pascal Pons) y solucionador débil exacto.

Una posición es el par (p, mask): p tiene las fichas del jugador que mueve y
mask todas las fichas. Cada columna ocupa H + 1 = 7 bits; el bit sobrante
separa columnas para que los desplazamientos no se mezclen.
"""
import numpy as np
from numba import njit
from numba.typed import Dict
from numba import types

W, H = 7, 6
H1 = H + 1
TT_LIMIT = 8_000_000   # entradas de la tabla de transposición: unos 320 MB como máximo
BOTTOM = sum(1 << (c * H1) for c in range(W))   # bit inferior de cada columna
FULL = BOTTOM * ((1 << H) - 1)                  # las 42 casillas
COLS = np.array([((1 << H) - 1) << (c * H1) for c in range(W)], dtype=np.int64)
ORDER = np.array([3, 2, 4, 1, 5, 0, 6], dtype=np.int64)
SHIFTS = np.array([[c * H1 + r for c in range(W)] for r in range(H)], dtype=np.int64)


# ---------------------------------------------------------------- escalares
# Sin cache=True: numba puede fallar al recargar de disco funciones recursivas.
@njit
def won(p):
    """¿Contiene p cuatro en línea? Direcciones: 1 vertical, 7 horizontal, 6 y 8 diagonales."""
    for d in (1, 6, 7, 8):
        m = p & (p >> d)
        if m & (m >> (2 * d)):
            return True
    return False


@njit
def winning_cells(p, mask):
    """Casillas vacías que completarían cuatro en línea para las fichas p."""
    r = (p << 1) & (p << 2) & (p << 3)
    for d in (H, H1, H + 2):
        q = (p << d) & (p << (2 * d))
        r |= q & (p << (3 * d))
        r |= q & (p >> d)
        q = (p >> d) & (p >> (2 * d))
        r |= q & (p << d)
        r |= q & (p >> (3 * d))
    return r & (FULL ^ mask)


@njit
def popcount(x):
    n = 0
    while x:
        x &= x - 1
        n += 1
    return n


@njit
def non_losing_moves(p, mask):
    """Jugadas que no dejan una victoria inmediata al rival (0 si todas pierden)."""
    possible = (mask + BOTTOM) & FULL
    opp_win = winning_cells(p ^ mask, mask)
    forced = possible & opp_win
    if forced:
        if forced & (forced - 1):
            return 0
        possible = forced
    return possible & ~(opp_win >> 1)


@njit
def _negamax(p, mask, moves, alpha, beta, table):
    # Precondición: el jugador que mueve no puede ganar en una jugada.
    nxt = non_losing_moves(p, mask)
    if nxt == 0:
        return -1
    if moves >= W * H - 2:
        return 0
    key = p + mask
    if key in table:
        e = table[key]
        lo, hi = e // 3 - 1, e % 3 - 1
        if lo == hi:
            return lo
        if lo > alpha:
            alpha = lo
        if hi < beta:
            beta = hi
        if alpha >= beta:
            return alpha
    a0 = alpha
    # Ordenar: más amenazas propias primero; el centro desempata.
    cand = np.empty(W, dtype=np.int64)
    score = np.empty(W, dtype=np.int64)
    n = 0
    for i in range(W):
        b = nxt & COLS[ORDER[i]]
        if b:
            s = popcount(winning_cells(p | b, mask | b))
            j = n
            while j > 0 and score[j - 1] < s:
                cand[j] = cand[j - 1]
                score[j] = score[j - 1]
                j -= 1
            cand[j] = b
            score[j] = s
            n += 1
    best = -1
    for i in range(n):
        b = cand[i]
        v = -_negamax(p ^ mask, mask | b, moves + 1, -beta, -alpha, table)
        if v > best:
            best = v
        if v > alpha:
            alpha = v
        if alpha >= beta:
            break
    lo, hi = -1, 1
    if key in table:
        e = table[key]
        lo, hi = e // 3 - 1, e % 3 - 1
    if best <= a0:
        hi = min(hi, best)
    elif best >= beta:
        lo = max(lo, best)
    else:
        lo = hi = best
    # La tabla es solo una caché: si está llena no se guardan entradas nuevas y la memoria
    # queda acotada también dentro de una sola llamada (sin esto, una posición de 6 u 8
    # jugadas llena más de 10 GB antes de terminar).
    if len(table) < TT_LIMIT or key in table:
        table[key] = (lo + 1) * 3 + hi + 1
    return best


@njit
def _value(p, mask, moves, table):
    """Valor exacto (+1, 0, -1) para el jugador que mueve."""
    if winning_cells(p, mask) & ((mask + BOTTOM) & FULL):
        return 1
    return _negamax(p, mask, moves, -1, 1, table)


@njit
def _analyze(p, mask, moves, table):
    out = np.full(W, -2, dtype=np.int64)   # -2 = columna llena
    for c in range(W):
        b = ((mask + BOTTOM) & FULL) & COLS[c]
        if b:
            if won(p | b):
                out[c] = 1
            elif mask | b == FULL:
                out[c] = 0
            else:
                out[c] = -_value(p ^ mask, mask | b, moves + 1, table)
    return out


def new_table():
    return Dict.empty(key_type=types.int64, value_type=types.int64)


class Solver:
    """Solucionador débil con tabla de transposición acotada a TT_LIMIT entradas."""

    def __init__(self):
        self.table = new_table()

    def _check(self):
        # Tabla llena: se empieza otra antes de la siguiente posición para no perder velocidad.
        if len(self.table) >= TT_LIMIT:
            self.table = new_table()

    def analyze(self, p, mask):
        """Valor exacto de cada columna desde el jugador que mueve; None si está llena."""
        self._check()
        v = _analyze(np.int64(p), np.int64(mask), popcount(np.int64(mask)), self.table)
        return [None if x == -2 else int(x) for x in v]

    def value(self, p, mask):
        self._check()
        return int(_value(np.int64(p), np.int64(mask), popcount(np.int64(mask)), self.table))


# ---------------------------------------------------------------- utilidades
def move_bit(mask, c):
    return ((mask + BOTTOM) & FULL) & int(COLS[c])


def play(p, mask, c):
    """Devuelve (p', mask', ganó) tras jugar en la columna c."""
    b = move_bit(mask, c)
    if not b:
        raise ValueError(f'columna {c} llena')
    return p ^ mask, mask | b, bool(won(np.int64(p | b)))


def from_moves(moves):
    """Posición tras una secuencia de columnas (desde 0) que no termina la partida."""
    p = mask = 0
    for i, c in enumerate(moves):
        p, mask, w = play(p, mask, c)
        if w and i < len(moves) - 1:
            raise ValueError('la secuencia continúa tras una victoria')
    return p, mask


def mirror(x):
    """Refleja un bitboard respecto a la columna central."""
    out = 0
    for c in range(W):
        out |= ((x >> (c * H1)) & ((1 << H1) - 1)) << ((W - 1 - c) * H1)
    return out


def canonical_key(p, mask):
    """Clave única de la posición y su reflejo."""
    return min(p + mask, mirror(p) + mirror(mask))


# ---------------------------------------------------------------- vectorizado
def won_np(p):
    p = np.asarray(p, dtype=np.int64)
    out = np.zeros(p.shape, dtype=bool)
    for d in (1, 6, 7, 8):
        m = p & (p >> d)
        out |= (m & (m >> (2 * d))) != 0
    return out


def legal_np(mask):
    """(..., 7) booleano de columnas jugables."""
    mask = np.asarray(mask, dtype=np.int64)
    free = (mask + BOTTOM) & FULL
    return (free[..., None] & COLS) != 0


def bits_np(mask, actions):
    free = (np.asarray(mask, dtype=np.int64) + BOTTOM) & FULL
    return free & COLS[actions]


def encode_np(p, mask):
    """Planos (B, 2, 6, 7) uint8: fichas propias y rivales; fila 0 = abajo."""
    p = np.asarray(p, dtype=np.int64)[:, None, None]
    o = (np.asarray(mask, dtype=np.int64)[:, None, None] ^ p)
    x = np.empty((p.shape[0], 2, H, W), dtype=np.uint8)
    x[:, 0] = (p >> SHIFTS) & 1
    x[:, 1] = (o >> SHIFTS) & 1
    return x


# ---------------------------------------------------------------- rivales fijos
@njit
def _minimax(p, mask, depth, alpha, beta):
    # Valor con horizonte: solo ve victorias forzadas en `depth` jugadas.
    if winning_cells(p, mask) & ((mask + BOTTOM) & FULL):
        return 1
    nxt = non_losing_moves(p, mask)
    if nxt == 0:
        return -1
    if depth <= 1 or popcount(mask) >= W * H - 2:
        return 0
    best = -1
    for i in range(W):
        b = nxt & COLS[ORDER[i]]
        if b:
            v = -_minimax(p ^ mask, mask | b, depth - 1, -beta, -alpha)
            if v > best:
                best = v
            if v > alpha:
                alpha = v
            if alpha >= beta:
                break
    return best


@njit
def minimax_scores(p, mask, depth):
    """Valor con horizonte de cada columna (-2 si está llena)."""
    out = np.full(W, -2, dtype=np.int64)
    for c in range(W):
        b = ((mask + BOTTOM) & FULL) & COLS[c]
        if b:
            if won(p | b):
                out[c] = 1
            elif (mask | b) == FULL:
                out[c] = 0
            else:
                out[c] = -_minimax(p ^ mask, mask | b, depth - 1, -1, 1)
    return out


def minimax_move(p, mask, depth, rng):
    """Rival de horizonte fijo: elige al azar entre las mejores columnas."""
    s = minimax_scores(np.int64(p), np.int64(mask), depth)
    best = np.flatnonzero(s == s.max())
    return int(rng.choice(best))
''')

import functools

rng = np.random.default_rng(0)


def random_position(ply):
    """Posición tras `ply` jugadas al azar que no han terminado la partida."""
    while True:
        p = mask = 0
        for _ in range(ply):
            p, mask, w = engine.play(p, mask, int(rng.choice([c for c in range(7) if engine.move_bit(mask, c)])))
            if w:
                break
        else:
            return p, mask


@functools.lru_cache(maxsize=None)
def brute(p, mask):
    """Minimax sin poda, sin tabla y sin trucos: lento pero evidentemente correcto."""
    vals = []
    for c in range(7):
        if engine.move_bit(mask, c):
            q, m, w = engine.play(p, mask, c)
            vals.append(1 if w else 0 if m == engine.FULL else -brute(q, m))
    return max(vals)


solver = engine.Solver()
checked = 0
for _ in range(100):
    p, m = random_position(int(rng.integers(30, 38)))
    for c, v in enumerate(solver.analyze(p, m)):
        if v is None:
            continue
        q, mm, w = engine.play(p, m, c)
        assert v == (1 if w else 0 if mm == engine.FULL else -brute(q, mm)), (p, m, c)
        checked += 1
print(f'solucionador = fuerza bruta en {checked} jugadas de 100 posiciones finales')
for ply in (20, 16, 12):
    t = time.perf_counter()
    for _ in range(3):
        engine.Solver().analyze(*random_position(ply))
    print(f'{ply} jugadas jugadas: {(time.perf_counter() - t) / 3:.2f} s por posición (las 7 columnas)')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The network is from lesson 3 with configurable width and depth: 5 blocks of 128 channels for the full run and 4 of 64 for the short one.

[ ]Policy-value networkLocal GPU
net = publish('net', r'''
"""Red residual de política y valor (la de p12-l03, con anchura y profundidad configurables)."""
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F

from .engine import encode_np, legal_np


class Block(nn.Module):
    def __init__(self, ch):
        super().__init__()
        self.c1 = nn.Conv2d(ch, ch, 3, padding=1, bias=False)
        self.b1 = nn.BatchNorm2d(ch)
        self.c2 = nn.Conv2d(ch, ch, 3, padding=1, bias=False)
        self.b2 = nn.BatchNorm2d(ch)

    def forward(self, x):
        y = F.relu(self.b1(self.c1(x)))
        return F.relu(x + self.b2(self.c2(y)))


class PolicyValueNet(nn.Module):
    def __init__(self, channels=128, blocks=5):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(2, channels, 3, padding=1, bias=False),
                                  nn.BatchNorm2d(channels), nn.ReLU())
        self.tower = nn.Sequential(*[Block(channels) for _ in range(blocks)])
        self.pol = nn.Sequential(nn.Conv2d(channels, 32, 1, bias=False), nn.BatchNorm2d(32), nn.ReLU(),
                                 nn.Flatten(), nn.Linear(32 * 42, 7))
        self.val = nn.Sequential(nn.Conv2d(channels, 32, 1, bias=False), nn.BatchNorm2d(32), nn.ReLU(),
                                 nn.Flatten(), nn.Linear(32 * 42, 128), nn.ReLU(), nn.Linear(128, 1), nn.Tanh())

    def forward(self, x, legal):
        """x: (B, 2, 6, 7) float; legal: (B, 7) bool. Logits ilegales a -1e9 (no -inf: 0 * -inf = nan)."""
        h = self.tower(self.stem(x))
        logits = self.pol(h).masked_fill(~legal, -1e9)
        return logits, self.val(h).squeeze(-1)


class Evaluator:
    """Adaptador para la búsqueda: bitboards -> (priors sobre legales, valor del que mueve)."""

    def __init__(self, net, device):
        self.net, self.device = net, device
        self.calls = 0
        self.positions = 0

    @torch.inference_mode()
    def __call__(self, p, mask):
        self.net.eval()
        x = torch.from_numpy(encode_np(p, mask)).to(self.device, non_blocking=True).float()
        legal = torch.from_numpy(legal_np(mask)).to(self.device)
        logits, v = self.net(x, legal)
        pri = torch.softmax(logits.float(), dim=1)
        self.calls += 1
        self.positions += len(p)
        return pri.cpu().numpy(), v.float().cpu().numpy()


def count_parameters(net):
    return sum(p.numel() for p in net.parameters())
''')

for ch, bl in ((128, 5), (64, 4), (32, 2)):
    print(f'{bl} bloques de {ch} canales: {net.count_parameters(net.PolicyValueNet(ch, bl)):,} parámetros')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

PUCT over many games at once

Search is from lesson 4, with its conventions (Q=0Q = 0 on unvisited edges, parent’s max⁡(1,N)\sqrt{\max(1, N)}, each edge stores value from the chooser’s perspective), but vectorized over GG trees. Each tree lives in arrays of shape (G,M,7)(G, M, 7) with MM = simulations + 1, since each simulation creates at most one node. Descent advances through all trees simultaneously and stops in each on reaching a new or terminal leaf; all nonterminal leaves are evaluated in one batch. The test uses an oracle evaluator, uniform priors, and the solver’s exact value at each leaf: with it, search must always choose an optimal move, and if it does not the fault is in search, not the network.

[ ]Vectorized PUCT and its oracle testLocal GPU
mcts = publish('mcts', r'''
"""PUCT de p12-l04 vectorizado sobre G árboles a la vez.

Cada simulación desciende en los G árboles en paralelo, evalúa todas las hojas
nuevas en un único lote de red y propaga los valores. Así la GPU recibe lotes
de G posiciones sin hilos, colas ni pérdida virtual: el paralelismo viene de
jugar muchas partidas a la vez. Convenciones de p12-l04: Q = 0 en aristas sin
visitas, sqrt(max(1, N)) del padre, cada arista guarda el valor desde el
jugador que la elige.
"""
import numpy as np

from .engine import FULL, won_np, legal_np, bits_np


def search(evaluate, p, mask, sims, c_puct=1.5, noise_frac=0.0, alpha=1.0, rng=None):
    """Devuelve (visitas (G, 7), Q de la raíz (G,), priors de la raíz sin ruido (G, 7)).

    evaluate(p, mask) -> (priors (B, 7) sobre legales, valores (B,) del que mueve).
    Las raíces deben ser posiciones no terminales.
    """
    p = np.asarray(p, dtype=np.int64)
    mask = np.asarray(mask, dtype=np.int64)
    G, M = len(p), sims + 1
    gi = np.arange(G)
    P = np.zeros((G, M, 7), np.float32)
    N = np.zeros((G, M, 7), np.float32)
    Wt = np.zeros((G, M, 7), np.float32)
    child = np.full((G, M, 7), -1, np.int32)
    legal = np.zeros((G, M, 7), bool)
    pos = np.zeros((G, M), np.int64)
    msk = np.zeros((G, M), np.int64)
    term = np.full((G, M), np.nan, np.float32)
    expanded = np.zeros((G, M), bool)
    count = np.ones(G, np.int64)

    pos[:, 0], msk[:, 0] = p, mask
    pri0, _ = evaluate(p, mask)
    legal[:, 0] = legal_np(mask)
    P[:, 0] = pri0
    expanded[:, 0] = True
    if noise_frac > 0:
        rng = np.random.default_rng() if rng is None else rng
        for g in range(G):
            a = np.flatnonzero(legal[g, 0])
            P[g, 0, a] = (1 - noise_frac) * P[g, 0, a] + noise_frac * rng.dirichlet(np.full(len(a), alpha))

    for _ in range(sims):
        node = np.zeros(G, np.int64)
        path_n, path_a, path_g = [], [], []
        g = gi
        while len(g):
            nd = node[g]
            n = N[g, nd]
            q = np.where(n > 0, Wt[g, nd] / np.maximum(n, 1), 0.0)
            tot = np.sqrt(np.maximum(n.sum(1, keepdims=True), 1))
            u = q + c_puct * P[g, nd] * tot / (1 + n)
            u = np.where(legal[g, nd], u, -np.inf)
            a = u.argmax(1)
            path_g.append(g); path_n.append(nd); path_a.append(a)
            ch = child[g, nd, a]
            new = ch < 0
            if new.any():
                gn, pn, an = g[new], nd[new], a[new]
                idx = count[gn]
                count[gn] += 1
                b = bits_np(msk[gn, pn], an)
                mover = pos[gn, pn] | b
                pos[gn, idx] = pos[gn, pn] ^ msk[gn, pn]
                msk[gn, idx] = msk[gn, pn] | b
                t = np.where(won_np(mover), -1.0, np.where(msk[gn, idx] == FULL, 0.0, np.nan))
                term[gn, idx] = t
                child[gn, pn, an] = idx
                ch = ch.copy()
                ch[new] = idx
            node[g] = ch
            go_on = expanded[g, ch] & np.isnan(term[g, ch])
            g = g[go_on]
        v = term[gi, node].astype(np.float64)
        need = np.isnan(v)
        if need.any():
            gl, nl = gi[need], node[need]
            pri, val = evaluate(pos[gl, nl], msk[gl, nl])
            P[gl, nl] = pri
            legal[gl, nl] = legal_np(msk[gl, nl])
            expanded[gl, nl] = True
            v[need] = val
        # v es el valor para el que mueve en la hoja; cada arista lo guarda desde quien la eligió.
        for g, nd, a in zip(reversed(path_g), reversed(path_n), reversed(path_a)):
            v[g] = -v[g]
            N[g, nd, a] += 1
            Wt[g, nd, a] += v[g]
    visits = N[:, 0].astype(np.int64)
    rootq = Wt[:, 0].sum(1) / np.maximum(visits.sum(1), 1)
    return visits, rootq, pri0
''')

positions = []
while len(positions) < 100:
    p, m = random_position(int(rng.integers(20, 32)))
    if not engine.winning_cells(np.int64(p), np.int64(m)) & ((m + engine.BOTTOM) & engine.FULL):
        positions.append((p, m))
P0 = np.array([p for p, _ in positions], np.int64)
M0 = np.array([m for _, m in positions], np.int64)


def oracle(p, mask):
    """Priors uniformes sobre legales y valor exacto: el mejor evaluador posible."""
    legal = engine.legal_np(mask).astype(np.float32)
    return legal / legal.sum(1, keepdims=True), np.array([solver.value(int(a), int(b)) for a, b in zip(p, mask)], np.float32)


visits, _, _ = mcts.search(oracle, P0, M0, sims=50)
ok = 0
for (p, m), vis in zip(positions, visits):
    vals = solver.analyze(p, m)
    ok += vals[int(vis.argmax())] == max(v for v in vals if v is not None)
print(f'búsqueda con oráculo, 50 simulaciones: {ok} de {len(positions)} jugadas óptimas')
assert ok == len(positions)


def uniform(p, mask):
    legal = engine.legal_np(mask).astype(np.float32)
    return legal / legal.sum(1, keepdims=True), np.zeros(len(p), np.float32)


idx = rng.integers(0, len(positions), 1024)
t = time.perf_counter()
mcts.search(uniform, P0[idx], M0[idx], sims=100)
dt = time.perf_counter() - t
print(f'1024 árboles x 100 simulaciones sin red: {dt:.2f} s, {dt / 102400 * 1e6:.1f} µs por simulación y árbol')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Evaluation: sets, games, and Elo

This module gathers the preceding sections: building the labeled set, deterministic network-only and search evaluation, Wilson interval, paired-opening games, maximum-likelihood Elo against fixed opponents, its opening bootstrap, and Bradley-Terry fitting of the ladder.

[ ]Sets, accuracy, games, and EloLocal GPU
evaluate = publish('evaluate', r'''
"""Evaluación contra la verdad: conjunto etiquetado por el solucionador, partidas y Elo."""
import json
import math
import time

import numpy as np

from .engine import (W, BOTTOM, FULL, Solver, canonical_key, from_moves, legal_np, minimax_move,
                     move_bit, play, winning_cells)
from .mcts import search

PHASES = {'temprana': (10, 14), 'media': (15, 28), 'final': (29, 40)}


# ------------------------------------------------------------ conjunto de prueba
def _sample_game_prefix(ply, rng):
    """Prefijo de una partida entre dos jugadores de horizonte 2 (ganan si pueden, no regalan)."""
    p = mask = 0
    moves = []
    for _ in range(ply):
        c = minimax_move(p, mask, 2, rng) if rng.random() < 0.5 else \
            int(rng.choice([c for c in range(W) if move_bit(mask, c)]))
        p, mask, w = play(p, mask, c)
        moves.append(c)
        if w or mask == FULL:
            return None
    return moves


def build_positions(n_per_phase, rng, exclude=frozenset(), log=print):
    """Posiciones no triviales etiquetadas con el valor exacto de cada columna."""
    solver = Solver()
    out, seen = [], set(exclude)
    for phase, (lo, hi) in PHASES.items():
        got, t0 = 0, time.time()
        while got < n_per_phase:
            moves = _sample_game_prefix(int(rng.integers(lo, hi + 1)), rng)
            if moves is None:
                continue
            p, mask = from_moves(moves)
            if winning_cells(np.int64(p), np.int64(mask)) & ((mask + BOTTOM) & FULL):
                continue            # victoria inmediata disponible: trivial
            key = canonical_key(p, mask)
            if key in seen:
                continue
            seen.add(key)
            values = solver.analyze(p, mask)
            legal = [v for v in values if v is not None]
            out.append({'moves': moves, 'values': values, 'phase': phase, 'ply': len(moves),
                        'decisive': len(set(legal)) > 1, 'key': key})
            got += 1
        log(f'{phase}: {got} posiciones en {time.time() - t0:.0f} s')
    return [out[i] for i in rng.permutation(len(out))]    # mezcladas: cualquier prefijo está estratificado


def save_jsonl(rows, path):
    with open(path, 'w', encoding='utf-8') as f:
        for r in rows:
            f.write(json.dumps(r) + '\n')


def load_jsonl(path):
    with open(path, encoding='utf-8') as f:
        return [json.loads(line) for line in f if line.strip()]


def random_baseline(positions):
    """Acierto esperado de elegir una columna legal al azar."""
    r = []
    for x in positions:
        legal = [v for v in x['values'] if v is not None]
        r.append(sum(v == max(legal) for v in legal) / len(legal))
    return float(np.mean(r))


# ------------------------------------------------------------ acierto frente al solucionador
def choose(visits, prior):
    """Selección final determinista: más visitas; desempata el prior y después la columna menor."""
    return np.argmax(visits + 1e-3 * prior, axis=1)


def solver_eval(evaluate, positions, sims, c_puct=1.5, batch=1024):
    """Para cada posición: elección, política, visitas y si conserva el valor teórico.

    sims = 0 significa la red sola (argmax de la política sobre legales).
    Sin ruido de Dirichlet ni temperatura: se mide el agente, no el explorador.
    """
    rows = []
    for s in range(0, len(positions), batch):
        chunk = positions[s:s + batch]
        pm = [from_moves(x['moves']) for x in chunk]
        p = np.array([a for a, _ in pm], np.int64)
        m = np.array([b for _, b in pm], np.int64)
        if sims == 0:
            prior, _ = evaluate(p, m)
            visits = np.zeros_like(prior, dtype=np.int64)
            pick = np.argmax(prior, axis=1)
        else:
            visits, _, prior = search(evaluate, p, m, sims, c_puct=c_puct)
            pick = choose(visits, prior)
        for x, a, pr, vi in zip(chunk, pick, prior, visits):
            legal = [v for v in x['values'] if v is not None]
            best = max(legal)
            v = x['values'][int(a)]
            rows.append({'moves': x['moves'], 'phase': x['phase'], 'ply': x['ply'], 'decisive': x['decisive'],
                         'choice': int(a), 'optimal': v == best, 'drop': int(best - v),
                         'policy': [round(float(t), 4) for t in pr], 'visits': [int(t) for t in vi],
                         'values': x['values'], 'sims': sims})
    return rows


def wilson(k, n, z=1.959964):
    if n == 0:
        return (float('nan'), float('nan'))
    ph = k / n
    c = (ph + z * z / (2 * n)) / (1 + z * z / n)
    h = z / (1 + z * z / n) * math.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n))
    return (c - h, c + h)


def summarize(rows):
    k, n = sum(r['optimal'] for r in rows), len(rows)
    dec = [r for r in rows if r['decisive']]
    kd = sum(r['optimal'] for r in dec)
    out = {'n': n, 'optimal': k, 'rate': k / n, 'wilson95': wilson(k, n), 'by_phase': {},
           'decisive_n': len(dec), 'decisive_rate': kd / max(len(dec), 1),
           'result_changing': sum(r['drop'] > 0 for r in rows), 'win_to_loss': sum(r['drop'] == 2 for r in rows)}
    for ph in PHASES:
        sub = [r for r in rows if r['phase'] == ph]
        if sub:
            kk = sum(r['optimal'] for r in sub)
            out['by_phase'][ph] = {'n': len(sub), 'optimal': kk, 'rate': kk / len(sub)}
    return out


# ------------------------------------------------------------ partidas
class SearchPlayer:
    """Red más PUCT, sin ruido y con selección determinista (sims = 0: red sola)."""

    def __init__(self, evaluate, sims, name):
        self.evaluate, self.sims, self.name = evaluate, sims, name

    def moves(self, p, mask, rng):
        if self.sims == 0:
            prior, _ = self.evaluate(p, mask)
            return np.argmax(prior, axis=1)
        visits, _, prior = search(self.evaluate, p, mask, self.sims)
        return choose(visits, prior)


class FunctionPlayer:
    def __init__(self, fn, name):
        self.fn, self.name = fn, name

    def moves(self, p, mask, rng):
        return np.array([self.fn(int(a), int(b), rng) for a, b in zip(p, mask)])


def random_player():
    return FunctionPlayer(lambda p, m, rng: int(rng.choice([c for c in range(W) if move_bit(m, c)])), 'aleatorio')


def minimax_player(depth):
    return FunctionPlayer(lambda p, m, rng: minimax_move(p, m, depth, rng), f'horizonte {depth}')


OPENINGS = [(a, b) for a in range(W) for b in range(W)]   # 49 aperturas de dos jugadas


def play_match(A, B, rng, openings=OPENINGS):
    """Cada apertura dos veces, cambiando colores. Devuelve puntuaciones de A (1, 0.5, 0) por pareja."""
    games = []
    for o in openings:
        for a_first in (True, False):
            p, mask = 0, 0
            for c in o:
                p, mask, _ = play(p, mask, c)
            games.append({'p': p, 'mask': mask, 'ply': len(o), 'a_first': a_first, 'done': None, 'moves': list(o)})
    while True:
        live = [g for g in games if g['done'] is None]
        if not live:
            break
        for player, is_a in ((A, True), (B, False)):
            # Mueve A si (ply par) == (A juega primero).
            turn = [g for g in live if ((g['ply'] % 2 == 0) == g['a_first']) == is_a]
            if not turn:
                continue
            cols = player.moves(np.array([g['p'] for g in turn], np.int64),
                                np.array([g['mask'] for g in turn], np.int64), rng)
            for g, c in zip(turn, cols):
                g['p'], g['mask'], w = play(g['p'], g['mask'], int(c))
                g['ply'] += 1
                g['moves'].append(int(c))
                if w:
                    g['done'] = 1.0 if is_a else 0.0
                elif g['mask'] == FULL:
                    g['done'] = 0.5
            live = [g for g in live if g['done'] is None]
    scores = np.array([g['done'] for g in games]).reshape(len(openings), 2)
    return scores, games


# ------------------------------------------------------------ Elo
def elo_mle(scores_by_opp, ratings, iters=60):
    """Elo de un jugador frente a rivales de Elo fijo (máxima verosimilitud logística, empate = 1/2).

    Devuelve +inf o -inf si todas las puntuaciones son 1 o 0: el estimador no es finito.
    """
    s = np.concatenate([np.asarray(v, float).ravel() for v in scores_by_opp.values()])
    r = np.concatenate([np.full(np.asarray(v).size, ratings[k]) for k, v in scores_by_opp.items()])
    if s.mean() == 1.0:
        return float('inf')
    if s.mean() == 0.0:
        return float('-inf')
    x = float(np.mean(r))
    k = math.log(10) / 400
    for _ in range(iters):
        e = 1 / (1 + 10 ** ((r - x) / 400))
        g = k * np.sum(s - e)
        h = -k * k * np.sum(e * (1 - e))
        x = float(np.clip(x - g / h, -4000, 4000))
    return x


def elo_bootstrap(scores_by_opp, ratings, rng, B=300):
    """Intervalo percentil 95 % remuestreando aperturas emparejadas (las dos partidas juntas)."""
    est = []
    for _ in range(B):
        res = {k: v[rng.integers(0, len(v), len(v))] for k, v in scores_by_opp.items()}
        est.append(elo_mle(res, ratings))
    est = np.array(est)
    return float(np.percentile(est, 2.5)), float(np.percentile(est, 97.5))


def fit_ladder(pair_scores, names, anchor, iters=200):
    """Bradley-Terry con empates a 1/2 sobre un torneo todos contra todos; anchor queda en 0."""
    idx = {n: i for i, n in enumerate(names)}
    x = np.zeros(len(names))
    k = math.log(10) / 400
    for _ in range(iters):
        g = np.zeros(len(names))
        h = np.zeros((len(names), len(names)))
        for (a, b), s in pair_scores.items():
            s = np.asarray(s, float).ravel()
            i, j = idx[a], idx[b]
            e = 1 / (1 + 10 ** ((x[j] - x[i]) / 400))
            g[i] += k * np.sum(s - e); g[j] -= k * np.sum(s - e)
            w = k * k * e * (1 - e) * s.size
            h[i, i] -= w; h[j, j] -= w; h[i, j] += w; h[j, i] += w
        free = [i for i in range(len(names)) if i != idx[anchor]]
        step = np.linalg.solve(h[np.ix_(free, free)], g[free])
        x[free] -= step
        x[free] = np.clip(x[free], -4000, 4000)
    return {n: float(x[idx[n]]) for n in names}
''')

print('Wilson 960/1000:', [round(x, 4) for x in evaluate.wilson(960, 1000)])
print('Elo con 75 % contra un rival de 600:', round(evaluate.elo_mle({'r': np.array([1, 1, 1, 0.0])}, {'r': 600}), 2))
toy = {('a', 'b'): np.full(98, 0.75), ('b', 'c'): np.full(98, 0.75), ('a', 'c'): np.full(98, 0.9)}
print('Bradley-Terry de juguete:', {k: round(v, 1) for k, v in evaluate.fit_ladder(toy, ['a', 'b', 'c'], 'c').items()})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The training loop

The loop follows lesson 5’s scheme, but in one process: self-play of games_per_gen games with parallel_games at once, evaluation-position exclusion, Adam steps on buffer samples with randomly applied left-right symmetry, solver validation, and state saving. Value target zz is assigned backward from the last move with alternating sign, and temperature is 1 on the first 12 moves and 0 afterward, with root Dirichlet noise (α=1\alpha = 1, ε=0.25\varepsilon = 0.25, AlphaZero.jl’s values for Connect 4). Three configurations: humo checks everything works in seconds, corta produced the figures, and completa is the one you will run.

Saving deserves attention: the entire state (weights, optimizer, random generators, buffer, and previous policy) goes into one file written under another name and renamed with os.replace, an atomic operation. If the process dies halfway through saving, the previous state remains intact; on resumption, later metrics rows are discarded because they will be repeated.

[ ]AlphaZero loop with exact resumptionLocal GPU
train = publish('train', r'''
"""Bucle de AlphaZero: autojuego, entrenamiento, registro, validación y reanudación exacta.

Uso: python -m az4.train --preset corta --run DIR --data DIR [--resume]
"""
import os
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')   # cuBLAS determinista

import argparse
import hashlib
import json
import time
from dataclasses import dataclass, asdict, replace
from pathlib import Path

import numpy as np
import psutil
import torch
import torch.nn.functional as F

from .engine import FULL, W, canonical_key, encode_np, legal_np, play
from .evaluate import load_jsonl, solver_eval, summarize
from .mcts import search
from .net import Evaluator, PolicyValueNet, count_parameters


@dataclass
class Config:
    generations: int = 40
    games_per_gen: int = 5000
    parallel_games: int = 1024
    sims: int = 600
    c_puct: float = 1.5
    dirichlet_alpha: float = 1.0
    noise_frac: float = 0.25
    temp_plies: int = 12          # tau = 1 en las primeras jugadas, después la más visitada
    channels: int = 128
    blocks: int = 5
    buffer_size: int = 1_000_000
    batch_size: int = 1024
    steps_per_gen: int = 1000
    lr: float = 1e-3
    weight_decay: float = 1e-4
    val_sims: int = 200           # simulaciones en la validación de cada generación
    val_positions: int = 1002     # cuántas posiciones de validación se usan por generación
    seed: int = 0
    max_rss_gb: float = 16.0


PRESETS = {
    # Lo que el lector ejecuta durante varias noches (escala de AlphaZero.jl para Conecta 4).
    'completa': Config(),
    # Ejecución corta con la que se generaron las figuras de la lección.
    'corta': Config(generations=20, games_per_gen=400, parallel_games=400, sims=100, channels=64, blocks=4,
                    buffer_size=60_000, batch_size=512, steps_per_gen=300, val_sims=100, val_positions=300,
                    max_rss_gb=4.0),
    # Comprobación de humo: minutos, no aprende nada útil.
    'humo': Config(generations=2, games_per_gen=24, parallel_games=24, sims=16, channels=32, blocks=2,
                   buffer_size=4_000, batch_size=64, steps_per_gen=20, val_sims=16, val_positions=48,
                   max_rss_gb=4.0),
}


# ------------------------------------------------------------------ utilidades
def rss_gb():
    return psutil.Process().memory_info().rss / 2 ** 30


def guard(cfg, where):
    r = rss_gb()
    if r > cfg.max_rss_gb:
        raise MemoryError(f'RSS {r:.2f} GB > {cfg.max_rss_gb} GB en {where}: se aborta la ejecución')
    return r


def entropy_norm(probs, legal):
    """Entropía dividida por log(#legales); 0 si solo hay una legal."""
    p = np.clip(probs, 1e-12, 1)
    h = -(probs * np.log(p)).sum(1)
    k = legal.sum(1)
    return np.where(k > 1, h / np.log(np.maximum(k, 2)), 0.0)


def weights_digest(net):
    h = hashlib.sha256()
    for t in net.state_dict().values():
        h.update(t.detach().cpu().numpy().tobytes())
    return h.hexdigest()[:16]


class Replay:
    """Búfer circular de posiciones (planos uint8, política objetivo, resultado, generación)."""

    def __init__(self, cap):
        self.x = np.zeros((cap, 2, 6, 7), np.uint8)
        self.pi = np.zeros((cap, 7), np.float32)
        self.z = np.zeros(cap, np.float32)
        self.gen = np.zeros(cap, np.int32)
        self.cap, self.n, self.ptr = cap, 0, 0

    def add(self, x, pi, z, gen):
        for i in range(len(x)):
            self.x[self.ptr], self.pi[self.ptr], self.z[self.ptr], self.gen[self.ptr] = x[i], pi[i], z[i], gen
            self.ptr = (self.ptr + 1) % self.cap
            self.n = min(self.n + 1, self.cap)

    def sample(self, b, rng):
        i = rng.integers(0, self.n, b)
        return self.x[i], self.pi[i], self.z[i], self.gen[i]

    def state(self):
        return {'x': self.x[:self.n].copy(), 'pi': self.pi[:self.n].copy(), 'z': self.z[:self.n].copy(),
                'gen': self.gen[:self.n].copy(), 'ptr': self.ptr}

    def load(self, d):
        n = len(d['z'])
        self.x[:n], self.pi[:n], self.z[:n], self.gen[:n] = d['x'], d['pi'], d['z'], d['gen']
        self.n, self.ptr = n, int(d['ptr'])


# ------------------------------------------------------------------ autojuego
def self_play(evaluate, cfg, rng, n_games):
    """n_games partidas, cfg.parallel_games a la vez; devuelve muestras y estadísticas."""
    G = min(cfg.parallel_games, n_games)
    slots = [None] * G
    started = finished = 0
    X, PI, Z, keys = [], [], [], []
    lengths, results, first_game = [], [], None
    ent_visits, ent_prior, absq = [], [], []

    def new_game(k):
        return {'id': k, 'p': 0, 'mask': 0, 'ply': 0, 'hist': [], 'moves': []}

    for i in range(G):
        slots[i] = new_game(started)
        started += 1
    while finished < n_games:
        act = [i for i in range(G) if slots[i] is not None]
        p = np.array([slots[i]['p'] for i in act], np.int64)
        m = np.array([slots[i]['mask'] for i in act], np.int64)
        visits, rootq, prior = search(evaluate, p, m, cfg.sims, cfg.c_puct, cfg.noise_frac,
                                      cfg.dirichlet_alpha, rng)
        pi = visits / visits.sum(1, keepdims=True)
        legal = legal_np(m)
        ent_visits.extend(entropy_norm(pi, legal))
        ent_prior.extend(entropy_norm(prior, legal))
        absq.extend(np.abs(rootq))
        for j, i in enumerate(act):
            g = slots[i]
            if g['ply'] < cfg.temp_plies:
                c = int(rng.choice(W, p=pi[j]))
            else:
                best = np.flatnonzero(visits[j] == visits[j].max())
                c = int(rng.choice(best))
            g['hist'].append((g['p'], g['mask'], pi[j].astype(np.float32)))
            g['p'], g['mask'], w = play(g['p'], g['mask'], c)
            g['moves'].append(c)
            g['ply'] += 1
            if w or g['mask'] == FULL:
                # z = +1 para el jugador que hizo la última jugada si ganó; signo alterno hacia atrás.
                n = len(g['hist'])
                for t, (hp, hm, hpi) in enumerate(g['hist']):
                    z = 0.0 if not w else (1.0 if (n - 1 - t) % 2 == 0 else -1.0)
                    X.append((hp, hm)); PI.append(hpi); Z.append(z); keys.append(canonical_key(hp, hm))
                lengths.append(n)
                results.append(0 if not w else (1 if n % 2 == 1 else -1))   # +1 gana el primero
                # Muestra: la partida que empezó primero. La primera en terminar sería la más corta.
                if g['id'] == 0:
                    first_game = {'moves': g['moves'], 'result': results[-1]}
                finished += 1
                if started < n_games:
                    slots[i] = new_game(started)
                    started += 1
                else:
                    slots[i] = None
    res = np.array(results)
    stats = {'games': n_games, 'positions': len(Z), 'mean_length': float(np.mean(lengths)),
             'first_win': float(np.mean(res == 1)), 'draw': float(np.mean(res == 0)),
             'second_win': float(np.mean(res == -1)),
             'entropy_visits': float(np.mean(ent_visits)), 'entropy_prior': float(np.mean(ent_prior)),
             'abs_root_q': float(np.mean(absq)),
             'z_var': float(np.var(Z)),   # pérdida de valor del mejor predictor constante
             'sample_game': first_game}
    xp = np.array([a for a, _ in X], np.int64)
    xm = np.array([b for _, b in X], np.int64)
    return encode_np(xp, xm), np.array(PI, np.float32), np.array(Z, np.float32), keys, stats


# ------------------------------------------------------------------ entrenamiento
def train_steps(net, opt, buf, cfg, rng, device, gen):
    net.train()
    lp, lv, ent, gn, age, hpi = [], [], [], [], [], []
    for _ in range(cfg.steps_per_gen):
        x, pi, z, g = buf.sample(cfg.batch_size, rng)
        flip = rng.random(len(z)) < 0.5                    # simetría izquierda-derecha
        x = np.where(flip[:, None, None, None], x[..., ::-1], x)
        pi = np.where(flip[:, None], pi[:, ::-1], pi)
        legal = (x.sum(axis=(1, 2)) < 6)                   # columna no llena
        xt = torch.from_numpy(np.ascontiguousarray(x)).to(device).float()
        lt = torch.from_numpy(np.ascontiguousarray(legal)).to(device)
        pit = torch.from_numpy(np.ascontiguousarray(pi)).to(device)
        zt = torch.from_numpy(z).to(device)
        logits, v = net(xt, lt)
        logp = F.log_softmax(logits, dim=1)
        loss_p = -(pit * logp).sum(1).mean()
        loss_v = F.mse_loss(v, zt)
        opt.zero_grad(set_to_none=True)
        (loss_p + loss_v).backward()
        gn.append(float(torch.nn.utils.clip_grad_norm_(net.parameters(), 10.0)))
        opt.step()
        with torch.no_grad():
            pr = logp.exp()
            h = -(pr * logp.clamp_min(-30)).sum(1)
            k = lt.sum(1).float()
            ent.append(float((h / torch.log(k.clamp_min(2))).mean()))
            # Cota inferior de la pérdida de política: H(pi) <= H(pi, p) = H(pi) + KL(pi || p).
            hpi.append(float(-(pit * torch.log(pit.clamp_min(1e-12))).sum(1).mean()))
        lp.append(loss_p.item()); lv.append(loss_v.item()); age.append(float(np.mean(gen - g)))
    return {'policy_loss': float(np.mean(lp)), 'target_entropy': float(np.mean(hpi)), 'value_loss': float(np.mean(lv)),
            'entropy_net': float(np.mean(ent)), 'grad_norm': float(np.mean(gn)), 'sample_age': float(np.mean(age))}


def kl_mean(p_old, p_new):
    a = np.clip(p_old, 1e-9, 1)
    b = np.clip(p_new, 1e-9, 1)
    return float(np.mean((p_old * (np.log(a) - np.log(b))).sum(1)))


# ------------------------------------------------------------------ programa
def rng_state(rng):
    return {'numpy': rng.bit_generator.state, 'torch': torch.get_rng_state(),
            'cuda': torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None}


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--preset', default='completa', choices=sorted(PRESETS))
    ap.add_argument('--run', required=True)
    ap.add_argument('--data', required=True, help='carpeta con validation.jsonl y test.jsonl')
    ap.add_argument('--resume', action='store_true')
    ap.add_argument('--generations', type=int)
    ap.add_argument('--stop-after', type=int, help='parar tras esta generación (para probar la reanudación)')
    a = ap.parse_args(argv)
    cfg = PRESETS[a.preset]
    if a.generations:
        cfg = replace(cfg, generations=a.generations)
    run, data = Path(a.run), Path(a.data)
    run.mkdir(parents=True, exist_ok=True)
    (run / 'checkpoints').mkdir(exist_ok=True)
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    torch.use_deterministic_algorithms(True)

    val = load_jsonl(data / 'validation.jsonl')
    excluded = {x['key'] for x in val} | {x['key'] for x in load_jsonl(data / 'test.jsonl')}
    val = val[:cfg.val_positions]

    torch.manual_seed(cfg.seed)
    rng = np.random.default_rng(cfg.seed)
    net = PolicyValueNet(cfg.channels, cfg.blocks).to(device)
    opt = torch.optim.Adam(net.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
    buf = Replay(cfg.buffer_size)
    evaluate = Evaluator(net, device)
    start = 1
    prev_prior = None
    if a.resume and (run / 'state.pt').exists():
        st = torch.load(run / 'state.pt', weights_only=False)
        net.load_state_dict(st['net']); opt.load_state_dict(st['opt'])
        rng.bit_generator.state = st['rng']['numpy']
        torch.set_rng_state(st['rng']['torch'])
        if st['rng']['cuda'] is not None:
            torch.cuda.set_rng_state_all(st['rng']['cuda'])
        buf.load(st['buffer'])
        prev_prior = st['prev_prior']
        start = st['generation'] + 1
        # Las filas de métricas posteriores al último estado completo se descartan: se van a repetir.
        lines = (run / 'metrics.jsonl').read_text(encoding='utf-8').splitlines()
        keep = [l for l in lines if l.strip() and json.loads(l)['generation'] < start]
        (run / 'metrics.jsonl').write_text(''.join(l + '\n' for l in keep), encoding='utf-8')
        print(f'reanudando en la generación {start} (pesos {weights_digest(net)})', flush=True)
    else:
        (run / 'config.json').write_text(json.dumps({'preset': a.preset, **asdict(cfg),
                                                     'parameters': count_parameters(net)}, indent=1),
                                         encoding='utf-8')
        (run / 'metrics.jsonl').write_text('', encoding='utf-8')
        torch.save(net.state_dict(), run / 'checkpoints' / 'gen_000.pt')
        s0 = summarize(solver_eval(evaluate, val, 0))
        s1 = summarize(solver_eval(evaluate, val, cfg.val_sims))
        row = {'generation': 0, 'val_net': s0['rate'], 'val_search': s1['rate'], 'val_n': s0['n']}
        with open(run / 'metrics.jsonl', 'a', encoding='utf-8') as f:
            f.write(json.dumps(row) + '\n')
        print(json.dumps(row), flush=True)

    for gen in range(start, cfg.generations + 1):
        t0 = time.time()
        torch.cuda.reset_peak_memory_stats() if device == 'cuda' else None
        x, pi, z, keys, sp = self_play(evaluate, cfg, rng, cfg.games_per_gen)
        keep = np.array([k not in excluded for k in keys], bool)
        buf.add(x[keep], pi[keep], z[keep], gen)
        t_play = time.time() - t0
        guard(cfg, 'autojuego')
        tr = train_steps(net, opt, buf, cfg, rng, device, gen)
        t_train = time.time() - t0 - t_play
        r_net = solver_eval(evaluate, val, 0)
        s0, s1 = summarize(r_net), summarize(solver_eval(evaluate, val, cfg.val_sims))
        prior = np.array([r['policy'] for r in r_net], np.float32)
        kl = kl_mean(prev_prior, prior) if prev_prior is not None else None
        prev_prior = prior
        torch.save(net.state_dict(), run / 'checkpoints' / f'gen_{gen:03d}.pt')
        # Estado completo en un solo fichero, escrito aparte y renombrado: o está entero o no está.
        torch.save({'net': net.state_dict(), 'opt': opt.state_dict(), 'rng': rng_state(rng), 'generation': gen,
                    'prev_prior': prev_prior, 'buffer': buf.state()}, run / 'state.tmp')
        os.replace(run / 'state.tmp', run / 'state.pt')
        row = {'generation': gen, **{k: v for k, v in sp.items() if k != 'sample_game'},
               'sample_game': sp['sample_game'], 'excluded_positions': int((~keep).sum()), **tr,
               'buffer': buf.n, 'val_net': s0['rate'], 'val_search': s1['rate'], 'val_n': s0['n'],
               'kl_prev': kl, 'seconds_selfplay': t_play, 'seconds_train': t_train,
               'seconds_total': time.time() - t0, 'evals_cumulative': evaluate.positions,
               'rss_gb': rss_gb(), 'gpu_peak_gb': (torch.cuda.max_memory_allocated() / 2 ** 30
                                                    if device == 'cuda' else 0.0),
               'weights': weights_digest(net)}
        with open(run / 'metrics.jsonl', 'a', encoding='utf-8') as f:
            f.write(json.dumps(row) + '\n')
        print(json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in row.items()
                          if k != 'sample_game'}), flush=True)
        guard(cfg, 'fin de generación')
        if a.stop_after and gen >= a.stop_after:
            break


if __name__ == '__main__':
    main()
''')

for name, c in train.PRESETS.items():
    evals = c.generations * c.games_per_gen * 35 * c.sims
    print(f'{name:9s} {c.generations:3d} generaciones x {c.games_per_gen:5d} partidas x {c.sims:4d} simulaciones, '
          f'red {c.blocks}x{c.channels}: unos {evals / 1e9:.2f} miles de millones de evaluaciones (35 jugadas por partida)')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The report evaluates a finished run: Elo of each checkpoint against the ladder (calculated once and saved alongside the data), each against its predecessor for chained Elo, simulation sweep on the test set with the last checkpoint, the list of positions with any error, and the deterministic game from the empty board checked with the solver.

[ ]Run reportLocal GPU
report = publish('report', r'''
"""Evaluación de una ejecución: Elo frente a rivales fijos, Elo encadenado, barrido de simulaciones y errores.

Uso: python -m az4.report --run DIR --data DIR [--every 3] [--sims 200] [--sweep 0,16,64,200,800]
"""
import argparse
import json
from pathlib import Path

import numpy as np
import torch

from .evaluate import (SearchPlayer, elo_bootstrap, elo_mle, fit_ladder, load_jsonl, minimax_player,
                       play_match, random_player, solver_eval, summarize)
from .engine import Solver, play
from .net import Evaluator, PolicyValueNet

DEPTHS = (2, 4, 8, 12)
LADDER = ['aleatorio'] + [f'horizonte {d}' for d in DEPTHS]


def ladder_players():
    return {'aleatorio': random_player(), **{f'horizonte {d}': minimax_player(d) for d in DEPTHS}}


def build_ladder(path, seed=7):
    """Torneo todos contra todos entre los rivales fijos: su Elo se calcula una vez y se congela."""
    if path.exists():
        return json.loads(path.read_text(encoding='utf-8'))
    rng = np.random.default_rng(seed)
    pl = ladder_players()
    pairs = {}
    for i, a in enumerate(LADDER):
        for b in LADDER[i + 1:]:
            s, _ = play_match(pl[a], pl[b], rng)
            pairs[(a, b)] = s
            print(f'{a} contra {b}: {s.mean():.3f}', flush=True)
    ratings = fit_ladder(pairs, LADDER, anchor='aleatorio')
    out = {'ratings': ratings, 'pairs': {f'{a} | {b}': float(s.mean()) for (a, b), s in pairs.items()},
           'games_per_pair': int(next(iter(pairs.values())).size)}
    path.write_text(json.dumps(out, indent=1, ensure_ascii=False), encoding='utf-8')
    return out


def load_net(cfg, path, device):
    net = PolicyValueNet(cfg['channels'], cfg['blocks']).to(device)
    net.load_state_dict(torch.load(path, map_location=device, weights_only=True))
    net.eval()
    return net


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('--run', required=True)
    ap.add_argument('--data', required=True)
    ap.add_argument('--every', type=int, default=3)
    ap.add_argument('--sims', type=int, default=200)
    ap.add_argument('--sweep', default='0,16,64,200,800')
    ap.add_argument('--seed', type=int, default=11)
    a = ap.parse_args(argv)
    run, data = Path(a.run), Path(a.data)
    cfg = json.loads((run / 'config.json').read_text(encoding='utf-8'))
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    rng = np.random.default_rng(a.seed)
    ladder = build_ladder(data / 'ladder.json')
    ratings = ladder['ratings']
    pl = ladder_players()
    ckpts = sorted((run / 'checkpoints').glob('gen_*.pt'))
    last = int(ckpts[-1].stem[4:])
    gens = sorted({g for g in range(0, last + 1, a.every)} | {last})

    elo, prev = [], None
    for g in gens:
        ev = Evaluator(load_net(cfg, run / 'checkpoints' / f'gen_{g:03d}.pt', device), device)
        agent = SearchPlayer(ev, a.sims, f'gen {g}')
        scores = {name: play_match(agent, pl[name], rng)[0] for name in LADDER}
        x = elo_mle(scores, ratings)
        lo, hi = elo_bootstrap(scores, ratings, rng)
        row = {'generation': g, 'elo': x, 'ci95': [lo, hi],
               'score': {k: float(v.mean()) for k, v in scores.items()}, 'games': int(sum(v.size for v in scores.values()))}
        if prev is not None:
            s, _ = play_match(agent, prev[1], rng)          # contra la generación evaluada anterior
            row['vs_previous'] = {'previous': prev[0], 'score': float(s.mean()), 'games': int(s.size)}
        prev = (g, agent)
        elo.append(row)
        print(json.dumps(row, ensure_ascii=False), flush=True)
    (run / 'elo.json').write_text(json.dumps({'ladder': ladder, 'sims': a.sims, 'rows': elo}, indent=1,
                                             ensure_ascii=False), encoding='utf-8')

    # Barrido de simulaciones y errores del último punto de control en el conjunto de prueba.
    test = load_jsonl(data / 'test.jsonl')
    ev = Evaluator(load_net(cfg, run / 'checkpoints' / f'gen_{last:03d}.pt', device), device)
    sweep, rows_by = [], {}
    for s in [int(t) for t in a.sweep.split(',')]:
        rows = solver_eval(ev, test, s)
        rows_by[s] = rows
        sm = summarize(rows)
        sweep.append({'sims': s, **sm})
        print(f'prueba, {s} simulaciones: {sm["optimal"]}/{sm["n"]} = {sm["rate"]:.4f}', flush=True)
    top = max(rows_by)
    errors = []
    for r0, r1 in zip(rows_by[0], rows_by[top]):
        if not (r0['optimal'] and r1['optimal']):
            errors.append({**r1, 'net_choice': r0['choice'], 'net_optimal': r0['optimal']})
    # Autojuego determinista desde el tablero vacío y valor exacto de cada posición desde la jugada 10.
    agent = SearchPlayer(ev, top, 'final')
    _, games = play_match(agent, agent, rng, openings=[()])
    moves = games[0]['moves']
    solver, p, m, exact = Solver(), 0, 0, []
    for i, c in enumerate(moves):
        if i >= 10:
            v = solver.value(p, m)
            exact.append({'ply': i, 'value_first': v if i % 2 == 0 else -v})
        p, m, _ = play(p, m, c)
    first = {'moves': moves, 'result_first': {1.0: 1, 0.5: 0, 0.0: -1}[games[0]['done']], 'exact_from_ply_10': exact}
    print('autojuego determinista:', ''.join(str(c + 1) for c in moves), 'resultado para el primero:',
          first['result_first'], flush=True)
    (run / 'final_eval.json').write_text(json.dumps({'generation': last, 'sweep': sweep, 'top_sims': top,
                                                     'errors': errors, 'selfplay': first}, ensure_ascii=False),
                                         encoding='utf-8')
    print(f'{len(errors)} posiciones con algún error (red sola o con {top} simulaciones)')


if __name__ == '__main__':
    main()
''')
print('escalera de rivales fijos:', report.LADDER)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Check that everything works

Before committing three GPU nights, a smoke run with a tiny set (8 positions per phase) traverses the full path: build solver sets, train two generations, interrupt and resume, and generate the report with its ladder. The decisive check is equality of weights between continuous and resumed runs.

[ ]Smoke datasetsLocal GPU
from az4.evaluate import build_positions, save_jsonl, random_baseline

DATA_HUMO = LAB / 'data-humo'
DATA_HUMO.mkdir(exist_ok=True)
rng = np.random.default_rng(2026)
val = build_positions(8, rng)
test = build_positions(8, rng, exclude={x['key'] for x in val})
save_jsonl(val, DATA_HUMO / 'validation.jsonl')
save_jsonl(test, DATA_HUMO / 'test.jsonl')
print(f'validación {len(val)}, prueba {len(test)}; decisivas {sum(x["decisive"] for x in test)} de {len(test)}; '
      f'acierto del azar en prueba {random_baseline(test):.3f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Smoke: train, interrupt, resume, and compare weightsLocal GPU
RUNS = LAB / 'runs'
for name in ('humo', 'humo-reanudada'):
    shutil.rmtree(RUNS / name, ignore_errors=True)

t = time.perf_counter()
run('train', '--preset', 'humo', '--run', RUNS / 'humo', '--data', DATA_HUMO)
run('train', '--preset', 'humo', '--run', RUNS / 'humo-reanudada', '--data', DATA_HUMO, '--stop-after', 1)
print(run('train', '--preset', 'humo', '--run', RUNS / 'humo-reanudada', '--data', DATA_HUMO, '--resume').splitlines()[0])


def last_weights(folder):
    rows = [json.loads(l) for l in (folder / 'metrics.jsonl').read_text(encoding='utf-8').splitlines() if l.strip()]
    return rows[-1]['generation'], rows[-1]['weights']


a, b = last_weights(RUNS / 'humo'), last_weights(RUNS / 'humo-reanudada')
print('continua:  generación %d, pesos %s' % a)
print('reanudada: generación %d, pesos %s' % b)
assert a == b, 'la reanudación no es exacta: falta algo del estado'
print(f'reanudación exacta comprobada en {time.perf_counter() - t:.0f} s')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Smoke: full reportLocal GPU
out = run('report', '--run', RUNS / 'humo', '--data', DATA_HUMO, '--every', 1, '--sims', 16, '--sweep', '0,16')
ladder = json.loads((DATA_HUMO / 'ladder.json').read_text(encoding='utf-8'))
print('Elo de la escalera:', {k: round(v) for k, v in ladder['ratings'].items()})
for line in out.splitlines():
    if line.startswith('{'):
        r = json.loads(line)
        print(f"generación {r['generation']}: Elo {r['elo']:.0f} [{r['ci95'][0]:.0f}, {r['ci95'][1]:.0f}] en {r['games']} partidas")
    else:
        print(line)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Long runs

The next three cells do not run in automatic page tests because they take minutes to days. The first builds full sets, 334 positions per phase in validation and as many in test; with the solver above it took 507 s on the reference machine, almost all in the early phase. The second launches the short run used in the figures (preset corta, same seed): 20 generations in 15 minutes plus about 9 for the report on a laptop RTX 4060, with 1.6 GB of training process memory. The third is full training.

[ ]Complete validation and test setsLocal GPU
DATA = LAB / 'data'
DATA.mkdir(exist_ok=True)
rng = np.random.default_rng(2026)
t = time.perf_counter()
val = build_positions(334, rng)
test = build_positions(334, rng, exclude={x['key'] for x in val})
save_jsonl(val, DATA / 'validation.jsonl')
save_jsonl(test, DATA / 'test.jsonl')
for name, s in (('validación', val), ('prueba', test)):
    print(f'{name}: {len(s)} posiciones, {sum(x["decisive"] for x in s)} decisivas, azar {random_baseline(s):.3f}')
print(f'{time.perf_counter() - t:.0f} s')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Short verification run (used in figures)Local GPU
t = time.perf_counter()
run('train', '--preset', 'corta', '--run', RUNS / 'corta', '--data', DATA)
print(f'entrenamiento: {(time.perf_counter() - t) / 60:.1f} min')
print(run('report', '--run', RUNS / 'corta', '--data', DATA, '--every', 2, '--sims', 100,
          '--sweep', '0,16,64,200,800')[-2000:])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For the full run, the supervisor relaunches training with --resume if the process dies (a video driver restart or system update) and leaves everything in a log you can follow from another terminal. If memory monitoring caused it, it does not retry: inspect what is growing. With the measured 37,000 evaluations per second, each generation of 5000 games of about 35 moves with 600 simulations is about 10810^8 evaluations, roughly 47 minutes of self-play plus training and validation: 40 generations take around 33 hours, three nights.

[ ]Full training over several nightsLocal GPU
def supervise(preset, folder, data, max_restarts=10):
    log_path = folder.parent / f'{folder.name}.log'
    for attempt in range(max_restarts + 1):
        with open(log_path, 'a', encoding='utf-8') as log:
            r = subprocess.run([sys.executable, '-m', 'az4.train', '--preset', preset, '--run', str(folder),
                                '--data', str(data), '--resume'], cwd=LAB, stdout=log, stderr=subprocess.STDOUT,
                               env={**os.environ, 'PYTHONUTF8': '1'})
        if r.returncode == 0:
            return True
        tail = log_path.read_text(encoding='utf-8')[-2000:]
        print(f'intento {attempt}: código {r.returncode}')
        if 'MemoryError' in tail:
            print('la vigilancia de memoria ha detenido el proceso; no se reintenta:\n', tail)
            return False
    return False


FULL_RUN = RUNS / 'completa'
t = time.perf_counter()
if supervise('completa', FULL_RUN, DATA):
    print(f'entrenamiento terminado en {(time.perf_counter() - t) / 3600:.1f} h')
    print(run('report', '--run', FULL_RUN, '--data', DATA, '--every', 4, '--sims', 200,
              '--sweep', '0,16,64,200,800')[-2000:])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Read your results

The last cell reads the largest run it finds (complete, short, or smoke) and checks the lesson’s verifiable outcome: test accuracy above 95% with 800 simulations and a first-player win in deterministic self-play from the empty board, with the exact value of every position in that game from move 10.

[ ]Results and verifiable criterionLocal GPU
from az4.evaluate import wilson

for name in ('completa', 'corta', 'humo'):
    folder = RUNS / name
    if (folder / 'final_eval.json').exists():
        break
cfg = json.loads((folder / 'config.json').read_text(encoding='utf-8'))
rows = [json.loads(l) for l in (folder / 'metrics.jsonl').read_text(encoding='utf-8').splitlines() if l.strip()]
fin = json.loads((folder / 'final_eval.json').read_text(encoding='utf-8'))
print(f'ejecución «{name}»: {len(rows) - 1} generaciones, red {cfg["blocks"]}x{cfg["channels"]}, {cfg["parameters"]:,} parámetros')
print('gen  pérdida π  suelo H(π)  valor  Var(z)  entropía  longitud  val. red  val. búsqueda')
for r in rows[1:]:
    print(f"{r['generation']:3d}  {r['policy_loss']:9.3f}  {r['target_entropy']:10.3f}  {r['value_loss']:5.3f}  "
          f"{r['z_var']:6.3f}  {r['entropy_net']:8.3f}  {r['mean_length']:8.1f}  {r['val_net']:8.3f}  {r['val_search']:13.3f}")
print('\nconjunto de prueba, punto de control final (generación %d):' % fin['generation'])
for s in fin['sweep']:
    lo, hi = wilson(s['optimal'], s['n'])
    print(f"  {s['sims']:4d} simulaciones: {s['optimal']}/{s['n']} = {s['rate']:.4f}  Wilson [{lo:.4f}, {hi:.4f}]  "
          f"decisivas {s['decisive_rate']:.4f}  por fase " +
          ', '.join(f"{k} {v['rate']:.3f}" for k, v in s['by_phase'].items()))
top = max(fin['sweep'], key=lambda s: s['sims'])
sp = fin['selfplay']
exact = [x['value_first'] for x in sp['exact_from_ply_10']]
print('\nautojuego determinista:', ''.join(str(c + 1) for c in sp['moves']),
      '| resultado para el primer jugador:', {1: 'gana', 0: 'tablas', -1: 'pierde'}[sp['result_first']])
print('valores exactos para el primero desde la jugada 10:', ''.join({1: '+', 0: '0', -1: '-'}[v] for v in exact))
ok_rate = top['sims'] >= 800 and top['rate'] > 0.95
ok_play = sp['result_first'] == 1 and all(v == 1 for v in exact)
print(f'\ncriterio de acierto (> 95 % con 800 simulaciones): {"cumplido" if ok_rate else "no cumplido"}')
print(f'criterio de autojuego (gana el primero y conserva el valor): {"cumplido" if ok_play else "no cumplido"}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What you should obtain

The full run reproduces the scale of AlphaZero.jl for Connect 4: a 5-block, 128-channel residual network (about 1.6 million parameters according to its documentation), 5000 games per iteration with 600 simulations per move, batches of 1024, and a buffer growing to one million positions. There each iteration takes between one and two hours on an RTX 2070 with a 6-core processor, for 15 iterations total; its documentation graphs results against the solver and summarizes that the agent with search makes few detectable errors 14 moves ahead, although it remains imperfect at long-term strategic decisions and openings.

The clearest quantitative reference is Aditya Prasad’s Oracle series (2018), which evaluated its Connect 4 AlphaZero against a solver-labeled set of positions from very imperfect games, like ours. On the weak scale, where any winning move counts, the self-play-trained network scored 98.83% alone and 99.76% with 800-simulation search; on the strong scale requiring the fastest win or slowest loss, 95.70% and 96.95%. An identical network trained supervised on solver labels reached 98.93% and 99.79% on the weak scale: self-play was one tenth from the architecture’s ceiling. In their weak set chance scored 58.1%; in ours, which excludes immediate wins but retains positions where all moves have equal value, 71.2%. The sets differ and percentages are not directly comparable, but establish the order of magnitude: with full configuration, this lesson’s criterion, over 95% with 800 simulations, should be met with room to spare.

For scale: AlphaZero trained for 700,000 steps with batches of 4096 positions, 5000 first-generation TPUs generating games and 16 second-generation TPUs training (Silver et al., Science, 2018), and AlphaGo Zero played 4.9 million games with 1600 simulations per move in its first three days (Silver et al., Nature, 2017). Connect 4 fits on a laptop GPU because its tree is orders of magnitude smaller, not because the method differs.

As a reference for limited compute, the short verification run (20 generations, 8000 self-play games, a 483,144-parameter network, and about 15 GPU minutes) achieved 88.2% on the test set with network alone and 96.4% with 800 simulations, Wilson interval [95.1 %,97.4 %][95.1\,\%, 97.4\,\%]: it meets the first criterion, though barely. It does not meet the second. Playing itself without noise from the empty board, it opens in the third column instead of the central one, the only winning opening according to Allis’ solution, and the position after 10 moves is already a theoretical draw. On move 11 the first player makes an error leaving it lost, on move 14 the second returns the favor, and the game ends in a draw with a full board. This is exactly the defect average accuracy misses: openings, with consequences 30 moves ahead, are the phase where network value is poorest (with search, early is the phase with most errors in the table above), and the test set excludes them. The full run, with 12.5 times more games per generation, six times more simulations, and a 1,669,704-parameter network three and a half times larger, is expected to resolve it.

Exercises

QuizAn entropy that collapses
In a new run, normalized network entropy falls from 0.95 to 0.04 between generations 1 and 3, policy loss halves, mean game length stays fixed at 23 moves, and KL between generations is nearly zero from generation 3. Validation accuracy rises from 0.74 to 0.78 and plateaus. What is the strongest diagnosis?
NumericHow much do we know about 96%?
The agent gets 960 of 1000 independent test positions right. Calculate, as a percentage, the lower endpoint of the 95% Wilson interval (use z=1.96z = 1.96).
QuizAn Elo that rises without improvement
A run publishes an Elo curve obtained by matching each generation against the previous one and adding differences: it rises 1500 points over 20 generations. Against the fixed-opponent ladder the agent has risen only 300. What explanation needs no code error?
NumericElo against one opponent
Against a fixed opponent rated Elo 600, the agent scores 147 out of 196 games (draw = half a win). What is its maximum-likelihood Elo under the logistic model?
NumericThe value-loss ceiling
On new positions in a phase, outcome from the player-to-move perspective is z=+1z = +1 in 55% of cases, z=0z = 0 in 5%, and z=−1z = -1 in 40%. What mean squared error does the best value head ignoring the board obtain?
NumericWhat the network actually learned
Between two generations, mean policy loss falls from 1.40 to 1.10 nats and mean visit-target entropy H(π)H(\pi) from 1.25 to 0.98 nats. What is the mean gap KL⁡(π ∥ pθ)\KL(\pi \,\|\, p_\theta) in the second generation?
NumericIs the new generation better?
Two generations are evaluated on the same 1000 positions. Only the new one gets 31 right and only the old one gets 14 right; both succeed or both fail on the rest. Calculate the two-sided p-value of the exact McNemar test.
CodeEvaluate an agent against the solver
Implement evaluate_against_solver(agent, positions). Each position is a dictionary of legal moves to exact strong-scale scores: higher is better (an earlier win scores more), and the sign indicates a win (+), draw (0), or loss (−) for the player to move. agent(position) returns a move. Return (optimas, cambian): the percentage of positions where the move has the maximum score and the percentage where its score’s sign is less than the maximum score’s sign (the error changes the theoretical outcome). Both are out of all positions, between 0 and 100. Raise ValueError if there are no positions, a position has no moves, or the agent returns an illegal move.
def evaluate_against_solver(agent, positions):
  """Devuelve (porcentaje de jugadas óptimas, porcentaje de errores que cambian el resultado)."""
  optimas = cambian = 0
  for position in positions:
      action = agent(position)
      # tu código: compara con la mejor puntuación y con su signo
  return optimas, cambian
Shift+Enter to run

On the lab’s weak scale, q∗∈{−1,0,1}q^* \in \{-1, 0, 1\}, the exercise’s two figures coincide: every nonoptimal move changes the outcome. With strong scores they separate, and their difference counts wins the agent prolongs without losing.

Summary

Key idea
Judge AlphaZero training with three different instruments: dynamics signals with their reference (H(π)H(\pi) floor for policy loss, Var⁡(z)\Var(z) ceiling for value loss) to detect failures; Elo against fixed opponents to measure strength; and optimal-move percentage against a solver, with its interval, to measure correctness.
  • Generation kk is the network after kk phases; self-play statistics for phase kk describe network k−1k - 1. Resumption must yield bit-for-bit identical weights, and this is checked.
  • H(π,pθ)=H(π)+KL⁡(π ∥ pθ)H(\pi, p_\theta) = H(\pi) + \KL(\pi \,\|\, p_\theta): policy loss also falls when search concentrates its visits. Compare value loss with Var⁡(z)\Var(z), the error of someone ignoring the board.
  • Solver evaluation measures the agent without noise or temperature on a fixed set, deduplicated by reflection, separated from the buffer, with declared phases and random baseline. With 1000 positions the Wilson interval is about 2.5 points wide; compare two generations on the same positions with McNemar.
  • Estimate each generation’s Elo against a ladder of opponents with frozen Elo, with an opening-bootstrap interval. Chained Elo against the previous generation is unanchored and inflates.
  • Search is the improvement operator: network with search is more accurate than network alone, but not on every position. Surviving errors arise from low prior on the correct move, poorly estimated value, or horizon, and are separated by phase, severity, and relationship with search.