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
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_poi_fused_cat_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
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tl.store(out_ptr0 + x0, tmp0, xmask)


@triton.jit
def triton_per_fused_mul_rsub_sum_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
    out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 64
    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 % 16
    r2 = rindex // 16
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0)
    tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0)
    tmp2 = tmp0 * tmp1
    tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
    tmp5 = tl.where(xmask, tmp3, 0)
    tmp6 = tl.sum(tmp5, 1)[:, None]
    tmp7 = 1.0
    tmp8 = tmp7 - tmp1
    tmp9 = tmp0 * tmp8
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
    tmp12 = tl.where(xmask, tmp10, 0)
    tmp13 = tl.sum(tmp12, 1)[:, None]
    tmp14 = tmp7 - tmp0
    tmp15 = tmp1 * tmp14
    tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
    tmp18 = tl.where(xmask, tmp16, 0)
    tmp19 = tl.sum(tmp18, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp6, xmask)
    tl.store(out_ptr1 + x0, tmp13, xmask)
    tl.store(out_ptr2 + x0, tmp19, xmask)


@triton.jit
def triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2(in_out_ptr0,
    in_ptr0, in_ptr1, in_ptr2, 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)
    tmp1 = tl.load(in_ptr1 + r0, None)
    tmp3 = tl.load(in_ptr2 + r0, None)
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp5 = 0.0
    tmp6 = tmp4 == tmp5
    tmp7 = tmp6.to(tl.float32)
    tmp8 = 1e-20
    tmp9 = tmp7 * tmp8
    tmp10 = tmp0 + tmp9
    tmp11 = tmp4 + tmp8
    tmp12 = tmp10 / tmp11
    tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
    tmp15 = tl.sum(tmp13, 1)[:, None]
    tmp16 = 4.0
    tmp17 = tmp15 / tmp16
    tmp18 = 1.0
    tmp19 = tmp18 - tmp17
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp19, 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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
            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_cat_0[grid(256)](arg1_1, buf1, 256, XBLOCK=128,
            num_warps=4, num_stages=1)
        del arg1_1
        buf2 = empty_strided_cuda((4,), (1,), torch.float32)
        buf3 = empty_strided_cuda((4,), (1,), torch.float32)
        buf4 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_per_fused_mul_rsub_sum_1[grid(4)](buf0, buf1, buf2, buf3,
            buf4, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
        buf5 = empty_strided_cuda((), (), torch.float32)
        buf6 = buf5
        del buf5
        triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2[grid(1)](buf6,
            buf2, buf3, buf4, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
        del buf2
        del buf3
        del buf4
    return buf6, buf1, buf0


def calculate_segmentation_statistics(outputs: 'torch.Tensor', targets:
    'torch.Tensor', class_dim: 'int'=1, threshold=None):
    """Compute calculate segmentation statistics.

    Args:
        outputs: torch.Tensor.
        targets: torch.Tensor.
        threshold: threshold for binarization of predictions.
        class_dim: indicates class dimension (K).

    Returns:
        True positives , false positives , false negatives for segmentation task.
    """
    num_dims = len(outputs.shape)
    assert num_dims > 2, 'Found only two dimensions, shape should be [bs , C , ...]'
    assert outputs.shape == targets.shape, 'shape mismatch'
    if threshold is not None:
        outputs = (outputs > threshold).float()
    dims = [dim for dim in range(num_dims) if dim != class_dim]
    true_positives = torch.sum(outputs * targets, dim=dims)
    false_positives = torch.sum(outputs * (1 - targets), dim=dims)
    false_negatives = torch.sum(targets * (1 - outputs), dim=dims)
    return true_positives, false_positives, false_negatives


class MetricMeter:
    """Base Class to structuring your metrics."""

    def accumulate(self, outputs, targets):
        """Method to accumulate outputs and targets per the batch."""
        raise NotImplementedError

    def compute(self):
        """Method to compute the metric on epoch end."""
        raise NotImplementedError

    def reset(self):
        """Method to reset the accumulation lists."""
        raise NotImplementedError


class IOU(MetricMeter):
    """Class which computes intersection over union."""

    def __init__(self, threshold: 'float'=None, class_dim: 'int'=1):
        """Constructor method for IOU.

        Args:
            threshold: threshold for binarization of predictions
            class_dim: indicates class dimension (K)

        Note:
            Supports only binary cases
        """
        self.threshold = threshold
        self.class_dim = class_dim
        self.eps = 1e-20
        self._outputs = []
        self._targets = []
        self.reset()

    def handle(self) ->str:
        """Method to get the class name.

        Returns:
            The class name
        """
        return self.__class__.__name__.lower()

    def accumulate(self, outputs: 'torch.Tensor', targets: 'torch.Tensor'):
        """Method to accumulate the outputs and targets.

        Args:
            outputs: [N, K, ...] tensor that for each of the N samples
                indicates the probability of the sample belonging to each of
                the K num_classes.
            targets:  binary [N, K, ...] tensor that encodes which of the K
                num_classes are associated with the N-th sample.
        """
        self._outputs.append(outputs)
        self._targets.append(targets)

    def compute(self) ->torch.Tensor:
        """Method to Compute IOU.

        Returns:
            The computed iou.
        """
        self._outputs = torch.cat(self._outputs)
        self._targets = torch.cat(self._targets)
        tp, fp, fn = calculate_segmentation_statistics(outputs=self.
            _outputs, targets=self._targets, threshold=self.threshold,
            class_dim=self.class_dim)
        union = tp + fp + fn
        score = (tp + self.eps * (union == 0).float()) / (tp + fp + fn +
            self.eps)
        return torch.mean(score)

    def reset(self):
        """Method to reset the accumulation lists."""
        self._outputs = []
        self._targets = []


class IOULossNew(nn.Module):
    """Computes intersection over union Loss.

    IOULoss =  1 - iou_score
    """

    def __init__(self, class_dim=1):
        """Constructor method for IOULoss.

        Args:
            class_dim: indicates class dimension (K) for
                outputs and targets tensors (default = 1)
        """
        super(IOULossNew, self).__init__()
        self.iou = IOU(threshold=None, class_dim=class_dim)

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