Residual policy-value network
Design the network: input planes from the player perspective, a small residual tower, a policy head over columns with an illegal-move mask, and a value head. Before self-play, validate it through supervised learning on solver-labeled positions, using horizontal board symmetry for augmentation.
After this lesson you can
- Design the input encoding and two-head residual network.
- Implement combined policy, value, and regularization loss with an illegal-move mask.
- Train supervised on solver positions with symmetry augmentation.
- Measure value and optimal-move accuracy on test positions and batch inference latency.
Before you start
A network viewing the board from the current turn
The exact solver gave us reference labels; MCTS with UCT showed how to allocate simulations without solving the entire tree. Now we build a network receiving a position and returning two answers: a preference distribution over columns and a value for the player to move. In later lessons these outputs will guide search. Before joining all components, we perform a supervised test in which the solver supplies targets, allowing a representation failure to be distinguished from a self-play failure.
An attractive distribution is not yet a good policy. It may assign mass to full columns, choose a loss in a winning position, or be correct only because almost every action in the sample preserves the outcome. Each prediction is therefore compared with legal actions and each one’s exact outcome. A uniform reference does not necessarily get one in seven right: in each position its accuracy probability is the number of optimal actions divided by the number of legal actions.
The figure shows predictions from the lab run, not values fitted to illustrate a case. An optimal column preserves the best weak outcome from the first lesson; two wins with different speed are equivalent on this scale. The value head returns a continuous scalar: its magnitude alone is not a win probability. Calculating three-class accuracy requires specifying how it becomes win, draw, or loss and fixing that criterion before evaluation.
Planes and perspective
This convention makes the value output always answer the same question: what outcome belongs to the active player? Changing turn changes which plane represents each player. If absolute colors are encoded instead, the network also needs the turn; learning with that representation is not mathematically impossible, but removing turn without equivalent information makes the problem ambiguous. Perspective change must also be respected in targets: a outcome for the player moving in one state becomes for the opponent after a nonterminal move.
The legality mask belongs in both selection and loss. Let be logits and legal columns. The policy is
Only nonterminal states with at least one legal action are evaluated. In a row without legal actions, all masked entries would be and softmax undefined. Detect that beforehand rather than hiding it with an arbitrary value. Normalization over legal actions also changes the gradient: computing softmax over all actions then zeroing illegal ones leaves a sum below one and lets irrelevant logits compete for mass.
Residual trunk and two heads
The policy-value network shares a convolutional trunk and branches into one head for seven columns and another for the value scalar. The trunk learns local features that can combine through layers: for example, a piece can belong to a horizontal threat, but its effect also depends on height and who moves. Correct cell colors alone do not suffice: encoding and architecture must preserve context determining whether a cell is reachable.
A residual block computes , where contains convolutions and normalization. The sum requires both terms to have the same shape. The identity path passes a direct signal and the branch learns a correction; it does not alone guarantee every network trains well. He and collaborators introduce residual learning as a reformulation of deep networks. Their classification result is not direct evidence that a particular architecture is optimal for Connect 4: here we will measure ours.
For scale, the AlphaZero supplement describes a trunk with an initial convolution and 19 residual blocks of two convolutions with 256 filters. This lab’s network is smaller and trained with a solver’s supervised labels; we are not reproducing that training or claiming its performance. The paper jointly optimizes policy and value heads, but its policy target comes from self-play search. Here we construct a uniform distribution over actions the oracle considers optimal.
The policy head produces unnormalized logits. The value head uses tanh to limit output to , matching win, draw, and loss outcomes encoded as . With squared loss, continuous value attempts to approximate a conditional mean under the label-generating procedure; it need not return exactly one of those three values. Another option is a three-logit head with cross-entropy, expressing a class distribution. Choosing between them requires declaring what is evaluated and how uncertainty is interpreted, rather than claiming one always dominates the other.
Targets, mask, and loss
Let be the set of legal actions attaining the oracle’s best outcome. To avoid imposing an arbitrary preference among them, define if and zero otherwise. Supervised loss combines policy cross-entropy, value squared error, and weight regularization:
Summing over legal actions also matters numerically. If masks logits and a zero target is then multiplied by an illegal action’s logarithm, can produce NaN. Exclude those entries or replace their logarithms with zero before multiplying. Regularization must define which parameters it includes: biases and normalization parameters need not follow the same convention as convolution weights. Combining losses is a scale decision; different batch reductions and coefficients change the balance.
The preceding expression describes an explicit objective penalty. The lab instead uses AdamW with decoupled weight decay: it applies decay as part of the update rather than adding it to Adam’s adaptive gradient. It is therefore not exactly equivalent to adding the preceding squared term to a loss optimized with Adam. Here decay is also applied to biases and normalization parameters; changing that selection is another experimental decision to record.
Reflect without leaking information
Horizontal symmetry maps column to and preserves gravity, winning lines, and turn. Thus reflecting input also reflects mask and policy vector; value label is unchanged. A rotation or vertical reflection does not preserve the falling direction and is not a symmetry of this game. Each epoch, augmentation randomly presents the original position or its reflection; it does not guarantee every position appears both ways or that a finite network is exactly equivariant. Symmetry is an exact property of rules, not of every learned approximator.
Splitting must precede augmentation. If a position is in training and its reflection in test, the test result may measure memorization of an equivalent example. Use a canonical key grouping both states and assign the entire group to one split. The previous lesson generates endgames conditioned on not ending before a fixed depth. They help with a supervised check but do not automatically represent openings or the future agent’s visited-position distribution. Test percentage applies only to the declared sampling procedure.
A supervised test before self-play
The supervised check asks whether the network can learn a task with known targets. Split training and test by position and reflection; fit only on training and evaluate with model.eval() and inference_mode() to avoid updating normalization statistics or constructing a gradient graph. Report optimal-action accuracy, a uniform legal-action reference, and value accuracy with an explicit draw rule. One aggregate figure does not explain failure: inspect incorrect examples and exact values of their alternatives.
The inference benchmark is another experiment. CUDA operations are asynchronous, so measuring only Python’s time to enqueue a call can underestimate work. PyTorch documentation recommends synchronization or CUDA events for correct timing. Warm up each batch size, retain evaluation mode, and declare whether transfers are included. Compare per-batch latency and per-example throughput without treating absolute timings on a shared GPU as a stable model property.
Lab
The first cell reproduces rule and search functions from the current version of lesson one. Generation retains its seed, 36 moves, and rejection of earlier wins; labels come from n_analyze, checked there against the external dataset. No temporary file from another lesson is needed. The canonical key compares the board with its reflection before splitting groups into training and test. Random augmentation reflects board, mask, and policy together only during training.
W, H, S = 7, 6, 7
ORDER = (3, 2, 4, 1, 5, 0, 6)
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)
def win(p):
for d in (1, 6, 7, 8):
pairs = p & (p >> d)
if pairs & (pairs >> (2 * d)):
return True
return False
def move_bit(mask, c):
legal = (mask + BOTTOM) & BOARD
return legal & (((1 << H) - 1) << (c * S))
def position(sequence):
# sequence contiene columnas desde cero y termina antes de ganar.
current = mask = 0
for c in sequence:
if not 0 <= c < W:
raise ValueError('Columna fuera del tablero')
b = move_bit(mask, c)
if not b or win(current | b):
raise ValueError('Columna llena o partida ya terminada')
current, mask = current ^ mask, mask | b
return current, mask
class Solver:
def __init__(self):
self.table = {}
self.nodes = 0
def search(self, current, mask, alpha, beta):
self.nodes += 1
if mask == BOARD:
return 0
key = current + mask
entry = self.table.get(key)
if entry is not None:
lower, upper = entry
if lower == upper:
return lower
alpha, beta = max(alpha, lower), min(beta, upper)
if alpha >= beta:
return lower if lower >= beta else upper
a0, b0 = alpha, beta
best = -2
for c in ORDER:
b = move_bit(mask, c)
if not b:
continue
if win(current | b):
value = 1
else:
value = -self.search(current ^ mask, mask | b, -beta, -alpha)
best = max(best, value)
alpha = max(alpha, best)
if alpha >= beta:
break
lower, upper = self.table.get(key, (-1, 1))
if best <= a0:
upper = min(upper, best)
elif best >= b0:
lower = max(lower, best)
else:
lower = upper = best
self.table[key] = (lower, upper)
return best
def value(self, current, mask):
return self.search(current, mask, -2, 2)
def analyze(self, current, mask):
values = []
for c in range(W):
b = move_bit(mask, c)
if not b:
values.append(None)
elif win(current | b):
values.append(1)
else:
values.append(-self.value(current ^ mask, mask | b))
return values
import numpy as np
from numba import njit, types
from numba.typed import Dict
@njit
def n_win(p):
for d in (1, 6, 7, 8):
pairs = p & (p >> d)
if pairs & (pairs >> (2*d)):
return True
return False
@njit
def n_bit(mask, c):
return ((mask + BOTTOM) & BOARD) & (63 << (c*7))
@njit
def n_search(p, mask, alpha, beta, table, counter):
counter[0] += 1
if mask == BOARD:
return 0
key = p + mask
if key in table:
entry = table[key]
lower, upper = entry // 3 - 1, entry % 3 - 1
if lower == upper:
return lower
alpha, beta = max(alpha, lower), min(beta, upper)
if alpha >= beta:
return lower if lower >= beta else upper
a0, b0 = alpha, beta
best = -2
for c in (3, 2, 4, 1, 5, 0, 6):
b = n_bit(mask, c)
if not b:
continue
if n_win(p | b):
table[key] = 8
return 1
value = -n_search(p ^ mask, mask | b, -beta, -alpha, table, counter)
best = max(best, value)
alpha = max(alpha, best)
if alpha >= beta:
break
lower, upper = -1, 1
if key in table:
entry = table[key]
lower, upper = entry // 3 - 1, entry % 3 - 1
if best <= a0:
upper = min(upper, best)
elif best >= b0:
lower = max(lower, best)
else:
lower = upper = best
table[key] = (lower + 1)*3 + upper + 1
return best
@njit
def n_analyze(p, mask, table, counter):
result = np.full(7, -2, dtype=np.int64)
for c in range(7):
b = n_bit(mask, c)
if b:
if n_win(p | b):
result[c] = 1
else:
result[c] = -n_search(p ^ mask, mask | b, -2, 2, table, counter)
return result
@njit
def n_value(p, mask, table, counter):
if n_search(p, mask, -1, 0, table, counter) < 0:
return -1
if n_search(p, mask, 0, 1, table, counter) >= 1:
return 1
return 0
npm run lab and open the connection link.The next cell fixes seeds and uses deterministic PyTorch algorithms on the available device. Reproducible predictions can vary across versions and devices; interpret table and curves as this run’s results. The policy target distributes mass uniformly among all moves tied for best weak value. -1e9 is used as the illegal-column logit in single precision, and every state is checked for at least one legal move. AdamW applies decoupled weight decay to parameters, which is not identical to adding an L2 penalty to Adam’s gradient.
Evaluation does not update the network: eval() disables normalization training behavior and inference_mode() avoids building the graph. Value classification uses thresholds −1/3 and +1/3: below the first is loss, above the second win, and between them draw. The uniform reference averages, per position, the ratio of optimal to legal moves. Both metrics come from the same test set, not a distribution of complete games.
"""Experimento de política y valor con el oráculo de la lección actual p12-l01."""
import json
import gc
import math
import os
import random
import re
import time
from pathlib import Path
import numpy as np
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(1)
random.seed(1203)
np.random.seed(1203)
torch.manual_seed(1203)
torch.use_deterministic_algorithms(True)
def reflect(x):
out = 0
for c in range(7):
out |= ((x >> (7*c)) & 127) << (7*(6-c))
return out
def generate(engine, n=20000):
from numba import types
from numba.typed import Dict
win, bit, analyze = engine['win'], engine['move_bit'], engine['n_analyze']
table = Dict.empty(key_type=types.int64, value_type=types.int64)
counter = np.zeros(1, np.int64)
rng = random.Random(1201)
records, seen = [], set()
attempts = 0
while len(records) < n:
p = mask = 0
seq = []
for _ in range(36):
legal = [(c, bit(mask, c)) for c in range(7)]
legal = [(c,b) for c,b in legal if b and not win(p | b)]
if not legal:
break
c, b = rng.choice(legal)
seq.append(c)
p, mask = p ^ mask, mask | b
attempts += 1
if len(seq) != 36 or p + mask in seen:
continue
seen.add(p + mask)
values = [int(v) for v in analyze(p, mask, table, counter)]
records.append({'sequence': seq, 'p': p, 'mask': mask, 'values': values})
if len(records) % 1000 == 0:
table.clear()
print('Posiciones etiquetadas:', len(records), 'intentos:', attempts, flush=True)
return records
def key(record):
p, mask = record['p'], record['mask']
return min((p,mask), (reflect(p), reflect(mask)))
def split(records):
groups = {}
for row in records:
groups.setdefault(key(row), []).append(row)
keys = list(groups)
random.Random(1203).shuffle(keys)
cutoff = int(.8 * len(keys))
train = [row for k in keys[:cutoff] for row in groups[k]]
test = [row for k in keys[cutoff:] for row in groups[k]]
assert set(map(key,train)).isdisjoint(set(map(key,test)))
print('Grupos de posición y reflejo:', len(groups), '; entrenamiento:', len(train), '; prueba:', len(test), flush=True)
return train,test
def encode(row):
p, mask = row['p'], row['mask']
x = np.zeros((2,6,7), dtype=np.float32)
for c in range(7):
for r in range(6):
bit = 1 << (7*c+r)
x[0,r,c] = bool(p & bit)
x[1,r,c] = bool((p ^ mask) & bit)
legal = np.array([v != -2 for v in row['values']])
if not legal.any():
raise ValueError('No se puede evaluar un estado terminal sin jugadas legales')
best = max(v for v in row['values'] if v != -2)
optimal = np.array([v == best for v in row['values']], dtype=np.float32)
policy = optimal / optimal.sum()
return x, legal, policy, np.float32(best)
def tensors(rows):
z = [encode(row) for row in rows]
return [torch.tensor(np.stack([x[i] for x in z])) for i in range(4)]
class Block(nn.Module):
def __init__(self, channels):
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(channels)
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(channels)
def forward(self, x):
y = F.relu(self.bn1(self.conv1(x)))
return F.relu(x + self.bn2(self.conv2(y)))
class PolicyValue(nn.Module):
def __init__(self, channels=32, blocks=3):
super().__init__()
self.stem = nn.Sequential(nn.Conv2d(2,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels), nn.ReLU())
self.tower = nn.Sequential(*(Block(channels) for _ in range(blocks)))
self.policy = nn.Sequential(nn.Conv2d(channels,2,1), nn.ReLU(), nn.Flatten(), nn.Linear(84,7))
self.value = nn.Sequential(nn.Conv2d(channels,1,1), nn.ReLU(), nn.Flatten(), nn.Linear(42,32), nn.ReLU(), nn.Linear(32,1), nn.Tanh())
def forward(self,x,legal):
y = self.tower(self.stem(x))
logits = self.policy(y).masked_fill(~legal, -1e9)
return logits, self.value(y).squeeze(-1)
def train_run():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Dispositivo:', device, flush=True)
eng = {'win': win, 'move_bit': move_bit, 'n_analyze': n_analyze}
records = generate(eng)
training, testing = split(records)
X,L,P,V = tensors(training)
Xt,Lt,Pt,Vt = tensors(testing)
model = PolicyValue().to(device)
print('Parámetros:', sum(p.numel() for p in model.parameters()), flush=True)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-4)
order_rng = torch.Generator().manual_seed(1203)
losses = []
for epoch in range(12):
model.train()
order = torch.randperm(len(X), generator=order_rng)
total = 0
for ix in order.split(256):
x,l,p,v = X[ix].to(device), L[ix].to(device), P[ix].to(device), V[ix].to(device)
# La misma reflexión transforma tablero, legales y objetivo de política.
flip = (torch.rand(len(ix), generator=order_rng) < .5).to(device)
x[flip] = x[flip].flip(-1)
l[flip] = l[flip].flip(-1)
p[flip] = p[flip].flip(-1)
logits, value = model(x,l)
loss = -(p*F.log_softmax(logits,dim=1)).sum(dim=1).mean() + F.mse_loss(value,v)
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
total += loss.item()*len(ix)
losses.append(total / len(X))
print('Época:', epoch+1, 'pérdida:', round(losses[-1],4), flush=True)
model.eval()
with torch.inference_mode():
outputs = [model(Xt[i:i+256].to(device), Lt[i:i+256].to(device)) for i in range(0,len(Xt),256)]
logits = torch.cat([x[0].cpu() for x in outputs])
values = torch.cat([x[1].cpu() for x in outputs])
pred = logits.argmax(dim=1)
correct = Pt.gather(1,pred[:,None]).squeeze(1) > 0
baseline = (Pt > 0).sum(dim=1) / Lt.sum(dim=1)
category = torch.where(values > 1/3, 1, torch.where(values < -1/3,-1,0))
print('Prueba:', len(Xt), 'óptimas:', int(correct.sum()), 'porcentaje óptimas:', 100 * int(correct.sum()) / len(Xt), 'aleatoria esperada:', round(float(baseline.mean()),4), 'exactitud valor:', round(float((category==Vt).float().mean()),4), flush=True)
chosen = []
value_correct = category == Vt
for flag in (True, False):
for value_flag in (True, False):
indices = torch.nonzero((correct == flag) & (value_correct == value_flag)).squeeze(1)[:2]
for idx in indices.tolist():
row = testing[idx]
chosen.append({'test_index': idx, 'sequence': row['sequence'],
'values': [None if x == -2 else x for x in row['values']],
'exact_value': int(Vt[idx]), 'prediction': int(pred[idx]),
'predicted_value': float(values[idx]), 'value_class': int(category[idx]),
'policy': [float(p) for p in logits[idx].softmax(-1)],
'correct': flag, 'value_correct': value_flag})
ids = [item['test_index'] for item in chosen]
reflected_x = Xt[ids].to(device).flip(-1)
reflected_legal = Lt[ids].to(device).flip(-1)
mirrored_logits, mirrored_values = model(reflected_x, reflected_legal)
mirrored_policy = mirrored_logits.softmax(-1).cpu()
mirrored_values_cpu = mirrored_values.cpu()
for i, item in enumerate(chosen):
item['reflected_policy'] = [float(p) for p in mirrored_policy[i]]
item['reflected_value'] = float(mirrored_values_cpu[i])
results = {'seed': 1203, 'train': len(X), 'test': len(Xt),
'optimal_hits': int(correct.sum()),
'random_expected': float(baseline.mean()),
'value_accuracy': float((category==Vt).float().mean()),
'losses': losses, 'examples': chosen}
for b in (1,8,32,128,512):
x = Xt[:b].to(device)
legal = Lt[:b].to(device)
for _ in range(10): model(x,legal)
if device.type == 'cuda': torch.cuda.synchronize()
t = time.perf_counter()
for _ in range(50): model(x,legal)
if device.type == 'cuda': torch.cuda.synchronize()
print('Lote:', b, 'ms/lote:', round((time.perf_counter()-t)*1000/50,3), flush=True)
del model, optimizer, outputs, x, legal, logits, values, l, p, v, flip, value, loss
del reflected_x, reflected_legal, mirrored_logits, mirrored_values
return results
def run():
try:
return train_run()
finally:
gc.collect()
if torch.cuda.is_available():
torch.cuda.synchronize()
torch.cuda.empty_cache()
print('CUDA: memoria ocupada por tensores propios:', torch.cuda.memory_allocated(), flush=True)
results = run()npm run lab and open the connection link.The following cells show complete examples feeding the figure. Each object indicates test index, zero-based column sequence, exact outcomes per action, the network’s two evaluations, and whether policy and value are correct. null indicates an illegal column. They are printed in groups to audit each prediction without truncating output.
print(json.dumps(results['examples'][0:2], separators=(',', ':')))npm run lab and open the connection link.print(json.dumps(results['examples'][2:4], separators=(',', ':')))npm run lab and open the connection link.print(json.dumps(results['examples'][4:6], separators=(',', ':')))npm run lab and open the connection link.print(json.dumps(results['examples'][6:8], separators=(',', ':')))npm run lab and open the connection link.The inference table warms up each size, transfers the batch before timing, and synchronizes CUDA before and after the loop. It shows average batch latency for that run; it excludes device copy and establishes no universal GPU figure. At the end, references to device tensors are released and the cache cleared. The memory reading concerns only this process. In the reference run the counter still showed 68 157 440 bytes after cleanup; the process ended and released its resources. empty_cache() does not free still-active allocations, so a persistent session may retain memory. For stable measurement repeat under known load and summarize the distribution, rather than extrapolating from one shared-GPU instant.
Output examples include policy and value for the original position and its separately evaluated reflection. Reflecting oracle data is an exact symmetry; whether the second network evaluation matches the reversed first is an experimental question, not an architectural guarantee. The sample, limited to 36-move endgames without earlier wins, checks data flow and separation but does not establish opening performance or playing strength in a complete game.
In the recorded run, of 4 000 test positions the policy chose an optimal move in 3 913. The uniform legal-action reference reaches expected mean 64.08%, and value classification with declared thresholds achieves 91.25%. The comparison confirms the network learns useful information in this endgame distribution. It does not mean it wins 97.825% of games or outperforms a random policy by the same margin in openings. Value and policy can fail separately: interactive positions reveal all four combinations of correct and incorrect.
Exercises
import numpy as np
def encode(current, mask, reflect=False):
passprint('Pesos de los bloques:', 6 * 2 * 64 * 64 * 3 * 3)