import torch


def TotalLogLoss(predicted, labels):
    """
        Take the binary log loss for each predicted label and sum them.
        This results in the equivalent of training multiple binary classifiers, a useful formulation
        for our multi-label problem.
    """

    labels = labels.bool()  # for logical indexing

    # take complement of classes that are not present,
    # in a way that maintains the computation graph

    subtracted_from = (~labels).float()
    sign_indicator = labels.float() * 2 - 1  # [0,1] -> [-1, 1]
    signed = sign_indicator * predicted
    complemented = subtracted_from + signed

    # take negative log and sum
    negative_log = -torch.log(complemented)

    return negative_log.sum()