Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
def gradient_at(value, repeat=False):
x = torch.tensor(float(value), requires_grad=True)
(x ** 2).backward()
if repeat:
x.grad = None
(x ** 2).backward()
return x.grad.item()- Reasoning
- The helper differentiates the scalar square function and optionally repeats an independent computation. Before the second backward call it clears the leaf gradient, and it constructs a fresh square expression rather than reusing a freed graph.