PyTorch Fundamentals
PyTorch is an open-source deep learning framework widely popular for its flexibility and dynamic computational graph.
PyTorch has several core concepts: Tensor, Autograd, neural network modules (nn.Module), optimizers (optim), and more.
- Tensor: PyTorch's core data structure, supporting multidimensional arrays and accelerated computation on CPU or GPU.
- Autograd: PyTorch provides automatic differentiation, making it easy to compute model gradients for backpropagation and optimization.
- Neural Networks (nn.Module): PyTorch provides a simple yet powerful API for building neural network models, making forward passes and model definition convenient.
- Optimizers: use optimizers (such as Adam and SGD) to update model parameters and minimize the loss.
- Device: you can move models and tensors to the GPU to accelerate computation.
PyTorch Architecture Overview
PyTorch uses a modular design, composed of several cooperating core components. Understanding the role of these components and how they relate is key to mastering PyTorch.
PyTorch architecture diagram
┌─────────────────────────────────────────────────────────────┐
│ PyTorch 生态系统 │
├─────────────────────────────────────────────────────────────┤
│ torchvision │ torchtext │ torchaudio │ 其他专业库 │
├─────────────────────────────────────────────────────────────┤
│ PyTorch 核心 │
├───────────────┬─────────────────┬───────────────────────────┤
│ torch.nn │ torch.optim │ torch.utils │
│ (神经网络) │ (优化器) │ (工具函数) │
├───────────────┼─────────────────┼───────────────────────────┤
│ │ │ torch.utils.data │
│ torch 核心 │ autograd │ (数据加载) │
│ (张量计算) │ (自动微分) │ │
└───────────────┴─────────────────┴───────────────────────────┘
PyTorch adopts aLayered Architecturedesign, arranged from the top layer down as follows:
1. Python API (top layer)
torch: core tensor computation (similar to NumPy, with GPU support).torch.nn: neural network layers, loss functions, etc.torch.autograd: automatic differentiation (backpropagation).- The interface developers call directly, simple and easy to use.
2. C++ Core (middle layer)
- ATen: core library for tensor operations (400+ operations).
- JIT: just-in-time compilation to optimize models.
- Autograd engine: the low-level implementation of automatic differentiation.
- High-performance computing that bridges Python with low-level hardware.
3. Foundation libraries (low-level)
- TH/THNN: Basic tensor and neural network operations implemented in C.
- THC/THCUNN: The corresponding CUDA (GPU) version.
- Direct hardware manipulation (CPU/GPU) for extreme speed optimization.
Execution flow:
Python code -> C++ core computation -> low-level CUDA/C library acceleration -> return results.
Maintaining ease of use while ensuring high performance.

Tensor
A Tensor is the core data structure in PyTorch, used to store and manipulate multi-dimensional arrays.
A tensor can be viewed as a multi-dimensional array that supports accelerated computation operations.
In PyTorch, the concept of a tensor is similar to an array in NumPy, but PyTorch tensors can run on different devices such as CPU and GPU, which makes them very suitable for large-scale parallel computation, especially in the field of deep learning.
-
Dimensionality: The dimensionality of a tensor refers to the multi-dimensional array structure of the data. For example, a scalar (0-dimensional tensor) is a single number, a vector (1-dimensional tensor) is a one-dimensional array, a matrix (2-dimensional tensor) is a two-dimensional array, and so on.
-
Shape: The shape of a tensor refers to the size along each dimension. For example, a tensor with shape
(3, 4)means it has 3 rows and 4 columns. -
Data Type (Dtype): The data type in a tensor defines the memory size required to store each element and how it is interpreted. PyTorch supports many data types, including integer types (such as
torch.int8,torch.int32), floating-point types (such astorch.float32,torch.float64) and boolean types (torch.bool).
Tensor creation:
Example
import
torch
Create a 2x3 all-zero tensor
a
=
torch.
zeros
(
2
,
3
)
(
a
)
Create a 2x3 all-one tensor
b
=
torch.
ones
(
2
,
3
)
(
b
)
Create a 2x3 random tensor
c
=
torch.
randn
(
2
,
3
)
(
c
)
Create a tensor from a NumPy array
import
numpy
as
np
numpy_array
=
np.
array
(
[
[
1
,
2
]
,
[
3
,
4
]
]
)
tensor_from_numpy
=
torch.
from_numpy
(
numpy_array
)
(
tensor_from_numpy
)
Create a tensor on a specified device (CPU/GPU)
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
d
=
torch.
randn
(
2
,
3
,
device
=
device
)
(
d
)
The output is similar to the following:
tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[ 1.0189, -0.5718, -1.2814],
[-0.5865, 1.0855, 1.1727]])
tensor([[1, 2],
[3, 4]])
tensor([[-0.3360, 0.2203, 1.3463],
[-0.5982, -0.2704, 0.5429]])
Common tensor operations:
Example
Tensor addition
e
=
torch.
randn
(
2
,
3
)
f
=
torch.
randn
(
2
,
3
)
(
e + f
)
Element-wise multiplication
(
e * f
)
Tensor transpose
g
=
torch.
randn
(
3
,
2
)
(
g.
t
(
)
)
or g.transpose(0, 1)
Tensor shape
(
g.
shape
)
Return the shape
Tensors and devices
PyTorch tensors can exist on different devices, including CPU and GPU; you can move a tensor to the GPU to accelerate computation:
if torch.cuda.is_available():
tensor_gpu = tensor_from_list.to('cuda') # 将张量移动到GPU
Gradients and automatic differentiation
PyTorch tensors support automatic differentiation, a key feature in deep learning. When you create a tensor that requires gradients, PyTorch can automatically compute its gradients:
Example
Create a tensor that requires gradients
tensor_requires_grad
=
torch.
tensor
(
[
1.0
]
,
requires_grad
=
True
)
Perform some operations
tensor_result
=
tensor_requires_grad *
2
Compute gradients
tensor_result.
backward
(
)
(
tensor_requires_grad.
grad
)
Print the gradient
Memory and performance
PyTorch tensors also provide some memory management features, such as the .clone(), .detach(), and .to() methods, which can help you optimize memory usage and improve performance.
Autograd
Automatic differentiation (abbreviated as Autograd) is a core feature of deep learning frameworks that allows computers to automatically compute the derivatives of mathematical functions.
In deep learning, automatic differentiation is mainly used in two aspects:First, computing gradients when training neural networks, Second, implementing the backpropagation algorithm.
Automatic differentiation is based on the chain rule, a mathematical rule for computing the derivatives of complex functions. The chain rule states that the derivative of a composite function is the product of the derivatives of its component parts. In deep learning, a model is usually a complex function composed of many layers, and automatic differentiation can efficiently compute the gradients of these layers.
Dynamic graphs and static graphs:
-
Dynamic Graph: In a dynamic graph, the computational graph is built dynamically at runtime. Each time an operation is executed, the graph is updated, making it easier to debug and modify the model. PyTorch uses dynamic graphs.
-
Static Graph: In a static graph, the computational graph is constructed before execution begins and does not change. TensorFlow originally used static graphs but later also supported dynamic graphs.
PyTorch provides automatic differentiation through the autograd module to compute gradients automatically.
A torch.Tensor object has a requires_grad attribute that indicates whether the gradient of that tensor needs to be computed.
When you create a tensor with requires_grad=True, PyTorch automatically tracks all operations on it so that gradients can be computed later.
Create a tensor that requires gradients:
Example
Create a tensor that requires gradient computation
x
=
torch.
randn
(
2
,
2
,
requires_grad
=
True
)
(
x
)
Perform some operations
y
=
x +
2
z
=
y * y *
3
out
=
z.
mean
(
)
(
out
)
The output is similar to the following:
tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[ 1.0189, -0.5718, -1.2814],
[-0.5865, 1.0855, 1.1727]])
tensor([[1, 2],
[3, 4]])
tensor([[-0.3360, 0.2203, 1.3463],
[-0.5982, -0.2704, 0.5429]])
tianqixin@Mac-mini runoob-test % python3 test.py
tensor([[-0.1908, 0.2811],
[ 0.8068, 0.8002]], requires_grad=True)
tensor(18.1469, grad_fn=)
Backpropagation
Once the computational graph is defined, gradients can be computed via the .backward() method.
Example
Backpropagate and compute gradients
out.
backward
(
)
View the gradient of x
(
x.
grad
)
In neural network training, automatic differentiation is mainly used to implement the backpropagation algorithm.
Backpropagation is a method of training neural networks by computing the gradient of the loss function with respect to the network parameters. In each iteration, the forward pass of the network computes the output and loss, then backpropagation computes the gradient of the loss with respect to each parameter and uses these gradients to update the parameters.
Stop gradient computation
If you do not want gradients to be computed for certain tensors (for example, when you don't need backpropagation), you can use torch.no_grad() or set requires_grad=False.
Example
Disable gradient computation with torch.no_grad()
with
torch.
no_grad
(
)
:
y
=
x *
2
Neural Networks (nn.Module)
A neural network is a computational model that mimics the connections of neurons in the human brain. It consists of multiple layers of nodes (neurons) and is used to learn complex patterns and relationships in data.
A neural network optimizes prediction results by adjusting the connection weights between neurons; this process involves forward propagation, loss computation, backpropagation, and parameter updates.
Types of neural networks include feedforward neural networks, convolutional neural networks (CNN), recurrent neural networks (RNN), and long short-term memory networks (LSTM), which are widely used in fields such as image recognition, speech processing, and natural language processing.
PyTorch provides a very convenient interface for building neural network models, namely torch.nn.Module.
We can inherit from the nn.Module class and define our own network layers.
Create a simple neural network:
Example
import
torch.
nn
as
nn
import
torch.
optim
as
optim
Define a simple fully connected neural network
class
SimpleNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleNN
,
self
)
.
init
(
)
self
.
fc1
=
nn.
Linear
(
2
,
2
)
Input layer to hidden layer
self
.
fc2
=
nn.
Linear
(
2
,
1
)
Hidden layer to output layer
def
forward
(
self
,
x
)
:
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
ReLU activation function
x
=
self
.
fc2
(
x
)
return
x
Create a network instance
model
=
SimpleNN
(
)
Print the model structure
(
model
)
Output result:
SimpleNN(
(fc1): Linear(in_features=2, out_features=2, bias=True)
(fc2): Linear(in_features=2, out_features=1, bias=True)
)
Training process:
-
Forward Propagation: During the forward propagation phase, input data passes through the network layers, with each layer applying weights and an activation function until an output is produced.
-
Calculate Loss: Compute the value of the loss function based on the network's output and the true labels.
-
Backpropagation: Backpropagation uses automatic differentiation to compute the gradient of the loss function with respect to each parameter.
-
Parameter Update: Use an optimizer to update the network's weights and biases based on the gradients.
-
Iteration: Repeat the above process until the model's performance on the training data reaches a satisfactory level.
Forward propagation and loss computation
Example
Random input
x
=
torch.
randn
(
1
,
2
)
Forward propagation
output
=
model
(
x
)
(
output
)
Define a loss function (such as mean squared error, MSE)
criterion
=
nn.
MSELoss
(
)
Assume the target value is 1
target
=
torch.
randn
(
1
,
1
)
Compute the loss
loss
=
criterion
(
output
,
target
)
(
loss
)
Optimizers
An optimizer updates the neural network's parameters during training to reduce the value of the loss function.
PyTorch provides a variety of optimizers, such as SGD and Adam.
Parameter update using an optimizer:
Example
Define an optimizer (using the Adam optimizer)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Training step
optimizer.
zero_grad
(
)
Clear the gradients
loss.
backward
(
)
Backpropagation
optimizer.
step
(
)
Update parameters
Train the model
Training a model is a core process in machine learning and deep learning, aiming to learn model parameters from large amounts of data so that the model can make accurate predictions on new, unseen data.
Training a model usually includes the following steps:
-
Data preparation:
-
Define the model:
-
Choose a loss function:
-
Choose an optimizer:
-
Forward propagation:
-
Compute the loss:
-
Backpropagation:
-
Parameter update:
-
Iterative Optimization:
-
Evaluation and testing:
-
Model tuning:
-
Deploy the model:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
1. Define a simple neural network model
class
SimpleNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleNN
,
self
)
.
init
(
)
self
.
fc1
=
nn.
Linear
(
2
,
2
)
Input layer to hidden layer
self
.
fc2
=
nn.
Linear
(
2
,
1
)
Hidden layer to output layer
def
forward
(
self
,
x
)
:
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
ReLU activation function
x
=
self
.
fc2
(
x
)
return
x
2. Create a model instance
model
=
SimpleNN
(
)
3. Define the loss function and optimizer
criterion
=
nn.
MSELoss
(
)
Mean squared error loss function
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Adam optimizer
4. Assume we have training data X and Y
X
=
torch.
randn
(
10
,
2
)
10 samples, 2 features
Y
=
torch.
randn
(
10
,
1
)
10 target values
5. Training loop
for
epoch
in
range
(
100
)
:
Train for 100 epochs
optimizer.
zero_grad
(
)
Clear previous gradients
output
=
model
(
X
)
Forward propagation
loss
=
criterion
(
output
,
Y
)
Compute the loss
loss.
backward
(
)
Backpropagation
optimizer.
step
(
)
Update parameters
Print the loss every 10 epochs
if
(
epoch+
1
)
%
10
==
0
:
(
f
'Epoch [{epoch+1}/100], Loss: {loss.item():.4f}'
)
The output is as follows:
Epoch [10/100], Loss: 1.7180
Epoch [20/100], Loss: 1.6352
Epoch [30/100], Loss: 1.5590
Epoch [40/100], Loss: 1.4896
Epoch [50/100], Loss: 1.4268
Epoch [60/100], Loss: 1.3704
Epoch [70/100], Loss: 1.3198
Epoch [80/100], Loss: 1.2747
Epoch [90/100], Loss: 1.2346
Epoch [100/100], Loss: 1.1991
Every 10 epochs, the program prints the current loss value to help us track the model's training progress. As training proceeds, the loss should gradually decrease, indicating that the model is continuously learning and optimizing its parameters.
Training a model is an iterative process that requires continuous adjustment and optimization until satisfactory performance is achieved. This process involves extensive experimentation and tuning, with the goal of giving the model good generalization ability on new, unseen data.
Device
PyTorch allows you to move models and data to the GPU for acceleration.
Use torch.device to specify the computing device.
Move the model and data to the GPU:
Example
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
Move the model to the device
model.
to
(
device
)
Move the data to the device
X
=
X.
to
(
device
)
Y
=
Y.
to
(
device
)
During training, all tensors and the model should be moved to the same device (either all on CPU or all on GPU).