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 torch.nn as nn
import torch.nn.functional as F
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_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 64
    xnumel = 4
    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 + 16 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)


@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, 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 % 4
    x3 = xindex // 64
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (x1 + 4 * x0 + 16 * x3), xmask,
        eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(out_ptr0 + x4, tmp2, xmask)


@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 1024
    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)
    tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp1 = 1.0
    tmp2 = tmp0 * tmp1
    tmp4 = tmp3 * tmp1
    tmp6 = tmp5 * tmp1
    tmp7 = triton_helpers.maximum(tmp4, tmp6)
    tmp9 = tmp8 * tmp1
    tmp10 = triton_helpers.maximum(tmp7, tmp9)
    tmp12 = tmp11 * tmp1
    tmp13 = triton_helpers.maximum(tmp10, tmp12)
    tmp14 = tmp2 - tmp13
    tmp15 = tmp14 * tmp1
    tmp16 = tl_math.exp(tmp15)
    tl.store(out_ptr0 + x2, tmp16, xmask)


@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 1024
    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_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
    constexpr, XBLOCK: tl.constexpr):
    ynumel = 64
    xnumel = 4
    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 + 16 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7, primals_8, primals_9, primals_10, primals_11) = 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,))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4,), (1,))
    assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_7, (4, 4), (4, 1))
    assert_size_stride(primals_8, (4,), (1,))
    assert_size_stride(primals_9, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_10, (4, 4), (4, 1))
    assert_size_stride(primals_11, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
            reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
        del primals_2
        buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0),
            reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
        del primals_4
        buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_9, (64, 4), (4, 1), 0),
            reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
        del primals_7
        buf3 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
            .float32)
        get_raw_stream(0)
        triton_poi_fused_clone_0[grid(64, 4)](buf0, primals_3, buf3, 64, 4,
            XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
        del primals_3
        buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1, 4), (64, 16, 4, 4, 1), 0)
        del buf0
        triton_poi_fused_clone_1[grid(256)](buf1, primals_5, buf4, 256,
            XBLOCK=128, num_warps=4, num_stages=1)
        del buf1
        del primals_5
        buf5 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf3, (64, 4, 1), (4, 1, 0), 
            0), reinterpret_tensor(buf4, (64, 1, 4), (4, 0, 1), 0), out=buf5)
        buf6 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
            torch.float32)
        triton_poi_fused__softmax_2[grid(1024)](buf5, buf6, 1024, XBLOCK=
            256, num_warps=4, num_stages=1)
        buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0
            )
        del buf5
        triton_poi_fused__softmax_3[grid(1024)](buf6, buf7, 1024, XBLOCK=
            128, num_warps=4, num_stages=1)
        del buf6
        buf8 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
            .float32)
        triton_poi_fused_clone_0[grid(64, 4)](buf2, primals_8, buf8, 64, 4,
            XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
        del primals_8
        buf9 = reinterpret_tensor(buf2, (64, 4, 1), (4, 1, 1), 0)
        del buf2
        extern_kernels.bmm(reinterpret_tensor(buf7, (64, 4, 4), (16, 4, 1),
            0), reinterpret_tensor(buf8, (64, 4, 1), (4, 1, 0), 0), out=buf9)
        buf10 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1),
            torch.float32)
        triton_poi_fused_clone_4[grid(64, 4)](buf9, buf10, 64, 4, XBLOCK=4,
            YBLOCK=32, num_warps=4, num_stages=1)
        buf11 = reinterpret_tensor(buf9, (64, 4), (4, 1), 0)
        del buf9
        extern_kernels.addmm(primals_11, reinterpret_tensor(buf10, (64, 4),
            (4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
            alpha=1, beta=1, out=buf11)
        del primals_11
    return reinterpret_tensor(buf11, (4, 16, 4), (64, 4, 1), 0
        ), buf7, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
        ), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
        ), reinterpret_tensor(primals_9, (64, 4), (4, 1), 0
        ), buf7, reinterpret_tensor(buf10, (64, 4), (4, 1), 0
        ), primals_10, reinterpret_tensor(buf8, (64, 1, 4), (4, 1, 1), 0
        ), reinterpret_tensor(buf3, (64, 1, 4), (4, 1, 1), 0
        ), reinterpret_tensor(buf4, (64, 4, 1), (4, 1, 4), 0)


class Linear(nn.Linear):

    def __init__(self, in_features, out_features, bias=True):
        super(Linear, self).__init__(in_features=in_features, out_features=
            out_features, bias=bias)
        self.noise = None
        self.vn_std = None

    def init_vn(self, vn_std):
        self.vn_std = vn_std

    def sample_synaptic_noise(self, distributed):
        self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(
            ), device=self.weight.device, dtype=self.weight.dtype)
        if distributed:
            torch.distributed.broadcast(self.noise, 0)

    def forward(self, input):
        weight = self.weight
        if self.noise is not None and self.training:
            weight = weight + self.vn_std * self.noise
        return F.linear(input, weight, self.bias)


class MultiHeadAttention(nn.Module):
    """Mutli-Head Attention Layer

    Args:
        dim_model: model feature dimension
        num_heads: number of attention heads

    References: 
        Attention Is All You Need, Vaswani et al.
        https://arxiv.org/abs/1706.03762

    """

    def __init__(self, dim_model, num_heads):
        super(MultiHeadAttention, self).__init__()
        self.num_heads = num_heads
        self.dim_model = dim_model
        self.dim_head = dim_model // num_heads
        self.query_layer = Linear(self.dim_model, self.dim_model)
        self.key_layer = Linear(self.dim_model, self.dim_model)
        self.value_layer = Linear(self.dim_model, self.dim_model)
        self.output_layer = Linear(self.dim_model, self.dim_model)

    def forward(self, Q, K, V, mask=None):
        """Scaled Dot-Product Multi-Head Attention

        Args:
            Q: Query of shape (B, T, D)
            K: Key of shape (B, T, D)
            V: Value of shape (B, T, D)
            mask: Optional position mask of shape (1 or B, 1 or H, 1 or T, 1 or T)
        
        Return:
            O: Attention output of shape (B, T, D)
            att_w: Attention weights of shape (B, H, T, T)

        """
        batch_size = Q.size(0)
        Q = self.query_layer(Q)
        K = self.key_layer(K)
        V = self.value_layer(V)
        Q = Q.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
            1, 2)
        K = K.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
            1, 2)
        V = V.reshape(batch_size, -1, self.num_heads, self.dim_head).transpose(
            1, 2)
        att_scores = Q.matmul(K.transpose(2, 3)) / K.shape[-1] ** 0.5
        if mask is not None:
            att_scores += mask * -1000000000.0
        att_w = att_scores.softmax(dim=-1)
        O = att_w.matmul(V)
        O = O.transpose(1, 2).reshape(batch_size, -1, self.dim_model)
        O = self.output_layer(O)
        return O, att_w.detach()

    def pad(self, Q, K, V, mask, chunk_size):
        overflow_Q = Q.size(1) % chunk_size
        overflow_KV = K.size(1) % chunk_size
        padding_Q = chunk_size - overflow_Q if overflow_Q else 0
        padding_KV = chunk_size - overflow_KV if overflow_KV else 0
        batch_size, seq_len_KV, _ = K.size()
        Q = F.pad(Q, (0, 0, 0, padding_Q), value=0)
        K = F.pad(K, (0, 0, 0, padding_KV), value=0)
        V = F.pad(V, (0, 0, 0, padding_KV), value=0)
        if mask is not None:
            if mask.size(2) == 1:
                mask = F.pad(mask, pad=(0, padding_KV), value=1)
            else:
                mask = F.pad(mask, pad=(0, padding_Q, 0, padding_KV), value=1)
        elif padding_KV:
            mask = F.pad(Q.new_zeros(batch_size, 1, 1, seq_len_KV), pad=(0,
                padding_KV), value=1)
        return Q, K, V, mask, padding_Q


class LocalMultiHeadAttentionNew(MultiHeadAttention):
    """Local Multi-Head Attention Layer

    Local multi-head attention restricts the attended positions to a local neighborhood 
    around the query position. This is achieved by segmenting the hidden sequence into 
    non overlapping blocks of size K and performing scaled dot-product attention in 
    parallel for each of these blocks.

    Args:
        dim_model: model feature dimension
        num_heads: number of attention heads
        kernel_size: attention kernel size / window 

    References:
        Image Transformer, Parmar et al.
        https://arxiv.org/abs/1802.05751

    """

    def __init__(self, dim_model, num_heads, kernel_size):
        super(LocalMultiHeadAttentionNew, self).__init__(dim_model, num_heads)
        self.kernel_size = kernel_size

    def forward(self, input_0, input_1, input_2):
        primals_2 = self.query_layer.weight
        primals_3 = self.query_layer.bias
        primals_4 = self.key_layer.weight
        primals_5 = self.key_layer.bias
        primals_7 = self.value_layer.weight
        primals_8 = self.value_layer.bias
        primals_10 = self.output_layer.weight
        primals_11 = self.output_layer.bias
        primals_1 = input_0
        primals_6 = input_1
        primals_9 = input_2
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7, primals_8, primals_9,
            primals_10, primals_11])
        return output[0], output[1]


Measured latency_ms: 0.036991