I’m not deeply familiar with TF, but based on loss.stack() I assume the corresponding PyTorch code snippet might be:
losses = []
while condition:
    loss = calculate_loss(...)
    losses.append(loss)
losses = torch.stack(losses).mean()
losses.backward()