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.
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.
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.
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.
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.
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.
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.