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.functional as F
import torch.nn as nn
import torch._C
import torch.serialization
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_binary_cross_entropy_mean_0(in_ptr0, in_ptr1, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
    tmp3 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
    tmp1 = 1.0
    tmp2 = tmp0 - tmp1
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = -tmp4
    tmp6 = libdevice.log1p(tmp5)
    tmp7 = -100.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tmp2 * tmp8
    tmp10 = tl_math.log(tmp4)
    tmp11 = triton_helpers.maximum(tmp10, tmp7)
    tmp12 = tmp0 * tmp11
    tmp13 = tmp9 - tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp17, xmask)


@triton.jit
def triton_per_fused_binary_cross_entropy_mean_1(in_ptr0, in_ptr1, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (16 + r1 + 64 * x0), xmask, other=0.0)
    tmp3 = tl.load(in_ptr1 + (16 + r1 + 64 * x0), xmask, other=0.0)
    tmp1 = 1.0
    tmp2 = tmp0 - tmp1
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = -tmp4
    tmp6 = libdevice.log1p(tmp5)
    tmp7 = -100.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tmp2 * tmp8
    tmp10 = tl_math.log(tmp4)
    tmp11 = triton_helpers.maximum(tmp10, tmp7)
    tmp12 = tmp0 * tmp11
    tmp13 = tmp9 - tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp17, xmask)


@triton.jit
def triton_per_fused_binary_cross_entropy_mean_2(in_ptr0, in_ptr1, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (32 + r1 + 64 * x0), xmask, other=0.0)
    tmp3 = tl.load(in_ptr1 + (32 + r1 + 64 * x0), xmask, other=0.0)
    tmp1 = 1.0
    tmp2 = tmp0 - tmp1
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = -tmp4
    tmp6 = libdevice.log1p(tmp5)
    tmp7 = -100.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tmp2 * tmp8
    tmp10 = tl_math.log(tmp4)
    tmp11 = triton_helpers.maximum(tmp10, tmp7)
    tmp12 = tmp0 * tmp11
    tmp13 = tmp9 - tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp17, xmask)


@triton.jit
def triton_per_fused_binary_cross_entropy_mean_3(in_ptr0, in_ptr1, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (48 + r1 + 64 * x0), xmask, other=0.0)
    tmp3 = tl.load(in_ptr1 + (48 + r1 + 64 * x0), xmask, other=0.0)
    tmp1 = 1.0
    tmp2 = tmp0 - tmp1
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = -tmp4
    tmp6 = libdevice.log1p(tmp5)
    tmp7 = -100.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tmp2 * tmp8
    tmp10 = tl_math.log(tmp4)
    tmp11 = triton_helpers.maximum(tmp10, tmp7)
    tmp12 = tmp0 * tmp11
    tmp13 = tmp9 - tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp17, xmask)


@triton.jit
def triton_per_fused_add_binary_cross_entropy_div_mean_mul_4(in_out_ptr0,
    in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 4
    xoffset = tl.program_id(0) * XBLOCK
    xoffset + tl.arange(0, XBLOCK)[:, None]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp5 = tl.load(in_ptr1 + r0, None)
    tmp8 = tl.load(in_ptr2 + r0, None)
    tmp11 = tl.load(in_ptr3 + r0, None)
    tmp1 = 16.0
    tmp2 = tmp0 / tmp1
    tmp3 = 0.0
    tmp4 = tmp2 + tmp3
    tmp6 = tmp5 / tmp1
    tmp7 = tmp4 + tmp6
    tmp9 = tmp8 / tmp1
    tmp10 = tmp7 + tmp9
    tmp12 = tmp11 / tmp1
    tmp13 = tmp10 + tmp12
    tmp14 = 0.25
    tmp15 = tmp13 * tmp14
    tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
    tmp18 = tl.sum(tmp16, 1)[:, None]
    tmp19 = 4.0
    tmp20 = tmp18 / tmp19
    tmp21 = 1.0
    tmp22 = tmp20 * tmp21
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp22, 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((4,), (1,), torch.float32)
        get_raw_stream(0)
        triton_per_fused_binary_cross_entropy_mean_0[grid(4)](arg1_1,
            arg0_1, buf0, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
        buf1 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_per_fused_binary_cross_entropy_mean_1[grid(4)](arg1_1,
            arg0_1, buf1, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
        buf2 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_per_fused_binary_cross_entropy_mean_2[grid(4)](arg1_1,
            arg0_1, buf2, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
        buf3 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_per_fused_binary_cross_entropy_mean_3[grid(4)](arg1_1,
            arg0_1, buf3, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf5 = buf4
        del buf4
        triton_per_fused_add_binary_cross_entropy_div_mean_mul_4[grid(1)](buf5,
            buf0, buf1, buf2, buf3, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
        del buf0
        del buf1
        del buf2
        del buf3
    return buf5,


def binary_cbce_loss(pred, label, **kwargs):
    """
    :param pred: [N, *]: here should be scores in [0,1]
    :param label: [N, *]: values in [0,1]
    :return: [N]
    """
    mask = (label > 0.5).float()
    b, h, w = mask.shape
    num_pos = torch.sum(mask, dim=[1, 2]).float()
    num_neg = h * w - num_pos
    weight = torch.zeros_like(mask)
    pos_weight = num_neg / (num_pos + num_neg)
    neg_weight = num_pos / (num_pos + num_neg)
    for i in range(b):
        weight[i][label[i] > 0.5] = pos_weight[i]
        weight[i][label[i] <= 0.5] = neg_weight[i]
    loss = torch.nn.functional.binary_cross_entropy(pred.float(), label.
        float(), weight=weight, reduction='none')
    return loss


def binary_ce_loss(pred, label, **kwargs):
    loss = F.binary_cross_entropy(pred, label, reduction='none')
    loss = torch.mean(loss, dim=(1, 2))
    return loss


def binary_dice_loss(pred, label, smooth=1e-05):
    """
    :param pred: [N, *]: here should be scores in [0,1]
    :param label: [N, *]
    :param power: 1 for abs, 2 for square
    :return: [N]
    """
    pred = pred.contiguous().view(pred.shape[0], -1).float()
    label = label.contiguous().view(label.shape[0], -1).float()
    num = 2 * torch.sum(torch.mul(pred, label), dim=1) + smooth
    den = torch.sum(pred, dim=1) + torch.sum(label, dim=1) + smooth
    loss = 1 - num / den
    return loss


def binary_ce_dice_loss(pred, label, smooth=1.0, **kwargs):
    loss1 = binary_ce_loss(pred, label, **kwargs)
    loss2 = binary_dice_loss(pred, label, smooth=smooth)
    return loss1 + loss2


def _make_one_hot(label, num_classes):
    """
    :param label: [N, *], values in [0,num_classes)
    :return: [N, C, *]
    """
    label = label.unsqueeze(1)
    shape = list(label.shape)
    shape[1] = num_classes
    result = torch.zeros(shape, device=label.device)
    result.scatter_(1, label, 1)
    return result


def reduce_loss(loss, reduction):
    """Reduce loss as specified.

    Args:
        loss (Tensor): Elementwise loss tensor.
        reduction (str): Options are "none", "mean" and "sum".

    Return:
        Tensor: Reduced loss tensor.
    """
    reduction_enum = F._Reduction.get_enum(reduction)
    if reduction_enum == 0:
        return loss
    elif reduction_enum == 1:
        return loss.mean()
    elif reduction_enum == 2:
        return loss.sum()


def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
    """Apply element-wise weight and reduce loss.

    Args:
        loss (Tensor): Element-wise loss.
        weight (Tensor): Element-wise weights.
        reduction (str): Same as built-in losses of PyTorch.
        avg_factor (float): Avarage factor when computing the mean of losses.

    Returns:
        Tensor: Processed loss values.
    """
    if weight is not None:
        assert weight.dim() == loss.dim()
        if weight.dim() > 1:
            assert weight.size(1) == 1 or weight.size(1) == loss.size(1)
        loss = loss * weight
    if avg_factor is None:
        loss = reduce_loss(loss, reduction)
    elif reduction == 'mean':
        loss = loss.sum() / avg_factor
    elif reduction != 'none':
        raise ValueError('avg_factor can not be used with reduction="sum"')
    return loss


def binary_loss(pred_raw, label_raw, loss_func, weight=None, class_weight=
    None, class_weight_norm=False, reduction='mean', avg_factor=None,
    smooth=1.0, **kwargs):
    """
    :param pred:  [N, C, *] scores without softmax
    :param label: [N, *] in [0, C], 0 stands for background, 1~C stands for pred in 0~C-1
    :return: reduction([N])
    """
    pred = pred_raw.clone()
    label = label_raw.clone()
    num_classes = pred.shape[1]
    if class_weight is not None:
        class_weight = class_weight.float()
    if pred.shape != label.shape:
        label = _make_one_hot(label, num_classes)
    pred = torch.sigmoid(pred)
    loss = 0.0
    for i in range(num_classes):
        if isinstance(loss_func, tuple):
            loss_function = loss_func[i]
        else:
            loss_function = loss_func
        class_loss = loss_function(pred[:, i], label[:, i], smooth=smooth)
        if class_weight is not None:
            class_loss *= class_weight[i]
        loss += class_loss
    if class_weight is not None and class_weight_norm:
        loss = loss / torch.sum(class_weight)
    else:
        loss = loss / num_classes
    loss = weight_reduce_loss(loss, weight=weight, reduction=reduction,
        avg_factor=avg_factor)
    return loss


class BinaryLossNew(nn.Module):

    def __init__(self, loss_type='ce', reduction='mean', class_weight=None,
        class_weight_norm=False, loss_weight=1.0, smooth=1.0, **kwargs):
        super(BinaryLossNew, self).__init__()
        assert loss_type in ['ce', 'dice', 'cbce', 'ce_dice', 'mix']
        self.reduction = reduction
        self.loss_weight = loss_weight
        self.class_weight = class_weight
        self.class_weight_norm = class_weight_norm
        self.loss_type = loss_type
        self.smooth = smooth

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