import torch


def _safe_mean(losses, num_present):
    """Computes a safe mean of the losses.
    Args:
    losses: `Tensor` whose elements contain individual loss measurements.
    num_present: The number of measurable elements in `losses`.
    Returns:
    A scalar representing the mean of `losses`. If `num_present` is zero,
      then zero is returned.
    """
    total_loss = torch.sum(losses)
    if num_present == 0:
        return 0 * total_loss
    else:
        return torch.div(total_loss, num_present)