Thanks, @ptrblck.
I’m doing the test in a Jupyter notebook via vscode. I’m not sure why I don’t get the warning message you pointed out.
Anyway, adding y.retain_grad() does work in this case as you suggested:
x = torch.tensor(0.3, requires_grad=True)
print(x)
# [output] tensor(0.3000, requires_grad=True)

y = x * x
print(y)
# [output] tensor(0.0900, grad_fn=<MulBackward0>)

y.retain_grad()

z = 2 * y
print(z)
# [output] tensor(0.1800, grad_fn=<MulBackward0>)

z.backward()

print(y.grad)
# [output] tensor(2.)

print(x.grad)
# [output] tensor(1.2000)