Error loading saved model

I have a model:

cnn=CNN(), ‘./model/’)

model = torch.load(’./model/’)

AttributeError: Can’t get attribute ‘CNN’ on <module ‘main’>

why am I getting this error and how to solve it?

I was having the similar error before.
How I solved it by copying the code of CNN class to the same file that load the model.
I think some hows the namespace is hard code when you save the model.
So then it can’t search when you load the model again.


Thanks @russellwmy. It worked :slight_smile:

Good, But the way to solve it is … so bad :sweat_smile:


Thank you @russellwmy .Anyone found any other way?

1 Like

Hi, I also have this problem and figure it out and just wanna post my solution here in case it helps anyone.

I read somewhere that Pytorch use Pickle to take care of the save/load model, the problem is really about Pickle, not Pytorch itself.

The solution is really simple, you just have to explicitly import the class definition. It’s equivalent to copy and paste the class definition.

In my case I have the following directory structure:


In, I make sure ./Release-code/ is in python path, and I just have to say

from myclass import class_definition

then torch.load(model_name) works

If your class_definition calls other classes, you also need to import them too.

This thread explains the problem and solutions for it:


I experienced the same error, simply re-running the cell in which your class is defined will do the trick if doing in jupyter notebook

it says:
The disadvantage of Save/Load Entire Model is that the serialized data is bound to the specific classes and the exact directory structure used when the model is saved. The reason for this is because pickle does not save the model class itself.
and there is no other way:(

1 Like