【最佳实践】.pth还是.tar?

本文详细介绍了PyTorch中模型保存与加载的最佳实践,包括仅保存模型用于推断时使用.pth或.pt,以及断点保存使用.tar,并通过load_state_dict()方法加载。文章还解释了.pth.tar文件的使用场景及后缀名的选择依据。

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

pytorch的官方教程里提供了相关说明:

只保存模型用于以后的推断的话使用.pth.pt,这样可以直接加载模型

A common PyTorch convention is to save models using either a .pt or .pth file extension.

torch.save(model, "model.pth") # or .pt
model = torch.load("model.pth")

断点保存的话则使用.tar,加载的时候模型需要使用load_state_dict()方法

To save multiple components, organize them in a dictionary and use torch.save() to serialize the dictionary. A common PyTorch convention is to save these checkpoints using the .tar file extension.

torch.save({
            'epoch': epoch,
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'loss': loss,
            ...
            }, "checkpoint.tar")

...

checkpoint = torch.load("checkpoint.tar")
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']

其中部份人群喜欢使用.pth.tar来表明这不是一个简单的压缩tar类型的文件

其实这个问题一直有人讨论,因为pth同时也是Python的一种格式,所以有人甚至提出要更改一种后缀来区分…不过暂时不太需要考虑这个问题…

但实际上阅读save的源码就会发现,torch只是调用了Python的pickle来完成,而且没有做任何的后缀名判断,因此无论保存成什么后缀都是可以的…

在这里插入图片描述
源问题链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值