"AttributeError: 'function' object has no attribute 'items'" error when loading state_dict

I’m trying to load a model with model.load_state_dict(torch.load('Automatter_test.pth'))

It was saved out using torch.save(model.state_dict, 'Automatter_test.pth')

Traceback is:

Traceback (most recent call last):
  File "/usr/share/pycharm/helpers/pydev/pydev_run_in_console.py", line 78, in <module>
    globals = run_file(file, None, None)
  File "/usr/share/pycharm/helpers/pydev/pydev_run_in_console.py", line 35, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/usr/share/pycharm/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/nic/machineLearning/Automatter/machine-learning/automatte/run.py", line 196, in <module>
    loss=criterion, use_gpu=use_gpu
  File "/home/nic/machineLearning/Automatter/machine-learning/automatte/run.py", line 27, in train_model
    model.load_state_dict(torch.load('Automatter_test.pth'))
  File "/home/nic/.conda/envs/pytorch/lib/python3.6/site-packages/torch/nn/modules/module.py", line 476, in load_state_dict
    for name, param in state_dict.items():
AttributeError: 'function' object has no attribute 'items'

Can someone help point out what I’m doing wrong?

2 Likes

model.state_dict is a function, so very likely you want to call it as model.state_dict().

Best regards

Thomas

2 Likes

Ahh heck, yes I missed my parenthesis when I saved it. Good catch, thank you.

Are you able to tell me what’s actually in the file then? It is fullsize, so I figure the data is in there in somehow. Would there be a trick to load the model having saved it incorrectly?

The state dict is a pretty vanilla python structure, so you can assign it to a variable, print the keys with .keys () etc.
You can torch.load the file back to a variable - it should give you what you saved.

Best regards

Thomas

1 Like

Makes sense, thanks! Good tip.