These are my notes for
c4c,
a standalone C implementation of a Connect Four player. The model was trained
in Python with self-play guided by Monte Carlo Tree Search (MCTS), in the
spirit of AlphaGo Zero. The inference side—a residual network plus the tree
search—is a single C99 file with no external dependencies. When a
BLAS library is available, such as the Accelerate
framework on macOS, it is used automatically for a large speedup.
The network follows the AlphaGo Zero design: a shared residual tower feeding
two heads. The
PyTorch reference model
serves as the specification, and the C forward pass (see
nn_forward)
mirrors it layer by layer.
| Stage | Layers | Output |
|---|---|---|
| Input | 3 planes: black stones, white stones, side to move | (1, 3, 6, 7) |
| Stem | conv 5×5 → batchnorm → relu | (1, 128, 6, 7) |
| Tower | 5 × residual block (conv 5×5 → bn → relu → conv 5×5 → bn → add → relu) | (1, 128, 6, 7) |
| Policy head | conv 1×1 → bn → relu → linear(84, 42) → softmax | 42 probabilities |
| Value head | conv 1×1 → bn → relu → linear(84, 256) → relu → linear(256, 1) → tanh | scalar in [−1, 1] |
The policy head predicts one probability per board cell (42 = 6 × 7), even for cells that cannot be played. Since a Connect Four move is just a column, the player reads the probability at the next legal cell of each column and ignores the rest. The value head estimates the chance that the side to move wins.
Train in PyTorch, Infer in C
The weights are exported into a minimal binary format (see the
spec):
a u32 tensor count, followed by all tensor shapes, followed by the
raw f32 data back to back. Keeping shapes and data in separate
sections makes the data contiguous and mmap friendly. There is no graph in the
file; the graph lives in code. The forward pass consumes weights strictly in
order, and a final assert(weight_idx == nn->weight_cnt) is a
cheap but effective check that the C graph and the Python graph agree.
Every operator is hand written in C99 and compiled with strict flags
(-std=c99 -Wall -Werror -pedantic -Wconversion): conv2d,
batchnorm, relu, residual add, linear, softmax, and tanh. No operator fusion,
multi-threading, or SIMD has been applied. Even so, the C version runs faster
than the original Python and PyTorch-based version.
The MCTS player, however, calls the network once for each new tree node, and the profile leaves no doubt about where the time goes:
% cumulative self self total
time seconds seconds calls s/call s/call name
99.96 27.85 27.85 3081 0.01 0.01 conv2d
0.07 27.87 0.02 1185 0.00 0.02 resnet_block
0.00 27.87 0.00 453 0.00 0.00 game_winner
0.00 27.87 0.00 237 0.00 0.12 mcts_node_new
0.00 27.87 0.00 237 0.00 0.12 nn_forward
Optimization: im2col + GEMM
The
naive conv2d
loops over output channels, input channels, pixels, and the kernel window. The
BLAS version
uses the im2col trick (see
cs231n)
instead. For every output pixel, the \(k_h \times k_w\) patch of each input
channel is copied into one row of a matrix \(B\) with shape
\((h \cdot w,\ c_{in} k_h k_w)\). The kernel, viewed as a matrix \(K\) with
shape \((c_{out},\ c_{in} k_h k_w)\), then gives the whole convolution as a
single matrix product
\[
O = K B^{\top} + \hbox{bias}.
\]
The neat part is that the contracting dimension of the matmul is exactly the
sum over all input channels and the kernel window, so one call to
cblas_sgemm does all the work:
int K = (int)( kernel_h * kernel_w * c_in );
cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasTrans, (int)c_out,
(int)( h * w ), K, 1.0f,
/*A=*/weight->data, K,
/*B=*/col_matrix->data, K, 1.0f, /*C=*/out_buf,
(int)( h * w ) );
The output buffer is pre-filled with the bias, and beta = 1 adds
the product on top of it. The im2col copy costs very little next to the
matmul. On macOS, with the Accelerate framework enabled by
default, this gave a 50x–60x speedup over the naive loop. On Linux,
openblas works too (make RELEASE=1 BLAS=1). The
choice between conv2d_blas and conv2d_naive is a
single compile-time macro.
Batchnorm Folding At inference time batchnorm is a fixed affine map per channel (see code). Rewriting \[ o = \frac{i - m}{\sqrt{v + \epsilon}}\, w + b = i \cdot \underbrace{\frac{w}{\sqrt{v + \epsilon}}}_{s} + \underbrace{(b - m s)}_{t} \] moves the square root and division out of the inner loop: \(s\) and \(t\) are computed once per channel, leaving one multiply and one add per element.
The raw network alone already plays reasonably well when it greedily picks the column with the highest policy probability. Wrapping it in a tree search makes it much stronger. The search follows the AlphaGo Zero paper (2017, "Methods" section). Each tree node keeps, per column, the visit count \(n\), the total backed-up value \(w\), and the prior \(p\) from the policy head.
mcts_node_new)
and one forward pass gives both its priors and its value. There is no
random rollout: the value head is the evaluation. A simulation
only reaches the end of a game when it hits an actual win, loss, or tie.
A Practical Floor on Priors
The network sometimes assigns a probability close to zero to a move that
actually wins. Since the exploration term is proportional to the prior, such a
move would almost never be visited. The fix is a simple clamp: every legal
prior is raised to at least 0.05, which forces the search to
look at every move at least occasionally. I did not tune this number for
different simulation counts.
Strength vs Compute
The number of simulations per move, MCTS_ITER_CNT, is a
compile-time knob. With 1600, the player is strong enough that I never win,
but it requires a lot of compute; 400 is still a good opponent and much faster.
MCTS_SELF_PLAY=1 lets two MCTS players play each other.
make RELEASE=1 # play against the nn
make RELEASE=1 MCTS_ITER_CNT=400 # faster, still strong
make RELEASE=1 MCTS_ITER_CNT=1600 MCTS_SELF_PLAY=1 # nn vs nn
Without a garbage collector or RAII, every allocation is accounted for by convention, written down in the code:
/*moved_in*/, such as the game snapshot
passed to mcts_node_new, transfer ownership to the callee; the
caller must not free them afterwards.
RESET_TENSOR macro that
frees and nulls the pointer. Only the tower output lives longer, because
both the policy head and the value head read it.
As with the iterative DFS in Algorithm 7.4.1.2T on my TAOCP notes, the result is more verbose than the equivalent Python, but every allocation, load, and store is visible.