PyTorch batch normalization and Dropout
Batch Normalization and Dropout are the two most core regularization and stabilization techniques in deep neural network training. The former addresses the internal covariate shift problem during training, making deeper networks trainable; the latter prevents overfitting by randomly dropping neurons, enhancing model generalization. The two are usually used together and are standard components of modern neural networks.
1. Batch Normalization
1.1 Basic principles
When training deep networks, small changes in the parameters of earlier layers are continuously amplified as the number of layers increases, causing the input distribution of subsequent layers to keep changing -- a phenomenon known asinternal covariate shift. Batch Normalization solves this problem by normalizing the output of each layer, forcing the activation values back into a stable distribution.
Normalization formula:
[\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}]
[y_i = \gamma \hat{x}_i + \beta]
Where:
- (\mu_B), (\sigma_B^2) are the mean and variance of the current batch
- (\epsilon) is a small constant to prevent division by zero (default
1e-5) - (\gamma), (\beta) are learnable scale and shift parameters that let the network decide the final distribution shape
Benefits of Batch Normalization:
- Allows larger learning rates and speeds up training
- Reduces sensitivity to initialization, making training more stable
- Has a certain regularization effect, reducing the reliance on Dropout
- Alleviates vanishing/exploding gradients, making deeper networks trainable
1.2 BatchNorm1d / 2d / 3d
PyTorch provides three versions based on input dimensionality; they are used in exactly the same way, differing only in the shape of data they process.
BatchNorm1d: for fully connected layers / sequential data
Example
import
torch
import
torch.
nn
as
nn
Input shape: (N, C) or (N, C, L)
N=batch_size, C=number of features/channels, L=sequence length
bn1d
=
nn.
BatchNorm1d
(
num_features
=
128
,
Number of features/channels
eps
=
1e-5
,
Small constant to prevent division by zero (default 1e-5)
momentum
=
0.1
,
Momentum of the moving average (default 0.1)
affine
=
True
,
Whether to learn gamma and beta (default True)
track_running_stats
=
True
,
Whether to track running mean/variance (default True)
)
Used after fully connected layers
x
=
torch.
randn
(
32
,
128
)
(batch=32, features=128)
out
=
bn1d
(
x
)
(
out.
shape
)
torch.Size([32, 128])
Sequential data (such as after 1D convolution)
x_seq
=
torch.
randn
(
32
,
128
,
50
)
(batch, channels, seq_len)
out_seq
=
bn1d
(
x_seq
)
(
out_seq.
shape
)
torch.Size([32, 128, 50])
BatchNorm2d: for CNN image feature maps
Example
Input shape: (N, C, H, W)
Normalize each channel C independently
bn2d
=
nn.
BatchNorm2d
(
num_features
=
64
)
64 channels
x
=
torch.
randn
(
32
,
64
,
28
,
28
)
(batch, channels, height, width)
out
=
bn2d
(
x
)
(
out.
shape
)
torch.Size([32, 64, 28, 28])
BatchNorm3d: for 3D convolution (video/medical imaging)
Example
Input shape: (N, C, D, H, W)
bn3d
=
nn.
BatchNorm3d
(
num_features
=
32
)
x
=
torch.
randn
(
4
,
32
,
16
,
32
,
32
)
(batch, channels, depth, h, w)
out
=
bn3d
(
x
)
(
out.
shape
)
torch.Size([4, 32, 16, 32, 32])
View learnable parameters
Example
bn
=
nn.
BatchNorm2d
(
64
)
(
f
"weight (gamma) shape: {bn.weight.shape}"
)
torch.Size([64])
(
f
"bias (beta) shape: {bn.bias.shape}"
)
torch.Size([64])
(
f
"running_mean shape: {bn.running_mean.shape}"
)
torch.Size([64])
(
f
"running_var shape: {bn.running_var.shape}"
)
torch.Size([64])
running_mean / running_var are not trainable parameters
They are moving-average statistics used during inference
(
f
"Number of trainable parameters: {sum(p.numel() for p in bn.parameters())}"
)
128 (64×2)
Meaning of the momentum parameter
Example
PyTorch's momentum is contrary to the usual understanding:
running_mean = (1 - momentum) × running_mean + momentum × batch_mean
that is, the larger the momentum, the greater the weight of the current batch's statistics
Default 0.1: usually appropriate
For small batch sizes, it is recommended to reduce it: momentum=0.01, to avoid unstable statistics
bn
=
nn.
BatchNorm2d
(
64
,
momentum
=
0.01
)
momentum=None: use cumulative moving average (CMA), suitable for very small batches
bn
=
nn.
BatchNorm2d
(
64
,
momentum
=
None
)
1.3 LayerNorm (layer normalization)
locksAll features of a single sampleare normalized, independent of the batch, suitable for scenarios with small or variable batch sizes.The standard normalization method for Transformers.
BatchNorm:在 batch 维度计算均值/方差(跨样本,同通道)
LayerNorm:在特征维度计算均值/方差(同样本,跨特征)
Example
import
torch
import
torch.
nn
as
nn
---- for fully connected/Transformer ------------------------------
normalized_shape: normalize the last few dimensions
ln
=
nn.
LayerNorm
(
normalized_shape
=
512
)
x
=
torch.
randn
(
32
,
10
,
512
)
(batch, seq_len, embed_dim)
out
=
ln
(
x
)
(
out.
shape
)
torch.Size([32, 10, 512])
---- normalize multiple dimensions ---------------------------------
ln_2d
=
nn.
LayerNorm
(
[
64
,
28
,
28
]
)
Normalize the three dimensions C, H, W
x
=
torch.
randn
(
8
,
64
,
28
,
28
)
out
=
ln_2d
(
x
)
---- typical usage in Transformer ----------------------------------
class
TransformerBlock
(
nn.
Module
)
:
def
init
(
self
,
embed_dim
,
num_heads
,
ff_dim
)
:
super
(
)
.
init
(
)
self
.
attn
=
nn.
MultiheadAttention
(
embed_dim
,
num_heads
,
batch_first
=
True
)
self
.
ff
=
nn.
Sequential
(
nn.
Linear
(
embed_dim
,
ff_dim
)
,
nn.
GELU
(
)
,
nn.
Linear
(
ff_dim
,
embed_dim
)
,
)
self
.
norm1
=
nn.
LayerNorm
(
embed_dim
)
<- normalize after each sublayer
self
.
norm2
=
nn.
LayerNorm
(
embed_dim
)
def
forward
(
self
,
x
)
:
attn_out
,
_
=
self
.
attn
(
x
,
x
,
x
)
x
=
self
.
norm1
(
x + attn_out
)
Residual + normalization
x
=
self
.
norm2
(
x +
self
.
ff
(
x
)
)
return
x
1.4 GroupNorm (group normalization)
Divide the channels into severalgroups, and normalize within each group. Independent of batch size, it performs better than BatchNorm in small-batch scenarios (such as object detection and medical image segmentation).
Example
num_groups: how many groups to divide the channels into (must divide num_channels evenly)
Special case: num_groups=1 is equivalent to LayerNorm
num_groups=num_channels is equivalent to InstanceNorm
gn
=
nn.
GroupNorm
(
num_groups
=
32
,
Number of groups (commonly: 8, 16, 32)
num_channels
=
256
,
Number of channels
eps
=
1e-5
,
affine
=
True
,
)
x
=
torch.
randn
(
4
,
256
,
56
,
56
)
Small batch (4 images), 256 channels
out
=
gn
(
x
)
(
out.
shape
)
torch.Size([4, 256, 56, 56])
GroupNorm is completely unaffected when batch=1 (such as inference on a single image)
x_single
=
torch.
randn
(
1
,
256
,
56
,
56
)
out_single
=
gn
(
x_single
)
Works perfectly normally
1.5 InstanceNorm (instance normalization)
locksEach channel of each sampleis normalized independently, without involving the batch dimension. Commonly used forimage style transfer-- preserving each image's own style information without letting the statistics of other images in the batch interfere.
Example
InstanceNorm2d: normalize the H x W for each (N, C)
in2d
=
nn.
InstanceNorm2d
(
num_features
=
64
,
affine
=
False
,
Default False (do not learn gamma/beta)
)
x
=
torch.
randn
(
8
,
64
,
128
,
128
)
out
=
in2d
(
x
)
(
out.
shape
)
torch.Size([8, 64, 128, 128])
1.6 Comparison of normalization methods
| Method | Normalization dimension | Batch dependency | Applicable scenarios |
|---|---|---|---|
BatchNorm |
Across batch (same channel) | Strong dependency | CNN image classification (large batch) |
LayerNorm |
Across features (same sample) | No dependency | Transformer, NLP, RNN |
GroupNorm |
Channels within a group (same sample) | No dependency | Small-batch object detection and segmentation |
InstanceNorm |
Spatial dimension (same sample, same channel) | No dependency | Image style transfer and generative models |
Quick reference for selection advice
batch_size >= 16, CNN image tasks -> BatchNorm2d
Transformer / BERT / GPT → LayerNorm
batch_size < 8, object detection/segmentation -> GroupNorm(num_groups=32)
Image style transfer / CycleGAN -> InstanceNorm2d
2. Dropout
2.1 Basic principles
During training, Dropout randomly sets the output of some neurons to 0 (with probability p), forcing the network not to rely on any single neuron, so as to learn more robust and distributed feature representations and effectively prevent overfitting.
During training:
[y_i = \begin{cases} 0 & \text{with probability } p \ \dfrac{x_i}{1-p} & \text{with probability } 1-p \end{cases}]
The retained neurons are scaled up by a factor of (\frac{1}{1-p}) to keep the expected value unchanged (i.e., Inverted Dropout).
During inference: Dropout Automatically disabled, all neurons participate in computation normally, equivalent to an ensemble average of multiple subnetworks.
训练时示意(p=0.5):
输入: [1.0, 2.0, 3.0, 4.0, 5.0]
掩码: [ 1, 0, 1, 0, 1 ] ← 随机生成
输出: [2.0, 0.0, 6.0, 0.0, 10.0] ← 保留的值乘以 1/(1-0.5)=2
During inference:
输出: [1.0, 2.0, 3.0, 4.0, 5.0] ← 原样输出
2.2 Dropout / Dropout2d / Dropout3d
Dropout: for fully connected layers
Example
import
torch
import
torch.
nn
as
nn
dropout
=
nn.
Dropout
(
p
=
0.5
)
p: probability of setting to zero
x
=
torch.
ones
(
2
,
10
)
(
"Training mode:"
)
dropout.
train
(
)
(
dropout
(
x
)
)
About 50% of the values are 0, and the retained values are 2.0
(
"\nEvaluation mode:"
)
dropout.
eval
(
)
(
dropout
(
x
)
)
All are 1.0, Dropout is disabled
Example output:
Training mode:
tensor([[2., 0., 2., 0., 2., 0., 0., 2., 2., 0.],
[0., 2., 0., 2., 0., 2., 2., 0., 0., 2.]])
Evaluation mode:
tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
Dropout2d: for CNN feature maps (whole-channel dropping)
Dropout2d Random dropping is performed at the channel level, meaning all spatial positions of an entire channel are zeroed together. This is more suitable for convolutional features than pointwise Dropout, because the activations of adjacent pixels are highly correlated, making pointwise dropping less effective.
Example
dropout2d
=
nn.
Dropout2d
(
p
=
0.3
)
Input: (N, C, H, W)
x
=
torch.
ones
(
4
,
16
,
8
,
8
)
4 images, 16 channels
out
=
dropout2d
(
x
)
(
out.
shape
)
torch.Size([4, 16, 8, 8])
Verification: whole-channel dropping
Channel dropping status of image 0 (nonzero = retained channel, all zeros = dropped channel)
kept_channels
=
(
out
[
0
]
.
sum
(
dim
=
(
1
,
2
)
)
!=
0
)
.
sum
(
)
.
item
(
)
(
f
"Image 0 retained {kept_channels}/16 channels"
)
Dropout3d: for 3D convolution
Example
Input: (N, C, D, H, W); the entire (D, H, W) feature volume is dropped
dropout3d
=
nn.
Dropout3d
(
p
=
0.2
)
x
=
torch.
ones
(
2
,
8
,
16
,
16
,
16
)
out
=
dropout3d
(
x
)
(
out.
shape
)
torch.Size([2, 8, 16, 16, 16])
Advice on choosing the p value
Example
Fully connected layers (wide hidden layers): higher Dropout
nn.
Dropout
(
p
=
0.5
)
Classic value, standard for hidden layers
Fully connected layers (narrow hidden layers) or small networks: lower Dropout
nn.
Dropout
(
p
=
0.2
)
Avoid underfitting
Convolutional layer Dropout2d: generally lower
nn.
Dropout2d
(
p
=
0.1
)
Convolutional layers already have a certain regularization effect
Dropout before the classification head (such as EfficientNet / ViT)
nn.
Dropout
(
p
=
0.3
)
Usually between 0.2 and 0.5
Transformer attention / FFN Dropout
nn.
Dropout
(
p
=
0.1
)
BERT's default value; Transformers are usually smaller
2.3 AlphaDropout
Specifically designed for the SELU activation function,this Dropout variant automatically adjusts the mean and variance after dropping neurons to maintain the self-normalizing property.
Example
Used together with SELU (self-normalizing network SELU + AlphaDropout)
class
SelfNormalizingNet
(
nn.
Module
)
:
def
init
(
self
,
in_dim
,
hidden_dim
,
num_classes
)
:
super
(
)
.
init
(
)
self
.
net
=
nn.
Sequential
(
nn.
Linear
(
in_dim
,
hidden_dim
)
,
nn.
SELU
(
)
,
nn.
AlphaDropout
(
p
=
0.1
)
,
<- used together with SELU
nn.
Linear
(
hidden_dim
,
hidden_dim
)
,
nn.
SELU
(
)
,
nn.
AlphaDropout
(
p
=
0.1
)
,
nn.
Linear
(
hidden_dim
,
num_classes
)
,
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
Note: AlphaDropout only makes sense when using the SELU activation function; with other activation functions, just use regular Dropout.
3. Training mode and evaluation mode
The behaviors of BatchNorm and Dropout during training and evaluation arecompletely different, so they must be switched correctly; this is one of the most common mistakes for beginners.
Comparison of behavioral differences
| Component | model.train() |
model.eval() |
|---|---|---|
| BatchNorm | Normalize using the current batch's mean/variance;update running_mean/var | Normalize using running_mean/var;Do not update |
| Dropout | Randomly set to zero (with probability p) | Disabled, all neurons output normally |
Correct usage
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Sequential
(
nn.
Linear
(
128
,
256
)
,
nn.
BatchNorm1d
(
256
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
nn.
Linear
(
256
,
10
)
,
)
---- training phase ------------------------------------------------
model.
train
(
)
<- switch to training mode (default state)
for
inputs
,
labels
in
train_loader:
optimizer.
zero_grad
(
)
outputs
=
model
(
inputs
)
BN uses batch statistics, Dropout randomly drops
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
---- evaluation/validation phase -----------------------------------
model.
eval
(
)
<- switch to evaluation mode (very important!)
with
torch.
no_grad
(
)
:
Also disable gradient computation
for
inputs
,
labels
in
val_loader:
outputs
=
model
(
inputs
)
BN uses running statistics, Dropout disabled
...
---- inference on a single image -----------------------------------
model.
eval
(
)
with
torch.
inference_mode
(
)
:
Faster than no_grad, dedicated to inference
output
=
model
(
single_input.
unsqueeze
(
0
)
)
pred
=
output.
argmax
(
1
)
.
item
(
)
Verify that mode switching is correct
Example
Use this code to verify that BN and Dropout are working in the correct mode
x
=
torch.
randn
(
8
,
128
)
model.
train
(
)
out_train_1
=
model
(
x
)
out_train_2
=
model
(
x
)
(
"Are the two outputs the same in training mode?"
,
torch.
allclose
(
out_train_1
,
out_train_2
)
)
False <- each Dropout mask is different, so the outputs differ (normal behavior)
model.
eval
(
)
out_eval_1
=
model
(
x
)
out_eval_2
=
model
(
x
)
(
"Are the two outputs the same in evaluation mode?"
,
torch.
allclose
(
out_eval_1
,
out_eval_2
)
)
True <- Dropout is disabled, BN uses fixed statistics, output is deterministic (normal behavior)
4. Placement within the network
Placement of BatchNorm
There are two schools of thought on the placement of BatchNorm, both currently practiced:
School one: before the activation function (original paper)
Conv → BN → ReLU
nn.
Sequential
(
nn.
Conv2d
(
32
,
64
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
64
)
,
BN before activation
nn.
ReLU
(
inplace
=
True
)
,
)
School two: after the activation function (some studies consider it more effective)
Conv → ReLU → BN
nn.
Sequential
(
nn.
Conv2d
(
32
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
inplace
=
True
)
,
nn.
BatchNorm2d
(
64
)
,
BN after activation
)
Practical advice: Follow the design of the paper you are referencing; with no special requirements, Conv -> BN -> ReLU is more mainstream
Placement of Dropout
Fully connected networks: place after the activation function
nn.
Sequential
(
nn.
Linear
(
512
,
256
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
After ReLU
nn.
Linear
(
256
,
128
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
nn.
Linear
(
128
,
10
)
,
Usually no Dropout before the output layer
)
CNN: place after BN (if BN is present, Dropout can be omitted)
Note: BN itself has a regularization effect; in a CNN, if BN is already present, there is no need to add Dropout to convolutional layers
Dropout is usually only added before fully connected layers or the classification head
nn.
Sequential
(
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
128
)
,
nn.
ReLU
(
inplace
=
True
)
,
Usually Dropout is not added here (BN already provides regularization)
)
Transformer: place inside the FFN and attention layers
class
FeedForward
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
d_ff
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
self
.
net
=
nn.
Sequential
(
nn.
Linear
(
d_model
,
d_ff
)
,
nn.
GELU
(
)
,
nn.
Dropout
(
dropout
)
,
Add Dropout inside the FFN
nn.
Linear
(
d_ff
,
d_model
)
,
nn.
Dropout
(
dropout
)
,
Add once more before the output
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
Should BN and Dropout be used together?
Fully connected networks: can be used together
nn.
Sequential
(
nn.
Linear
(
512
,
256
)
,
nn.
BatchNorm1d
(
256
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.3
)
,
BN + Dropout coexisting is common and effective
nn.
Linear
(
256
,
10
)
,
)
Convolutional networks: usually choose one or use Dropout only in the head.
Reason: BN's normalization and Dropout may produce a "variance shift" problem. That is, during training Dropout changes the variance of the activation values, while during inference Dropout is disabled, causing the statistics BN sees at inference to be inconsistent with those during training.
Recommended practice:
Option A: use only BN in convolutional layers, and only Dropout in fully connected layers / the classification head
Example
class
ConvNet
(
nn.
Module
)
:
def
init
(
self
,
num_classes
)
:
super
(
)
.
init
(
)
self
.
features
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
64
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
64
)
,
Convolutional part: use only BN
nn.
ReLU
(
inplace
=
True
)
,
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
128
)
,
nn.
ReLU
(
inplace
=
True
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
)
self
.
classifier
=
nn.
Sequential
(
nn.
Flatten
(
)
,
nn.
Linear
(
128
,
256
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
Fully connected part: use only Dropout
nn.
Linear
(
256
,
num_classes
)
,
)
def
forward
(
self
,
x
)
:
return
self
.
classifier
(
self
.
features
(
x
)
)
5. Complete network examples
Example 1: fully connected classification network (BN + Dropout)
Example
import
torch
import
torch.
nn
as
nn
class
MLPClassifier
(
nn.
Module
)
:
"""
A fully connected classifier with BatchNorm1d and Dropout
Suitable for tabular data classification tasks
"""
def
init
(
self
,
in_dim
,
hidden_dims
,
num_classes
,
dropout
=
0.5
)
:
super
(
)
.
init
(
)
layers
=
[
]
prev_dim
=
in_dim
for
hidden_dim
in
hidden_dims:
layers +
=
[
nn.
Linear
(
prev_dim
,
hidden_dim
)
,
nn.
BatchNorm1d
(
hidden_dim
)
,
nn.
ReLU
(
inplace
=
True
)
,
nn.
Dropout
(
dropout
)
,
]
prev_dim
=
hidden_dim
layers.
append
(
nn.
Linear
(
prev_dim
,
num_classes
)
)
self
.
net
=
nn.
Sequential
(
*layers
)
def
forward
(
self
,
x
)
:
return
self
.
net
(
x
)
model
=
MLPClassifier
(
in_dim
=
784
,
hidden_dims
=
[
512
,
256
,
128
]
,
num_classes
=
10
,
dropout
=
0.4
)
Verify the output shape
x
=
torch.
randn
(
32
,
784
)
model.
eval
(
)
(
model
(
x
)
.
shape
)
torch.Size([32, 10])
Example 2: CNN image classification (BN dominant)
Example
class
ConvBNBlock
(
nn.
Module
)
:
"""Standard convolution block: Conv -> BN -> ReLU"""
def
init
(
self
,
in_ch
,
out_ch
,
stride
=
1
)
:
super
(
)
.
init
(
)
self
.
block
=
nn.
Sequential
(
nn.
Conv2d
(
in_ch
,
out_ch
,
3
,
stride
=
stride
,
padding
=
1
,
bias
=
False
)
,
nn.
BatchNorm2d
(
out_ch
)
,
bias=False: BN's beta already serves as the bias
nn.
ReLU
(
inplace
=
True
)
,
)
def
forward
(
self
,
x
)
:
return
self
.
block
(
x
)
class
SmallCNN
(
nn.
Module
)
:
"""A small CNN for CIFAR-10"""
def
init
(
self
,
num_classes
=
10
)
:
super
(
)
.
init
(
)
self
.
features
=
nn.
Sequential
(
ConvBNBlock
(
3
,
32
)
,
32×32 → 32×32
ConvBNBlock
(
32
,
64
,
stride
=
2
)
,
32×32 → 16×16
ConvBNBlock
(
64
,
128
,
stride
=
2
)
,
16×16 → 8×8
ConvBNBlock
(
128
,
256
,
stride
=
2
)
,
8×8 → 4×4
nn.
AdaptiveAvgPool2d
(
1
)
,
4×4 → 1×1
)
self
.
classifier
=
nn.
Sequential
(
nn.
Flatten
(
)
,
nn.
Linear
(
256
,
128
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
Use Dropout only in the fully connected layers
nn.
Linear
(
128
,
num_classes
)
,
)
def
forward
(
self
,
x
)
:
return
self
.
classifier
(
self
.
features
(
x
)
)
model
=
SmallCNN
(
num_classes
=
10
)
x
=
torch.
randn
(
16
,
3
,
32
,
32
)
model.
eval
(
)
(
model
(
x
)
.
shape
)
torch.Size([16, 10])
Example 3: complete training loop
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
from
torch.
optim
.
lr_scheduler
import
CosineAnnealingLR
DEVICE
=
torch.
device
(
'cuda'
if
torch.
cuda
.
is_available
(
)
else
'cpu'
)
EPOCHS
=
50
model
=
SmallCNN
(
num_classes
=
10
)
.
to
(
DEVICE
)
criterion
=
nn.
CrossEntropyLoss
(
label_smoothing
=
0.1
)
optimizer
=
optim.
AdamW
(
model.
parameters
(
)
,
lr
=
1e-3
,
weight_decay
=
1e-4
)
scheduler
=
CosineAnnealingLR
(
optimizer
,
T_max
=
EPOCHS
)
def
run_epoch
(
model
,
loader
,
optimizer
=
None
,
train
=
True
)
:
if
train:
model.
train
(
)
<- BN uses batch statistics, Dropout active
else
:
model.
eval
(
)
<- BN uses running statistics, Dropout disabled
total_loss
,
correct
=
0.0
,
0
ctx
=
torch.
enable_grad
(
)
if
train
else
torch.
no_grad
(
)
with
ctx:
for
imgs
,
labels
in
loader:
imgs
,
labels
=
imgs.
to
(
DEVICE
)
,
labels.
to
(
DEVICE
)
if
train:
optimizer.
zero_grad
(
)
outputs
=
model
(
imgs
)
loss
=
criterion
(
outputs
,
labels
)
if
train:
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- imgs.
size
(
0
)
correct +
=
(
outputs.
argmax
(
1
)
==
labels
)
.
sum
(
)
.
item
(
)
n
=
len
(
loader.
dataset
)
return
total_loss / n
,
correct / n
best_acc
=
0.0
for
epoch
in
range
(
1
,
EPOCHS +
1
)
:
train_loss
,
train_acc
=
run_epoch
(
model
,
train_loader
,
optimizer
,
train
=
True
)
val_loss
,
val_acc
=
run_epoch
(
model
,
val_loader
,
train
=
False
)
scheduler.
step
(
)
(
f
"Epoch {epoch:2d}/{EPOCHS} | "
f
"Train {train_loss:.4f}/{train_acc:.4f} | "
f
"Val {val_loss:.4f}/{val_acc:.4f}"
)
if
val_acc
best_acc:
best_acc
=
val_acc
torch.
save
(
model.
state_dict
(
)
,
'best.pth'
)
6. Hyperparameter tuning guide
BatchNorm parameter tuning
Example
---- momentum (the most frequently adjusted parameter) -------------
The default value of 0.1 works in most cases
batch_size is very small (< 8) -> unstable statistics -> reduce momentum
nn.
BatchNorm2d
(
64
,
momentum
=
0.01
)
Many training steps and a stable data distribution -> momentum can be appropriately increased
nn.
BatchNorm2d
(
64
,
momentum
=
0.2
)
---- affine=False (do not learn gamma/beta) -------------------------
Rarely used; usually keep the default True
Unless you clearly do not want BN to change the scale and offset of features
nn.
BatchNorm2d
(
64
,
affine
=
False
)
── track_running_stats=False ──────────────────────
Also use the current batch statistics for each inference (training and inference behave consistently)
Suitable for special scenarios such as online learning and streaming data
nn.
BatchNorm2d
(
64
,
track_running_stats
=
False
)
Dropout tuning strategies
Example
---- adjust p according to the degree of overfitting ----------------
Training acc much higher than validation acc (severe overfitting) -> increase p
Training acc close to validation acc but both low (underfitting) -> decrease p or remove Dropout
---- reference for recommended p values -----------------------------
p_values
=
{
'large fully connected hidden layers (> 1024)'
:
0.5
,
'medium fully connected hidden layers (256~1024)'
:
0.3
,
'small fully connected hidden layers (< 256)'
:
0.2
,
'CNN convolutional layers (Dropout2d)'
:
0.1
,
'before the classification head'
:
0.3
,
'Transformer FFN'
:
0.1
,
'Transformer attention'
:
0.1
,
}
---- dynamic Dropout (adjusted as training progresses) --------------
In some practices, p is small in the early stage of training and increased later (stronger regularization as the model becomes more complex)
class
DynamicDropoutNet
(
nn.
Module
)
:
def
init
(
self
,
initial_p
=
0.1
)
:
super
(
)
.
init
(
)
self
.
dropout
=
nn.
Dropout
(
initial_p
)
self
.
fc
=
nn.
Linear
(
256
,
10
)
def
set_dropout
(
self
,
p
)
:
self
.
dropout
.
p
=
p
def
forward
(
self
,
x
)
:
return
self
.
fc
(
self
.
dropout
(
x
)
)
model
=
DynamicDropoutNet
(
initial_p
=
0.1
)
In the middle of training, increase Dropout
model.
set_dropout
(
0.4
)
7. Common mistakes and precautions
Mistake 1: forgetting to switch to eval() mode
Incorrect Writing
Error: model.eval() was not called during evaluation
model.
train
(
)
Default state
for
imgs
,
labels
in
val_loader:
with
torch.
no_grad
(
)
:
outputs
=
model
(
imgs
)
Dropout still randomly drops! BN is still updating!
Results are nondeterministic, accuracy is falsely low, and running_mean/var is polluted
Correct Writing
Correct: explicitly switch modes before evaluation
model.
eval
(
)
with
torch.
no_grad
(
)
:
outputs
=
model
(
imgs
)
Deterministic output
Mistake 2: adding bias to a Conv layer and then connecting BN
Incorrect Writing
Redundant: the Conv bias will be canceled by BN's beta, wasting parameters
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
,
bias
=
True
)
,
Default True
nn.
BatchNorm2d
(
128
)
,
Correct Writing
Correct: when Conv is followed by BN, disable bias
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
,
bias
=
False
)
,
← bias=False
nn.
BatchNorm2d
(
128
)
,
Mistake 3: using BatchNorm when batch size=1
Incorrect Writing
Error: when batch=1, BN cannot compute the variance, and NaN or inf will appear during training
Single-sample inference is fine (using running stats), but single-sample training will crash
model.
train
(
)
x
=
torch.
randn
(
1
,
64
,
32
,
32
)
out
=
bn2d
(
x
)
<- in training mode, batch=1 will raise an error or produce NaN
Solution
Solution 1: use GroupNorm instead
nn.
GroupNorm
(
num_groups
=
32
,
num_channels
=
64
)
Solution 2: use LayerNorm
nn.
LayerNorm
(
[
64
,
32
,
32
]
)
Solution 3: switch to eval() during inference, which does not affect BN
model.
eval
(
)
out
=
bn2d
(
x
)
In inference mode, batch=1 works perfectly fine
Mistake 4: Dropout causing BN's variance shift
Problem
Problem: Dropout changes the variance of activation values during training
During inference Dropout is disabled, and BN uses the training-time running_var (containing the effect of Dropout)
The statistics do not match, and inference results are biased
nn.
Sequential
(
nn.
Conv2d
(
64
,
128
,
3
)
,
nn.
Dropout2d
(
0.5
)
,
<- using Dropout in convolutional layers
nn.
BatchNorm2d
(
128
)
,
<- the variance seen by BN has been changed by Dropout
)
Solution
Option 1: BN first, Dropout after
nn.
Sequential
(
nn.
Conv2d
(
64
,
128
,
3
)
,
nn.
BatchNorm2d
(
128
)
,
BN first (unaffected by Dropout)
nn.
ReLU
(
)
,
nn.
Dropout2d
(
0.1
)
,
Dropout after
)
Option 2: use only BN in convolutional layers and only Dropout in fully connected layers (most recommended)
Mistake 5: forgetting to switch frozen BN layers to eval mode
Incorrect Writing
In transfer learning, when freezing the backbone, the running stats of pretrained BN should not be updated
Otherwise, the new data distribution will pollute the pretrained statistics
Error: parameters are frozen, but BN's running_mean/var is still being updated
model
=
models.
resnet50
(
weights
=
'IMAGENET1K_V2'
)
for
param
in
model.
parameters
(
)
:
param.
requires_grad
=
False
Only learnable parameters are frozen; BN statistics are still updated
Correct Writing
Correct approach: also switch the backbone's BN layers to eval mode
def
freeze_bn
(
model
)
:
for
module
in
model.
modules
(
)
:
if
isinstance
(
module
,
(
nn.
BatchNorm1d
,
nn.
BatchNorm2d
,
nn.
BatchNorm3d
)
)
:
module.
eval
(
)
Fix running_mean/var
for
param
in
module.
parameters
(
)
:
param.
requires_grad
=
False
model
=
models.
resnet50
(
weights
=
'IMAGENET1K_V2'
)
freeze_bn
(
model
)
Freeze all BN
model.
fc
=
nn.
Linear
(
model.
fc
.
in_features
,
10
)
Only the new FC layers are trainable
Quick diagnostic checklist
| Symptom | Possible cause | Check item |
|---|---|---|
| Validation loss fluctuates high and low | Forgot to model.eval() |
Confirm the call before evaluation eval() |
| Huge gap between training/validation acc | Dropout p Too large |
Try decreasing p or removing Dropout |
| Training NaN/inf | batch=1 used BatchNorm | Switch to GroupNorm or LayerNorm |
| Poor transfer learning performance | BN running stats are polluted | Backbone BN layers call eval() |
| Model inference results are unstable | Did not switch during inference eval() |
Required before inference model.eval() |
| Conv has too many parameters | Conv+BN did not disable bias | Settings bias=False |