Neural network training: optimizers, regularization, normalization and training stability

Neural Network Training: Optimizer, regularization, normalization and training stability

The goal of neural network training is to gradually reduce Loss Function by optimizing model parameters while allowing the model to generalize to unseen data.

After understanding Forward Propagation, Backpropagation and PyTorch Training Loop, the next most important thing is to master:

  • Optimization: How to update parameters based on gradients.
  • Learning Rate Scheduling: How to adjust the learning rate during training.
  • Regularization: How to control overfitting.
  • Normalization: How to improve the internal numerical distribution and training behavior of the network.
  • Initialization: How to reasonably initialize model parameters.
  • Training Stability: How to diagnose and deal with issues such as gradients and numerical accuracy.

These methods are applicable to various neural network architectures such as MLP, CNN, Transformer, etc.

1. Basic goals of neural network training

Neural network training can usually be expressed as:

min⁡θL(θ)\min_\theta \mathcal L(\theta)

Among them:

  • θ\theta: model parameters.
  • L\mathcal L: training objective function.

The most basic parameter update method is Gradient Descent:

θt+1=θt−η∇θL(θt)\theta_{t+1}=\theta_t-\eta\nabla_\theta\mathcal L(\theta_t)

where η\eta is Learning Rate.

Modern neural networks usually do not directly use the simplest Batch Gradient Descent, but use Mini-batch Training, combined with Momentum, Adaptive Optimizers, Learning Rate Schedulers and other methods to improve training efficiency and stability.

Training Loss and Validation Loss

During the training process, you should also pay attention to:

  • Training Loss: How well the model fits the training data.
  • Validation Loss: The model’s generalization performance on data that does not participate in parameter updating.

For example:

phenomenonPossible reasons
Train Loss and Val Loss are both highUnderfitting, insufficient training, optimization problems
Train Loss falls, Val Loss risesPossible overfitting
Loss fluctuated sharplyLearning rate too high, gradient or data issues
Loss almost does not dropThe learning rate is too low, the gradient is abnormal, or the model is configured incorrectly
Loss appears NaNNumerical overflow, illegal calculation or unstable training

You cannot judge whether the model is successfully trained based on Training Loss alone.

2. SGD: Stochastic Gradient Descent

Stochastic Gradient Descent (SGD) updates model parameters using gradient estimation.

In actual deep learning, Mini-batch SGD is usually used:

θt+1=θt−ηgt\theta_{t+1}=\theta_t-\eta g_t

Where gtg_t is the gradient calculated by the current Mini-batch.

PyTorch implementation

import torch

optimizer = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
)

Features of SGD

Advantages:

  • The calculation logic is simple.
  • Optimizer State has less overhead.
  • It has good generalization performance under appropriate parameter adjustment conditions.

Limitations:

  • More sensitive to Learning Rate.
  • Shocks may occur.
  • When the gradient scales of different parameters are very different, the convergence may be slow.

Therefore, Momentum is often combined in actual training.

3. Momentum: Momentum

Momentum utilizes exponentially weighted information from past gradients to improve parameter update direction.

Simplified form:

vt=βvt−1+gtv_t=\beta v_{t-1}+g_t θt+1=θt−ηvt\theta_{t+1}=\theta_t-\eta v_t

Among them:

  • vtv_t: Momentum.
  • β\beta: Momentum coefficient.
  • gtg_t: Current gradient.

Intuitively:

  • Updates can accumulate when the gradient direction is consistently consistent.
  • When the gradient direction changes frequently, some oscillations may be suppressed.

PyTorch implementation

optimizer = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
    momentum=0.9,
)

You can also use Nesterov Momentum:

optimizer = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
    momentum=0.9,
    nesterov=True,
)

Nesterov Momentum will make forward-looking corrections to gradient updates.

SGD with Momentum remains an important choice for training some CNN and vision models.

4. Adam: Adaptive Optimizer

Adam (Adaptive Moment Estimation) combines two types of information:

  1. First moment estimate of the gradient.
  2. Second-order raw moment estimates of squared gradients.

Its basic form:

mt=β1mt−1+(1−β1)gtm_t=\beta_1m_{t-1}+(1-\beta_1)g_t vt=β2vt−1+(1−β2)gt2v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2

After bias correction:

θt+1=θt−ηm^tv^t+ϵ\theta_{t+1} = \theta_t- \eta \frac{\hat m_t} {\sqrt{\hat v_t}+\epsilon}

where all vector operations are performed element-wise.

The core idea of Adam

Adam adjusts the effective update scale of each parameter based on the historical gradient statistics of different parameters.

Therefore, Adam is often easier to achieve usable initial training results in a variety of tasks than ordinary SGD.

PyTorch implementation

optimizer = torch.optim.Adam(
    model.parameters(),
    lr=1e-3,
    betas=(0.9, 0.999),
    eps=1e-8,
)
parametersfunction
lrbasic learning rate
betasAttenuation coefficients for first- and second-order moment estimates
epsnumerical stability term
weight_decayParameter attenuation configuration

Limitations of Adam

  • Additional storage of optimizer state is required.
  • There is no guarantee of generalization better than SGD on all tasks.
  • Still need to set Learning Rate appropriately.
  • Cannot automatically resolve exploding gradients or data problems.

5. AdamW: Decoupled weight decay

AdamW is a very important optimizer in modern deep learning and is widely used in the training of architectures such as Transformer.

One of its core differences from traditional Adam is Decoupled Weight Decay (decoupled weight decay).

L2 Regularization

Traditional L2 regularization is added to the loss function:

Ltotal=Ldata+λ2∥θ∥22\mathcal L_{\text{total}} = \mathcal L_{\text{data}}+\frac{\lambda}{2}\|\theta\|_2^2

Therefore, additional terms related to parameters will appear in the gradient.

For ordinary SGD, the L2 regularization is equivalent to the common Weight Decay form under certain conditions.

However, in adaptive optimizers such as Adam, adding the L2 penalty term to the gradient is not exactly the same as directly performing Weight Decay on the parameters.

Decoupled Weight Decay

AdamW handles parameter decay separately from adaptive gradient updates.

It can be summarized as:

θt+1=θt−η⋅AdaptiveUpdatet−ηλθt\theta_{t+1} = \theta_t - \eta\cdot AdaptiveUpdate_t - \eta\lambda\theta_t

This way Weight Decay will not be mixed into the momentum and second moment statistics of Adam.

PyTorch implementation

optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=0.01,
)

Adam, AdamW, SGD comparison

OptimizerFeaturesCommon applications
SGDSimple and low state overheadbase model
SGD + MomentumUsing historical gradient directionsCNN, visual training
AdamAdaptive parameter updateGeneral deep learning
AdamWAdam + decoupled Weight DecayTransformer, LLM, modern network

In actual development of , AdamW is a very reasonable default starting point, but it is not the optimal choice for all scenarios.

6. Learning Rate: Learning rate

Learning Rate (learning rate) is one of the most important training hyperparameters.

Learning rate is too large

May appear:

  • Loss oscillates violently.
  • Parameter update is too large.
  • Loss does not drop.
  • NaN / Inf。

Learning rate is too small

May appear:

  • The convergence rate is very slow.
  • It cannot be fully fitted within the limited training time.
  • Model performance did not improve significantly over a long period of time.

Common initial learning rates

The following is only a reference for the initial search range and is not a unified standard:

OptimizerA starting point to try
SGD + Momentum1e-2、1e-1
Adam1e-3
AdamW1e-4、1e-3
Pre-trained model Fine-tuningIt is often necessary to try a smaller learning rate for the model

The optimal learning rate is affected by factors such as model structure, Batch Size, Normalization, data size, and training goals.

7. Learning Rate Scheduler: Learning rate scheduling

Fixed Learning Rate is not always ideal.

Common training strategies are:

  • Use a larger learning rate in the early stage to learn quickly.
  • In the later stage, the learning rate is gradually reduced and the parameters are finely adjusted.

StepLR

Reduce the learning rate after each fixed number of Epoch:

from torch.optim.lr_scheduler import StepLR

scheduler = StepLR(
    optimizer,
    step_size=10,
    gamma=0.1,
)

for epoch in range(30):
    train_one_epoch(...)
    scheduler.step()

For example, the initial learning rate is 0.01, and every 10 Epoch times 0.1.

Cosine Annealing

Cosine annealing (Cosine Annealing) uses a smooth cosine curve to reduce the learning rate.

Common forms:

ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT)\eta_t= \eta_{\min} + \frac12(\eta_{\max}-\eta_{\min}) \left(1+\cos\frac{\pi t}{T}\right)
from torch.optim.lr_scheduler import CosineAnnealingLR

scheduler = CosineAnnealingLR(
    optimizer,
    T_max=100,
    eta_min=1e-6,
)

T_max corresponds to the step cycle of Scheduler. If each Epoch calls scheduler.step() once, this corresponds to 100 Epoch level scheduling steps.

OneCycleLR

One Cycle Policy usually increases the learning rate first and then gradually decreases it.

from torch.optim.lr_scheduler import OneCycleLR

scheduler = OneCycleLR(
    optimizer,
    max_lr=1e-3,
    epochs=10,
    steps_per_epoch=len(train_loader),
)

It usually needs to be called after every Optimizer Update:

optimizer.step()
scheduler.step()

Warmup

Warmup is a commonly used method in modern Transformer training.

Gradually increase the learning rate at the beginning of training, and then implement a normal decay schedule.

Learning Rate
      /\
     /  \
    /    \________
   /
  └────────────────→ Training Steps
   Warmup   Decay

Its main purpose is to avoid directly using a larger Learning Rate in the early stages of training, resulting in unstable updates.

Commonly used Scheduler comparison

SchedulerFeatures
StepLRDecrease according to fixed period
CosineAnnealingLRSmooth falloff
OneCycleLRFirst rise and then fall
ReduceLROnPlateauAdjust based on verification metrics
Warmup + DecayTraining plan for larger models

Note how often Scheduler is called: some are updated as Epoch, some are updated as Optimizer Step. The counting unit should be clearly defined when using it to avoid the learning rate changing faster than expected.

8. Regularization: Regularization

The purpose of Regularization is to limit the model from overfitting the training data.

The core idea is not to simply make Training Loss lower, but to improve the model's generalization ability to new data.

Common methods:

  • Weight Decay。
  • Dropout。
  • Early Stopping。
  • Data Augmentation。
  • Label Smoothing。
  • Control model capacity.

Weight Decay

Weight Decay limits parameter amplitude by continuously decaying model weights.

optimizer = torch.optim.AdamW(
    model.parameters(),
    weight_decay=0.01,
)

But not all parameters are suitable for using the same Weight Decay.

For example, in Transformer training, a common practice is to not impose Weight Decay on some Bias and Normalization Parameters.

decay_params = []
no_decay_params = []

for name, param in model.named_parameters():
    if not param.requires_grad:
        continue

    if name.endswith("bias") or param.ndim < 2:
        no_decay_params.append(param)
    else:
        decay_params.append(param)

optimizer = torch.optim.AdamW(
    [
        {
            "params": decay_params,
            "weight_decay": 0.01,
        },
        {
            "params": no_decay_params,
            "weight_decay": 0.0,
        },
    ],
    lr=1e-4,
)

This is a common engineering convention and not a rule that all models must adhere to.

9. Dropout: Random deactivation

Dropout randomly sets some activation values to 0 during training to reduce the model's dependence on specific neuron combinations.

import torch.nn as nn

model = nn.Sequential(
    nn.Linear(128, 256),
    nn.ReLU(),
    nn.Dropout(p=0.2),
    nn.Linear(256, 10),
)

Among them:

nn.Dropout(p=0.2)

Indicates that during training, the probability of each corresponding activation element being set to 0 is 20%.

PyTorch uses Inverted Dropout: the retained activation values are appropriately scaled during the training phase, and random deactivation is no longer performed during the inference phase.

Dropout and train/eval

model.train()

Dropout takes effect.

model.eval()

Normal Dropout no longer randomly deactivates.

Limitations of Dropout

  • Dropout is too strong and may cause underfitting.
  • Not necessarily applicable to all network layers.
  • Combinations with certain Normalization and architectures require careful configuration.
  • Modern large models don't necessarily all rely on higher Dropout Rate.

Therefore, Dropout should be scaled based on model and data size rather than being added by default in all layers.

10. Early Stopping: Stop early

Early Stopping decides when to stop training based on validation set performance.

For example:

Epoch       1    2    3    4    5    6
Train Loss  ↓    ↓    ↓    ↓    ↓    ↓
Val Loss    ↓    ↓    ↓    ↑    ↑    ↑

If Validation Loss continues to deteriorate, you can stop training to avoid continuing to fit the training set noise.

PyTorch example

best_val_loss = float("inf")
patience = 5
bad_epochs = 0

for epoch in range(100):
    train_one_epoch(...)

    val_loss = validate(...)

    if val_loss < best_val_loss:
        best_val_loss = val_loss
        bad_epochs = 0

        torch.save(
            model.state_dict(),
            "best_model.pth",
        )
    else:
        bad_epochs += 1

    if bad_epochs >= patience:
        print("Early stopping")
        break

In practical applications, min_delta can also be added to prevent very small random fluctuations from being regarded as effective improvements.

The important thing is: should eventually load Checkpoint corresponding to the best verification result, and not necessarily use the model of the last Epoch.

11. Normalization: normalization

Normalization is a very important mechanism in neural network training.

Its goals may include:

  • Controls the scale of intermediate activation values.
  • Improve conditions for the optimization process.
  • Improve training stability.
  • Reduce sensitivity to certain hyperparameter configurations.

The two most common methods are:

  • Batch Normalization。
  • Layer Normalization。

General normalization formula

x^=x−μσ2+ϵ\hat x=\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}

Then perform an affine transformation using learnable parameters:

y=γx^+βy=\gamma\hat x+\beta

Among them:

  • μ\mu: mean.
  • σ2\sigma^2: Variance.
  • ϵ\epsilon: Numerical stability term.
  • γ\gamma: Learnable scaling coefficient.
  • β\beta: Learnable offset.

The most important difference between the different Normalization methods is: along which dimensions calculates the mean and variance.

12. Batch Normalization

Batch Normalization (BatchNorm) typically normalizes activation values based on the statistics currently in Mini-batch.

For 2D input:

[Batch, Features]

BatchNorm1d generally computes statistics along the Batch dimension for each Feature.

PyTorch implementation

model = nn.Sequential(
    nn.Linear(128, 256),
    nn.BatchNorm1d(256),
    nn.ReLU(),
    nn.Linear(256, 10),
)

Training and Evaluation

BatchNorm often has different behavior during training and inference phases.

Training phase

Normalize using the statistics of the current Batch and update Running Statistics.

inference stage

Usually Running Mean and Running Variance accumulated during training are used.

Therefore:

model.train()

and:

model.eval()

May produce different results.

Limitations of BatchNorm

  • Depends on the Batch statistic.
  • A very small Batch may make the statistics unstable.
  • It is not necessarily convenient to use in sequence modeling and certain dynamic structures.

BatchNorm is very common among CNN, but modern Transformer is usually more commonly used with methods such as LayerNorm or RMSNorm.

13. Layer Normalization

Layer Normalization (LayerNorm) usually calculates the mean and variance for a specified feature dimension of a single sample.

For example:

[Batch, Sequence, Hidden]
nn.LayerNorm(768)

Represents normalization along the last Hidden Dimension of length 768.

PyTorch implementation

layer_norm = nn.LayerNorm(768)

x = torch.randn(32, 128, 768)

y = layer_norm(x)

The output is still:

[32, 128, 768]

Features of LayerNorm

  • Statistics that do not depend on other Batch samples.
  • Training and inference typically use statistics from the current input.
  • Suitable for sequence models such as Transformer.
  • The use of different Batch Size is more flexible.

BatchNorm vs. LayerNorm

FeaturesBatchNormLayerNorm
statistical dimensionUsually across Batch, press Channel/FeatureSpecify feature dimensions within a single sample
Depends on Batch Sizemore obvioussmaller
training/inference behaviorusually differentusually close
Common applicationsCNNTransformer

14. RMSNorm and other normalization methods

Modern Transformer is also often used as RMSNorm (Root Mean Square Normalization).

Unlike LayerNorm, RMSNorm does not perform mean centering, but scales the activations using the root mean square.

Simplified form:

RMS(x)=1d∑ixi2+ϵRMS(x)=\sqrt{\frac1d\sum_i x_i^2+\epsilon} y=γ⊙xRMS(x)y=\gamma\odot\frac{x}{RMS(x)}

Available in supported PyTorch versions:

norm = nn.RMSNorm(768)

RMSNorm is an important normalization method in modern LLM.

In addition:

  • GroupNorm: Normalized according to Channel Group, common in visual models.
  • InstanceNorm: Normalizes the corresponding Channel statistic in a single sample.
  • RMSNorm: Common in modern Transformer / LLM.

These methods only require mastering the main differences, and there is no need to go into in-depth mathematical derivation one by one in the basic training chapter.

15. Weight Initialization: Parameter initialization

Before starting neural network training, initial values need to be set for parameters.

Improper initialization may lead to:

  • The gradient disappears.
  • Gradient explosion.
  • The activation value scale is abnormal.
  • Convergence is slow.

Why can't all weights be initialized to 0?

If neurons in the same layer have exactly the same initialization state and subsequent gradients remain symmetrical, they may learn the same features.

Therefore, symmetry needs to be broken through appropriate random initialization.

Xavier Initialization

Xavier / Glorot Initialization are designed to control the variance of signals as they propagate between network layers.

Usually suitable for scenarios with activation functions such as Tanh.

nn.init.xavier_uniform_(layer.weight)

Kaiming Initialization

Kaiming / He Initialization specifically takes into account the characteristics of activation functions such as ReLU.

nn.init.kaiming_normal_(
    layer.weight,
    nonlinearity="relu",
)

Custom initialization

def initialize_weights(module):
    if isinstance(module, nn.Linear):
        nn.init.kaiming_normal_(
            module.weight,
            nonlinearity="relu",
        )

        if module.bias is not None:
            nn.init.zeros_(module.bias)

Application:

model.apply(initialize_weights)

However, this initialization strategy is only suitable for the corresponding ReLU network and should not be directly applied to all architectures containing GELU, gating modules or special output layers.

Most PyTorch built-ins of Layer already have a default initialization method. When using a pre-trained model, you should not reinitialize existing weights at will.

16. Vanishing / Exploding Gradients

Vanishing and exploding gradients are important issues when training deep neural networks.

Vanishing Gradients

In backpropagation, the multiplication of multiple small local derivatives may cause the gradient to decay quickly.

Result:

  • Early layer gradients are small.
  • Training speed slows down.
  • Deep parameters are difficult to update efficiently.

Common relief methods:

  • suitable activation function.
  • Weight Initialization。
  • Residual Connections。
  • Normalization。
  • Reasonable network architecture.

Exploding Gradients

If the gradient is continuously amplified during inter-layer propagation, it may cause the update to be very unstable.

Common relief methods:

  • Lower Learning Rate.
  • Gradient Clipping。
  • Improve initialization.
  • Normalization。
  • Check for numerical overflow.

17. Gradient Clipping: Gradient cropping

Gradient Clipping is used to limit the gradient size.

The most common is Gradient Norm Clipping.

If the overall norm of the gradient exceeds a specified threshold, the gradient is scaled down.

PyTorch implementation

loss.backward()

torch.nn.utils.clip_grad_norm_(
    model.parameters(),
    max_norm=1.0,
)

optimizer.step()

Gradient Norm

For a vector consisting of all gradients:

∥g∥2=∑igi2\|g\|_2=\sqrt{\sum_i g_i^2}

When the norm exceeds the threshold cc:

gclipped=g⋅c∥g∥2g_{\text{clipped}} = g\cdot\frac{c}{\|g\|_2}

In actual implementation, scaling is only performed when the norm exceeds a threshold, and necessary numerical processing is performed.

Things to note

  • Clipping is usually executed after backward() and before optimizer.step().
  • max_norm=1.0 is a common candidate setting and is not a universal optimal value.
  • Clipping can limit the gradient update amplitude, but it cannot solve all numerical problems.

18. Mixed Precision and training stability

Modern GPU usually supports low-precision calculations such as FP16, BF16, etc.

Mixed Precision Training can reduce some graphics memory overhead and improve throughput on supported hardware.

FP32、FP16、BF16

AccuracyFeatures
FP32Numerical accuracy and range are relatively balanced
FP16Lower accuracy and smaller dynamic range
BF16The mantissa has lower precision, but the exponent range is close to FP32

FP16 is prone to Underflow / Overflow, so Loss Scaling is usually required.

BF16 has a larger dynamic range and GradScaler used by FP16 is generally not needed.

FP16 + Gradient Clipping

scaler = torch.amp.GradScaler("cuda")

for X, y in train_loader:
    X = X.cuda()
    y = y.cuda()

    optimizer.zero_grad(set_to_none=True)

    with torch.autocast(
        device_type="cuda",
        dtype=torch.float16,
    ):
        logits = model(X)
        loss = criterion(logits, y)

    scaler.scale(loss).backward()

    # Restore gradient scale before cropping
    scaler.unscale_(optimizer)

    torch.nn.utils.clip_grad_norm_(
        model.parameters(),
        max_norm=1.0,
    )

    scaler.step(optimizer)
    scaler.update()

Note: If GradScaler is used, unscale_() must be executed before Gradient Clipping, otherwise the clipping will act on the amplified gradient.

19. Gradient Accumulation: Gradient accumulation

When the video memory of GPU is not enough to accommodate the larger Batch, you can accumulate the gradients of multiple Micro-batch and then execute Optimizer Update once.

For example:

Micro-batch Size:  8
Accumulation Steps: 4

Effective Batch Size ≈ 8 × 4 = 32

PyTorch implementation

The following assumes that the number of Batch is evenly divisible by the cumulative number of steps, and that each Micro-batch is the same size:

accumulation_steps = 4

optimizer.zero_grad(set_to_none=True)

for step, (X, y) in enumerate(train_loader):
    X = X.to(device)
    y = y.to(device)

    logits = model(X)

    loss = criterion(logits, y)
    loss = loss / accumulation_steps

    loss.backward()

    if (step + 1) % accumulation_steps == 0:
        optimizer.step()
        optimizer.zero_grad(set_to_none=True)

A real implementation would also need to correctly handle data that is less than accumulation_steps at the end.

Limitations of Gradient Accumulation

It can approximate the larger Effective Batch Size, but is not necessarily exactly equivalent to the really large Batch.

For example BatchNorm will rely on the statistics of each Micro-batch.

In addition, Gradient Accumulation will increase the number of forward and reverse calculations between each Optimizer Update, and will not automatically reduce the total calculation amount.

20. Diagnostic methods for training stability

Rather than constantly changing Optimizer, it is more important to first determine where the training problem comes from.

Check Loss

print(loss.item())

Observations:

  • Whether it continues to decline.
  • Is there any significant shock?
  • Whether NaN / Inf appears.
  • Whether the training and validation curves are separated.

Check the gradient

for name, param in model.named_parameters():
    if param.grad is not None:
        print(
            name,
            param.grad.norm().item(),
        )

If some key layers have no gradients for a long time, the calculation graph, requires_grad and model structure need to be checked.

Check for non-finite values

if not torch.isfinite(loss):
    raise RuntimeError("Non-finite loss")

Can also be enabled in Gradient Clipping:

torch.nn.utils.clip_grad_norm_(
    model.parameters(),
    max_norm=1.0,
    error_if_nonfinite=True,
)

Anomaly Detection

PyTorch provides Autograd Anomaly Detection:

with torch.autograd.detect_anomaly():
    logits = model(X)
    loss = criterion(logits, y)
    loss.backward()

It helps locate operations that produce NaN in partial backpropagation, but adds operational overhead and is suitable for debugging rather than regular production training.

Check data

If Loss is abnormal, you should first confirm:

  • Enter whether NaN / Inf exists.
  • Is the label range correct?
  • Whether Loss matches the output shape.
  • Whether the numerical scale is reasonable.
  • Whether the data preprocessing is consistent.
  • Whether there are leaks in the training set and validation set.

21. Actual training configuration example

A training configuration suitable for the common classification MLP is given below, combining AdamW, LayerNorm, Dropout, Cosine Scheduler, Gradient Clipping and Early Stopping.

Model

import torch
import torch.nn as nn

class MLP(nn.Module):
    def __init__(self, input_dim, num_classes):
        super().__init__()

        self.network = nn.Sequential(
            nn.Linear(input_dim, 256),
            nn.LayerNorm(256),
            nn.GELU(),
            nn.Dropout(0.1),

            nn.Linear(256, 128),
            nn.LayerNorm(128),
            nn.GELU(),

            nn.Linear(128, num_classes),
        )

    def forward(self, x):
        return self.network(x)

Optimizer / Scheduler

model = MLP(
    input_dim=20,
    num_classes=3,
).to(device)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=0.01,
)

scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
    optimizer,
    T_max=50,
    eta_min=1e-6,
)

Training

best_val_loss = float("inf")
patience = 8
bad_epochs = 0

for epoch in range(50):
    model.train()

    for X, y in train_loader:
        X = X.to(device)
        y = y.to(device)

        optimizer.zero_grad(set_to_none=True)

        logits = model(X)
        loss = criterion(logits, y)

        loss.backward()

        torch.nn.utils.clip_grad_norm_(
            model.parameters(),
            max_norm=1.0,
        )

        optimizer.step()

    model.eval()

    total_val_loss = 0.0
    total_samples = 0

    with torch.inference_mode():
        for X, y in val_loader:
            X = X.to(device)
            y = y.to(device)

            logits = model(X)
            loss = criterion(logits, y)

            batch_size = X.size(0)

            total_val_loss += loss.item() * batch_size
            total_samples += batch_size

    val_loss = total_val_loss / total_samples

    scheduler.step()

    if val_loss < best_val_loss:
        best_val_loss = val_loss
        bad_epochs = 0

        torch.save(
            model.state_dict(),
            "best_model.pth",
        )
    else:
        bad_epochs += 1

    if bad_epochs >= patience:
        break

It is assumed here that device, train_loader and val_loader have been prepared according to the previous PyTorch article.

This example shows how common training mechanisms can be combined and does not mean that all models need to use LayerNorm, Dropout, Weight Decay, and Gradient Clipping simultaneously.

Real projects will need to experiment to determine which mechanisms actually help.

22. How to choose training method?

sceneIt is recommended to give priority to
Simple MLPAdamW, reasonable Learning Rate
CNNSGD + Momentum or AdamW, BatchNorm
TransformerAdamW、Warmup、Learning Rate Decay、LayerNorm/RMSNorm
small data setWeight Decay, Early Stopping, data enhancement
Gradient instabilityGradient Clipping, learning rate check, numerical diagnosis
Insufficient video memoryMixed Precision、Gradient Accumulation
Training is slowerProfiling, AMP, optimized data loading, use torch.compile on demand

These are candidate policies, not fixed configuration templates.

For example:

  • Not all CNN are required to use BatchNorm.
  • Not all Transformer necessarily use the same Warmup scale.
  • Not all training instabilities can be resolved with Gradient Clipping.
  • Larger Batch Size also does not necessarily lead to better generalization.

Summary

Knowledge pointsimportance
SGD / Momentumcore
Adam / AdamWcore
Learning Ratecore
LR Scheduler / Warmupcore
Weight Decaycore
Dropoutimportant
Early Stoppingcore
BatchNormcore
LayerNorm / RMSNormcore
Xavier / Kaiming Initializationimportant
Vanishing / Exploding Gradientscore
Gradient Clippingcore
Mixed Precision / AMPimportant
Gradient Accumulationimportant
Training Diagnosticscore

The five most important concepts in neural network training:

  1. Optimization: SGD, Momentum, and AdamW update model parameters using gradients in different ways.
  2. Learning Rate Scheduling: Reasonable learning rate and training schedule usually have an important impact on the convergence speed and stability.
  3. Regularization: Weight Decay, Dropout, Early Stopping and other methods are used to improve generalization ability.
  4. Normalization & Initialization: Control the numerical scale of activations and parameters, helping to train deep networks.
  5. Training Stability: It is necessary to combine gradient, Loss, accuracy, data and computing equipment to comprehensively diagnose training problems.

Reference documentation

Back to top