---
title: "Automatic Differentiation"
jupyter: python3
---

Automatic differentiation evaluates derivatives by applying local rules along a recorded computation graph.

```{python}
import torch

x = torch.tensor(2.0, requires_grad=True)
y = (x**3 + 2 * x) ** 2
y.backward()
analytical = 2 * (x.detach() ** 3 + 2 * x.detach()) * (3 * x.detach() ** 2 + 2)
assert torch.allclose(x.grad, analytical)
print(f"gradient={x.grad.item():.1f}")
```
