BatchNorm2d
Stabilize each feature channelUses that channel’s values across N×H×W. It suits classic CNN stages, but training statistics depend on the mini-batch.
Yann LeCun’s late-1980s work made trainable convolutional networks practical for handwritten recognition.
Kunihiko Fukushima’s Neocognitron established an influential hierarchical, locally connected predecessor.
LeCun and colleagues at Bell Labs trained shared-weight networks with backpropagation to recognize handwritten ZIP-code digits.
CNN-based document recognition moved into commercial check-reading systems.
LeNet-5 and graph transformer document systems were described in the landmark IEEE paper.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A real industrial problem: turn handwritten amounts on US checks into reliable machine-readable records.
AT&T / NCR systems combined CNN recognition with segmentation and contextual constraints. Low-confidence readings could be sent to human review.
LeCun’s historical homepage reported an estimate of 10% of all checks written in the US read by a system he helped develop. This is a historical estimate, not a current market-share claim.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A feature map has a spatial grid and a channel axis. A batch adds one more dimension.
Actual TensorFlow.js convolution · N = 1 · bias = 0 · Conv2d → optional activation → optional pooling. Filters are hand-designed or seeded random, not trained. Feature maps are revealed in row-major order as the selected channel is computed; later channels remain hidden until their turn. Spatial views use the same fixed pixels-per-cell scale. Each map is independently scaled for display; black = its minimum and white = its maximum. All three input channels contribute to each output.
Photo: “Pug sophie” — existentist · CC BY 3.0 · resized and channel-separated for this demonstration.
One standard filter has shape Cin × K × K. Its dot product sums over spatial positions and all input channels.
PyTorch images: NCHW. Browser / TensorFlow.js images: NHWC. This deck labels the layout when showing shapes.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A CNN receives a batch tensor. PyTorch normally uses NCHW: batch, channels, height, width. Each output channel is produced by one learned filter spanning the connected input channels.
Track shapes whenever a layer changes channels or spatial size; most convolution mistakes are dimension or layout mistakes. A feature map is one channel of activations, while a filter is a set of weights that produces one output channel. They are related but are not the same object.
Thinking in tensors makes the computation easier to reason about: a pixel is not a single number but a channel vector, and a feature map is not the whole layer but one plane in its output tensor. The batch axis keeps independent examples together for efficient computation; it does not create connections between those examples. When a framework uses NHWC instead of NCHW, the meaning is unchanged even though the memory order and axis indices differ.
For an examination, be able to name every axis and explain why a standard filter has shape Cin×Kh×Kw.
Follow the highlighted input and weight. Multiply, add, then write one output value.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A 2D convolution computes a sliding dot product. At one output location, it multiplies a local input patch by a filter, sums over spatial taps and connected input channels, then optionally adds one bias.
Use it when nearby spatial patterns matter and the same detector should work at every image location. Unlike a dense layer, convolution reuses weights across positions. This preserves spatial structure and usually needs far fewer parameters.
Padding controls what happens near image boundaries, stride controls how densely outputs are sampled, and dilation controls the spacing between taps. None of these changes how many times a particular coefficient is learned: the filter remains shared across positions. Groups change channel connectivity, so they affect both the parameter count and the amount of arithmetic. Bias, when enabled, contributes one additional learned scalar per output channel rather than one per pixel.
For an examination, given H, K, S, P, D, and G, compute the output size, parameter count, and which input channels feed one output channel.
Apply a fixed or custom filter to the pug photograph. The weights stay the same as the sampled patch moves.
Fixed filters encode rules we choose. Learned convolutions acquire weights during training. This embedded MobileNet-v1 (width 0.25) learned on ImageNet. Here its frozen weights transform your image through spatial filters, channel mixing, and a classification head; uploading an image runs inference, not training.
Model input: center crop → 224×224 RGB → values −1 to 1. Local inference; image stays in this page.
Select a class to see its class-specific evidence map.
Every saved layer is shown in execution order from the 224×224 RGB tensor through depthwise spatial filtering, pointwise channel mixing, normalization, ReLU6, global pooling, and the 1,000-class head. Each card includes its exact output shape, operation settings, and parameter count.
The pathway appears after inference.
Move across the output stack to inspect channels in real time. The hovered slice is pulled from its fixed 0-to-N−1 position, outlined in gold, and enlarged at right. Each channel is independently normalized for display; brightness cannot be compared across channels. Class maps use positive evidence for a class logit at the final 7×7 feature layer. They are coarse attribution maps, not segmentation masks or a guarantee of causal explanation.
Fixed demonstration filters, not trained weights · one input plane · stride 1 · zero padding 1 · bias 0. Output display is scaled symmetrically around zero: dark = negative, gray = zero, light = positive. Sampling marks do not change the image.
Photo: “Pug sophie” — existentist, CC BY 3.0; resized and converted to a single input plane.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Weight sharing means the same filter coefficients are applied at every valid spatial position. Training learns one detector that can respond wherever its pattern appears.
Use convolution when translation of a local pattern should not require a new parameter set for every location. Local connectivity limits each output to a neighborhood; weight sharing makes the detector reusable. A locally connected layer has local receptive fields but separate weights at each position.
Sharing is the source of convolution's strong inductive bias. The model assumes that a useful edge, texture, or part detector should remain useful after translation. This assumption greatly improves statistical efficiency, but it can be inappropriate when absolute position has special meaning. Boundary handling, downsampling, and later global aggregation also prevent a complete guarantee of translation equivariance in a practical network.
For an examination, distinguish translation equivariance from invariance: shifting the input shifts a convolutional feature map; pooling or aggregation may add approximate invariance.
GEMM = General Matrix–Matrix Multiplication. Each patch becomes a column. One flattened filter becomes a row. Their product gives all spatial outputs.
One input channel · one output filter · bias = 0. Gold marks the selected output position; amber cells are zero padding.
All entries are included. Scroll horizontally or vertically for larger matrices; the active column is highlighted.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Unfold (im2col) copies every receptive-field patch into a column. Flattened filters form rows, so one matrix multiplication computes every output position before reshaping the result.
Use this view to derive convolution, debug indexing, or understand why optimized convolution can map to GEMM hardware. The result is exactly the same as direct convolution. Explicit im2col can duplicate data and consume memory, so libraries may use implicit GEMM, direct, Winograd, or FFT kernels instead.
The matrix view separates data rearrangement from arithmetic. Unfold determines exactly which input values belong to every receptive field, while the matrix product applies all filters to all patches in parallel. During backpropagation, gradients from overlapping columns must be accumulated back into their shared input locations. This explains why fold is a sum-over-overlaps operation rather than a simple inverse of unfold.
For an examination, explain what one column represents, why columns overlap, and why reshaping restores the spatial output.
Flatten the input instead. Copy the same kernel into shifted rows of a large, sparse matrix.
nn.Conv2d / F.conv2d call a convolution backend; they do not build this dense A matrix. The backend selects a fast direct convolution, implicit GEMM, Winograd, FFT, or platform-specific kernel based on tensor shape, device, dtype, and available libraries. This avoids storing mostly-zero A while preserving the same mathematical result.
One input channel · one output filter · bias = 0. Gold marks the selected output position; amber cells are zero padding.
All entries are included. Scroll horizontally or vertically for larger matrices; the active row is highlighted.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Convolution is a linear map y = Ax when the input and output are flattened. Each row of sparse A places a shifted copy of the same kernel weights at the input indices used by one output.
Use this operator view to reason about transposed convolution, adjoints, sparsity, and gradients. A is a mathematical construction, not a new set of learned weights. Repeated entries in A are tied to the same K² kernel values, so materializing dense A wastes memory.
The repeated diagonals and shifted rows of A expose two important properties: locality, because each row has only a small set of nonzero entries, and sharing, because those entries reuse the same kernel values. The transpose AT reverses the direction of information flow but does not compute A-1. This distinction is central when interpreting transposed convolution and convolutional gradients.
For an examination, do not count every nonzero entry of A as a parameter. Count the unique shared kernel coefficients (plus optional bias).
Split the channels into independent groups. Each output filter sees only the inputs in its own group.
Choose an output channel to bring its map and filter to the front. Matching colors show connectivity; there are no connections between groups. Highlighted input cells form the current 3×3 window. Toy inputs and weights are deterministic; output values are computed exactly.
Matching configuration; PyTorch initializes its own random weights. The browser uses illustrative fixed weights.
Grouped convolution partitions the input and output channels into equally sized groups. Each output filter spans every input channel within its group, sums their spatial dot products, and produces one output map. The same filter is reused at every spatial position. Both channel counts must be divisible by the number of groups.
With one group, this is standard convolution. With groups equal to the input-channel count, each filter sees just one input channel: this is depthwise convolution, provided the output count is an integer multiple of the input count. That multiple is the depth multiplier. Grouping reduces connectivity and weights; it does not by itself reduce the requested number of output channels or the output spatial size.
Grouping can lower computation and parameter cost, but information cannot cross group boundaries in this layer. A later ungrouped 1×1 convolution can mix the channels. The weight count is Cout × (Cin / G) × 3 × 3; this example disables bias. With stride 1 and no padding, a 5×5 input produces a 3×3 output.
Think of this as a regular convolution within each group, followed by concatenation of the output maps along the channel axis. Every group scans the full spatial grid; grouping partitions channels, not image regions. Its connectivity can be drawn as independent diagonal blocks. For fixed input/output sizes, both the weight count and convolution MAC count are reduced by a factor of G compared with an ungrouped layer.
AlexNet used grouped connections to split work across two GPUs; ResNeXt later emphasized the number of parallel groups (cardinality). Repeatedly keeping the same groups isolated restricts communication, so architectures can use an ungrouped pointwise layer or channel shuffling followed by further grouped layers to exchange information.
A learned matrix mixes the channel vector at every sampled pixel, without looking at neighboring pixels.
The gold square is one pointwise operation. Stride controls how far it jumps before applying the same 1×1 channel-mixing weights again.
With stride 1 and padding 0, H and W stay the same. With stride 2 on an 8×8 input, the output becomes 4×4. A 1×1 layer can expand, compress, or mix channels; it cannot directly see neighboring pixels.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A 1×1 convolution applies the same learned matrix to the channel vector at each sampled pixel. It changes or mixes channels without directly inspecting neighboring pixels.
Use it to compress or expand channels, build bottlenecks, or combine depthwise features efficiently. A spatial K×K convolution mixes neighbors and channels. A pointwise layer only mixes channels; stride greater than one may also downsample by sampling fewer locations.
At each pixel, the layer behaves like a small fully connected layer applied to the channel vector, with the same matrix reused over the entire image. A row of W defines one output channel, and its coefficients say how strongly that output uses each input channel. The layer can therefore learn combinations such as color opponency or recombine specialized feature detectors while retaining the current spatial coordinate.
For an examination, for 3 input and 4 output channels with bias disabled, state why W has shape 4×3 and exactly 12 learned parameters.
Factor one full convolution into a spatial stage, then a channel-mixing stage.
Same padding is assumed. Bias is off so the comparison isolates convolution weights and multiply-adds.
groups = Cin. It performs K×K spatial filtering independently in each channel. The following pointwise 1×1 convolution has groups = 1, so each output channel can combine all depthwise channels.Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Depthwise separable convolution factorizes a standard convolution into depthwise spatial filtering followed by pointwise channel mixing.
Use it when compute, memory, or model size matters and some loss of cross-channel/spatial coupling is acceptable. It is cheaper than a regular convolution because it replaces CinCoutK² weights with CinK² + CinCout. It is not identical in representational form to one unrestricted convolution.
The factorization imposes a structural constraint: spatial patterns are first learned independently inside channels and only then recombined. That constraint lowers cost but can reduce expressiveness compared with an unrestricted K×K filter that jointly models space and channels. Modern efficient architectures compensate with nonlinearities, normalization, expansion layers, and repeated separable blocks.
For an examination, calculate both counts and explain which stage learns spatial patterns and which stage learns channel combinations.
Spread the taps apart to see a wider field without adding weights.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Dilated convolution inserts gaps between sampled kernel taps. It enlarges the receptive field without increasing the number of kernel weights.
Use it when dense prediction needs more context while retaining a relatively high-resolution feature map. Increasing kernel size also enlarges context but adds parameters; dilation preserves K² weights. Large repeated dilation patterns can create gridding gaps, so practical models often vary dilation rates.
Dilation is especially useful when the output must remain dense, because it increases context without an immediate pooling step. However, widely spaced taps may miss fine structures between sampled locations. Combining several dilation rates or mixing dilated and ordinary convolutions helps cover both local detail and broad context, which is why atrous spatial-pyramid designs use parallel rates.
For an examination, compute Keff and then use it in the normal output-size formula. Dilation changes sampled spacing, not the learned-weight count.
As unfold turns convolution into gather-and-multiply, transposed convolution lets each input scale a shifted kernel column. The contributions add into the output.
One input channel · one output filter · bias = 0 · output_padding = 0. Gold marks the selected input and its scattered kernel taps.
Each column is one shifted copy of the kernel. The active column is multiplied by the selected input value.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript lab does.
Transposed convolution applies the transpose of the linear operator associated with convolution: input values scatter weighted contributions into an output grid, and overlaps add.
Use it for learned spatial upsampling in decoders and generative networks when the upsampling kernel should be trainable. It is not an inverse convolution and does not reconstruct lost information automatically. Resize-then-convolve offers more explicit interpolation and can reduce checkerboard artifacts.
Each input cell writes a scaled copy of the kernel into the output canvas. When copies overlap, their contributions add, so the pattern of overlap matters. If the kernel size is not well matched to stride, some output locations receive more contributions than others, which can produce checkerboard structure. A following convolution after explicit interpolation offers another learnable decoder design with more uniform initial coverage.
For an examination, explain scatter-and-add, distinguish output_padding from actual zero padding, and know why uneven overlap can create checkerboards.
A Conv3d kernel reads the same spatial neighborhood in adjacent video frames, then writes one value into a spatiotemporal output volume.
PyTorch stores weights as [Cout, Cin, Kt, Kh, Kw]. With RGB, each output filter owns three 3D slices—one each for R, G, and B—and sums all three.
Sizes such as 3, 5, and 7 have one unambiguous center voxel. Symmetric padding can then keep that center aligned with the output position.
Equal spatial sides avoid favoring one direction and simplify design and optimization. Rectangular or anisotropic kernels are still useful when space and time have different scales.
Copyable Python reference code. The JavaScript lab crops the first ten frames from the cited sequence and computes every displayed padded, stride-1 output locally.
A 3D convolution slides through depth/time as well as height and width. Each filter spans all connected input channels and a Kd×Kh×Kw volume.
Use it for video clips, volumetric medical scans, or other data where nearby slices or frames contain meaningful local structure. Stacking frames as channels loses explicit translation along time. Conv3d preserves a depth/time axis and shares the kernel as it moves through that axis, but costs more memory and compute.
For video, the depth axis normally represents time; for CT or MRI, it represents physical slices. A temporal kernel can detect motion or change because it observes several neighboring frames at once. Kernel depth should reflect the sampling rate and phenomenon being modeled: a very short temporal window may miss slow motion, while a large one increases computation and may blur distinct events.
For an examination, separate the channel axis from the depth/time axis, then compute Dout, Hout, and Wout independently.
At time t, use only the present and past. Never leak future values into the prediction.
WaveNet stacks dilated causal convolutions to grow temporal context efficiently.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A causal convolution prevents an output at time t from using future inputs. Padding and masking arrange the receptive field entirely at or before t.
Use it for autoregressive generation, streaming inference, forecasting, or any task where future information is unavailable or would leak the answer. A centered convolution sees both past and future and is appropriate for offline sequence labeling. Causality is about information flow, not merely using Conv1d.
Causality is a constraint on dependency rather than a special learned parameter. During training, a mask or asymmetric padding must enforce the same information restriction that will exist during generation or streaming. Dilated causal stacks are attractive because their history grows quickly while computation remains parallel across known training positions, unlike strictly sequential recurrent updates.
For an examination, given a stack of dilated causal layers, trace which earlier time steps can influence one output and verify that no future index appears.
“Convolution” can be defined through a Fourier basis or a graph Laplacian instead of a rectangular pixel grid.
Zero-padding is needed for linear convolution via FFT; unpadded multiplication corresponds to circular convolution.
A GCN propagates normalized neighbor information. Its local rule is motivated by approximating spectral graph filters.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Spectral convolution multiplies Fourier coefficients; graph convolution aggregates information according to graph connectivity or a graph-derived operator. Both generalize structured filtering beyond a regular image grid.
Use FFT methods for large/global or periodic filters when frequency-domain multiplication is advantageous; use graph convolutions for meshes, molecules, social networks, and irregular neighborhoods. Image convolution assumes a regular translation grid. Graph neighborhoods vary by node, while spectral methods define filtering through basis functions or eigenvectors and may have different localization costs.
The Fourier convolution theorem can make very large convolutions efficient, but transforming into and out of the frequency domain has overhead, so small image kernels are often faster with specialized spatial kernels. Graph convolution replaces the regular image neighborhood with edges from an adjacency structure. Its meaning therefore depends on how the graph is built and normalized, not only on the learned weight matrix.
For an examination, state the domain, the neighborhood definition, and whether the method is local, global, or graph-structured before comparing costs.
Max pooling preserves the strongest response; average pooling measures the average response.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Pooling summarizes each local window. Max pooling retains the strongest response; average pooling retains the mean. Pooling has no learned weights unless embedded in a learned mechanism.
Use it to downsample, enlarge later receptive fields, reduce compute, or aggregate a fixed-size summary. A strided convolution learns how to downsample and may change channels. Pooling uses a fixed reduction and normally preserves channel count; it trades precise spatial layout for compactness.
Max pooling answers whether a strong feature occurred in a window, whereas average pooling answers how much of that feature was present on average. Both reduce spatial precision, and repeated pooling can remove small objects or boundary detail. Modern networks sometimes replace pooling with strided convolution so that downsampling itself is learned, but this adds parameters and does not automatically preserve more information.
Global average pooling averages the entire spatial map independently for each channel. An N × C × H × W tensor becomes N × C × 1 × 1. It provides a compact fixed-length descriptor for a classification head even when spatial input size varies, subject to the backbone’s constraints. It discards spatial layout and can dilute a small localized response. Max pooling is useful for retaining strong local detections; local average pooling summarizes distributed responses more smoothly. Neither guarantees translation invariance or preserves all useful detail.
For an examination, compare max, average, adaptive, and strided-convolution outputs; know that pooling is generally not invertible.
Both standardize activations and can then learn γ and β. They differ in which values share statistics, whether behavior depends on the batch, and where they fit in an architecture.
Xi denotes the temporary activation tensor produced by layer i. Open a PyTorch tab to compute its statistics and normalized output explicitly. correction=0 matches the displayed population-variance formulas; keepdim=True retains axes for broadcasting.
Uses that channel’s values across N×H×W. It suits classic CNN stages, but training statistics depend on the mini-batch.
Uses all channels and pixels within one image. It is batch-independent, while strong regions can influence the sample-wide scale.
Uses the channels at each (n,h,w) independently. It preserves separate spatial positions and fits token-style vision blocks.
γ scales; β shifts. They let the network choose how normalized responses should reach the next layer, rather than forcing every response group to stay standardized. For example, β can change which values pass through ReLU. They do not guarantee prevention of overfitting, dead neurons, or vanishing gradients. ε is the numerical safeguard when variance is very small.
Off: output is x̂ (equivalent to γ = 1, β = 0); no affine tensors are stored. Frozen parameters: existing γ and β are still applied, but not updated. Evaluation mode: a separate setting; it does not turn off the affine transformation.
Training computes statistics across N, H, W. Evaluation normally uses running statistics. The same γ and β are reused at every pixel and in every sample within a channel.
Statistics come from each example in both training and evaluation. The axes used to compute statistics and the positions with distinct learned parameters are different concepts.
Keep each normalization local to the block it was designed for. Avoid placing BatchNorm and LayerNorm directly back-to-back: the second normalization largely redefines the scale produced by the first. There is no universal BN→LN or LN→BN rule for the same activation; treat that as an architecture choice requiring an ablation.
Copyable Python reference code. The browser updates axes, parameter counts, and example ordering; Python does not execute inside this HTML.
BatchNorm2d computes one mean and variance per channel over N, H, and W. LayerNorm computes statistics over the chosen trailing dimensions for each sample. Learnable γ and β restore affine flexibility; ε is numerical stabilization.
Use BatchNorm in many CNNs with reliable batch statistics; use LayerNorm when batch size varies or in architectures that normalize within each example. BatchNorm uses running estimates at evaluation and couples examples during training. LayerNorm uses the current example in both modes. Applying both sequentially is uncommon unless an architecture gives a specific reason.
The choice of axes determines which variations are removed. BatchNorm treats all pixels and examples for one channel as samples from the same training-time distribution; LayerNorm standardizes selected features inside each example. The affine parameters do not undo normalization: they let the network learn a useful scale and offset after standardization. Small or non-independent batches make BatchNorm statistics noisy, while LayerNorm remains independent of other batch members.
For an examination, for NCHW input, state the reduction axes and statistic shapes: BN has C statistics; full CHW LayerNorm has N independent statistic pairs.
Without nonlinearities, compositions of linear layers collapse into one linear operation.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
An activation applies a nonlinear function after a learned affine operation. Without nonlinearities, stacked convolutions collapse to one linear operator and cannot model complex decision boundaries.
ReLU is a simple CNN default; leaky variants preserve a small negative slope; sigmoid is useful for independent probabilities or gates; softmax converts logits into a categorical distribution. ReLU is cheap but can produce inactive units. Smooth activations such as GELU have different gradient behavior. The output task, not visual preference, determines sigmoid versus softmax.
An activation also shapes optimization. Saturating sigmoid or tanh regions produce small gradients, while ReLU keeps a constant positive-side derivative but discards negative responses. The final layer has a different purpose from hidden activations: it must match the semantics of the target and loss. For example, raw logits are preferred by cross-entropy implementations because they can combine softmax and logarithms stably.
For an examination, explain why nonlinearity is essential and match an output activation/loss to multiclass versus multilabel prediction.
Use the same pug input to distinguish activation regularization from parameter regularization. Select one method to activate its visualization.
How to read the kernel bars: each kernel uses its own original maximum magnitude as the fixed ±1 display scale. The cyan “next” label reports the numerical update, so changes remain visible even when a large coefficient makes the bar-height change subtle.
The browser runs a labeled toy simulation. The PyTorch block is reference code and can be copied.
Dropout regularizes activations by sampling paths during training. L1, L2, and Elastic Net regularize weights by adding penalties to the task loss; optimizer details determine the exact update.
Use dropout to reduce co-adaptation; L1 to encourage exact sparsity; L2/weight decay to discourage large weights; Elastic Net when both sparsity and shrinkage are useful. L1 exerts roughly constant-magnitude pull and can reach zero. L2 pull grows with |w| and usually shrinks smoothly. Decoupled weight decay is not always identical to adding L2 to the loss for adaptive optimizers.
Regularization changes the preference among solutions that fit the training data. Dropout injects multiplicative noise into intermediate representations; weight penalties change the optimization objective or parameter update. Their effects are not guaranteed to match a simple visual story for every weight, because the task gradient acts at the same time. A coefficient can still grow under L2 if the task gradient pushing it outward is stronger than the shrinkage term.
For an examination, distinguish activation regularization from parameter regularization, and explain subgradient versus proximal L1 updates without treating them as the same algorithm.
A common starting point, with deliberate choices for normalization, nonlinearity, and downsampling.
A convolution bias adds the same number to every spatial value in one output channel. During training, BatchNorm subtracts that channel’s mean, cancelling this constant offset. Its learned β already supplies a new offset.
Disable convolution bias when BatchNorm directly follows it. BatchNorm still learns γ and β. Do not simply remove bias from an already trained model without adjusting its stored statistics.
Usually choose one normalization suited to the architecture. BatchNorm pools statistics across batch and space per channel; small or unrepresentative batches can make its statistics unreliable. LayerNorm uses each example’s configured axes and has no running batch statistics.
Channel-only LayerNorm normalizes across channels at each pixel. Per-channel convolution biases do not generally cancel under this normalization, so the BatchNorm bias rule does not carry over. In PyTorch, LayerNorm(C) needs C as the last tensor dimension.
A useful conventional block is convolution, BatchNorm, activation, and optional downsampling. Convolution learns spatial and channel combinations, normalization controls the scale and offset of its responses, and an activation makes the transformation nonlinear. A stack of linear operations alone cannot supply the same expressive power. Pooling reduces spatial resolution only when the architecture needs it; it is not required after every convolution.
There is no single correct order for all CNNs. Preactivation residual networks put normalization and activation before convolutions, while ConvNeXt uses depthwise convolution, channel-wise LayerNorm, channel expansion, GELU, projection, and a residual addition. These are designed blocks, not arbitrary permutations. When reproducing an architecture, preserve its specified order. Do not routinely stack BatchNorm and LayerNorm as though both were required.
Choose either pooling or a strided convolution for a planned downsampling stage unless two reductions are intended. Repeated downsampling can erase small objects and boundaries. Residual additions require matching shapes, sometimes via projection; global average pooling belongs near a classification head when spatial layout is no longer needed. Dropout or stochastic depth are optional regularizers with placement and strength chosen for the architecture.
For BatchNorm, training uses batch statistics and evaluation normally uses running statistics. Use model.train() and model.eval() appropriately. LayerNorm uses input-derived statistics in both modes. Shape tracing, correct channel axes, a suitable normalization, and a verified implementation matter more than treating one block ordering as universal.
A Convolutional Neural Network (CNN) extracts hierarchical visual features that can support a wide range of computer vision tasks.
Convolutional blocks typically reduce spatial dimensions (H × W) while increasing feature channels (C), learning increasingly complex visual patterns.
Feature maps—for example, 2048 × 7 × 7 in C × H × W order—encode high-level visual information. Dense tasks may also use earlier, higher-resolution maps.
The head transforms these features into the output required by the task. The backbone and head are normally trained or adapted together for that task.
Predicts image-level class scores, converted to probabilities when needed.
Locates and classifies objects using bounding boxes.
Assigns pixel-level labels or individual object masks.
Estimates scene geometry and pixel motion.
Generates or enhances images using decoder networks.
Predicts landmark locations or compact feature vectors.
Illustrative architecture; exact shapes depend on kernel, stride, padding, and resizing choices.
Illustrative architecture; exact shapes depend on kernel, stride, padding, and resizing choices.
Illustrative architecture; exact shapes depend on kernel, stride, padding, and resizing choices.
Illustrative architecture; exact shapes depend on kernel, stride, padding, and resizing choices.
Fixed-size kernels remain local within each layer, while deeper activations integrate increasingly large regions of the original image.
Copyable Python reference code. ReLU changes values, not receptive-field geometry.
The receptive field of a deeper unit is the region of the original image that can influence it. Repeated convolution and downsampling let fixed small kernels integrate evidence from progressively larger regions.
Use receptive-field reasoning when a prediction needs sufficient context, especially in detection, segmentation, and dense prediction. More channels provide more learned feature types; they do not themselves enlarge the spatial receptive field. Depth, kernel size, stride, pooling, and dilation control receptive-field growth.
A deeper feature channel should not be interpreted as a literal picture of one object part in every case. It is a distributed learned response whose meaning emerges together with other channels. Downsampling makes each remaining cell summarize a larger input region, while additional channels provide capacity for more response types. The elephant analogy is useful for local evidence, but the network combines overlapping, learned measurements rather than independent verbal descriptions.
For an examination, differentiate theoretical receptive field from effective receptive field: all positions may be reachable, but influence is often concentrated near the center.
The task determines the head: classification may collapse space, while dense prediction must return a spatial field.
448 × 448 image → convolutional backbone → 7 × 7 × 1024 → flatten → FC 4096 → FC 1470 → reshape 7 × 7 × 30.
Each grid cell predicts boxes, object confidence, and class scores. YOLOv1 therefore does not use global pooling: collapsing the 7 × 7 grid would erase which cell owns each detection. Newer YOLO families generally use fully convolutional, multi-scale detection heads rather than YOLOv1’s two fully connected layers.
Depthwise 3 × 3 filters handle cheap spatial processing; pointwise 1 × 1 convolutions mix channels. The final feature tensor is 7 × 7 × 1024. A 7 × 7 average pool produces 1 × 1 × 1024, then an FC layer produces 1000 ImageNet logits.
This head accepts other valid spatial sizes when implemented with adaptive global pooling, because it always returns one number per channel.
The contracting path increases semantic context while shrinking H and W. The expanding path upsamples. Skip connections copy fine, same-resolution encoder features into the decoder so object boundaries are not reconstructed from the bottleneck alone.
Flattening or global pooling would destroy the per-pixel correspondence required by segmentation. A final 1 × 1 convolution maps the decoder features to K class logits at every pixel.
The encoder forms progressively smaller feature maps through conv1 … conv6. A coarse flow is predicted at conv6, then upconvolutions combine that prediction with higher-resolution encoder features and refine it at flow5, flow4, flow3, and flow2.
This is a multi-resolution feature/prediction pyramid: several scales represent the scene, and coarse motion guides finer estimates. It predates and differs from the named FPN detection neck, but uses the same coarse-to-fine idea.
The encoder compresses local texture and wider context into learned features. The decoder expands those features back to a spatial image. This example uses a coarse prediction followed by a refinement network; autoencoders and VAEs use the same broad encode–latent–decode pattern, although a VAE additionally learns a probabilistic latent distribution.
No global classifier pool is used at the end because the network must emit a value for every output location. Depending on the task, the last convolution commonly produces one grayscale channel or three RGB channels.
Linear layer → 10 logits → optional probability conversion. Each row is a different sample. Edit its scores and compare both conversions side by side in class space.
Signed scores, −5 to +5
Computed independently per sample across classes
zᵢ / Σzⱼ · not an arithmetic mean; may give invalid probabilities
Subtracting the largest logit keeps computation stable without changing the probabilities.
Why softmax? Dividing scores by their sum can produce negative values, values above 1, or division by zero. Softmax first maps signed scores to positive values, then normalizes. It preserves score ranking and depends on score differences; adding the same constant to every score changes nothing.
When to use softmax: when displaying class probabilities, sampling a class, or supplying probabilities to a downstream calculation for mutually exclusive classes. It is unnecessary for choosing the largest-score class: argmax is unchanged. High probability does not guarantee correctness; independent multi-label outputs generally use sigmoid.
CrossEntropyLoss expects raw prediction logits and has no from_logits switch. Do not apply softmax before it. It performs the stable log-softmax-based calculation internally. Class-index targets below are integer labels, not logits.
Reference: PyTorch CrossEntropyLoss ↗
Copyable Python reference code. The browser diagram updates the tensor shapes and parameter counts.
Flatten preserves every spatial cell before a dense layer; global average pooling reduces each channel to one number before classification.
Use flatten when the head must depend on a fixed spatial arrangement. Use global pooling for fewer parameters, varying compatible input sizes, and channel-level evidence summaries. Flatten retains layout but its dense layer scales with H×W and fixes the expected feature-map size. Global pooling discards location and uses only C features, so it is compact but unsuitable when exact spatial arrangement is essential.
Suppose a backbone outputs C feature maps. Flatten asks the classifier to learn a separate coefficient for every channel-location pair, so moving the same feature to a different position changes the dense input coordinate. Global pooling summarizes each channel first, making the head indifferent to that within-channel location. This is often suitable for whole-image classification but unsuitable as the only head for detection or segmentation, where location is part of the answer.
For an examination, given C, H, W, and class count, compute both parameter counts and identify what information GAP removes.
Upsampling increases the spatial resolution of an image or feature map. Imagine enlarging an image by estimating values at new pixel locations. Nearest neighbor copies nearby values; bilinear and bicubic interpolation use weighted neighboring values. Transposed convolution instead learns weights for an upsampling operation—it is not a fixed interpolation rule.
Used in segmentation, super-resolution, reconstruction, and generative decoders. Increasing resolution alone does not recover details already lost; learned decoders use features and training data to predict plausible detail.
An additive residual connection forms y = x + F(x): the learned branch can refine existing features by predicting a correction. The shortcut provides a direct gradient pathway, helping deep networks optimize. Addition requires matching tensor shapes; a projection can align channels or spatial size.
Used in ResNet and many deep architectures. “Skip connection” is broader than residual addition: an encoder–decoder may concatenate earlier features instead, preserving detail while increasing channel count.
Attention dynamically emphasizes or combines information. Self-attention mixes information from spatial locations to build context; spatial attention weights where to focus, such as a dog’s face; channel gating weights which feature responses matter, such as texture or edges.
SE-Net gates channels; CBAM combines channel and spatial gating; Attention U-Net gates skip features. These gating mechanisms reweight features, whereas self-attention can explicitly aggregate information across distant locations. Choose the mechanism for the task rather than assuming every attention block gives long-range mixing.
Reading the output: for NCHW output O, O[0, :, 3, 8] is the C-dimensional feature vector at (row 3, column 8) in the first image. After spatial self-attention, this vector can incorporate nearby and distant evidence: fur at one location may be interpreted in the context of ears, eyes, and a muzzle. Channel or spatial gates alone do not imply this same explicit mixing.
Upsampling increases spatial resolution; shortcuts add or concatenate earlier features; attention reweights information according to context. They solve different problems and can coexist in one decoder.
Use resize or transposed convolution for resolution, skip connections for detail/gradient flow, and attention when the model should emphasize informative channels or positions dynamically. Interpolation has no learned parameters. Transposed convolution learns upsampling. Additive shortcuts require compatible shapes; concatenation increases channels. Attention adds data-dependent weighting and computation.
A decoder often combines all three mechanisms: interpolation or transposed convolution grows the grid, a skip connection restores high-resolution encoder evidence, and attention chooses which restored evidence is useful. The order and fusion method affect both shape and meaning. Addition assumes the two paths already express compatible features; concatenation lets a following layer learn how to combine them.
For an examination, for a proposed block, name whether it changes resolution, preserves information, or changes weighting; do not use these terms interchangeably.
Embedded MobileNet-v1 · width multiplier 0.25 · ImageNet · 224×224 RGB. Choose a photo and inspect actual learned activations.
Press Run MobileNet.
No model inference has run yet.
Each map is independently normalized for visibility; brightness is not comparable across maps. A channel has no guaranteed human-readable meaning.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Inference is a forward pass with learned parameters fixed. Evaluation mode changes layers such as dropout and BatchNorm; disabling gradient tracking saves memory and overhead.
Use model.eval() and an inference/no-grad context for deployment or evaluation, while applying exactly the preprocessing expected by the trained model. eval() changes module behavior but does not disable autograd. no_grad()/inference_mode() disables gradient recording but does not switch BatchNorm or dropout to evaluation behavior; both concerns must be handled.
A reproducible inference pipeline includes model weights, architecture, input resizing, color order, numerical range, normalization constants, and class labels. A correct forward pass with incorrect preprocessing can produce confident but meaningless predictions. Deployment also requires deciding how to batch examples, which device and precision to use, and whether the measured latency includes preprocessing and data transfer.
For an examination, explain logits versus probabilities and identify preprocessing, model mode, gradient tracking, and label mapping as separate inference steps.
Class-conditioned localization from activations and gradients—not a proof of causality.
For this MobileNet’s global-average-pool + linear logit head, these gradient weights are proportional to classifier weights. The lab computes this exact special case from trained features.
Uses the image from the previous slide. Map is coarse (7×7), resized for display.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Grad-CAM weights a convolutional layer's feature maps by gradients of a selected class score, then combines them into a coarse localization heatmap.
Use it to inspect which spatial regions support a class prediction, compare failures, or communicate model evidence. It is a post-hoc explanation, not a proof of causality or correctness. Resolution is limited by the chosen feature map, and changing the layer or class can change the map.
Grad-CAM is class-specific because its weights come from the gradient of one chosen score. A region can be visually salient yet absent from the map if it does not positively support that class score at the selected layer. Upsampling the coarse heatmap improves display size but does not create new explanatory resolution. Reliable interpretation therefore compares classes, layers, examples, and ideally intervention-based checks.
For an examination, name the target class and target layer, explain gradient pooling, and state why ReLU keeps positive supporting evidence in the original method.
Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton made CNNs the headline of large-scale visual recognition.
Top-5 test error for their ensemble competition entry, versus 26.2% for the next-best entry. These are challenge results, not the paper’s separate ILSVRC-2010 experiment.
Five convolutional layers + three dense layers; ReLU; GPU training; data augmentation; dropout; about 60 million parameters.
The first huge ImageNet-era CNN breakthrough—not the first CNN success.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
VGG and GoogLeNet already trained deeper networks. ResNet addressed a specific degradation problem.
Some plain deeper networks had higher training error than shallower counterparts. That cannot be explained by overfitting alone.
More layers can make an identity mapping unnecessarily hard to learn.
Deep Residual Learning for Image Recognition
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun (2015; CVPR 2016).
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
Very deep plain networks can suffer a degradation problem: training error becomes worse as depth increases, even when the deeper model could represent the shallower solution.
Use residual parameterization when optimizing deep stacks of transformations is difficult. This degradation is not simply overfitting because training error also rises. A residual block learns a correction F(x) around an identity path instead of learning the full mapping H(x) directly.
Residual learning provides a convenient identity reference. If extra layers are not useful, they can in principle drive their residual branch toward zero instead of reconstructing an identity transformation through many nonlinear layers. This does not mean every block learns only a tiny correction, but it improves information and gradient flow enough to make substantially deeper networks trainable.
For an examination, distinguish optimization degradation from vanishing gradients and from generalization/overfitting, although these phenomena can interact.
Learn a correction while preserving a direct route—and build the residual architecture block by block.
Click a block, then change its internal depth.
This editor keeps tensor shapes fixed inside a block, so the shortcut can remain an identity.
A residual shortcut provides an identity or projected path around a block. The addition gives activations and gradients a direct route through depth.
Use identity shortcuts when shapes match; use a learned projection when spatial size or channel count changes. Addition preserves channel width and merges paths elementwise. Concatenation preserves both tensors explicitly but increases channel count and is the characteristic DenseNet connection pattern.
The shortcut creates two simultaneous computational paths: a transformed residual path and a simpler reference path. During differentiation, the identity path contributes a direct term to the gradient, reducing dependence on every residual weight being well conditioned. When resolution changes, the shortcut must use stride, pooling, padding, or projection so that the tensors can be combined legally.
For an examination, check tensor compatibility before addition, and explain why a projection shortcut has parameters while an identity shortcut does not.
Configure the four stages, inspect the complete residual pipeline, and compare plain versus residual depth.
| Operation | Output · NCHW (N=1) | Trainable parameters | Cumulative |
|---|
Counts include BN γ and β and the FC bias; BN running statistics are buffers and are excluded.
The browser builder calculates BasicBlock and Bottleneck shapes and trainable parameters directly.
ResNet organizes residual blocks into stages. Basic blocks use two 3×3 convolutions; bottleneck blocks use 1×1, 3×3, 1×1 layers to compress, process, then expand channels.
Basic blocks are common in ResNet-18/34; bottlenecks make deeper ResNet-50/101/152 models computationally practical. A bottleneck's 1×1 layers reduce the expensive 3×3 channel width, but the final expansion and projection shortcuts affect the exact parameter count.
A ResNet stage keeps a common output resolution and channel scale across several blocks; the first block of a new stage usually downsamples and increases channels. Bottleneck blocks save computation by doing the expensive 3×3 operation at a narrower width. Model names count weighted layers under the paper's convention, so understanding the stage configuration is more reliable than inferring structure from the number alone.
For an examination, know the block type, stage repetition counts, and when the shortcut needs stride or projection; derive counts from tensor shapes rather than memorizing totals alone.
Both preserve earlier information, but ResNet adds a shortcut while DenseNet keeps every earlier feature map available by concatenation.
The block learns a correction to the current representation. Addition keeps the channel width fixed and provides a direct path for signals and gradients.
Each layer receives the feature maps produced by every earlier layer in the dense block, then contributes a small set of new maps.
Imagine each layer writes a few useful observations into a shared notebook. Later layers read the entire notebook instead of repeatedly rediscovering edges, textures, or shapes.
DenseNet-121 uses dense blocks separated by transition layers; its final classifier follows global average pooling.
ResNet adds a block's input to its output. DenseNet concatenates every earlier feature map within a dense block, so each new layer directly reuses all previous features.
Use ResNet for a strong general-purpose backbone; DenseNet is useful when feature reuse and parameter efficiency are priorities. DenseNet's growth rate k controls how many new channels each layer contributes. Concatenation improves reuse but activation memory and channel count grow, so transition layers compress and downsample.
Dense connectivity gives every layer short routes to the loss and exposes earlier features directly instead of repeatedly relearning them. Because a layer receives the concatenation of all earlier outputs, its input width grows inside the block even though it contributes only k new channels. Transition layers use 1×1 convolution and pooling to control this growth between blocks.
For an examination, compare addition with concatenation and explain growth rate, dense blocks, and transition layers.
Keep the backbone fixed, then choose a task-specific head, tensor shape, and training objective. Change the controls to inspect concrete outputs.
Same embedded “Pug sophie” photograph used earlier · illustrative output, not model inference.
Denoising, deblurring, and super-resolution usually predict N×3×H×W (or a larger spatial size). Pixel and perceptual losses teach different visual qualities.
Depth uses N×1×H×W; surface normals use N×3×H×W. The targets and loss give those channels their physical meaning.
The same backbone-and-head pattern supports medical volumes, satellite maps, industrial inspection, scientific fields, audio, and graphs.
Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.
A shared convolutional backbone can feed task-specific heads. Classification produces class scores; detection produces boxes and classes; segmentation produces per-pixel labels; optical flow produces a 2D motion vector per pixel.
Use task-specific heads when the same learned representation must be decoded into different output structures. Global pooling is appropriate for image-level decisions but destroys location. Dense tasks retain or recover spatial grids, often using pyramids and skip connections for multiple scales.
The backbone answers 'what visual evidence is present?' while each head converts that evidence into the structure required by a task. Feature pyramids expose several spatial scales so large semantic regions and small detailed objects can both be handled. Multi-task systems may share a backbone but must balance losses carefully, because gradients from different heads can reinforce or compete with one another.
For an examination, match the output tensor, loss, and decoder to the task. State which axes carry class, box, or motion information.
Select an application family to see its output, real-world implication, and representative papers. The map covers the major families; deployed systems often combine several.
A still frame can show a person holding a cup, but motion distinguishes lifting, drinking, and putting it down. The spatial stream asks what is visible?; the temporal stream asks how is it moving?
This 2014 design is one example. Later video models learn spatiotemporal features with 3D convolution, recurrence, or attention.
The exact head, targets, losses, and postprocessing depend on the application.
Primary papers and official APIs. Links are optional reading; the slides and inference work offline.
Original diagrams are rendered locally. Model outputs are clearly separated from illustrative task animations.
Presentation controls: Home / arrows / slide grid · fit and zoom · hidden marker palette · copyable Python references · pins and downloadable notes. Code edits persist locally. Pins are session notes: download before closing; refresh can also trigger the unsaved-note warning. A crash can bypass it.
Concise concept summaries for revision. Choose a topic, review the key ideas, and try one reflection question.
A CNN represents an image as a tensor and learns filters that detect useful local patterns. In N × C × H × W, N is batch size, C is channels, and H × W is spatial size.
These choices determine which input locations contribute to each output and how large the output becomes.
Apply the same formula to width. Odd kernels have a central tap; square kernels are convenient, but neither choice is mandatory.
Parameters are learned values. Computation is the work performed using them. Activations are the resulting tensors.
A sliding convolution can also be expressed as matrix multiplication. These are different views of the same calculation.
Transposed convolution is useful for learned upsampling, but it is not generally the inverse of convolution and cannot automatically recover lost information.
These variants change how channels communicate.
Depthwise-separable convolution combines depthwise spatial filtering with pointwise channel mixing. This reduces weights and arithmetic, helping build compact models such as MobileNet.
The trade-off is a more restricted operation than full convolution. Depthwise filtering alone does not mix channels.
The neighborhood should match the structure of the data.
Activation functions change responses; pooling summarizes neighborhoods.
Pooling acts independently on channels. Downsampling saves computation but discards spatial detail. Local pooling may reduce sensitivity to small shifts; it does not guarantee complete translation or rotation invariance.
Normalization standardizes selected groups of activations. An optional learned scale γ and shift β then let the model choose useful output magnitudes.
Turning affine parameters off removes scale and shift. Freezing them keeps their values; evaluation mode is a separate choice. ε prevents numerical instability when variance is small.
A common CNN block is Conv → BatchNorm → ReLU, followed by optional downsampling. This is a useful default, not a universal rule.
Regularization discourages fitting training-specific patterns and can improve generalization.
The task gradient can still increase a useful weight. L2 does not guarantee equal importance across features or classes. Decoupled weight decay and an L2 loss penalty differ for adaptive optimizers such as Adam.
A receptive field is the region of the original input that can influence a particular activation. Stacking local layers lets deeper units combine evidence from broader regions.
The elephant analogy illustrates how combining partial observations gives broader understanding. Deeper maps are learned summaries, not simply smaller photographs. The effective influence within a theoretical receptive field is often uneven.
A classification head converts feature maps into image-level predictions.
Dense prediction tasks usually retain spatial maps rather than globally pooling them away.
These operations recover resolution, reuse features, or select useful information.
For NCHW output O, O[0,:,3,8] is the feature vector at one location. Attention may enrich it with context from elsewhere in the image.
Both architectures help deep networks reuse information, but their connections differ.
ResNet adds compatible tensors; DenseNet retains earlier maps through concatenation. Dense connectivity encourages feature reuse but can increase activation memory. Neither architecture guarantees that simply adding depth improves accuracy.
A backbone extracts features. The head, target, and training loss determine what the model learns to predict.
Softmax converts mutually exclusive class logits into probabilities summing to one. PyTorch CrossEntropyLoss takes raw logits; apply softmax separately for display. Heads may use several feature resolutions. Classification can discard precise location; detection and segmentation need spatial information. Choose outputs and losses that match the task.
Inference applies learned parameters to a new input. Interpretation tools help inspect a model’s behavior but do not prove that its reasoning is correct.
A confident prediction can be wrong. A plausible heatmap is not proof of causality, fairness, or reliability. Judge performance using suitable held-out data and task-specific metrics.
Equivariance: transforming the input transforms the output correspondingly. Invariance: transforming the input leaves the output unchanged.
Classification often benefits from invariance; segmentation needs outputs that move or rotate with the input.
These notes synthesize this deck's examples with the CS231n convolution curriculum and the primary references linked beside each topic. Framework-specific details follow PyTorch documentation, including floor-based output sizes, normalization axes, and optimizer distinctions. History and reference-only slides provide context; the focus here is reasoning about the computational concepts.