Week-05 · ML-2026
Alexei Kornaev,
Dr. Sc., Prof.
Innopolis University
Researcher at the RC for AI,
National RC for Oncology n.a. N.N. Blokhin

Why local connectivity and shared parameters fit many visual tasks.
1
Prediction
→
2
Mean mini-batch objective
→
3
Gradient
→
4
Parameter update
Week 04 · MLP
Every output unit can connect to every input value.
architecture changes →
Week 05 · CNN
Connections are local; the same parameters are shared across positions.
The learning loop stays the same; the architecture constrains which predictions it can express.
One batch:
measured channels spatial axes
Grayscale
One intensity at each location.
RGB
Three measurements at each location in one image.
Hyperspectral
Many wavelength bands at each location.
Channels describe what is measured; height and width describe where it is measured.
Both layers map the same input to the same output shape:
Dense layer
784 inputs≋≋≋≋≋6272 outputs
Each output has its own weight for every input.
Conv2d: 8 filters, , padding 1
local same filter
at every position8 maps
Eight local filters are shared over the image.
Equal output dimensions do not mean equal models: the convolution imposes local, shared connectivity.

What was measured
Invasive single-cell recordings from visual cortex in lightly anaesthetized cats while patterned light stimulated the retina.
What this drawing shows
The spikes and tuning curve are schematic illustrations, not data reproduced from the paper.
Historical study: (Hubel and Wiesel 1959). Supplied schematic shown unaltered.
A receptive field is the region of the visual input that can influence the measured response.
Illustrative response patterns—not measured traces. The biological finding is that response can depend on both stimulus position and orientation.
Measured observation
Some recorded cortical cells responded selectively to visual patterns in restricted regions.
motivates architectural questions →
⌗
Local connectivity
Each unit initially uses a small spatial neighborhood.
↔︎
Shared weights
One learned local rule is reused at many positions.
▱
Composition through layers
Deeper layers combine earlier local responses.
These are engineered CNN assumptions. The cat experiment did not prove them or prescribe a CNN.
Image batch
Conv2d weights
Preactivations
Kernel slice
Spatial weights for one input channel.
Filter
All channel slices that produce one output channel.
Response map
Output of a fixed kernel before an activation.
Activation map
One channel of a learned representation after activation.
Single-layer notation suppresses : , with .
Local mean
Asks: what is the average intensity nearby?
Smooths small local changes.
Vertical contrast
Asks: does the right side exceed the left?
Produces a signed edge response.
A kernel defines one local question; scanning asks that same question at every position.
One input channel
One fixed kernel
One signed scalar at each valid position.
Scan the image
Those scalars form one response map.
The map records where the kernel’s local pattern is present—and with which sign.
Forward pass
The same participate at every position.
Backpropagation
Gradient contributions from all uses accumulate into and .
Update
One update changes the local question everywhere.
Weight sharing is a parameter identity built into the architecture; learning still uses the Week 04 loop.
One filter has shape . For RGB, its three channel slices jointly produce one output value at each position.
RGB is one image with three measured channels; a filter combines them rather than classifying them independently.
How spatial sampling changes representations and how depth combines local evidence.
Conv2d compute?input
+ weights
→ preactivations
groups=1, dilation=1; indexes examples, are strides.
sums over all input channels.
sum over a local spatial window.
selects one learned output filter.
PyTorch uses unflipped cross-correlation; is the padded input, the preactivation.
Operation convention: PyTorch Conv2d.
Zeros encode locality
Each output ignores distant inputs.
Repeated labels encode sharing
The same parameter appears at shifted positions.
The operation is still linear
Before bias and activation, a convolution is a structured matrix multiplication.
Convolution restricts a dense linear map to a sparse, repeated pattern of coefficients.
Pattern at the left
translate input
four pixels →
The same pattern at the right
For stride 1, shared weights make responses shift with the input, away from boundary effects.
Equivariant representation
shift input → feature map shifts
location is preserved
Invariant prediction
shift input → same class score
location is discarded
Convolution supplies a moving representation. Pooling, aggregation, data augmentation, and training determine whether the final decision becomes stable to a shift.
Equivariance is a property of the representation; invariance is a property of the final output.
A -value window centred at the left boundary needs one value outside the measured input.
No padding
outside47
Do not evaluate this boundary-centred window.
Zero padding
047
Assume the unmeasured value is zero.
Reflect padding
747
Assume the signal mirrors at the boundary.
Padding supplies values beyond the observed domain; its width controls output size and its rule changes border evidence.
Stride
Evaluate every valid start: .
Stride
Evaluate starts ; the others are skipped.
The filter is unchanged. The output samples fewer spatial positions, so a one-pixel input shift can land on a different sampling phase.
Stride reduces resolution by choosing where to evaluate the local rule.
Max pooling keeps the largest value.
Average pooling keeps the local mean.
Both reduce a region to one number, discarding the exact arrangement inside that region.
Pooling can make some small shifts less consequential, but it does not guarantee translation invariance.
Pooling trades spatial detail for a compact summary.
Receptive-field size: four input positions can influence one layer-2 output.
Output spacing: adjacent layer-2 outputs begin two input positions apart.
Depth composes local dependencies into larger input regions; stride also changes how far adjacent outputs jump.
Track two quantities
One axis; sequential local layers; dilation 1.
: receptive-field size
: input spacing between adjacent outputs
| Stage | ||||
|---|---|---|---|---|
| input | — | — | 1 | 1 |
| layer 1 | 3 | 1 | 3 | 1 |
| layer 2 | 2 | 2 | 4 | 2 |
For this two-layer path, one output sees four input positions while adjacent outputs are spaced two positions apart.

Early block
Fine spatial detail remains visible.
Deeper blocks
Resolution shrinks while channels combine earlier responses.
Interpret carefully
Strong activation does not give every channel a simple human-readable meaning.
Composition through layers changes both what a channel represents and how precisely it preserves location.
Retained: which channels responded strongly.
Discarded: where within each map the responses occurred.
Global average pooling creates location-insensitive summaries by explicitly removing spatial coordinates.
━━━━
Conv1d
Slides along one spatial axis: time, sequence position, or distance.
Input:
▦
Conv2d
Slides along height and width: images and spatial fields.
Input:
▧
Conv3d
Slides along three spatial axes: volumes or space–time grids.
Input:
The dimension counts convolved spatial axes; channels remain measurements or learned features at each location.
Accuracy · validation-selected epoch 30
| Model | Validation | Test |
|---|---|---|
| MLP | 0.536 | 0.521 |
| Conv1d | 0.675 | 0.654 |
Same split, seed, optimizer, and 30-epoch budget.
Both validation losses were still decreasing. This is one non-converged run on a synthetic benchmark—not a general ranking of CNNs and MLPs.
Here the local, shared architecture reached higher accuracy within 30 epochs; this does not establish faster wall-clock training.
A useful match
A weak match
Treat locality and sharing as hypotheses. Compare against credible alternatives with validation data and inspect failures under the shifts that matter.
CNNs work when their architectural assumptions resemble the structure of the task—not merely because the input can be arranged as a grid.
Architectural choices that made deep visual models trainable.
RGB crop→5 convolutional layers→3 fully connected layers→1000 classes
Use the available scale
1.2 million training images and two GPUs made a large model feasible.
Make optimization practical
ReLUs trained faster than saturating nonlinearities; pooling reduced spatial resolution.
Control overfitting
Random crops and reflections, colour augmentation, weight decay, and dropout.
ILSVRC 2012 top-5 test error: AlexNet ensemble 15.3% · second-best entry 26.2%
AlexNet’s result came from a coordinated model–data–compute–optimization system, not from convolution alone.
Architecture, training choices, and reported competition result: (Krizhevsky et al. 2012).
Follow the authors’ argument
Problem→design constraint→intervention→evidence
Questions to carry into the paper
Architecture: five convolutional + three fully connected learned layers Optimization: ReLU comparison on CIFAR-10 Generalization: augmentation, dropout, held-out error
Read an architecture paper as a chain of design claims and evidence—not as a list of layers to memorize.
Guided reading: (Krizhevsky et al. 2012).
2012 paper reportTraced Torchvision implementation
The name identifies a model family. It does not make a library implementation a literal reconstruction of the paper.
Paper specification: (Krizhevsky et al. 2012). Torchvision values come from the repository’s reviewed FX trace of alexnet(weights=None).
If added layers can represent identity
So its best achievable training error should be no worse.
But plain networks were harder to optimize
On CIFAR-10, the deeper plain network showed higher training error.
Higher training error diagnoses an optimization problem; overfitting would instead describe a widening train–test gap.
When the shallow function can be preserved, extra depth need not worsen the best fit—but optimization may still struggle.
Constructed identity solution and 20/56-layer degradation experiment: (He et al. 2016). Bars are schematic, not digitized paper data.
If the desired mapping is near identity, learn a small correction. If identity is adequate, drive toward zero.
The block learns what should change relative to its input, while the shortcut preserves a reference path.
Residual sum before a following activation; collects branch parameters (He et al. 2016).
Forward signal
The block can preserve directly while adding a learned transformation.
Backward sensitivity
At the sum, the Jacobian has an identity term. A following ReLU adds its own gate.
This creates a useful route for signals and gradients. It does not guarantee convergence, prevent every vanishing gradient, or make arbitrary depth beneficial.
Addition lets the direct path and learned path coexist; optimization can use both.
Residual block definition: (He et al. 2016). The derivative follows from the block equation.
Identity shortcut: shapes already match
Projection shortcut: shape must change
Elementwise addition requires equal batch, channel, and spatial dimensions; a projection is used when they differ.
Automatically traced, untrained Torchvision ResNet-18 graphs; shortcut equations from (He et al. 2016).
| Model | Block | Blocks per stage |
|---|---|---|
| ResNet-18 | basic, 2 conv | 2 · 2 · 2 · 2 |
| ResNet-34 | basic, 2 conv | 3 · 4 · 6 · 3 |
| ResNet-50 | bottleneck, 3 conv | 3 · 4 · 6 · 3 |
| ResNet-101 | bottleneck, 3 conv | 3 · 4 · 23 · 3 |
| ResNet-152 | bottleneck, 3 conv | 3 · 8 · 36 · 3 |
Across stages: spatial resolution falls while channel capacity rises.
The family scales depth by repeating residual blocks within a stable four-stage spatial design.
Family configurations and stage rules: (He et al. 2016). ResNet-18 overview is an automatically traced Torchvision implementation.
1 · Center→2 · Scale→3 · Restore flexibility
describe a chosen set of activations. prevents division by zero and limits extreme scaling. are learned with the rest of .
Normalization changes the parameterization and optimization path. It does not guarantee unit variance after the learned affine step, nor does it make every deeper network train well.
The equation is shared; the method is defined by which activations contribute to and .
Batch-normalizing transform and learned affine parameters: (Ioffe and Szegedy 2015).
For each channel :
One learned pair is shared across spatial positions.
channel 0: its own statisticschannel 1: different statisticschannel 0 at another location: same statistics
BatchNorm2d(C) couples examples and locations within each channel; it does not mix channels into one mean.
Convolutional BatchNorm axes: (Ioffe and Szegedy 2015).
Training mode
The current batch affects every example’s output. Running estimates are updated for later evaluation.
Evaluation mode
The learned remain active, but the current evaluation batch does not set the statistics.
Small or correlated batches: noisy, unrepresentative training statistics. Domain shift: stored statistics may describe the pretraining domain poorly. Wrong mode: training and evaluation can silently disagree.
BatchNorm carries state: correct train/eval mode and representative batches are part of the model’s behavior.
Default track_running_stats=True: PyTorch BatchNorm2d; (Ioffe and Szegedy 2015).
is deliberately large so its numerical role is visible; production defaults are usually much smaller.
LayerNorm computes statistics from the chosen coordinates of this example, then learns how each normalized coordinate should be scaled and shifted.
LayerNorm construction: (Ba et al. 2016).
normalized_shape names the trailing axes that share statistics. For tokens, is token count and is embedding width.
LayerNorm((C,H,W))one over every channel and pixel of each image
LayerNorm((H,W))separate for each map
LayerNorm(D)separate across features for each token
The affine parameter shape follows normalized_shape; changing the axes changes both the statistics and the learned degrees of freedom.
LayerNorm is batch-independent, but its meaning is incomplete until the normalized axes are stated.
Single-example LayerNorm principle: (Ba et al. 2016). Axis notation: PyTorch LayerNorm.
| Choice | Statistics over | Batch coupling | Train / eval | Useful starting point |
|---|---|---|---|---|
BatchNorm2d(C) |
for each | yes | different statistics | CNN with representative batches |
LayerNorm((C,H,W)) |
for each | no | same computation | batch-independent whole-image features |
LayerNorm(D) on |
for each | no | same computation | token features (e.g. ViT) |
| no normalization | none | no | same computation | baseline to test on validation data |
Choose axes that preserve distinctions the task needs, then test the choice under the actual batch size and deployment distribution.
Normalization is an architectural hypothesis about which activation scales may be treated as nuisance variation.
BatchNorm: (Ioffe and Szegedy 2015). LayerNorm: (Ba et al. 2016).
Match invariances, pretraining, and model choice to the evidence available.
A plausible label-preserving change
Horizontal reflection can preserve an object-class label.
A label-changing change
Reflection reverses the meaning of a direction sign.
Training on with the original label asserts that for the task.
Use augmentation only when the transformation preserves the target and resembles variation expected after deployment.
AlexNet used random crops, reflections, and colour augmentation as task-specific regularization (Krizhevsky et al. 2012).
Pretrained backbonesource-task features→fixed representation→New task headrandomly initialized→Target prediction
Frozen
Backbone parameters and normalization state stay fixed; use evaluation mode.
Trainable
Only the new head follows the gradient update.
Strong starting point when target labels or compute are limited and the source representation matches the target domain.
Frozen transfer tests whether an existing representation already separates the new task.
Feature transfer becomes less reliable as source and target tasks diverge (Yosinski et al. 2014).
| Strategy | Updated parameters | Adaptation | Main risk |
|---|---|---|---|
| Head only | new task head | low | representation mismatch |
| Partial | head + later blocks | medium | unstable frozen/trainable boundary |
| Full | entire network | high | overfitting or destructive updates |
start with head only→unfreeze later blocks→fine-tune all layers if evidence supports it
Compare strategies on the same validation split. Use smaller learning rates for pretrained parameters and inspect domain-specific errors.
Fine-tuning trades preservation of reusable features for adaptation to the target task; validation chooses the useful amount.
Transferred initialization can improve generalization even after target-task fine-tuning (Yosinski et al. 2014).
| Starting assumption | CNN | Image MLP | Vision Transformer |
|---|---|---|---|
| Input units | pixels or features on a grid | flattened pixels or patches | embedded image patches |
| Early interaction | local, shared filters | dense or token-mixing layers | self-attention can connect distant patches |
| Spatial prior | strong locality and translation sharing | depends on design | position must be represented explicitly |
| Evidence to seek | task matches local repeated patterns | simple baseline is competitive | pretraining, data, and compute justify weaker image-specific bias |
These are typical starting assumptions, not permanent boundaries: hybrids and modern variants combine them.
Choose the architecture whose assumptions and resource needs match the task, then compare it against credible baselines.
ViT represents images as patch sequences and uses position embeddings; its original study found stronger dependence on pretraining scale than comparable CNNs (Dosovitskiy et al. 2021).
Decision question: does the model keep using the right evidence when conditions change in ways that matter?
A high average score is the beginning of evaluation; deployment claims require failure analysis under realistic shifts.
Local evidencesmall receptive fields→Shared filtersreuse across positions→Compositionlarger structures through depth→Aggregationtask-level prediction→Validationtest assumptions on data
Why CNN ideas work
They reduce the search space when locality, repetition, and hierarchy describe the task.
When they fail
The imposed invariances or connectivity can discard distinctions the target needs.
Architecture encodes a hypothesis about visual structure; training fits it, and held-out evidence decides whether it was useful.
1959 · Measured visual selectivity
Hubel and Wiesel characterize receptive fields in cat visual cortex.
1980 · Neocognitron
Fukushima proposes a hierarchical network designed for shift-tolerant pattern recognition.
1989 · Learned convolutional recognition
LeCun and colleagues train a constrained network for handwritten ZIP codes.
1998 · LeNet-5 and documents
Gradient-based convolutional systems are evaluated in practical document recognition.
2012–2016 · Scale and depth
AlexNet demonstrates GPU-scale ImageNet training; residual learning supports much deeper models.
2021 · Vision Transformer
Patch tokens and self-attention offer a scalable alternative visual architecture.
Progress came from changing architectural assumptions together with data, optimization, and compute.

Yann LeCun helped make trainable convolutional networks a practical approach to visual recognition.
1989 · Learn the filters
Task-specific architectural constraints and backpropagation support handwritten ZIP-code recognition (LeCun et al. 1989).
1998 · Build a recognition system
LeNet-5 connects learned convolutional features to document-reading applications (LeCun et al. 1998).
2018 · ACM A.M. Turing Award
LeCun shares the award with Geoffrey Hinton and Yoshua Bengio for conceptual and engineering breakthroughs in deep neural networks (Association for Computing Machinery, n.d.).
Local connectivity and shared parameters become useful when they are trained end to end for the task.
← Lectures Introduction to Machine Learning · Week 05