import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda


@triton.jit
def triton_poi_fused_add_log_mul_pow_rsub_sigmoid_squeeze_sub_0(in_ptr0,
    in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 1024
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex % 256
    x0 = xindex % 64
    x2 = xindex // 256
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp1 = tl.sigmoid(tmp0)
    tmp2 = 1.0
    tmp3 = tmp2 - tmp1
    tmp4 = tmp3 * tmp3
    tmp5 = -4.0
    tmp6 = tmp4 * tmp5
    tmp8 = tmp6 * tmp7
    tmp9 = 1e-08
    tmp10 = tmp1 + tmp9
    tmp11 = tl_math.log(tmp10)
    tmp12 = tmp8 * tmp11
    tmp13 = tmp1 * tmp1
    tmp14 = -3.0
    tmp15 = tmp13 * tmp14
    tmp16 = tmp2 - tmp7
    tmp17 = tmp15 * tmp16
    tmp18 = tmp3 + tmp9
    tmp19 = tl_math.log(tmp18)
    tmp20 = tmp17 * tmp19
    tmp21 = tmp12 - tmp20
    tl.store(out_ptr0 + x4, tmp21, xmask)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
            torch.float32)
        get_raw_stream(0)
        triton_poi_fused_add_log_mul_pow_rsub_sigmoid_squeeze_sub_0[grid(1024)
            ](arg0_1, arg1_1, buf0, 1024, XBLOCK=256, num_warps=4, num_stages=1
            )
        del arg0_1
        del arg1_1
    return buf0,


def binary_focal_loss_with_logits(input: 'torch.Tensor', target:
    'torch.Tensor', alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
    'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
    """Function that computes Binary Focal loss.

    .. math::

        \\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)

    where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        input (torch.Tensor): input data tensor with shape :math:`(N, 1, *)`.
        target (torch.Tensor): the target tensor with shape :math:`(N, 1, *)`.
        alpha (float): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`. Default: 0.25.
        gamma (float): Focusing parameter :math:`\\gamma >= 0`. Default: 2.0.
        reduction (str, optional): Specifies the reduction to apply to the. Default: 'none'.
        eps (float): for numerically stability when dividing. Default: 1e-8.

    Returns:
        torch.tensor: the computed loss.

    Examples:
        >>> num_classes = 1
        >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
        >>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])
        >>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
        >>> binary_focal_loss_with_logits(logits, labels, **kwargs)
        tensor(4.6052)
    """
    if not isinstance(input, torch.Tensor):
        raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
            type(input)))
    if not len(input.shape) >= 2:
        raise ValueError('Invalid input shape, we expect BxCx*. Got: {}'.
            format(input.shape))
    if input.size(0) != target.size(0):
        raise ValueError(
            'Expected input batch_size ({}) to match target batch_size ({}).'
            .format(input.size(0), target.size(0)))
    probs = torch.sigmoid(input)
    target = target.unsqueeze(dim=1)
    loss_tmp = -alpha * torch.pow(1.0 - probs, gamma) * target * torch.log(
        probs + eps) - (1 - alpha) * torch.pow(probs, gamma) * (1.0 - target
        ) * torch.log(1.0 - probs + eps)
    loss_tmp = loss_tmp.squeeze(dim=1)
    if reduction == 'none':
        loss = loss_tmp
    elif reduction == 'mean':
        loss = torch.mean(loss_tmp)
    elif reduction == 'sum':
        loss = torch.sum(loss_tmp)
    else:
        raise NotImplementedError('Invalid reduction mode: {}'.format(
            reduction))
    return loss


class BinaryFocalLossWithLogitsNew(nn.Module):
    """Criterion that computes Focal loss.

    According to :cite:`lin2017focal`, the Focal loss is computed as follows:

    .. math::

        \\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)

    where:
       - :math:`p_t` is the model's estimated probability for each class.

    Args:
        alpha (float): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
        gamma (float): Focusing parameter :math:`\\gamma >= 0`.
        reduction (str, optional): Specifies the reduction to apply to the
         output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied,
         ‘mean’: the sum of the output will be divided by the number of elements
         in the output, ‘sum’: the output will be summed. Default: ‘none’.

    Shape:
        - Input: :math:`(N, 1, *)`.
        - Target: :math:`(N, 1, *)`.

    Examples:
        >>> N = 1  # num_classes
        >>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
        >>> loss = BinaryFocalLossWithLogits(**kwargs)
        >>> input = torch.randn(1, N, 3, 5, requires_grad=True)
        >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
        >>> output = loss(input, target)
        >>> output.backward()
    """

    def __init__(self, alpha: 'float', gamma: 'float'=2.0, reduction: 'str'
        ='none') ->None:
        super(BinaryFocalLossWithLogitsNew, self).__init__()
        self.alpha: 'float' = alpha
        self.gamma: 'float' = gamma
        self.reduction: 'str' = reduction
        self.eps: 'float' = 1e-08

    def forward(self, input_0, input_1):
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1])
        return output[0]


Measured latency_ms: 0.014837