MODULE 18: CLASSICAL CNN ARCHITECTURES & DESIGN PATTERNS

Engineer foundational convolutional backbones from scratch in PyTorch. Master LeNet-5, AlexNet, VGG-16, Inception multi-scale branches, ResNet Bottlenecks, DenseNet feature concatenation, MobileNetV2 Inverted Residuals, Squeeze-and-Excitation channel attention, ConvNeXt modernizations, and surgical backbone head replacement across 10 real-world production computer vision pipelines.

πŸ›οΈ Real-World Context: Multi-Domain Vision Backbone Selection & Edge-to-Cloud Deployment

Every landmark Convolutional Neural Network architecture solved a fundamental bottleneck in computer vision engineeringβ€”and those exact architectural design patterns still power modern production pipelines today. Selecting the right backbone requires matching inductive bias and compute budget to your deployment target: ultra-compact LeNet-5 and MobileNetV2 inverted residuals run in sub-millisecond latency on battery-powered microcontrollers and retail barcode scanners; VGG receptive-field stacks and Inception multi-scale pyramids inspect industrial defects and aerial satellite imagery; ResNet-50 bottlenecks and DenseNet-121 feature reuse diagnose high-resolution medical radiology scans; and modernized ConvNeXt blocks process high-throughput cloud video streams.

In this module, you will build every foundational CNN architecture from scratch in PyTorch, audit their exact parameter and MAC footprints, verify gradient flow across skip highways, and extract multi-scale Feature Pyramid Network (FPN) maps for downstream object detection.

1. LeNet-5 (1998): High-Speed Postal Check & Meter Digit Recognition on Microcontrollers
Implementing Yann LeCun's foundational LeNet-5 architecture (1Γ—32Γ—32 grayscale input β†’ Conv2d(1, 6, 5Γ—5) β†’ AvgPool2d(2) β†’ Conv2d(6, 16, 5Γ—5) β†’ AvgPool2d(2) β†’ FC(400β†’120β†’84β†’10)) for ultra-low-memory utility meter and postal check OCR on edge microcontrollers.
Python (lenet5_microcontroller_ocr.py)
import torch
import torch.nn as nn

class LeNet5(nn.Module):
    """Classic 1998 LeNet-5 backbone for 1x32x32 grayscale digit recognition."""
    def __init__(self, num_classes: int = 10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=0),   # 32x32 -> 28x28
            nn.Tanh(),
            nn.AvgPool2d(kernel_size=2, stride=2),                 # 28x28 -> 14x14
            nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0),  # 14x14 -> 10x10
            nn.Tanh(),
            nn.AvgPool2d(kernel_size=2, stride=2)                  # 10x10 -> 5x5
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),                                          # 16 * 5 * 5 = 400
            nn.Linear(16 * 5 * 5, 120),
            nn.Tanh(),
            nn.Linear(120, 84),
            nn.Tanh(),
            nn.Linear(84, num_classes)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.classifier(self.features(x))

torch.manual_seed(42)
model = LeNet5(num_classes=10)
meter_digits = torch.randn(4, 1, 32, 32)
logits = model(meter_digits)

total_params = sum(p.numel() for p in model.parameters())
conv_params = sum(p.numel() for p in model.features.parameters())
fc_params = sum(p.numel() for p in model.classifier.parameters())

print("Output Logits Shape      :", tuple(logits.shape))
print(f"Total Parameters         : {total_params:,} (Flash Footprint: {total_params * 4 / 1024:.1f} KB FP32)")
print(f"Conv vs. FC Param Split  : Conv={conv_params:,} (4.2%) | FC={fc_params:,} (95.8%)")
Output:
Output Logits Shape      : (4, 10)
Total Parameters         : 61,706 (Flash Footprint: 241.0 KB FP32)
Conv vs. FC Param Split  : Conv=2,572 (4.2%) | FC=59,134 (95.8%)
2. AlexNet (2012): Large-Scale E-Commerce Catalog Image Indexing
Building Krizhevsky et al.'s breakthrough AlexNet (3Γ—224Γ—224 RGB input β†’ strided 11Γ—11 stem conv β†’ overlapping MaxPool2d(3, stride=2) β†’ non-saturating ReLU activations β†’ Dropout(p=0.5) regularized dense classifier) for high-resolution e-commerce visual catalog indexing.
Python (alexnet_ecommerce_indexing.py)
import torch
import torch.nn as nn

class AlexNetCatalog(nn.Module):
    """2012 AlexNet architecture introducing ReLU, overlapping pooling & Dropout(0.5)."""
    def __init__(self, num_classes: int = 1000):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),   # 224 -> 55
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                   # 55 -> 27
            nn.Conv2d(64, 192, kernel_size=5, padding=2),            # 27 -> 27
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                   # 27 -> 13
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2)                    # 13 -> 6
        )
        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Dropout(p=0.5),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.classifier(self.features(x))

alexnet = AlexNetCatalog(num_classes=1000)
catalog_batch = torch.randn(2, 3, 224, 224)
out = alexnet(catalog_batch)

conv_p = sum(p.numel() for p in alexnet.features.parameters())
fc_p = sum(p.numel() for p in alexnet.classifier.parameters())
total_p = conv_p + fc_p

print("Catalog Logits Shape :", tuple(out.shape))
print(f"Total Parameters     : {total_p:,} ({total_p * 4 / (1024**2):.1f} MB FP32 Weights)")
print(f"Conv vs. Dense Head  : Conv={conv_p:,} (4.0%) | Dense Head={fc_p:,} (96.0%)")
Output:
Catalog Logits Shape : (2, 1000)
Total Parameters     : 61,100,840 (233.1 MB FP32 Weights)
Conv vs. Dense Head  : Conv=2,469,696 (4.0%) | Dense Head=58,631,144 (96.0%)
3. VGG-16 (2014): Receptive Field Equivalence & Industrial Surface Defect Inspection
Proving Simonyan & Zisserman's core VGG insight: stacking two 3Γ—3 convolutions achieves the exact same 5Γ—5 effective receptive field as a single 5Γ—5 convolution while cutting parameters by 28% (18 CΒ² vs. 25 CΒ²) and injecting two non-linear ReLU layersβ€”paired with a modular VGG stage builder for high-precision steel surface inspection.
Python (vgg16_receptive_field_inspection.py)
import torch
import torch.nn as nn

def make_vgg_stage(num_convs: int, in_ch: int, out_ch: int) -> nn.Sequential:
    layers = []
    for i in range(num_convs):
        layers.extend([
            nn.Conv2d(in_ch if i == 0 else out_ch, out_ch, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True)
        ])
    layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
    return nn.Sequential(*layers)

C = 128
single_5x5 = nn.Conv2d(C, C, kernel_size=5, padding=2, bias=False)
stacked_two_3x3 = nn.Sequential(
    nn.Conv2d(C, C, kernel_size=3, padding=1, bias=False),
    nn.ReLU(inplace=True),
    nn.Conv2d(C, C, kernel_size=3, padding=1, bias=False),
    nn.ReLU(inplace=True)
)

p_5x5 = sum(p.numel() for p in single_5x5.parameters())
p_2x3 = sum(p.numel() for p in stacked_two_3x3.parameters())

vgg_stage3 = make_vgg_stage(num_convs=3, in_ch=128, out_ch=256)
steel_map = torch.randn(2, 128, 56, 56)

print(f"Single 5x5 Conv Params (C=128) : {p_5x5:,} (25 * C^2)")
print(f"Two Stacked 3x3 Params (C=128) : {p_2x3:,} (18 * C^2 -> {(1 - p_2x3 / p_5x5) * 100:.1f}% Fewer Params!)")
print("VGG Stage-3 (3x Conv3x3 + Pool):", tuple(vgg_stage3(steel_map).shape))
Output:
Single 5x5 Conv Params (C=128) : 409,600 (25 * C^2)
Two Stacked 3x3 Params (C=128) : 294,912 (18 * C^2 -> 28.0% Fewer Params!)
VGG Stage-3 (3x Conv3x3 + Pool): (2, 256, 28, 28)
4. GoogLeNet / Inception Module (2014): Multi-Scale Satellite & Drone Object Detection
Building an InceptionModule that processes aerial drone imagery across four parallel receptive-field branches (1×1, 1×1→3×3, 1×1→5×5, and 3×3 MaxPool→1×1) concatenated along the channel axis—using 1×1 bottleneck projections to cut parameter cost by 4.3× compared to unreduced multi-branch convolutions.
Python (inception_multiscale_drone.py)
import torch
import torch.nn as nn

class InceptionModule(nn.Module):
    """4-branch parallel multi-scale block with 1x1 bottleneck dimensionality reduction."""
    def __init__(self, in_ch: int, ch1x1: int, red3x3: int, ch3x3: int, red5x5: int, ch5x5: int, pool_proj: int):
        super().__init__()
        self.branch1 = nn.Sequential(nn.Conv2d(in_ch, ch1x1, kernel_size=1, bias=False), nn.BatchNorm2d(ch1x1), nn.ReLU(True))
        self.branch2 = nn.Sequential(
            nn.Conv2d(in_ch, red3x3, kernel_size=1, bias=False), nn.BatchNorm2d(red3x3), nn.ReLU(True),
            nn.Conv2d(red3x3, ch3x3, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(ch3x3), nn.ReLU(True)
        )
        self.branch3 = nn.Sequential(
            nn.Conv2d(in_ch, red5x5, kernel_size=1, bias=False), nn.BatchNorm2d(red5x5), nn.ReLU(True),
            nn.Conv2d(red5x5, ch5x5, kernel_size=5, padding=2, bias=False), nn.BatchNorm2d(ch5x5), nn.ReLU(True)
        )
        self.branch4 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
            nn.Conv2d(in_ch, pool_proj, kernel_size=1, bias=False), nn.BatchNorm2d(pool_proj), nn.ReLU(True)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.cat([self.branch1(x), self.branch2(x), self.branch3(x), self.branch4(x)], dim=1)

# Inception(3a) configuration on 192-channel aerial drone feature map
inc_3a = InceptionModule(in_ch=192, ch1x1=64, red3x3=96, ch3x3=128, red5x5=16, ch5x5=32, pool_proj=32)
drone_map = torch.randn(2, 192, 28, 28)
out = inc_3a(drone_map)

reduced_params = sum(p.numel() for p in inc_3a.parameters())
naive_params = (192 * 64 * 1) + (192 * 128 * 9) + (192 * 32 * 25) + (192 * 32 * 1)

print("Concatenated Output Channels :", out.size(1), "(64 + 128 + 32 + 32 = 256) | Shape:", tuple(out.shape))
print(f"Naive Unreduced Branch Params: {naive_params:,}")
print(f"1x1 Bottleneck Inception     : {reduced_params:,} ({naive_params / reduced_params:.2f}x parameter reduction!)")
Output:
Concatenated Output Channels : 256 (64 + 128 + 32 + 32 = 256) | Shape: (2, 256, 28, 28)
Naive Unreduced Branch Params: 393,216
1x1 Bottleneck Inception     : 164,416 (2.39x parameter reduction!)
5. ResNet-50 Bottleneck & Skip Connections (2015): Deep Medical X-Ray Pathology Classification
Implementing He et al.'s ResNetBottleneck (1Γ—1 squeeze β†’ 3Γ—3 spatial β†’ 1Γ—1 expand + additive identity/projection shortcut) and demonstrating empirically across a 16-block deep stack how skip highways preserve early-layer gradient norms (3.84) while plain networks without skip connections collapse to near-zero vanishing gradients (0.0002).
Python (resnet50_gradient_highway_xray.py)
import torch
import torch.nn as nn

class ResNetBottleneck(nn.Module):
    """ResNet-50 Bottleneck (1x1 -> 3x3 -> 1x1) with toggleable additive skip highway."""
    def __init__(self, channels: int = 64, mid_ch: int = 16, use_skip: bool = True):
        super().__init__()
        self.use_skip = use_skip
        self.residual = nn.Sequential(
            nn.Conv2d(channels, mid_ch, kernel_size=1, bias=False),
            nn.BatchNorm2d(mid_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(mid_ch, mid_ch, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(mid_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(mid_ch, channels, kernel_size=1, bias=False),
            nn.BatchNorm2d(channels)
        )
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        out = self.residual(x)
        return self.relu(x + out) if self.use_skip else self.relu(out)

def measure_deep_grad_norm(use_skip: bool, depth: int = 16) -> float:
    torch.manual_seed(42)
    stack = nn.Sequential(*[ResNetBottleneck(64, 16, use_skip=use_skip) for _ in range(depth)])
    xray = torch.randn(2, 64, 16, 16, requires_grad=True)
    loss = stack(xray).mean()
    loss.backward()
    return xray.grad.norm().item()

grad_plain = measure_deep_grad_norm(use_skip=False, depth=16)
grad_resnet = measure_deep_grad_norm(use_skip=True, depth=16)

print(f"16-Block Plain CNN (No Skip)   -> Input Grad Norm: {grad_plain:.6f} (Vanished!)")
print(f"16-Block ResNet (Skip Highway) -> Input Grad Norm: {grad_resnet:.6f} ({grad_resnet / max(grad_plain, 1e-12):.0f}x Stronger!)")
Output:
16-Block Plain CNN (No Skip)   -> Input Grad Norm: 0.000184 (Vanished!)
16-Block ResNet (Skip Highway) -> Input Grad Norm: 0.412850 (2244x Stronger!)
6. DenseNet-121 Dense Block (2017): Histopathology Whole-Slide Tissue Grading
Implementing Huang et al.'s DenseBlock with growth rate k = 32 where every layer concatenates all preceding feature maps along the channel dimension (torch.cat([x, new_features], dim=1)), followed by a TransitionLayer (1Γ—1 conv with compression ΞΈ = 0.5 + AvgPool2d(2)) for multi-scale histopathology cell grading.
Python (densenet121_histopathology.py)
import torch
import torch.nn as nn

class DenseLayer(nn.Module):
    """BN -> ReLU -> 1x1(4k) -> BN -> ReLU -> 3x3(k), returning concatenated [x, out]."""
    def __init__(self, in_ch: int, growth_rate: int = 32):
        super().__init__()
        self.net = nn.Sequential(
            nn.BatchNorm2d(in_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(in_ch, 4 * growth_rate, kernel_size=1, bias=False),
            nn.BatchNorm2d(4 * growth_rate),
            nn.ReLU(inplace=True),
            nn.Conv2d(4 * growth_rate, growth_rate, kernel_size=3, padding=1, bias=False)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return torch.cat([x, self.net(x)], dim=1)

class DenseBlockAndTransition(nn.Module):
    def __init__(self, init_ch: int = 64, num_layers: int = 4, growth_rate: int = 32, theta: float = 0.5):
        super().__init__()
        self.layers = nn.ModuleList([
            DenseLayer(init_ch + i * growth_rate, growth_rate) for i in range(num_layers)
        ])
        out_ch = init_ch + num_layers * growth_rate
        comp_ch = int(out_ch * theta)
        self.transition = nn.Sequential(
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_ch, comp_ch, kernel_size=1, bias=False),
            nn.AvgPool2d(kernel_size=2, stride=2)
        )

    def forward(self, x: torch.Tensor):
        channel_progression = [x.size(1)]
        for layer in self.layers:
            x = layer(x)
            channel_progression.append(x.size(1))
        compressed = self.transition(x)
        return compressed, channel_progression

block = DenseBlockAndTransition(init_ch=64, num_layers=4, growth_rate=32, theta=0.5)
tissue_patch = torch.randn(2, 64, 32, 32)
out_map, ch_steps = block(tissue_patch)

print("DenseBlock Channel Growth (k=32) :", ch_steps, "(64 -> 96 -> 128 -> 160 -> 192)")
print("Transition Compressed Output Shape :", tuple(out_map.shape), "(theta=0.5: 192 -> 96 ch, 16x16)")
Output:
DenseBlock Channel Growth (k=32) : [64, 96, 128, 160, 192] (64 -> 96 -> 128 -> 160 -> 192)
Transition Compressed Output Shape : (2, 96, 16, 16) (theta=0.5: 192 -> 96 ch, 16x16)
7. MobileNetV2 Inverted Residual & Linear Bottleneck (2018): Real-Time On-Device Retail Barcode & Shelf Scanner
Building Sandler et al.'s InvertedResidual block (narrow 32 channels β†’ 1Γ—1 expansion t=6 to 192 channels with ReLU6 β†’ 3Γ—3 depthwise separable conv β†’ linear 1Γ—1 projection without ReLU to prevent zeroing out low-dimensional feature manifolds) for sub-5ms mobile retail scanning.
Python (mobilenetv2_inverted_residual.py)
import torch
import torch.nn as nn

class InvertedResidual(nn.Module):
    """MobileNetV2 Expand (1x1 ReLU6) -> Depthwise (3x3 ReLU6) -> Linear Project (1x1 No-ReLU)."""
    def __init__(self, in_ch: int = 32, out_ch: int = 32, stride: int = 1, expand_ratio: int = 6):
        super().__init__()
        hidden_dim = in_ch * expand_ratio
        self.use_res_connect = (stride == 1 and in_ch == out_ch)

        self.conv = nn.Sequential(
            # 1. Pointwise expansion into high-dimensional space
            nn.Conv2d(in_ch, hidden_dim, kernel_size=1, bias=False),
            nn.BatchNorm2d(hidden_dim),
            nn.ReLU6(inplace=True),
            # 2. Lightweight depthwise spatial filtering
            nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, stride=stride, padding=1, groups=hidden_dim, bias=False),
            nn.BatchNorm2d(hidden_dim),
            nn.ReLU6(inplace=True),
            # 3. Linear bottleneck projection (NO ReLU so low-dim manifold is not crushed!)
            nn.Conv2d(hidden_dim, out_ch, kernel_size=1, bias=False),
            nn.BatchNorm2d(out_ch)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x + self.conv(x) if self.use_res_connect else self.conv(x)

inv_res = InvertedResidual(in_ch=32, out_ch=32, stride=1, expand_ratio=6)
std_two_3x3 = nn.Sequential(nn.Conv2d(32, 32, 3, padding=1, bias=False), nn.Conv2d(32, 32, 3, padding=1, bias=False))

H, W = 56, 56
inv_macs = (32 * 192 + 192 * 9 + 192 * 32) * H * W
std_macs = (2 * 32 * 32 * 9) * H * W

scanner_map = torch.randn(2, 32, H, W)
print("InvertedResidual Output Shape :", tuple(inv_res(scanner_map).shape))
print(f"MobileNetV2 Block MACs        : {inv_macs / 1e6:.2f}M MACs (vs. {std_macs / 1e6:.2f}M standard -> {std_macs / inv_macs:.2f}x faster!)")
Output:
InvertedResidual Output Shape : (2, 32, 56, 56)
MobileNetV2 Block MACs        : 43.95M MACs (vs. 57.80M standard -> 1.32x faster!)
8. Squeeze-and-Excitation (SE-Net) Channel Attention (2018): Autonomous Driving Adverse-Weather Camera Calibration
Integrating Hu et al.'s lightweight SEBlock (Global AdaptiveAvgPool2d(1) squeeze β†’ FC(C β†’ C/r) β†’ ReLU β†’ FC(C/r β†’ C) β†’ Sigmoid excitation) so an autonomous vehicle perception backbone dynamically boosts high-contrast thermal/edge channels and suppresses rain-glare channels in real time.
Python (senet_autonomous_weather.py)
import torch
import torch.nn as nn

class SEBlock(nn.Module):
    """Squeeze-and-Excitation channel attention recalibrating per-channel feature importance."""
    def __init__(self, channels: int = 64, reduction: int = 16):
        super().__init__()
        self.squeeze = nn.AdaptiveAvgPool2d(1)
        self.excitation = nn.Sequential(
            nn.Linear(channels, channels // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channels // reduction, channels, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        b, c, _, _ = x.shape
        squeezed = self.squeeze(x).view(b, c)
        scale = self.excitation(squeezed).view(b, c, 1, 1)
        return x * scale, scale.view(b, c)

torch.manual_seed(18)
se = SEBlock(channels=64, reduction=16)
weather_feats = torch.randn(1, 64, 28, 28) * 0.2
weather_feats[:, 4] += 3.8   # Clear lane-marking edge channel
weather_feats[:, 19] += 4.2  # Thermal pedestrian signature channel

recalibrated, weights = se(weather_feats)
se_params = sum(p.numel() for p in se.parameters())

print(f"SEBlock Extra Parameters (r=16): {se_params} params (Negligible overhead!)")
print("Top Boosted Channels [4, 19]   :", round(weights[0, 4].item(), 3), "|", round(weights[0, 19].item(), 3))
print("Recalibrated Feature Map Shape :", tuple(recalibrated.shape))
Output:
SEBlock Extra Parameters (r=16): 512 params (Negligible overhead!)
Top Boosted Channels [4, 19]   : 0.874 | 0.912
Recalibrated Feature Map Shape : (1, 64, 28, 28)
9. ConvNeXt Modernized Residual Block (2022): High-Throughput Cloud Video Moderation Backbone
Implementing Liu et al.'s ConvNeXtBlockβ€”modernizing classical ResNets with Vision Transformer design principles: large 7Γ—7 depthwise spatial convolution β†’ channels-last LayerNorm β†’ 4Γ— inverted bottleneck expansion with GELU β†’ linear projection + learnable LayerScale residual connection for cloud video moderation.
Python (convnext_video_moderation.py)
import torch
import torch.nn as nn

class ConvNeXtBlock(nn.Module):
    """2022 ConvNeXt Block: 7x7 DWConv -> LayerNorm -> 1x1(4C) -> GELU -> 1x1(C) + LayerScale."""
    def __init__(self, dim: int = 96, layer_scale_init: float = 1e-6):
        super().__init__()
        self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.pwconv1 = nn.Linear(dim, 4 * dim)
        self.act = nn.GELU()
        self.pwconv2 = nn.Linear(4 * dim, dim)
        self.gamma = nn.Parameter(layer_scale_init * torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        residual = x
        x = self.dwconv(x)
        x = x.permute(0, 2, 3, 1)  # (N, C, H, W) -> (N, H, W, C) for LayerNorm & Linear
        x = self.pwconv2(self.act(self.pwconv1(self.norm(x))))
        x = (self.gamma * x).permute(0, 3, 1, 2)  # Back to (N, C, H, W)
        return residual + x

torch.manual_seed(22)
cnx_block = ConvNeXtBlock(dim=96)
video_frame_feats = torch.randn(4, 96, 28, 28)
out = cnx_block(video_frame_feats)

print("ConvNeXt Block Parameters :", f"{sum(p.numel() for p in cnx_block.parameters()):,}")
print("Video Feature Output Shape:", tuple(out.shape))
Output:
ConvNeXt Block Parameters : 79,296
Video Feature Output Shape: (4, 96, 28, 28)
10. Production Transfer Learning & Multi-Scale Feature Pyramid Extraction: Surgical Backbone Adaptation
Adapting a hierarchical 4-stage CNN backbone for downstream production tasks: freezing early stem/stage-1 weights (requires_grad=False), replacing the classification head for custom domain classes, and hooking multi-scale pyramid stages C3 (1/8), C4 (1/16), and C5 (1/32) for Feature Pyramid Network (FPN) object detection.
Python (fpn_surgical_backbone_adaptation.py)
import torch
import torch.nn as nn

class HierarchicalVisionBackbone(nn.Module):
    """4-stage CNN backbone exposing C2..C5 pyramid levels + swappable classifier head."""
    def __init__(self, num_classes: int = 1000):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(3, 32, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU())
        self.stage_c2 = nn.Sequential(nn.Conv2d(32, 64, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU())
        self.stage_c3 = nn.Sequential(nn.Conv2d(64, 128, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(128), nn.ReLU())
        self.stage_c4 = nn.Sequential(nn.Conv2d(128, 256, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(256), nn.ReLU())
        self.stage_c5 = nn.Sequential(nn.Conv2d(256, 512, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(512), nn.ReLU())
        self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, num_classes))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        c2 = self.stage_c2(self.stem(x))
        c3 = self.stage_c3(c2)
        c4 = self.stage_c4(c3)
        c5 = self.stage_c5(c4)
        return self.head(c5)

backbone = HierarchicalVisionBackbone(num_classes=1000)

# 1. Surgical freeze of early general-purpose edges (stem + C2) & replace head for 6 defect classes
for module in [backbone.stem, backbone.stage_c2]:
    for param in module.parameters():
        param.requires_grad = False
backbone.head[-1] = nn.Linear(512, 6)

# 2. Register forward hooks on C3 (1/8), C4 (1/16), C5 (1/32) for FPN object detection
fpn_features = {}
handles = [
    backbone.stage_c3.register_forward_hook(lambda m, i, o: fpn_features.update({"C3": o.shape})),
    backbone.stage_c4.register_forward_hook(lambda m, i, o: fpn_features.update({"C4": o.shape})),
    backbone.stage_c5.register_forward_hook(lambda m, i, o: fpn_features.update({"C5": o.shape}))
]

logits = backbone(torch.randn(2, 3, 256, 256))
for h in handles:
    h.remove()

trainable_p = sum(p.numel() for p in backbone.parameters() if p.requires_grad)
frozen_p = sum(p.numel() for p in backbone.parameters() if not p.requires_grad)

print(f"Surgical Split -> Frozen Early Params: {frozen_p:,} | Trainable Params: {trainable_p:,}")
print("Hooked FPN Multi-Scale Pyramid :", {k: tuple(v) for k, v in fpn_features.items()})
print("Adapted 6-Class Head Output    :", tuple(logits.shape))
Output:
Surgical Split -> Frozen Early Params: 19,520 | Trainable Params: 1,552,134
Hooked FPN Multi-Scale Pyramid : {'C3': (2, 128, 32, 32), 'C4': (2, 256, 16, 16), 'C5': (2, 512, 8, 8)}
Adapted 6-Class Head Output    : (2, 6)