Your code snippet doesn’t include a tensor with requires_grad=True in the loss calculation.
This would make the code work:
pred = torch.rand((b, num_class, h, w), dtype=torch.float, requires_grad=True)