import torch


def weighted_binary_cross_entropy_with_logits(logits, labels, weights):
    """
    assume N samples
    :param logits: (N, 2)  unnormalized foreground/background score
    :param labels: (N, )   {0, 1}
    :param weights: (N, )  float \in [0,1] for rareness
    :return: float loss
    """
    loss = logits.clamp(min=0) - logits*labels + torch.log(1 + torch.exp(-logits.abs()))
    loss = (weights*loss).sum()/(weights.sum()+1e-12)
    return loss