AI Wiki中文/EN

ResNet: residual blocks and optimization

ResNet

Implement basic and bottleneck blocks, inspect shortcut dimensions and normalization, and test what the identity path does not guarantee.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with an experiment

Set a residual branch to zero. Does the whole block become the identity? In the original post-activation form, its output is ReLU(x). That equals x for nonnegative inputs, but clips negative values. The shortcut and the activation around it must both be part of the explanation.

ResNet reparameterizes a transformation relative to a shortcut. The 2016 paper addresses a degradation problem: some deeper plain networks had higher training error than shallower counterparts. That is different from diagnosing overfitting solely from worse validation results. The authors also report healthy gradient norms in the particular batch-normalized comparison, so the account should not be reduced to “all deeper networks failed because their gradients vanished.” He et al., 2016

We will implement basic and bottleneck residual blocks, including shape-changing shortcuts and inference-mode normalization. The examples test the computation and its gradient locally; they are not trained ImageNet networks.

The model and its assumptions

Let F be the learned residual branch and S the shortcut. In the post-activation form examined here:

y=ReLU⁡(F(x)+S(x)).y=\operatorname{ReLU}(F(x)+S(x)).

An identity shortcut has S(x)=xS(x)=x. When spatial size or channel width changes, the shortcut must transform x to exactly the residual branch’s shape. A 1-by-1 strided projection is one choice. The paper compares parameter-free dimension handling, projections at dimension changes, and projections everywhere; these are distinct configurations. He et al., 2016

A basic block uses 3-by-3 convolution, BN, ReLU, then 3-by-3 convolution and BN before addition. A bottleneck instead uses 1-by-1,3-by-3,1-by-1 convolutions, reducing and restoring channel width around the spatial operator. The final activation follows addition. Our code applies the requested stride in the first convolution of the residual path and in the projection; moving it to another bottleneck layer defines a different convention.

The paper’s main-path depth counts can be reconstructed from its table. The stem convolution and final classifier contribute two additional layers; BN, pooling and separate shortcut projections are not added to this naming convention.

ModelBlocks in four stagesConvolutions per blockMain-path count
182,2,2,222+8×2=18
343,4,6,322+16×2=34
503,4,6,332+16×3=50
1013,4,23,332+33×3=101
1523,8,36,332+50×3=152

Basic-stage output widths are 64,128,256,512; bottleneck-stage outputs are 256,512,1024,2048 in these listed ImageNet configurations. The original table and basic block explanation were checked separately from later family variants. He et al., 2016 D2L: Residual blocks

In an activation region away from a ReLU kink, let D be the diagonal matrix selecting positive preactivations. An identity shortcut gives:

Jy=D(JF+I).J_y=D(J_F+I).

The identity term supplies a direct derivative path, but does not prove nonzero gradients or successful optimization everywhere. The learned derivative can cancel it, and inactive output gates can remove it. In a typical post-activation stack, a preceding ReLU often supplies nonnegative x, explaining why a zero branch can act as identity on that actual input domain.

The program’s inference BN uses supplied channel statistics and affine parameters:

BN⁡infer(a)=γa−μv+ε+β,ε=10−5.\operatorname{BN}_{\mathrm{infer}}(a)=\gamma\frac{a-\mu}{\sqrt{v+\varepsilon}}+\beta,\qquad \varepsilon=10^{-5}.

It does not estimate a batch mean or update running statistics. Our projection path also uses this normalization, so its inference transformation can be affine rather than simply a bare matrix multiplication. Those details affect both values and parameter accounting.

A complete small program

Run with Python 3.12 and NumPy 1.26.4. A seven-by-seven four-channel input passes through a stride-two basic block with eight output channels, then a bottleneck block. Sampled weights and default running statistics make this a numerical demonstration. Only the two selected blocks are executed; the table above does not mean the program trains or runs every full ResNet.

import numpy as np

EPS=1e-5

def conv(image,weights,stride=1):
    a,w=np.asarray(image,dtype=float),np.asarray(weights,dtype=float)
    if a.ndim!=3 or w.ndim!=4 or w.shape[1]!=a.shape[2] or w.shape[2]!=w.shape[3] or w.shape[2]%2!=1:
        raise ValueError('need compatible HWC input and odd square OIKK weights')
    if type(stride) is not int or stride<1 or min(a.shape)<1 or min(w.shape)<1 or not np.isfinite(a).all() or not np.isfinite(w).all():
        raise ValueError('invalid convolution values')
    radius=w.shape[2]//2;a=np.pad(a,((radius,radius),(radius,radius),(0,0)))
    windows=np.lib.stride_tricks.sliding_window_view(a,w.shape[2:],axis=(0,1))[::stride,::stride]
    return np.einsum('hwcij,ocij->hwo',windows,w)

def bn_inference(x,stats):
    # Supplied running statistics; this is not training-mode batch normalization.
    a=np.asarray(x,dtype=float);mean,var,gamma,beta=[np.asarray(v,dtype=float) for v in stats]
    if a.ndim!=3 or min(a.shape)<1 or any(v.shape!=(a.shape[2],) for v in (mean,var,gamma,beta)):
        raise ValueError('one BN value per output channel required')
    if not all(np.isfinite(v).all() for v in (a,mean,var,gamma,beta)) or np.any(var<0):
        raise ValueError('finite statistics and nonnegative variance required')
    return (a-mean)/np.sqrt(var+EPS)*gamma+beta

def init_block(cin,cout,stride=1,bottleneck=False,seed=23):
    if any(type(n) is not int or n<1 for n in (cin,cout,stride)) or type(bottleneck) is not bool or (bottleneck and cout%4):
        raise ValueError('positive widths/stride; bottleneck output must divide by four')
    rng=np.random.default_rng(seed)
    def layer(incoming,outgoing,k,s):
        weights=rng.normal(size=(outgoing,incoming,k,k))*np.sqrt(2/(incoming*k*k))
        stats=(np.zeros(outgoing),np.ones(outgoing),np.ones(outgoing),np.zeros(outgoing))
        return weights,stats,s
    kernels=(1,3,1) if bottleneck else (3,3)
    widths=(cout//4,cout//4,cout) if bottleneck else (cout,cout)
    layers=[];incoming=cin
    for i,(k,outgoing) in enumerate(zip(kernels,widths)):
        layers.append(layer(incoming,outgoing,k,stride if i==0 else 1));incoming=outgoing
    shortcut=layer(cin,cout,1,stride) if cin!=cout or stride!=1 else None
    return dict(layers=layers,shortcut=shortcut)

def forward(image,block):
    x=np.asarray(image,dtype=float);a=x
    for i,(w,stats,stride) in enumerate(block['layers']):
        a=bn_inference(conv(a,w,stride),stats)
        if i<len(block['layers'])-1:a=np.maximum(a,0)
    if block['shortcut'] is None:skip=x
    else:
        w,stats,stride=block['shortcut'];skip=bn_inference(conv(x,w,stride),stats)
    if a.shape!=skip.shape:raise ValueError('shortcut and residual shapes must match exactly')
    return np.maximum(a+skip,0)

def parameter_count(block):
    layers=block['layers']+([block['shortcut']] if block['shortcut'] is not None else [])
    return sum(w.size+stats[2].size+stats[3].size for w,stats,stride in layers)

if __name__=='__main__':
    x=np.random.default_rng(6).normal(size=(7,7,4))
    basic=init_block(4,8,stride=2);y=forward(x,basic)
    bottle=init_block(8,8,bottleneck=True);z=forward(y,bottle)
    print('basic projection block:',x.shape,'->',y.shape,'parameters:',parameter_count(basic))
    print('bottleneck block:',y.shape,'->',z.shape,'parameters:',parameter_count(bottle))
    identity=init_block(4,4)
    for w,stats,stride in identity['layers']:w.fill(0)
    print('zero residual yields ReLU(x):',np.allclose(forward(x,identity),np.maximum(x,0)))
    print('zero residual equals signed x:',np.allclose(forward(x,identity),x))
basic projection block: (7, 7, 4) -> (4, 4, 8) parameters: 944
bottleneck block: (4, 4, 8) -> (4, 4, 8) parameters: 92
zero residual yields ReLU(x): True
zero residual equals signed x: False

Parameter counts include convolution weights and BN gamma/beta, but exclude running means and variances. The basic projection block has 944 parameters; the following bottleneck has 92. A same-shape four-channel bottleneck with one internal channel has 17 convolution weights and 12 affine normalization parameters. These are explicit small-model counts, not parameter totals for a full ResNet 18 or 50.

Independent checks cover literal strided convolution, manual inference BN, odd spatial sizes, a constructed projection, both block types and invalid shapes/statistics. A directional finite-difference test sets central channel-preserving weights to 0.2 and 0.3, cancels BN’s scale with a known gamma and stays in a positive activation region. The resulting block is locally 1.06 x and its measured directional derivative agrees. Zero-branch tests separately demonstrate the signed-input ReLU boundary.

Limits and comparisons

A shortcut changes the parameterization and optimization paths; it does not remove the need for data, an objective and a stable training procedure. Changing normalization placement or moving the activation before addition creates a different block. Borrowing batch statistics from the current test image also changes the computation; it is not a harmless replacement for the supplied running statistics used here.

The paper reports batch-normalized ImageNet training with momentum, weight decay and augmentation. Its validation tables distinguish inference protocols: the best reported single-model ResNet 152 top-five validation error is 4.49%, while the ensemble test result is 3.57%. The latter is not a single 152-layer model result, and neither number is produced by this demonstration. The authors’ observed optimization improvements support their reported setting, not a theorem that adding residual blocks always improves an arbitrary task. He et al., 2016

Projection, extra blocks and bottleneck width all affect compute and memory. A parameter-free identity shortcut still requires elementwise addition, and activation storage remains relevant in training. Evaluate a candidate on the intended input and latency constraints with a matched protocol, rather than inferring practical cost or quality from depth alone.

Exercises with answers

1. Why do 3,4,6,3 basic blocks produce a 34-layer main path?

Answer. The 16 blocks each contain two convolutions; the stem and classifier add two:16×2+2=34. The shortcut projection count is not added to this naming convention.

2. For F=0 and x=(−1,2), what does a post-activation identity-shortcut block return?

Answer. ReLU(x)=(0,2). It preserves x on the nonnegative domain, not on every possible signed input.

3. A stride-two residual branch maps 7×7×4 to 4×4×8. Can unchanged x be added?

Answer. No. Spatial and channel dimensions differ. A matching stride-two projection or another explicitly defined shape conversion is required.

4. Does the identity term in I+JF guarantee a nonzero derivative?

Answer. No. If JF=−I, the terms cancel. Output activation gates can also suppress derivatives; the shortcut is an optimization mechanism, not a universal guarantee.

Sources and next steps

The CVPR 2016 paper supplies the residual formulation, original architecture table and scoped comparisons. The table was visually checked rather than reconstructed from mixed PDF columns. D 2 L’s basic Residual class provides a second, explicitly delimited teaching reference; its projection details are not silently substituted for the conventions implemented here. He et al., 2016 D2L: Residual blocks

Review batch normalization and residual connections for the component ideas. Compare VGG and Inception to separate sequential depth, parallel channel concatenation and residual addition.

Make a prediction, then check

A post-activation residual block has F=0 and identity shortcut. What is its output?

Choose one answer

Learning objectives

  • Reconstruct main-path depth and shape-changing residual blocks.
  • Analyze activation, normalization and gradient claims with explicit assumptions.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Residual Learning for Image Recognition — architecture and comparison passages
    Kaiming He; Xiangyu Zhang; Shaoqing Ren; Jian Sun · 2016
  2. Dive into Deep Learning 1.0.3 — resnet
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit image classification experiments and CNN architecture models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 8 tests: literal strided multichannel convolution, manual inference BN, zero-residual post-ReLU behavior, constructed odd-size projection,1.06 directional derivative, basic/bottleneck parameter counts and invalid statistics. Visually checked original architecture table; no training-mode BN or full network reproduction.
  • Single AI author compared both locales across six sections, assumptions, definitions, equations, executed code and output, four exercise/answer pairs and scoped citations.43 checks across six draft articles; not independent human review or full historical training reproduction.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
  • After visual reading review, shortened/localized inline citation labels. Verified ordered link targets and every protected code/math/tag span unchanged; full source identities remain in metadata. Frozen drafts preserved and final article SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.