【报错记录】AttributeError: ‘xxx‘ object has no attribute ‘module‘


问题描述

在跑代码时,报出 AttributeError: 'InpaintGenerator' object has no attribute 'module' 的错误,如下图所示:
在这里插入图片描述

经过一通Debug,定位到是模型保存的位置出错,在检查完路径等没有错误之后。去网上搜寻了一翻资料。终于在一篇博客里找到了解决方案,此处进行记录,以后遇到方便查看。

问题分析与解决

原来这是别人多GPU跑的模型,用的方法是:

torch.save(self.netG.module.state_dict(),   # state_dict变量存放训练过程中需要学习的权重和偏执系数
                os.path.join(self.args.save_dir, f'G{
      
      str(self.iteration).zfill(7)}.pt'))

可以看到第一个参数是 netG.module.state_dict(),而我的电脑是单GPU,因此只需要把.module去掉就好了。

即将代码改为:

torch.save(self.netG.state_dict(),   # state_dict变量存放训练过程中需要学习的权重和偏执系数
                os.path.join(self.args.save_dir, f'G{
      
      str(self.iteration).zfill(7)}.pt'))

此时再次运行代码就不再报错了。

总结

在保存模型时,如果电脑是单GPU,报 AttributeError: 'xxx' object has no attribute 'module' 的错误的话,只需要把 torch.save() 中第一个参数的.moudle去掉即可。

参考资料

[1] https://blog.csdn.net/qq_45860671/article/details/124118416

猜你喜欢

转载自blog.csdn.net/hshudoudou/article/details/127435680