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 libdevice, math as tl_math
import torch.jit
import torch.nn.functional as F
import torch.nn.functional
from functools import partial
from torch.nn.modules.loss import _Loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda


@triton.jit
def triton_per_fused_add_binary_cross_entropy_with_logits_exp_mean_mul_neg_pow_rsub_0(
    in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
    XBLOCK: tl.constexpr = 1
    RBLOCK: tl.constexpr = 256
    xoffset = tl.program_id(0) * XBLOCK
    tl.full([1], xoffset, tl.int32)
    tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    tl.full([RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp3 = tl.load(in_ptr1 + r0, None)
    tmp1 = 1.0
    tmp2 = tmp1 - tmp0
    tmp4 = tmp2 * tmp3
    tmp5 = 0.0
    tmp6 = triton_helpers.minimum(tmp5, tmp3)
    tmp7 = tl_math.abs(tmp3)
    tmp8 = -tmp7
    tmp9 = tl_math.exp(tmp8)
    tmp10 = libdevice.log1p(tmp9)
    tmp11 = tmp6 - tmp10
    tmp12 = tmp4 - tmp11
    tmp13 = -tmp12
    tmp14 = tl_math.exp(tmp13)
    tmp15 = tmp1 - tmp14
    tmp16 = tmp15 * tmp15
    tmp17 = -tmp16
    tmp18 = tmp17 * tmp13
    tmp19 = 0.25
    tmp20 = tmp0 * tmp19
    tmp21 = 0.75
    tmp22 = tmp2 * tmp21
    tmp23 = tmp20 + tmp22
    tmp24 = tmp18 * tmp23
    tmp25 = tl.broadcast_to(tmp24, [RBLOCK])
    tmp27 = triton_helpers.promote_to_tensor(tl.sum(tmp25, 0))
    tmp28 = 256.0
    tmp29 = tmp27 / tmp28
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp29, None)


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((), (), torch.float32)
        buf1 = buf0
        del buf0
        get_raw_stream(0)
        triton_per_fused_add_binary_cross_entropy_with_logits_exp_mean_mul_neg_pow_rsub_0[
            grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
    return buf1,


def reduced_focal_loss(outputs: 'torch.Tensor', targets: 'torch.Tensor',
    threshold: 'float'=0.5, gamma: 'float'=2.0, reduction='mean'):
    """
    Compute reduced focal loss between target and output logits.
    Source https://github.com/BloodAxe/pytorch-toolbelt
    See :class:`~pytorch_toolbelt.losses` for details.
    Args:
        outputs: Tensor of arbitrary shape
        targets: Tensor of the same shape as input
        reduction (string, optional):
            Specifies the reduction to apply to the output:
            "none" | "mean" | "sum" | "batchwise_mean".
            "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.
            Note: :attr:`size_average` and :attr:`reduce`
            are in the process of being deprecated,
            and in the meantime, specifying either of those two args
            will override :attr:`reduction`.
            "batchwise_mean" computes mean loss per sample in batch.
            Default: "mean"
    See https://arxiv.org/abs/1903.01347
    """
    targets = targets.type(outputs.type())
    logpt = -F.binary_cross_entropy_with_logits(outputs, targets, reduction
        ='none')
    pt = torch.exp(logpt)
    focal_reduction = ((1.0 - pt) / threshold).pow(gamma)
    focal_reduction[pt < threshold] = 1
    loss = -focal_reduction * logpt
    if reduction == 'mean':
        loss = loss.mean()
    if reduction == 'sum':
        loss = loss.sum()
    if reduction == 'batchwise_mean':
        loss = loss.sum(0)
    return loss


def sigmoid_focal_loss(outputs: 'torch.Tensor', targets: 'torch.Tensor',
    gamma: 'float'=2.0, alpha: 'float'=0.25, reduction: 'str'='mean'):
    """
    Compute binary focal loss between target and output logits.
    Source https://github.com/BloodAxe/pytorch-toolbelt
    See :class:`~pytorch_toolbelt.losses` for details.
    Args:
        outputs: Tensor of arbitrary shape
        targets: Tensor of the same shape as input
        reduction (string, optional):
            Specifies the reduction to apply to the output:
            "none" | "mean" | "sum" | "batchwise_mean".
            "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.
    See https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/loss/losses.py  # noqa: E501
    """
    targets = targets.type(outputs.type())
    logpt = -F.binary_cross_entropy_with_logits(outputs, targets, reduction
        ='none')
    pt = torch.exp(logpt)
    loss = -(1 - pt).pow(gamma) * logpt
    if alpha is not None:
        loss = loss * (alpha * targets + (1 - alpha) * (1 - targets))
    if reduction == 'mean':
        loss = loss.mean()
    if reduction == 'sum':
        loss = loss.sum()
    if reduction == 'batchwise_mean':
        loss = loss.sum(0)
    return loss


class FocalLossBinaryNew(_Loss):

    def __init__(self, ignore: 'int'=None, reduced: 'bool'=False, gamma:
        'float'=2.0, alpha: 'float'=0.25, threshold: 'float'=0.5, reduction:
        'str'='mean'):
        """
        Compute focal loss for binary classification problem.
        """
        super().__init__()
        self.ignore = ignore
        if reduced:
            self.loss_fn = partial(reduced_focal_loss, gamma=gamma,
                threshold=threshold, reduction=reduction)
        else:
            self.loss_fn = partial(sigmoid_focal_loss, gamma=gamma, alpha=
                alpha, reduction=reduction)

    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.015012