Pretrained Backbone Architecture & Parameter Audit
(Milestone 3 · Question 2 Study Guide)
1. The Core Concept: The Transfer Learning Advantage
Training deep semantic segmentation networks from scratch can require substantial labeled data, depending on the task and architecture. On specialized industrial datasets like surface anomaly inspection, annotations are scarce, expensive to produce, and heavily skewed toward clean background material.
When a convolutional network is initialized randomly (e.g., via Kaiming/He normal initialization), the earliest convolutional filters possess no prior concept of visual reality. The network must learn useful image processing primitives during training:
- Directional edge filters (horizontal, vertical, diagonal)
- Color and intensity gradients
- Local frequency and Gabor textures
- Corner and boundary detectors
Inductive Visual Priors from ImageNet
Transfer learning addresses this cold-start bottleneck by utilizing feature extractors pretrained on large-scale natural image datasets such as ImageNet-1k (\(1.28\text{M}\) images across 1,000 object categories). Even though steel strips look radically different from dogs, cars, and landscapes, the low-level physics of light, edge contrast, and spatial continuity are universal across optical sensors.
By adopting a pretrained encoder backbone, your model starts training with mature, robust feature hierarchies already formed:
- Stages 1–2 (Shallow features): Generic edge, ridge, and scratch primitives that transfer immediately to surface cracks.
- Stages 3–5 (Deep features): High-level spatial groupings that adapt rapidly to diffuse stains and structural variations.
2. Theoretical Principles: ResNet vs. EfficientNet Architectures
In modern semantic segmentation toolkits like segmentation_models_pytorch (SMP), a standard segmentation model decomposes into three distinct structural modules:
Backbone Architecture 1: ResNet-34 (Residual Networks)
ResNet-34 employs standard \(3 \times 3\) convolutional layers organized into residual blocks with additive identity shortcut connections:
The identity shortcut helps gradients propagate across deep stacks. However, standard 2D convolutions apply dense spatial-channel matrix multiplications:
For \(3 \times 3\) kernels across hundreds of channels, parameter counts scale quadratic with channel depth.
Backbone Architecture 2: EfficientNet-B0 (Compound Scaling & MBConv)
EfficientNet-B0 was engineered using Neural Architecture Search (NAS) and compound coefficient scaling. Instead of standard convolutions, EfficientNet utilizes Mobile Inverted Bottleneck Convolutions (MBConv) built from:
- \(1 \times 1\) Pointwise Expansion: Expands channel capacity.
- \(k \times k\) Depthwise Convolutions: Applies spatial filtering independently per channel (\(C_{\text{in}} \times K_h \times K_w\) parameters, eliminating dense cross-channel multiplying).
- Squeeze-and-Excitation (SE) Attention: Adaptively recalibrates channel-wise feature responses.
- \(1 \times 1\) Pointwise Projection: Compresses channels back down to match linear bottlenecks.
This factorization separates spatial filtering from channel mixing. Count parameters for the complete model: decoder width, expansion layers and SE blocks also contribute, and parameter savings do not guarantee equal accuracy or lower peak activation memory.
3. Parameter Accounting & Freezing Dynamics in PyTorch
In deep learning auditing, total parameters represent the storage footprint and parameter capacity of a model. In PyTorch, parameter tensors are queried using model.parameters():
# Total parameters (weights + biases) across all layers:
total_params = sum(p.numel() for p in model.parameters())
# Trainable parameters (requiring gradient computation during backward pass):
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
Feature-Extractor Fine-Tuning (Encoder Freezing)
In the first phase of transfer learning on small datasets, it is common practice to freeze the encoder backbone. Because ImageNet features are already well-conditioned, updating encoder weights with aggressive gradients can cause catastrophic forgetting (destabilizing generic edge priors).
By setting requires_grad = False on the encoder:
for param in model.encoder.parameters():
param.requires_grad = False
- The encoder parameters no longer receive newly computed gradients. This alone does not freeze its running buffers or stochastic behavior.
- Only the randomly initialized decoder blocks and the segmentation head receive gradient updates.
- GPU VRAM consumption during training decreases because intermediate encoder activation gradients do not need to be retained in memory.
If a fixed feature extractor is intended, call model.encoder.eval() after each model.train(). BatchNorm running mean/variance otherwise update in training mode even when its affine parameters have requires_grad=False. eval() also changes dropout behavior; it does not disable gradients. Q2 asks only for parameter accounting; Q8/Q9 train all parameters with normal training-mode BatchNorm.
model.train() # sets all submodules to training mode
model.encoder.eval() # only for a deliberately fixed feature extractor
See PyTorch BatchNorm2d for the running-statistics contract and SMP 0.5.0 model settings for encoder/decoder options. The assessment pins SMP 0.5.0 and explicitly fixes decoder settings so parameter counts are reproducible.
This is a five-stage ResNet feature trace, separate from Q1's four-pooling toy network. Feature meanings are illustrative, not measured activations.
Trainable Parameter Ratio Formula
When the encoder is frozen, the percentage of remaining trainable parameters is:
4. Guiding Hints for Question 2
To solve Question 2 in MILESTONE_3.md:
-
Hint 1 (Instantiate Models Consistently): Instantiate both
smp.Unetmodels using the exact starter code parameters:import segmentation_models_pytorch as smp model_resnet = smp.Unet(encoder_name="resnet34", encoder_weights="imagenet", in_channels=1, classes=4) model_effnet = smp.Unet(encoder_name="efficientnet-b0", encoder_weights="imagenet", in_channels=1, classes=4) -
Hint 2 (Compute Total Parameter Counts): For both
model_resnetandmodel_effnet, write a helper function that iterates throughmodel.parameters()and sumsp.numel(). Compare the two totals to determine which model is more parameter-efficient, and compute the exact numerical difference:\[\Delta_{\text{params}} = |\text{params}_{\text{resnet}} - \text{params}_{\text{effnet}}|\] -
Hint 3 (Apply Encoder Freezing): For
model_resnet, loop overmodel_resnet.encoder.parameters()and setparam.requires_grad = False. Verify thatmodel_resnet.decoderandmodel_resnet.segmentation_headparameters still haverequires_grad == True. - Hint 4 (Calculate Percentage): Divide the count of parameters with
requires_grad == Trueby the total parameter count ofmodel_resnet, multiply by 100, and round to 1 decimal place.
5. Your Assignment Task
- Open Milestone 3 Assessment: Question 2.
- Instantiate
model_resnetandmodel_effnetvia SMP. - Compute the exact total parameter counts, identify the more efficient model, and find their difference.
- Freeze the ResNet-34 encoder and compute the exact percentage of trainable parameters remaining.
- Enter your response in the specified format:
more_efficient_model, param_diff; trainable_pct.