# AOT ID: ['0_inference']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_7/inductor_cache/7d/c7dubrsigenrd2jmd6iwmxj4ghxpnyetwaywlk3uefyl3icppnek.py
# Topologically Sorted Source Nodes: [max_1, sub, exp_x, mul_2, sum_1, add, exp_x_sum, mul_3, expected_x, mul, mul_1, expected_y], Original ATen: [aten.max, aten.sub, aten.exp, aten.mul, aten.sum, aten.add, aten.reciprocal]
# Source node to ATen node mapping:
#   add => add
#   exp_x => exp
#   exp_x_sum => mul, reciprocal
#   expected_x => sum_3
#   expected_y => sum_2
#   max_1 => max_1
#   mul => mul_5
#   mul_1 => mul_6
#   mul_2 => mul_7
#   mul_3 => mul_8
#   sub => sub
#   sum_1 => sum_1
# Graph fragment:
#   %max_1 : [num_users=1] = call_function[target=torch.ops.aten.max.dim](args = (%view, -1, True), kwargs = {})
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%view, %getitem), kwargs = {})
#   %exp : [num_users=3] = call_function[target=torch.ops.aten.exp.default](args = (%sub,), kwargs = {})
#   %mul_7 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%view_3, %exp), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%exp, [-1], True), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sum_1, 1e-06), kwargs = {})
#   %reciprocal : [num_users=1] = call_function[target=torch.ops.aten.reciprocal.default](args = (%add,), kwargs = {})
#   %mul : [num_users=2] = call_function[target=torch.ops.aten.mul.Tensor](args = (%reciprocal, 1.0), kwargs = {})
#   %mul_8 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul_7, %mul), kwargs = {})
#   %sum_3 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_8, [-1], True), kwargs = {})
#   %mul_5 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%view_4, %exp), kwargs = {})
#   %mul_6 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul_5, %mul), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_6, [-1], True), kwargs = {})
triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0 = async_compile.triton('triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.persistent_reduction(
    size_hints=[16, 16],
    reduction_hint=ReductionHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 4, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False}
)
@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
    rnumel = 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, :]
    roffset = 0
    rmask = 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)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

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)  # alias
        buf4 = reinterpret_tensor(buf5, (4, 4, 1), (8, 2, 1), 1)  # alias
        # Topologically Sorted Source Nodes: [max_1, sub, exp_x, mul_2, sum_1, add, exp_x_sum, mul_3, expected_x, mul, mul_1, expected_y], Original ATen: [aten.max, aten.sub, aten.exp, aten.mul, aten.sum, aten.add, aten.reciprocal]
        stream0 = get_raw_stream(0)
        triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0.run(arg0_1, buf3, buf4, 16, 16, grid=grid(16), stream=stream0)
        del arg0_1
    return (buf5, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import torch.nn as nn
from typing import Optional


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 SoftArgmax2D(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(SoftArgmax2D, self).__init__()
        self.normalized_coordinates: 'Optional[bool]' = normalized_coordinates
        self.eps: 'float' = 1e-06

    def forward(self, input: 'torch.Tensor') ->torch.Tensor:
        if not torch.is_tensor(input):
            raise TypeError('Input input type is not a torch.Tensor. Got {}'
                .format(type(input)))
        if not len(input.shape) == 4:
            raise ValueError('Invalid input shape, we expect BxCxHxW. Got: {}'
                .format(input.shape))
        batch_size, channels, _height, _width = input.shape
        x: 'torch.Tensor' = input.view(batch_size, channels, -1)
        exp_x = torch.exp(x - torch.max(x, dim=-1, keepdim=True)[0])
        exp_x_sum = 1.0 / (exp_x.sum(dim=-1, keepdim=True) + self.eps)
        pos_y, pos_x = create_meshgrid(input, self.normalized_coordinates)
        pos_x = pos_x.reshape(-1)
        pos_y = pos_y.reshape(-1)
        expected_y: 'torch.Tensor' = torch.sum(pos_y * exp_x * exp_x_sum,
            dim=-1, keepdim=True)
        expected_x: 'torch.Tensor' = torch.sum(pos_x * exp_x * exp_x_sum,
            dim=-1, keepdim=True)
        output: 'torch.Tensor' = torch.cat([expected_x, expected_y], dim=-1)
        return output.view(batch_size, channels, 2)


def get_inputs():
    return [torch.rand([4, 4, 4, 4])]


def get_init_inputs():
    return [[], {}]

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]
