# AOT ID: ['0_forward']
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_1/inductor_cache/gh/cghdn4pihhs4yx6f6a4ig3pjgfy5zh6dghclq5xeandkuwdvuk5c.py
# Topologically Sorted Source Nodes: [contiguous], Original ATen: [aten.clone]
# Source node to ATen node mapping:
#   contiguous => clone_3
# Graph fragment:
#   %clone_3 : [num_users=1] = call_function[target=torch.ops.aten.clone.default](args = (%permute_7,), kwargs = {memory_format: torch.contiguous_format})
triton_poi_fused_clone_0 = async_compile.triton('triton_poi_fused_clone_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.pointwise(
    size_hints=[256], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_clone_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_clone_0(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
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (x0), xmask)
    tl.store(out_ptr0 + (x0), tmp0, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

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), (16, 4, 1))
    assert_size_stride(primals_2, (16, 4), (4, 1))
    assert_size_stride(primals_3, (16, ), (1, ))
    assert_size_stride(primals_4, (16, 4), (4, 1))
    assert_size_stride(primals_5, (16, ), (1, ))
    assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_7, (16, 4), (4, 1))
    assert_size_stride(primals_8, (16, ), (1, ))
    assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_10, (4, 16), (16, 1))
    assert_size_stride(primals_11, (4, ), (1, ))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        # Topologically Sorted Source Nodes: [linear], Original ATen: [aten.addmm]
        extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf0)
        del primals_2
        del primals_3
        buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        # Topologically Sorted Source Nodes: [linear_1], Original ATen: [aten.addmm]
        extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf1)
        del primals_4
        del primals_5
        buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        # Topologically Sorted Source Nodes: [linear_2], Original ATen: [aten.addmm]
        extern_kernels.addmm(primals_8, reinterpret_tensor(primals_9, (16, 4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf2)
        del primals_7
        del primals_8
        # Topologically Sorted Source Nodes: [], Original ATen: []
        buf3 = torch.ops.aten._scaled_dot_product_efficient_attention.default(reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), None, True, scale=0.5)
        buf4 = buf3[0]
        buf5 = buf3[1]
        buf6 = buf3[2]
        buf7 = buf3[3]
        del buf3
        buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [contiguous], Original ATen: [aten.clone]
        stream0 = get_raw_stream(0)
        triton_poi_fused_clone_0.run(buf4, buf8, 256, grid=grid(256), stream=stream0)
        buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [linear_3], Original ATen: [aten.addmm]
        extern_kernels.addmm(primals_11, reinterpret_tensor(buf8, (16, 16), (16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0), alpha=1, beta=1, out=buf9)
        del primals_11
    return (reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), buf4, buf5, buf6, buf7, reinterpret_tensor(buf8, (16, 16), (16, 1), 0), primals_10, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 4, 4), (16, 4, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((16, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((16, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((16, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_5 = rand_strided((16, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_6 = rand_strided((4, 4, 4), (16, 4, 1), device='cuda:0', dtype=torch.float32)
    primals_7 = rand_strided((16, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_8 = rand_strided((16, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_9 = rand_strided((4, 4, 4), (16, 4, 1), device='cuda:0', dtype=torch.float32)
    primals_10 = rand_strided((4, 16), (16, 1), device='cuda:0', dtype=torch.float32)
    primals_11 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11])
    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 math
import torch
from torch import nn
from torch.nn import functional as F
from numpy import inf
from math import inf


def Linear(in_features, out_features, bias=True):
    m = nn.Linear(in_features, out_features, bias)
    nn.init.xavier_uniform_(m.weight)
    if bias:
        nn.init.constant_(m.bias, 0.0)
    return m


class MultiHeadAttention(nn.Module):

    def __init__(self, d_model, d_qk, d_v, num_head):
        super().__init__()
        self.d_model = d_model
        self.num_head = num_head
        self.d_qk = d_qk
        self.d_v = d_v
        self.W_Q = Linear(d_model, num_head * d_qk)
        self.W_K = Linear(d_model, num_head * d_qk)
        self.W_V = Linear(d_model, num_head * d_v)
        self.W_out = Linear(d_v * num_head, d_model)

    def ScaledDotProductAttention(self, query, keys, values, mask=None):
        score = torch.matmul(query, keys.transpose(-1, -2)) / math.sqrt(self
            .d_model)
        if mask is not None:
            score.masked_fill_(mask.unsqueeze(1), -inf)
        weight = F.softmax(score, dim=-1)
        return torch.matmul(weight, values)

    def forward(self, Q, K, V, mask=None):
        batch_size = Q.size(0)
        query = self.W_Q(Q).view(batch_size, Q.size(1), self.num_head, self
            .d_qk)
        keys = self.W_K(K).view(batch_size, K.size(1), self.num_head, self.d_qk
            )
        values = self.W_V(V).view(batch_size, V.size(1), self.num_head,
            self.d_v)
        query.transpose_(1, 2)
        keys.transpose_(1, 2)
        values.transpose_(1, 2)
        outputs = self.ScaledDotProductAttention(query, keys, values, mask)
        del query, keys, values
        outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
            self.d_v * self.num_head)
        return self.W_out(outputs)

    def cal_one_vector(self, vector, memory, memory_new, i):
        batch_size = vector.size(0)
        query = self.W_Q(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_qk)
        key = self.W_K(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_qk)
        value = self.W_V(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_v)
        query.transpose_(1, 2)
        key.transpose_(1, 2)
        value.transpose_(1, 2)
        outputs = torch.cat((key.unsqueeze(-1), value.unsqueeze(-1)), dim=-1)
        del key, value
        if memory is not None:
            if memory_new is None:
                memory_new = torch.cat((memory[:, i, ...], outputs), dim=2
                    ).unsqueeze(1)
            else:
                _m = torch.cat((memory[:, i, ...], outputs), dim=2)
                memory_new = torch.cat((memory_new, _m.unsqueeze(1)), dim=1)
        elif memory_new is None:
            memory_new = outputs.unsqueeze(1)
        else:
            memory_new = torch.cat((memory_new, outputs.unsqueeze(1)), dim=1)
        outputs = self.ScaledDotProductAttention(query, memory_new[:, i,
            ..., 0], memory_new[:, i, ..., 1])
        outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
            self.d_v * self.num_head)
        return self.W_out(outputs), memory_new


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


def get_init_inputs():
    return [[], {'d_model': 4, 'd_qk': 4, 'd_v': 4, 'num_head': 4}]

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
import math
from torch import nn
from torch.nn import functional as F
from numpy import inf
from math import inf
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, 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
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tl.store(out_ptr0 + x0, tmp0, xmask)


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), (16, 4, 1))
    assert_size_stride(primals_2, (16, 4), (4, 1))
    assert_size_stride(primals_3, (16,), (1,))
    assert_size_stride(primals_4, (16, 4), (4, 1))
    assert_size_stride(primals_5, (16,), (1,))
    assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_7, (16, 4), (4, 1))
    assert_size_stride(primals_8, (16,), (1,))
    assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_10, (4, 16), (16, 1))
    assert_size_stride(primals_11, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (16, 
            4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 16), (1, 4), 
            0), alpha=1, beta=1, out=buf0)
        del primals_2
        del primals_3
        buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (16, 
            4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 16), (1, 4), 
            0), alpha=1, beta=1, out=buf1)
        del primals_4
        del primals_5
        buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
        extern_kernels.addmm(primals_8, reinterpret_tensor(primals_9, (16, 
            4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 16), (1, 4), 
            0), alpha=1, beta=1, out=buf2)
        del primals_7
        del primals_8
        buf3 = torch.ops.aten._scaled_dot_product_efficient_attention.default(
            reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0),
            reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0),
            reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), None,
            True, scale=0.5)
        buf4 = buf3[0]
        buf5 = buf3[1]
        buf6 = buf3[2]
        buf7 = buf3[3]
        del buf3
        buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_clone_0[grid(256)](buf4, buf8, 256, XBLOCK=128,
            num_warps=4, num_stages=1)
        buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_11, reinterpret_tensor(buf8, (16, 16),
            (16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0
            ), alpha=1, beta=1, out=buf9)
        del primals_11
    return reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0
        ), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
        ), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
        ), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
        ), reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0
        ), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0
        ), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0
        ), buf4, buf5, buf6, buf7, reinterpret_tensor(buf8, (16, 16), (16, 
        1), 0), primals_10


def Linear(in_features, out_features, bias=True):
    m = nn.Linear(in_features, out_features, bias)
    nn.init.xavier_uniform_(m.weight)
    if bias:
        nn.init.constant_(m.bias, 0.0)
    return m


class MultiHeadAttentionNew(nn.Module):

    def __init__(self, d_model, d_qk, d_v, num_head):
        super().__init__()
        self.d_model = d_model
        self.num_head = num_head
        self.d_qk = d_qk
        self.d_v = d_v
        self.W_Q = Linear(d_model, num_head * d_qk)
        self.W_K = Linear(d_model, num_head * d_qk)
        self.W_V = Linear(d_model, num_head * d_v)
        self.W_out = Linear(d_v * num_head, d_model)

    def ScaledDotProductAttention(self, query, keys, values, mask=None):
        score = torch.matmul(query, keys.transpose(-1, -2)) / math.sqrt(self
            .d_model)
        if mask is not None:
            score.masked_fill_(mask.unsqueeze(1), -inf)
        weight = F.softmax(score, dim=-1)
        return torch.matmul(weight, values)

    def cal_one_vector(self, vector, memory, memory_new, i):
        batch_size = vector.size(0)
        query = self.W_Q(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_qk)
        key = self.W_K(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_qk)
        value = self.W_V(vector).view(batch_size, vector.size(1), self.
            num_head, self.d_v)
        query.transpose_(1, 2)
        key.transpose_(1, 2)
        value.transpose_(1, 2)
        outputs = torch.cat((key.unsqueeze(-1), value.unsqueeze(-1)), dim=-1)
        del key, value
        if memory is not None:
            if memory_new is None:
                memory_new = torch.cat((memory[:, i, ...], outputs), dim=2
                    ).unsqueeze(1)
            else:
                _m = torch.cat((memory[:, i, ...], outputs), dim=2)
                memory_new = torch.cat((memory_new, _m.unsqueeze(1)), dim=1)
        elif memory_new is None:
            memory_new = outputs.unsqueeze(1)
        else:
            memory_new = torch.cat((memory_new, outputs.unsqueeze(1)), dim=1)
        outputs = self.ScaledDotProductAttention(query, memory_new[:, i,
            ..., 0], memory_new[:, i, ..., 1])
        outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
            self.d_v * self.num_head)
        return self.W_out(outputs), memory_new

    def forward(self, input_0, input_1, input_2):
        primals_2 = self.W_Q.weight
        primals_3 = self.W_Q.bias
        primals_4 = self.W_K.weight
        primals_5 = self.W_K.bias
        primals_7 = self.W_V.weight
        primals_8 = self.W_V.bias
        primals_10 = self.W_out.weight
        primals_11 = self.W_out.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]
