Your sample function might return invalid outputs.
torch.rand samples from [0, 1) and if you sample a zero in it, torch.log would return -Inf.
Try to add a small eps value to this operation or check other operations, which could potentially output an invalid value.