Premium problem78. Gradient Accumulation

Medium Locked

Let x be a scalar tensor holding value with requires_grad=True. Call backward() on loss1 = x**2 and then on loss2 = 3*x, without clearing x.grad in between.

Return the accumulated x.grad, which is 2*value + 3.

.backward() adds into .grad rather than replacing it. That is why training loops call optimizer.zero_grad(), and why forgetting to is such a common bug.

Input

2.0

Output

tensor(7.)

Premium problem

This one's part of Premium. Unlock the full PyTorch track plus every other premium problem on the site.

Implement solve(...)