.torch.save与torch.jit.save

本文介绍了如何使用torch.jit.save在PyTorch中保存和加载编译模型,区分了script和trace两种方式,并详细讲解了torch.save的不同用途,包括模型测试、训练状态恢复和模型分享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.torch.jit.save

torch.jit.save用来保存编译后的模型,支持跨平台,要注意模型中只能使用pytorch的函数。

jit.save支持保存script类型和trace类型的模型,其中script为全量模型,trace为仅保存运行过的路径

2.torch.save

torch.save有三种使用场景,参考:https://stackoverflow.com/questions/42703500/best-way-to-save-a-trained-model-in-pytorch

1.保存模型用来做测试

torch.save(model.state_dict(), filepath)
#Later to restore:
model.load_state_dict(torch.load(filepath))
model.eval()

2.用来恢复训练状态

state = {
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}
torch.save(state, filepath)
#later
model.load_state_dict(state['state_dict'])
optimizer.load_state_dict(state['optimizer'])

Since you are resuming training, DO NOT call model.eval() once you restore the states when loading.

3.用来给不不知道你的网络结构的人使用

torch.save(model, filepath)
# Then later:
model = torch.load(filepath)

This way is still not bullet proof and since pytorch is still undergoing a lot of changes, I wouldn’t recommend it.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值