☆ Bonus

Claude has some suggestions for you. I personally haven't vetted the below, so take with a grain of salt.


Some directions if you have time:

  • Tune the search. How does strength (Pons optimal-move accuracy) change with sims (simulations per move) and c_puct? (More play-time sims makes the agent stronger without any retraining: see the Elo ladder below.)
  • Subtree reuse. Between consecutive moves of one game, the new root is a child of the old root — its subtree is already partly searched. Reuse it instead of starting from scratch.
  • Bigger network. Add more residual blocks or channels. Where are the diminishing returns?
  • Compare to a model-free method. [2.3] trains PPO against a fixed environment, not by self-play. Adapt it to train the same network by self-play on Connect 4 and compare it with AlphaZero. Which is more sample-efficient here, and why?

Exercise - data augmentation by mirror symmetry

Difficulty: 🔴🔴⚪⚪⚪
Importance: 🔵🔵🔵⚪⚪
You should spend up to 10-20 minutes on this exercise.

Connect 4 is left-right mirror-symmetric: reflecting the board across the centre column gives a strategically identical position. So every self-play example (boards, pi, z) can be made into a mirror copy: reflect the board, reverse the action distribution column-wise (column $c \leftrightarrow 6 - c$), and keep the value unchanged. Training on both doubles your data at zero self-play cost. (This is a standard trick; AlphaGo Zero exploited all 8 symmetries of the Go board (reflections and rotations)).

Implement augment_with_mirror, returning the batch concatenated with its mirror image (mirroring a board doesn't change whose turn it is, so only boards.obs gets flipped). The simplest place to apply it is at the top of training_step (doubling each minibatch); augmenting in the buffer's minibatches works too, the trainer just sees bigger batches either way. Then see whether the agent reaches a given strength in fewer self-play games.

def augment_with_mirror(
    boards: Board,
    pi: Float[Tensor, "batch 7"],
    z: Float[Tensor, "batch"],
) -> tuple[Board, Float[Tensor, "b2 7"], Float[Tensor, "b2"]]:
    """Concatenate (boards, pi, z) with their left-right mirror image (Connect-4's only symmetry).

    Args:
        boards: (B,) boards
        pi:     (B, 7) policy targets
        z:      (B,) value targets

    Returns:
        boards: (2B,) original + width-flipped boards (same `red_to_move`)
        pi:     (2B, 7) original + column-reversed policies
        z:      (2B,) value targets, duplicated unchanged
    """
    raise NotImplementedError()


tests.test_augment_with_mirror(augment_with_mirror)
Solution
def augment_with_mirror(
    boards: Board,
    pi: Float[Tensor, "batch 7"],
    z: Float[Tensor, "batch"],
) -> tuple[Board, Float[Tensor, "b2 7"], Float[Tensor, "b2"]]:
    """Concatenate (boards, pi, z) with their left-right mirror image (Connect-4's only symmetry).

    Args:
        boards: (B,) boards
        pi:     (B, 7) policy targets
        z:      (B,) value targets

    Returns:
        boards: (2B,) original + width-flipped boards (same `red_to_move`)
        pi:     (2B, 7) original + column-reversed policies
        z:      (2B,) value targets, duplicated unchanged
    """
    # reflect the board across the centre column (width is the last dim); whose turn it is is unchanged
    boards_m = Board(boards.obs.flip(dims=[-1]), boards.red_to_move)
    pi_m = pi.flip(dims=[-1])     # column c <-> column 6 - c
    return Board.cat([boards, boards_m]), t.cat([pi, pi_m]), t.cat([z, z])


tests.test_augment_with_mirror(augment_with_mirror)

The AlphaZero scaling law: Elo vs log(search)

How much is search alone worth? A clean way to measure it is a self-play ladder: take the same trained network and have it play itself at different simulation budgets, then fit an Elo rating to the round-robin results. Elo only fixes rating differences (a 400-point gap means 10:1 odds), so the zero point is a convention: we pin the raw policy network, playing with no search at all, at Elo 1000. Plotting Elo against $\log_2(\text{sims})$ reproduces the well-known AlphaZero result that playing strength is roughly linear in the log of the search budget — every doubling of thinking time buys a roughly constant Elo gain, with no change to the weights.

(This is SLOW: it runs a full round-robin of MCTS-vs-MCTS matches. Set SLOW = True to run it, ideally on a strong network — train one with a longer run first, e.g. sims=64 and num_generations=50.)

@t.no_grad()
def _ladder_action(model, env, boards, sims):
    """Move for the side to move: raw policy if sims == 0, else MCTS with `sims` simulations."""
    if sims == 0:
        return greedy_policy_action(model, boards)
    # This uses MCTSConfig's default c_puct=1.5, not AZConfig's 1.0. That's deliberate: 1.0 was tuned for
    # generating *training* data (with root noise), and play-time search is a separate setting. On the default
    # recipe's network, 1.5 scored 0.92 vs the raw policy at 64 sims, against 0.86 with 1.0.
    N = BatchedMCTS(env, MCTSConfig(sims=sims)).search(model, boards, add_noise=False)
    # At tiny budgets visit counts often tie (with 2 sims, ~40% of moves are a 1-1 split). A plain
    # argmax would break those ties by column index, making low-sim players weaker than no search at
    # all. Break them by the prior instead (the bonus is small enough to never override a real gap).
    _, logits = model(boards)
    prior = masked_softmax_prior(logits, legal_mask_from_obs(boards.obs))
    return (N + 1e-3 * prior).argmax(-1)


@t.no_grad()
def ladder_match(model, env, sims_a, sims_b):
    """Player A (sims_a) vs player B (sims_b), same network, over all 98 openings (A as both
    colours). Returns A's score (win + ½·draw) in [0, 1]."""
    boards, a_is_red = two_ply_positions(env)
    N = boards.shape[0]
    finished = t.zeros(N, dtype=t.bool, device=env.device)
    result = t.zeros(N, device=env.device)
    for _ in range(42):
        if bool(finished.all()):
            break
        a_to_move = (boards.red_to_move == a_is_red)
        move = t.where(a_to_move,
                           _ladder_action(model, env, boards, sims_a),
                           _ladder_action(model, env, boards, sims_b))
        boards, done, rew = env.step(boards, move)
        newly = done & (~finished)
        win = newly & (rew > 0.5)
        result = t.where(win & a_to_move, t.ones_like(result), result)
        result = t.where(win & (~a_to_move), -t.ones_like(result), result)
        finished = finished | newly
    w = int((result > 0.5).sum()); l = int((result < -0.5).sum()); d = N - w - l
    return (w + 0.5 * d) / N


def fit_elo(score_matrix, n_games=98, iters=3000, lr=10.0):
    """Maximum-likelihood (Bradley-Terry) Elo fit to a pairwise score matrix (score[i,j] = i's score
    vs j over `n_games` games), centred at 0. Each pairing gets one extra virtual draw (as in
    BayesElo), so a clean sweep gives a large but finite rating gap instead of an infinite one."""
    S = score_matrix.shape[0]
    R = t.zeros(S, requires_grad=True)
    P = (t.as_tensor(score_matrix, dtype=t.float32) * n_games + 0.5) / (n_games + 1)
    off = ~t.eye(S, dtype=t.bool)
    opt = t.optim.Adam([R], lr=lr)
    for _ in range(iters):
        logits = (R[:, None] - R[None, :]) * (math.log(10) / 400)   # expected score = sigmoid(logits)
        loss = F.binary_cross_entropy_with_logits(logits[off], P[off])
        opt.zero_grad(); loss.backward(); opt.step()
    return (R.detach() - R.detach().mean())
if SLOW:
    levels = [0, 1, 2, 4, 8, 16, 32, 64]   # 0 = the raw policy network, no search
    S = len(levels)
    score = t.full((S, S), 0.5)
    pairs = [(i, j) for i in range(S) for j in range(i + 1, S)]
    for i, j in tqdm(pairs, desc="ladder matches"):
        score[i, j] = ladder_match(model, env, levels[i], levels[j])
        score[j, i] = 1 - score[i, j]
    elo = fit_elo(score.numpy())
    elo = elo - elo[0] + 1000   # Elo only fixes differences: by convention, the raw policy is 1000
    for M, e in zip(levels, elo.tolist()):
        print(f"{'raw policy' if M == 0 else f'{M:3d} sims':>10}:  Elo {e:5.0f}")
if SLOW:
    import matplotlib.pyplot as plt

    searched = [M for M in levels if M > 0]   # log2(0) is undefined: the raw policy is a reference line
    fig, ax = plt.subplots(figsize=(7, 4.5))
    ax.axhline(1000, color="gray", ls="--", label="raw policy, no search (Elo 1000 by convention)")
    ax.plot([math.log2(M) for M in searched], elo[1:].tolist(), "o-", label="policy + MCTS")
    ax.set_xticks([math.log2(M) for M in searched]); ax.set_xticklabels(searched)
    ax.legend()
    ax.set_xlabel("MCTS simulations per move (log scale)")
    ax.set_ylabel("Elo (self-play ladder)")
    ax.set_title("Strength is ~linear in log(search) — the AlphaZero scaling law")
    ax.grid(alpha=0.3); fig.tight_layout()
Click to see the expected output

This was measured on the default AZConfig() recipe (16 sims, 8 generations, ~86% Pons accuracy). On an RTX A4000 training took ~3.3 min and the ladder ~5.6 min. Search adds roughly +50 Elo per doubling, and 64 sims scores ~0.80 against the raw policy. 1 and 2 sims sit exactly on the raw policy: with one or two visits there's nothing for search to change, since the ladder breaks visit-count ties by the prior.