Table of contents

    Eight axes of block design

    CNNsMap1 / 1
    Eight axesA star of eight coloured spokes round a small feature volume, four pointing up and four down. Each spoke is one axis of block design and carries its name at the outer end: spatial mixing, channel mixing, information flow, dimensional transformation, spatial resolution, feature modulation, multi-scale representation and stabilization, clockwise from the lower left. The blocks and operations sit along their spoke as labelled dots, from the centre outward; a filled dot has a slide in this deck and a hollow dot has none yet. The spokes are drawn one after another. When a block is marked, the blocks on other spokes that it is built from, or that are built from it, keep their colour and get a ring while the rest fade, and a button opens the slide of the marked block.Every block answers one of eight questions
    Eight axes

    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 y

    Every 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

    CNNsConvolution1 / 3
    1DBlocks of cubes, one number on the front of each cube. A green kernel block moves onto the blue feature block, the cubes it covers turn green, and a row below shows the covered numbers, the kernel's numbers, their products and the sum, which lands in the next cube of the output block. A slider moves the kernel to any position; clicking an output cube does the same; in the last step chips bring another channel of the volume to the front.1D: slide, multiply, add2D: the same over a gridConv2D: a kernel as deep as the feature
    1D

    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

    CNNsFilter bank1 / 1
    Filter bankThe feature volume as a block of cubes; beside it a column of small kernel blocks in different colours, each with an arrow to the flat grid of numbers it gives; the grids then move into one stacked block, a slab per kernel in the kernel's colour, which is the output volume. A dashed frame gathers the kernels into the filter bank and a line gives its shape and the number of weights. A slider sets how many kernels there are; clicking a kernel brings its channel to the front of the output.Many kernels, one output channel each
    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())   # 84

    Many 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

    CNNsPoint-wise1 / 2
    One kernelA feature volume of cubes and a kernel that is a single column of cubes running into the depth. The kernel visits every pixel; a row below shows the numbers of all channels at that pixel, the kernel's weights, the products and their sum, and the output block, as high and as wide as the input, fills in. In the second step the kernels are drawn as the rows of a small matrix of numbers, and the output volume has one slab per row; a slider sets the number of kernels and clicking a pixel or a row shows that sum.A kernel one cube wideA bank of them is a small matrix
    One kernel

    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 bottleneck

    A 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

    CNNsDepth-wise separable1 / 3
    Depth-wiseThe feature volume drawn as coloured slabs, one colour per channel. The slabs move apart into four rows; each row has its own flat kernel in the same colour and the grid that kernel gives, with a frame showing where the kernel sits; the grids are then stacked again. In the second step that stack goes through a matrix of 1 × 1 kernels into an output volume with a slab per kernel. The last step draws every weight of a standard layer and of the separable pair as a cube, with the two counts as bars; a slider sets the number of output channels and chips set the kernel size.Depth-wise: a flat kernel per channelPoint-wise: a 1 × 1 bank mixes themWhy: count the weights
    Depth-wise

    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,536

    Depth-wise: a flat kernel per channel

    • Each channel gets its own flat kernel: groups=C_in in 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

    CNNsTerminology1 / 3
    StemBlocks of cubes drawn to scale with real layer sizes. First an image as a wide, almost flat block that becomes a smaller and deeper block after a strided convolution and again after a pooling layer, with a bar under each for the number of places a kernel must visit; chips switch between the ResNet stem and the one-step ConvNeXt stem. Then a ResNet-50 block as four volumes, deep, thin, thin and deep, with the weight count of each of its three layers and two bars comparing the block with one plain layer; a slider sets the width of the thin part. Last, the four stages of a ResNet as pairs of blocks, the narrow layer above its output, with the ratio beside each; chips switch to the ResNets without a bottleneck.An aggressive stemA bottleneckThe expansion factor
    Stem

    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

    CNNsKernel placement1 / 1
    Stride, padding, dilationA 7 by 7 grid of cubes with a number on each, a 3 by 3 kernel shown as a green frame with its nine taps tinted, and the output grid, which fills as the kernel scans. With stride 2 the frame jumps two cubes at a time; with padding a ring of zero cubes surrounds the grid and the frame hangs over the edge; with dilation the nine taps spread apart inside a larger frame. Three groups of chips set the stride, the padding and the dilation, a slider moves the kernel, and a panel beside the figure holds the three settings and, under them, the output-size formula with the current settings filled in; a term that has just changed is lit for a moment.Where the kernel may sit
    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)                 # 5

    Where 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

    CNNsDeformable1 / 1
    Taps that moveA feature map 13 cells wide and 7 high with a thin slanted stroke across it: dark cells marked 8 where the stroke crosses the middle of a cell, and pairs of lighter cells marked 4 where it runs between two rows. A dashed square marks the 3 by 3 window of a standard kernel and nine green dots mark where the kernel reads. For the standard kernel the dots sit in the square; for the dilated one they move apart on a wider square; for the deformable one each dot travels along a thin line to a place on the stroke, so that the nine dots line up along it. At the right a 3 by 3 block shows the nine values read and a cube shows their sum. For a marked tap, a note says how far it was moved and, when it lands between two rows, a frame marks the two cells it is interpolated from and the sum is written out. A slider moves the kernel along the stroke.Every tap gets an offset of its own
    Taps that move

    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 sampling

    Every 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

    CNNsReceptive field1 / 2
    Receptive fieldFour grids of cubes from left to right: the input and the outputs of three stacked 3 by 3 layers, each grid two cubes smaller than the one before. One cube of the last grid is marked; a frame and a tint show the 3 by 3 cubes it came from in the grid before, the 5 by 5 behind those, and the 7 by 7 of the input, with dashed lines joining the frames like a funnel. Under each funnel stands the small 3 by 3 kernel of that layer. In the last move the small kernels gather for a count, and the patch itself leaves the input and shrinks beside them as the one large kernel that would see as far: a cube for every weight. A slider sets the number of layers and clicking a cube of the last grid moves the trace. Second step: one row of 17 cubes for each of three layers, drawn in 1D, input at the bottom and output at the top, with each layer's three-weight kernel drawn on the right, its taps 1, 2 or 4 cubes apart with dashed holes between. Lines trace one output cube down to the three cubes each cube reads in the row below. With plain layers the traced cubes at the input span 7; with dilations 1, 2 and 4 they span 15, marked by a bracket, and a grey bracket below shows the 7 of the plain stack with the same weights.One cube, traced backDilation: further, with the same weights
    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()      # 15

    One 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

    CNNsGroups1 / 1
    GroupsThe input as six coloured slabs, six kernels in a row, and the output volume. Every kernel is drawn as a small block of cubes, one cube per weight, in the colours of the channels it reads. As the number of groups goes up the slabs of the input move apart into groups and the kernels become thinner, from six layers deep to one; a bracket marks the kernels of each group and a bar shows the number of weights of the layer. A slider sets the number of groups.From one group to one per channel
    Groups

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

    From one group to one per channel

    • With groups a kernel reads channels: groups=g in 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

    CNNsChannel shuffle1 / 1
    Deal them outFour rows of nine cubes, one cube per channel, numbered 0 to 8 and coloured by group: green, orange and purple, three each. Thin lines join the first row to the second: every cube of the second row reads only the three cubes of its own group. The cubes then travel down to a third row, either straight, or crossing over into the order 0, 3, 6, 1, 4, 7, 2, 5, 8. A second set of lines joins the third row to the fourth, again inside groups of three, and each cube of the fourth row is striped with the colours of the input groups it descends from: one colour without the shuffle, all three with it. At the right two small grids of the same nine numbers show how the shuffle is done: laid out as three groups by three, then transposed. A slider or a click picks an output channel, and its ancestors are framed in the first row.Deal the channels out again
    Deal them out

    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

    CNNsInception1 / 2
    Four branchesAn input volume on the left fans out into four rows, one per branch, each with its layers drawn as arrows and its volumes to scale: a 1 by 1 kernel; a 1 by 1 kernel and then a 3 by 3 kernel; a 1 by 1 kernel and then a 5 by 5 kernel; a max-pool and then a 1 by 1 kernel. The branches run one after the other, each scanning the volume it reads, and at the end the four outputs slide together into one volume of 256 channels. The second step shows the same rows with a bar of weights for each; the 1 by 1 layers are put in one branch at a time, the bars shrink, and chips switch between the block with and without them.Several kernel sizes at onceWhat the 1 × 1 layers save
    Four branches

    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 out

    Several 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

    CNNsResidual1 / 2
    The addA block of cubes with numbers passes two small kernels and becomes a second block of numbers, while a wire carries the first block round them to a plus; the third block fills cube by cube with the sums, and a line under it writes out the sum of the marked cube. Chips set the layers' output to zero, which leaves the input unchanged. In the second step the blocks are drawn to scale: the layers halve the face and double the depth, a red note says the two shapes cannot be added, a 1 by 1 kernel with stride 2 scans the input on the wire and reshapes it, and then the two are added.Add, cube by cubeWhen the shapes differ
    The 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

    CNNsBottleneck1 / 2
    The blockA row of four volumes drawn to scale, deep, thin, thin and deep, with the three layers between them, each scanning the volume it reads, and under each its weight count and what follows it. A wire leaves the input line, runs over the row and ends in an add after the last volume, followed by a ReLU. A bar at the bottom collects the weights of the three layers. The second step puts two rows one above the other, a basic block of two 3 by 3 layers at full width and the bottleneck, each with a bar for the weights it has paid so far.Squeeze, convolve, expandAgainst the basic block
    The 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,632

    Squeeze, 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

    CNNsInverted bottleneck1 / 3
    MobileNetV2A row of four volumes drawn to scale, thin, deep, deep and thin, with three layers between them, a 1 by 1 expansion, a 3 by 3 depth-wise layer and a 1 by 1 projection, each scanning the volume it reads; a wire carries the input over the row into an add, and a bar collects the weights. The second step draws a classic bottleneck and an inverted one with the same two widths, one above the other; chips mark where the 3 by 3 layer works, what the skip carries, where the last ReLU is, and the weights. The third step is the ConvNeXt block in the same drawing: a 7 by 7 depth-wise layer first, then a 1 by 1 expansion to four times the width and a 1 by 1 projection.Expand, filter, projectThe same widths, the other way roundConvNeXt: the large kernel first
    MobileNetV2

    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

    CNNsGhost module1 / 2
    The moduleVolumes drawn as stacks of slabs, one slab for 8 channels. An input of 48 channels goes through a 3 by 3 convolution that makes only half of the 96 output maps, the intrinsic maps, each slab in its own colour. One arrow carries them unchanged to the output; another leads down to a second stack, the ghosts, which fills slab by slab, each ghost in a pale tint of the intrinsic slab it is made from. Both stacks then travel to the output and form one volume of 96 channels. Two bars at the lower left compare the weights of an ordinary convolution with those of the two parts of the Ghost module, and chips change how many ghosts each intrinsic map gets. The second step works one ghost by hand: a 5 by 5 map of numbers, a 3 by 3 filter, and the map that comes out as the filter slides over it, with the sum at the marked place written out; beside it, for comparison, the 3 by 3 kernel through all 48 input channels that an ordinary convolution needs for a single output map.Most maps for almost nothingA ghost, by hand
    The 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 1

    Most 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

    CNNsDense1 / 2
    The growing stackA stack of feature maps drawn to scale on the left, a layer in the middle (a 1 by 1 kernel to 128 channels, then a 3 by 3 kernel to 32), and a slab of 32 new channels on the right, which flies back over the top and joins the back of the stack in its own colour. This repeats for six layers while the stack grows from 64 to 256 channels, and a bar for each layer shows its weights. The second step draws the seven feature maps in a row with the connections between them: a plain chain, a residual network with a skip round every layer, and dense connectivity with an arc from every earlier map to every later layer; below, the input of the chosen layer is drawn as a stack. Chips pick the wiring, a slider the number of layers, a click the layer.Every layer adds to the stackPlain, residual, dense
    The growing stack

    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")               # 21

    Every 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

    CNNsCross-stage1 / 1
    Half goes roundA row of stacks of thin slabs, one slab for 32 channels. On the left the input of the stage, two blue slabs. Four columns follow, one for each layer of a dense block; each shows the stack after that layer, with the slab the layer has just made in front in its own colour, and under it how many channels the layer reads, a bar, and its number of weights. On the right the output of the stage, six slabs. In the dense block both input slabs run through every column. With the cross-stage connection one input slab lifts out, turns orange and travels along a dashed lane above the block to the output, so every column is one slab thinner and every number of weights smaller; the total under the output falls from 129,024 to 92,160. At the end a red line runs back along the lane from the output to the input: a gradient path that does not pass through the block.Half the channels go round the stage
    Half goes round

    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 92160

    Half 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

    CNNsUpsampling1 / 2
    No weightsA grid of 3 by 3 cubes with numbers becomes a grid of 6 by 6. A dot on the small grid shows where each new cube sits and lines join it to the cubes it reads; in nearest mode it reads one and copies it, in bilinear mode it mixes up to four, and the sum is written out under the large grid. In the second step each cube of a 2 by 2 grid in turn multiplies a small kernel, and the product travels into the large grid at twice its position; with a 3 by 3 kernel the stamps overlap and the overlapping cubes, drawn darker, hold sums.Nearest and bilinearTransposed convolution
    No weights

    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

    CNNsPixel shuffle1 / 3
    Channel to spaceA stack of four coloured channels on a 3 by 3 grid. The channels slide out of the stack and lie side by side as four small maps of numbers, arranged two by two. The four numbers at one place, one from each map, then travel into a 2 by 2 block of a 6 by 6 grid on the right, each keeping its colour, and the other places follow one after another until the large grid is full and reads 1 to 36 in order. Each channel is then lit in turn with the pixels it wrote, and at the end the same picture runs backwards. The second step has a 6 by 6 grid of numbers on the left and two results on the right: above, a 3 by 3 map that keeps only the largest number of every 2 by 2 block while the other three turn grey; below, four 3 by 3 maps into which all four numbers of a block travel. The third step shows a 6 by 6 feature with a diagonal edge, four small kernels of weights arranged two by two, and an 8 by 8 output shaded by value. A frame marks the window the kernels read; the four results travel into one block of the output. With four unrelated kernels the output is a checkerboard; when copies of the first kernel cover the other three it becomes blocky and clean; with four kernels that each lean to a corner it becomes smooth. The sum behind the marked output pixel is written out under the kernels.Channel to spaceSpace to channelFour kernels, four sub-pixels
    Channel to space

    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

    CNNsU-Net1 / 3
    The UA U of volumes drawn to scale. On the left an image and three encoder volumes that get smaller and deeper going down, with 64, 128 and 256 channels, and at the bottom a thin volume of 512 channels. On the right three decoder volumes going back up, each made of two halves: a yellow half written by an up-convolution from the level below, and a copy of the encoder volume of the same size, which slides across along a dashed arrow marked copy. A last arrow leads to a flat mask as large as the image. The sizes of the four levels are listed at the left. The second step shows the same sketch of a few cells four times, once for each level. A red pixel sits where two cells touch; on each tile a square, drawn to scale, shows how much of the image one feature of that level has seen around it, 5, 14, 32 and 68 pixels wide, and it grows as the pool and the two convolutions of the level are applied. The cells are tinted green the way that level's grid can place them: exactly at the first level, in blocks of 2, 4 and 8 pixels further down, where the two touching cells run together. The third step is a toy that can be checked by hand: a 16 by 16 image of bright and dark pixels with a blob and seven specks; a deep path that pools it into 4 by 4 blocks, keeps the blocks that are at least a quarter bright and upsamples them; a dashed skip that carries the image itself; and a small kernel that keeps a pixel only where both agree. The mask on the right is shown for the deep path alone, for the skip alone and for both, with the wrong pixels outlined in red.Down, across and upWhat each level seesWhat the skip carries
    The U

    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 yes

    Down, 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++

    CNNsU-Net++1 / 3
    Nested skipsTen volumes drawn to scale and arranged as a triangle standing on its tip: four in the top row at full size, three in the row below, then two, then one. The left edge of the triangle is the encoder and the right edge the decoder of a U-Net, with one long skip on each level. Then the inner nodes fill in column by column, each with an arrow coming up from the node below it and with coloured skips from every earlier node of its row, short ones straight and long ones arching over the nodes between. A panel shows the stack of channels that the marked node reads, one slab per source. The second step shows the sketch of cells once for each input of the last node, with a square for what that input has seen around the red pixel: 5 and 92 pixels wide for the two inputs that U-Net has, and 18 and 44 pixels for the two that U-Net++ adds between them; brackets under the row give the ratio from one view to the next. In the third step a small mask sits above each of the three later nodes of the top row; chips choose a depth, the nodes that this depth does not need fade, and a bar shows how many of the weights are still used.Nodes in the gapSmaller steps to mergeOne network, every depth
    Nested skips

    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

    CNNsFeature pyramid1 / 2
    The pyramidTwo rows of volumes drawn to scale on four column axes. The top row is the backbone: four volumes that get smaller and deeper from left to right, with 256, 512, 1024 and 2048 channels at strides 4, 8, 16 and 32, joined by arrows marked stride 2. Under each of them sits a map of the pyramid, one slab of 256 channels at the same size. A slab travels down each column from the backbone volume, through an arrow marked 1 by 1; from the right a copy of the map of the level above travels left while its cubes double in size; the two are added and the map takes a mixed colour. Arrows marked 3 by 3 lead down from every map to the names P2 to P5 on one line. The second step shows one box four times, once for each level, with that level's grid laid over it and a blob drawn in the cells of that grid: 28 by 28 cells on P2, 14, 7 and 3.5 on the others for a box of 112 pixels. A rule written above the tiles picks one level, which is framed in green and shows the 7 by 7 bins of the pooling; a slider changes the size of the box and the choice moves.Meaning at every sizeA level for every size
    The 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 pixels

    Meaning 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

    CNNsASPP1 / 1
    Five viewsA square feature map of 41 by 41 small cells with one place marked at its centre. Round that place three coloured squares appear one after another, each with nine dots at its corners, the middles of its sides and its centre: the taps of a 3 by 3 kernel spread 6, 12 and 18 cells apart, so that the squares are 13, 25 and 37 cells wide. Then the whole map is tinted for the branch that averages it. Beside the map five small slabs stand in a column, one for the output of each branch, with its name and what it sees; they travel together into one stack of five slabs, and an arrow marked 1 by 1 leads to a single slab of 256 channels. When the rates are doubled the two larger squares grow past the edge of the map, their outer dots disappear, and a red note says that one of nine taps is left on the map. A slider moves the place from the centre to a corner.Five branches read one feature map
    Five views

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

    Five 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

    CNNsWeight sharing1 / 3
    SharingFirst a 6 by 9 grid of numbered cubes, a 3 by 3 kernel shown with its nine weights, and the 4 by 7 grid of responses. One weight of the kernel is dark; as the window visits the 28 places a dashed line joins that weight to the cube it multiplies, and every cube it has met stays tinted, so that a block of 28 cubes is marked at the end. Chips switch to a version without sharing, where the kernel's numbers change from place to place and a weight is used once; a slider moves the window and a click picks another weight. The second step is a grid that is zero except for a small pattern, a kernel, and the grid of responses, darkest where the kernel lies on the pattern; a slider moves the pattern sideways and the dark spot of the response moves by the same number of cubes, while the largest response, shown in one cell, stays the same. The third step draws weights as tiny cubes: a single 3 by 3 kernel, then one such kernel for every place, then a wall with a cube for every pair of input and output cube, with the three counts as bars; a slider changes the width of the feature.The same nine weights, 28 timesShift the input, the output shiftsWhat sharing saves
    Sharing

    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

    CNNsProperties1 / 4
    LocalityFirst a small grey image of blobs, a square in which every pair of pixels a given distance apart is a dot, and a curve of the correlation at each distance. One pixel apart the dots hug the diagonal and the correlation is 0.84; as a slider moves the pairs further apart the cloud spreads and the curve falls to zero by four pixels; a green band marks what a 3 by 3 kernel reads. The second step is a square of four grids: a pattern of ones and its response under a kernel in the upper row, the shifted pattern and its response below. The upper response, shifted, travels down onto the lower one and a verdict says that all 32 cubes agree; pushed to the border, or with stride 2 and a shift of one, cubes that differ are framed in red. The third step sends a detector's response through max-pooling over 2 by 2 windows and through pooling over everything, and a strip below shows the pooled map and the largest value for every shift, with an equals sign between neighbours that agree. The last step is a 25 by 25 matrix of weights drawn as coloured cells: all different when fully connected, mostly blank with locality, and nine colours repeated on every row as a convolution; one row is folded back onto the 5 by 5 pixels to show what that unit reads, and three bars give the counts 625, 169 and 9.Locality: neighbours belong togetherEquivariance, and where it stopsInvariance: local or globalInductive bias: what is assumed
    Locality

    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

    CNNsClassifier head1 / 2
    Pool or flattenA small volume drawn as four coloured slabs with numbers on the front one. One channel at a time comes to the front, its six numbers are added and divided by six, the sum is written out, and the mean lands in a row of four cells; for flatten, the cubes leave the volume one at a time, row by row and channel after channel, and fly into one long row of 24 coloured by channel. Chips replay either operation and a slider moves it by hand; the last move shows both results. The second step draws the classifier's weights as cubes, a small block after pooling and a wide one after flatten, with a slider for the number of classes, and three bars for the real counts of ResNet-50 and VGG-16.Global average pooling, or flattenWhat the classifier costs
    Pool or flatten

    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,448

    Global 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

    CNNsUnfold1 / 1
    UnfoldA 4 by 4 grid of numbers. The nine numbers under the kernel's first place travel out of the grid and line up as the first row of a matrix; the other three places follow, a row each. The nine numbers of the kernel then travel into a column. The matrix times the column gives four numbers, and these fold back into a 2 by 2 grid, the output of the convolution. A slider moves the unrolling by hand.Windows as rows, kernel as a column
    Unfold

    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))  # True

    Windows 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

    CNNsSqueeze-and-excitation1 / 1
    Squeeze-and-excitationA volume of four coloured slabs. One channel at a time comes to the front and its six cubes run together into one cell of a column, its mean, with the sum written out. Two small layers are drawn as their connections, thick for a large weight and brown for a negative one; they turn the four means into two numbers and then into four factors between 0 and 1. Each factor then leaves its cell and lands on its own slab of a second copy of the volume, which fades and whose numbers shrink by that factor, with one product written out. Chips bring another channel to the front.One factor per channel
    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] # excite

    One 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

    CNNsChannel attention1 / 1
    Mean and maximumA volume of four coloured slabs. One channel at a time comes to the front: first its six cubes run together into a cell of a column of means, then the largest cube of each channel flies into a second column. Both columns go, one after the other, through the same two small layers, drawn as their connections, giving two columns of scores; these are added, a sigmoid makes four factors, and each factor travels to its slab of a copy of the volume, which fades and whose numbers shrink. Chips switch the maximum off, which leaves squeeze-and-excitation.Mean and maximum, one MLP
    Mean and maximum

    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

    CNNsSpatial attention1 / 1
    WhereA volume of four channels, four by five places, with a brighter patch in the middle. The four numbers at one place are drawn out as a row with their mean and their largest value; then every place is pooled into two flat maps. A small kernel, two deep, scans both maps and writes one score per place into a grid, with the sum for the chosen place written out; a sigmoid turns the scores into a mask, and a copy of the volume fades place by place as it is multiplied by the mask. A slider or a click chooses the place that is worked out.One mask value per place
    Where

    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 mask

    One 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

    CNNsCBAM1 / 1
    BothThree copies of a volume from left to right with a column of four channel factors between the first two and a four by five mask between the last two. The factors appear one at a time and each fades its slab of the second volume; the mask is then read off the second volume place by place and fades the places of the third. One framed cube is followed through both multiplications with its product written out. Chips switch to channel attention alone or spatial attention alone, and a click picks another cube.Channels first, then places
    Both

    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

    CNNsECA1 / 1
    A 1D kernelA volume of eight coloured slabs. Each channel is pooled to its mean, and the eight means form a row. A kernel of three weights sits over three neighbouring means, with zeros beyond the ends, and slides along the row; the sum for its place is written out and lands in a row of scores, a sigmoid gives a row of factors, and each factor travels to its slab of a copy of the volume. A slider moves the kernel.A kernel along the channels
    A 1D kernel

    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 weights

    A 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

    CNNsCoordinate attention1 / 1
    Rows and columnsA volume of two channels, four by four, with numbers on the front one. The four cubes of each row run together into a cell of a column of row means beside the volume, and the four cubes of each column into a cell of a row of column means under it, with each sum written out. Both profiles pass through the same small convolution, giving a second column and a second row, and then through one convolution each and a sigmoid, giving a column of row factors and a row of column factors, tinted green by their size. The row of column factors travels under a copy of the volume; then every cube of the copy is multiplied by the factor of its row and the factor of its column, one cube after another, with the product of the framed cube written out, and the copy fades where the factors are small. Chips bring the other channel to the front and a slider or a click picks the cube that is followed.A factor for every row and every column
    Rows and columns

    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 column

    A 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

    CNNsStabilization1 / 4
    InitializationFirst step: a grid of small cells, 21 columns for the input and twenty layers and 14 rows for units, each cell shaded by the size of that unit's output, and beside it a chart of the size of the whole signal on a logarithmic scale. The columns fill from left to right. With a weight variance of 1 over n the cells fade to white and the curve falls to a thousandth; with 4 over n they turn orange and the curve climbs a thousandfold; with 2 over n they keep their shade and the curve stays level. Second step: two panels, the output of an activation function on the left and its slope on the right, with the chosen function drawn in colour over the faint curves of the others, 24 sample inputs as dots on both curves, and a marked input with its value and slope written out; for ReLU the samples left of zero lie flat on the axis and a note counts those that pass no gradient. Third step: on the left the batch, drawn as two feature volumes, image 2 under image 1, each two by two positions wide and four channels deep, with arrows for its four axes: N from one image to the next, C from front to back, H and W across a map. The first channel is outlined in both volumes and the arrows for N, H and W are drawn strong. That channel slides out of both volumes onto a bench beside them and shows its numbers. The eight numbers travel onto a number line as dots; a dashed mark shows their mean and a shaded band one deviation to each side, with the two sums written above. The dots slide until the mean sits on zero and close up until the band is one unit to each side, while a line above follows one number through the arithmetic. The results travel to a second bench and from there into the first channel of an empty copy of the batch on the right. The other three channels then send their numbers to rows of their own, each with its own mean and band, and all four rows end on the same scale. Last, each row is stretched and shifted by a learned scale and shift. Fourth step: the same two volumes with their axes, and beside them the batch laid out flat, a row of four small maps of numbers for each image; the slabs first slide out of the volumes into that layout. Colours in the volumes and frames in the flat layout mark the sets that share one mean and deviation: a channel through both images for batch norm, a whole image for layer norm, a single map for instance norm, two channels of an image for group norm, each frame with its mean and deviation on a tag, and the arrows of the pooled axes drawn strong. On the right the normalized first image. When the second image is multiplied by 2 or 3, the tags of the sets it belongs to change, and the numbers of the first image that change turn red: all of them for batch norm in training, none for batch norm at inference, layer, instance or group norm.Initialization: start at the right scaleActivation: the bend and its slopeBatch norm: one channel, across the batchNormalization: which axes share a mean
    Initialization

    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(): True

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