# Using grad to calculate derivative of two outputs w.r.t. the same input

**URL:** <https://discuss.pytorch.org/t/using-grad-to-calculate-derivative-of-two-outputs-w-r-t-the-same-input/105882>\
**Category:** autograd\
**Created:** [December 11, 2020, 5:24pm UTC](https://discuss.pytorch.org/t/using-grad-to-calculate-derivative-of-two-outputs-w-r-t-the-same-input/105882 "2020-12-11T17:24:10Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![InnovArul](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/innovarul/32/5282_2.png) [@InnovArul](https://discuss.pytorch.org/u/InnovArul)\
**Post date:** [December 12, 2020, 4:22am UTC](https://discuss.pytorch.org/t/using-grad-to-calculate-derivative-of-two-outputs-w-r-t-the-same-input/105882/2 "2020-12-12T04:22:13Z")

</div>

Make sure to zero the gradients (`if x.grad: x.grad.zero_()`) before calculating new `y`.

Some more info:

> [@Why do we need to set the gradients manually to zero in pytorch?](https://discuss.pytorch.org/t/why-do-we-need-to-set-the-gradients-manually-to-zero-in-pytorch/4903/12):
>
> y.backward() doesn’t just assign the value of y’(x) to x.grad (say y depends on x). It actually adds y’(x) to the current value of x.grad (think it as x.grad += true\_gradient). In the following example, y.backward() is called 5 times, so the final value of x.grad will be 5\*cos(0)=5. import torch from torch.autograd import Variable x = Variable(torch.Tensor([[0]]), requires\_grad=True) for t in range(5): y = x.sin() y.backward() print(x.grad) # shows 5 Calling x.grad.data.zero\_…

---

_[View the full topic](https://discuss.pytorch.org/t/using-grad-to-calculate-derivative-of-two-outputs-w-r-t-the-same-input/105882)._
