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.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_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_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)
    tmp8 = tl.load(in_ptr1 + r0, None)
    tmp1 = 0.25
    tmp2 = tmp0 * tmp1
    tmp3 = 1.0
    tmp4 = tmp3 - tmp0
    tmp5 = 0.75
    tmp6 = tmp4 * tmp5
    tmp7 = tmp2 + tmp6
    tmp9 = tmp4 * tmp8
    tmp10 = 0.0
    tmp11 = triton_helpers.minimum(tmp10, tmp8)
    tmp12 = tl_math.abs(tmp8)
    tmp13 = -tmp12
    tmp14 = tl_math.exp(tmp13)
    tmp15 = libdevice.log1p(tmp14)
    tmp16 = tmp11 - tmp15
    tmp17 = tmp9 - tmp16
    tmp18 = tl.sigmoid(tmp8)
    tmp19 = tmp18 * tmp0
    tmp20 = tmp3 - tmp18
    tmp21 = tmp20 * tmp4
    tmp22 = tmp19 + tmp21
    tmp23 = tmp3 - tmp22
    tmp24 = tmp23 * tmp23
    tmp25 = tmp17 * tmp24
    tmp26 = tmp7 * tmp25
    tmp27 = tl.broadcast_to(tmp26, [RBLOCK])
    tmp29 = triton_helpers.promote_to_tensor(tl.sum(tmp27, 0))
    tmp30 = 256.0
    tmp31 = tmp29 / tmp30
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp31, 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_mean_mul_pow_rsub_sigmoid_0[
            grid(1)](buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
    return buf1,


class FocalLossNew(nn.Module):
    """
    Softmax and sigmoid focal loss
    https://github.com/lonePatient/TorchBlocks/blob/master/torchblocks/losses/focal_loss.py
    """

    def __init__(self, num_labels, gamma=2.0, alpha=0.25, epsilon=1e-09,
        reduction='mean', activation_type='softmax'):
        super(FocalLossNew, self).__init__()
        self.num_labels = num_labels
        self.gamma = gamma
        self.alpha = alpha
        self.epsilon = epsilon
        self.activation_type = activation_type
        self.reduction = reduction

    def sigmoid_focal_loss(self, inputs: 'torch.Tensor', targets:
        'torch.Tensor') ->torch.Tensor:
        """
        https://github.com/facebookresearch/fvcore/blob/main/fvcore/nn/focal_loss.py
        Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
        Args:
            inputs: A float tensor of arbitrary shape.
                    The predictions for each example.
            targets: A float tensor with the same shape as inputs. Stores the binary
                    classification label for each element in inputs
                    (0 for the negative class and 1 for the positive class).
            alpha: (optional) Weighting factor in range (0,1) to balance
                    positive vs negative examples. Default = -1 (no weighting).
            gamma: Exponent of the modulating factor (1 - p_t) to
                balance easy vs hard examples.
            reduction: 'none' | 'mean' | 'sum'
                    'none': No reduction will be applied to the output.
                    'mean': The output will be averaged.
                    'sum': The output will be summed.
        Returns:
            Loss tensor with the reduction option applied.
        """
        inputs = inputs.float()
        targets = targets.float()
        p = torch.sigmoid(inputs)
        ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs,
            targets, reduction='none')
        p_t = p * targets + (1 - p) * (1 - targets)
        loss = ce_loss * (1 - p_t) ** self.gamma
        if self.alpha >= 0:
            alpha_t = self.alpha * targets + (1 - self.alpha) * (1 - targets)
            loss = alpha_t * loss
        if self.reduction == 'mean':
            loss = loss.mean()
        elif self.reduction == 'sum':
            loss = loss.sum()
        return loss

    def forward_old(self, preds, target):
        """
        Args:
            logits: model's output, shape of [batch_size, num_cls]
            target: ground truth labels, shape of [batch_size]
        Returns:
            shape of [batch_size]
        """
        if self.activation_type == 'softmax':
            idx = target.view(-1, 1).long()
            one_hot_key = torch.zeros(idx.size(0), self.num_labels, dtype=
                torch.float32, device=idx.device)
            one_hot_key = one_hot_key.scatter_(1, idx, 1)
            logits = torch.softmax(preds, dim=-1)
            loss = -self.alpha * one_hot_key * torch.pow(1 - logits, self.gamma
                ) * (logits + self.epsilon).log()
            loss = loss.sum(1)
        elif self.activation_type == 'sigmoid':
            multi_hot_key = target
            logits = torch.sigmoid(preds)
            zero_hot_key = 1 - multi_hot_key
            loss = -self.alpha * multi_hot_key * torch.pow(1 - logits, self
                .gamma) * (logits + self.epsilon).log()
            None
            loss += -(1 - self.alpha) * zero_hot_key * torch.pow(logits,
                self.gamma) * (1 - logits + self.epsilon).log()
            None
        if self.reduction == 'mean':
            loss = loss.mean()
        elif self.reduction == 'sum':
            loss = loss.sum()
        elif self.reduction == 'none':
            pass
        return loss

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