Code Architecture — Squeeze-and-Excitation Networks Notebook
Overview
The notebook implements the SE block from scratch in PyTorch, puts it into a small 3-block CNN, and trains that CNN with and without SE blocks on CIFAR-10 for 4 epochs. It then looks at the channel weights produced by the first SE block. It runs on a GPU if there is one (the saved run used a Tesla T4).
Notebook Structure
1. Setup & Imports
- PyTorch, torchvision, NumPy, matplotlib; nothing is installed
- Seed 42;
CUBLAS_WORKSPACE_CONFIGset before importing torch, cuDNN deterministic,torch.use_deterministic_algorithms(True, warn_only=True) - Figures as JPEG at 80 dpi; on Kaggle an
atexithook and a small background process copy the executed notebook toexecuted_solution.ipynb
2. SE Block Implementation (SEBlock(channels, reduction=16))
- Squeeze:
nn.AdaptiveAvgPool2d(1): (B, C, H, W) → (B, C, 1, 1) - Excitation:
nn.Conv2d(C, C//r, 1)→ ReLU →nn.Conv2d(C//r, C, 1)→ Sigmoid; 1×1 convolutions on a (C, 1, 1) tensor act as the two fully connected layers. The width ismax(C // r, 1) - Scale:
x * s, with s of shape (B, C, 1, 1) broadcast over H and W - Stores the last weights in
last_excitationfor the plots (get_excitation_weights())
3. CNN Architecture (ConvBlock, SmallCNN(use_se=...))
ConvBlock(in_channels, out_channels, use_se, reduction): 3×3 conv (padding 1) → BatchNorm → ReLU →SEBlockifuse_se→ 2×2 max-poolSmallCNN(num_classes=10, use_se=False, reduction=16):block1(3→32),block2(32→64),block3(64→128), global average pooling,nn.Linear(128, 10)get_se_blocks()returns the SE blocks for the plots- With r = 16 the SE bottlenecks are 2, 4 and 8 units wide
4. Data Loading (CIFAR-10)
- Training transforms: RandomCrop(32, padding=4), RandomHorizontalFlip, normalisation; test: normalisation only
- Downloaded quietly (no progress bars)
- Batch size 128, 2 workers; the training loader has a seeded generator
- 50,000 training and 10,000 test images
5. Training Loop
train_model(): CrossEntropyLoss, SGD (momentum 0.9, weight decay 5e-4), learning rate 0.05,CosineAnnealingLRover the epochs- Epochs: 4
- Reseeds torch and the loader’s generator at the start, so both models see the same data order
- Records training and test loss and accuracy per epoch, and the best test accuracy
- Both models are built after
torch.manual_seed(42)and their parameters are counted: 94,986 without SE, 97,912 with SE (+2,926, 3.1%) - The baseline (
use_se=False) is trained first, then the SE model (use_se=True)
6. Results Comparison
- Training and test loss and accuracy per epoch for both models (2×2 plot)
- Prints both best test accuracies and the computed difference (SE-Net minus Baseline)
- Bar chart of the two best test accuracies
7. Channel Attention Visualization
- Runs the SE model on the first test batch (128 images) and takes the first SE block’s weights, shape (128, 32)
- Bar charts of the 32 channel weights for 8 images, and sorted weights for one image of each of 4 classes
8. Excitation Weight Statistics
- Mean and standard deviation of each channel’s weight over the batch (plots)
- Prints the overall mean and std, how many channels have mean > 0.5, how many have std > 0.1, and the largest per-channel std
9. Summary
### What the run above showswith the saved run’s numbers
Key Shapes
| Stage | Shape (B = 128) |
|---|---|
| Input | (128, 3, 32, 32) |
| block1: conv + BN + ReLU (+ SE) | (128, 32, 32, 32) |
| block1 max-pool | (128, 32, 16, 16) |
| block2: conv + BN + ReLU (+ SE) | (128, 64, 16, 16) |
| block2 max-pool | (128, 64, 8, 8) |
| block3: conv + BN + ReLU (+ SE) | (128, 128, 8, 8) |
| block3 max-pool | (128, 128, 4, 4) |
| Global average pool + flatten | (128, 128) |
fc | (128, 10) |
Inside an SE block with C channels: (B, C, H, W) → pool → (B, C, 1, 1) → conv 1×1 → (B, C/16, 1, 1) → ReLU → conv 1×1 → (B, C, 1, 1) → sigmoid → multiply → (B, C, H, W).
Deliberate Simplifications vs Full Paper
- Scale: a 3-block CNN on CIFAR-10 (32×32, 10 classes) instead of ResNet, ResNeXt, Inception and other networks on ImageNet (224×224, 1,000 classes).
- Reduction ratio: fixed at r = 16, the paper’s default; the paper compares r = 2 to 32 (Table 10). On 32, 64 and 128 channels this gives bottlenecks of only 2, 4 and 8 units.
- Placement: SE after the ReLU of each convolution, the paper’s VGG-style placement (Section 3.3); there are no residual connections.
- Ablations: none; the notebook only looks at the first SE block’s weights.
- Training: 4 epochs with SGD at learning rate 0.05, instead of the paper’s 100 epochs on ImageNet (Section 5.1).
- Biases: the excitation layers keep their biases; the paper’s ablations remove them on ResNet (Section 6).