Search code examples
pythonneural-networkpytorchgradient-descentautograd

autograd differentiation example in PyTorch - should be 9/8?


In the example for the Torch tutorial for Python, they use the following graph:

x = [[1, 1], [1, 1]]
y = x + 2
z = 3y^2
o = mean( z )  # 1/4 * x.sum()

Thus, the forward pass gets us this:

x_i = 1, y_i = 3, z_i = 27, o = 27

In code this looks like:

import torch

# define graph
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()

# if we don't do this, torch will only retain gradients for leaf nodes, ie: x
y.retain_grad()
z.retain_grad()

# does a forward pass
print(z, out)

however, I get confused at the gradients computed:

# now let's run our backward prop & get gradients
out.backward()
print(f'do/dz = {z.grad[0,0]}')

which outputs:

do/dx = 4.5

By chain rule, do/dx = do/dz * dz/dy * dy/dx, where:

dy/dx = 1
dz/dy = 9/2 given x_i=1
do/dz = 1/4 given x_i=1

which means:

do/dx = 1/4 * 9/2 * 1 = 9/8

However this doesn't match the gradients returned by Torch (9/2 = 4.5). Perhaps I have a math error (something with the do/dz = 1/4 term?), or I don't understand autograd in Torch.

Any pointers?


Solution

  • do/dz = 1 / 4
    dz/dy = 6y = 6 * 3 = 18
    dy/dx = 1
    

    therefore, do/dx = 9/2