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
import torch._C
import torch.serialization
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_mul_pow_sub_sum_0(in_ptr0, in_ptr1, in_ptr2, 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 % 4
    x1 = xindex // 4 % 16
    x2 = xindex // 64
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (x1 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp2 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr1 + (16 + x1 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp6 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp10 = tl.load(in_ptr1 + (32 + x1 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp11 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp15 = tl.load(in_ptr1 + (48 + x1 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp16 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp3 = tmp1 - tmp2
    tmp4 = tmp3 * tmp3
    tmp7 = tmp5 - tmp6
    tmp8 = tmp7 * tmp7
    tmp9 = tmp4 + tmp8
    tmp12 = tmp10 - tmp11
    tmp13 = tmp12 * tmp12
    tmp14 = tmp9 + tmp13
    tmp17 = tmp15 - tmp16
    tmp18 = tmp17 * tmp17
    tmp19 = tmp14 + tmp18
    tmp20 = tmp0 * tmp19
    tl.store(out_ptr0 + x4, tmp20, xmask)


@triton.jit
def triton_poi_fused__softmax_1(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
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), 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
    tmp9 = tl_math.exp(tmp8)
    tl.store(out_ptr0 + x2, tmp9, xmask)


@triton.jit
def triton_poi_fused__softmax_2(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
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp3 = tmp1 + tmp2
    tmp5 = tmp3 + tmp4
    tmp7 = tmp5 + tmp6
    tmp8 = tmp0 / tmp7
    tl.store(out_ptr0 + x2, tmp8, xmask)


@triton.jit
def triton_per_fused_mul_sub_sum_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    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)
    r3 = rindex
    x1 = xindex // 4 % 4
    x2 = xindex // 16
    x0 = xindex % 4
    x4 = xindex % 16
    x5 = xindex
    tmp0 = tl.load(in_ptr0 + (x1 + 4 * r3 + 64 * x2), xmask,
        eviction_policy='evict_last', other=0.0)
    tmp1 = tl.load(in_ptr1 + (r3 + 16 * x0 + 64 * x2), xmask,
        eviction_policy='evict_last', other=0.0)
    tmp2 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
    tmp3 = tmp1 - tmp2
    tmp4 = tmp0 * tmp3
    tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
    tmp7 = tl.where(xmask, tmp5, 0)
    tmp8 = tl.sum(tmp7, 1)[:, None]
    tl.store(out_ptr0 + x5, tmp8, xmask)


def call(args):
    primals_1, primals_2, primals_3 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_mul_pow_sub_sum_0[grid(256)](primals_3, primals_1,
            primals_2, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
        buf1 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
        triton_poi_fused__softmax_1[grid(256)](buf0, buf1, 256, XBLOCK=256,
            num_warps=4, num_stages=1)
        buf2 = buf0
        del buf0
        triton_poi_fused__softmax_2[grid(256)](buf1, buf2, 256, XBLOCK=256,
            num_warps=4, num_stages=1)
        del buf1
        buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_per_fused_mul_sub_sum_3[grid(64)](buf2, primals_1, primals_2,
            buf3, 64, 16, XBLOCK=1, num_warps=2, num_stages=1)
        del buf2
    return buf3, primals_1, primals_2, primals_3


class EncodingNew(nn.Module):
    """Encoding Layer: a learnable residual encoder.

    Input is of shape  (batch_size, channels, height, width).
    Output is of shape (batch_size, num_codes, channels).

    Args:
        channels: dimension of the features or feature channels
        num_codes: number of code words
    """

    def __init__(self, channels, num_codes):
        super(EncodingNew, self).__init__()
        self.channels, self.num_codes = channels, num_codes
        std = 1.0 / (num_codes * channels) ** 0.5
        self.codewords = nn.Parameter(torch.empty(num_codes, channels,
            dtype=torch.float).uniform_(-std, std), requires_grad=True)
        self.scale = nn.Parameter(torch.empty(num_codes, dtype=torch.float)
            .uniform_(-1, 0), requires_grad=True)

    @staticmethod
    def scaled_l2(x, codewords, scale):
        num_codes, channels = codewords.size()
        batch_size = x.size(0)
        reshaped_scale = scale.view((1, 1, num_codes))
        expanded_x = x.unsqueeze(2).expand((batch_size, x.size(1),
            num_codes, channels))
        reshaped_codewords = codewords.view((1, 1, num_codes, channels))
        scaled_l2_norm = reshaped_scale * (expanded_x - reshaped_codewords
            ).pow(2).sum(dim=3)
        return scaled_l2_norm

    @staticmethod
    def aggregate(assignment_weights, x, codewords):
        num_codes, channels = codewords.size()
        reshaped_codewords = codewords.view((1, 1, num_codes, channels))
        batch_size = x.size(0)
        expanded_x = x.unsqueeze(2).expand((batch_size, x.size(1),
            num_codes, channels))
        encoded_feat = (assignment_weights.unsqueeze(3) * (expanded_x -
            reshaped_codewords)).sum(dim=1)
        return encoded_feat

    def __repr__(self):
        repr_str = self.__class__.__name__
        repr_str += (
            f'(Nx{self.channels}xHxW =>Nx{self.num_codes}x{self.channels})')
        return repr_str

    def forward(self, input_0):
        primals_2 = self.codewords
        primals_3 = self.scale
        primals_1 = input_0
        output = call([primals_1, primals_2, primals_3])
        return output[0]


Measured latency_ms: 0.021386