I have tried to recreate the error that I get for a code in this simple code snippet.
Why does the following code throw an error?
If you run this code, it will run into an error the second time it goes into the training loop on line 18 (“self.matrix2 = result”) that “TypeError: cannot assign ‘torch.FloatTensor’ as parameter ‘matrix2’ (torch.nn.Parameter or None expected)”. My issue is that when the code enters the if block, we are already sure that self.matrix2 is None. So why is this error happening?
Solving the error is simple and it can be done by simply using the commented line in the function miniBatchStep. My issue is just I don’t completely get why this error is happening.
import torch
import torch.nn as nn
def func(vv):
uu = [vv[:, 0:1], vv[:, 1:2]]
return torch.hstack(uu)
class Test(nn.Module):
def __init__(self):
super(Test, self).__init__()
self.matrix = nn.Parameter(torch.randn(2, 2), requires_grad=True)
self.matrix2 = None
def getModifiedParam(self):
if self.matrix2 is None:
result = func(self.matrix)
self.matrix2 = result
return self.matrix2
def forward(self, x):
return x @ self.getModifiedParam()
def miniBatchStep(self):
self.matrix2 = None
with torch.no_grad():
self.matrix.data = self.getModifiedParam()
self.matrix2 = self.matrix
# self.matrix2 = self.matrix.clone()
def main():
net = Test()
optimizer = torch.optim.Adam(net.parameters(), lr=0.1)
for _ in range(2):
x = torch.randn(2, 2)
net(x).sum().backward()
optimizer.step()
with torch.no_grad():
optimizer.zero_grad()
net.miniBatchStep()
if __name__ == "__main__":
main()
I have got the error on python 3.11.3 and torch 2.2.1 on mac, and python 3.8.10 and torch 2.1.2+cu118 on ubuntu 20.04.4 LTS.