Eight axes of block design
PyTorch
class MBConv(nn.Module): # one block, seven axes def __init__(self, c, t=4, s=1): # s: stride super().__init__() m = c * t # dimension: expand self.up = nn.Conv2d(c, m, 1) # channel mixing self.dw = nn.Conv2d(m, m, 3, s, 1, groups=m) self.bn = nn.BatchNorm2d(m) # stabilization self.act = nn.SiLU() # stabilization self.se = SqueezeExcite(m) # modulation self.down = nn.Conv2d(m, c, 1) # projection self.skip = s == 1 # information flow def forward(self, x): y = self.dw(self.act(self.up(x))) y = self.down(self.se(self.act(self.bn(y)))) return x + y if self.skip else yEvery block answers one of eight questions
- Each axis is one question about a feature volume; a primitive such as a pointwise convolution sits on one axis.
- A named block is several choices at once. Click one: the pieces it is built from light up on their own axes.
- A filled dot has a slide, and the button opens it. A hollow dot is not in this deck yet.
The convolution operation
PyTorch
x = torch.tensor([1., 3, 0, 2, 1, -1, 2, 0, 1])w = torch.tensor([1., 2, -1])y = torch.stack([(x[i:i+3] * w).sum() # one place for i in range(len(x) - 2)])# built in; it does not flip the kernel eithery = F.conv1d(x[None, None], w[None, None]) # (1, 1, 7)def conv2d(x, w): # x (H, W), w (K, K) K = w.shape[0] H, W = x.shape[0] - K + 1, x.shape[1] - K + 1 y = torch.zeros(H, W) for i in range(H): # slide down for j in range(W): # slide right y[i, j] = (x[i:i+K, j:j+K] * w).sum() return y # (3, 5) herex = torch.randn(1, 3, 4, 5) # (N, C, H, W)conv = nn.Conv2d(3, 1, kernel_size=3, bias=False)conv.weight.shape # (1, 3, 3, 3)y = conv(x) # (1, 1, 2, 3)# one output number: every channel, one windowwin = x[0, :, 0:3, 0:3] # (3, 3, 3)y[0, 0, 0, 0] == (win * conv.weight[0]).sum()1D: slide, multiply, add
- A CNN's convolution does not flip the kernel: strictly, it is cross-correlation.
- : one output for every place the kernel fits.
- Nine numbers and a kernel of three leave outputs.
2D: the same over a grid
- : the kernel moves along height and width.
- This kernel is a Sobel filter: it is large where values rise from left to right.
- A grid and a kernel leave a output.
Conv2D: a kernel as deep as the feature
- A feature volume is ; the kernel is .
- The sum also runs over the channels, so one kernel returns one flat grid.
- The kernel never moves along : that is why the layer is called Conv2D.
A filter bank
PyTorch
conv = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3)conv.weight.shape # (3, 3, 3, 3)conv.bias.shape # (3,)x = torch.randn(1, 3, 4, 5) # (N, C_in, H, W)y = conv(x) # (1, 3, 2, 3)y[0, 1] # kernel 2's gridsum(p.numel() for p in conv.parameters()) # 84Many kernels, one output channel each
- One kernel returns one flat grid: one feature map.
- A layer holds kernels. Each one reads the whole input volume.
- Their grids are stacked: the output is .
- All the kernels are one weight tensor, , with one bias per kernel.
- The next layer's kernels must then be deep.
- Drag Kernels; click a kernel to bring its channel to the front.
1 × 1 convolution
PyTorch
pw = nn.Conv2d(4, 1, kernel_size=1, bias=False)pw.weight.shape # (1, 4, 1, 1)x = torch.randn(1, 4, 4, 5)y = pw(x) # (1, 1, 4, 5)# at one pixel: a weighted sum of its channelsw = pw.weight[0, :, 0, 0] # 4 numbersy[0, 0, 2, 3] == (x[0, :, 2, 3] * w).sum()pw = nn.Conv2d(4, 3, kernel_size=1, bias=False)M = pw.weight[:, :, 0, 0] # (3, 4): a matrixx = torch.randn(1, 4, 4, 5)y = pw(x) # (1, 3, 4, 5)# the same as a linear layer at every pixely2 = torch.einsum("oc,nchw->nohw", M, x)torch.allclose(y, y2) # Truesqueeze = nn.Conv2d(4, 2, 1) # a bottleneckA kernel one cube wide
- A kernel covers one pixel through every channel: numbers.
- It fits at every pixel, so and do not change.
- Each output is a weighted sum of the channels at one pixel.
A bank of them is a small matrix
- such kernels are a matrix, applied at every pixel.
- Fewer kernels than channels: a bottleneck. More kernels: an expansion.
- It mixes channels, and never looks at a neighbouring pixel.
Depth-wise separable convolution
PyTorch
dw = nn.Conv2d(4, 4, kernel_size=3, groups=4, bias=False) # one per channeldw.weight.shape # (4, 1, 3, 3)x = torch.randn(1, 4, 4, 5)y = dw(x) # (1, 4, 2, 3)# channel c only ever meets kernel cpw = nn.Conv2d(4, 6, kernel_size=1, bias=False)z = pw(y) # (1, 6, 2, 3)class SeparableConv(nn.Module): def __init__(self, c_in, c_out, k=3): super().__init__() self.dw = nn.Conv2d(c_in, c_in, k, groups=c_in) self.pw = nn.Conv2d(c_in, c_out, 1) def forward(self, x): return self.pw(self.dw(x))def n_weights(m): return sum(p.numel() for p in m.parameters())std = nn.Conv2d(256, 256, 3, bias=False)dw = nn.Conv2d(256, 256, 3, groups=256, bias=False)pw = nn.Conv2d(256, 256, 1, bias=False)n_weights(std) # 589,824n_weights(dw) + n_weights(pw) # 2,304 + 65,536Depth-wise: a flat kernel per channel
- Each channel gets its own flat kernel:
groups=C_inin PyTorch. - No kernel sees another channel, so nothing is mixed yet.
- Channels in equals channels out. Click a row for its numbers.
Point-wise: a 1 × 1 bank mixes them
- A bank then mixes the channels and sets .
- Depth-wise looks across space, point-wise across channels.
- Together they stand in for one standard convolution.
Why: count the weights
- Standard: weights. Separable: .
- , 256 channels in and out: 589,824 against 67,840, about 8.7 times fewer.
- MobileNet and Xception are built from this layer.
Stem, bottleneck, expansion
PyTorch
stem = nn.Sequential( # ResNet nn.Conv2d(3, 64, 7, stride=2, padding=3), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(3, stride=2, padding=1))x = torch.randn(1, 3, 224, 224)stem(x).shape # (1, 64, 56, 56)# ConvNeXt: patches of 4 x 4 pixelspatchify = nn.Conv2d(3, 96, 4, stride=4)patchify(x).shape # (1, 96, 56, 56)class Bottleneck(nn.Module): # norms left out def __init__(self, c=256, w=64): super().__init__() self.a = nn.Conv2d(c, w, 1) # squeeze self.b = nn.Conv2d(w, w, 3, padding=1) self.c = nn.Conv2d(w, c, 1) # expand def forward(self, x): y = self.c(F.relu(self.b(F.relu(self.a(x))))) return F.relu(x + y)class Bottleneck(nn.Module): expansion = 4 # out / widthclass BasicBlock(nn.Module): expansion = 1 # ResNet-18, 34widths = [64, 128, 256, 512] # one per stage[w * Bottleneck.expansion for w in widths]# [256, 512, 1024, 2048]An aggressive stem
- The spatial dimensions are height and width: the face of a block. Depth is channels.
- The first layers use big kernels and strides to shrink fast: 224 down to 56.
- Everything after the stem then visits 16 times fewer places.
A bottleneck
- A bottleneck is a layer with fewer channels than its neighbours.
- ResNet-50: down to 64, at 64, back up to 256.
- 69,632 weights, against 589,824 for one layer at full width.
The expansion factor
- Expansion factor: channels out of a block over the channels of its narrow layer.
- ResNet-50, 101 and 152: .
- ResNet-18 and 34 use plain blocks, so the factor is 1.
Stride, padding, dilation
PyTorch
def out_size(n, k, s=1, p=0, d=1): return (n + 2*p - d*(k - 1) - 1) // s + 1x = torch.randn(1, 1, 7, 7)nn.Conv2d(1, 1, 3)(x).shape # 5 x 5nn.Conv2d(1, 1, 3, stride=2)(x).shape # 3 x 3nn.Conv2d(1, 1, 3, padding=1)(x).shape # 7 x 7nn.Conv2d(1, 1, 3, padding=1, dilation=2)(x).shape # 5 x 5out_size(7, 3, p=1, d=2) # 5Where the kernel may sit
- Stride : how many cubes the kernel moves each time. Stride 2 halves height and width.
- Padding : a ring of zeros round the feature, so that the kernel also fits at the edge. keeps the size for a kernel.
- Dilation : space between the taps. The kernel sees further with the same nine weights.
- Here the kernel is nine ones, so each output is the sum of the cubes it taps.
- The size rule holds for height and width separately. A term that changes lights up in it.
Deformable convolution
PyTorch
import torch, torch.nn as nnfrom torchvision.ops import DeformConv2dclass DeformBlock(nn.Module): def __init__(self, c, k=3): super().__init__() # (dy, dx) for each of the k*k taps, per place self.offset = nn.Conv2d(c, 2 * k * k, k, 1, 1) # zero offsets at first: an ordinary convolution nn.init.zeros_(self.offset.weight) nn.init.zeros_(self.offset.bias) self.conv = DeformConv2d(c, c, k, padding=1) def forward(self, x): # (B, C, H, W) off = self.offset(x) # (B, 18, H, W) return self.conv(x, off) # bilinear samplingEvery tap gets an offset of its own
- A standard kernel samples a fixed square, and dilation only stretches that square. Objects are not squares.
- Deformable convolution: . A second convolution predicts the offsets: numbers at every place.
- Offsets are fractional, so a tap is read by bilinear interpolation. The offsets here are set by hand to follow the stroke; v2 adds a learned weight per tap.
Receptive field
PyTorch
def receptive_field(layers): # [(k, s), ...] r, jump = 1, 1 for k, s in layers: r += (k - 1) * jump # grows by k - 1 jump *= s # strides multiply return rreceptive_field([(3, 1)] * 3) # 7receptive_field([(7, 2), (3, 2)]) # 11: ResNet stem3 * 9, 7 * 7 # 27 < 49 weightsimport torch, torch.nn as nndef field(ks, ds): # kernels, dilations return 1 + sum((k - 1) * d for k, d in zip(ks, ds))field([3, 3, 3], [1, 1, 1]) # 7field([3, 3, 3], [1, 2, 4]) # 15net = nn.Sequential(*[nn.Conv2d(1, 1, 3, padding=d, dilation=d, bias=False) for d in (1, 2, 4)])sum(p.numel() for p in net.parameters()) # 27x = torch.zeros(1, 1, 31, 31, requires_grad=True)net(x)[0, 0, 15, 15].backward() # which inputs count?(x.grad[0, 0, 15] != 0).sum() # 15One cube, traced back
- One layer: a cube sees of the input.
- Each layer adds cubes: after layers the field is wide.
- Two layers reach with 18 weights instead of 25; three reach with 27 instead of 49.
- Stride and dilation make the field grow much faster.
- Drag Layers; click a cube of the last grid to trace another one.
Dilation: further, with the same weights
- Dilation leaves holes between the taps: a kernel with spans and still has 9 weights.
- Rates 1, 2, 4: the field is wide, against 7 for plain layers. Both stacks have 27 weights per channel pair. Drawn in 1D; in 2D it holds along and .
- Doubling the rate doubles the field each layer, with no pooling: WaveNet, DeepLab. Rates 2, 2, 2 would leave holes in the field (gridding); 1, 2, 4 covers every cell.
Grouped convolution
PyTorch
for g in (1, 2, 3, 6): conv = nn.Conv2d(6, 6, kernel_size=3, groups=g, bias=False) print(g, tuple(conv.weight.shape), conv.weight.numel())# 1 (6, 6, 3, 3) 324# 2 (6, 3, 3, 3) 162# 3 (6, 2, 3, 3) 108# 6 (6, 1, 3, 3) 54 depth-wiseFrom one group to one per channel
- With groups a kernel reads channels:
groups=gin PyTorch. - Weights: , so times fewer than the standard layer.
- is the standard layer; is depth-wise.
- Channels of different groups never meet inside the layer.
- ResNeXt uses 32 groups in its layers and spends the saving on more channels.
- Drag Groups.
Channel shuffle
PyTorch
import torch, torch.nn as nndef channel_shuffle(x, g): # x: (B, C, H, W) B, C, H, W = x.shape x = x.view(B, g, C // g, H, W) # groups x channels x = x.transpose(1, 2) # deal them out return x.reshape(B, C, H, W) # flatten backgconv1 = nn.Conv2d(9, 9, 1, groups=3)gconv2 = nn.Conv2d(9, 9, 1, groups=3)x = torch.randn(1, 9, 8, 8)y = gconv2(channel_shuffle(gconv1(x), 3))i = torch.arange(9.).view(1, 9, 1, 1)print(channel_shuffle(i, 3).flatten())# tensor([0., 3., 6., 1., 4., 7., 2., 5., 8.])Deal the channels out again
- A grouped convolution is cheap because a group never reads the others. Stack two, and every output still descends from one group.
- Channel shuffle (ShuffleNet): view the channels as , transpose, flatten. No weights and no arithmetic.
- The next grouped layer then gets one channel from every old group. PyTorch has it as nn.ChannelShuffle.
The Inception block
PyTorch
class Inception(nn.Module): # GoogLeNet 3a def __init__(self, c=192): # ReLUs left out super().__init__() self.b1 = nn.Conv2d(c, 64, 1) self.b2 = nn.Sequential(nn.Conv2d(c, 96, 1), nn.Conv2d(96, 128, 3, padding=1)) self.b3 = nn.Sequential(nn.Conv2d(c, 16, 1), nn.Conv2d(16, 32, 5, padding=2)) self.b4 = nn.Sequential( nn.MaxPool2d(3, stride=1, padding=1), nn.Conv2d(c, 32, 1)) def forward(self, x): # (N, 192, 28, 28) ys = [b(x) for b in (self.b1, self.b2, self.b3, self.b4)] return torch.cat(ys, dim=1) # (N, 256, 28, 28)# weights of a branch, biases left out9 * 192 * 128 # 221,184 3 x 3 alone192 * 96 + 9 * 96 * 128 # 129,024 with a 1 x 125 * 192 * 32 # 153,600 5 x 5 alone192 * 16 + 25 * 16 * 32 # 15,872 with a 1 x 1# pooling keeps all 192 channels; a 1 x 1 makes 32192 * 32 # 6,144# the block: 387,072 -> 163,328 weights, 416 -> 256 outSeveral kernel sizes at once
- Four branches read the same input: , , and a max-pool.
- All keep height and width (padding, stride 1), so the outputs can be concatenated.
- Block 3a of GoogLeNet: 192 channels in, out.
What the 1 × 1 layers save
- A layer first cuts the channels that a large kernel has to read.
- After the pooling it cuts the 192 channels that would otherwise all pass on.
- 387,072 weights become 163,328, and 416 output channels become 256.
The residual add
PyTorch
class BasicBlock(nn.Module): # norms left out def __init__(self, c): super().__init__() self.conv1 = nn.Conv2d(c, c, 3, padding=1) self.conv2 = nn.Conv2d(c, c, 3, padding=1) def forward(self, x): f = self.conv2(F.relu(self.conv1(x))) # F(x) return F.relu(x + f) # the addclass DownBlock(nn.Module): # 64 -> 128 def __init__(self, c_in=64, c_out=128): super().__init__() self.conv1 = nn.Conv2d(c_in, c_out, 3, 2, 1) self.conv2 = nn.Conv2d(c_out, c_out, 3, 1, 1) self.skip = nn.Conv2d(c_in, c_out, 1, stride=2) def forward(self, x): f = self.conv2(F.relu(self.conv1(x))) return F.relu(self.skip(x) + f)Add, cube by cube
- : the layers only have to learn the change.
- Adding needs the same shape on both wires: every cube has a partner.
- If the block is the identity, so a very deep stack starts out harmless.
When the shapes differ
- Between stages the layers use stride 2 and twice the kernels.
- The skip then gets a convolution with stride 2: the projection shortcut.
- It is the only time the skip has weights of its own.
The bottleneck block
PyTorch
class Bottleneck(nn.Module): # ResNet-50 def __init__(self, c=256, w=64): super().__init__() self.conv1 = nn.Conv2d(c, w, 1, bias=False) self.bn1 = nn.BatchNorm2d(w) self.conv2 = nn.Conv2d(w, w, 3, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(w) self.conv3 = nn.Conv2d(w, c, 1, bias=False) self.bn3 = nn.BatchNorm2d(c) def forward(self, x): y = F.relu(self.bn1(self.conv1(x))) y = F.relu(self.bn2(self.conv2(y))) y = self.bn3(self.conv3(y)) # no ReLU yet return F.relu(x + y) # add, then ReLUdef n_weights(m): return sum(p.numel() for p in m.parameters())basic = nn.Sequential( # ResNet-18, 34 nn.Conv2d(256, 256, 3, padding=1, bias=False), nn.Conv2d(256, 256, 3, padding=1, bias=False))neck = nn.Sequential( # ResNet-50, 101 nn.Conv2d(256, 64, 1, bias=False), nn.Conv2d(64, 64, 3, padding=1, bias=False), nn.Conv2d(64, 256, 1, bias=False))n_weights(basic), n_weights(neck) # 1,179,648 69,632Squeeze, convolve, expand
- down to a quarter, there, back up.
- BN after every convolution; ReLU after the first two, and once more after the add.
- The skip joins the wide ends: 256 channels in, 256 out.
Against the basic block
- Basic block (ResNet-18, 34): two layers, weights.
- Bottleneck with a quarter width: weights, 17 times fewer.
- Both end in the same skip and add; only the layers between differ.
The inverted bottleneck
PyTorch
class InvertedResidual(nn.Module): # MobileNetV2 def __init__(self, c=24, t=6): super().__init__() h = c * t # 144 self.block = nn.Sequential( nn.Conv2d(c, h, 1, bias=False), nn.BatchNorm2d(h), nn.ReLU6(), nn.Conv2d(h, h, 3, padding=1, groups=h, bias=False), nn.BatchNorm2d(h), nn.ReLU6(), nn.Conv2d(h, c, 1, bias=False), nn.BatchNorm2d(c)) # linear: no ReLU def forward(self, x): return x + self.block(x)# the same two widths, in opposite orderneck = [nn.Conv2d(96, 24, 1), # squeeze nn.Conv2d(24, 24, 3, padding=1), # 5,184 nn.Conv2d(24, 96, 1)] # expandinv = [nn.Conv2d(24, 96, 1), # expand nn.Conv2d(96, 96, 3, padding=1, groups=96), # 864 nn.Conv2d(96, 24, 1)] # project# the skip: 96 channels above, 24 below# the last ReLU: after the add above, none belowclass ConvNeXtBlock(nn.Module): def __init__(self, c=96): super().__init__() self.dw = nn.Conv2d(c, c, 7, padding=3, groups=c) self.norm = nn.LayerNorm(c) self.up = nn.Linear(c, 4 * c) # a 1 x 1 conv self.down = nn.Linear(4 * c, c) def forward(self, x): # (N, C, H, W) y = self.dw(x).permute(0, 2, 3, 1) y = self.down(F.gelu(self.up(self.norm(y)))) return x + y.permute(0, 3, 1, 2)Expand, filter, project
- up by a factor (6 here), depth-wise, back down.
- No ReLU after the projection: a linear bottleneck.
- The skip joins the narrow ends, and only when stride is 1 and the shapes match.
The same widths, the other way round
- Classic: wide, narrow, wide. Inverted: narrow, wide, narrow.
- The layer moves from the narrow part to the wide part, and becomes depth-wise.
- The skip and the memory it needs follow the narrow ends.
ConvNeXt: the large kernel first
- Depth-wise on the narrow tensor, then up by 4 and down.
- One LayerNorm and one GELU in the block, as in a transformer's FFN.
- Moving the depth-wise layer up lets the large kernel run on few channels.
Ghost module
PyTorch
class GhostModule(nn.Module): def __init__(self, c, n, k=3, s=2, d=3): super().__init__() m = n // s # intrinsic maps self.primary = nn.Sequential( # ordinary conv nn.Conv2d(c, m, k, padding=k // 2), nn.BatchNorm2d(m), nn.ReLU()) self.cheap = nn.Sequential( # a filter per map nn.Conv2d(m, m * (s - 1), d, padding=d // 2, groups=m), nn.BatchNorm2d(m * (s - 1)), nn.ReLU()) def forward(self, x): y = self.primary(x) # (N, m, H, W) g = self.cheap(y) # the ghosts return torch.cat([y, g], 1) # (N, n, H, W)y = intrinsic # (1, 1, 5, 5): one mapphi = torch.tensor([[0., 1, 0], [1., 0, 1], [0., 1, 0]]).view(1, 1, 3, 3)ghost = F.conv2d(y, phi, padding=1) # 9 weights# an ordinary conv reads all 48 input channels# for one output map: 3 * 3 * 48 = 432 weights# in GhostNet's blocks the primary conv is 1 x 1Most maps for almost nothing
- An ordinary conv makes only intrinsic maps. Each gets ghosts from a depthwise filter.
- Weights fall by about : 41,472 becomes 21,168 for . Biases and batch norm are not counted.
- Why it can work: many maps of a trained net are near copies, so a cheap filter can stand in for a full conv.
A ghost, by hand
- A ghost is one intrinsic map through one filter: 9 weights. An ordinary conv map costs .
- The paper's tests use and . In GhostNet's blocks the primary conv is .
- The cost: ghosts carry no information that the intrinsic maps lack. BN and ReLU are left out here.
Dense connectivity
PyTorch
class DenseLayer(nn.Module): # BN, ReLU, conv; twice def __init__(self, c_in, k=32): super().__init__() self.f = nn.Sequential( nn.BatchNorm2d(c_in), nn.ReLU(), nn.Conv2d(c_in, 4 * k, 1, bias=False), nn.BatchNorm2d(4 * k), nn.ReLU(), nn.Conv2d(4 * k, k, 3, padding=1, bias=False)) def forward(self, x): # x: the stack return torch.cat([x, self.f(x)], dim=1)block = nn.Sequential(*[DenseLayer(64 + 32 * i) for i in range(6)])block(torch.randn(1, 64, 56, 56)).shape # 256 channels# plain: x = f(x)# residual: x = x + f(x) # added: width stays# dense: x = torch.cat([x, f(x)], 1) # width growsdef connections(L, kind): return {"plain": L, "residual": 2 * L, "dense": L * (L + 1) // 2}[kind]connections(6, "dense") # 21Every layer adds to the stack
- Layer reads the concatenation of everything before it: channels.
- It adds only channels, the growth rate. A layer first cuts its input to .
- Between dense blocks a transition layer halves the channels and pools .
Plain, residual, dense
- Residual: , added, the width stays. Dense: , concatenated, the width grows.
- layers have connections: 21 for six.
- Every layer has a short path to the input and to the loss; features are reused instead of relearned.
Cross-stage partial connections
PyTorch
import torch, torch.nn as nnclass CSPStage(nn.Module): def __init__(self, block): # block: the stage body super().__init__() self.block = block # sees half the channels def forward(self, x): a, b = x.chunk(2, dim=1) # split the channels b = self.block(b) # only this half goes in return torch.cat([a, b], 1) # joined at the end# dense block: 4 layers, growth 32, 3 x 3 (9 * 32 = 288)w = lambda c: sum(288 * (c + 32 * i) for i in range(4))print(w(64), w(32)) # 129024 92160Half the channels go round the stage
- Normally the blocks of a stage process every channel of its input; in a dense block each layer re-reads all of it.
- Cross-stage partial (CSPNet): split the input channels in two, send one half through the blocks, and concatenate at the end of the stage.
- The paper reports about 20% less computation on ImageNet at equal or better accuracy. Here: a toy dense block, transition layers not counted.
Upsampling
PyTorch
x = torch.tensor([[16., 32, 0], [48, 16, 32], [0, 48, 16]])[None, None]F.interpolate(x, scale_factor=2, mode="nearest")F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)up = nn.Upsample(scale_factor=2, mode="bilinear")up(x).shape # (1, 1, 6, 6)up = nn.ConvTranspose2d(1, 1, kernel_size=2, stride=2, bias=False)x = torch.tensor([[1., 2], [3, 1]])[None, None]up(x).shape # (1, 1, 4, 4)# (n - 1) * s + k = (2 - 1) * 2 + 2 = 4up3 = nn.ConvTranspose2d(1, 1, 3, stride=2)up3(x).shape # (1, 1, 5, 5)# or: upsample, then an ordinary convolutionnn.Sequential(nn.Upsample(scale_factor=2), nn.Conv2d(1, 1, 3, padding=1))Nearest and bilinear
- Nearest: each cube is repeated. Fast, and blocky.
- Bilinear: each new cube is a weighted mean of up to four neighbours; the weights are distances.
- Neither has any weights. Click a cube of the large grid to see its sum.
Transposed convolution
- Each input cube stamps kernel into the output, a stride apart.
- Output size: . U-Net uses , : no overlap.
- Where stamps overlap they add, which can leave a checkerboard: one reason to prefer upsample then convolve.
Pixel shuffle and unshuffle
PyTorch
import torch, torch.nn.functional as Fdef pixel_shuffle(x, r): # x: (B, C*r*r, H, W) B, Crr, H, W = x.shape C = Crr // (r * r) x = x.view(B, C, r, r, H, W) # channel: c, i, j x = x.permute(0, 1, 4, 2, 5, 3) # (B, C, H, i, W, j) return x.reshape(B, C, H * r, W * r)x = torch.randn(2, 4, 3, 3)y = pixel_shuffle(x, 2) # (2, 1, 6, 6)assert torch.equal(y, F.pixel_shuffle(x, 2))# y[b, c, r*h+i, r*w+j] == x[b, c*r*r + r*i+j, h, w]back = F.pixel_unshuffle(y, 2) # (2, 4, 3, 3) == ximport torch, torch.nn.functional as Fx = torch.randn(1, 64, 32, 32)pool = F.max_pool2d(x, 2) # (1, 64, 16, 16)un = F.pixel_unshuffle(x, 2) # (1, 256, 16, 16)# un[b, 4*c + 2*i + j, h, w] == x[b, c, 2*h+i, 2*w+j]assert torch.equal(F.pixel_shuffle(un, 2), x)# nothing is lost, so a convolution can choosedown = torch.nn.Conv2d(256, 128, 3, padding=1)(un)# a ViT patch embedding is this with r = 16tok = F.pixel_unshuffle(torch.randn(1, 3, 224, 224), 16)print(tok.shape) # (1, 768, 14, 14)import torch, torch.nn as nndef icnr_(w, r): # w: (C*r*r, cin, k, k) sub = torch.empty(w.shape[0] // r**2, *w.shape[1:]) nn.init.kaiming_normal_(sub) # one kernel per C with torch.no_grad(): # copied r*r times w.copy_(sub.repeat_interleave(r**2, dim=0))class SubPixelUp(nn.Module): def __init__(self, cin, C, r=2): super().__init__() self.conv = nn.Conv2d(cin, C * r * r, 3, 1, 1) icnr_(self.conv.weight, r) self.ps = nn.PixelShuffle(r) def forward(self, x): # (B, cin, H, W) return self.ps(self.conv(x)) # (B, C, rH, rW)Channel to space
- Pixel shuffle: . Nothing is computed and nothing is lost.
- PyTorch's rule: output is input . A channel is a sub-pixel position.
- The numbers here are labels, 1 to 36, so that each one can be followed.
Space to channel
- Pixel unshuffle: , the exact inverse; also called space to depth.
- A downsampling that loses nothing. SPD-Conv uses it, with an unstrided convolution, in place of strides and pooling.
- InternVL merges visual tokens with it: 1,024 per tile become 256. A ViT patch embedding is an unshuffle with , then a linear map.
Four kernels, four sub-pixels
- Sub-pixel convolution (ESPCN): convolve on the small grid, then shuffle. Every weight works at low resolution.
- Unrelated kernels give a checkerboard. ICNR starts all as copies of one: nearest-neighbour upsampling.
- Nearest and bilinear are special cases, and it can be rewritten as a transposed convolution with stride . The weights here are a toy, in sixteenths.
U-Net
PyTorch
def forward(self, x): # (N, 3, H, W) s0 = self.enc0(x) # 64, H s1 = self.enc1(F.max_pool2d(s0, 2)) # 128, H/2 s2 = self.enc2(F.max_pool2d(s1, 2)) # 256, H/4 b = self.mid(F.max_pool2d(s2, 2)) # 512, H/8 d2 = self.dec2(torch.cat([s2, self.up2(b)], 1)) d1 = self.dec1(torch.cat([s1, self.up1(d2)], 1)) d0 = self.dec0(torch.cat([s0, self.up0(d1)], 1)) return self.head(d0) # (N, K, H, W)# enc*, mid, dec*: two 3 x 3 convs (padding 1), ReLU# up*: ConvTranspose2d(2 * c, c, 2, stride=2)# head: Conv2d(64, K, 1)r, j = 1, 1 # view, grid step (pixels)for level in range(4): if level: r, j = r + j, 2 * j # 2 x 2 max-pool r += 2 * j # 3 x 3 conv r += 2 * j # 3 x 3 conv print(level, r, j)# 0: 5, 1 1: 14, 2 2: 32, 4 3: 68, 8# up-conv (k = 2, stride 2): no overlap, r stays# on the way up: 68 -> 84 -> 92 -> 96, at step 1x = img # (1, 1, 16, 16): 0 or 1c = F.avg_pool2d(x, 4) # bright share per blockdeep = (c >= 0.25).float() # keep a block or notup = F.interpolate(deep, scale_factor=4) # blockyboth = torch.cat([x, up], 1) # the skip: two channelsw = torch.ones(1, 2, 1, 1) # a 1 x 1 conv: 1 and 1mask = F.relu(F.conv2d(both, w) - 1) # both say yesDown, across and up
- Encoder: two convs, then a max-pool. The size halves, the channels double.
- Decoder: an up-conv doubles the size, the encoder's volume of that size is concatenated, two convs mix them.
- Four levels and padded convs here. The original has five, up to 1024 channels, and crops the copies.
What each level sees
- A conv widens a feature's view by 2 grid steps; a pool doubles the step. Views: 5, 14, 32, 68 pixels.
- Deep levels see whole cells and their neighbours, but place them only to 2, 4 or 8 pixels.
- After the way up an output pixel has seen pixels on the full grid. The cells are a sketch, to scale.
What the skip carries
- The deep path knows what is there and roughly where. The skip knows exactly where.
- The toy: blocks with mean are kept, then at every pixel.
- Deep alone: 23 pixels wrong. Skip alone: 7. Both: 0. The rules are fixed here; a U-Net learns them.
U-Net++
PyTorch
def forward(self, x): x00 = self.c00(x) x10 = self.c10(self.pool(x00)) x01 = self.c01(cat([x00, self.up(x10)])) x20 = self.c20(self.pool(x10)) x11 = self.c11(cat([x10, self.up(x20)])) x02 = self.c02(cat([x00, x01, self.up(x11)])) x30 = self.c30(self.pool(x20)) x21 = self.c21(cat([x20, self.up(x30)])) x12 = self.c12(cat([x10, x11, self.up(x21)])) x03 = self.c03(cat([x00, x01, x02, self.up(x12)])) return self.head(x03)# cat = lambda v: torch.cat(v, 1); up: bilinear, x 2# cXY: two 3 x 3 convs, ReLU; pool: 2 x 2 max# the view of a node: its widest input, plus its own# two 3 x 3 convs on a grid of step 2 ** idef view(i, j): if j == 0: # the encoder return (5, 14, 32, 68)[i] ins = [view(i, k) for k in range(j)] ins.append(view(i + 1, j - 1)) # from below return max(ins) + 4 * 2 ** i# x03 merges views of 5, 18, 44 and 92 pixels# U-Net's last node merges only 5 and 92# training: a head and a loss on every top nodetops = (x01, x02, x03)outs = [h(v) for h, v in zip(self.heads, tops)]loss = sum(crit(o, y) for o in outs) / 3# inference, pruned to depth 2: stop at x02def forward_l2(self, x): x00 = self.c00(x) x10 = self.c10(self.pool(x00)) x01 = self.c01(cat([x00, self.up(x10)])) x20 = self.c20(self.pool(x10)) x11 = self.c11(cat([x10, self.up(x20)])) x02 = self.c02(cat([x00, x01, self.up(x11)])) return self.heads[1](x02)Nodes in the gap
- Node : level , place along it. is the encoder; U-Net is the outer V.
- reads and the upsampled , all concatenated.
- Four levels and bilinear upsampling here. Click a node to see the channels it reads.
Smaller steps to merge
- U-Net's last node merges a view with a view: the semantic gap.
- U-Net++ puts views of 18 and 44 pixels between them, so each merge joins features that are more alike.
- Views count convs and pools; upsampling is taken as nearest. The view stands in for how abstract a feature is.
One network, every depth
- Deep supervision: a head and a loss on every with .
- The head on needs only the nodes with . Pruning cuts the rest at inference.
- Reported for the five-level net: 3.9 IoU points over U-Net on average, on four medical tasks.
Feature pyramid
PyTorch
class FPN(nn.Module): # on C2..C5 of a ResNet def __init__(self, cs=(256, 512, 1024, 2048), d=256): super().__init__() self.lat = nn.ModuleList( # lateral, 1 x 1 nn.Conv2d(c, d, 1) for c in cs) self.out = nn.ModuleList( # after the sum nn.Conv2d(d, d, 3, padding=1) for _ in cs) def forward(self, cs): # [C2, C3, C4, C5] m = self.lat[3](cs[3]) # the top: from C5 ps = [self.out[3](m)] # P5 for i in (2, 1, 0): up = F.interpolate(m, scale_factor=2) m = self.lat[i](cs[i]) + up # add ps.insert(0, self.out[i](m)) # P4, P3, P2 return psdef level(w, h, k0=4): # which Pk reads a box s = math.sqrt(w * h) k = math.floor(k0 + math.log2(s / 224)) return min(5, max(2, k))# 56 -> P2 112 -> P3 224 -> P4 448 -> P5stride = 2 ** level(w, h) # 4, 8, 16 or 32cells = w / stride # 14 to 28 a side# RPN anchors: one size per level, three shapes# P2 32, P3 64, P4 128, P5 256, P6 512 pixelsMeaning at every size
- Bottom-up: the backbone's , strides 4 to 32. Lateral: a conv to 256 channels.
- Top-down: upsample by 2 (nearest) and add. A conv on each sum gives . No non-linearities.
- Why: is sharp but shallow, deep but coarse. After the sums every level is both, at little extra cost.
A level for every size
- A box is read from , , held between 2 and 5.
- So a box of 56 to 896 pixels covers 14 to 28 cells a side; RoI pooling makes of them.
- RPN anchors: on up to on , three shapes each. is subsampled, for the RPN only.
ASPP: atrous spatial pyramid pooling
PyTorch
class ASPP(nn.Module): def __init__(self, cin, c=256, rates=(6, 12, 18)): super().__init__() self.b = nn.ModuleList([nn.Conv2d(cin, c, 1)] + [ nn.Conv2d(cin, c, 3, padding=r, dilation=r) for r in rates]) # same size out self.gap = nn.AdaptiveAvgPool2d(1) self.gconv = nn.Conv2d(cin, c, 1) self.fuse = nn.Conv2d(c * (len(rates) + 2), c, 1) def forward(self, x): g = self.gconv(self.gap(x)) # (B, c, 1, 1) g = F.interpolate(g, x.shape[2:]) # one for all y = [b(x) for b in self.b] + [g] return self.fuse(torch.cat(y, 1)) # 5c -> cFive branches read one feature map
- Objects come in many sizes, and one kernel has one. Dilation makes the same nine weights reach further.
- ASPP (DeepLab): a branch, three branches with rates 6, 12, 18, and a pooled branch, concatenated and fused by a .
- A rate too large for the map leaves only the centre tap: a in disguise, so the pooled branch supplies the global view. The rates double at output stride 8.
One kernel, every place
PyTorch
conv = nn.Conv2d(1, 1, 3, bias=False)w = conv.weight[0, 0] # the nine weightsx = torch.randn(1, 1, 6, 9)y = conv(x) # (1, 1, 4, 7)# every output: the same w on another windowy[0, 0, 2, 3] == (x[0, 0, 2:5, 3:6] * w).sum()# so one weight hears from all 28 placesy.sum().backward()# conv.weight.grad[0, 0, 0, 0] is x[0, 0, :4, :7].sum()4 * 7 * 9 # 252 if not sharedx = torch.zeros(1, 1, 6, 9)x[0, 0, 1:4, 1:4] = torch.tensor( [[0., 2, 0], [2, 3, 2], [0, 2, 0]])y = conv(x)x2 = torch.roll(x, shifts=2, dims=3) # 2 to the righty2 = conv(x2)torch.allclose(y2[..., 2:], y[..., :-2]) # Truey.amax(dim=(2, 3)) == y2.amax(dim=(2, 3)) # Trueconv.weight.numel() # 94 * 7 * 9 # 252 if not sharedfc = nn.Linear(6 * 9, 4 * 7, bias=False)fc.weight.numel() # 1,512# the conv's 9 do not grow with the imagebig = torch.randn(1, 1, 600, 900)conv(big).shape # (1, 1, 598, 898)The same nine weights, 28 times
- Weight sharing: one kernel, the same weights at every place.
- Each weight multiplies a different cube at each place: 28 here.
- In training, a weight collects a gradient from every place it was used.
Shift the input, the output shifts
- Shift the input by cubes and the output shifts by cubes: equivariance.
- It holds because the kernel is the same at every place.
- Pooling over the response forgets the place: invariance, so the label stays.
What sharing saves
- Convolution: weights, whatever the size of the feature.
- Fully connected: inputs times outputs. Here 1,512 against 9.
- Fewer weights to learn, and what is learned at one place works at all.
Why convolutions suit images
PyTorch
def corr_at(img, d): # pixels d apart a = torch.cat([img[:, :-d].flatten(), img[:-d, :].flatten()]) b = torch.cat([img[:, d:].flatten(), img[d:, :].flatten()]) return torch.corrcoef(torch.stack([a, b]))[0, 1]# the toy image: 0.84 at d = 1, 0.51 at 2, 0.02 at 4conv = nn.Conv2d(1, 8, 3, padding=1) # reads d <= 1# deeper layers widen the view: 5 x 5, then 7 x 7def shift(t, d): # d cubes right, zeros in return F.pad(t, (d, 0))[..., :t.shape[-1]]a = F.conv2d(shift(x, 2), w, padding=1) # shift, convb = shift(F.conv2d(x, w, padding=1), 2) # conv, shifttorch.equal(a, b) # True# holds while the pattern stays inside the bordera = F.conv2d(shift(x, 1), w, stride=2, padding=1)r = F.conv2d(x, w, stride=2, padding=1)any(torch.equal(a, shift(r, d)) for d in range(4))# False: with stride 2, one pixel is no shift at allr = F.relu(F.conv2d(x, w, padding=1) - 2) # a detectorlocal = F.max_pool2d(r, 2) # 2 x 2 windowglob = r.amax(dim=(2, 3)) # one number# shift x by one cube: r moves by one cube.# local is unchanged while the peak stays in its# window; glob while the pattern is inside the imagelogits = head(glob) # the labelfc = nn.Linear(25, 25, bias=False) # 625 free weightsconv = nn.Conv2d(1, 1, 3, padding=1, bias=False) # 9W = torch.zeros(25, 25) # the conv, as that matrixfor i in range(25): # output unit for j in range(25): # input pixel dy, dx = j // 5 - i // 5, j % 5 - i % 5 if abs(dy) <= 1 and abs(dx) <= 1: # locality W[i, j] = conv.weight[0, 0, dy + 1, dx + 1](W != 0).sum() # 169 places, 9 values# W @ x.flatten() equals conv(x).flatten()Locality: neighbours belong together
- Locality: nearby pixels are related, distant ones hardly. Here the correlation is 0.84 one pixel apart and 0.02 four apart.
- So a unit may read a small window: a kernel takes the 9 most related of the 256 pixels.
- Wider relations come with depth, as each layer widens the view. A toy image; photographs behave alike.
Equivariance, and where it stops
- Translation equivariance: . Shift the input and the feature map shifts with it.
- It follows from weight sharing, and holds while the pattern stays inside the border.
- With stride only shifts by multiples of carry over: one pixel can change the output.
Invariance: local or global
- Translation invariance: . The answer does not move at all.
- Max-pooling forgives a shift of one cube only while the peak stays in its window.
- Pooling everything, on an equivariant map, forgives every shift that keeps the pattern inside.
Inductive bias: what is assumed
- An inductive bias is what a model assumes before it sees data. Here: zeros (locality) and ties (sharing) in the weights.
- 625 free weights fully connected, 169 with locality alone, 9 as a convolution.
- Fewer weights need less data, if the assumptions hold. Vision transformers assume less and need more data.
Into the classifier
PyTorch
x = torch.randn(1, 4, 2, 3) # last feature volumepooled = x.mean(dim=(2, 3)) # (1, 4)pooled = nn.AdaptiveAvgPool2d(1)(x).flatten(1)flat = x.flatten(1) # (1, 24)head = nn.Sequential( # ResNet-50 nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(2048, 1000))head[2].weight.numel() # 2,048,000vgg_fc = nn.Linear(512 * 7 * 7, 4096) # VGG-16vgg_fc.weight.numel() # 102,760,448Global average pooling, or flatten
- Global average pooling: one mean per channel, so becomes .
- Flatten: every number kept, of them, read channel by channel and row by row.
- Pooling works for any image size; flatten fixes the input size of the model.
What the classifier costs
- A linear classifier has inputs times classes weights.
- ResNet-50 pools to 2,048: 2.0M weights for 1,000 classes.
- VGG-16 flattens to 25,088 and feeds 4,096 units: 102.8M weights, most of the network.
Convolution as a matrix product
PyTorch
x = torch.randn(1, 1, 4, 4)w = torch.randn(1, 1, 3, 3) # one kernelcols = F.unfold(x, kernel_size=3) # (1, 9, 4)out = w.view(1, -1) @ cols # (1, 1, 4)y = out.view(1, 1, 2, 2) # fold backtorch.allclose(y, F.conv2d(x, w)) # TrueWindows as rows, kernel as a column
F.unfold(x, 3)writes every window as a column of numbers (drawn here as rows).- The weight tensor is reshaped to : one row per kernel.
- One matrix product then computes every place and every kernel at once.
- The result is folded back to .
- This is why a convolution is as fast as the matrix multiply underneath it.
- Drag Window to unroll by hand.
Squeeze-and-excitation
PyTorch
class SE(nn.Module): def __init__(self, c, r=16): super().__init__() self.fc1 = nn.Linear(c, c // r) self.fc2 = nn.Linear(c // r, c) def forward(self, x): # (N, C, H, W) z = x.mean(dim=(2, 3)) # squeeze s = torch.sigmoid(self.fc2(F.relu(self.fc1(z)))) return x * s[:, :, None, None] # exciteOne factor per channel
- Squeeze: global average pooling, one number per channel.
- Excite: two small fully connected layers and a sigmoid, one factor per channel.
- The first layer is narrower by a ratio (16 in SENet), which keeps the branch cheap.
- Every cube of channel is multiplied by : attention over channels.
- The factors depend on the image, unlike the weights of the convolution.
- Thick lines are large weights, brown ones negative. The factors are sigmoids rounded to one decimal.
Channel attention
PyTorch
class ChannelAttention(nn.Module): # CBAM def __init__(self, c, r=16): super().__init__() self.mlp = nn.Sequential( # shared nn.Linear(c, c // r), nn.ReLU(), nn.Linear(c // r, c)) def forward(self, x): # (N, C, H, W) a = self.mlp(x.mean(dim=(2, 3))) # the means m = self.mlp(x.amax(dim=(2, 3))) # the maxima s = torch.sigmoid(a + m) # (N, C) return x * s[:, :, None, None]Mean and maximum, one MLP
- Channel attention (CBAM): one factor per channel, from its mean and its largest value.
- Both go through the same small MLP; the two results are added before the sigmoid.
- With the mean alone it is squeeze-and-excitation. The weights here are picked to be easy to follow.
Spatial attention
PyTorch
class SpatialAttention(nn.Module): # CBAM def __init__(self, k=7): super().__init__() self.conv = nn.Conv2d(2, 1, k, padding=k // 2, bias=False) def forward(self, x): # (N, C, H, W) a = x.mean(dim=1, keepdim=True) # (N, 1, H, W) m = x.amax(dim=1, keepdim=True) # (N, 1, H, W) s = self.conv(torch.cat([a, m], dim=1)) return x * torch.sigmoid(s) # one maskOne mask value per place
- Spatial attention: one mask value per place, shared by all channels.
- Pool across the channels (mean and largest), run a kernel over the two maps, apply a sigmoid.
- CBAM uses a kernel; here so that a score can be checked by hand.
CBAM
PyTorch
class CBAM(nn.Module): def __init__(self, c, r=16, k=7): super().__init__() self.channel = ChannelAttention(c, r) self.spatial = SpatialAttention(k) def forward(self, x): x = self.channel(x) # which channels return self.spatial(x) # which places# in a ResNet block: on the branch, before the add# out = F.relu(x + cbam(bn3(conv3(y))))Channels first, then places
- , then : channels first, then places.
- It sits on the residual branch of a block, just before the add.
- Cheap: a small MLP and one kernel per block. Cubes here are rounded to one decimal.
Efficient channel attention
PyTorch
class ECA(nn.Module): def __init__(self, c, gamma=2, b=1): super().__init__() t = int(abs((math.log2(c) + b) / gamma)) k = t if t % 2 else t + 1 # odd: 3, 5, 7 self.conv = nn.Conv1d(1, 1, k, padding=k // 2, bias=False) def forward(self, x): # (N, C, H, W) z = x.mean(dim=(2, 3)) # (N, C) s = torch.sigmoid(self.conv(z[:, None]))[:, 0] return x * s[:, :, None, None] # k weightsA kernel along the channels
- ECA: a 1D kernel over the channel means replaces the MLP of squeeze-and-excitation.
- No narrow layer: every channel keeps a direct line to its own factor.
- The kernel size follows the channel count: for 64 channels, 5 for 256, 7 for 2048.
Coordinate attention
PyTorch
class CoordAtt(nn.Module): def __init__(self, c, m): # m = max(8, c // 32) super().__init__() self.f1 = nn.Sequential(nn.Conv2d(c, m, 1), nn.BatchNorm2d(m), nn.Hardswish()) self.fh = nn.Conv2d(m, c, 1) self.fw = nn.Conv2d(m, c, 1) def forward(self, x): # (N, C, H, W) zh = x.mean(3, keepdim=True) # (N, C, H, 1) zw = x.mean(2, keepdim=True).transpose(2, 3) f = self.f1(torch.cat([zh, zw], 2)) fh, fw = f.split(x.shape[2:], 2) gh = self.fh(fh).sigmoid() # one per row gw = self.fw(fw).sigmoid().transpose(2, 3) return x * gh * gw # row x columnA factor for every row and every column
- Coordinate attention: pool each channel along its rows and along its columns, so the place survives in two profiles.
- A shared conv, a conv per direction, a sigmoid: .
- MobileNetV2 on ImageNet: 72.3 plain, 73.5 with SE, 73.6 with CBAM, 74.3 with this. A toy here: averages two channels, factors are rounded.
Stabilization
PyTorch
import torch, torch.nn as nnconv = nn.Conv2d(64, 128, 3)fan_in = 64 * 3 * 3 # 576 inputs per unitnn.init.kaiming_normal_(conv.weight, nonlinearity="relu")print(conv.weight.var() * fan_in) # about 2x = torch.randn(1024, 128) # 20 ReLU layersfor g in (1.0, 2.0, 4.0): h = x for _ in range(20): w = torch.randn(128, 128) * (g / 128) ** 0.5 h = torch.relu(h @ w) print(g, (h.pow(2).mean() / x.pow(2).mean()).sqrt())# roughly 0.001, 1 and 1000import torch, torch.nn.functional as Fz = torch.randn(10000, requires_grad=True)leaky = lambda t: F.leaky_relu(t, 0.1)for name, f in [("relu", F.relu), ("leaky", leaky), ("gelu", F.gelu), ("silu", F.silu)]: z.grad = None f(z).sum().backward() dead = (z.grad == 0).float().mean() print(name, round(dead.item(), 2))# relu 0.5 leaky 0.0 gelu 0.0 silu 0.0import torch, torch.nn as nnx = torch.randn(8, 64, 32, 32) # (N, C, H, W)bn = nn.BatchNorm2d(64) # in training modem = x.mean(dim=(0, 2, 3), keepdim=True) # over N, H, Wv = x.var(dim=(0, 2, 3), keepdim=True, unbiased=False)# m, v: shape (1, 64, 1, 1), one pair per channelxh = (x - m) / (v + bn.eps).sqrt() # centre, then scaleg = bn.weight.view(1, -1, 1, 1) # gamma, starts at 1b = bn.bias.view(1, -1, 1, 1) # beta, starts at 0assert torch.allclose(bn(x), g * xh + b, atol=1e-5)# bn also keeps running averages of m and v for eval()import torch, torch.nn as nnx = torch.randn(2, 4, 2, 2) # (N, C, H, W)x.mean(dim=(0, 2, 3)) # batch: over N, H, Wx.mean(dim=(1, 2, 3)) # layer: over C, H, Wx.mean(dim=(2, 3)) # instance: over H, Wx.view(2, 2, 2, 2, 2).mean(dim=(2, 3, 4)) # groupnorms = {"batch": nn.BatchNorm2d(4), "layer": nn.GroupNorm(1, 4), "instance": nn.InstanceNorm2d(4), "group": nn.GroupNorm(2, 4)}x2 = x.clone(); x2[1] *= 3 # change image 2for name, f in norms.items(): # image 1 the same? print(name, torch.allclose(f(x)[0], f(x2)[0]))# batch False, the rest True; batch in eval(): TrueInitialization: start at the right scale
- With ReLU a layer keeps the size of its signal only if , with the fan-in: He initialization.
- For a convolution . Too small and the signal fades with depth; too large and it blows up, and the gradients with it.
- Computed in the page: 20 ReLU layers of 128 units, one fixed random seed. Skips and normalization make a network less sensitive to this.
Activation: the bend and its slope
- ReLU: cheap, and no saturation on the right; but a unit at zero passes no gradient.
- Leaky ReLU keeps a small slope on the left: 0.1 here, 0.01 by default in PyTorch.
- GELU, , and SiLU, , are smooth and dip just below zero. ConvNeXt uses GELU, EfficientNet SiLU.
Batch norm: one channel, across the batch
- A batch of feature maps has four axes, : here . Batch norm pools over , , , so each channel gets one mean and one variance.
- , then with a learned scale and shift per channel. The , shown are toy values.
- Whatever scale a channel arrives with, the next layer sees mean 0 and deviation 1 at the start: that keeps deep stacks trainable.
Normalization: which axes share a mean
- Batch norm pools over ; layer norm over ; instance norm over ; group norm over and a group of channels.
- Only batch norm looks across the batch, so in training an image's output depends on the other images. At inference it uses stored averages (here: those of the batch as it came).
- That fixed affine map folds into the convolution before it. The other three behave the same in training and at inference. Numbers here are rounded to one decimal.