Examples · PyTorch

ResNet block for CIFAR-10 in PyTorch

The building block of ResNet in a small network for 32×32 colour photos: two convolutions learn a correction that an Add layer puts on top of their input, so the signal and its gradient can also take the short way around.

Open in the editor See the code

Code
PyTorch
Task
Classification
Input
3 × 32 × 32
Bricks
14
Trainable parameters
76,490

What the network does

A stem of Conv2d (64 filters of 3×3, without bias), BatchNorm2d and ReLU turns the 3 × 32 × 32 image into 64 × 32 × 32 feature maps. The residual block then runs two more convolutions with batch normalization. The convolutions have no bias, because the batch normalization right after them has its own shift.

Add sums the block’s output and the stem’s output element by element, which is why both must have the same shape, 64 × 32 × 32; Brick DNN checks that while you build. After a ReLU, AdaptiveAvgPool2d averages every feature map to one value (64 × 1 × 1), and a Linear layer of 650 parameters gives the ten class scores. Global average pooling instead of a large dense layer keeps the whole network at 76,490 parameters.

When to use it

  • When a plain stack of convolutions stops improving as you add layers: skip connections are what lets deep networks train.
  • To learn how a merge layer works: try connecting tensors of different shapes to Add and read the message.
  • As a base for a deeper network: copy the block, connect several in a row, and add a convolution with stride 2 between them to halve the resolution.

Layers, shapes and parameters

Diagram of the example Residual CNN for CIFAR-10Input (3 × 32 × 32), Conv2d (64 × 32 × 32), BatchNorm2d (64 × 32 × 32), Activation (64 × 32 × 32), Conv2d (64 × 32 × 32), BatchNorm2d (64 × 32 × 32), Activation (64 × 32 × 32), Conv2d (64 × 32 × 32), BatchNorm2d (64 × 32 × 32), Add (64 × 32 × 32), Activation (64 × 32 × 32), AdaptiveAvgPool2d (64 × 1 × 1), Flatten (64), Linear (10)Input3 × 32 × 32Conv2d64 × 32 × 321,728 parametersBatchNorm2d64 × 32 × 32128 parametersActivation64 × 32 × 32Conv2d64 × 32 × 3236,864 parametersBatchNorm2d64 × 32 × 32128 parametersActivation64 × 32 × 32Conv2d64 × 32 × 3236,864 parametersBatchNorm2d64 × 32 × 32128 parametersAdd64 × 32 × 32Activation64 × 32 × 32AdaptiveAvgPool2d64 × 1 × 1Flatten64Linear10650 parameters
The network as it is laid out in the editor. Each box shows the output shape (without the batch dimension) and the number of parameters.
The bricks of Residual CNN for CIFAR-10: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
inputInputshape=3×32×323 × 32 × 320
stemConv2dout_channels=64 bias=false64 × 32 × 321,728
stem_bnBatchNorm2ddefaults64 × 32 × 32128
stem_reluActivationfunction=relu64 × 32 × 320
conv_aConv2dout_channels=64 bias=false64 × 32 × 3236,864
bn_aBatchNorm2ddefaults64 × 32 × 32128
relu_aActivationfunction=relu64 × 32 × 320
conv_bConv2dout_channels=64 bias=false64 × 32 × 3236,864
bn_bBatchNorm2ddefaults64 × 32 × 32128
addAdddefaults64 × 32 × 320
relu_outActivationfunction=relu64 × 32 × 320
gapAdaptiveAvgPool2doutput_size=1×164 × 1 × 10
flattenFlattendefaults640
fcLinearout_features=1010650
Total76,490

Training it in Brick DNN

Choose CIFAR-10 (60,000 colour photos in ten classes, downloaded once on the server); it fits the Input 3, 32, 32 as it is. Batch normalization behaves differently during training and evaluation, which the exported module handles through PyTorch’s model.train() and model.eval().

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (resnet_block.py): an nn.Module with one attribute per layer and a forward method, plus a check that runs a random batch through it. It needs nothing but PyTorch.

# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""NeuralNetwork: generated with Brick DNN.

Input: (batch, 3, 32, 32)
Output: (batch, 10)
Trainable parameters: 76,490

Print the model and run it on a random batch:

    python this_file.py
"""

import torch
import torch.nn as nn


class NeuralNetwork(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv2d_1 = nn.Conv2d(3, 64, kernel_size=3, padding='same', bias=False)
        self.batchnorm2d_1 = nn.BatchNorm2d(64)
        self.relu_1 = nn.ReLU()
        self.conv2d_2 = nn.Conv2d(64, 64, kernel_size=3, padding='same', bias=False)
        self.batchnorm2d_2 = nn.BatchNorm2d(64)
        self.relu_2 = nn.ReLU()
        self.conv2d_3 = nn.Conv2d(64, 64, kernel_size=3, padding='same', bias=False)
        self.batchnorm2d_3 = nn.BatchNorm2d(64)
        self.relu_3 = nn.ReLU()
        self.avgpool_1 = nn.AdaptiveAvgPool2d(1)
        self.flatten_1 = nn.Flatten()
        self.linear_1 = nn.Linear(64, 10)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        conv2d_1 = self.conv2d_1(x)
        batchnorm2d_1 = self.batchnorm2d_1(conv2d_1)
        relu_1 = self.relu_1(batchnorm2d_1)
        conv2d_2 = self.conv2d_2(relu_1)
        batchnorm2d_2 = self.batchnorm2d_2(conv2d_2)
        relu_2 = self.relu_2(batchnorm2d_2)
        conv2d_3 = self.conv2d_3(relu_2)
        batchnorm2d_3 = self.batchnorm2d_3(conv2d_3)
        added_1 = batchnorm2d_3 + relu_1
        relu_3 = self.relu_3(added_1)
        avgpool_1 = self.avgpool_1(relu_3)
        flatten_1 = self.flatten_1(avgpool_1)
        linear_1 = self.linear_1(flatten_1)
        return linear_1


def count_parameters(model: nn.Module) -> int:
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


def main() -> None:
    model = NeuralNetwork()
    print(model)
    print(f"Trainable parameters: {count_parameters(model):,}")

    # Check the model with a random batch of 2 samples.
    model.eval()
    x = torch.randn(2, 3, 32, 32)
    with torch.no_grad():
        out = model(x)
    print("Output shape:", tuple(out.shape))  # expected (2, 10)


if __name__ == "__main__":
    main()

Open in the editor

Guides