Search code examples
pythondeep-learningpytorchtorch

Pytorch: AttributeError: 'function' object has no attribute 'copy'


I am trying to load a model state_dict I trained on Google Colab GPU, here is my code to load the model:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

model = models.resnet50()
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, n_classes)
model.load_state_dict(copy.deepcopy(torch.load("./models/model.pth",device)))
model = model.to(device)
model.eval()

Here is the error:

state_dict = state_dict.copy()

AttributeError: 'function' object has no attribute 'copy'

Pytorch :

>>> import torch
>>> print (torch.__version__)
1.4.0
>>> import torchvision
>>> print (torchvision.__version__)
0.5.0

Please help I have searched everywhere to no avail

[full error details][1] https://i.sstatic.net/s22DL.png


Solution

  • I am guessing this is what you did by mistake. You saved the function

    torch.save(model.state_dict, 'model_state.pth')

    instead of the state_dict()

    torch.save(model.state_dict(), 'model_state.pth')

    Otherwise, everything should work as expected. (I tested the following code on Colab)

    Replace model.state_dict() with model.state_dict to reproduce error

    import copy
    model = TheModelClass()
    torch.save(model.state_dict(), 'model_state.pth')
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model.load_state_dict(copy.deepcopy(torch.load("model_state.pth",device)))