Did you somehow manipulate the forward method of your model, since your code works fine on my machine using random input:
output = model(torch.randn(1, 3, 224, 224))
output.mean().backward()
optimizer.step()