2️⃣ Single-Game AlphaZero MCTS (PUCT)

Learning Objectives
  • Implement a Node class, PUCT selection, expansion, and backup.
  • Assemble the full search loop and verify it finds tactical wins and blocks.

Before we build a fully batched version of Monte-Carlo Tree Search, let's build a simpler version of MCTS in plain Python that operates on a single board. Note that this is the AlphaZero variant of MCTS: rather than the UCB1 selection rule and random rollouts of vanilla MCTS, we select children with the PUCT rule (using the network's priors) and evaluate leaves with the network's value head.

We store statistics on the edges of each node: a node holds per-action arrays N (visit counts) and W (value sums, from this node's mover perspective), plus the network priors P and a dict of child Nodes created lazily. The substrate is the provided Connect4Env with a batch of size 1, so transitions are identical to the batched version (this matters for section 3).

Action = int # 0, 1, 2, 3, 4, 5, 6

@dataclass
class Node:
    """One node of the single-game search tree = one board state. Statistics live on the **edges**
    (per-action length-7 arrays), filled in as the search runs.

    Attributes:
        board          Board of batch shape (1,): the connect4 board for this state, and whose turn
                       it is. Note that `Connect4Env.step` auto-resets a finished board, so on a **terminal**
                       node this is the empty starting board, for which
                       only `terminal_value` is well-defined.
        is_terminal    bool : True if this state is game-over. Set by `expand`.
        terminal_value float : result from the perspective of this node's mover (= -reward of the
                       move that created the node). Only meaningful when `is_terminal=True`. Set by `expand`.
        P              (7,) network prior over each move. Set by `evaluate`.
        legal          (7,) bool legal-column mask. Set by `evaluate`.
        N              (7,) per-edge visit counts N(s, a). Updated by `backup`.
        W              (7,) per-edge value sums W(s, a), accumulated from the perspective of THIS
                       node's mover: backup negates each child value once per step on
                       the way up, so what lands here is already in this node's convention. Updated by `backup`.
        children       dict[Action, Node] : child nodes per played action, created lazily by `expand`.
        parent         Node | None : the node we were expanded from (`None` at the root).
        parent_action  Action | None : the column that led from `parent` to this node. Updated by `expand`.

    Properties:
        Q              (7,) per-edge mean value W / max(N, 1).
    """
    board: Board  # batch shape (1,); lives on GPU
    is_terminal: bool = False
    terminal_value: float = 0.0
    P: Tensor | None = None
    legal: Tensor | None = None
    N: Float[Tensor, "7"] = field(default_factory=lambda: t.zeros(7))   # N(s,a_0), ..., N(s,a_6)
    W: Float[Tensor, "7"] = field(default_factory=lambda: t.zeros(7))   # W(s,a_0), ..., W(s,a_6)
    children: dict[Action, 'Node'] = field(default_factory=dict)
    parent: 'Node | None' = None
    parent_action: Action | None = None

    @property
    def Q(self) -> Float[Tensor, "7"]:
        return self.W / t.maximum(self.N, t.ones_like(self.N))


# Sentinel "no action" returned by `select` when the selection walk stops on a terminal node.
# We use -100 rather than None because None silently inserts a dim when used to index a tensor
# (`t[None]`), whereas -100 is always an illegal column and raises loudly if ever misused as an index.
NULL_ACTION = -100

tests.test_mcts_node(Node)

Exercise - implement select_child (PUCT)

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

Return the action maximising the PUCT score

$$ PUCT(s,a) = Q(s,a) + c_\text{puct} p_\theta(a|s) \frac{ \sqrt{1 + \sum_{a'} N(s,a')} }{1 + N(s,a)} $$
Illegal moves always have $PUCT(s,a) = -\infty$. You can use node.legal to obtain a legal move mask for the board state at that node.

Use the same form in the batched version so the two agree exactly. \ You may assume there will always be at least one legal action.

def select_child(node : Node, c_puct: float) -> Action:
    """Return the action (column index) with the highest PUCT score at `node`.

    Everything you need is already stored on the node (see the `Node` class above):
        node.Q      (7,) per-edge mean values Q(s,a) = W / max(N, 1)  — a property, kept up to date
        node.N      (7,) per-edge visit counts N(s,a); its sum is the parent visit total Σ_a' N(s,a')
        node.P      (7,) the network prior p_θ(a|s), set when the node was evaluated
        node.legal  (7,) bool mask of legal columns

    Compute the PUCT score per action, set illegal actions to -inf, and take the argmax.

    Args:
        node:   the node to pick an action from (its edge statistics are already populated)
        c_puct: the exploration/exploitation trade-off constant c

    Returns:
        int: the PUCT-maximising column 0-6 (you may assume at least one action is legal).
        Return a plain Python int — `int(scores.argmax())`, not a 0-dim Tensor. A Tensor looks
        identical in comparisons but breaks `action in node.children` dict lookups in `select`
        (tensors hash by identity, not value).
    """
    raise NotImplementedError()


tests.test_select_child(select_child, Node)
Solution
def select_child(node : Node, c_puct: float) -> Action:
    """Return the action (column index) with the highest PUCT score at `node`.

    Everything you need is already stored on the node (see the `Node` class above):
        node.Q      (7,) per-edge mean values Q(s,a) = W / max(N, 1)  — a property, kept up to date
        node.N      (7,) per-edge visit counts N(s,a); its sum is the parent visit total Σ_a' N(s,a')
        node.P      (7,) the network prior p_θ(a|s), set when the node was evaluated
        node.legal  (7,) bool mask of legal columns

    Compute the PUCT score per action, set illegal actions to -inf, and take the argmax.

    Args:
        node:   the node to pick an action from (its edge statistics are already populated)
        c_puct: the exploration/exploitation trade-off constant c

    Returns:
        int: the PUCT-maximising column 0-6 (you may assume at least one action is legal).
        Return a plain Python int — `int(scores.argmax())`, not a 0-dim Tensor. A Tensor looks
        identical in comparisons but breaks `action in node.children` dict lookups in `select`
        (tensors hash by identity, not value).
    """
    sumN = node.N.sum()
    puct_score = node.Q + c_puct * node.P * t.sqrt(sumN + 1.0) / (1.0 + node.N)
    legal_score = t.where(node.legal, puct_score, -t.inf)
    return int(legal_score.argmax())


tests.test_select_child(select_child, Node)

Exercise - implement select

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

Starting at the root, take the PUCT-best action and step into that child, over and over, until you reach a node that is either terminal or whose PUCT-best action has not yet been expanded (no child). Return (node, action): the node to expand and the action to play. If you stopped on a terminal node there's nothing to expand, so return (node, NULL_ACTION).

You may assume root is never terminal. Use select_child to select the next action.

def select(root: Node, 
           c_puct: float
) -> tuple[Node, Action]:
    """Walks down the tree from root: at each node take the PUCT-best action (`select_child`);
    if that action has a child, step into it and repeat. Halt at the first node whose PUCT-best
    action has NO child yet (`action not in node.children`), or on a terminal node.

    Note the halting rule is a property of the node's best *action*, not of the node itself: a
    node may already have children on other actions (and visits on them) while its current
    PUCT-best action is still unexpanded — that node is where the walk stops.

    Args:
        root: The root node of the search tree (never terminal).
        c_puct: The PUCT constant.

    Returns:
        * `(node, action)`: the node to expand and the action to play, OR
        * `(node, NULL_ACTION)` if the walk stopped on a terminal node (nothing to expand).
    """
    assert not root.is_terminal, "select: root must not be terminal"
    raise NotImplementedError()


tests.test_select(select, Node)
Solution
def select(root: Node, 
           c_puct: float
) -> tuple[Node, Action]:
    """Walks down the tree from root: at each node take the PUCT-best action (`select_child`);
    if that action has a child, step into it and repeat. Halt at the first node whose PUCT-best
    action has NO child yet (`action not in node.children`), or on a terminal node.

    Note the halting rule is a property of the node's best *action*, not of the node itself: a
    node may already have children on other actions (and visits on them) while its current
    PUCT-best action is still unexpanded — that node is where the walk stops.

    Args:
        root: The root node of the search tree (never terminal).
        c_puct: The PUCT constant.

    Returns:
        * `(node, action)`: the node to expand and the action to play, OR
        * `(node, NULL_ACTION)` if the walk stopped on a terminal node (nothing to expand).
    """
    assert not root.is_terminal, "select: root must not be terminal"
    node = root
    while not node.is_terminal:
        a = select_child(node, c_puct)
        if a not in node.children:
            return node, a            # found unexpanded action
        node = node.children[a]       # descent into the chosen child
    return node, NULL_ACTION          # hit terminal node


tests.test_select(select, Node)

Exercise - implement expand

Difficulty: 🔴🔴⚪⚪⚪
Importance: 🔵🔵🔵🔵⚪
You should spend up to 10-15 minutes on this exercise.
  1. Play the given action action on the current board state node.board using env.step to receive a new board state.
  2. Construct a new Node object with the result, and store it as a child of the current node.
  3. Mark the child terminal if the move ended the game, and set the terminal_value to -reward received from the environment.
  4. Set parent/parent_action so we can follow from the child back to its parent later on.

Why terminal_value = -reward?

env.step reports the reward to the player who just moved, but the child's mover is the opponent, so from the child's perspective that value is negated.

You don't need to track whose turn it is yourself: env.step returns the child's Board with red_to_move already flipped.

@t.no_grad()
def expand(node: Node, 
           action: int, 
           env: Connect4Env) -> Node:
    """
    Plays the given action on the current board state, constructs a new node with the result,
    stores it as a child of the current node, and returns it.

    Side effects:
        * Mutates the current node to add a new child node.

    Args:
        node: The current node in the search tree.
        action: The action to play.
        env: The Connect4Env instance

    Returns:
        The newly created child node after the action has been played.
    """
    assert not node.is_terminal, "expand: cannot expand a terminal node"
    raise NotImplementedError()


tests.test_expand(expand)
Solution
@t.no_grad()
def expand(node: Node, 
           action: int, 
           env: Connect4Env) -> Node:
    """
    Plays the given action on the current board state, constructs a new node with the result,
    stores it as a child of the current node, and returns it.

    Side effects:
        * Mutates the current node to add a new child node.

    Args:
        node: The current node in the search tree.
        action: The action to play.
        env: The Connect4Env instance

    Returns:
        The newly created child node after the action has been played.
    """
    assert not node.is_terminal, "expand: cannot expand a terminal node"
    next_board, done, reward = env.step(node.board, action)
    child = Node(board = next_board,
                 is_terminal = done,
                 terminal_value = -reward,
                 parent = node,
                 parent_action = action)
    node.children[action] = child
    return child


tests.test_expand(expand)

Exercise - implement evaluate

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

Estimate the value of the current node.

If the node is terminal, then we already know the value, it was stored during its creation in node.terminal_value. If the node is non-terminal, we estimate the value using the critic. We also set the node.P and node.legal attributes using the actor. Recall that the model returns a tuple of (value, logits) for the critic and actor heads.

  • Use model(node.board) -> (value, logits) for the forward pass.
  • Don't forget that the returned tensors live on the GPU, while the tree's per-node stats live in CPU memory.
  • You can use env.legal_action_mask(board : Board) to get a mask for the legal moves for a given board state (you'll have to strip off the batch dimension).
@t.no_grad()
def evaluate(node: Node, model: nn.Module, env: Connect4Env) -> float:
    """
    Estimates the value of a node from its mover's perspective.

    Side effects:
        If the node is non-terminal, mutates the node to 
        set the `node.P` and `node.legal` attributes to the
        action probability from the model, and to the current legal moves
        of the board respectively.

    Args:
        node: The node to estimate the value of.
        model: The model to use.
        env: The Connect4Env instance

    Returns:
        For terminal nodes: the stored `terminal_value` (already from the mover's perspective).
        For non-terminal nodes: the critic head's value estimate, from the mover's perspective.
    """
    raise NotImplementedError()


tests.test_evaluate(evaluate)
Solution
@t.no_grad()
def evaluate(node: Node, model: nn.Module, env: Connect4Env) -> float:
    """
    Estimates the value of a node from its mover's perspective.

    Side effects:
        If the node is non-terminal, mutates the node to 
        set the `node.P` and `node.legal` attributes to the
        action probability from the model, and to the current legal moves
        of the board respectively.

    Args:
        node: The node to estimate the value of.
        model: The model to use.
        env: The Connect4Env instance

    Returns:
        For terminal nodes: the stored `terminal_value` (already from the mover's perspective).
        For non-terminal nodes: the critic head's value estimate, from the mover's perspective.
    """
    if node.is_terminal:
        return node.terminal_value                                   
    value, logits = model(node.board)
    value = value.squeeze(0).float().cpu()    # .float(): keep node stats fp32 even if the net runs in bf16
    logits = logits.squeeze(0).float().cpu()
    node.legal = env.legal_action_mask(node.board).squeeze(0).cpu()
    legal_logits = t.where(node.legal, logits, -t.inf)
    node.P = t.softmax(legal_logits, dim=-1)
    return float(value)


tests.test_evaluate(evaluate)

Exercise - implement backup

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

Backup walks from a node back along the parent pointers to the root. At each edge it flips the sign of a running copy of the value (v = -v), then adds one to the visit count N and adds v to the value sum W, so the sign alternates along the path (negamax). The stored values are not negated in place; only the local running v is. Mutates N/W in place; returns nothing.

Don't forget to flip the sign of the value at every step (negamax): the sign alternates between consecutive edges!

def backup(leaf: Node, value: float) -> None:
    """Walks from a node back up the tree to the root, updating the visit counts and value sums at each edge.

    Side effects:
        * Mutates the visit counts and value sums at each edge.

    Args:
        leaf: The leaf node to backup from.
        value: The value of the leaf node from its mover's perspective.

    Returns:
        None
    """
    raise NotImplementedError()


tests.test_backup(backup, Node)
Solution
def backup(leaf: Node, value: float) -> None:
    """Walks from a node back up the tree to the root, updating the visit counts and value sums at each edge.

    Side effects:
        * Mutates the visit counts and value sums at each edge.

    Args:
        leaf: The leaf node to backup from.
        value: The value of the leaf node from its mover's perspective.

    Returns:
        None
    """
    v, curr = value, leaf
    while curr.parent is not None:
        v = -v
        curr.parent.N[curr.parent_action] += 1.0
        curr.parent.W[curr.parent_action] += v
        curr = curr.parent


tests.test_backup(backup, Node)

Exercise - implement sample_tree_policy

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

After the MCTS sampling, we then define the tree policy based on the visit counts. This is the actual policy that is used to play the game.

$$ \pi(a|s) = \frac{N(s,a)}{\sum_{a'} N(s,a')} $$

During self-play we sample from this distribution. When greedy=True (deployment and evaluation), just return the action with the highest visit count instead.

Use t.multinomial to sample from the distribution.

def sample_tree_policy(visits: Float[Tensor, "7"], 
                       greedy: bool = False,
) -> Action:
    """Samples an action from the tree policy: proportional to visits, or the argmax if `greedy`.

    Args:
        visits: The visit counts for each action, shape `(7,)`.
        greedy: If True, return the action with the most visits instead of sampling.

    Returns:
        int: The action to sample.
    """
    raise NotImplementedError()


tests.test_sample_tree_policy(sample_tree_policy)
Solution
def sample_tree_policy(visits: Float[Tensor, "7"], 
                       greedy: bool = False,
) -> Action:
    """Samples an action from the tree policy: proportional to visits, or the argmax if `greedy`.

    Args:
        visits: The visit counts for each action, shape `(7,)`.
        greedy: If True, return the action with the most visits instead of sampling.

    Returns:
        int: The action to sample.
    """
    if greedy:
        return int(visits.argmax())

    probs = visits / visits.sum()
    return int(t.multinomial(probs, 1))


tests.test_sample_tree_policy(sample_tree_policy)

Root exploration noise (given)

We inject some noise to the prior at the root node when doing MCTS simulations (NOT when actually selecting the move, or when evaluating the model) to encourage exploration from the root node.

$$ P(a) \;\leftarrow\; (1-\varepsilon)\,P(a) \;+\; \varepsilon\,\eta_a, \qquad \eta \sim \mathrm{Dir}(\alpha). $$
with $\varepsilon = 0.25$ and $\alpha = 10/7$, and $\mathrm{Dir}$ denotes the Dirichlet distribution. See section Self-Play in the original paper.

More details on root exploration noise

MCTS is steered by the network's prior, so it mostly explores moves the network already likes, and the network only learns about moves the search explores. It could be the case that the policy network collapses to near determinism early, completely killing the P-UCT exploration term.

AlphaZero's fix is to add Dirichlet noise to the prior at the root only so it changes which move from the current board state gets explored without tampering with the search's own value estimates:

The Dirichlet distribution is a distribution over probability vectors $\eta=(\eta_1,\dots,\eta_n)$ with $\eta_i \ge 0$ and $\sum_i \eta_i = 1$ i.e. over the probability simplex. In general it has one concentration parameter per component, $\alpha_1,\dots,\alpha_n$, but we use the same $\alpha$ for all of them (a symmetric Dirichlet). That single $\alpha$ controls how spiky the samples are:

  • $\alpha < 1$: spiky / sparse: most weight lands on one or two moves, so the noise occasionally gives a normally-ignored column a big boost (strong, targeted exploration).
  • $\alpha = 1$: uniform over the simplex.
  • $\alpha > 1$: flat: close to the centroid $(1/n,\dots,1/n)$, only a mild perturbation.

See this blog post for some details and plots of the Dirichlet distribution.

What is a Dirichlet distribution, and why use one here?

The Dirichlet is the standard distribution over probability vectors, and the conjugate prior of the categorical distribution.

In less fancy terms, if you have a random variable that generates outcomes over one of $n$ possible options (e.g. unfair dice), the Dirichlet distribution has the property that if your prior over the distribution of the dice rolls is Dirichlet, then the posterior after obtaining evidence and updating using Bayes rule is also Dirichlet, which is mathematically convenient.

The update rule is also convenient and avoids any nasty integration: If your prior over a die's face probabilities is $\mathrm{Dir}(\alpha_1, \dots, \alpha_n)$ and face $i$ then comes up $c_i$ times, the posterior is just $\mathrm{Dir}(\alpha_1 + c_1, \dots, \alpha_n + c_n)$.

So each $\alpha_i$ acts like a "pseudo-count" seen before any data. Setting all the $\alpha_i$ equal to $\alpha$, large $\alpha$ says you're confident the probabilities are all about equal and $\alpha$ below 1 says you expect most of the mass on a few outcomes, without saying which.

This implies that by choosing $\alpha=10/7$, we're claiming that we've already seen every move played "10/7" times, whatever that means. We then created a weighted mixture of a sample $\eta \sim \text{Dir}(\alpha)$ with the prior $P$ given by the network.

Here there's no Bayesian updating, and the noise isn't really a prior: we just need random probability vectors to mix into $P$. The Dirichlet is the natural choice because:

  • every sample is a valid distribution over moves, so $(1-\varepsilon)P + \varepsilon\eta$ is also valid,
  • the symmetric version favours no move over another,
  • a single number, $\alpha$, sets how concentrated the noise is.

Gumbel AlphaZero suggests to remove the Dirichlet noise and instead replace it with a method based on the Gumbel-Max trick of choosing which root moves to search that provably improves the policy.

Where did those values of eps and alpha come from?

Not entirely clear: $\varepsilon=0.25$ we cargo cult from the original implementation. For $\alpha$, see Appendix: Configuration in this paper, where they mention that $\alpha$ is chosen to be inversely proportional to the number of legal moves (who knows why, they didn't say!) Extrapolating from the values of $\alpha$ given for chess, shogi and Go gives the rough rule of thumb $\alpha = \dfrac{10}{\text{average number of legal moves}}$ for which we choose alpha = 10/7 for Connect4.

I didn't really find this to be terribly critical a value when building this material, and it works fine for other reasonable values of $\alpha$. You can disable the noise entirely with either cfg.dirichlet_eps=0 or passing add_noise=False to mcts, but we do actually get worse performance with the root noise disabled, and it was more faithful to the original implementation, so I left it in.

You can see in the following plot a series of runs with and without the noise enabled. Not only does it help performance, it also makes the variance of performance (as measured by cross-entropy loss on the pascal-pons benchmark) between different seeds much lower.

def dirichlet_root_noise(
    prior: Float[Tensor, "... 7"],
    legal: Bool[Tensor, "... 7"],
    alpha: float,
    eps: float,
) -> Float[Tensor, "... 7"]:
    """Mix Dirichlet exploration noise into the root prior.

    Args:
        prior: (..., 7) the network prior at the root
        legal: (..., 7) legal-column mask (the noise is renormalised over the legal columns)
        alpha: Dirichlet concentration (smaller = spikier noise)
        eps:   mixing weight on the noise

    Returns:
        (..., 7) the mixed prior `(1 - eps) * prior + eps * noise`
    """
    noise = t.distributions.Dirichlet(
        t.full((prior.shape[-1],), alpha, device=prior.device)
    ).sample(prior.shape[:-1])
    noise = noise * legal.float()
    noise = noise / noise.sum(-1, keepdim=True).clamp_min(1e-8)
    return (1.0 - eps) * prior + eps * noise


tests.test_dirichlet_root_noise(dirichlet_root_noise)

Exercise - implement mcts

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

Each simulation grows the tree by at most one node (none if select stops at a terminal node), via the four MCTS phases you just built. The root is created and evaluate'd for you; we then loop the four phases of MCTS for cfg.sims times.

  1. SELECT. We use select to walk down from the root, following the PUCT-best action at each node, until we reach a node we can't go further from: either its chosen action leads to a position not yet in the tree, or the node is terminal. select returns (node, action): the node to expand (unless it's terminal) and the action to expand it with (or NULL_ACTION if the node is terminal).
  2. EXPAND. If the selected node from select is:
    • non-terminal, we expand it by adding the new child node reached by that action. This new child is the leaf for the remaining steps.
    • terminal, there is nothing to do, and the selected node itself is the leaf.
  3. EVALUATE. We evaluate the leaf to get its value (terminal or not).
  4. BACKUP. We backup the obtained value of the leaf up the tree, through its ancestors to the root.

After cfg.sims iterations, return the root Node (not its visit counts). Its visit counts root.N are what we then use to choose the action played against the opponent.

This function should be mostly gluing together the previous functions select, expand, evaluate and backup that you wrote earlier.

@t.no_grad()
def mcts(
    root_board: Board,
    model: nn.Module,
    env: Connect4Env,
    cfg: MCTSConfig,
    add_noise: bool = False,
) -> Node:
    """Runs single-game MCTS from `root_board` and returns the root of the search tree.

    The root node is created and evaluated (setting its prior `P` and `legal` mask) before the
    loop. Each of the `cfg.sims` simulations then grows the tree by (at most) one node:
    `select` a node and action, 
    `expand` the new child it leads to (if the node is not terminal),
    `evaluate` the (possibly new) leaf node,
    `backup` its value from the leaf to the root.

    Args:
        root_board:  the position to search from, a single-game `Board` of batch shape (1,).
                     Must not be terminal.
        model:       the policy-value network, called as `model(boards) -> (value, logits)`.
        env:         the Connect4Env, used to play moves during expansion.
        cfg:         search settings; reads `cfg.sims` and `cfg.c_puct` (plus `cfg.dirichlet_alpha`
                     and `cfg.dirichlet_eps` when `add_noise=True`).
        add_noise:   if True, mix Dirichlet exploration noise into the root prior (self-play only;
                     leave False for evaluation, so the search is deterministic).

    Returns:
        The root node `root`, after `cfg.sims` many MCTS simulations were performed. 
        `root.N` are the (7,) root visit counts N(root, a), summing to `cfg.sims` (illegal columns get 0)
        `root.children` holds the rest of the tree.
    """
    root = Node(root_board)
    evaluate(root, model, env) #required to set root.P and root.legal
    if add_noise:   # mix Dirichlet exploration noise into the root prior
        root.P = dirichlet_root_noise(root.P, root.legal, cfg.dirichlet_alpha, cfg.dirichlet_eps)
    for _ in range(cfg.sims):
        raise NotImplementedError()
    return root

# First check the search logic in isolation, with a dummy (uniform-policy, zero-value) network:
# a forced win-in-one must be found purely from the terminal reward backing up the tree.
tests.test_mcts(mcts)
# Then confirm the same search drives the real network correctly:
tests.test_mcts(mcts, Connect4Model(device).eval())
Solution
@t.no_grad()
def mcts(
    root_board: Board,
    model: nn.Module,
    env: Connect4Env,
    cfg: MCTSConfig,
    add_noise: bool = False,
) -> Node:
    """Runs single-game MCTS from `root_board` and returns the root of the search tree.

    The root node is created and evaluated (setting its prior `P` and `legal` mask) before the
    loop. Each of the `cfg.sims` simulations then grows the tree by (at most) one node:
    `select` a node and action, 
    `expand` the new child it leads to (if the node is not terminal),
    `evaluate` the (possibly new) leaf node,
    `backup` its value from the leaf to the root.

    Args:
        root_board:  the position to search from, a single-game `Board` of batch shape (1,).
                     Must not be terminal.
        model:       the policy-value network, called as `model(boards) -> (value, logits)`.
        env:         the Connect4Env, used to play moves during expansion.
        cfg:         search settings; reads `cfg.sims` and `cfg.c_puct` (plus `cfg.dirichlet_alpha`
                     and `cfg.dirichlet_eps` when `add_noise=True`).
        add_noise:   if True, mix Dirichlet exploration noise into the root prior (self-play only;
                     leave False for evaluation, so the search is deterministic).

    Returns:
        The root node `root`, after `cfg.sims` many MCTS simulations were performed. 
        `root.N` are the (7,) root visit counts N(root, a), summing to `cfg.sims` (illegal columns get 0)
        `root.children` holds the rest of the tree.
    """
    root = Node(root_board)
    evaluate(root, model, env) #required to set root.P and root.legal
    if add_noise:   # mix Dirichlet exploration noise into the root prior
        root.P = dirichlet_root_noise(root.P, root.legal, cfg.dirichlet_alpha, cfg.dirichlet_eps)
    for _ in range(cfg.sims):
        node, action = select(root, cfg.c_puct)
        if not node.is_terminal:
            leaf = expand(node, action, env)
        else:
            leaf = node
        leaf_value = evaluate(leaf, model, env)
        backup(leaf, leaf_value)
    return root

# First check the search logic in isolation, with a dummy (uniform-policy, zero-value) network:
# a forced win-in-one must be found purely from the terminal reward backing up the tree.
tests.test_mcts(mcts)
# Then confirm the same search drives the real network correctly:
tests.test_mcts(mcts, Connect4Model(device).eval())

Watch it find a win

To show the search does the tactical work, we hand MCTS a dummy network that returns value 0 and a uniform prior for every board. So whatever the search concentrates on comes purely from the tree policy backing up terminal rewards, not from the net.

Below it's Red (X) to move on a crowded mid-game position where Red already has a diagonal three, (5,1)-(4,2)-(3,3). Dropping in column 4 falls to (2,4) and completes the / diagonal; with a uniform prior, only the visit counts can single it out.

The right-hand bars are the visit-count policy $\pi(a) = N(s,a) / \sum_{a'} N(s,a')$: the improved policy that we will train the policy network to mimic.

class DummyNet(nn.Module):

    def forward(self, boards):
        b, dev = boards.shape[0], boards.obs.device
        values = t.zeros(b, device=dev)
        logits = t.zeros(b, 7, device=dev)
        return values, logits

model = DummyNet()
board = tests.diagonal_win_red()

print("Starting position (X = Red to move):")
print(render_board(board))

root = mcts(board, model, env, MCTSConfig(sims=32))
visits = root.N
print("\nMCTS visit counts per column:", visits.int().tolist())
chosen = int(visits.argmax())
print(f"Most-visited column: {chosen}  ({int(visits[chosen])} of {int(visits.sum())} visits)")

board_after = place_piece(board, chosen)
print(f"\nBoard after X plays column {chosen}  (completes the diagonal):")
print(render_board(board_after, show_to_move=False))

# board + the visit-count policy pi(a) = N(s,a) / sum_a' N(s,a'), chosen column highlighted
plot_board_and_policy(board, visits / visits.sum(), chosen_action=chosen,
                      title="MCTS finds the diagonal win")
# the search tree the simulations grew: edge thickness ~ visit count, terminal leaves in yellow
plot_mcts_tree(root, max_depth=2, title="MCTS search tree (after 32 sims)")
tests.test_diagonal_win(visits)