A set of data, sum() as the dividend, how to find grad

Hi,guys,
A set of data, sum() as the dividend, how to find grad.code like this:

x = torch.tensor([1.,2.,3.],requires_grad=True)
sum = x.sum()
y = x**2/sum
z = y[1]
z.sum().backward()
print(x.grad)

tensor([-0.1111,  0.5556, -0.1111])

x1 = torch.tensor([1.,2.,3.],requires_grad=True)
sum1 = x1.sum()
y1 = x1**2/sum1
z1 = y1
z1.sum().backward()
print(x1.grad)

tensor([-0.0556,  0.2778,  0.6111])

Any answer or idea will be appreciated!

I know how to get the first code array[1] grad,is 0.5556
it is sum = 6 sum’ = 1
so
uv/w = (u’w-uw’)/(w * * 2) =( 2 * 2 * 6-2 * * 2)/(6 * 6) = 0.5556
but others no index i don’t know

I tried to answer in a gist, as it involves math expressions.
Hopefully, it helps.

1 Like

I see, thank you very much