I tried to store the state dict of my model in a variable temporarily and wanted to restore it to my model later, but the content of this variable changed automatically as the model updated.
There is a minimal example:
import torch as t
import torch.nn as nn
from torch.optim import Adam
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc = nn.Linear(3, 2)
def forward(self, x):
return self.fc(x)
net = Net()
loss_fc = nn.MSELoss()
optimizer = Adam(net.parameters())
weights = net.state_dict()
print(weights)
x = t.rand((5, 3))
y = t.rand((5, 2))
loss = loss_fc(net(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(weights)
I thought the two outputs would be the same, but I got (outputs may change due to random initialization)
OrderedDict([('fc.weight', tensor([[-0.5557, 0.0544, -0.2277],
[-0.0793, 0.4334, -0.1548]])), ('fc.bias', tensor([-0.2204, 0.2846]))])
OrderedDict([('fc.weight', tensor([[-0.5547, 0.0554, -0.2267],
[-0.0783, 0.4344, -0.1538]])), ('fc.bias', tensor([-0.2194, 0.2856]))])
The content of weights changed, which is so weird.
I also tried .copy() and t.no_grad() as following, but they did not help.
with t.no_grad():
weights = net.state_dict().copy()
Yes, I know that I can save state dict using t.save(), but I just want to figure out what happened in the previous example.
I'm using Python 3.8.5 and Pytorch 1.8.1
Thanks for any help.