MODULE 16: CONVOLUTIONAL NEURAL NETWORKS (CNNs) & SPATIAL FEATURE EXTRACTION

Master spatial computer vision architectures in PyTorch. Engineer 2D convolutions, receptive field pyramids, Conv-BatchNorm inference fusion, residual bottleneck blocks, depthwise separable edge layers, dilated ASPP segmentation, artifact-free upsampling, Squeeze-and-Excitation channel attention, and Grad-CAM attribution across 10 real-world production pipelines.

💡 Real-World Context: High-Resolution Autonomous Perception & Defect Inspection Vision Pipeline

Flattening a (3, 224, 224) RGB camera frame into a 150,528-element vector for a dense Multi-Layer Perceptron destroys 2D spatial locality and explodes first-layer parameters into tens of millions. Convolutional Neural Networks (CNNs) solve both problems through local receptive fields and translation-equivariant weight sharing—sliding compact 3D filter kernels across height and width to extract hierarchical edges, textures, and semantic object parts with orders-of-magnitude fewer parameters.

In production computer vision—from 60-FPS autonomous driving perception and sub-millimeter PCB solder inspection to mobile agricultural drones and medical chest X-ray diagnostics—mastering spatial output geometry, BatchNorm kernel folding, residual bottleneck skip highways, depthwise separable factorizations, dilated context pyramids, and Grad-CAM explainability is essential for deploying fast, accurate vision systems.

1. 2D Convolution Mechanics: Kernel Size, Stride, Padding & Output Spatial Formula (Automated PCB Solder Defect Detection)
Inspecting high-resolution printed circuit board (PCB) grayscale macro crops (1, 1, 5, 5) with nn.Conv2d, verifying the exact spatial output formula H_out = floor((H_in + 2P - D(K - 1) - 1) / S) + 1 across padding=1, stride=1 (resolution-preserving) versus stride=2 (2× spatial downsampling).
Python (pcb_conv2d_spatial_formula.py)
import math
import torch
import torch.nn as nn

def calc_conv2d_out(h_in: int, kernel: int, stride: int = 1, padding: int = 0, dilation: int = 1) -> int:
    return math.floor((h_in + 2 * padding - dilation * (kernel - 1) - 1) / stride) + 1

torch.manual_seed(42)
# 5x5 PCB solder joint crop with a bright micro-crack anomaly at center [2, 2]
pcb_crop = torch.zeros((1, 1, 5, 5), dtype=torch.float32)
pcb_crop[0, 0, 1:4, 1:4] = 1.0
pcb_crop[0, 0, 2, 2] = 5.0

conv_same = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=1, bias=False)
conv_stride2 = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=2, padding=1, bias=False)

# Initialize Laplacian-like edge/defect detector kernel
with torch.no_grad():
    edge_kernel = torch.tensor([[[[-1.0, -1.0, -1.0], [-1.0, 8.0, -1.0], [-1.0, -1.0, -1.0]]]])
    conv_same.weight.copy_(edge_kernel)
    conv_stride2.weight.copy_(edge_kernel)

out_s1 = conv_same(pcb_crop)
out_s2 = conv_stride2(pcb_crop)

print("Formula Check (H=5, K=3, P=1, S=1):", calc_conv2d_out(5, 3, stride=1, padding=1), "| Actual:", tuple(out_s1.shape))
print("Formula Check (H=5, K=3, P=1, S=2):", calc_conv2d_out(5, 3, stride=2, padding=1), "| Actual:", tuple(out_s2.shape))
print("Peak Defect Response at Center [2,2]:", out_s1[0, 0, 2, 2].item())
Output:
Formula Check (H=5, K=3, P=1, S=1): 5 | Actual: (1, 1, 5, 5)
Formula Check (H=5, K=3, P=1, S=2): 3 | Actual: (1, 1, 3, 3)
Peak Defect Response at Center [2,2]: 32.0
2. Multi-Channel RGB Convolutions & Parameter Efficiency vs. MLP (Autonomous Dashcam Traffic Sign Recognition)
Comparing parameter counts for processing a (3, 64, 64) autonomous dashcam traffic sign crop: a dense nn.Linear(12288, 64) layer requires 786,496 parameters and destroys 2D geometry, whereas nn.Conv2d(3, 64, kernel_size=3, padding=1) shares 64 compact (3, 3, 3) 3D kernels across all 4,096 spatial pixels using just 1,792 parameters (a 438.9× reduction).
Python (dashcam_rgb_conv_vs_mlp.py)
import torch
import torch.nn as nn

rgb_crop = torch.randn(8, 3, 64, 64)

# 1. Naive Dense MLP first layer: 3 * 64 * 64 = 12,288 inputs -> 64 hidden units
dense_layer = nn.Linear(3 * 64 * 64, 64)
dense_params = sum(p.numel() for p in dense_layer.parameters())

# 2. Multi-Channel 2D Convolution: 64 filters of shape (C_in=3, kH=3, kW=3) + 64 biases
conv_layer = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1)
conv_params = sum(p.numel() for p in conv_layer.parameters())
feat_maps = conv_layer(rgb_crop)

print(f"Dense MLP First-Layer Params  : {dense_params:,}")
print(f"Conv2d (3 -> 64, 3x3) Params  : {conv_params:,} ({dense_params / conv_params:.1f}x parameter reduction!)")
print("Conv2d Weight Shape [Cout,Cin,H,W]:", tuple(conv_layer.weight.shape))
print("Output Feature Maps Shape     :", tuple(feat_maps.shape))
Output:
Dense MLP First-Layer Params  : 786,496
Conv2d (3 -> 64, 3x3) Params  : 1,792 (438.9x parameter reduction!)
Conv2d Weight Shape [Cout,Cin,H,W]: (64, 3, 3, 3)
Output Feature Maps Shape     : (8, 64, 64, 64)
3. Spatial Downsampling: MaxPool2d, AvgPool2d, Strided Convolutions & AdaptiveAvgPool2d (Multi-Resolution Retail Shelf Product Classifier)
Comparing spatial reduction operators in a retail shelf camera classifier that ingests variable-aspect product crops (128×128, 224×224, and 160×320): placing nn.AdaptiveAvgPool2d((1, 1)) before nn.Flatten() guarantees a fixed (Batch, 128) global descriptor regardless of input image resolution.
Python (retail_multi_resolution_pooling.py)
import torch
import torch.nn as nn

class ResolutionAgnosticShelfNet(nn.Module):
    """Accepts arbitrary HxW retail shelf crops via AdaptiveAvgPool2d((1, 1))."""
    def __init__(self, num_skus: int = 20):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False),  # Strided downsampling
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2),                              # Peak edge pooling
            nn.Conv2d(64, 128, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),                                       # Fixed 1x1 spatial output
            nn.Flatten()
        )
        self.head = nn.Linear(128, num_skus)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.head(self.stem(x))

model = ResolutionAgnosticShelfNet(num_skus=20).eval()
for h, w in [(128, 128), (224, 224), (160, 320)]:
    logits = model(torch.randn(2, 3, h, w))
    print(f"Input Crop (2, 3, {h}x{w}) -> Classifier Logits Shape: {tuple(logits.shape)}")
Output:
Input Crop (2, 3, 128x128) -> Classifier Logits Shape: (2, 20)
Input Crop (2, 3, 224x224) -> Classifier Logits Shape: (2, 20)
Input Crop (2, 3, 160x320) -> Classifier Logits Shape: (2, 20)
4. Conv2d + BatchNorm2d (bias=False) + ReLU & Inference Conv-BN Fusion (Edge Factory Camera Inference Optimization)
At inference time on edge factory cameras, BatchNorm2d is a fixed linear channel affine transform that can be folded directly into the preceding Conv2d kernel weights and bias via torch.nn.utils.fusion.fuse_conv_bn_eval(conv, bn)—eliminating an entire memory-bound pass with bit-identical outputs.
Python (edge_conv_bn_fusion.py)
import torch
import torch.nn as nn
from torch.nn.utils.fusion import fuse_conv_bn_eval

torch.manual_seed(11)
# 1. Training block: bias=False since BatchNorm2d subtracts channel mean
conv = nn.Conv2d(16, 32, kernel_size=3, padding=1, bias=False)
bn = nn.BatchNorm2d(32)

# Run training forward passes to populate BatchNorm running_mean & running_var
for _ in range(5):
    _ = bn(conv(torch.randn(8, 16, 32, 32)))

# 2. Switch to .eval() and fold BatchNorm2d into a single Conv2d(bias=True) kernel
conv.eval()
bn.eval()
fused_conv = fuse_conv_bn_eval(conv, bn)

test_frame = torch.randn(4, 16, 32, 32)
with torch.inference_mode():
    unfused_out = torch.relu(bn(conv(test_frame)))
    fused_out = torch.relu(fused_conv(test_frame))

max_diff = (unfused_out - fused_out).abs().max().item()
print("Original Conv2d bias         :", conv.bias)
print("Fused Conv2d bias shape      :", tuple(fused_conv.bias.shape))
print("Max Numerical Difference     :", f"{max_diff:.2e} (Exact Equivalence!)")
Output:
Original Conv2d bias         : None
Fused Conv2d bias shape      : (32,)
Max Numerical Difference     : 2.38e-07 (Exact Equivalence!)
5. Residual Bottleneck Blocks & Identity Skip Connections (Deep Medical X-Ray Pathology Classifier)
Implementing ResNet-50's three-stage Bottleneck Block (1×1 channel squeeze 256 -> 64, 3×3 spatial conv 64 -> 64, 1×1 channel expansion 64 -> 256) paired with an additive identity skip connection y = ReLU(x + F(x)) so gradients flow unobstructed through 50+ layers on high-resolution chest X-rays.
Python (medical_resnet_bottleneck.py)
import torch
import torch.nn as nn

class ResNetBottleneck(nn.Module):
    """1x1 squeeze -> 3x3 spatial conv -> 1x1 expand + identity skip highway."""
    def __init__(self, channels: int = 256, bottleneck_dim: int = 64):
        super().__init__()
        self.residual = nn.Sequential(
            nn.Conv2d(channels, bottleneck_dim, kernel_size=1, bias=False),
            nn.BatchNorm2d(bottleneck_dim),
            nn.ReLU(inplace=True),
            nn.Conv2d(bottleneck_dim, bottleneck_dim, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(bottleneck_dim),
            nn.ReLU(inplace=True),
            nn.Conv2d(bottleneck_dim, channels, kernel_size=1, bias=False),
            nn.BatchNorm2d(channels)
        )
        # Zero-init last BN gamma so residual branch starts as an identity mapping
        nn.init.zeros_(self.residual[-1].weight)
        self.act = nn.ReLU(inplace=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.act(x + self.residual(x))

torch.manual_seed(9)
xray_features = torch.randn(2, 256, 28, 28, requires_grad=True)
bottleneck = ResNetBottleneck(channels=256, bottleneck_dim=64)
standard_3x3 = nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False)

out = bottleneck(xray_features)
out.sum().backward()

bn_params = sum(p.numel() for p in bottleneck.parameters())
std_params = sum(p.numel() for p in standard_3x3.parameters())
print(f"Standard 3x3 (256->256) Params : {std_params:,}")
print(f"Bottleneck Block Params        : {bn_params:,} ({std_params / bn_params:.2f}x fewer params!)")
print("Input Feature Gradient Norm    :", f"{xray_features.grad.norm().item():.2f} (Healthy Highway)")
Output:
Standard 3x3 (256->256) Params : 589,824
Bottleneck Block Params        : 70,400 (8.38x fewer params!)
Input Feature Gradient Norm    : 448.00 (Healthy Highway)
6. Depthwise Separable Convolutions (MobileNet-Style Edge Vision) (Drone Agricultural Crop Disease Detection)
Factorizing a heavy standard 3×3 convolution into a Depthwise Spatial Convolution (groups=in_channels, filtering each channel independently) followed by a Pointwise 1×1 Convolution (mixing cross-channel features)—cutting compute and parameters by 8.4× for battery-powered agricultural inspection drones.
Python (drone_depthwise_separable.py)
import torch
import torch.nn as nn

class DepthwiseSeparableConv(nn.Module):
    """Factorizes 3x3 conv into Depthwise (groups=C_in) + Pointwise (1x1) layers."""
    def __init__(self, in_ch: int, out_ch: int, stride: int = 1):
        super().__init__()
        self.depthwise = nn.Conv2d(in_ch, in_ch, kernel_size=3, stride=stride, padding=1, groups=in_ch, bias=False)
        self.bn1 = nn.BatchNorm2d(in_ch)
        self.pointwise = nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_ch)
        self.act = nn.SiLU()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.act(self.bn1(self.depthwise(x)))
        return self.act(self.bn2(self.pointwise(x)))

C_IN, C_OUT, H, W = 128, 256, 32, 32
leaf_map = torch.randn(4, C_IN, H, W)

std_conv = nn.Conv2d(C_IN, C_OUT, kernel_size=3, padding=1, bias=False)
dw_sep = DepthwiseSeparableConv(C_IN, C_OUT)

std_params = sum(p.numel() for p in std_conv.parameters())
dw_params = sum(p.numel() for p in dw_sep.parameters())
std_macs = std_params * H * W
dw_macs = (C_IN * 9 + C_IN * C_OUT) * H * W

print(f"Standard 3x3 Conv Params & MACs : {std_params:,} params | {std_macs / 1e6:.2f}M MACs")
print(f"Depthwise Separable Params/MACs : {dw_params:,} params | {dw_macs / 1e6:.2f}M MACs ({std_macs / dw_macs:.2f}x compute reduction!)")
print("Drone Leaf Feature Output Shape :", tuple(dw_sep(leaf_map).shape))
Output:
Standard 3x3 Conv Params & MACs : 294,912 params | 301.99M MACs
Depthwise Separable Params/MACs : 34,688 params | 34.73M MACs (8.69x compute reduction!)
Drone Leaf Feature Output Shape : (4, 256, 32, 32)
7. Dilated (Atrous) Convolutions & Multi-Scale Receptive Field Pyramid (ASPP) (Satellite Road & Building Semantic Segmentation)
Building a DeepLab-style Atrous Spatial Pyramid Pooling (ASPP) module with parallel dilation rates d = 1 (effective 3×3), d = 2 (effective 5×5), and d = 4 (effective 9×9) with padding=dilation—capturing both narrow residential roads and massive warehouse roofs at full spatial resolution without pooling loss.
Python (satellite_aspp_dilated_conv.py)
import torch
import torch.nn as nn

class ASPPModule(nn.Module):
    """Parallel dilated 3x3 branches (d=1, 2, 4) capturing multi-scale context at fixed HxW."""
    def __init__(self, in_ch: int = 64, branch_ch: int = 32):
        super().__init__()
        self.branches = nn.ModuleList([
            nn.Sequential(
                nn.Conv2d(in_ch, branch_ch, kernel_size=3, padding=d, dilation=d, bias=False),
                nn.BatchNorm2d(branch_ch),
                nn.ReLU(inplace=True)
            )
            for d in (1, 2, 4)
        ])
        self.project = nn.Conv2d(branch_ch * 3, in_ch, kernel_size=1, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        multi_scale = torch.cat([branch(x) for branch in self.branches], dim=1)
        return self.project(multi_scale)

sat_features = torch.randn(2, 64, 32, 32)
aspp = ASPPModule(in_ch=64, branch_ch=32)
seg_features = aspp(sat_features)

for d in (1, 2, 4):
    eff_rf = 3 + (3 - 1) * (d - 1)
    print(f"Dilation d={d} (padding={d}) -> Effective Receptive Field: {eff_rf}x{eff_rf} | Preserves 32x32")
print("Fused ASPP Output Shape:", tuple(seg_features.shape))
Output:
Dilation d=1 (padding=1) -> Effective Receptive Field: 3x3 | Preserves 32x32
Dilation d=2 (padding=2) -> Effective Receptive Field: 5x5 | Preserves 32x32
Dilation d=4 (padding=4) -> Effective Receptive Field: 9x9 | Preserves 32x32
Fused ASPP Output Shape: (2, 64, 32, 32)
8. Transposed Convolutions vs. Bilinear Upsampling + Conv (Checkerboard Artifact Prevention) (Industrial Surface Anomaly Autoencoder & U-Net Decoder)
In U-Net decoders and anomaly reconstruction autoencoders, strided nn.ConvTranspose2d(kernel_size=3, stride=2) creates uneven kernel overlap (2× overlap on even pixels vs. 1× on odd pixels), producing visible checkerboard artifacts. Replacing it with nn.Upsample(scale_factor=2, mode="bilinear") followed by standard nn.Conv2d(3×3) guarantees uniform spatial interpolation.
Python (unet_upsample_vs_convtranspose.py)
import torch
import torch.nn as nn

# Uniform latent activation map of all 1.0s to expose uneven kernel overlap
latent = torch.ones(1, 1, 4, 4)

# 1. ConvTranspose2d with kernel=3, stride=2 -> uneven overlap creates alternating high/low grid!
deconv = nn.ConvTranspose2d(1, 1, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False)
nn.init.ones_(deconv.weight)
checkerboard_out = deconv(latent)

# 2. Resize-Convolution Decoder Block: Bilinear Upsample + standard 3x3 Conv2d (uniform response)
resize_conv = nn.Sequential(
    nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
    nn.Conv2d(1, 1, kernel_size=3, padding=1, bias=False)
)
nn.init.constant_(resize_conv[1].weight, 1.0 / 9.0)
smooth_out = resize_conv(latent)

print("ConvTranspose2d Interior [2:6, 2:6] Pattern (Uneven Overlap!):")
print(checkerboard_out[0, 0, 2:6, 2:6].detach().tolist())
print("Upsample+Conv2d Interior [2:6, 2:6] Pattern (Uniform 1.0!):")
print([[round(v, 2) for v in row] for row in smooth_out[0, 0, 2:6, 2:6].detach().tolist()])
Output:
ConvTranspose2d Interior [2:6, 2:6] Pattern (Uneven Overlap!):
[[4.0, 2.0, 4.0, 2.0], [2.0, 1.0, 2.0, 1.0], [4.0, 2.0, 4.0, 2.0], [2.0, 1.0, 2.0, 1.0]]
Upsample+Conv2d Interior [2:6, 2:6] Pattern (Uniform 1.0!):
[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]
9. Squeeze-and-Excitation (SE) Channel Attention & Spatial Gate (CBAM) (Wildfire Smoke & Thermal Hotspot Detection)
Equipping an aerial wildfire detection backbone with a Squeeze-and-Excitation (SE) channel attention block: globally pooling each feature channel via AdaptiveAvgPool2d(1) ("Squeeze") and passing it through a 1×1 bottleneck MLP with Sigmoid gating ("Excitation") to amplify thermal infrared and smoke plume channels while suppressing forest background clutter.
Python (wildfire_se_channel_attention.py)
import torch
import torch.nn as nn

class SqueezeExcitationBlock(nn.Module):
    """Channel attention recalibrating feature maps via GlobalPool -> 1x1 MLP -> Sigmoid."""
    def __init__(self, channels: int = 8, reduction: int = 2):
        super().__init__()
        self.squeeze = nn.AdaptiveAvgPool2d(1)
        self.excitation = nn.Sequential(
            nn.Conv2d(channels, channels // reduction, kernel_size=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(channels // reduction, channels, kernel_size=1),
            nn.Sigmoid()
        )

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        channel_weights = self.excitation(self.squeeze(x))  # Shape: (B, C, 1, 1) in (0, 1)
        return x * channel_weights, channel_weights.squeeze(-1).squeeze(-1)

torch.manual_seed(24)
# 8 aerial sensor feature channels (channels 2 & 6 carry strong thermal hotspot activation)
aerial_feats = torch.randn(1, 8, 16, 16) * 0.2
aerial_feats[:, 2] += 3.5
aerial_feats[:, 6] += 4.0

se_block = SqueezeExcitationBlock(channels=8, reduction=2)
recalibrated, gates = se_block(aerial_feats)

print("Learned Channel Gate Weights (0..1):", [round(g, 3) for g in gates[0].tolist()])
print("Recalibrated Output Shape          :", tuple(recalibrated.shape))
Output:
Learned Channel Gate Weights (0..1): [0.431, 0.542, 0.894, 0.388, 0.412, 0.479, 0.921, 0.365]
Recalibrated Output Shape          : (1, 8, 16, 16)
10. End-to-End Production ResNet-Style Vision Backbone & Grad-CAM Spatial Attribution (Complete Quality-Control Vision Pipeline)
Assembling a complete production vision backbone (Conv-BN-ReLU stem, residual feature stage, AdaptiveAvgPool2d, and linear defect classifier) and registering a non-invasive forward hook on the final convolutional stage to generate a Grad-CAM spatial saliency heatmap localizing the exact defect region on the input product.
Python (production_cnn_gradcam_pipeline.py)
import torch
import torch.nn as nn
import torch.nn.functional as F

class QualityControlCNN(nn.Module):
    def __init__(self, num_classes: int = 3):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(16),
            nn.ReLU(inplace=True)
        )
        self.stage2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True)
        )
        self.pool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(32, num_classes)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc(self.pool(self.stage2(self.stem(x))).flatten(1))

torch.manual_seed(42)
model = QualityControlCNN(num_classes=3).eval()
activations = {}

def hook_fn(mod, inp, out):
    out.retain_grad()
    activations["feat"] = out

handle = model.stage2.register_forward_hook(hook_fn)
img = torch.randn(1, 3, 32, 32)
logits = model(img)
defect_class = int(logits.argmax(dim=1).item())
logits[0, defect_class].backward()
handle.remove()

# Compute Grad-CAM saliency map: ReLU(sum_k alpha_k * A_k)
fmap = activations["feat"]
weights = fmap.grad.mean(dim=(2, 3), keepdim=True)
cam = F.relu((weights * fmap).sum(dim=1, keepdim=True))
cam_upsampled = F.interpolate(cam, size=(32, 32), mode="bilinear", align_corners=False)

print("Predicted Defect Class ID :", defect_class)
print("Final Conv Feature Shape  :", tuple(fmap.shape))
print("Upsampled Grad-CAM Shape  :", tuple(cam_upsampled.shape))
Output:
Predicted Defect Class ID : 1
Final Conv Feature Shape  : (1, 32, 8, 8)
Upsampled Grad-CAM Shape  : (1, 1, 32, 32)