Generals.io Bot Competition

September 2026


For the last few weeks of August, I had the pleasure of participating in the generals.bot competition. I came across the competition after seeing a tweet by Agustin Lebron. I’ve played generals.io on and off for almost 10 years, and I’ve always been interested in building an RL bot for it but never had the time to make it a priority. This competition was the perfect excuse!

It ended up being a bit of a sprint, with a few focused weekends and some experiments ticking along midweek. In the end, I (Chig) made it to joint 5th place, which I’m happy with given that I joined a few weeks in. I had a lot of fun and learnt a lot, and hopefully there will be some similar competitions in the future. Thanks to the organiser, Matej.

This post is a little write-up of my approach and thoughts on the competition.

Behaviour Cloning

I’d come across Matej’s post about his RL bot, AverageJoe. He trained a 15M-parameter vision transformer (ViT) for a week on 4x H200s with pure self-play. I didn’t want to wait for days just for the sake of learning from scratch, so my initial plan was to train a supervised/behaviour-cloning policy from the existing top bots to learn a decent initial representation, and bootstrap from there (a perk of joining late, I suppose).

Setting up a replay-download pipeline was more annoying than it needed to be. The competition website has a heavily rate-limited and truncated API for downloading replays. The replay format is also slightly unfriendly: instead of being the initial board state + player actions, it just contains a list of the full per-step board states, and you have to infer the actions with heuristics & probing of the game simulator. Once that was sorted, I had a few thousand action-labelled replays on disk, and could train a BC agent.

First PPO Run

I then set up a basic PPO self-play scaffold. I took plenty of ideas from the AverageJoe paper (which in turn took plenty of ideas from the Sokota Stratego paper): top-25% advantage selection for sample efficiency, most of the hyperparameters, and Matej’s JAX game env. The general structure was: roll out a few thousand games in parallel for a few hundred steps as one fused, unrolled JAX function, compute advantages, compact, then run one PPO epoch in minibatches on those observations.

My initial model architecture was a ~10M-parameter ResNet operating on the full-resolution 21x21 board, with a minimal set of feature input channels, similar to AverageJoe’s (army counts, general/castle/mountain indicators, enemy last seen maps, a short 16-turn history of board moves, etc.). The final 21x21x9 action logits (4 full moves, 4 half moves, castle build) were flattened and softmaxed. It also had a small downsampling 1D-CNN ‘temporal’ network, operating on the last few hundred steps of land and army time series. The output of the temporal network, and an embedding of various scalar features (turn counters, etc.), were broadcast and added after the first conv layer. This architecture and size were a pretty arbitrary starting point – ResNets train quickly and stably, and model inference measured around 90ms on a server CPU, which felt safe relative to the 150ms per-step budget.

Getting PPO off the ground was a little fiddly: self-play of the initial BC model was resulting entirely in draws: not enough exploration to produce a win on a full board within the 1200-step limit. To get around this problem, the AverageJoe paper used a training curriculum to gradually grow the board size / inter-general distance. Instead, I eventually managed to break the symmetry by playing the BC model against a random opponent. This resulted in some wins, and PPO started to make progress on its own at full map scale. I kept a reverse-KL anchor loss to the BC policy, which seemed to help avoid policy collapse and encourage exploration, as well as a small raw entropy bonus (which I don’t think ever did much).

I also had some auxiliary losses/targets that were kept on through most of training:

  • enemy general location
  • hidden ownership
  • hidden army (one-hot size buckets)
  • threats to our general (scalar predictions: can the enemy reach our general in 1/2/4/8 turns + the strength margin)
  • next enemy contact position within X steps
  • next enemy action (whether visible or hidden)
  • future enemy movement: predict enemy move destinations over the next 4/8 steps

Overall loss/gradient contributions varied over time. Towards the end of training, the gradient norms relative to the PPO gradient norm were: ~10% for auxiliary loss, ~10% for value, <1% for the BC anchor and entropy.

For the the first half of training, the opponent mixture was pretty manual to avoid having too many moving parts – no automatic league system. Each training iteration mixed 50% live self-play (with experience gathered from both seats), 25% play against a moving lagged policy, and 25% play against a fixed pool of past models & checkpoints that I changed & re-weighted as they became saturated. Early on, the fixed opponents also included a few heuristic agents from Matej’s repo. Eventually I added a simple dynamic pool weighter that down-weighted past checkpoints as they became easy.

After about 250M env steps, the policy was behaving pretty sensibly, and consistently beating the heuristic bots. I uploaded it, and it ranked somewhere between 30th and 40th.

Features V2

At this point, a very long PPO run didn’t feel like a good return on investment. I wanted to get to a quicker feedback cycle, and avoid spending GPU-hours/days learning a basic board representation, so I added a lot of hand-crafted input features. I also wanted some stronger temporal structure/memory in the features: I was trying to avoid, at this stage, having a learnt temporal component in the policy – I thought it would slow down training and be another thing to debug.

I fleshed out the feature set significantly, going from about 30 to 200 input channels. Some examples:

  • routing features: shortest-path distance field + one-hot ‘in the direction’ fields to: own general, enemy general if known, nearest friendly/enemy castles, troop frontier, centre & corners of the board
  • much more fleshed-out memory & movement features: tracking of last-seen enemy state, various EMAs of enemy presence, mass, movement direction, cell inflows/outflows
  • logarithmic one-hot encodings of army magnitudes instead of continuous values — e.g. ==1, >=2, >=4, … >=128
  • visible fraction of total mobile (army minus land) enemy army at a cell
  • friendly & enemy cell reachability fields within 1, 2, 4, 8 … turns, as well as strength margins, etc (most of these implemented as multi-round stencil/convolution flood-fills).
  • exact castle construction costs (a 13x13 convolution implementing this rule)

I also added more scalar input features:

  • game-rule clocks: turn modulo 50 (the ‘army growth’ clock), turns until deathtouch (800), turns until draw (1200), etc
  • simple rolling features of own & opponent army & land counts: EMAs over various windows, production rates, army/land ratio, mobile army count, own vs enemy ratios, visible/total ratios
  • fog accounting: visible vs hidden enemy land, visible mobile army, unaccounted-for mobile army

Around this point I also realised that you can immediately see enemy castles in the fog, by diffing the “structure in fog” input map. Because there are no neutral castles, any structure at the start of the game is a mountain, and any unknown structure added subsequently is an enemy castle. These became clean feature channels.

I retrained a similar model with these new features, and it got a good uplift offline. When I went to deploy it, though, it didn’t pass qualification because it received too many timing faults (i.e. it exceeded the 150ms turn budget). This was surprising because on a cloud CPU I had, the features only added a few milliseconds of overhead.

Timing Probes & Tuning

I wanted to understand more about why my model was faulting, and why there was a big gap between my offline measurements and the competition setup. I’d seen from the Discord that the competition was being run on Modal, so I set up a Modal account and ran some benchmarks. Across 72 jobs I saw about 8 different CPU families, spanning 3 generations of AMD & Intel, some with AVX512 support, some without, etc. Inference performance varied by a factor of 2-3, and was noisy within a run because of noisy VM neighbours. Even if your submission made it past the submission gate, it could later fault during gameplay if a match ran on a bad CPU.

The competition also didn’t give any information about your submission’s timing. There was no fault counter, per-step fault indicator or timer.

To test out architectures before training them, I built a ‘timing probe’ wrapper that would run the model step, then return a legal, non-pass move from a cheap heuristic strategy (this was so I could submit an untrained model and still pass the submission gate of not losing to the heuristic bots…). If I then scraped my replays, I’d know that any apparent ‘pass’ move in the replay was actually due to a timing fault, and from this I could get a proper rate across many games.

Architectural Shakeup

Following this, I decided to make the model a bit more efficient, and get towards a more final competitive architecture. I took some inspiration from the successful AverageJoe model, and added a low-resolution 7x7 trunk, but I kept a few full-resolution 21x21 ResNet blocks at the base because I suspected that these would build a better early-stage representation than a simple linear patch embedding. After the 7x7 trunk, low-resolution embeddings were broadcast back to their 3x3 neighbourhood, added to the high-resolution embeddings, and passed to the action head.

For the low-resolution trunk, I raced a ResNet against a 49-token ViT for a while. Eventually the ViT pulled ahead on skill (which seemed reasonable), and was also slightly faster at inference time.

The rough architecture at this point was:

  • 1x1 convolution from ~200 input channels to 64, added to learnt 8x21 row & column embeddings
  • four d=160 3x3 ResNet blocks
  • 3x3 stride-3 downsample
  • six d=288 transformer blocks on the 49 patch tokens + 1 global token. The transformer had learnt absolute position embeddings, and a learnt relative-position attention bias (13x13 matrix of every pair-relative position). Otherwise pretty vanilla: LayerNorm, SiLU, 2x expansion factor
  • full-resolution action projection on the sum of: the high-resolution embedding at that cell, the local low-resolution embedding, and the broadcast ‘global’ token
  • the value head was a projection of the global token

This totalled about 7M parameters (half the size of AverageJoe). This model performed significantly better than the previous iteration over the same compute budget (about 600M env steps), and wasn’t showing obvious signs of plateauing.

Further Timing Problems

At this point I was still rank 25-30, and I was losing a lot of very odd games where my model would appear to lag out a lot:

The number of passes well exceeded the 50-fault forfeit budget, so timing faults alone couldn’t explain it.

I built a proper reconciliation tool that could download a replay, run the policy locally on that replay’s states, and compare the offline ‘intended’ action with the action the live policy took. This was very useful, and I should have built it earlier. It immediately found a bug in how I was padding the maps in live vs training, leading to small policy divergences.

It also allowed me to analyse the odd laggy replays. After a lot of head-scratching, I figured out that the model was often falling behind by a fixed number of steps: for example, it was emitting the correct action for turn t, but at turn t + 16. Because most lagged moves are no longer legal/valid, the runner would reject them and it would look like a pass. Sometimes this would happen from the start of the match, and sometimes halfway through. For example:

Replay 278429: recovered online actions align with local policy actions shifted by 16 turns

It seems like the runner harness uses a continuous 150ms deadline rather than a clean ‘step both players and wait’. If you miss the deadline, the runner gives you a pass, and pushes a new observation to your stdin. When you eventually emit the stdout action for the original step, it attributes that action to the next turn, and tries to apply it. Even if my model was fast on most turns, it wouldn’t get back in sync after a startup lag or a mid-game blip.

The fix was simple: after startup and every step, fully drain stdin and advance the state cheaply, then loop back to a blocking read. This ensures that you’re always ‘phase-locked’ with the runner, and a single blip is isolated to a few turns.

With this and the padding bugs fixed, the same policy jumped up to rank ~20.

Further Model Speedups & Improvements

The reconciliation tool allowed me to measure fault rates on the real policy (I could now distinguish a probable policy-intended pass from a timing-fault pass), and it was still faulting a lot. I needed to speed things up further.

Features V3

I ran a simple permutation-style feature importance test: I swapped out channels of feature groups with the same channels from other states, and measured KL between the policy action distributions. This gave me a crude sense of feature importance, and allowed me to cull a few expensive groups that seemed to be doing nothing.

I also added a few more, motivated by weak spots I’d seen in replays:

  • enemy-under-fog modelling: feasible enemy territory, feasible general location (based on e.g. the 17-step minimum general-to-general distance + reasoning about enemy land bounds when you first see them), crude tracking of enemy counts in regions (again, GPU flood-fills)
  • ‘old wood’ features: the enemy’s oldest terrain cells will often be high-numbered and equal in number, if they haven’t been swept in a while. I was concerned the model would find exact-equality hard to express, so I added a few features tracking neighbour-equality counts, etc.
  • what the enemy knows about us: for basically every feature I was computing about the enemy (seen terrain, movement & presence EMAs, last-seen cell states, etc.), I added in the opposite enemy-perspective view about us, so the policy could more easily learn to disguise its movements or model enemy reactions
  • more static terrain topology features: graph articulation/cut importance, average detour lengths if a cell was blocked, local space at several radii

I also had a coding agent whip up a replay / feature / policy viewer, which was helpful when debugging features and the model:

Terrain Encoder

One realisation I had was: the map is static for the entire game, and the inference budget for the first turn is longer than normal (10 seconds, for importing stuff, JITing, etc.). I decided to factor out a ‘static terrain encoder’ part of my model that would run once on the map structure (mountains + my general) at the start of a game/rollout, and produce a per-cell embedding for the per-step model. I could potentially make this model quite big and expressive.

PPO updates are a bit more tricky to amortise: because the model is changing, the terrain encoder needs to re-run for each map in each minibatch. Initially my minibatches were shuffled randomly across the full multi-env rollout (e.g. run 2048 parallel envs/maps for 128 steps, then optimise in batches of 1024 observations), which wasn’t very efficient. I restructured the minibatches to be map-grouped: so a minibatch would e.g. contain 128 observations from each of 8 maps, and I could run the terrain encoder once per map in the minibatch, and amortise a bit more. The extra correlation inside each batch didn’t seem to cause a problem.

The terrain encoder itself ended up being a bit smaller and simpler than it could have been – it was just a small CNN. I ran out of time to develop it further, but I had a few ideas for more expressive mountain/graph-aware models.

Sparse Action Head

The initial model produced a logit for each possible action on the board (21 x 21 x 9 = 3969), plus one global pass logit. On a given board, most actions aren’t legal, and only a small subset of the legal actions are interesting.

I wanted to exploit this structure to make the model cheaper and concentrate more computation on the interesting actions. I changed it to only consider a deterministic, heuristically selected set of actions, and score those actions with a much larger, multi-layered action head.

The candidate actions were proposed at the cell level – so all actions at those cells would be considered. Up to K=48 sources were selected, based on ranking cells across some simple heuristic groups such as:

  • largest armies
  • cells that would win immediate combat
  • armies near own general or castles
  • armies near enemy, enemy general or castles
  • gathers: movable cells on the edge of my territory
  • sources on or near recent enemy presence

On a dataset of expert games, these heuristics had 99.5%+ support. These candidates could potentially have been learnt instead, but the non-smooth support would need some tweaks to work with training & PPO.

For each cell I constructed 9 rows, so 432 total rows + a pass row. Each row was a concatenation of the source cell embedding, the action target cell embedding (i.e. the cell in the move direction, or zero for build), and a few exact tactical features (army sent, army remaining, ownership change, visibility to enemy, etc.). These were all passed through a 3-layer MLP, producing final logits.

With all of these improvements, the model was meeting the timing budget and was much stronger. After training for 1-2B environment steps, it was ranked in 10th place.

Castles & Half-Moves

I spent a while watching replays to try and understand the bot’s weaknesses, while I continued to train it. The main obvious gap compared to top opponents was that it was never building castles, and never using half-moves. Castles are a key strategic part of the game, but take a long time to pay off, so they are hard to discover. Half-moves are also important: they allow you to split an army in two, and leave one stack behind to defend, for example.

Here’s a replay from that era, where I get overwhelmed by a castle-building opponent:

I first tried some reward shaping to encourage these moves, but I couldn’t get it right: it would either not be enough, or would warp the policy too much.

In the end, an approach that worked was to temporarily add a strong forward-KL anchor to a new, better BC expert policy (which often assigned non-zero mass to castles & half-moves), for about 1000 updates, then linearly taper it out over another 1000 updates. This forced some natural castle building & half-moves at sensible positions, without breaking the policy, and the behaviour was retained after that.

I don’t have a control branch for the full length of this intervention, but within 50 steps castle builds had gone from 0 -> 0.4 per game, and in a zero-coefficient control branch after that, castle builds reverted to ~0 after 25 steps. Here’s the rate over time, where we see it first discover building, then learn to gather bigger troop stacks so it has more build opportunities:

Castle build rates during training

This was what the much-improved policy looked like – offensive castle building:

This improvement helped me jump up to ~7th place.

Temporal Belief

My bot had another obvious weakness: it would forget the presence of known enemy troops hidden behind the fog, leading to blunders like this:

This wasn’t that surprising given the temporal features were mostly finite-horizon and somewhat crude.

I tried to build a separate, recurrent ‘temporal belief’ network that would focus on predicting the hidden state behind the fog. For sample efficiency, I trained this with supervised learning (on replays) to predict the unknown state from both seats.

The targets and losses were a blend of:

  • enemy ownership (binary per-cell cross-entropy)
  • enemy army bucket (8-way per-cell cross-entropy 2/4/8/16/32/64/128)
  • enemy general position (cross-cell cross-entropy)
  • conservation (sum of predicted mass near true total)
  • strongest-stack mass (Huber loss on that one cell)
  • strongest-stack location
  • strongest threatening stack location (largest within X distance of general)

I played around with losses that decomposed mass from location a bit more (so: you know there is a stack of X within this region but are unsure exactly where), to avoid predictions becoming too diffuse, but couldn’t get this to be stable.

The architecture was a CNN + a per-cell GRU and a global GRU.

This model ended up no better than the mature PPO-trained models on the auxiliary targets they shared. Nonetheless, I tried integrating it, frozen, into PPO training for a while (passing in the hidden states to the main network, with zero-init adapter weights). The adapter weight parameter norms steadily grew, but when I ran an ablation that reset the previous hidden state on every step, the policy didn’t degrade, so it might have just been using it as extra width for current-step representations. I didn’t have time to pursue any more RNN/temporal stuff, though it feels clear that a proper policy-learnt temporal component would be sensible and could subsume a lot of my hand-crafted features.

Entropy Collapse

I was concerned that the BC-policy KL anchor was holding learning back, so I tried to remove it. It turns out that it was upholding most of my exploration entropy (rather than the direct entropy bonus):

Entropy dropping as KL anchor coefficient drops

Learning slowed down a lot after the entropy dropped. I tried forcing more entropy by increasing the raw entropy bonus, but the policy got worse – a raw bonus feels like quite a blunt instrument, especially in a game where some moves are big exploratory decision points but between those you have lots of precise, micro moves that need to be chained well. I reverted to some sort of expert/BC-based exploration pull throughout training (more on that below).

Learning from Experts

I spent a lot of time trying to figure out how to ‘distil’ knowledge from the replays of the top few bots. The behaviour-cloning anchor seemed to be providing ‘good’ entropy which was helping exploration, but it had a few downsides:

  • the BC policy is a distillation, through my architecture/training, of the expert moves. It’s an extra layer of indirection and might lose some stuff.
  • the KL-loss required a forward pass through the anchor model, slowing down overall training by ~20-30%

One idea I had was to generate counterfactual rollouts from surprising expert actions, and incorporate those into training / value learning. Across thousands of expert replays, I evaluated my own policy’s probability of the expert moves. From that, I generated a dataset of ‘surprising’ moves: where I assigned very low probability to the move. I subset these, spaced apart in time to avoid too many moves per game, and also included all expert builds and half-moves. This ended up being about 400k root game states + expert actions.

During the training loop, I then sampled these states, and generated 8 self-play rollouts: 4 forcing the expert move, and 4 control branches sampled from my policy. Each trajectory continued in self-play under my policy for 128 steps. I then computed group-normalised advantages for these initial actions (or the first T actions) and trained on them in a small dose, interleaved with main PPO.

This didn’t go anywhere, for the simple reason that: after running a more thorough Monte Carlo evaluation, the expert actions seemed to be no better on average, when continued by my own policy! They may have been better with the expert’s own policy finishing the game, but I couldn’t simulate that. This plot shows value/reward difference at 128 and 512 steps (+ the completed game subset, which avoids critic bias – it would have been better to run the games to completion, but this is the data I have), broken down by expert and by ‘surprise’:

Monte Carlo reward differences of expert actions

The next idea I tried was to simply replace the BC anchor by a supervised training loss on the expert game dataset, during the main PPO loop. This worked OK: it seemed to provide about the same entropy ‘support’ as the KL anchor, was not obviously better or worse for training / the policy, and was much faster. I kept this approach from then on.

Failed Ideas

During training I tried a few architectural additions, none of which proved themselves decisively against their baselines.

Tactical Transformer

I added a separate transformer trunk that had one token for each of various key ‘entity’ cells, for example:

  • my general, enemy general
  • all castles
  • large army stacks

There were also a few free queries that could do full-cell attention over the board to construct some ‘soft’ entities. My goal was to allow for transformer reasoning with cell resolution, without a full self-attention 441x441 cost. This didn’t show any uplift as a sidecar after a few thousand steps, but I have some ideas to explore it further.

Mountain-aware Convolutions

The generals.io board is presented as a 2D grid, but really it is a graph. Two cells nearby in grid-space can be dozens of steps away in passable-cell-space. I was concerned that my early CNN would end up blurring information across mountain ranges, and might struggle to learn precise measures of distance, etc.

I experimented with some ‘masked’ convolutional layers: basically a 3x3 convolution restricted to the 4 cardinal directions, followed by a mountain masking operation. This means information has to flow around mountains. You can also view this as graph message-passing: one step per layer.

When trained into a mature model, these layers didn’t show any improvement. I didn’t have time to run a serious from-scratch experiment with them.

Final Elo Curve

Just because you have to have it, here’s the final training lineage’s progress:

Final training Elo curve

Training ran for about 14B seat observations (i.e. roughly 7B self-play steps), or ~20k steps. During earlier training, an EMA of recent model weights (half-life ~200 steps) strongly outperformed the raw weights, and the EMA models were used in the opponent pool. By the end of training, the raw model was on par with the EMA. The final jump is real – I ran a rushed learning rate decay on the last day, which boosted performance a bit.

Other Write-ups

bca (joint 5th place) wrote up their approach here. They used a similar CNN + ViT architecture (but ~2x the size at 16M params), no BC (because they started before there were any experts!), and trained for about 60B observations (about 4x as long).

Kubic, in the competition Discord, said his model was about 10M parameters and trained by pure self-play for about 50B observations.

So, the bitter lesson definitely applies here too, though it seems like some combination of feature engineering, having the luxury of learning from existing replays, and possibly training methodology allowed me to get close to bca’s performance with half the model size and 1/4 the steps.

Closing Thoughts

This was a great competition.

In a potential future edition, it would be interesting to change the rules to make it less compute/bitter-lesson-oriented – for example by drastically reducing the inference budget (1ms? 5ms? less?). This might push solutions into more creative architectures, especially ones that combine heuristics/search with a learnt model, and emphasise inference performance tuning more. It would also make the competition more accessible, e.g. to students who might not want to splash hundreds of dollars on training.

The competition would also benefit from a more predictable hardware platform: for example, running all games on a particular, dedicated EC2 instance type with a known CPU model that everyone can tune for. The competition website could also make timing information more transparent, rather than everyone having to guess or reverse-engineer it.