Each time you do something.backward() the gradients are added to the gradients stored in param.grad for each parameter.
So you can do
loss1.backward(retain_graph=True)
loss2.backward()
optimizer.step() # uses combined gradients from both losses