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
from torch.nn import Parameter
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_poi_fused_clamp_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp1 = -1.0
    tmp2 = triton_helpers.maximum(tmp0, tmp1)
    tmp3 = 1.0
    tmp4 = triton_helpers.minimum(tmp2, tmp3)
    tl.store(out_ptr0 + x0, tmp4, xmask)


@triton.jit
def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 2
    x1 = xindex // 2
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy=
        'evict_last')
    tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy=
        'evict_last')
    tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
        'evict_last')
    tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
        'evict_last')
    tmp2 = tmp1 + tmp0
    tmp4 = tmp3 + tmp2
    tmp6 = tmp5 + tmp4
    tmp7 = 0.25
    tmp8 = tmp6 * tmp7
    tl.store(out_ptr0 + x2, tmp8, xmask)


@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4 % 8
    x0 = xindex % 4
    x2 = xindex // 32
    x3 = xindex
    tmp0 = x1
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0)
    tmp6 = tmp0 >= tmp3
    tl.full([1], 8, tl.int64)
    tmp9 = tl.load(in_ptr1 + (x0 + 4 * (-4 + x1) + 16 * x2), tmp6 & xmask,
        other=0.0)
    tmp10 = tl.where(tmp4, tmp5, tmp9)
    tl.store(out_ptr0 + x3, tmp10, xmask)


@triton.jit
def triton_per_fused_add_mul_sum_3(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    RBLOCK: tl.constexpr = 8
    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)
    r2 = rindex
    x0 = xindex % 4
    x1 = xindex // 4
    x3 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 4 * r2 + 32 * x1), xmask, other=0.0)
    tmp1 = tl.load(in_ptr1 + (x0 + 4 * r2), xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp7 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 * tmp1
    tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
    tmp5 = tl.where(xmask, tmp3, 0)
    tmp6 = tl.sum(tmp5, 1)[:, None]
    tmp8 = tmp6 + tmp7
    tl.debug_barrier()
    tl.store(in_out_ptr0 + x3, tmp8, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4 = args
    args.clear()
    assert_size_stride(primals_1, (1, 4, 1, 2), (8, 2, 2, 1))
    assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_3, (1, 8, 1, 4), (32, 4, 4, 1))
    assert_size_stride(primals_4, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((1, 4, 1, 2), (8, 2, 2, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_clamp_0[grid(8)](primals_1, buf0, 8, XBLOCK=8,
            num_warps=1, num_stages=1)
        buf1 = torch.ops.aten.cudnn_grid_sampler.default(primals_2,
            reinterpret_tensor(buf0, (4, 4, 1, 2), (0, 2, 0, 1), 0))
        buf2 = buf1
        buf3 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
        triton_poi_fused_avg_pool2d_1[grid(64)](primals_2, buf3, 64, XBLOCK
            =64, num_warps=1, num_stages=1)
        buf4 = torch.ops.aten.cudnn_grid_sampler.default(buf3,
            reinterpret_tensor(buf0, (4, 4, 1, 2), (0, 2, 0, 1), 0))
        buf5 = buf4
        buf6 = empty_strided_cuda((4, 8, 4, 1), (32, 4, 1, 1), torch.float32)
        triton_poi_fused_cat_2[grid(128)](buf2, buf5, buf6, 128, XBLOCK=128,
            num_warps=4, num_stages=1)
        del buf2
        del buf5
        buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf8 = buf7
        del buf7
        triton_per_fused_add_mul_sum_3[grid(16)](buf8, buf6, primals_3,
            primals_4, 16, 8, XBLOCK=1, num_warps=2, num_stages=1)
        del primals_4
        buf9 = torch.ops.aten.set_.source_Tensor(primals_1, buf0)
        assert_size_stride(buf9, (1, 4, 1, 2), (8, 2, 2, 1))
        del buf1
        del buf4
        del primals_1
    return buf8, primals_2, primals_3, buf0, buf3, buf6


def positive(weight, cache=None):
    weight.data *= weight.data.ge(0).float()
    return cache


class SpatialTransformerPooled2dNew(nn.Module):

    def __init__(self, in_shape, outdims, pool_steps=1, positive=False,
        bias=True, pool_kern=2, init_range=0.1):
        super().__init__()
        self._pool_steps = pool_steps
        self.in_shape = in_shape
        c, _w, _h = in_shape
        self.outdims = outdims
        self.positive = positive
        self.grid = Parameter(torch.Tensor(1, outdims, 1, 2))
        self.features = Parameter(torch.Tensor(1, c * (self._pool_steps + 1
            ), 1, outdims))
        if bias:
            bias = Parameter(torch.Tensor(outdims))
            self.register_parameter('bias', bias)
        else:
            self.register_parameter('bias', None)
        self.pool_kern = pool_kern
        self.avg = nn.AvgPool2d((pool_kern, pool_kern), stride=pool_kern,
            count_include_pad=False)
        self.init_range = init_range
        self.initialize()

    @property
    def pool_steps(self):
        return self._pool_steps

    @pool_steps.setter
    def pool_steps(self, value):
        assert value >= 0 and int(value
            ) - value == 0, 'new pool steps must be a non-negative integer'
        if value != self._pool_steps:
            None
            c, _w, _h = self.in_shape
            self._pool_steps = int(value)
            self.features = Parameter(torch.Tensor(1, c * (self._pool_steps +
                1), 1, self.outdims))
            self.features.data.fill_(1 / self.in_shape[0])

    def initialize(self):
        self.grid.data.uniform_(-self.init_range, self.init_range)
        self.features.data.fill_(1 / self.in_shape[0])
        if self.bias is not None:
            self.bias.data.fill_(0)

    def feature_l1(self, average=True):
        if average:
            return self.features.abs().mean()
        else:
            return self.features.abs().sum()

    def group_sparsity(self, group_size):
        f = self.features.size(1)
        n = f // group_size
        ret = 0
        for chunk in range(0, f, group_size):
            ret = ret + (self.features[:, chunk:chunk + group_size, ...].
                pow(2).mean(1) + 1e-12).sqrt().mean() / n
        return ret

    def __repr__(self):
        c, w, h = self.in_shape
        r = self.__class__.__name__ + ' (' + '{} x {} x {}'.format(c, w, h
            ) + ' -> ' + str(self.outdims) + ')'
        if self.bias is not None:
            r += ' with bias'
        r += ' and pooling for {} steps\n'.format(self.pool_steps)
        for ch in self.children():
            r += '  -> ' + ch.__repr__() + '\n'
        return r

    def forward(self, input_0):
        primals_1 = self.grid
        primals_3 = self.features
        primals_4 = self.bias
        primals_2 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4])
        return output[0]


Measured latency_ms: 0.014008