In this project, I trained a transformer model to play chess at a 2545 Elo on Stockfish’s engine scale using similar techniques as LLM pretraining. Over the course of the project, I sped up training by 23x, and improved learning by 11x, for an effective 260x compared to my first baseline. Hopefully this will be useful for anyone applying Transformer models to non-standard applications, or generally trying to improve ML models!
There are two ways to write a chess AI:
These can also be combined, where a direct prediction of good moves is used to prune the search tree and avoid exploring obviously bad branches.
In the spirit of imitating LLM pretraining, I’m directly predicting which move to take (“next token”) from the board (“prompt”).
So I need to find some chess data to “pretrain” on to predict the next “token”! The most obvious source of this would be databases of human games (maybe filtered to high skilled players) and the model would learn to predict the most likely next move. I can do even better than this though - Lichess hosts a database of ~1B Stockfish evaluations on Hugging Face, and Stockfish is stronger than human grandmasters.
Each row of the dataset looks like this:
{
"fen": "2bq1rk1/pr3ppn/1p2p3/7P/2pP1B1P/2P5/PPQ2PB1/R3R1K1 w - -",
"line": "g2e4 f7f5 e4b7 c8b7 f2f3 b7f3 e1e6 d8h4 c2h2 h4g4",
"depth": 36,
"knodes": 206765,
"cp": 311,
"mate": None
}
“FEN” is a string representation of the board, “line” is the optimal series of next moves that Stockfish found (starting in this case with Bishop from g2 to e4), “depth” and “knodes” are how deeply Stockfish searched, and “cp” (centi-pawns) and “mate” are how good the found move is and whether it’s a checkmate.
I used a Jupyter notebook to slice and dice the data and try to understand its distribution and anything weird about it.
The FEN strings themselves would be a terrible input to a neural net - I needed to transform the data into a vectorized representation easy for a network.
The size of the data also presented a big challenge here: just each FEN with python-chess took hours sharded across 10 Modal workers.
Whatever data format I chose would also have to live on disk rather than in RAM. I would need to write a data using NumPy’s memmap object, which looks like a normal array, but is actually mapped onto disk and only loads chunks of it at a time into RAM!
x = np.lib.format.open_memmap("data.npy", mode="r")
x[[0, 1, 2]] # fast: contiguous on disk
x[[0, 10_000, 20_000]] # slow: distant pages
I transformed the chess board into different 2D “layers”, with each layer representing one piece type and all the locations that it exists.
There are 6 layers for white’s pieces, 6 for black’s, and also 1 to track the location of any available “en passant”. There are also a few booleans of metadata to track: castling rights on either side for both players, and whose turn it is to move.
The aim here wasn’t to have the perfect board representation, but just something that would be easy to do further transformations.
Now that I could represent chess boards as input to a network, the output layer is just 1-hot encoding of different possible moves (originally 64 x 64 x 5 = 20,480 geometrically possible moves, and later a “vocab” of the 1,968 moves that are actually legal)
Before working on the Transformer model, I wanted some simple baselines to compare against and test my training setup. The MLP was simple as can be: .flatten() the input board, layers of FFNs and ReLUs, and then an output neuron for each possible move.
However, something was wonky with the learning. I was getting these weird spikes of lower loss across all my training runs of sweeps of different numbers of layers and different numbers of hidden dimensions:
Lower loss means it’s easier for the model to predict the right answer. This made me suspicious of the training data, because almost any other problem in training would make it harder for the model to predict the answer. When I plotted the data with step as the X-axis, it became clear that this was definitely a data artifact, because the spikes were always happening on the same training step, and thus the same data batch.
After a bit more digging I discovered that one of the worker shards on Modal transforming my data had crashed, and left a big stripe of data that was always 0! Indeed quite easy to predict…
With no more obvious problems I moved on to training a CNN as my next baseline, but I soon ran into another problem:
All of the models were getting stuck at ~25% accuracy over a 10x difference in model scale! Surely this can’t be the ceiling of predicting chess moves from the board? I was again suspicious of the training data, and on a hunch discovered massive duplication in the first 100k rows:
Total samples: 100,000
Unique FENs: 13,929
Ratio: 7.18 samples per unique FEN
FENs with conflicting labels: 10,925 (78.4%)
The training data comes from Lichess’s crowdsourced Stockfish analyses. The same position appears multiple times with different “best moves”. There are two reasons for this duplication in the dataset:
cp / mate ranking how good they are
Initially I was suspicious that low search depth rows were the root cause and did some experiments filtering to only keep deep searches, but ultimately ~1/2 of rows were parts of single Stockfish runs that output multiple possible moves, and only ~1% of rows contained conflicting information from different-depth runs.
But what was the best way to combine these rows? Just throwing out all the duplicates felt wasteful - there were many cases where Stockfish did a very deep analysis and found several moves that only differed by tiny fractions of a pawn in how good they were. Instead, I decided to combine rows into “soft labels” rather than hard labels!
A particular run of Stockfish on a board might have produced 3 different rows in the dataset:
| FEN (board) | Line (next move) | CP (centi-pawn score) |
|---|---|---|
r1bq1rk1/... |
cxb6… | 68 |
r1bq1rk1/... |
h3… | 18 |
r1bq1rk1/... |
Nc3… | -11 |
Instead of treating these as 3 separate training examples, I want to combine them to be one example, and use the cp / mate columns to determine how much the model should try to predict them. First, I convert checkmates into cp scores near 10k, and then use a softmax with a temperature of 50 centipawns:
In this case, cxb6 scored much higher, so it gets most of the probability.
With the data converted into soft labels rather than conflicting hard labels I was able to push past the 25% accuracy ceiling.
A later ablation showed that the simpler approach of just throwing out all-but-the-best duplicate rows would have learned just as well as my soft labels, and I should have just done “the simple thing that works” :/
I am using a Transformer architecture, but an important difference is that my input tokens (board squares) and outputs (moves) are different from each other! In a transformer for language models, the output tokens are the same as the input tokens, and you can take the output and append it back to the input to keep going, which is called “autoregressive”.
Because my network takes in the full board as a list of exactly 64 tokens, it doesn’t make sense to “add” another token onto it. Instead, to play a game forward, an output move would transform the board, changing several input tokens (squares).
Here are some more details about my architecture:
The token embedding and position embedding are just lookup tables that map a particular piece or position index to a n_embed dimensional vector which is learned over time by the network.
self.token_embedding = nn.Embedding(N_PIECES, config.n_embed)
self.position_embedding = nn.Embedding(N_SQUARES, config.n_embed)
tok_emb = self.token_embedding(toks)
pos_emb = self.position_embedding(torch.arange(N_SQUARES))
x = tok_emb + pos_emb
Here toks is the actual array of piece types (including “empty”s), just like an LLM would input a string of token IDs.
(Not pictured here: I also learn an embedding from the board metadata, like castling rights, whose turn it is, and add that to the token as well)
The position embeddings are initialized randomly and independently - there’s nothing at the start that tells the model that squares E3 and E4 are right next to each other. It will need to learn that from the data. After training, we can then look at different vector “directions” in the embeddings to look for things that might be human-interpretable!
This animation takes all the squares of a chess board and plots them with 2 particular vector directions as the X,Y axes. The position embeddings themselves are 512 dimensional, so there’s huge number of different ways to project them. The Y axis vector direction chosen here corresponds very closely with up/down on the chessboard! It’s not exact though - if you look at the top two rows of the chess board they actually map to the same Y values, and the top row is shifted over in the X direction!
Along the X axis vector direction chosen here, the model has learned something like “center vs edge” of the board! The A4 and H4 squares on the board map very closely to each other along these chosen X,Y coordinates. The particular X and Y vector directions here were found using non-metric Multidimensional Scaling (MDS), which is visualization technique similar to principle component analysis.
The tokens are embedded into this set of 64 n_embed dimensional vectors representing the board, which is called the Residual Stream. The stream hits successive Transformer Blocks, each of which adds the results of its computation back to the residual stream.
Each layer adds to the data, rather than fully replacing it. Without these direct connections that can “skip” over each block, gradients would have to flow through every single part of the network, often causing them to vanish to zero or explode to infinity. Residual Streams makes deep models much more stable and efficient to train.
Each layer iteratively refines the answer, rather than fully transforming it. That means we can use the same output head to look at answers part way through the network.
This image shows the output head decoding the most likely moves after each layer of the network, and how it changes and narrows in on the final selected move: Nxh3.
Each block is composed of a MultiHeadedAttention block, and then a Feed Forward Network block. Attention lets each token “attend” to other tokens on the board and share information between them. The FFN then separately does computation on each token’s data.
q, k, v = self.Q(x), self.K(x), self.V(x)
out = F.scaled_dot_product_attention(q, k, v, is_causal=False)
There are lots of resources out there explaining exactly how attention works, (my favorite is Andrej Karpathy’s youtube tutorial), so I won’t repeat it here, but I will point out two things:
is_causal=False meaning that scaled_dot_product_attention is significantly faster than writing your own out directly in matmuls, because it dispatches to specialized GPU kernels that are faster than directly doing the matmuls one at a time (FlashAttention).
I use multi-headed attention which is standard and just means I run the above code N times and each head is 1/N the size, and the heads are concatted together. This helps the distinct heads attend to many different things at once, rather than being forced to be single minded.
Traditionally, the total size of attention is the same as your n_embed, and split over 8 heads. After training, we can see that many of the attention heads learned patterns that quite strongly look like chess moves!
Each square here shows average Attention activations from a square to all relative positions around it.
The FFNs are very simple:
hidden_dim = 4 * n_embed
self.net = nn.Sequential(
nn.Linear(n_embed, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, n_embed),
)
Traditionally, the hidden layer is 4x larger than the input. GELUs are basically ReLUs but a softer knee rather than a hard cutoff at zero, and have largely replaced ReLUs. The last layer must go back to the same size as the input layer n_embed so that it’s compatible with the residual stream.
So my chessboard was embedded into tokens, which have flown through the residual stream of Transformer blocks. By the end of the network we have 64 vectors of n_embed size each and need to pick a move. How should we output a move?
The most naive solution is to simply flatten all the final tokens together, and have a big matmul map its output logits for each move. This would be a Linear(64 * n_embed, 1968) which is actually a really big matrix! On my smaller test CNNs with n_embed=128, this was 80% of the params of the entire model!
Time to get creative and brainstorm some architectures to save parameters while keeping high performance! I came up with 6 possible output head architectures and tested them all to pick the best:
Head Mechanisms:
flatten: [baseline] Global linear layer, each output logit sees all 64 squares’ featuresreduce: Same as above, but make the final layer squeeze down to a smaller dimension size first.spatial_shared: I have a network that looks at just a single token, and predicts an output logit for each possible “to” square (64 locations + promo options) from that space. This network is run in parallel on ALL possible “from” squares.spatial_unshared: Same as above, but each “from” square has a separate network with separate weights, rather than forcing them to all use the same set of weights.bilinear: The idea here was to match a “from” with a “to” square. Each square token outputs a “from” vector and a “to” vector, and the chosen move is the to/from combination with the highest dot product. This was slightly inspired by the K * Q mechanism in attentionfactored: Separately pick a “from” square and a “to” square with two separate linear layers that just output 64 neurons each, instead of a giant 1968.
And then I ran a set of 2-hour training runs comparing each of them:
| Head Type | Mechanism | Head Params | Eval Score |
|---|---|---|---|
| flatten | Linear(n_embed * 64, Moves) |
16.1M | 44.49% |
| reduce | Conv1×1(n_embed → 32) → Linear(32 * 64, Moves) |
4.0M | 44.85% |
| spatial_shared | Conv1×1(n_embed → 68) + gather |
17K | 42.38% |
| spatial_unshared | per-square (64, n_embed, 68) einsum + gather |
570K | 44.55% |
| bilinear | two Conv1×1(n_embed → 64) , dot product |
25K | 43.15% |
| factored | two Linear(n_embed * 64, 64) , score=f[from]+g[to] |
1.1M | 41.34% |
The winning architecture was spatial_unshared, because it tied for best performance, with 28x fewer parameters than the baseline.
In hindsight, saving a few million params might not have mattered much at all once I scaled up to bigger networks, and maybe I would have been fine staying with the naive flatten 🤷.
One of the takeaways from the Bitter Lesson is that your cleverness matters less than just how much data and compute you can pour on the problem. The less cynical version of this is that you should be directing all your cleverness not on the problem itself, but on getting as much data and compute as you can! People often think about performance tuning as squeezing an extra 10 or 20% of speed out of something, but that’s not true at all. Your first implementation of anything can probably be sped up by 10x or 100x.
From my first CNN baseline to my final hero run, I sped up training throughput by 23x.
I was using Modal for my experiments: it easily let me launch sweeps of different configurations in parallel, rather than running one at a time on my own GPU. I highly recommend Modal for cheap ML experiments. Claude knows how to use it perfectly, so you don’t even need to learn anything new.
However, the downside of Modal is noise and variability between different machines. I ran exactly the same training setup 4 times and saw a max of 27% difference in training speed. When looking for 10% speedups from architecture changes, this drowns out any signal, and was the bane of many of my experiments!
These were all Modal machines with the same GPU, but sometimes I would notice different host CPU/RAM configurations. I think most of the variability ended up coming from accessing disk over network.
Ultimately my solution here (which I sadly came up with late in the project) was to first launch a “speed probe”, which would run each arm of my experiment on the same machine for 5 min, one after the other, and record the speed they achieved. Then, I would launch each arm of the full experiment on different machines (so they could run in parallel), and normalize the results with the speed probe.
Here are some highlights from my experiments:
The first speedup I worked on was data . My first naive version of the code looked like this, and timing it found that almost 1/2 of the time was being spent on just the next batch of data, not on training!
X = load_next_batch()
Y = model(X)
The fix was straightforward (or so I thought…): prefetch data in a separate thread, so the CPU can do it in parallel while the GPU is running the model. This worked on paper - the time I measured for X = load_next_batch() went to zero, and I got a 1.3x speedup.
However, another problem lurked that I embarrassingly did not realize until much later… quite bad GPU utilization! Instead of staying nice and busy, the green GPU bar is filled with idle time during the model’s forward/backward passes.
It looked like kernel launch overhead, but because I was still paranoid of data , I launched some experiments to isolate the root cause:
1.5x slower`` 1.9x slower
This showed that just running the thread at all, even with no data dependence on it was slowing down training! The problem looked like GIL contention. I moved the data into a separate Process rather than a separate thread, and got a 1.45x speedup!
I learned later (Thanks Fable 5.2) we can get nearly the same speedup by just not logging loss.item() each step, because that’s what forces a GPU <-> CPU synchronization! Without this, the CPU actually starts working on batch N+1 while batch N is still being run on the GPU without any explicit threading.
As excited as I was to get a nearly 2x speedup from this work, when I later scaled up to a larger model this all just became a 1.25x multiplier because of Amdahl’s law. My final model had roughly 8x the GPU load, and 1/2 the batch size, so the data overhead became less important :/
Anyway, I learned how to do GPU profiling, about GPU <-> CPU synchronization, and got a good reminder that premature optimization is the root of all evil. On to other speedups…
BF16 is a floating point format that keeps the same total range (~1e-38 to ~3e38) as FP32 but uses only 16 bits by sacrificing more precision than FP16 does. It is more than 2x faster than FP32 on modern GPUs.
Some parts of the network need more precision than BF16 provides, so we have to do “Mixed Precision”, where the master weights, optimizer state, and some sensitive ops are in FP32, but all the big matmuls are in BF16.
PyTorch has a function autocast which handles all this for us, rather than needing to go manually change datatypes everywhere!
def autocast():
return torch.autocast(device.type, dtype=torch.bfloat16)
with autocast():
logits = model(X)
loss = F.cross_entropy(logits, target)
The autocast context will automatically downcast the correct FP32 weight matrix multiplies into BF16 so they are faster and take less memory bandwidth.
This is literally a 1-liner that makes the AdamW optimizer faster, by launching a fused kernel instead of calculating the updates with several separate operations!
optimizer = torch.optim.AdamW(..., fused=True)
For most of the project I had been using A10Gs on Modal for $1.10/hr to keep experiments cheap, and because I figured extra capacity of a stronger GPU would be wasted on my small models. After being frustrated at waiting for experiments to run, I figured it was worth spending a bit more money to get more iterations in. I did a quick benchmark, and was surprised to find that the more expensive H100 for $3.95/hr was cost neutral, and for bigger models would actually save me money!
The H100 can train about 3.5x faster for my model size or 5.3x faster for the next size up which I ended up switching to. It’s cheaper for the same amount of training! (Also much nicer to only have to wait 1 hour rather than 5 hours).
In addition to speeding up the compute itself, I did a lot of architecture and learning experiments. We can compare these to compute improvements by asking “how much longer would we have had to train to get the same increase in score”.
Over the course of the project, I sped up compute by 23x, and improved learning by 11x, for an effective 260x compared to my first baseline. Here are some highlights:
Originally, the network would predict the next move in a global coordinate frame - meaning it would need to learn that black’s pawns move down the board, and white’s move up the board. My fix was to mirror the board vertically, so the model always sees the board from “the player’s” perspective of pieces moving forward. This also means that the King is always on the right for the model.
This was the most non-bitter-lesson-pilled thing I did - directly encoding some of my intuitions about chess into the network, but quite effective in making it easier to learn! I also included an input neuron showing the model whether it was playing as white or black, so the information wasn’t totally lost.
Matmul weights (but not biases, norms, etc) are slowly decayed back towards zero unless a gradient is actively pushing them back up. This is basically L2 regularization. Regularization normally slows down learning on the training set, but is a net win because it prevents overfitting.
But on large models, people noticed that weight decay improved learning against the training set, in addition to helping with overfitting! This is strange! Somehow telling the optimization process to balance two different competing objectives (lower loss and smaller weights), made it better at lowering the loss than only focusing on lowering the loss!
This is not yet fully understood, but the leading explanation is that without weight decay, the scale of weights keeps increasing over training, which means the same gradient update becomes smaller and smaller relative to the weights. With weight decay, the scale stays more constant, and so the same gradient updates remain effective. Weight decay is now standard in LLM training.
The optimal learning rate gets smaller during training, as the model gets closer to an optimum. You can kind of think of this as needing smaller step sizes as the optimizer is getting down into the bottom of a canyon in the loss landscape. This is often done with “Cosine Decay” where the LR gradually lowers throughout training, and is quite effective:
The only downside is that it’s hard to extrapolate or continue training on runs with cosine decay, so instead we can just use a fixed LR for most of the run, and then a “LR cooldown” for the last 10%, and this captures most of the value. I used this fixed LR + cooldown for my final hero run.
Moving from a CNN to a Transformer was my best architecture change. It’s hard to say exactly why Transformers are better, but a few intuitions:
O(N^2), so mixing your computation and your communication together into one big matmul is really expensive. Much better to have 64x matmuls, than 1 matmul where each matrix is 64x^2 larger.
I also tried out several chess-specific variants of the transformer architecture! Most of them boiled down to the idea that there is some spatial invariance in chess, and giving the model a way to encode that will speed up learning. For instance, an enemy pawn diagonally above your pawn means the same thing no matter where on the board it is, and we shouldn’t force the model to re-learn that relationship in every different spot. At the same time, we don’t want to go as far as a CNN where we force it to only learn spatially invariant rules!
There were 3 attention variants I tried:
Bias64: Each attention head learns a bias for every possible pair of squares (64x64) that’s added to the attention score. This is a very direct way for the network to learn “these two squares are important for each other”, instead of that needing to emerge from position embeddings, queries, and keys.
attn_logit[i,j] = (query_i · key_j) / √dim + bias[i, j]
attn_weight = softmax(attn_logit)
This is a quite tiny number of additional parameters, and PyTorch’s scaled_dot_product_attention function actually lets you pass in a matrix of bias terms instead of a mask. FlashAttention does not support bias terms, but PyTorch still uses a very fast memory efficient fused kernel, so this is still much faster than writing your own attention with matmuls.
def forward(self, x):
q, k, v = ... # (B, H, 64, d_head)
out = F.scaled_dot_product_attention(
q, k, v,
attn_mask=self.pos_bias.unsqueeze(0), # broadcast over batch
is_causal=False,
)
This is from Lc0, an open source RL chess engine.
Relative Position Attention (RPA): Instead of learning a bias per pair of absolute squares, we want to learn something for each relative position, i.e. “up 2, right 1”. This will let the network directly learn “moves” in a spatially invariant way! RPA goes one step further and learns something that depends on both the relative position, and the piece asking the query, so a square with a knight can ask to attend to all the squares a knight’s move away.
In normal attention, each token produces a query, key, and value. We take the dot product of our query and each other token’s key s to select how much of that token’s value to take in. In RPA we also learn a relative_key and relative_value which are based on the relative position!
relative_key and relative_value are shared across all attention heads in the layer. My intuition is that they are representing a more “constant” thing, that doesn’t need to be learned per head. relative_key probably encodes something where all knight moves are similar vectors, all diagonal moves are similar vectors, etc, and now a query can easily ask something like “select all tokens that are knight moves away from me”.
relative_value adds information to the final output of attention, and probably encodes something like “that thing you noticed is up and to the right”.
While RPA can capture more information, it also required hand-writing my own attention, instead of using scaled_dot_product_attention, which made it run slower. It also had stability problems where sometimes during training gradients would explode, and I had to add a QK norm which further slowed down training.
This is from the paper Chessformer.
Smolgen: Smolgen computes an attention bias for each pair of squares, but does it live with a little extra network that reads the entire board, instead of learning a fixed bias map, like Bias64 above. An example of what’s possible:
Here’s an explainer of how the bias network works:
An interesting part here is that the final matrix that converts 256dim vectors at each attention head into the final 64x64 bias terms for attention is shared across all heads and all layers. It’s pretty unusual to share things across layers like this, and my guess is because it’s a very big matrix, and so re-using it saves a lot of parameter count without hurting accuracy too much.
Comparing all of these different attention mechanisms found that Smolgen produced the best results!
At this point my network was finalized, and I was ready for the big “hero” run.
I did a final 2.5-hour scan of model size and extrapolated learning curves out to a 24 hour run, and selected 16 Layers and 512dim as my hero model. I then continued training that model in a 1-hour learning-rate scan, where 1.5e-4 was the winner, and then continued that model on for another 18 hours. Finally I did a 2 hour cosine-decay LR cooldown to reach my final model! The full lineage of training was 23.7 hours on an H100, for $94.
The model has a 2545 rating on Stockfish’s UCI_Elo scale. Over 1,500 games against Stockfish 19 at settings around that level, its score crosses 50% at UCI_Elo 2545. Here is one of its matches against Stockfish at 2570:
When playing against itself, here are its favorite openings:
Having fiddled with this project for most of a year, it’s interesting to look back with hindsight (and Fable 5.2) and measure what changes really mattered and what didn’t; where I overinvested and where I underinvested. There was very little correlation between how much time I spent on an improvement and how big a multiplier it was on the model’s learning!
python-chess library would have been sufficient. I also overcomplicated deduplicating rows into soft-labels. I thought soft labels would be the “best” solution, but Claude later did an ablation and found that just throwing out all but the highest scoring row learned just as well…N to large M, like a large embedding to a large list of possible moves. The most naive way to do this is a simple NxM matmul, but this takes an unexpectedly large number of params. The different output head variants, the re-used matrix in Smolgen, and even FFNs in transformers being per-token instead of global are all places that dealt with this problem.
I hope reading through my journey with this project will be helpful to you in your own projects!