import torch
from torch._inductor.select_algorithm import extern_kernels
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 numpy as np
import torch as th
import torch.nn as nn
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_mean_0(in_ptr0, out_ptr0, 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, 0)
    tmp4 = tl.sum(tmp3, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp4, xmask)


@triton.jit
def triton_poi_fused_add_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 272
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 17
    x3 = xindex // 17
    x4 = xindex % 68
    x5 = xindex
    tmp15 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
    tmp0 = x0
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 1, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + x3, tmp4 & xmask, eviction_policy='evict_last',
        other=0.0)
    tmp6 = 16.0
    tmp7 = tmp5 / tmp6
    tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
    tmp9 = tl.where(tmp4, tmp7, tmp8)
    tmp10 = tmp0 >= tmp3
    tl.full([1], 17, tl.int64)
    tmp13 = tl.load(in_ptr1 + (16 * x3 + (-1 + x0)), tmp10 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp14 = tl.where(tmp4, tmp9, tmp13)
    tmp16 = tmp14 + tmp15
    tl.store(out_ptr0 + x5, tmp16, xmask)


@triton.jit
def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 272
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex // 68
    x3 = xindex % 68
    x1 = xindex // 17 % 4
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (x3 + 204 * x2), xmask)
    tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = 0.7071067811865475
    tmp4 = tmp2 * tmp3
    tl.store(out_ptr0 + x4, tmp4, xmask)


@triton.jit
def triton_poi_fused_mul_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 272
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex // 68
    x3 = xindex % 68
    x1 = xindex // 17 % 4
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (68 + x3 + 204 * x2), xmask)
    tmp1 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = 0.7071067811865475
    tmp4 = tmp2 * tmp3
    tl.store(out_ptr0 + x4, tmp4, xmask)


@triton.jit
def triton_per_fused__softmax_4(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
    tl.constexpr):
    xnumel = 68
    rnumel = 17
    RBLOCK: tl.constexpr = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    rmask = rindex < rnumel
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 17 * x0), rmask & xmask, other=0.0)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.where(rmask & 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(rmask & xmask, tmp7, 0)
    tmp10 = tl.sum(tmp9, 1)[:, None]
    tmp11 = tmp6 / tmp10
    tl.store(out_ptr2 + (r1 + 17 * x0), tmp11, rmask & xmask)


@triton.jit
def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 816
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 17 % 12
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x3, tmp2, xmask)


@triton.jit
def triton_poi_fused_convolution_6(in_ptr0, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 17
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x2 = xindex
    y0 = yindex % 4
    y1 = yindex // 4
    y3 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 68 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tl.store(out_ptr0 + (x2 + 17 * y3), tmp0, xmask & ymask)


@triton.jit
def triton_poi_fused_convolution_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 272
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 17 % 4
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x3, tmp2, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 17), (17, 1))
    assert_size_stride(primals_3, (12, 4, 1), (4, 1, 1))
    assert_size_stride(primals_4, (12,), (1,))
    assert_size_stride(primals_5, (4, 4, 1), (4, 1, 1))
    assert_size_stride(primals_6, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
        get_raw_stream(0)
        triton_per_fused_mean_0[grid(16)](primals_1, buf0, 16, 16, XBLOCK=1,
            num_warps=2, num_stages=1)
        buf1 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32)
        triton_poi_fused_add_cat_1[grid(272)](buf0, primals_1, primals_2,
            buf1, 272, XBLOCK=256, num_warps=4, num_stages=1)
        del buf0
        del primals_1
        del primals_2
        buf2 = extern_kernels.convolution(buf1, primals_3, stride=(1,),
            padding=(0,), dilation=(1,), transposed=False, output_padding=(
            0,), groups=1, bias=None)
        assert_size_stride(buf2, (4, 12, 17), (204, 17, 1))
        buf3 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32)
        triton_poi_fused_mul_2[grid(272)](buf2, primals_4, buf3, 272,
            XBLOCK=128, num_warps=4, num_stages=1)
        buf4 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32)
        triton_poi_fused_mul_3[grid(272)](buf2, primals_4, buf4, 272,
            XBLOCK=256, num_warps=4, num_stages=1)
        buf5 = empty_strided_cuda((4, 17, 17), (289, 17, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf3, (4, 17, 4), (68, 1, 17),
            0), buf4, out=buf5)
        buf8 = empty_strided_cuda((4, 17, 17), (289, 17, 1), torch.float32)
        triton_per_fused__softmax_4[grid(68)](buf5, buf8, 68, 17, XBLOCK=8,
            num_warps=2, num_stages=1)
        del buf5
        buf9 = buf2
        del buf2
        triton_poi_fused_convolution_5[grid(816)](buf9, primals_4, 816,
            XBLOCK=256, num_warps=4, num_stages=1)
        del primals_4
        buf10 = empty_strided_cuda((4, 17, 4), (68, 4, 1), torch.float32)
        extern_kernels.bmm(buf8, reinterpret_tensor(buf9, (4, 17, 4), (204,
            1, 17), 136), out=buf10)
        buf11 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32)
        triton_poi_fused_convolution_6[grid(16, 17)](buf10, buf11, 16, 17,
            XBLOCK=32, YBLOCK=16, num_warps=4, num_stages=1)
        buf12 = extern_kernels.convolution(buf11, primals_5, stride=(1,),
            padding=(0,), dilation=(1,), transposed=False, output_padding=(
            0,), groups=1, bias=None)
        assert_size_stride(buf12, (4, 4, 17), (68, 17, 1))
        del buf11
        buf13 = buf12
        del buf12
        triton_poi_fused_convolution_7[grid(272)](buf13, primals_6, 272,
            XBLOCK=128, num_warps=4, num_stages=1)
        del primals_6
    return reinterpret_tensor(buf13, (4, 4), (68, 17), 0
        ), primals_3, primals_5, buf1, buf8, reinterpret_tensor(buf10, (4, 
        4, 17), (68, 1, 4), 0), reinterpret_tensor(buf9, (4, 4, 17), (204, 
        17, 1), 136), buf3, reinterpret_tensor(buf4, (4, 17, 4), (68, 1, 17), 0
        )


def count_flops_attn(model, _x, y):
    """
    A counter for the `thop` package to count the operations in an
    attention operation.
    Meant to be used like:
        macs, params = thop.profile(
            model,
            inputs=(inputs, timestamps),
            custom_ops={QKVAttention: QKVAttention.count_flops},
        )
    """
    b, c, *spatial = y[0].shape
    num_spatial = int(np.prod(spatial))
    matmul_ops = 2 * b * num_spatial ** 2 * c
    model.total_ops += th.DoubleTensor([matmul_ops])


def conv_nd(dims, *args, **kwargs):
    """
    Create a 1D, 2D, or 3D convolution module.
    """
    if dims == 1:
        return nn.Conv1d(*args, **kwargs)
    elif dims == 2:
        return nn.Conv2d(*args, **kwargs)
    elif dims == 3:
        return nn.Conv3d(*args, **kwargs)
    raise ValueError(f'unsupported dimensions: {dims}')


class QKVAttention(nn.Module):
    """
    A module which performs QKV attention and splits in a different order.
    """

    def __init__(self, n_heads):
        super().__init__()
        self.n_heads = n_heads

    def forward(self, qkv):
        """
        Apply QKV attention.

        :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
        :return: an [N x (H * C) x T] tensor after attention.
        """
        bs, width, length = qkv.shape
        assert width % (3 * self.n_heads) == 0
        ch = width // (3 * self.n_heads)
        q, k, v = qkv.chunk(3, dim=1)
        scale = 1 / math.sqrt(math.sqrt(ch))
        weight = th.einsum('bct,bcs->bts', (q * scale).view(bs * self.
            n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch,
            length))
        weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
        a = th.einsum('bts,bcs->bct', weight, v.reshape(bs * self.n_heads,
            ch, length))
        return a.reshape(bs, -1, length)

    @staticmethod
    def count_flops(model, _x, y):
        return count_flops_attn(model, _x, y)


class AttentionPool2dNew(nn.Module):
    """
    Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
    """

    def __init__(self, spacial_dim: 'int', embed_dim: 'int',
        num_heads_channels: 'int', output_dim: 'int'=None):
        super().__init__()
        self.positional_embedding = nn.Parameter(th.randn(embed_dim, 
            spacial_dim ** 2 + 1) / embed_dim ** 0.5)
        self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
        self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
        self.num_heads = embed_dim // num_heads_channels
        self.attention = QKVAttention(self.num_heads)

    def forward(self, input_0):
        primals_2 = self.positional_embedding
        primals_3 = self.qkv_proj.weight
        primals_4 = self.qkv_proj.bias
        primals_5 = self.c_proj.weight
        primals_6 = self.c_proj.bias
        primals_1 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6])
        return output[0]


Measured latency_ms: 0.021163