inp = torch.eye(5,requires_grad=True)
out = (inp+1).pow(2)
out.backward(torch.ones_like(inp), retain_graph=True)
print(f"First call\n{inp.grad}")
torch.ones_like(inp)
will create a tensor in the same shape and dtype
, device
, and layout
as inp
filled with 1
s and is used as the gradient
argument to the backward
call.