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
Addand 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
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
input | Input | shape=3×32×32 | 3 × 32 × 32 | 0 |
stem | Conv2d | out_channels=64 bias=false | 64 × 32 × 32 | 1,728 |
stem_bn | BatchNorm2d | defaults | 64 × 32 × 32 | 128 |
stem_relu | Activation | function=relu | 64 × 32 × 32 | 0 |
conv_a | Conv2d | out_channels=64 bias=false | 64 × 32 × 32 | 36,864 |
bn_a | BatchNorm2d | defaults | 64 × 32 × 32 | 128 |
relu_a | Activation | function=relu | 64 × 32 × 32 | 0 |
conv_b | Conv2d | out_channels=64 bias=false | 64 × 32 × 32 | 36,864 |
bn_b | BatchNorm2d | defaults | 64 × 32 × 32 | 128 |
add | Add | defaults | 64 × 32 × 32 | 0 |
relu_out | Activation | function=relu | 64 × 32 × 32 | 0 |
gap | AdaptiveAvgPool2d | output_size=1×1 | 64 × 1 × 1 | 0 |
flatten | Flatten | defaults | 64 | 0 |
fc | Linear | out_features=10 | 10 | 650 |
| Total | 76,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()
Guides
Build a neural network without code and export it to PyTorch
Connect layers on a canvas, let Brick DNN check every shape, and download a PyTorch script that runs on its own.
Image segmentation with a U-Net: from masks to a trained model
From a ZIP file of images and masks to a trained U-Net, with mean IoU, Dice and the predicted masks.
Common PyTorch shape errors and how to fix them
The exact messages of the most common PyTorch shape errors, what causes each one and how to fix it.