Stronger backgammon

Here we show some findings when training a simple MLP to roughly match performance of GNU Backgammon (GNUbg) [1] by self-play. High-level takeaways are,

We show the results first, then give details of methods. Finally a quick discussion on why small MLPs work, and a failed experiment.

experiments

setup

The final evaluation of the model is straightforward: play 10k games versus different GNUbg models. To mitigate lucky dice, we seed 5k games, and then use the same seeds with players switched for the remaining 5k games. We evaluate 'cubeless money play' - no doubling cube, but gammons and backgammons count.

GNUbg has various settings that all use the same underlying model. The 'expert' setting is the simplest, as it evaluates with no noise and no search. The weaker settings (advanced, intermediate, casual, beginner) use no search with added noise. The stronger settings (world class, supremo, grandmaster) use increasingly deep search. GNUbg's architecture involves 3 subnetworks for different position types and bearoff databases for the endgame.

We trained an MLP using self-play with Bellman backups, i.e. no databases. At inference time, we use either 0-, 1-, or 2-ply. For 1- and 2-ply, we use a search filter designed to match the GNUbg world class search filter. We give a more detailed description of the model and the training approach below.

overall performance

See Figure 1 for the main result, where we match GNUbg. The like-for-like comparison is expert@0-ply and world class@2-ply. Outperformance versus world class appears to be significant, though for expert it is not.

Mean points per game against GNUbg expert and world class, by search depth
Figure 1: Mean points per game of our MLP model vs. GNUbg for different plies (search depth). Larger ply is deeper search. Error bars are the 95% interval of each evaluation. $> 0$ mean points is better than GNUbg, $< 0$ is worse.

analysis of specific positions

We look at our MLP's value judgements in some specific positions, against an exact answer where there is one, and against GNUbg's 2-ply otherwise.

has it learned the bearoff database?

GNUbg looks up endgame moves in bearoff databases, whereas our MLP has to learn them from self-play. We run an experiment where we look at every position where both players have at most 6 checkers left, all on their home boards. Optimal play is computable in these positions, so we can calculate the error rate and the average equity lost (per decision) of our model.

search wrong move mean equity lost
0-ply 6.2% 0.0005
1-ply 4.8% 0.0003
2-ply 1.2% 0.00001
random move 64.6% 0.11

Increasing search depth improves the model's performance, as we have seen previously, but the model does make mistakes. Mean equity lost here is over all decisions, which is very small because we rarely make mistakes. The equity lost is still small when conditioned on a mistake - for example at 2-ply, the equity lost is roughly 100*0.00001 = 0.001. Equity here is $p(\text{win}) - p(\text{lose})$, since there are no gammons or backgammons. We also show 'random move' as a baseline. Overall the model is not perfect, but it is pretty accurate.

has it learned the opening moves?

We evaluate each of the 15 opening rolls at 2-ply (no move filter) with our model and GNUbg (world class). We show equities below; the models are in agreement about the best move for all dice rolls except 2-1. Our model prefers the starting move 13/11 6/5 over 24/23 13/11. The former is high risk, high reward, since it leaves a blot on the 5 point.

Roll Move Our 2-ply GNUbg 2-ply
2-1 ours: 13/11 6/5
GNUbg: 24/23 13/11
+0.005
+0.004
−0.002
+0.001
3-1 8/5 6/5 +0.166 +0.160
4-1 24/23 13/9 +0.002 −0.001
5-1 24/23 13/8 +0.007 +0.007
6-1 13/7 8/7 +0.104 +0.099
3-2 24/21 13/11 +0.005 +0.008
4-2 8/4 6/4 +0.123 +0.118
5-2 24/22 13/8 +0.005 +0.007
6-2 24/18 13/11 +0.009 +0.013
4-3 13/10 13/9 +0.010 +0.009
5-3 8/3 6/3 +0.062 +0.061
6-3 24/18 13/10 +0.004 +0.008
5-4 24/20 13/8 +0.018 +0.027
6-4 24/18 13/9 +0.009 +0.011
6-5 24/13 +0.056 +0.054

large disagreements

We sampled 50 games and found the largest disagreement between our model and GNUbg at 2-ply. We show it in Figure 2 below,

Holding position: the opponent holds our bar point; we are to play 4-2
Figure 2: The largest disagreement. We (orange) are to play 4-2, bearing off counterclockwise. Our model says to play 13/9 8/6 leaving a blot on the 9 point, while GNUbg suggests the safer play of 13/11 5/1.

We show the equities of the two moves and the two models below,

Move Our 2-ply GNUbg 2-ply
13/9 8/6 (ours) +0.262 +0.140
13/11 5/1 (GNUbg) +0.251 +0.255

It seems that GNUbg would consider 13/9 8/6 to be a blunder, since it loses ~0.1 equity. 13/9 seems natural: even though it leaves a blot, the opponent has blots on 21 and 22 in their home board, so if they hit us we have return shots when entering from the bar.

methods

model

The model is fairly simple - it's a resnet with 2 GLU blocks (~200k parameters). We give pseudocode below,

def features(board):
    # board: (28,) signed checker counts for 24 points, 2 bar, 2 off
    #               +ve means 'side to move', -ve is the opponent
    # each slot's count n is embedded as 
    #              -> [n>=1, n>=2, n>=3, max(n-3,0)/4]
    # concatenated, this gives 2+28*8=226 features
    # plus each side's pip count / 100          -> (2,)
    x = cat([units(board), pips(board) / 100])  # (226,)
    return x


class GLUBlock:
    # residual silu GLU block
    def forward(self, x):
        norm_x = self.rms_norm(x)                 # (,128)
        gate = self.gate(norm_x)                  # (,256)
        up = self.up(norm_x)                      # (,256)
        return x + self.down(F.silu(gate) * up)   # (,128)


class ValueModel:
    # value of a board state: distribution over 6 outcomes
    # (win/lose \times single/gammon/backgammon)
    def forward(self, board):
        x = self.inputs(features(board))          # (,226) -> (,128)
        x = self.block1(x)                        # (,128)
        x = self.block2(x)                        # (,128)
        return self.head(self.rms_norm(x)).softmax(-1)   # (,6)

training approach

We trained on 20M greedy self-play games using exact Bellman backups with soft target updates [3]. We explain the rationale behind these pieces.

exact Bellman backups

We first give an explanation of exact Bellman backups.

We model a game of backgammon as a sequence of states $\{s_t\}_t$. We make a move that gives state $s_t$, then the opponent rolls dice, and makes their move to give $s_{t+1}$, and so on.

We model $V(s_t)$, our expected score at the end of the game from a current position $s_t$. Recall the Bellman equation with no discounting, $$ \begin{align}\label{eq:bellman} V(s_t) = \mathbb{E}[R_{t+1} +V(s_{t+1})]. \end{align} $$ We use the RHS of Eq. \eqref{eq:bellman} to train our model of $V$. We assume no rewards ($R_{t+1} = 0$) except when the game ends.

How do we actually calculate the RHS of the Bellman equation? The simplest case is when $s_t$ corresponds to the end of the game - we have $V(s_t) = \text{score}(s_t)$ where $\text{score}(s_t)=\pm 1,\,\pm2,\,\text{or }\pm3$ depending on the outcome.

When not at game end, we have, $$ V(s_t) = \mathbb{E}_{s_{t+1}\, \sim\, p(s_{t+1}\,\mid\, s_{t})}[V(s_{t+1})]. $$ We have to look at $p(s_{t+1}\mid s_t)$ to make any progress. We first condition on each of the possible dice rolls $r$, $$ p(s_{t+1}\mid s_t) = \sum_{r} p(r) p(s_{t+1}\mid s_t,\,r). $$ This nicely partitions the next state into randomness from the dice and a decision for the opponent to make based on the roll $r$. We make a decision to train with greedy self-play which simplifies $p(s_{t+1} \mid s_t,\,r)$. With greedy self-play, the opponent chooses the move which minimizes the value $V(s_{t+1})$. Therefore, $$ p(s_{t+1}\mid s_t,\,r) = \delta(s_{t+1} - s^\star_{r,t}), $$ where $s^\star_{r,t} = \operatorname{argmin}_{s} V(s)$, with the argmin taken over possible moves for the opponent after roll $r$ from state $s_t$.

Therefore the RHS of the Bellman equation becomes, $$ \begin{align}\label{eq:bellman_simple} \mathbb{E}_{s_{t+1}\, \sim\, p(s_{t+1}\,\mid\, s_{t})}[V(s_{t+1})] = \sum_r p(r) V(s^\star_{r,t}). \end{align} $$ This is computable with roughly 400 calls to $V(\cdot)$ since there are 21 possible dice rolls, and there are around 20 moves to consider when evaluating $s_{r,t}^\star$.

Eq. \eqref{eq:bellman_simple} is called an exact Bellman backup, and we use it to train $V$. 'Exact' because we compute the expectation exactly (unlike TD learning, which approximates the expectation using a single sample), and 'backup' because we propagate information from the future state $s_{t+1}$ back to state $s_t$. One could also imagine using a deeper search, $$ \mathbb{E}[V(s_{t+1})] = \mathbb{E}[R_{t+2} + V(s_{t+2})] = \cdots, $$ but this gets very expensive due to the branching factor of around 400.

algorithm

We show the full algorithm below as pseudocode - a while loop with rollouts and gradient descent. We quickly clarify some details:

θ  = init()             # used for rollouts and training
θ_ema = copy(θ)         # used only to build targets
replay = ring_buffer()  # FIFO, capacity 1,000,000 decisions
B               = 256   # batch size
nsteps          = 0     # tracks when to do GD
ngames          = 1024  # number of concurrent rollouts

gs = [Game() for _ in range(ngames)]
while True:
    # ---- ACT: one move in every game ----
    for g in gs:
        s, r     = g.board, g.dice_roll()
        moves    = legal_moves(s, r)
        afters   = afterstates(s, moves)
        logits   = f_θ(afters) # : (nstates, 6)
        ix       = argmax(softmax(logits, -1) @ c) # greedy self-play
        g.board  = afters[ix]
        score    = g.score()
        replay.add(after=afters[ix], reward=score, y=None)
        if score: # if there is a score, it implies game over
            g.restart()
        else:
            g.board = mirror(g.board)

    # ---- LEARN ----
    if len(replay) >= 20_000:
        nsteps += ngames / B # works out as
                         # 4 descent steps per 1024 decisions
    while nsteps >= 1 and len(replay) >= 20_000:
        batch = replay.sample(B)  # uniform, with replacement

        # assign targets
        for sample in batch:
            if sample.reward:
                sample.y = one_hot(sample.reward) # game end target
            else:
                # compute targets from θ_ema
                # we hide the details here, but see the appendix
                sample.y = compute_targets(θ_ema, sample.after)

        # use raw θ here
        loss   = cross_ent(f_θ(batch.after), batch.y)
        θ      = gd_step(lr, wd, grad_clip, loss, θ)
        θ_ema  = λ·θ_ema + (1-λ)·θ
        nsteps -= 1

why is a small MLP effective?

It is initially very surprising that a small, fairly shallow MLP is good enough to play backgammon well. However, we can actually interpret the environment transitions and the n-ply search as scaling the effective width and depth of the network (Figure 3)! Lots of heavy lifting is being done by the inputs from the environment - for example, the model does not need to understand the stochastic nature of the dice or even the rules of backgammon in the first place. We suspect that modelling the game engine itself and/or the search algorithm would require a bigger model.

Example 2-ply search diagram
Figure 3: Example 2-ply search diagram to illustrate increased effective width and depth of $V(\cdot)$. Given an initial state, the environment gives possible future states $s_1,\,s_2,\,s_3$ which we evaluate using $V$. The outputs $V(s_1),\,V(s_2),\,V(s_3)$ are used to decide which states to investigate (e.g. top-$k$ with $k=2$ tells us to discard $s_2$). We repeat the process another time (from the opponent's point of view), and then perform minimax to get an estimate of the value of the initial state. Effective width increases because we evaluate $V$ using several candidate states in parallel, and the effective depth increases because of the candidate states provided by the environment, and the minimax.

failed experiment: incorporating search into the model

We experimented with an architecture similar to the simple MLP, but that also incorporates some search (a 'per-roll head'). Essentially the idea is to take a board embedding $x=g(s)\in\mathbb{R}^d$, combine it with a dice roll embedding $e_r$ to get $q_r = f_r(x, e_r)$. Then we ought to have, $$V(s) = \sum_r p(r) f_r(g(s),\,e_r).$$ In some loose sense the network can learn to do some lookahead search. However it is unclear how to teach the model that $e_r$ corresponds to a specific dice roll (if we want to do this at all). Ultimately we abandon this idea and prefer the simpler model. The simpler model is (a) faster computationally, and (b) good enough at 0-ply, and is stronger at larger ply (Figure 4). We also show training curves in Figure 5, and find no obvious benefit of a per-roll head.

Mean points per game against GNUbg expert and world class, by search depth. MLP and MLP + per-roll head.
Figure 4: Mean points per game of two models vs. GNUbg for different plies (search depth). Error bars are the 95% interval of each evaluation.
Mean points per game against GNUbg over 20M self-play games, at 0-ply and 2-ply, log scale
Figure 5: Mean points per game against GNUbg during training. We show 0-ply (top, evaluated every 200k games) and 2-ply (bottom, every 1M games). Each evaluation is 1,000 games on the same 500 seeds; more games are required to reduce noise. Thin faint lines are the raw evaluations. Thick lines are a centred moving average (window of size 5).

References

[1] GNU Backgammon

[2] Snell, Charlie, et al. "Scaling LLM Test-Time Compute Optimally can be More Effective than Scaling Model Parameters" arXiv preprint arXiv:2408.03314 (2024)

[3] Lillicrap, Timothy P., et al. "Continuous control with deep reinforcement learning" arXiv preprint arXiv:1509.02971 (2015)


Appendix

Modelling technicalities

We put some technicalities below to avoid overcomplicating the main exposition. They are not important for understanding the core idea, but are useful to know for an implementation.

scalar vs. non-scalar $V$

In the exposition, we described training a scalar value function. However, we technically train on the distribution of outcomes, rather than the raw scalar score. I.e. we use a network $f_\theta$ with 6 outputs (logits), designed to model probability of single/gammon/backgammon for both players. Let $c = [1,\,2,\,3,\,-1,\,-2,\,-3]$, then $V_\theta(s) = c^\top \mathrm{softmax}(f_\theta(s))$.

This affects the targets slightly. For a position $s$ (just after White's move), with $f_\theta$ giving White's outcome probabilities, the targets become, $$ \begin{aligned} y(s) &= \begin{cases} \mathrm{e}(s) & \text{if } s \text{ is terminal},\\ \displaystyle\sum_{r} p(r)\, \mathrm{softmax}\big(f_{\theta}(s^\star_{r})\big) & \text{otherwise}, \end{cases}\\ \qquad s^\star_{r} &= \operatorname*{argmin}_{s' \in \mathcal{A}(s,\,r)} \,\,c^\top \mathrm{softmax}\big(f_{\theta}(s')\big), \end{aligned} $$ where $\mathcal{A}(s, r)$ is the set of positions Black can reach from $s$ with roll $r$, and $\mathrm{e}(s)$ is a one-hot vector representing the game outcome.

'side-to-move' representation

Rather than pass the model an extra bit to tell it whose turn it is, we always pass it candidate states $s$ from the point of view of the player choosing between them. Thus $f_\theta(s)$ gives that player's outcome probabilities.

This affects the targets yet again! Let $\operatorname{mirror}(s)$ swap the positions of the two players. The targets become, $$ \begin{aligned} y(s) &= \begin{cases} \mathrm{e}(s) & \text{if } s \text{ is terminal},\\ \displaystyle\sum_{r} p(r)\, \operatorname{flip}\big(\mathrm{softmax}(f_{\theta}(s^\star_{r}))\big) & \text{otherwise}, \end{cases}\\ \qquad s^\star_{r} &= \operatorname*{argmax}_{s' \in \mathcal{A}(\operatorname{mirror}(s),\,r)} \,\,c^\top \mathrm{softmax}\big(f_{\theta}(s')\big), \end{aligned} $$ where $\mathcal{A}(\operatorname{mirror}(s), r)$ is the set of positions the opponent can reach from $\operatorname{mirror}(s)$ with roll $r$. '$\operatorname{flip}(\cdots)$' swaps single/gammon/backgammon probabilities between the two players. This is necessary because of the mirroring - for example $f_\theta(s_r^\star)_1$ is probability of the opponent winning, so flip puts it in position 4.