The error is raised if you call .backward() on a tensor, which is not a scalar.
In that case you should either reduce the tensor before (e.g. via tensor.mean()) or pass the gradients to backward (e.g. via tensor.backward(torch.ones_like(tensor))).
You can access the gradients after the backward() call by accessing them directly, e.g.:
print(model.layer.weight.grad)