I am trying to use the gradient of a network with respect to its inputs as part of my loss function. However, whenever I try to calculate it, the training proceeds but the weights do not update
import torch
import torch.optim as optim
import torch.autograd as autograd
ic = torch.rand((25, 3))
ic = torch.tensor(ic, requires_grad=True)
optimizer = optim.RMSprop([ic], lr=1e-2)
for itr in range(1, 50):
optimizer.zero_grad()
sol = torch.tanh(.5*torch.stack(100*[ic])) # simplified for minimal working example
dx = sol[-1, :, 0]
dxdxy, = autograd.grad(dx,
inputs=ic,
grad_outputs = torch.ones(ic.shape[0]), # batchwise
retain_graph=True
)
dxdxy = torch.tensor(dxdxy, requires_grad=True)
loss = torch.sum(dxdxy)
loss.backward()
optimizer.step()
if itr % 5 == 0:
print(loss)
What am I doing wrong?