Env
import torch
x = torch.arange(4.0) x.requires_grad_(True)// x=torch.arange(4.0, requires_grad=True)
\( y = 2\mathbf{x}^\top\mathbf{x} \)
y = 2 * torch.dot(x, x)
\( \nabla_{\mathbf{x}} \mathbf{x}^\top\mathbf{x} = 2\mathbf{x} \)
\( \nabla_{\mathbf{x}} y = \nabla_{\mathbf{x}} (2\mathbf{x}^\top\mathbf{x}) = 2 \times \nabla_{\mathbf{x}} (\mathbf{x}^\top\mathbf{x}) = 2 \times 2\mathbf{x} = 4\mathbf{x} \)
\( \frac{\partial y}{\partial x_i} = 4x_i \)
y.backward()
Clean grad
x.grad.zero_()