Problem loading saved state_dict

I am getting the following error trying to load my model:

File “/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py”, line 470, in load_state_dict
for name, param in state_dict.items():
AttributeError: ‘str’ object has no attribute ‘items’

I save the model using:

torch.save(model.state_dict(), save_path)

and then I try to load it using:

model = MyModel((1000,1000))
model.load_state_dict(model_path)

What could be causing this?

I think load_state_dict takes a state_dict, not a string path, so you’d need to do something like the following:

model = MyModel((1000,1000))
model.load_state_dict(torch.load(model_path))

as per http://pytorch.org/docs/master/notes/serialization.html

9 Likes

Thanks, that resolved the issue.

However, I now get a KeyError when the parameters load:

KeyError: ‘unexpected key “module.feature_extractor.conv_block1.0.weight” in state_dict’

feature_extractor is a custom module that is used as part of MyModel and conv_block1 is a nn.Sequential class member of feature_extractor. Why can’t those weights be loaded? Again I saved the model as:

torch.save(model.state_dict(), save_path)

Nevermind, this is answered here:

Sorry to interrupt, but i got an error with state_dict.copy(). it says that " AttributeError: ‘VGG’ object has no attribute ‘copy’". Can someone here help

Traceback (most recent call last):
File “C:/AI_Projects/Pytorch_to_TensorFlow_API/test.py”, line 20, in
convert.load_torch_model()
File “C:\AI_Projects\Pytorch_to_TensorFlow_API\converter.py”, line 43, in load_torch_model
self.torch_model.load_state_dict(torch.load(self.torch_model_path))
File “C:\Python37\lib\site-packages\torch\nn\modules\module.py”, line 818, in load_state_dict
state_dict = state_dict.copy()
File “C:\Python37\lib\site-packages\torch\nn\modules\module.py”, line 591, in getattr
type(self).name, name))
AttributeError: ‘VGG’ object has no attribute ‘copy’