Residual blocks
Quick answer
A residual block learns F(x) and adds a shortcut, often y=x+F(x). The shortcut creates a direct path for information and gradients. Branch shapes and spatial alignment must match. Examples are static Python snippets tested locally on PyTorch CPU. ByteMind execution is unverified.
Identity path gradient
import torchx=torch.tensor([1.,-2.],requires_grad=True)y=x+0*xy.sum().backward(); print(y.tolist(),x.grad.tolist())Expected output (locally tested): [1.0, -2.0] [1.0, 1.0]. Zero residual leaves identity output and gradient.
How it works
An identity shortcut works when dimensions match. A simple block uses two padded 3x3 stride-1 convolutions with activation between them. A 1x1 projection with appropriate stride can align changed channels or spatial sizes. The Jacobian of x+F(x) before any post-add activation is I+J_F; a post-add ReLU can gate the identity contribution. Residual paths help optimization but do not guarantee nonvanishing gradients. Addition differs from concatenation, which enlarges an axis. Assert exact shape equality: PyTorch broadcasting can silently produce an incorrect shortcut even if addition succeeds.
Projection shortcut
import torchx=torch.ones(1,2,8,8)f=torch.nn.Conv2d(2,4,3,stride=2,padding=1)(x)s=torch.nn.Conv2d(2,4,1,stride=2)(x)assert f.shape==s.shapeprint(list((f+s).shape))Expected output (locally tested): [1, 4, 4, 4]. Both branches downsample and produce four channels.
Common mistakes
Do not broadcast a single-channel shortcut across multiple output channels unintentionally. Do not downsample only one branch. Do not claim residuals guarantee successful training.
Practice and next steps
Zero the residual branch and inspect the gradient. Construct a projection from two to four channels at half resolution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Residual blocks — knowledge check
Apply residual blocks to small examples and debugging scenarios.
What is added in an identity residual?
When use projection?
Jacobian of x+F(x)?
What can gate direct gradient after addition?
Why exact shape check?