How Pytorch tensors’ backward() accumulates gradient

I was not sure what “accumulated” mean exactly for the behavior of pytorch tensors'backward() method and .grad attribute mentioned here:

torch.Tensor is the central class of the package. If you set its attribute .requires_grad as True, it starts to track all operations on it. When you finish your computation you can call .backward() and have all the gradients computed automatically. The gradient for this tensor will be accumulated into .grad attribute.

Here’s some code to illustrate. Define an input tensor x with value 1 and tell pytorch that I want it to track the gradients of x.

Output:

Define two tensors y and z that depends on x.

See how x.grad is accumulated from y.backward() then z.backward() : first 2 then 5 = 2 + 3, where 2 comes from dy/dx=2x=2 (evaluated at x=1)and 3 comes from dz/dx=3x**2=3 (evaluated at x=1).

Output:

Run:

(Note 5 = 2 + 3.) Output:

Can switch y.backward() and z.backward(). Now first 3 then 5 = 3 + 2.

Output:

Run:

Output:

Can set x.grad back to 0 after y.backward() so that it does not accumulate.

Output:

Run:

Output:

Run:

Output:

Can also look at a vectorized version (y below is a vector instead of separate y and z)

vector version

Run:

Output:

Run:

Cumulative grad of x[0] and x[1] respectively.

Run:

Output:

Now manually calculate the gradient and compare. Run:

Output:

Run:

Output: (compare the gradient from pytorch above)

Code is here: http://nbviewer.jupyter.org/github/yang-zhang/yang-zhang.github.io/blob/master/ds_code/pytorch_grad_accum.ipynb

--

--

Software Engineering SMTS at Salesforce Commerce Cloud Einstein

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yang Zhang

Software Engineering SMTS at Salesforce Commerce Cloud Einstein