import torch
def model(x, W, b):
return x@W + b
def mse(t1, t2):
diff = t1 - t2
return torch.sum(diff * diff) / diff.numel()
inputs = torch.rand(2, 3, requires_grad=True)
targets = torch.rand( 2,2, requires_grad=True)
W = torch.rand(3, 2, requires_grad=True)
b = torch.rand(2, requires_grad=True)
pred = model(inputs, W, b)
loss = mse(pred, targets)
loss.backward()
print(W.grad)
print(b.grad)
with torch.no_grad():
W -= W.grad * 1e-5
b -= b.grad * 1e-5
print(W.grad)
print(b.grad)
For the above example, the output of the last 2 print statements is the same as that of the first two print statements.
But, for the code snippet below, the 2 last print statements give result as None.
I can't understand why it is so?
print(W.grad)
print(b.grad)
with torch.no_grad():
W = W - W.grad * 1e-5
b = b - b.grad * 1e-5
print(W.grad)
print(b.grad)