import torch


def cwl2_lossf(logits, target, kappa=0):
    """
    Computes the non-norm portion of the C&W L_2 attack

    This is a direct translation of the formula on
    page 9 of the paper "Towards Evaluating the
    Robustness of Neural Networks"

    Args:
        logits (torch.Tensor): 2d torch tensor of output
            logit units of a model (no softmax should be
            applied to the model)

        target (float): the target class whose score
            should be increased

        kappa (float): the parameter kappa from the
            paper (see pg. 9 for details.)
    """
    mask = torch.ones_like(logits, dtype=torch.uint8)

    target_val = logits[:, target]
    non_targets = logits[mask]
    max_non_target = non_targets.max()

    return torch.clamp(max_non_target - target_val, min=-kappa)