Attribute Error When Saving Pytorch Model
I want to save pytorch model in one .py file and use it in another .py file, but I get
AttributeError: 'function' object has no attribute 'copy'
Here is what I have:
train.py
data = {
    &quot;model_state&quot;: model.state_dict,
    &quot;optimizer_state&quot;: optimizer.state_dict,
    &quot;input_size&quot;: input_size,
    &quot;output_size&quot;: output_size,
    &quot;hidden_size&quot;: hidden_size,
    &quot;all_words&quot;: all_words,
    &quot;tags&quot;: tags
}
file = &quot;data.pth&quot;
torch.save(data, file)

use.py
file = &quot;data.pth&quot;
data = torch.load(file)
input_size = data['input_size']
output_size = data['output_size']
hidden_size = data['hidden_size']
all_words = data['all_words']
tags = data['tags']
model_state = data['model_state']

model = NeuralNet(input_size, hidden_size, output_size)
model.load_state_dict(model_state)
model.eval()

NeuralNet is a class I defined elsewhere for building a model. The error happens with the second to last line of use.py.

In fact, what you have done is save a function (AKA method in OOP) then load it in a variable utilizing deepcopy which is not available for functions!
The only change you need to make is adding () to state_dict. Let's assume this is the model
import copy
from torch import nn
import torch
class MyModel(nn.Module):
  def __init__(self):
    super().__init__()
    self.layer1=nn.Linear(10,4) 
    self.act1=nn.Sigmoid()
  
  def forward(self,x):
    x=self.layer1(x)
    x=self.act1(x)
    return x

type of state_dict vs type of state_dict():
print('Type With (): ', type(model.state_dict()), '\nType Without (): ', type(model.state_dict))
#Type With ():  &lt;class 'collections.OrderedDict'&gt; 
#Type Without ():  &lt;class 'method'&gt;

reproducing the error:
model = MyModel()
torch.save(model.state_dict, 'model_state.pth')
device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)
model.load_state_dict(copy.deepcopy(torch.load(&quot;model_state.pth&quot;,device)))
# AttributeError: 'function' object has no attribute 'copy'

the correct way:
model = MyModel()
torch.save(model.state_dict(), 'model_state.pth')
device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)
model.load_state_dict(copy.deepcopy(torch.load(&quot;model_state.pth&quot;,device)))

