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 import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp3 = triton_helpers.maximum(tmp1, tmp2)
    tmp5 = triton_helpers.maximum(tmp3, tmp4)
    tmp7 = triton_helpers.maximum(tmp5, tmp6)
    tmp8 = tmp0 - tmp7
    tmp9 = tl_math.exp(tmp8)
    tl.store(out_ptr0 + x3, tmp9, xmask)


@triton.jit
def triton_poi_fused__softmax_add_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp3 = tmp1 + tmp2
    tmp5 = tmp3 + tmp4
    tmp7 = tmp5 + tmp6
    tmp8 = tmp0 / tmp7
    tmp9 = 1e-06
    tmp10 = tmp8 + tmp9
    tl.store(out_ptr0 + x3, tmp10, xmask)


@triton.jit
def triton_poi_fused_add_log_mul_neg_pow_sum_2(in_ptr0, in_ptr1, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 16
    x1 = xindex // 16
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
    tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
    tmp11 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
    tmp12 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
    tmp21 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
    tmp22 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
    tmp31 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
    tmp32 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
    tmp2 = -tmp1
    tmp3 = 1.0
    tmp4 = tmp2 + tmp3
    tmp5 = tmp4 * tmp4
    tmp6 = -1.0
    tmp7 = tmp5 * tmp6
    tmp8 = tl_math.log(tmp1)
    tmp9 = tmp7 * tmp8
    tmp10 = tmp0 * tmp9
    tmp13 = -tmp12
    tmp14 = tmp13 + tmp3
    tmp15 = tmp14 * tmp14
    tmp16 = tmp15 * tmp6
    tmp17 = tl_math.log(tmp12)
    tmp18 = tmp16 * tmp17
    tmp19 = tmp11 * tmp18
    tmp20 = tmp10 + tmp19
    tmp23 = -tmp22
    tmp24 = tmp23 + tmp3
    tmp25 = tmp24 * tmp24
    tmp26 = tmp25 * tmp6
    tmp27 = tl_math.log(tmp22)
    tmp28 = tmp26 * tmp27
    tmp29 = tmp21 * tmp28
    tmp30 = tmp20 + tmp29
    tmp33 = -tmp32
    tmp34 = tmp33 + tmp3
    tmp35 = tmp34 * tmp34
    tmp36 = tmp35 * tmp6
    tmp37 = tl_math.log(tmp32)
    tmp38 = tmp36 * tmp37
    tmp39 = tmp31 * tmp38
    tmp40 = tmp30 + tmp39
    tl.store(out_ptr0 + x2, tmp40, xmask)


@triton.jit
def triton_poi_fused_mul_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 16
    x2 = xindex // 64
    x3 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
        'evict_last')
    tmp1 = tl.load(in_ptr1 + x3, xmask)
    tmp2 = tmp0 * tmp1
    tl.store(out_ptr0 + x3, tmp2, xmask)


def call(args):
    arg0_1, arg1_1, arg2_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))
    assert_size_stride(arg2_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), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
            256, num_warps=4, num_stages=1)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused__softmax_add_1[grid(256)](buf0, buf1, 256, XBLOCK=
            128, num_warps=4, num_stages=1)
        del buf0
        buf2 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
        triton_poi_fused_add_log_mul_neg_pow_sum_2[grid(64)](arg1_1, buf1,
            buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
        del arg1_1
        buf3 = buf1
        del buf1
        triton_poi_fused_mul_3[grid(256)](buf2, arg2_1, buf3, 256, XBLOCK=
            128, num_warps=4, num_stages=1)
        del arg2_1
        del buf2
    return buf3,


class SoftmaxFocalClassificationLossNew(nn.Module):
    """Criterion that computes Focal loss.
    According to [1], 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.
    Arguments:
        alpha (float): Weighting factor :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, C, *)` where C = number of classes.
        - Target: :math:`(N, *)` where each value is
          :math:`0 ≤ targets[i] ≤ C−1`.
    Examples:
        >>> N = 5  # num_classes
        >>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
        >>> loss = kornia.losses.FocalLoss(**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()
    References:
        [1] https://arxiv.org/abs/1708.02002
    """

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

    def focal_loss(self, input: 'torch.Tensor', target: 'torch.Tensor',
        weights: 'torch.Tensor', alpha: 'float'=1.0, gamma: 'float'=2.0,
        reduction: 'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
        """Function that computes Focal loss.
        See :class:`~kornia.losses.FocalLoss` for details.
        """
        if not torch.is_tensor(input):
            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)))
        if not input.device == target.device:
            raise ValueError(
                'input and target must be in the same device. Got: {} and {}'
                .format(input.device, target.device))
        input_soft: 'torch.Tensor' = F.softmax(input, dim=1) + eps
        weight = torch.pow(-input_soft + 1.0, gamma)
        focal = -alpha * weight * torch.log(input_soft)
        loss_tmp = torch.sum(target * focal, dim=1, keepdims=True)
        if weights is None:
            return loss_tmp
        return loss_tmp * weights

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


Measured latency_ms: 0.051166