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 torch.nn as nn
from typing import Optional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0(in_ptr0, out_ptr2,
    out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    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 + 16 * x0), xmask, other=0.0)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.where(xmask, tmp1, float('-inf'))
    tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
    tmp5 = tmp0 - tmp4
    tmp6 = tl_math.exp(tmp5)
    tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
    tmp9 = tl.where(xmask, tmp7, 0)
    tmp10 = tl.sum(tmp9, 1)[:, None]
    tmp11 = r1 % 4
    tmp12 = tmp11.to(tl.float32)
    tmp13 = 2.0
    tmp14 = tmp12 < tmp13
    tmp15 = 0.6666666666666666
    tmp16 = tmp12 * tmp15
    tmp17 = -1.0
    tmp18 = tmp16 + tmp17
    tmp19 = 3 + -1 * (r1 % 4)
    tmp20 = tmp19.to(tl.float32)
    tmp21 = tmp20 * tmp15
    tmp22 = 1.0
    tmp23 = tmp22 - tmp21
    tmp24 = tl.where(tmp14, tmp18, tmp23)
    tmp25 = tmp24 * tmp6
    tmp26 = 1e-06
    tmp27 = tmp10 + tmp26
    tmp28 = tl.full([1, 1], 1, tl.int32)
    tmp29 = tmp28 / tmp27
    tmp30 = tmp29 * tmp22
    tmp31 = tmp25 * tmp30
    tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
    tmp34 = tl.where(xmask, tmp32, 0)
    tmp35 = tl.sum(tmp34, 1)[:, None]
    tmp36 = r1 // 4
    tmp37 = tmp36.to(tl.float32)
    tmp38 = tmp37 < tmp13
    tmp39 = tmp37 * tmp15
    tmp40 = tmp39 + tmp17
    tmp41 = 3 + -1 * (r1 // 4)
    tmp42 = tmp41.to(tl.float32)
    tmp43 = tmp42 * tmp15
    tmp44 = tmp22 - tmp43
    tmp45 = tl.where(tmp38, tmp40, tmp44)
    tmp46 = tmp45 * tmp6
    tmp47 = tmp46 * tmp30
    tmp48 = tl.broadcast_to(tmp47, [XBLOCK, RBLOCK])
    tmp50 = tl.where(xmask, tmp48, 0)
    tmp51 = tl.sum(tmp50, 1)[:, None]
    tl.store(out_ptr2 + 2 * x0, tmp35, xmask)
    tl.store(out_ptr3 + 2 * x0, tmp51, xmask)


def call(args):
    arg0_1, = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf5 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
        buf3 = reinterpret_tensor(buf5, (4, 4, 1), (8, 2, 1), 0)
        buf4 = reinterpret_tensor(buf5, (4, 4, 1), (8, 2, 1), 1)
        get_raw_stream(0)
        triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0[grid(16)](arg0_1,
            buf3, buf4, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
        del arg0_1
    return buf5,


def create_meshgrid(x: 'torch.Tensor', normalized_coordinates: 'Optional[bool]'
    ) ->torch.Tensor:
    assert len(x.shape) == 4, x.shape
    _, _, height, width = x.shape
    _device, _dtype = x.device, x.dtype
    if normalized_coordinates:
        xs = torch.linspace(-1.0, 1.0, width, device=_device, dtype=_dtype)
        ys = torch.linspace(-1.0, 1.0, height, device=_device, dtype=_dtype)
    else:
        xs = torch.linspace(0, width - 1, width, device=_device, dtype=_dtype)
        ys = torch.linspace(0, height - 1, height, device=_device, dtype=_dtype
            )
    return torch.meshgrid(ys, xs)


class SoftArgmax2DNew(nn.Module):
    """Creates a module that computes the Spatial Soft-Argmax 2D
    of a given input heatmap.

    Returns the index of the maximum 2d coordinates of the give map.
    The output order is x-coord and y-coord.

    Arguments:
        normalized_coordinates (Optional[bool]): wether to return the
          coordinates normalized in the range of [-1, 1]. Otherwise,
          it will return the coordinates in the range of the input shape.
          Default is True.

    Shape:
        - Input: :math:`(B, N, H, W)`
        - Output: :math:`(B, N, 2)`

    Examples::
        >>> input = torch.rand(1, 4, 2, 3)
        >>> m = tgm.losses.SpatialSoftArgmax2d()
        >>> coords = m(input)  # 1x4x2
        >>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)
    """

    def __init__(self, normalized_coordinates: 'Optional[bool]'=True) ->None:
        super(SoftArgmax2DNew, self).__init__()
        self.normalized_coordinates: 'Optional[bool]' = normalized_coordinates
        self.eps: 'float' = 1e-06

    def forward(self, input_0):
        arg0_1 = input_0
        output = call([arg0_1])
        return output[0]


Measured latency_ms: 0.016663