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 math as tl_math
import math
import random
import numpy as np
import typing as t
from torch import 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__log_softmax_0(in_ptr0, out_ptr0, out_ptr1, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp3 = triton_helpers.maximum(tmp1, tmp2)
    tmp5 = triton_helpers.maximum(tmp3, tmp4)
    tmp7 = triton_helpers.maximum(tmp5, tmp6)
    tmp8 = tmp0 - tmp7
    tl.store(out_ptr0 + x3, tmp8, xmask)
    tl.store(out_ptr1 + x3, tmp8, xmask)


@triton.jit
def triton_per_fused__to_copy_nll_loss2d_forward_1(in_ptr0, in_ptr1,
    out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 64
    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)
    r2 = rindex
    r0 = rindex % 16
    r1 = rindex // 16
    tmp0 = tl.load(in_ptr0 + r2, None)
    tmp12 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
    tmp14 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
    tmp17 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
    tmp20 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
    tmp1 = tmp0.to(tl.int64)
    tmp2 = tl.full([1, 1], -100, tl.int64)
    tmp3 = tmp1 != tmp2
    tmp4 = tl.full([1, 1], 0, tl.int64)
    tmp5 = tl.where(tmp3, tmp1, tmp4)
    tmp6 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
    tmp7 = tmp5 + tmp6
    tmp8 = tmp5 < 0
    tmp9 = tl.where(tmp8, tmp7, tmp5)
    tl.device_assert((0 <= tmp9) & (tmp9 < 4),
        'index out of bounds: 0 <= tmp9 < 4')
    tmp11 = tl.load(in_ptr1 + (r0 + 16 * tmp9 + 64 * r1), None)
    tmp13 = tl_math.exp(tmp12)
    tmp15 = tl_math.exp(tmp14)
    tmp16 = tmp13 + tmp15
    tmp18 = tl_math.exp(tmp17)
    tmp19 = tmp16 + tmp18
    tmp21 = tl_math.exp(tmp20)
    tmp22 = tmp19 + tmp21
    tmp23 = tl_math.log(tmp22)
    tmp24 = tmp11 - tmp23
    tmp25 = -tmp24
    tmp26 = 0.0
    tmp27 = tl.where(tmp3, tmp25, tmp26)
    tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK])
    tmp30 = tl.sum(tmp28, 1)[:, None]
    tmp31 = tmp3.to(tl.int64)
    tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
    tmp34 = tl.sum(tmp32, 1)[:, None]
    tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp30, None)
    tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp34, None)


@triton.jit
def triton_per_fused__to_copy_nll_loss2d_forward_2(in_ptr0, in_ptr1,
    out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 64
    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)
    r2 = rindex
    r0 = rindex % 16
    r1 = rindex // 16
    tmp0 = tl.load(in_ptr0 + (64 + r2), None)
    tmp12 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
    tmp14 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
    tmp17 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
    tmp20 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
    tmp1 = tmp0.to(tl.int64)
    tmp2 = tl.full([1, 1], -100, tl.int64)
    tmp3 = tmp1 != tmp2
    tmp4 = tl.full([1, 1], 0, tl.int64)
    tmp5 = tl.where(tmp3, tmp1, tmp4)
    tmp6 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
    tmp7 = tmp5 + tmp6
    tmp8 = tmp5 < 0
    tmp9 = tl.where(tmp8, tmp7, tmp5)
    tl.device_assert((0 <= tmp9) & (tmp9 < 4),
        'index out of bounds: 0 <= tmp9 < 4')
    tmp11 = tl.load(in_ptr1 + (r0 + 16 * tmp9 + 64 * r1), None)
    tmp13 = tl_math.exp(tmp12)
    tmp15 = tl_math.exp(tmp14)
    tmp16 = tmp13 + tmp15
    tmp18 = tl_math.exp(tmp17)
    tmp19 = tmp16 + tmp18
    tmp21 = tl_math.exp(tmp20)
    tmp22 = tmp19 + tmp21
    tmp23 = tl_math.log(tmp22)
    tmp24 = tmp11 - tmp23
    tmp25 = -tmp24
    tmp26 = 0.0
    tmp27 = tl.where(tmp3, tmp25, tmp26)
    tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK])
    tmp30 = tl.sum(tmp28, 1)[:, None]
    tmp31 = tmp3.to(tl.int64)
    tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
    tmp34 = tl.sum(tmp32, 1)[:, None]
    tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp30, None)
    tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp34, None)


@triton.jit
def triton_poi_fused_add_mul_nll_loss2d_forward_rsub_3(in_ptr0, in_ptr1,
    in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 0)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
    tmp2 = tl.load(in_ptr1 + 0)
    tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
    tmp6 = tl.load(in_ptr2 + (192 + x0), xmask)
    tmp8 = tl.load(in_ptr3 + 0)
    tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
    tmp10 = tl.load(in_ptr4 + 0)
    tmp11 = tl.broadcast_to(tmp10, [XBLOCK])
    tmp4 = tmp3.to(tl.float32)
    tmp5 = tmp1 / tmp4
    tmp7 = tmp5 * tmp6
    tmp12 = tmp11.to(tl.float32)
    tmp13 = tmp9 / tmp12
    tmp14 = 1.0
    tmp15 = tmp14 - tmp6
    tmp16 = tmp13 * tmp15
    tmp17 = tmp7 + tmp16
    tl.store(out_ptr0 + x0, tmp17, xmask)


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)
        buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, buf3, 256,
            XBLOCK=256, num_warps=4, num_stages=1)
        del arg1_1
        buf1 = empty_strided_cuda((), (), torch.float32)
        buf2 = empty_strided_cuda((), (), torch.int64)
        triton_per_fused__to_copy_nll_loss2d_forward_1[grid(1)](arg0_1,
            buf0, buf1, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
        del buf0
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf5 = empty_strided_cuda((), (), torch.int64)
        triton_per_fused__to_copy_nll_loss2d_forward_2[grid(1)](arg0_1,
            buf3, buf4, buf5, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
        del buf3
        buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_add_mul_nll_loss2d_forward_rsub_3[grid(16)](buf1,
            buf2, arg0_1, buf4, buf5, buf6, 16, XBLOCK=16, num_warps=1,
            num_stages=1)
        del arg0_1
        del buf1
        del buf2
        del buf4
        del buf5
    return buf6,


class GridMixupLossNew(nn.Module):
    """ Implementation of GridMixup loss

    :param alpha: Percent of the first image on the crop. Can be float or Tuple[float, float]
                    - if float: lambda parameter gets from the beta-distribution np.random.beta(alpha, alpha)
                    - if Tuple[float, float]: lambda parameter gets from the uniform
                        distribution np.random.uniform(alpha[0], alpha[1])
    :param n_holes_x: Number of holes by OX
    :param hole_aspect_ratio: hole aspect ratio
    :param crop_area_ratio: Define percentage of the crop area
    :param crop_aspect_ratio: Define crop aspect ratio
    """

    def __init__(self, alpha: 't.Union[float, t.Tuple[float, float]]'=(0.1,
        0.9), n_holes_x: 't.Union[int, t.Tuple[int, int]]'=20,
        hole_aspect_ratio: 't.Union[float, t.Tuple[float, float]]'=1.0,
        crop_area_ratio: 't.Union[float, t.Tuple[float, float]]'=1.0,
        crop_aspect_ratio: 't.Union[float, t.Tuple[float, float]]'=1.0):
        super().__init__()
        self.alpha = alpha
        self.n_holes_x = n_holes_x
        self.hole_aspect_ratio = hole_aspect_ratio
        self.crop_area_ratio = crop_area_ratio
        self.crop_aspect_ratio = crop_aspect_ratio
        if isinstance(self.n_holes_x, int):
            self.n_holes_x = self.n_holes_x, self.n_holes_x
        if isinstance(self.hole_aspect_ratio, float):
            self.hole_aspect_ratio = (self.hole_aspect_ratio, self.
                hole_aspect_ratio)
        if isinstance(self.crop_area_ratio, float):
            self.crop_area_ratio = self.crop_area_ratio, self.crop_area_ratio
        if isinstance(self.crop_aspect_ratio, float):
            self.crop_aspect_ratio = (self.crop_aspect_ratio, self.
                crop_aspect_ratio)
        self.loss = nn.CrossEntropyLoss()

    def __str__(self):
        return 'gridmixup'

    @staticmethod
    def _get_random_crop(height: 'int', width: 'int', crop_area_ratio:
        'float', crop_aspect_ratio: 'float') ->t.Tuple:
        crop_area = int(height * width * crop_area_ratio)
        crop_width = int(np.sqrt(crop_area / crop_aspect_ratio))
        crop_height = int(crop_width * crop_aspect_ratio)
        cx = np.random.random()
        cy = np.random.random()
        y1 = int((height - crop_height) * cy)
        y2 = y1 + crop_height
        x1 = int((width - crop_width) * cx)
        x2 = x1 + crop_width
        return x1, y1, x2, y2

    def _get_gridmask(self, image_shape: 't.Tuple[int, int]',
        crop_area_ratio: 'float', crop_aspect_ratio: 'float', lam: 'float',
        nx: 'int', ar: 'float') ->np.ndarray:
        """ Method make grid mask

        :param image_shape: Shape of the images
        :param lam: Lambda parameter
        :param crop_area_ratio: Ratio of the crop area
        :param crop_aspect_ratio: Aspect ratio of the crop
        :param nx: Amount of holes by width
        :param ar: Aspect ratio of the hole
        :return: Binary mask, where holes == 1, background == 0
        """
        img_height, img_width = image_shape
        xc1, yc1, xc2, yc2 = self._get_random_crop(height=img_height, width
            =img_width, crop_area_ratio=crop_area_ratio, crop_aspect_ratio=
            crop_aspect_ratio)
        height = yc2 - yc1
        width = xc2 - xc1
        if not 1 <= nx <= width // 2:
            raise ValueError(
                f'The nx must be between 1 and {width // 2}.\nGive: {nx}')
        patch_width = math.ceil(width / nx)
        patch_height = int(patch_width * ar)
        ny = math.ceil(height / patch_height)
        ratio = np.sqrt(1 - lam)
        hole_width = int(patch_width * ratio)
        hole_height = int(patch_height * ratio)
        hole_width = min(max(hole_width, 1), patch_width - 1)
        hole_height = min(max(hole_height, 1), patch_height - 1)
        holes = []
        for i in range(nx + 1):
            for j in range(ny + 1):
                x1 = min(patch_width * i, width)
                y1 = min(patch_height * j, height)
                x2 = min(x1 + hole_width, width)
                y2 = min(y1 + hole_height, height)
                holes.append((x1, y1, x2, y2))
        mask = np.zeros(shape=image_shape, dtype=np.uint8)
        for x1, y1, x2, y2 in holes:
            mask[yc1 + y1:yc1 + y2, xc1 + x1:xc1 + x2] = 1
        return mask

    def get_sample(self, images: 'torch.Tensor', targets: 'torch.Tensor'
        ) ->t.Tuple[torch.Tensor, torch.Tensor]:
        """ Method returns augmented images and targets

        :param images: Batch of non-augmented images
        :param targets: Batch of non-augmented targets
        :return: Augmented images and targets
        """
        indices = torch.randperm(images.size(0))
        shuffled_targets = targets[indices]
        height, width = images.shape[2:]
        if isinstance(self.alpha, float):
            lam = np.random.beta(self.alpha, self.alpha)
        else:
            lam = np.random.uniform(self.alpha[0], self.alpha[1])
        nx = random.randint(self.n_holes_x[0], self.n_holes_x[1])
        ar = np.random.uniform(self.hole_aspect_ratio[0], self.
            hole_aspect_ratio[1])
        crop_area_ratio = np.random.uniform(self.crop_area_ratio[0], self.
            crop_area_ratio[1])
        crop_aspect_ratio = np.random.uniform(self.crop_aspect_ratio[0],
            self.crop_aspect_ratio[1])
        mask = self._get_gridmask(image_shape=(height, width),
            crop_area_ratio=crop_area_ratio, crop_aspect_ratio=
            crop_aspect_ratio, lam=lam, nx=nx, ar=ar)
        lam = 1 - mask.sum() / (images.size()[-1] * images.size()[-2])
        mask = torch.from_numpy(mask)
        images = images * (1 - mask) + images[indices, ...] * mask
        lam_list = torch.from_numpy(np.ones(shape=targets.shape) * lam)
        out_targets = torch.cat([targets, shuffled_targets, lam_list], dim=1
            ).transpose(0, 1)
        return images, out_targets

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