# AOT ID: ['0_inference']
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/bx/cbxqbi5x6ergwgugds2mtfqlbo6szwuxtzsbdvjl73lycn3nina2.py
# Topologically Sorted Source Nodes: [eq, attn_score_3, attn_score_2, attn_score_4], Original ATen: [aten.eq, aten.masked_fill, aten.mul, aten._softmax]
# Source node to ATen node mapping:
#   attn_score_2 => mul
#   attn_score_3 => full_default, where
#   attn_score_4 => amax, exp, sub, sum_1
#   eq => eq
# Graph fragment:
#   %eq : [num_users=1] = call_function[target=torch.ops.aten.eq.Scalar](args = (%arg2_1, 0), kwargs = {})
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], -9.999999843067494e+17), kwargs = {dtype: torch.float32, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%squeeze, %arg2_1), kwargs = {})
#   %where : [num_users=2] = call_function[target=torch.ops.aten.where.self](args = (%eq, %full_default, %mul), kwargs = {})
#   %amax : [num_users=1] = call_function[target=torch.ops.aten.amax.default](args = (%where, [1], True), kwargs = {})
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%where, %amax), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%sub,), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%exp, [1], True), kwargs = {})
triton_poi_fused__softmax_eq_masked_fill_mul_0 = async_compile.triton('triton_poi_fused__softmax_eq_masked_fill_mul_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=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '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, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__softmax_eq_masked_fill_mul_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 8, '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__softmax_eq_masked_fill_mul_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (4*x0), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (4*x0), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr0 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr1 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp15 = tl.load(in_ptr1 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp19 = tl.load(in_ptr0 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp21 = tl.load(in_ptr1 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp1 = 0.0
    tmp2 = tmp0 == tmp1
    tmp4 = tmp3 * tmp0
    tmp5 = -9.999999843067494e+17
    tmp6 = tl.where(tmp2, tmp5, tmp4)
    tmp8 = tmp7 == tmp1
    tmp10 = tmp9 * tmp7
    tmp11 = tl.where(tmp8, tmp5, tmp10)
    tmp12 = triton_helpers.maximum(tmp6, tmp11)
    tmp14 = tmp13 == tmp1
    tmp16 = tmp15 * tmp13
    tmp17 = tl.where(tmp14, tmp5, tmp16)
    tmp18 = triton_helpers.maximum(tmp12, tmp17)
    tmp20 = tmp19 == tmp1
    tmp22 = tmp21 * tmp19
    tmp23 = tl.where(tmp20, tmp5, tmp22)
    tmp24 = triton_helpers.maximum(tmp18, tmp23)
    tmp25 = tmp6 - tmp24
    tmp26 = tl_math.exp(tmp25)
    tmp27 = tmp11 - tmp24
    tmp28 = tl_math.exp(tmp27)
    tmp29 = tmp26 + tmp28
    tmp30 = tmp17 - tmp24
    tmp31 = tl_math.exp(tmp30)
    tmp32 = tmp29 + tmp31
    tmp33 = tmp23 - tmp24
    tmp34 = tl_math.exp(tmp33)
    tmp35 = tmp32 + tmp34
    tl.store(out_ptr0 + (x0), tmp24, xmask)
    tl.store(out_ptr1 + (x0), tmp35, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/pp/cppjz4dxuvgrncmxnw5kpreuob3rkj7zd6kq3uth6xbedmtz2f3j.py
# Topologically Sorted Source Nodes: [eq_1, attn_score_5, eq, attn_score_3, attn_score_2, attn_score_4], Original ATen: [aten.eq, aten.masked_fill, aten.mul, aten._softmax]
# Source node to ATen node mapping:
#   attn_score_2 => mul
#   attn_score_3 => full_default, where
#   attn_score_4 => amax, div, exp, sub
#   attn_score_5 => full_default_1, where_1
#   eq => eq
#   eq_1 => eq_1
# Graph fragment:
#   %eq_1 : [num_users=1] = call_function[target=torch.ops.aten.eq.Scalar](args = (%arg2_1, 0), kwargs = {})
#   %full_default_1 : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], 0.0), kwargs = {dtype: torch.float32, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %eq : [num_users=1] = call_function[target=torch.ops.aten.eq.Scalar](args = (%arg2_1, 0), kwargs = {})
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], -9.999999843067494e+17), kwargs = {dtype: torch.float32, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%squeeze, %arg2_1), kwargs = {})
#   %where : [num_users=2] = call_function[target=torch.ops.aten.where.self](args = (%eq, %full_default, %mul), kwargs = {})
#   %amax : [num_users=1] = call_function[target=torch.ops.aten.amax.default](args = (%where, [1], True), kwargs = {})
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%where, %amax), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%sub,), kwargs = {})
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%exp, %sum_1), kwargs = {})
#   %where_1 : [num_users=2] = call_function[target=torch.ops.aten.where.self](args = (%eq_1, %full_default_1, %div), kwargs = {})
triton_poi_fused__softmax_eq_masked_fill_mul_1 = async_compile.triton('triton_poi_fused__softmax_eq_masked_fill_mul_1', '''
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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '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, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__softmax_eq_masked_fill_mul_1', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 4, '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__softmax_eq_masked_fill_mul_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    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_out_ptr0 + (x2), xmask)
    tmp7 = tl.load(in_ptr1 + (x1), xmask, eviction_policy='evict_last')
    tmp10 = tl.load(in_ptr2 + (x1), xmask, eviction_policy='evict_last')
    tmp1 = 0.0
    tmp2 = tmp0 == tmp1
    tmp4 = tmp3 * tmp0
    tmp5 = -9.999999843067494e+17
    tmp6 = tl.where(tmp2, tmp5, tmp4)
    tmp8 = tmp6 - tmp7
    tmp9 = tl_math.exp(tmp8)
    tmp11 = tmp9 / tmp10
    tmp12 = tl.where(tmp2, tmp1, tmp11)
    tl.store(in_out_ptr0 + (x2), tmp12, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/qe/cqeeiitmvmc7ui53bm5y7a4byl7ns254nr75puduye6fahglzoyw.py
# Topologically Sorted Source Nodes: [mul_1, attn_memory], Original ATen: [aten.mul, aten.sum]
# Source node to ATen node mapping:
#   attn_memory => sum_2
#   mul_1 => mul_1
# Graph fragment:
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%unsqueeze_1, %arg3_1), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_1, [1]), kwargs = {})
triton_poi_fused_mul_sum_2 = async_compile.triton('triton_poi_fused_mul_sum_2', '''
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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '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, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_mul_sum_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 8, '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_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = (xindex // 4)
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (4*x1), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (x0), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (1 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr0 + (2 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (3 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 * tmp1
    tmp5 = tmp3 * tmp4
    tmp6 = tmp2 + tmp5
    tmp9 = tmp7 * tmp8
    tmp10 = tmp6 + tmp9
    tmp13 = tmp11 * tmp12
    tmp14 = tmp10 + tmp13
    tl.store(out_ptr0 + (x2), tmp14, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    assert_size_stride(arg3_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [attn_score], Original ATen: [aten.bmm]
        extern_kernels.bmm(arg0_1, reinterpret_tensor(arg1_1, (4, 4, 1), (4, 1, 1), 0), out=buf0)
        del arg0_1
        del arg1_1
        buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
        buf2 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
        # Topologically Sorted Source Nodes: [eq, attn_score_3, attn_score_2, attn_score_4], Original ATen: [aten.eq, aten.masked_fill, aten.mul, aten._softmax]
        stream0 = get_raw_stream(0)
        triton_poi_fused__softmax_eq_masked_fill_mul_0.run(arg2_1, buf0, buf1, buf2, 4, grid=grid(4), stream=stream0)
        buf3 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0); del buf0  # reuse
        # Topologically Sorted Source Nodes: [eq_1, attn_score_5, eq, attn_score_3, attn_score_2, attn_score_4], Original ATen: [aten.eq, aten.masked_fill, aten.mul, aten._softmax]
        triton_poi_fused__softmax_eq_masked_fill_mul_1.run(buf3, arg2_1, buf1, buf2, 16, grid=grid(16), stream=stream0)
        del arg2_1
        del buf1
        del buf2
        buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [mul_1, attn_memory], Original ATen: [aten.mul, aten.sum]
        triton_poi_fused_mul_sum_2.run(buf3, arg3_1, buf4, 16, grid=grid(16), stream=stream0)
        del arg3_1
    return (buf3, buf4, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4, 4), (16, 4, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    arg2_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    arg3_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1, arg2_1, arg3_1])
    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 torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data


class GlobalAttention(nn.Module):
    """
  Global attention takes a matrix and a query vector. It
  then computes a parameterized convex combination of the matrix
  based on the input query.

  Constructs a unit mapping a query `q` of size `dim`
  and a source matrix `H` of size `n x dim`, 
  to an output of size `dim`.

  All models compute the output as
  :math:`c = sum_{j=1}^{SeqLength} a_j H_j` where
  :math:`a_j` is the softmax of a score function.

  However they differ on how they compute the attention score.

  * Luong Attention (dot, general):
     * dot: :math:`score(H_j,q) = H_j^T q`
     * general: :math:`score(H_j, q) = H_j^T W_a q`

  * Bahdanau Attention (mlp):
     * :math:`score(H_j, q) = w_a^T tanh(W_a q + U_a h_j)`

  Args:
     attn_size (int): dimensionality of query and key
     attn_type (str): type of attention to use, options [dot,general,mlp]
  """

    def __init__(self, query_size, attn_size, attn_type='dot'):
        super(GlobalAttention, self).__init__()
        self.query_size = query_size
        self.attn_size = attn_size
        self.attn_type = attn_type
        if self.attn_type == 'general':
            self.linear_in = nn.Linear(query_size, attn_size, bias=False)
        elif self.attn_type == 'mlp':
            self.linear_query = nn.Linear(query_size, attn_size, bias=True)
            self.attn_w = nn.Linear(attn_size, 1, bias=False)
        elif self.attn_type == 'dot':
            assert self.query_size == self.attn_size

    def forward(self, query, memory_keys, memory_values, memory_masks):
        """
    Args:
      query (`FloatTensor`): (batch, query_size)
      memory_keys (`FloatTensor`): (batch, seq_len, attn_size)
      memory_values (`FloatTensor`): (batch, seq_len, attn_size)
      memory_masks (`LongTensor`): (batch, seq_len)

    Returns:
      attn_score: attention distributions (batch, seq_len)
      attn_memory: computed context vector, (batch, attn_size)
    """
        batch_size, seq_len, attn_size = memory_keys.size()
        if self.attn_type == 'mlp':
            query_hidden = self.linear_query(query.unsqueeze(1)).expand(
                batch_size, seq_len, attn_size)
            attn_hidden = torch.tanh(query_hidden + memory_keys)
            attn_score = self.attn_w(attn_hidden)
        elif self.attn_type == 'dot':
            attn_score = torch.bmm(memory_keys, query.unsqueeze(2))
        elif self.attn_type == 'general':
            query_hidden = self.linear_in(query)
            attn_score = torch.bmm(memory_keys, query_hidden.unsqueeze(2))
        attn_score = attn_score.squeeze(2)
        if memory_masks is not None:
            attn_score = attn_score * memory_masks
            attn_score = attn_score.masked_fill(memory_masks == 0, -1e+18)
        attn_score = F.softmax(attn_score, dim=1)
        if memory_masks is not None:
            attn_score = attn_score.masked_fill(memory_masks == 0, 0)
        attn_memory = torch.sum(attn_score.unsqueeze(2) * memory_values, 1)
        return attn_score, attn_memory


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


def get_init_inputs():
    return [[], {'query_size': 4, 'attn_size': 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
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.utils.data
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__softmax_eq_masked_fill_mul_0(in_ptr0, in_ptr1,
    out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp15 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp19 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp21 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp1 = 0.0
    tmp2 = tmp0 == tmp1
    tmp4 = tmp3 * tmp0
    tmp5 = -9.999999843067494e+17
    tmp6 = tl.where(tmp2, tmp5, tmp4)
    tmp8 = tmp7 == tmp1
    tmp10 = tmp9 * tmp7
    tmp11 = tl.where(tmp8, tmp5, tmp10)
    tmp12 = triton_helpers.maximum(tmp6, tmp11)
    tmp14 = tmp13 == tmp1
    tmp16 = tmp15 * tmp13
    tmp17 = tl.where(tmp14, tmp5, tmp16)
    tmp18 = triton_helpers.maximum(tmp12, tmp17)
    tmp20 = tmp19 == tmp1
    tmp22 = tmp21 * tmp19
    tmp23 = tl.where(tmp20, tmp5, tmp22)
    tmp24 = triton_helpers.maximum(tmp18, tmp23)
    tmp25 = tmp6 - tmp24
    tmp26 = tl_math.exp(tmp25)
    tmp27 = tmp11 - tmp24
    tmp28 = tl_math.exp(tmp27)
    tmp29 = tmp26 + tmp28
    tmp30 = tmp17 - tmp24
    tmp31 = tl_math.exp(tmp30)
    tmp32 = tmp29 + tmp31
    tmp33 = tmp23 - tmp24
    tmp34 = tl_math.exp(tmp33)
    tmp35 = tmp32 + tmp34
    tl.store(out_ptr0 + x0, tmp24, xmask)
    tl.store(out_ptr1 + x0, tmp35, xmask)


@triton.jit
def triton_poi_fused__softmax_eq_masked_fill_mul_1(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    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_out_ptr0 + x2, xmask)
    tmp7 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp10 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
    tmp1 = 0.0
    tmp2 = tmp0 == tmp1
    tmp4 = tmp3 * tmp0
    tmp5 = -9.999999843067494e+17
    tmp6 = tl.where(tmp2, tmp5, tmp4)
    tmp8 = tmp6 - tmp7
    tmp9 = tl_math.exp(tmp8)
    tmp11 = tmp9 / tmp10
    tmp12 = tl.where(tmp2, tmp1, tmp11)
    tl.store(in_out_ptr0 + x2, tmp12, xmask)


@triton.jit
def triton_poi_fused_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
    tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp12 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 * tmp1
    tmp5 = tmp3 * tmp4
    tmp6 = tmp2 + tmp5
    tmp9 = tmp7 * tmp8
    tmp10 = tmp6 + tmp9
    tmp13 = tmp11 * tmp12
    tmp14 = tmp10 + tmp13
    tl.store(out_ptr0 + x2, tmp14, xmask)


def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    assert_size_stride(arg3_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        extern_kernels.bmm(arg0_1, reinterpret_tensor(arg1_1, (4, 4, 1), (4,
            1, 1), 0), out=buf0)
        del arg0_1
        del arg1_1
        buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
        buf2 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__softmax_eq_masked_fill_mul_0[grid(4)](arg2_1,
            buf0, buf1, buf2, 4, XBLOCK=4, num_warps=1, num_stages=1)
        buf3 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0)
        del buf0
        triton_poi_fused__softmax_eq_masked_fill_mul_1[grid(16)](buf3,
            arg2_1, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
        del arg2_1
        del buf1
        del buf2
        buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_mul_sum_2[grid(16)](buf3, arg3_1, buf4, 16, XBLOCK
            =16, num_warps=1, num_stages=1)
        del arg3_1
    return buf3, buf4


class GlobalAttentionNew(nn.Module):
    """
  Global attention takes a matrix and a query vector. It
  then computes a parameterized convex combination of the matrix
  based on the input query.

  Constructs a unit mapping a query `q` of size `dim`
  and a source matrix `H` of size `n x dim`, 
  to an output of size `dim`.

  All models compute the output as
  :math:`c = sum_{j=1}^{SeqLength} a_j H_j` where
  :math:`a_j` is the softmax of a score function.

  However they differ on how they compute the attention score.

  * Luong Attention (dot, general):
     * dot: :math:`score(H_j,q) = H_j^T q`
     * general: :math:`score(H_j, q) = H_j^T W_a q`

  * Bahdanau Attention (mlp):
     * :math:`score(H_j, q) = w_a^T tanh(W_a q + U_a h_j)`

  Args:
     attn_size (int): dimensionality of query and key
     attn_type (str): type of attention to use, options [dot,general,mlp]
  """

    def __init__(self, query_size, attn_size, attn_type='dot'):
        super(GlobalAttentionNew, self).__init__()
        self.query_size = query_size
        self.attn_size = attn_size
        self.attn_type = attn_type
        if self.attn_type == 'general':
            self.linear_in = nn.Linear(query_size, attn_size, bias=False)
        elif self.attn_type == 'mlp':
            self.linear_query = nn.Linear(query_size, attn_size, bias=True)
            self.attn_w = nn.Linear(attn_size, 1, bias=False)
        elif self.attn_type == 'dot':
            assert self.query_size == self.attn_size

    def forward(self, input_0, input_1, input_2, input_3):
        arg1_1 = input_0
        arg0_1 = input_1
        arg2_1 = input_2
        arg3_1 = input_3
        output = call([arg0_1, arg1_1, arg2_1, arg3_1])
        return output[0], output[1]
