Hi,
I guess you have two options:
either you do the backward only when it happened:
total_loss = 0.
# You code
if torch.is_tensor(total_loss):
    total_loss.backward()

Or create it with requires grad all the time.
total_loss = torch.tensor([0.0], requires_grad=True)
# You code
total_loss.backward() # This will always work now.