PyTorch torch.save and torch.load functions
PyTorch torch reference manual
torch.save and torch.load are functions in PyTorch used to serialize (save) and deserialize (load) tensors, models, and other Python objects.
These functions are essential for scenarios such as saving trained models and saving checkpoints to resume training.
Function definition
torch.save(obj, f, pickle_module, pickle_protocol)
torch.load(f, map_location, pickle_module, weights_only)
torch.save parameters:
obj: the object to save, which can be a tensor, model, dictionary, list, etc.f: file path (string or file object).pickle_module(optional): module used for serialization.pickle_protocol(optional): serialization protocol version.
torch.load parameters:
f: file path (string or file object).map_location(optional): specifies how to map storage to different devices.pickle_module(optional): module used for deserialization.weights_only(bool, optional): whether to load only weights and not Python objects.
Usage examples
Example 1: save and load a tensor
Example
import
torch
Create some tensors
x
=
torch.
tensor
(
[
1
,
2
,
3
,
4
,
5
]
)
y
=
torch.
randn
(
3
,
4
)
Save a tensor to a file
torch.
save
(
{
'x'
: x
,
'y'
: y
}
,
'tensors.pth'
)
Load a tensor from a file
loaded
=
torch.
load
(
'tensors.pth'
)
(
"Loaded data:"
,
loaded
)
(
"x:"
,
loaded
[
'x'
]
)
(
"y:"
,
loaded
[
'y'
]
)
The output is:
加载的数据: {'x': tensor([1, 2, 3, 4, 5]), 'y': tensor([[-0.3042, -0.9077, -1.0826, 0.9333],
[ 0.0551, 0.6728, 0.5942, -0.1522],
[-0.3744, 0.9239, -0.2104, -0.5239]])}
x: tensor([1, 2, 3, 4, 5])
y: tensor([[-0.3042, -0.9077, -1.0826, 0.9333],
[ 0.0551, 0.6728, 0.5942, -0.1522],
[-0.3744, 0.9239, -0.2104, -0.5239]])
Example 2: save and load a model
Example
import
torch
import
torch.
nn
as
nn
Define a simple neural network
class
SimpleNet
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleNet
,
self
)
.
init
(
)
self
.
fc1
=
nn.
Linear
(
10
,
5
)
self
.
fc2
=
nn.
Linear
(
5
,
2
)
def
forward
(
self
,
x
)
:
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
x
=
self
.
fc2
(
x
)
return
x
Create a model instance
model
=
SimpleNet
(
)
Save the model (save the entire model)
torch.
save
(
model
,
'model.pth'
)
Load model
loaded_model
=
torch.
load
(
'model.pth'
)
(
"Model saved and loaded"
)
(
loaded_model
)
Example 3: save only model parameters (recommended)
Example
import
torch
import
torch.
nn
as
nn
class
SimpleNet
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleNet
,
self
)
.
init
(
)
self
.
fc1
=
nn.
Linear
(
10
,
5
)
self
.
fc2
=
nn.
Linear
(
5
,
2
)
def
forward
(
self
,
x
)
:
x
=
torch.
relu
(
self
.
fc1
(
x
)
)
x
=
self
.
fc2
(
x
)
return
x
model
=
SimpleNet
(
)
Save only model parameters (recommended)
torch.
save
(
model.
state_dict
(
)
,
'model_weights.pth'
)
Create a new model and load the parameters
new_model
=
SimpleNet
(
)
new_model.
load_state_dict
(
torch.
load
(
'model_weights.pth'
)
)
(
"Model parameters saved and loaded"
)
(
new_model.
state_dict
(
)
.
keys
(
)
)
The output is:
模型参数已保存并加载
odict_keys(['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias'])
推荐只保存模型参数(state_dict),而不是保存整个模型。这样可以在不同架构的模型之间复用参数。
示例 4: 在 CPU 和 GPU 之间迁移
实例
import torch
# Assuming the model is saved on the GPU
if torch.cuda.is_available():
x = torch.randn(2, 3, device='cuda')
torch.save(x, 'tensor_gpu.pth')
# Load on CPU
x_cpu = torch.load('tensor_gpu.pth', map_location='cpu')
print("加载到 CPU:", x_cpu.device)
使用 map_location 参数可以将张量加载到不同的设备上。
注意事项
保存文件通常使用 .pth 或 .pt 扩展名。
推荐只保存模型参数(state_dict),而不是保存整个模型。
加载时需要注意安全性和版本兼容性。
Pytorch torch 参考手册