The error is raised, since the .grad attribute is set to None be default. The first backward() call populates the .grad attribute of all parameters used in the computation of the loss, which require gradients.
If you gut w.grad.zero_() after the loss.backward() call, the error should disappear.
Also, have a look at this example 1 to see how to manually update the parameters. E.g. in your example the torch.no_grad() guard is missing.