PyTorch: Neural network training and development

PyTorch: Neural network training and development

PyTorch is a deep learning framework based on Python, providing functions such as Tensor calculation, automatic differentiation, neural network module, data loading and model optimization.

It is widely used in the research, training and inference of modern neural networks such as CNN, Transformer, Diffusion Models, LLM.

The core development process of PyTorch can be summarized as:

Dataset
   ↓
DataLoader
   ↓
Model (nn.Module)
   ↓
Forward Propagation
   ↓
Loss Function
   ↓
Autograd / Backward
   ↓
Optimizer / Parameter Update
   ↓
Validation / Checkpoint
   ↓
Inference

This article focuses on the most important API and working mechanisms when actually training neural networks. It does not repeat the mathematical derivation of backpropagation, nor does it introduce the theoretical details of the optimization algorithm in depth.

1. Basic composition of PyTorch

moduleMain function
torchTensor Calculation, equipment operation, basics of automatic differentiation
torch.nnNeural network layer, Loss, model module
torch.nn.functionalNeural network operations in functional form
torch.optimOptimizers such as SGD, Adam, AdamW
torch.utils.dataDataset、DataLoader
torch.autogradautomatic differentiation
torch.ampAutomatic mixed precision training
torch.distributedDistributed training
torch.compileCompile and optimize model execution

Installation

The CPU environment can be used:

pip install torch

If you need NVIDIA GPU, CUDA or other acceleration backends, you should select the corresponding installation command from the [PyTorch official installation page ] (https://pytorch.org/get-started/locally/) according to the operating system, GPU and driver environment.

Check the environment:

import torch

print(torch.__version__)
print(torch.cuda.is_available())

2. Tensor: Basic data structure

Tensor is the most basic data structure of PyTorch, similar to NumPy and ndarray, but supports:

  • CPU / GPU calculation.
  • Automatic Differentiation。
  • Neural network parameter optimization.
  • Multiple data types and memory layouts.

Create Tensor

import torch

a = torch.tensor([1, 2, 3])

b = torch.zeros(3, 4)
c = torch.ones(2, 3)
d = torch.randn(5, 10)

print(d.shape)  # torch.Size([5, 10])

Shape、Dtype、Device

x = torch.randn(32, 128)

print(x.shape)
print(x.dtype)
print(x.device)

These three properties are very important:

  • shape: Tensor dimension.
  • dtype: Data type, such as float32, float16.
  • device: Computing device, such as CPU, CUDA.

Typical image input:

[Batch, Channels, Height, Width]
[32, 3, 224, 224]

Typical Transformer input:

[Batch, Sequence Length, Hidden Dimension]
[32, 512, 768]

Commonly used Tensor operations

x = torch.randn(32, 10)

x.reshape(16, 20)
x.unsqueeze(0)
x.squeeze()
x.transpose(0, 1)

x.mean(dim=0)
x.sum(dim=1)

x @ torch.randn(10, 5)

Operations such as reshape() and transpose() are similar to the corresponding concepts in NumPy.

Note: reshape() is not guaranteed to always return View; a new data copy may be generated in some cases.

Broadcasting

x = torch.randn(32, 10)
bias = torch.randn(10)

y = x + bias

bias expands to Batch dimensions based on Broadcasting Rules.

NumPy conversion

import numpy as np

arr = np.array([1.0, 2.0, 3.0])

x = torch.from_numpy(arr)

arr2 = x.numpy()

CPU Tensor and NumPy Array can share the underlying memory when conditions are met.

For Tensor which may be located at GPU and participate in the gradient calculation:

arr = x.detach().cpu().numpy()

This is a more general conversion method.

3. Device: CPU, GPU and data migration

PyTorch Use device to specify Tensor and the computing device on which the model resides.

Device Selection

import torch

if torch.cuda.is_available():
    device = torch.device("cuda")
elif torch.backends.mps.is_available():
    device = torch.device("mps")
else:
    device = torch.device("cpu")

Among them:

  • cpu:CPU。
  • cuda:NVIDIA GPU。
  • mps: Apple GPU that supports Metal Performance Shaders.

Move Tensor

x = torch.randn(32, 10)

x = x.to(device)

Mobile model:

model = model.to(device)

When training you need to make sure:

X = X.to(device)
y = y.to(device)

Model parameters and the Tensor involved in the calculation must be on a compatible device.

Common mistakes:

Expected all tensors to be on the same device

It is usually caused by the model and data being located at CPU and GPU respectively.

.to() vs original Tensor

x_gpu = x.to(device)

.to() returns Tensor on the target device or type, and it should not be assumed that x is modified in-place in all cases.

For nn.Module:

model.to(device)

The parameters and Buffer in the module will be moved and converted, which can usually be used directly.

4. Autograd: automatic differentiation

PyTorch uses torch.autograd to automatically calculate gradients.

requires_grad

w = torch.tensor(
    2.0,
    requires_grad=True,
)

x = torch.tensor(3.0)

y = w * x
loss = y ** 2

loss.backward()

print(w.grad)

Due to:

L=(3w)2=9w2L=(3w)^2=9w^2

Therefore:

∂L∂w=18w\frac{\partial L}{\partial w}=18w

When w=2w=2, the gradient is 36.

Computational Graph

When Tensor participates in operations with gradient tracking, PyTorch will record the corresponding calculation relationship.

w ──┐
    × ── y ── square ── loss
x ──┘
                       ↓
                  backward()
                       ↓
                     w.grad

By default, the computational graph of PyTorch is built dynamically in each forward calculation.

.backward()

loss.backward()

For the scalar Loss, this can usually be called directly.

After execution, the gradients of the leaf parameters are accumulated into .grad.

Gradient accumulation

loss.backward()
loss.backward()  # By default, released calculation graphs cannot be directly reused.

In normal training, a new calculation graph will be created in each round, and .grad will be accumulated by default.

Therefore it is usually necessary to:

optimizer.zero_grad()

or:

optimizer.zero_grad(set_to_none=True)

The latter sets the gradient to None, which can reduce memory and unnecessary operations in some cases.

detach()

y = model(x)

y_detached = y.detach()

detach() returns a Tensor that no longer participates in the current Autograd calculation graph.

Commonly used for:

  • Extract prediction results.
  • Record training metrics.
  • Give the result to NumPy.
  • Explicitly block a gradient path.

But be aware: detach() usually shares storage with the original Tensor and does not mean the creation of an independent copy.

5. nn.Module: Define neural network

nn.Module is the basic abstraction of the PyTorch neural network.

Models are generally defined by inheriting it:

import torch.nn as nn

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

        self.layers = nn.Sequential(
            nn.Linear(10, 64),
            nn.ReLU(),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, 1),
        )

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

Instantiation:

model = MLP()

__init__() and forward()

  • __init__(): Define and register the submodules and parameters of the model.
  • forward(): Define the forward calculation process.

Execution:

y = model(x)

Instead of calling directly:

y = model.forward(x)

Because model(x) will enter the model through nn.Module.__call__() and process related Hooks and other mechanisms.

Commonly used Layers

Layerfunction
nn.LinearFully connected layer
nn.Conv2d2D convolution
nn.EmbeddingDiscrete ID maps to vector
nn.LayerNormLayer Normalization
nn.BatchNorm1dBatch Normalization
nn.DropoutDropout
nn.ReLUReLU activation
nn.GELUGELU activation
nn.MultiheadAttentionmulti-head attention module

The most important things to master here are nn.Linear, nn.Sequential, nn.Embedding, nn.LayerNorm and common activation functions.

nn.Sequential

Suitable for simple sequential networks:

model = nn.Sequential(
    nn.Linear(10, 64),
    nn.ReLU(),
    nn.Linear(64, 2),
)

If you need conditional branches, multiple inputs, Residual Connection, or other complex calculations, you should customize forward().

nn.ModuleList and nn.ModuleDict

Used to dynamically organize multiple submodules.

self.layers = nn.ModuleList([
    nn.Linear(64, 64)
    for _ in range(4)
])

Then:

def forward(self, x):
    for layer in self.layers:
        x = layer(x)
    return x

Ordinary Python List will not automatically register the modules in it, so do not use ordinary List to replace ModuleList that needs to be registered.

6. Parameter, Buffer and state_dict

Parameter

nn.Parameter is a special kind of Tensor.

When it is assigned a value of nn.Module, it will be automatically registered as a trainable parameter.

class MyLayer(nn.Module):
    def __init__(self):
        super().__init__()

        self.weight = nn.Parameter(
            torch.randn(10, 10)
        )

    def forward(self, x):
        return x @ self.weight

View parameters:

for name, param in model.named_parameters():
    print(name, param.shape)

Buffer

Buffer is part of the model state, but is not typically updated via Optimizer.

For example:

self.register_buffer(
    "running_value",
    torch.zeros(10),
)

Persistent Buffer is included in state_dict() by default and moves the device with the model.

Some running statistics in BatchNorm are common examples.

state_dict

state_dict() saves the parameters of model registration and persistence Buffer.

state = model.state_dict()

for name, tensor in state.items():
    print(name, tensor.shape)

It is an important interface for saving and loading model weights.

7. Dataset: Organize training data

PyTorch abstracts data access using Dataset.

The most common one is Map-style Dataset, which needs to be implemented:

  • __len__(): sample number.
  • __getitem__(): Get samples based on index.

TensorDataset

If the data is already Tensor:

from torch.utils.data import TensorDataset

X = torch.randn(1000, 10)
y = torch.randint(0, 2, (1000,))

dataset = TensorDataset(X, y)

Custom Dataset

from torch.utils.data import Dataset

class CustomDataset(Dataset):
    def __init__(self, X, y):
        self.X = torch.as_tensor(
            X,
            dtype=torch.float32,
        )
        self.y = torch.as_tensor(
            y,
            dtype=torch.long,
        )

    def __len__(self):
        return len(self.X)

    def __getitem__(self, index):
        return self.X[index], self.y[index]

In actual projects, __getitem__() may also be responsible for:

  • Read pictures or other files.
  • Convert raw data to Tensor.
  • Perform necessary data preprocessing.
  • Return training labels and other metadata.

Map-style and IterableDataset

TypeFeatures
DatasetUsually supports indexed access
IterableDatasetGenerate data in iterative order

IterableDataset is common in scenarios such as streaming data and continuously read data sources.

When using multiple DataLoader Worker, you need to be careful to avoid reading the same batch of streaming data repeatedly.

8. DataLoader: Batch data loading

DataLoader wraps Dataset into an iterable object, responsible for Batch combination, sampling, and optional multi-process data loading.

from torch.utils.data import DataLoader

loader = DataLoader(
    dataset,
    batch_size=32,
    shuffle=True,
    num_workers=0,
)

Traverse:

for X_batch, y_batch in loader:
    print(X_batch.shape)
    print(y_batch.shape)

Core parameters

parametersfunction
batch_sizeNumber of samples per Batch
shuffleWhether to disrupt the order of samples
num_workersNumber of data loading sub-processes
pin_memoryWhether to use Pinned Memory
drop_lastWhether to discard the last batch of less than one Batch
collate_fnCustom Batch assembly logic
persistent_workersWhether to retain the Worker process

Train and Validation

Usually:

train_loader = DataLoader(
    train_dataset,
    batch_size=64,
    shuffle=True,
)

val_loader = DataLoader(
    val_dataset,
    batch_size=64,
    shuffle=False,
)

The training set usually shuffles the data, the validation set usually doesn't.

collate_fn

When the sample is of variable length, such as a text sequence, collate_fn can be customized to complete Padding.

from torch.nn.utils.rnn import pad_sequence

def collate_fn(batch):
    sequences, labels = zip(*batch)

    padded = pad_sequence(
        sequences,
        batch_first=True,
        padding_value=0,
    )

    labels = torch.tensor(labels)

    return padded, labels

For LLM, Padding, Attention Mask, and dynamic Batch assembly are important data preparation steps, but can be covered further in the Transformer or LLM Training topics.

9. Loss Functions: training target

PyTorch provides common Loss Functions via torch.nn.

TaskCommonly used Loss
Regressionnn.MSELoss、nn.L1Loss
Binary Classificationnn.BCEWithLogitsLoss
Multiclass Classificationnn.CrossEntropyLoss

Two categories

criterion = nn.BCEWithLogitsLoss()

logits = model(X)

loss = criterion(
    logits,
    y.float(),
)

Typically the model output and label have the same shape, such as [batch_size, 1].

BCEWithLogitsLoss receives Logits without Sigmoid.

Multiple categories

criterion = nn.CrossEntropyLoss()

logits = model(X)  # [Batch, NumClasses]

loss = criterion(
    logits,
    labels,         # [Batch], integer category index
)

Do not execute Softmax before passing in CrossEntropyLoss.

This distinction is one of the most common mistakes made by PyTorch beginners.

10. Optimizer: Model parameter update

Optimizer updates model parameters based on gradients.

Commonly used optimizers:

import torch.optim as optim

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

optimizer = optim.Adam(
    model.parameters(),
    lr=0.001,
)

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

Main operations:

APIfunction
zero_grad()Clear or reset previous gradient
step()Update parameters based on gradient
state_dict()Get Optimizer status
load_state_dict()Restore Optimizer state
param_groupsManage different parameter groups and their hyperparameters

Four Key Steps to Training

optimizer.zero_grad()

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

loss.backward()
optimizer.step()

These four steps are the core Training Loop.

Parameter Groups

Different Learning Rate can be set for different parameters:

optimizer = optim.AdamW([
    {
        "params": model.encoder.parameters(),
        "lr": 1e-5,
    },
    {
        "params": model.classifier.parameters(),
        "lr": 1e-3,
    },
])

This is very common when pre-training the model Fine-tuning.

11. Training Loop: Complete training cycle

Training loops typically include:

For each Epoch:
    For each Batch:
        Move Data to Device
        Zero Gradients
        Forward
        Compute Loss
        Backward
        Optimizer Step

Train Function

def train_one_epoch(
    model,
    dataloader,
    criterion,
    optimizer,
    device,
):
    model.train()

    total_loss = 0.0
    total_samples = 0

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

        optimizer.zero_grad(set_to_none=True)

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

        loss.backward()
        optimizer.step()

        batch_size = X.size(0)

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

    return total_loss / total_samples

The sample size weighted average Loss is used here to avoid unnecessary bias in the average Epoch when the last Batch is small.

This implementation assumes that criterion uses per-sample average reduction.

model.train()

model.train()

Training Mode for switching models.

Will affect some modules, such as:

  • Dropout。
  • BatchNorm。

But calling model.train() itself will not start training, nor will gradients be automatically calculated.

12. Validation Loop: Model verification

The verification process usually does not require computing gradients or updating parameters.

def evaluate(
    model,
    dataloader,
    criterion,
    device,
):
    model.eval()

    total_loss = 0.0
    total_correct = 0
    total_samples = 0

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

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

            predictions = logits.argmax(dim=1)

            batch_size = X.size(0)

            total_loss += loss.item() * batch_size
            total_correct += (
                predictions == y
            ).sum().item()

            total_samples += batch_size

    return {
        "loss": total_loss / total_samples,
        "accuracy": total_correct / total_samples,
    }

model.eval() and torch.inference_mode()

The two functions are different.

model.eval()

Switch the behavior of the module, such as turning off Dropout and letting BatchNorm use the corresponding running statistics.

torch.inference_mode()

Turn off gradient tracking and further reduce some Autograd related overhead.

Therefore, practical inference often uses both:

model.eval()

with torch.inference_mode():
    predictions = model(X)

torch.no_grad() can also turn off gradient recording, but inference_mode() often provides further optimization in pure inference scenarios; its use is also more restrictive.

13. Complete example: train a classification MLP

Next, use scikit-learn to generate simulated classification data, and then use PyTorch to complete data preparation, training, verification, and model saving.

import numpy as np
import torch
import torch.nn as nn

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from torch.utils.data import TensorDataset, DataLoader

torch.manual_seed(42)

# 1. Generate data
X, y = make_classification(
    n_samples=2000,
    n_features=20,
    n_informative=12,
    n_redundant=4,
    random_state=42,
)

# 2. Split training set and validation set
X_train, X_val, y_train, y_val = train_test_split(
    X,
    y,
    test_size=0.2,
    stratify=y,
    random_state=42,
)

# 3. Standardization (only fit on the training set)
scaler = StandardScaler()

X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)

# 4. Convert to Tensor
train_dataset = TensorDataset(
    torch.tensor(X_train, dtype=torch.float32),
    torch.tensor(y_train, dtype=torch.long),
)

val_dataset = TensorDataset(
    torch.tensor(X_val, dtype=torch.float32),
    torch.tensor(y_val, dtype=torch.long),
)

# 5. DataLoader
train_loader = DataLoader(
    train_dataset,
    batch_size=64,
    shuffle=True,
)

val_loader = DataLoader(
    val_dataset,
    batch_size=64,
    shuffle=False,
)

# 6. Device
if torch.cuda.is_available():
    device = torch.device("cuda")
elif torch.backends.mps.is_available():
    device = torch.device("mps")
else:
    device = torch.device("cpu")

# 7. Model
class MLP(nn.Module):
    def __init__(self):
        super().__init__()

        self.network = nn.Sequential(
            nn.Linear(20, 64),
            nn.ReLU(),
            nn.Linear(64, 32),
            nn.ReLU(),
            nn.Linear(32, 2),
        )

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

model = MLP().to(device)

# 8. Loss / Optimizer
criterion = nn.CrossEntropyLoss()

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

# 9. Training
for epoch in range(20):
    train_loss = train_one_epoch(
        model,
        train_loader,
        criterion,
        optimizer,
        device,
    )

    metrics = evaluate(
        model,
        val_loader,
        criterion,
        device,
    )

    print(
        f"Epoch {epoch + 1:02d} | "
        f"Train Loss: {train_loss:.4f} | "
        f"Val Loss: {metrics['loss']:.4f} | "
        f"Val Accuracy: {metrics['accuracy']:.4f}"
    )

# 10. Save
torch.save(
    model.state_dict(),
    "mlp_weights.pth",
)

This is a complete basic training process. train_one_epoch() and evaluate() use the functions defined in the previous two sections.

Real projects should also consider independent test sets, optimal Checkpoint preservation, hyperparameter selection, and experimental recording.

14. Model Saving: Save and load

PyTorch It is recommended to use state_dict to save model weights.

Save model parameters

torch.save(
    model.state_dict(),
    "model.pth",
)

Load model parameters

model = MLP().to(device)

state_dict = torch.load(
    "model.pth",
    map_location=device,
    weights_only=True,
)

model.load_state_dict(state_dict)

model.eval()

Before loading weights, you need to create a model structure that is compatible with saving.

weights_only=True is the recommended restricted loading method when reading general weight files, but it does not mean that model files from unknown sources can be fully trusted.

Checkpoint

If you need to resume training, you should also save:

  • Model State。
  • Optimizer State。
  • Epoch / Global Step。
  • Learning Rate Scheduler State (if used).
  • Other training conditions that require recovery.

For example:

checkpoint = {
    "epoch": epoch,
    "model_state_dict": model.state_dict(),
    "optimizer_state_dict": optimizer.state_dict(),
}

torch.save(checkpoint, "checkpoint.pth")

Recovery:

checkpoint = torch.load(
    "checkpoint.pth",
    map_location=device,
    weights_only=True,
)

model.load_state_dict(
    checkpoint["model_state_dict"]
)

optimizer.load_state_dict(
    checkpoint["optimizer_state_dict"]
)

start_epoch = checkpoint["epoch"] + 1

For more complex training, you may also need to save the AMP Scaler, random number generator state, and Data Sampler state to resume the training process as accurately as possible.

15. Inference: Model inference

Backpropagation and Optimizer are not required for inference.

model.eval()

with torch.inference_mode():
    logits = model(X)

    probabilities = torch.softmax(
        logits,
        dim=1,
    )

    predictions = probabilities.argmax(dim=1)

detach(), no_grad() and inference_mode()

APIMain function
detach()Separate a Tensor from the current gradient calculation graph
torch.no_grad()Turn off gradient recording in code area
torch.inference_mode()Gradient off mode optimized specifically for inference
model.eval()Switch model to evaluation mode

These mechanisms are not perfect substitutes for each other.

Batch Inference

It is generally not recommended to call the model separately for each sample.

DataLoader batch inference can be used to improve device utilization:

model.eval()

all_predictions = []

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

        logits = model(X)
        predictions = logits.argmax(dim=1)

        all_predictions.append(
            predictions.cpu()
        )

all_predictions = torch.cat(all_predictions)

16. Mixed Precision: Mixed Precision Training

Modern neural network training often uses low-precision calculations to reduce video memory usage and improve throughput on supported hardware.

Common data types:

DtypeDescription
FP32single precision floating point
FP16half precision floating point
BF16Brain Floating Point, the index range is the same as FP32
FP64Double precision floating point, rarely used in ordinary deep learning

Automatic Mixed Precision(AMP)

PyTorch provides torch.autocast and torch.amp.GradScaler interfaces.

Typical CUDA FP16 training:

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

for X, y in train_loader:
    X = X.to("cuda")
    y = y.to("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()
    scaler.step(optimizer)
    scaler.update()

This assumes that the model has been moved to the CUDA device.

Autocast and GradScaler

  • autocast: Automatically selects calculation precision for appropriate operations.
  • GradScaler: Reduce the risk of FP16 gradient underflow via dynamic Loss Scaling.

When using BF16, GradScaler is generally not needed for FP16.

The actual performance gain of AMP depends on the GPU architecture, operation type, model and Batch Size, and not every scenario will be faster.

17. torch.compile: Model compilation

PyTorch 2.x Provides torch.compile() for compiling and optimizing the model execution process.

model = MLP().to(device)

model = torch.compile(model)

Key goals include:

  • Reduce some Python and frame scheduling overhead.
  • Optimize the computational graph.
  • Fusion operators in appropriate scenarios.
  • Improve training or inference performance of certain models.

Need to pay attention to:

  • There may be compilation overhead on the first run.
  • Acceleration is not guaranteed for all models.
  • There may be limitations on certain dynamic control flows, special operations, and device backends.
  • Benefits should be judged by actual Benchmark.

For general learning projects, it is not necessary to enable torch.compile() from the beginning.

18. Distributed Training: Distributed training

When a single GPU cannot meet the training scale or training time requirements, distributed training can be considered.

The most important concepts:

technologyMain function
DDPDistributed Data Parallel, multi-process data parallelism
FSDPFully Sharded Data Parallel, sharding model status
Distributed SamplerSplit data between multiple training processes
Gradient AccumulationAccumulate gradients of multiple Micro-batch
Gradient CheckpointingUse additional computing in exchange for lower activation memory usage

DDP

DDP typically lets different GPU process different subsets of data and then synchronizes the required gradients.

GPU 0 → Batch A → Gradients
                    ↓
                Synchronize
                    ↑
GPU 1 → Batch B → Gradients

FSDP

FSDP can slice and store model states such as parameters, gradients, and Optimizer State into different processes, reducing the memory pressure on a single device.

These contents are very important in large model training, but are not necessary to master the basic training of single GPU PyTorch.

19. Frequently Asked Questions and Practical Suggestions

1. Why does model Loss not drop?

Common reasons:

  • Learning Rate is inappropriate.
  • Input features are not preprocessed correctly.
  • Loss Function does not match the output shape.
  • Gradient was unexpectedly detach().
  • Forgot to execute optimizer.step().
  • There is a numerical problem with the model or data.

2. Why does GPU video memory continue to increase?

Possible reasons:

  • Tensor with calculation graph saved.
  • Accumulate Loss Tensor in the loop without detach().
  • Gradients are not managed correctly.
  • Batch Size is too large.
  • Models or intermediate activations take up a lot of video memory.

For example, it is not recommended:

losses.append(loss)

If you only need to log scalars:

losses.append(loss.item())

3. Why are the model training and inference results different?

First check:

model.train()
model.eval()

Dropout and BatchNorm may behave differently in training and inference modes.

4. Do all trainings require GPU?

unnecessary.

CPU is sufficient for small MLP, teaching examples, and some small-scale experiments.

But CNN, Transformer, large-scale matrix computations, etc. can often significantly benefit from a suitable GPU.

5. Can PyTorch be used only in neural networks?

no.

PyTorch is also essentially Tensor Computing and Automatic Differentiation Framework.

It can be used for numerical calculations, differentiable optimization, scientific calculations and other scenarios that require GPU or automatic derivation.


Summary

Knowledge pointsimportance
Tensor / Shape / Dtypecore
CPU / CUDA / MPS / Devicecore
Autograd / backward / gradcore
nn.Module / forwardcore
Parameter / Buffer / state_dictcore
nn.Sequential / ModuleListimportant
Dataset / DataLoadercore
Loss Functionscore
Optimizer / zero_grad / stepcore
Training Loopcore
Validation Loopcore
train / eval / inference_modecore
Checkpoint / Model Savingcore
Mixed Precision / AMPimportant
torch.compileon demand
DDP / FSDPon demand

PyTorch The five most important concepts:

  1. Tensor: The data, parameters and intermediate calculation results of the neural network are all represented by Tensor.
  2. Autograd: Automatically calculate gradients through dynamic calculation graphs, which is the basis of backpropagation.
  3. nn.Module: used to organize neural network layers, parameters and forward calculation process.
  4. Dataset / DataLoader: Responsible for organizing the original data into training Batch that can be iterated efficiently.
  5. Training Loop: Parameter optimization is done with Forward, Loss, Backward and Optimizer Step.

For real projects, being able to independently write training, validation, model saving, and inference processes is more important than memorizing a large number of PyTorch API.

Reference documentation

Back to top