惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
WordPress大学
WordPress大学
The Cloudflare Blog
云风的 BLOG
云风的 BLOG
博客园 - Franky
D
Docker
小众软件
小众软件
阮一峰的网络日志
阮一峰的网络日志
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
U
Unit 42
M
MIT News - Artificial intelligence
B
Blog
GbyAI
GbyAI
C
Check Point Blog
P
Proofpoint News Feed
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
IT之家
IT之家
Google DeepMind News
Google DeepMind News
V
V2EX
Stack Overflow Blog
Stack Overflow Blog

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
A Dig into PyTorch Model Loading
2022-01-28 · via jdhao's digital space

Saving and loading PyTorch models#

Models in PyTorch are a subclass of torch.nn.Module. To save the model parameters, we use model.state_dict() to get all the model parameters:

state = model.state_dict()

Then save the model parameter using torch.save():

torch.save(state, 'my-model.pth')

Loading error when using torch.load to load model trained on GPU#

When we load a model trained on GPU in a machine with no GPU using torch.load(model_path), we often get the following error:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the CPU.

The cause#

This is because when we use torch.save() to save an object, torch will also store the location of original data (called location tag, check code here). torch.save() also keeps the view relationship between tensors unchanged, see here.

Based on code here, it seems that PyTorch will save the GPU tensor as CPU.

When we use torch.load(), since the tensor location has been recorded, torch will load the tensor first to CPU, then moves it to the GPU indicated by the location tag. If that GPU is missing or we are using a CPU machine, the above error will occur.

Load the model correctly#

A better way to load a model is to move it to CPU using the map_location parameter of torch.load(). Load the model to CPU, then load the model parameter into the model, finally, move the model to GPU:

# move the model parameter to cpu
state = torch.load('my-model.pth', map_location=torch.device('cpu'))

model.load_state_dict(state)

# now move the model parameter to a GPU device of your choice
model.to(torch.device('cuda:0'))

ref#