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 import 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_clamp_div_mean_mul_rsub_sum_0(in_out_ptr0, in_ptr0,
    in_ptr1, 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)
    tmp3 = tl.load(in_ptr1 + r0, None)
    tmp5 = tl.load(in_ptr0 + (4 + r0), None)
    tmp8 = tl.load(in_ptr1 + (4 + r0), None)
    tmp11 = tl.load(in_ptr0 + (8 + r0), None)
    tmp14 = tl.load(in_ptr1 + (8 + r0), None)
    tmp17 = tl.load(in_ptr0 + (12 + r0), None)
    tmp20 = tl.load(in_ptr1 + (12 + r0), None)
    tmp1 = tmp0.to(tl.float32)
    tmp2 = tl.sigmoid(tmp1)
    tmp4 = tmp2 * tmp3
    tmp6 = tmp5.to(tl.float32)
    tmp7 = tl.sigmoid(tmp6)
    tmp9 = tmp7 * tmp8
    tmp10 = tmp4 + tmp9
    tmp12 = tmp11.to(tl.float32)
    tmp13 = tl.sigmoid(tmp12)
    tmp15 = tmp13 * tmp14
    tmp16 = tmp10 + tmp15
    tmp18 = tmp17.to(tl.float32)
    tmp19 = tl.sigmoid(tmp18)
    tmp21 = tmp19 * tmp20
    tmp22 = tmp16 + tmp21
    tmp23 = 2.0
    tmp24 = tmp22 * tmp23
    tmp25 = tmp2 + tmp3
    tmp26 = tmp7 + tmp8
    tmp27 = tmp25 + tmp26
    tmp28 = tmp13 + tmp14
    tmp29 = tmp27 + tmp28
    tmp30 = tmp19 + tmp20
    tmp31 = tmp29 + tmp30
    tmp32 = 1e-05
    tmp33 = triton_helpers.maximum(tmp31, tmp32)
    tmp34 = tmp24 / tmp33
    tmp35 = 1.0
    tmp36 = tmp35 - tmp34
    tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
    tmp39 = tl.sum(tmp37, 1)[:, None]
    tmp40 = 4.0
    tmp41 = tmp39 / tmp40
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp41, None)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf1 = empty_strided_cuda((), (), torch.float32)
        buf2 = buf1
        del buf1
        get_raw_stream(0)
        triton_per_fused_add_clamp_div_mean_mul_rsub_sum_0[grid(1)](buf2,
            arg0_1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
    return buf2,


def expand_as_one_hot(input, C, ignore_index=None):
    """
    Converts NxDxHxW label image to NxCxDxHxW, where each label is stored in a separate channel
    :param input: 4D input image (NxDxHxW)
    :param C: number of channels/labels
    :param ignore_index: ignore index to be kept during the expansion
    :return: 5D output image (NxCxDxHxW)
    """
    assert input.dim() == 4
    shape = input.size()
    shape = list(shape)
    shape.insert(1, C)
    shape = tuple(shape)
    src = input.unsqueeze(0)
    if ignore_index is not None:
        expanded_src = src.expand(shape)
        mask = expanded_src == ignore_index
        src = src.clone()
        src[src == ignore_index] = 0
        result = torch.zeros(shape).scatter_(1, src, 1)
        result[mask] = ignore_index
        return result
    else:
        return torch.zeros(shape).scatter_(1, src, 1)


def flatten(tensor):
    """Flattens a given tensor such that the channel axis is first.
    The shapes are transformed as follows:
       (N, C, D, H, W) -> (C, N * D * H * W)
    """
    C = tensor.size(1)
    axis_order = (1, 0) + tuple(range(2, tensor.dim()))
    transposed = tensor.permute(axis_order)
    return transposed.view(C, -1)


def compute_per_channel_dice(input, target, epsilon=1e-05, ignore_index=
    None, weight=None):
    if target.dim() == 4:
        target = expand_as_one_hot(target, C=input.size()[1], ignore_index=
            ignore_index)
    assert input.size() == target.size(
        ), "'input' and 'target' must have the same shape"
    if ignore_index is not None:
        mask = target.clone().ne_(ignore_index)
        mask.requires_grad = False
        input = input * mask
        target = target * mask
    input = flatten(input)
    target = flatten(target)
    intersect = (input * target).sum(-1)
    if weight is not None:
        intersect = weight * intersect
    denominator = (input + target).sum(-1)
    return 2.0 * intersect / denominator.clamp(min=epsilon)


class DiceLossNew(nn.Module):
    """Computes Dice Loss, which just 1 - DiceCoefficient described above.
    Additionally allows per-class weights to be provided.
    """

    def __init__(self, epsilon=1e-05, weight=None, ignore_index=None,
        sigmoid_normalization=True):
        super(DiceLossNew, self).__init__()
        self.epsilon = epsilon
        self.register_buffer('weight', weight)
        self.ignore_index = ignore_index
        if sigmoid_normalization:
            self.normalization = nn.Sigmoid()
        else:
            self.normalization = nn.Softmax(dim=1)

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