1️⃣ The Environment & Network
Learning Objectives
- Use the provided vectorised Connect-4 environment, and understand how the board is encoded.
- Build the AlphaZero policy-value network.
⚠️ Note: The exercises in this section are pretty similar to the ones that we did on CNN/ResNets day. If you're already comfortable and don't desire to do more exercises on building a bunch of
nn.Modulesgiven a blueprint, feel free to just read the description of the environment and the actor/critic network, and then skip the exercises and move on.
The Connect-4 environment (given)
Connect4Env (in game.py) is a fully vectorised environment: it operates on a batch of
N boards at once. Its state is a Board, which holds both the pieces (obs) and whose turn it is
(red_to_move); we'll look at Board properly just below. The interface:
# Don't copy this code in, is provided only for reference.
class Connect4Env:
"""
Vectorized, GPU-friendly Connect 4 environment.
- Board shape: height x width (default 6 x 7)
- State: a `Board` of batch shape (N,), holding
obs: (N, 3, H, W) float32, channels = [empty, red, yellow] (absolute colours)
red_to_move: (N,) bool, whose turn it is
Reward scheme (mover's perspective): +1 win, -2 illegal move (worse than a
normal loss), 0 for a draw or a game that continues. ``step`` only ever checks
whether the *mover* just won or drew: you cannot lose on your own move.
Environments auto-reset in-place whenever done or illegal, but the returned
`done` indicates the terminal transition.
"""
def reset(self, num_env: int) -> Board:
"""Return `num_env` empty boards (a Board of batch shape (num_env,)), red to move on all of them."""
@t.no_grad()
def step(
self,
boards: Board,
actions: Int[Tensor, "N"] | int,
) -> tuple[Board, Bool[Tensor, "N"] | bool, Float[Tensor, "N"] | float]:
"""
Apply one move by the player to move on each board: red (channel 1) where
`boards.red_to_move`, else yellow (channel 2).
Args:
boards (Board): batch shape (N,).
actions (int or Tensor): Actions to apply; either scalar int or (N,) long tensor.
Returns:
next_boards (Board): the boards after the move, with `red_to_move` flipped
(finished games auto-reset: empty board, red to move),
done (Tensor (N,), or bool if N = 1 and `actions` is an int),
reward (Tensor (N,), or float if N = 1 and `actions` is an int): to the player who moved.
"""
@t.no_grad()
def legal_action_mask(self, boards: Board) -> Bool[Tensor, "N W"]:
"""Boolean mask of columns with space: (N,) boards -> (N, W)."""
Let's look at a board:
env = Connect4Env(device=device)
board = env.reset(1)
board, _, _ = env.step(board, t.tensor([3], device=device)) # red plays column 3
board, _, _ = env.step(board, t.tensor([3], device=device)) # yellow replies in column 3
print(render_board(board))
Boards and whose turn it is: Board
The current position in a game of Connect4 is described by two things:
- The current state of pieces on the grid
- recorded as a tensor of shape
(3, H, W), where the three channels are each (0,1)-matrices representing if- channel 0: the cell is empty,
- channel 1: contains player 1's (red) token, or
- channel 2: contains player 2's (yellow) token.
- recorded as a tensor of shape
- Whose turn it is to play (a boolean
red_to_move,Trueif it is red's (player 1's) turn to play.)
We record this with the class Board (given, in game.py), which bundles the two
to store a batch of gamestates:
# Don't copy in this code, is already imported from `game.py`
@dataclass
class Board:
obs: Float[Tensor, "*B 3 H W"] # channels [empty, red, yellow]
red_to_move: Bool[Tensor, "*B"] # True where red (player 1) is the player to move
def __getitem__(self, idx): # index both fields at once
return Board(self.obs[idx], self.red_to_move[idx])
def __setitem__(self, idx, other): # ...and assign both fields at once
self.obs[idx] = other.obs
self.red_to_move[idx] = other.red_to_move
...
def mover_view(self) -> Float[Tensor, "*B 3 H W"]:
"""The board from the perspective of the player to move: channels [empty, mover, opponent].
Red-to-move boards are unchanged; yellow-to-move boards get channels 1 and 2 swapped. This is
what the network sees, so it only ever has to learn to play one side."""
Indexing a Board just passes the index on to both fields, so it behaves like a single tensor
whose shape is the batch shape *B (board.shape): indexing, slicing, masking and assignment all
act on both fields at once (plus a few helpers: .clone(), .reshape(...) of the batch dims, and
Board.cat([...]) in place of t.cat). So a batch of N boards is just a Board of shape
(N,), boards[b] is game b's board (with its own red_to_move).
boards = env.reset(4) # a Board of shape (4,): 4 empty boards, red to move
boards.obs.shape # t.Size([4, 3, 6, 7])
boards.red_to_move # tensor([True, True, True, True])
boards[1:3] # a Board of shape (2,)
boards, done, reward = env.step(boards, t.tensor([3, 3, 0, 6])) # one move in every game
boards.red_to_move # tensor([False, False, False, False]): yellow to move
boards[[0, 2]] = env.reset(2) # restart games 0 and 2: writes their obs AND red_to_move
boards.red_to_move # tensor([ True, False, True, False])
env.reset returns Boards, and env.step(boards, actions) returns the next Boards (with
red_to_move flipped, since the opponent moves next), along with done and reward.
The network would rather see the board from the perspective of the player to move (its own
pieces in channel 1, the opponent's in channel 2), so that it only ever has to learn to play
as red. Board.mover_view() does exactly that: it swaps channels 1 and 2 wherever yellow is to move.
The network takes a Board, and the (given) first line of Connect4Model.forward calls
mover_view for you, so the network always returns a distribution over actions for the player to move,
while internally only learning to play as red.
board = env.reset(1)
board, _, _ = env.step(board, 3) # red plays column 3 (env.step flips red_to_move for us)
print(render_board(board), "\n")
print("...and from the mover's (yellow's) perspective, as the network sees it:")
print(render_board(Board(board.mover_view(), board.red_to_move), show_to_move=False))
# channels swapped: red's piece is now the opponent's, so it is drawn as O
The network architecture
The network is a small residual CNN with a shared trunk and two heads: an actor head (a prior over the 7 columns) and a critic head (how good the position is for the mover):
flowchart TD
I["Board (B,)"] --> MV["boards.mover_view() (given)<br/>(B, 3, 6, 7), channels: empty, mover, opponent"]
MV --> C["initial Conv2d 3 to 128<br/>3x3, pad 1, then BatchNorm, ReLU"]
C --> R1["ResBlock(128)"]
R1 --> R2["ResBlock(128)"]
R2 --> VH["critic"]
R2 --> PH["actor"]
VH --> V["value (B,)<br/>mover's expected result"]
PH --> P["logits (B, 7)<br/>one score per column"]
Each residual block adds its input back after two conv layers (the skip connection), which keeps deep stacks easy to train:
flowchart TD
X(["x"]) --> A["Conv 3x3, BN, ReLU"]
A --> B["Conv 3x3, BN"]
X -. skip .-> S(("+"))
B --> S
S --> RO["ReLU"]
RO --> O["out"]
The two heads each collapse the 128-channel trunk down to their output:
flowchart TD
subgraph "critic (value head)"
direction TB
XV["trunk<br/>(B, 128, 6, 7)"] --> AV["Conv 1x1<br/>128 to 3"] --> BV["BN, ReLU"] --> FV["flatten"] --> LV["Linear<br/>3*6*7 to 32"] --> RV["ReLU"] --> OV["Linear<br/>32 to 1"] --> TV["tanh"] --> VV["value<br/>(B,)"]
end
subgraph "actor (policy head)"
direction TB
XP["trunk<br/>(B, 128, 6, 7)"] --> AP["Conv 1x1<br/>128 to 32"] --> BP["BN, ReLU"] --> FP["flatten"] --> LP["Linear<br/>32*6*7 to 7"] --> OP["logits<br/>(B, 7)"]
end
(Note the two heads shrink the trunk to a different number of channels: 3 for the critic, 32 for the actor.)
Building the network
We'll build the network in four small pieces, each with its own test: the ResBlock the trunk
stacks, the Critic (value head) and Actor (policy head), and finally the Connect4Model that
wires the shared trunk and the two heads together. This is just like how we built CNNs in [0.2]. Throughout: 3×3 convs use padding=1, the 1×1 convs in the heads use padding=0, and
each conv is followed by BatchNorm.
Exercise - implement ResBlock
A residual block runs its input through two 3×3 conv→BatchNorm layers and adds the original input back
before the final ReLU (the skip connection). The block only has to learn a residual, which keeps
deep stacks easy to train.
class ResBlock(nn.Module):
"""A residual block, shape-preserving on (B, channels, H, W):
x -> Conv2d 3×3 -> BatchNorm -> ReLU -> Conv2d 3×3 -> BatchNorm -> (+ x) -> ReLU
Both convs are `channels -> channels`, 3×3, padding=1, `bias=False`: each conv is followed
immediately by a BatchNorm, whose learned shift makes a conv bias redundant.
"""
def __init__(self, channels: int):
super().__init__()
raise NotImplementedError()
def forward(self, x: Float[Tensor, "B C H W"]) -> Float[Tensor, "B C H W"]:
"""Two conv-BN layers (ReLU between), then add the input back (skip) and ReLU.
Args:
x: (B, C, H, W) input feature map
Returns:
(B, C, H, W) output feature map (shape preserved)
"""
raise NotImplementedError()
tests.test_resblock(ResBlock)
Solution
class ResBlock(nn.Module):
"""A residual block, shape-preserving on (B, channels, H, W):
x -> Conv2d 3×3 -> BatchNorm -> ReLU -> Conv2d 3×3 -> BatchNorm -> (+ x) -> ReLU
Both convs are `channels -> channels`, 3×3, padding=1, `bias=False`: each conv is followed
immediately by a BatchNorm, whose learned shift makes a conv bias redundant.
"""
def __init__(self, channels: int):
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: Float[Tensor, "B C H W"]) -> Float[Tensor, "B C H W"]:
"""Two conv-BN layers (ReLU between), then add the input back (skip) and ReLU.
Args:
x: (B, C, H, W) input feature map
Returns:
(B, C, H, W) output feature map (shape preserved)
"""
residual = x
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)) + residual)
return x
Exercise - implement Critic (the value head)
The critic maps the shared trunk to a single scalar giving the value of the position for the side
to move. It shrinks the 128-channel trunk with a 1×1 conv, then flattens and runs a small MLP down
to one number. Finish with a tanh so the output is squashed into [-1, 1] so it lies in the same range as the
game-outcome value targets z (−1 loss / 0 draw / +1 win), which keeps the head's range matched to
its target and stops it from drifting to large magnitudes. Output shape: (B,).
class Critic(nn.Module):
"""The value head, (B, in_channels, H, W) trunk features -> (B,) values in [-1, 1]:
Conv2d 1×1 `in_channels -> conv_out` (bias=False) -> BatchNorm -> ReLU -> Flatten
-> Linear(conv_out*height*width -> 32) -> ReLU -> Linear(32 -> 1) -> Tanh -> squeeze to (B,)
The 1×1 conv shrinks the trunk to `conv_out` channels before flattening (a per-square shared
Linear), and the final tanh bounds the value to [-1, 1] to match the game-outcome targets z.
As in `ResBlock`, the conv uses `bias=False`: the BatchNorm right after makes a conv bias redundant.
"""
def __init__(self, in_channels=128, conv_out=3, height=6, width=7):
super().__init__()
raise NotImplementedError()
def forward(self, x: Float[Tensor, "B C H W"]) -> Float[Tensor, "B"]:
"""Map the shared trunk to a scalar value for the side to move.
Args:
x: (B, C, 6, 7) shared-trunk features
Returns:
(B,) the position's value for the mover, in [-1, 1] (tanh-squashed)
"""
return self.net(x).squeeze(-1) # (B, 1) -> (B,)
tests.test_critic(Critic)
Solution
class Critic(nn.Module):
"""The value head, (B, in_channels, H, W) trunk features -> (B,) values in [-1, 1]:
Conv2d 1×1 `in_channels -> conv_out` (bias=False) -> BatchNorm -> ReLU -> Flatten
-> Linear(conv_out*height*width -> 32) -> ReLU -> Linear(32 -> 1) -> Tanh -> squeeze to (B,)
The 1×1 conv shrinks the trunk to `conv_out` channels before flattening (a per-square shared
Linear), and the final tanh bounds the value to [-1, 1] to match the game-outcome targets z.
As in `ResBlock`, the conv uses `bias=False`: the BatchNorm right after makes a conv bias redundant.
"""
def __init__(self, in_channels=128, conv_out=3, height=6, width=7):
super().__init__()
# The 1x1 conv is a shared per-cell Linear: it maps each square's `in_channels`-vector down
# to `conv_out` channels with the *same* weights at every square, shrinking the trunk before
# we flatten and run the small MLP. Far fewer params than flattening all 128 channels straight
# into a Linear, and it keeps the board's spatial layout intact.
self.net = nn.Sequential(
nn.Conv2d(in_channels, conv_out, 1, bias=False),
nn.BatchNorm2d(conv_out),
nn.ReLU(),
nn.Flatten(),
nn.Linear(conv_out * height * width, 32),
nn.ReLU(),
nn.Linear(32, 1),
nn.Tanh(), # squash to [-1, 1] so the value head's range matches the game-outcome targets z
)
def forward(self, x: Float[Tensor, "B C H W"]) -> Float[Tensor, "B"]:
"""Map the shared trunk to a scalar value for the side to move.
Args:
x: (B, C, 6, 7) shared-trunk features
Returns:
(B,) the position's value for the mover, in [-1, 1] (tanh-squashed)
"""
return self.net(x).squeeze(-1) # (B, 1) -> (B,)
Exercise - implement Actor (the policy head)
The actor maps the shared trunk to 7 logits, one for each column on the board. Same
1×1-conv → flatten → Linear pattern as the critic, but the final Linear produces width outputs.
Output shape: (B, 7).
class Actor(nn.Module):
"""The policy head, (B, in_channels, H, W) trunk features -> (B, width) column logits:
Conv2d 1×1 `in_channels -> conv_out` (bias=False) -> BatchNorm -> ReLU -> Flatten
-> Linear(conv_out*height*width -> width)
Same shrink-then-flatten pattern as the Critic (note the different `conv_out` default: 32
here vs 3 there), but the final Linear emits one logit per column and there is no squashing —
these are raw logits, softmaxed later. Conv bias=False (a BatchNorm follows), as in the Critic.
"""
def __init__(self, in_channels=128, conv_out=32, height=6, width=7):
super().__init__()
raise NotImplementedError()
def forward(self, x: Float[Tensor, "B C H W"]) -> Float[Tensor, "B 7"]:
"""Map the shared trunk to one policy logit per column.
Args:
x: (B, C, 6, 7) shared-trunk features
Returns:
(B, 7) one logit per column
"""
return self.net(x)
tests.test_actor(Actor)
Solution
class Actor(nn.Module):
"""The policy head, (B, in_channels, H, W) trunk features -> (B, width) column logits:
Conv2d 1×1 `in_channels -> conv_out` (bias=False) -> BatchNorm -> ReLU -> Flatten
-> Linear(conv_out*height*width -> width)
Same shrink-then-flatten pattern as the Critic (note the different `conv_out` default: 32
here vs 3 there), but the final Linear emits one logit per column and there is no squashing —
these are raw logits, softmaxed later. Conv bias=False (a BatchNorm follows), as in the Critic.
"""
def __init__(self, in_channels=128, conv_out=32, height=6, width=7):
super().__init__()
# 1x1 conv = shared per-cell Linear (see Critic), shrinking the trunk before the flatten + FC.
self.net = nn.Sequential(
nn.Conv2d(in_channels, conv_out, 1, bias=False),
nn.BatchNorm2d(conv_out),
nn.ReLU(),
nn.Flatten(),
nn.Linear(conv_out * height * width, width),
)
def forward(self, x: Float[Tensor, "B C H W"]) -> Float[Tensor, "B 7"]:
"""Map the shared trunk to one policy logit per column.
Args:
x: (B, C, 6, 7) shared-trunk features
Returns:
(B, 7) one logit per column
"""
return self.net(x)
Exercise - implement Connect4Model
Now assemble the full network: a stem (3×3 conv → BN → ReLU) lifting the 3-channel board to
channels, two ResBlocks, then the critic and actor heads on the shared trunk. forward
takes a Board and returns (value, logits). Its first line, x = boards.mover_view(), is given:
it turns the boards into (B, 3, 6, 7) tensors from the mover's perspective, so the network
only ever sees boards when playing a turn as red.
class Connect4Model(nn.Module):
"""The full AlphaZero network: a shared convolutional trunk and the two heads.
Architecture (build the modules in this order — see note below):
- `self.features` (the trunk): Conv2d 3×3 `3 -> channels` (padding=1, bias=False) -> BatchNorm
-> ReLU, then two `ResBlock(channels)`.
- `self.critic = Critic(channels, critic_conv_out, height, width)` on the trunk output.
- `self.actor = Actor(channels, actor_conv_out, height, width)` on the trunk output.
Note: create trunk, then critic, then actor, in that order. The tests check your model is
functionally identical to the reference by copying the reference weights in by
*parameter-creation order*, so a correct architecture built in a different order fails them.
"""
def __init__(self,
device,
channels: int = 128,
critic_conv_out: int = 3,
actor_conv_out: int = 32,
height: int = 6,
width: int = 7,
):
super().__init__()
raise NotImplementedError()
self.to(device)
def forward(
self, boards: Board
) -> tuple[Float[Tensor, "B"], Float[Tensor, "B 7"]]:
"""Run the shared trunk then both heads on a batch of boards.
Args:
boards: a `Board` of batch shape (B,).
Returns:
value: (B,) the position's value for the mover, in [-1, 1] (tanh-squashed)
logits: (B, 7) one policy logit per column
"""
x = boards.mover_view() # (B, C, H, W)
raise NotImplementedError()
summary(Connect4Model(device))
tests.test_connect4_model(Connect4Model)
Solution
class Connect4Model(nn.Module):
"""The full AlphaZero network: a shared convolutional trunk and the two heads.
Architecture (build the modules in this order — see note below):
- `self.features` (the trunk): Conv2d 3×3 `3 -> channels` (padding=1, bias=False) -> BatchNorm
-> ReLU, then two `ResBlock(channels)`.
- `self.critic = Critic(channels, critic_conv_out, height, width)` on the trunk output.
- `self.actor = Actor(channels, actor_conv_out, height, width)` on the trunk output.
Note: create trunk, then critic, then actor, in that order. The tests check your model is
functionally identical to the reference by copying the reference weights in by
*parameter-creation order*, so a correct architecture built in a different order fails them.
"""
def __init__(self,
device,
channels: int = 128,
critic_conv_out: int = 3,
actor_conv_out: int = 32,
height: int = 6,
width: int = 7,
):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, channels, 3, padding=1, bias=False),
nn.BatchNorm2d(channels),
nn.ReLU(),
ResBlock(channels),
ResBlock(channels),
)
self.critic = Critic(channels, critic_conv_out, height, width)
self.actor = Actor(channels, actor_conv_out, height, width)
self.to(device)
def forward(
self, boards: Board
) -> tuple[Float[Tensor, "B"], Float[Tensor, "B 7"]]:
"""Run the shared trunk then both heads on a batch of boards.
Args:
boards: a `Board` of batch shape (B,).
Returns:
value: (B,) the position's value for the mover, in [-1, 1] (tanh-squashed)
logits: (B, 7) one policy logit per column
"""
x = boards.mover_view() # (B, C, H, W)
x = self.features(x)
return self.critic(x), self.actor(x)