Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch saving model UserWarning: Couldn't retrieve source code for container of type Network

When saving model in Pytorch by using:

torch.save(model, 'checkpoint.pth')

I get the following warning:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py:193: UserWarning: Couldn't retrieve source code for container of type Network. It won't be checked for correctness upon loading. "type " + obj.name + ". It won't be checked "

When I load it I get the following error:

state_dict = torch.load('checkpoint_state_dict.pth')
model = torch.load('checkpoint.pth')
model.load_state_dict(state_dict)


AttributeError                            Traceback (most recent call last)
<ipython-input-2-6a79854aef0f> in <module>()
      2 state_dict = torch.load('checkpoint_state_dict.pth')
      3 model = 0
----> 4 model = torch.load('checkpoint.pth')
      5 model.load_state_dict(state_dict)

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in load(f, map_location, pickle_module)
    301         f = open(f, 'rb')
    302     try:
--> 303         return _load(f, map_location, pickle_module)
    304     finally:
    305         if new_fd:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _load(f, map_location, pickle_module)
    467     unpickler = pickle_module.Unpickler(f)
    468     unpickler.persistent_load = persistent_load
--> 469     result = unpickler.load()
    470 
    471     deserialized_storage_keys = pickle_module.load(f)

AttributeError: Can't get attribute 'Network' on <module '__main__'>

Why is not possible to save a model and reload it entirely?

like image 689
Dario Federici Avatar asked Sep 11 '18 13:09

Dario Federici


1 Answers

Saving

torch.save({'state_dict': model.state_dict()}, 'checkpoint.pth.tar')

Loading

model = describe_model()
checkpoint = torch.load('checkpoint.pth.tar')
model.load_state_dict(checkpoint['state_dict'])
like image 195
Salih Karagoz Avatar answered Nov 15 '22 14:11

Salih Karagoz