3D Connect 4

Reinforcement learning · C++ · PyTorch

I built a self-play reinforcement learning agent for gravity-based 4×4×4 Connect 4. There are 16 columns to play into, and a winning line can run horizontally, vertically, or diagonally through the cube. I wanted the bot to learn strong play rather than rely entirely on hand-written rules.

A physical four-by-four-by-four Connect 4 board, with pieces stacked on sixteen vertical posts.
A 4×4×4 board: pieces stack under gravity, and four in a line can win across rows, columns, layers, or spatial diagonals.

Search and self-play

I started with a heuristic opponent that took immediate wins, blocked threats, and avoided obvious traps. This provided training examples and a baseline I could play against through a CLI. I then implemented an AlphaZero-style loop: a policy/value network guides Monte Carlo tree search, self-play generates positions, and the network learns from the search policies and game outcomes.

A two-plane board input passes through a 32-channel 3D convolution and four residual blocks, then separates into a 16-action policy head and a scalar value head.
The policy/value network: four residual blocks and 229,879 trainable parameters. Two input volumes distinguish the current player’s pieces from the opponent’s.

The network’s policy gives a prior probability for each of the 16 columns. PUCT balances that prior with the outcomes of earlier simulations and an exploration bonus. When search reaches a new position, the value head estimates how favourable it is, avoiding the need to play every simulation to the end. Those estimates are backed up through the tree; the root’s visit counts give a search-improved distribution over moves.

Self-play stores the board, that visit distribution, and the eventual game outcome. Cross-entropy teaches the policy to reproduce the search distribution, while mean-squared error trains the value head against the outcome. Repeating this cycle lets better predictions improve search, and better search provide stronger training targets. The game and search run in C++ with bitboards; PyTorch trains the network.

The cost of looking ahead

Search made each training position expensive. In the initial single-threaded, unbatched benchmark, increasing the budget from 32 to 800 simulations per move reduced generation from 18.61 to 1.52 positions per second. Those measurements used a small, randomly initialized network: they measure computational cost, not playing strength.

Initial self-play generation throughput: 18.61 positions per second at 32 simulations, 12.93 at 64, 8.26 at 128, and 1.52 at 800 simulations per move.
Generation rate versus search budget in the initial single-threaded, unbatched implementation. Each data point is a game position.

A larger search budget can improve a move target, but it also reduces the number of positions available for training in a fixed amount of time. I therefore worked on both tree-level and game-level parallelism. Within a shared tree, virtual loss temporarily makes a branch being explored look less attractive, so other workers are less likely to duplicate the same work. Across games, a batched TorchScript service groups leaf evaluations into larger GPU calls. This reduces the overhead of repeatedly evaluating one small board at a time.

Data diversity and symmetry

Inspecting the empty-board policy revealed a strong preference for one corner, even though rotating or reflecting the board makes the four corners equivalent. That preference can reinforce itself: self-play repeatedly visits the same opening, and training then gives the model more evidence for the move it already favours.

I diversified the seed positions and added symmetry augmentation. Transforming a board also requires transforming its policy target, so the network sees equivalent positions with consistently remapped moves. This encourages it to learn board structure rather than an arbitrary orientation. The desired corner symmetry does not mean all 16 columns must be equally likely: corners, edges, and central columns are different kinds of positions.

Left: the original policy, with 70.76 percent on one corner. Right: an idealised illustration with 25 percent on each corner and zero on every other position.
Left: the measured opening policy, dominated by one corner. Right: an idealised example with equal probability on the four corners; it illustrates symmetry rather than a measured checkpoint.

Evaluating improvement

I compared checkpoints with their predecessors, the starting model, and depth-limited alpha-beta opponents. These tests sometimes disagreed: a checkpoint could improve against the starting model while failing the promotion threshold against its predecessor. Relative strength can be non-transitive—one policy exploits another’s habits without becoming generally stronger—so beating the previous checkpoint alone is a weak promotion criterion.

Arena score rates over eleven rounds: scores against the starting model generally rise, while scores against the previous checkpoint fluctuate around a 55 percent promotion threshold.
Arena scores against the previous checkpoint and the fixed stage-zero model. The dashed line is the 55% promotion threshold; the different trajectories show how the choice of opponent changes the apparent progress.

I also built a DAG-based oracle solver. Different move sequences can reach the same board, so representing positions as a directed acyclic graph allows those transpositions to share cached evaluations. On solved positions, the solver can check whether a chosen move preserves the best achievable outcome. This provides a more direct decision-quality signal than an arena score, although solving positions near the opening remains expensive.

Faster self-play and an endgame curriculum

Actor-critic self-play offers a different trade-off from using MCTS as the teacher. Moves are sampled directly from the policy, so each game can be generated without a search at every turn. The policy update depends on the advantage: the observed return minus the value network’s prediction. Actions that lead to better-than-expected outcomes become more likely, while the value head learns to predict those returns. The targets are cheaper to generate, but less informed than a search-improved move distribution.

An endgame-first curriculum addresses the difficulty of learning from a reward that may be many moves away. Near-terminal positions have short tactical consequences and are more tractable for the oracle to label. Training can begin with these positions, then move progressively toward earlier stages of the game. A competence gate makes advancement depend on performance at the current difficulty instead of a fixed training schedule.

Search can also be used selectively as an opponent rather than to label every learner move. A search-guided opponent exposes mistakes that a similarly weak self-play partner may overlook. Discounting rewards by game length gives another useful signal: a positive reward received sooner is worth more, while a delayed negative reward is less severe. These choices change both the experience the agent receives and which outcomes its objective prefers.

Schematic comparison of search-guided training, direct self-play, and an endgame-first curriculum. These are illustrative curves, not measured training runs.
Illustrative comparison of the training approaches, not measured learning curves. The curriculum combines cheaper experience generation with progressively harder starting positions; the plotted values are schematic.

The central trade-off is between the quality of each training target, the amount of experience that can be generated, and the reliability of the evaluation. A faster generator is only useful if it produces varied, informative games; a stronger search is only useful if its extra cost improves learning enough to justify it.

Additional result: tactical pretraining

The supervised starting model achieved 93.7% top-1 target accuracy on 100,000 held-out tactical positions. Immediate-win and immediate-block accuracy exceeded 98%, while agreement with depth-three minimax targets was 69.6%. This measures agreement with curriculum labels, not match win rate.

Validation and held-out test accuracy for seven tactical curriculum categories, ranging from 69.6 to 98.9 percent on the test set.
Recorded curriculum evaluation before the subsequent self-play rounds.

← All projects