# 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_8/inductor_cache/fd/cfdx66zl4254e3wmlgrklcqmkb6eqboub6fpmwu4o33z2dij6xke.py
# Topologically Sorted Source Nodes: [cumsum], Original ATen: [aten.cumsum]
# Source node to ATen node mapping:
#   cumsum => cumsum
# Graph fragment:
#   %cumsum : [num_users=1] = call_function[target=torch.ops.aten.cumsum.default](args = (%primals_1, 1), kwargs = {})
triton_per_fused_cumsum_0 = async_compile.triton('triton_per_fused_cumsum_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.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
    tmp0 = arg0_0 + arg1_0
    return tmp0

@triton_heuristics.persistent_reduction(
    size_hints=[4, 4],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_cumsum_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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}
)
@triton.jit
def triton_per_fused_cumsum_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 4
    rnumel = 4
    RBLOCK: tl.constexpr = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    roffset = 0
    rmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + (4*x0)), xmask, other=0.0)
    tmp1 = tmp0.to(tl.float32)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp3, = tl.associative_scan((tmp2,), 1, _triton_helper_fn_add0)
    tl.store(out_ptr0 + (r1 + (4*x0)), tmp3, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/2s/c2sayahpuhbu7rbygl4n62bnypotycyr7hnrbototi6dpx3h3d2u.py
# Topologically Sorted Source Nodes: [sq], Original ATen: [aten.add]
# Source node to ATen node mapping:
#   sq => add
# Graph fragment:
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%select, %view), kwargs = {})
triton_poi_fused_add_1 = async_compile.triton('triton_poi_fused_add_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=[64], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_add_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex % 16
    x0 = xindex % 4
    x5 = xindex
    tmp0 = tl.load(in_ptr0 + (x3), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + (x5), xmask)
    tmp1 = 1 + x0
    tmp2 = tmp1.to(tl.float32)
    tmp3 = tmp0 / tmp2
    tmp5 = tmp3 + tmp4
    tl.store(out_ptr0 + (x5), tmp5, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/2j/c2jjtkxrbf45fydgbmbxldeievsjn7ybuwsj2gjr752am3yq3dgt.py
# Topologically Sorted Source Nodes: [b_k_r, sk, sk_1], Original ATen: [aten.sum, aten.add, aten.constant_pad_nd]
# Source node to ATen node mapping:
#   b_k_r => sum_1
#   sk => add_1
#   sk_1 => constant_pad_nd
# Graph fragment:
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%view_3, [2]), kwargs = {})
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sum_1, %view_1), kwargs = {})
#   %constant_pad_nd : [num_users=1] = call_function[target=torch.ops.aten.constant_pad_nd.default](args = (%add_1, [0, 0, 1, 0], 0.0), kwargs = {})
triton_poi_fused_add_constant_pad_nd_sum_2 = async_compile.triton('triton_poi_fused_add_constant_pad_nd_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=[128], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_constant_pad_nd_sum_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_add_constant_pad_nd_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = (xindex // 4) % 5
    x3 = xindex % 20
    x0 = xindex % 4
    x2 = (xindex // 20)
    x5 = xindex
    tmp0 = (-1) + x1
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.load(in_ptr0 + ((-4) + x3), tmp2 & xmask, eviction_policy='evict_last', other=0.0)
    tmp4 = 1 + x0
    tmp5 = tmp4.to(tl.float32)
    tmp6 = tmp3 / tmp5
    tmp7 = tl.load(in_ptr1 + ((-4) + x3 + (16*x2)), tmp2 & xmask, other=0.0)
    tmp8 = tmp6 + tmp7
    tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
    tmp10 = tl.where(tmp2, tmp8, tmp9)
    tl.store(out_ptr0 + (x5), tmp10, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/kx/ckxxdgiylfy52szzmwxthnn4a5llczmvc5ig7yeka2wmefvxnnjc.py
# Topologically Sorted Source Nodes: [triu_indices], Original ATen: [aten.triu_indices]
# Source node to ATen node mapping:
#   triu_indices => cat
# Graph fragment:
#   %cat : [num_users=1] = call_function[target=torch.ops.aten.cat.default](args = ([%add_3, %add_4],), kwargs = {})
triton_poi_fused_triu_indices_3 = async_compile.triton('triton_poi_fused_triu_indices_3', '''
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=[32], 
    filename=__file__,
    triton_meta={'signature': {0: '*i64', 1: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0,), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_triu_indices_3', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 0, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_triu_indices_3(out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = x0
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.full([1], 10, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tmp0.to(tl.float64)
    tmp6 = tl.full([1], 2.0, tl.float64)
    tmp7 = tmp5 * tmp6
    tmp8 = tl.full([1], 20.25, tl.float64)
    tmp9 = tmp8 - tmp7
    tmp10 = libdevice.sqrt(tmp9)
    tmp11 = tl.full([1], 4.5, tl.float64)
    tmp12 = tmp11 - tmp10
    tmp13 = libdevice.floor(tmp12)
    tmp14 = tmp13.to(tl.int64)
    tmp15 = tmp14 + tmp1
    tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
    tmp17 = tl.where(tmp4, tmp15, tmp16)
    tmp18 = tmp0 >= tmp3
    tmp19 = tl.full([1], 20, tl.int64)
    tmp20 = tmp0 < tmp19
    tmp21 = (-10) + x0
    tmp22 = tmp21.to(tl.float64)
    tmp23 = tmp22 * tmp6
    tmp24 = tmp8 - tmp23
    tmp25 = libdevice.sqrt(tmp24)
    tmp26 = tmp11 - tmp25
    tmp27 = libdevice.floor(tmp26)
    tmp28 = tl.full([1], 7.0, tl.float64)
    tmp29 = tmp28 - tmp27
    tmp30 = tmp29 * tmp27
    tmp31 = tl.full([1], 0.5, tl.float64)
    tmp32 = tmp30 * tmp31
    tmp33 = tmp22 - tmp32
    tmp34 = libdevice.floor(tmp33)
    tmp35 = tmp34.to(tl.int64)
    tmp36 = tmp35 + tmp1
    tmp37 = tl.full(tmp36.shape, 0.0, tmp36.dtype)
    tmp38 = tl.where(tmp18, tmp36, tmp37)
    tmp39 = tl.where(tmp4, tmp17, tmp38)
    tl.store(out_ptr0 + (x0), tmp39, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/mt/cmtuioa7yvegaefkickdkbylvluixxvcmep3opfcbevrlmuy3nki.py
# Topologically Sorted Source Nodes: [mask], Original ATen: [aten._to_copy]
# Source node to ATen node mapping:
#   mask => full_default
# Graph fragment:
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([4, 4, 5], False), kwargs = {dtype: torch.bool, layout: torch.strided, device: cuda:0, pin_memory: False})
triton_poi_fused__to_copy_4 = async_compile.triton('triton_poi_fused__to_copy_4', '''
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=[128], 
    filename=__file__,
    triton_meta={'signature': {0: '*i1', 1: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__to_copy_4', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 0, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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__to_copy_4(out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.full([1], False, tl.int1)
    tl.store(out_ptr0 + (x0), tmp0, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/aw/cawmkayvx5gj7pqrlhulfvdgfycrgpa44nx66pjb3tbte6bz65ey.py
# Topologically Sorted Source Nodes: [mask, setitem], Original ATen: [aten._to_copy, aten.lift_fresh, aten.index_put]
# Source node to ATen node mapping:
#   mask => full_default
#   setitem => full_default_1, index_put
# Graph fragment:
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([4, 4, 5], False), kwargs = {dtype: torch.bool, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %full_default_1 : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], True), kwargs = {dtype: torch.bool, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %index_put : [num_users=2] = call_function[target=torch.ops.aten.index_put_.default](args = (%full_default, [None, %select_1, %add_5], %full_default_1), kwargs = {})
triton_poi_fused__to_copy_index_put_lift_fresh_5 = async_compile.triton('triton_poi_fused__to_copy_index_put_lift_fresh_5', '''
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=[64], 
    filename=__file__,
    triton_meta={'signature': {0: '*i64', 1: '*i1', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__to_copy_index_put_lift_fresh_5', 'mutated_arg_names': ['out_ptr0'], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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__to_copy_index_put_lift_fresh_5(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 40
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 10
    x1 = (xindex // 10)
    tmp0 = tl.load(in_ptr0 + (x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (10 + x0), xmask, eviction_policy='evict_last')
    tmp1 = tl.full([XBLOCK], 4, tl.int32)
    tmp2 = tmp0 + tmp1
    tmp3 = tmp0 < 0
    tmp4 = tl.where(tmp3, tmp2, tmp0)
    tl.device_assert(((0 <= tmp4) & (tmp4 < 4)) | ~(xmask), "index out of bounds: 0 <= tmp4 < 4")
    tmp7 = tl.full([1], 1, tl.int64)
    tmp8 = tmp6 + tmp7
    tmp9 = tl.full([XBLOCK], 5, tl.int32)
    tmp10 = tmp8 + tmp9
    tmp11 = tmp8 < 0
    tmp12 = tl.where(tmp11, tmp10, tmp8)
    tl.device_assert(((0 <= tmp12) & (tmp12 < 5)) | ~(xmask), "index out of bounds: 0 <= tmp12 < 5")
    tmp14 = tl.full([1], True, tl.int1)
    tl.store(out_ptr0 + (tmp12 + (5*tmp4) + (20*x1)), tmp14, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/xc/cxcqnmpzsocx4dzlfxh4awc2uchnbw3lqqbwwsoe7g5wjg3psa6h.py
# Topologically Sorted Source Nodes: [R_1], Original ATen: [aten._softmax]
# Source node to ATen node mapping:
#   R_1 => amax, exp, sub_4, sum_2
# Graph fragment:
#   %amax : [num_users=1] = call_function[target=torch.ops.aten.amax.default](args = (%view_13, [-1], True), kwargs = {})
#   %sub_4 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%view_13, %amax), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%sub_4,), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%exp, [-1], True), kwargs = {})
triton_poi_fused__softmax_6 = async_compile.triton('triton_poi_fused__softmax_6', '''
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: '*i1', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), '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_6', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 10, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (5*x0), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp1 = tl.load(in_ptr1 + (5*x0), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (1 + (5*x0)), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp5 = tl.load(in_ptr1 + (1 + (5*x0)), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (2 + (5*x0)), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp9 = tl.load(in_ptr1 + (2 + (5*x0)), xmask, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr0 + (3 + (5*x0)), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp13 = tl.load(in_ptr1 + (3 + (5*x0)), xmask, eviction_policy='evict_last')
    tmp16 = tl.load(in_ptr0 + (4 + (5*x0)), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp17 = tl.load(in_ptr1 + (4 + (5*x0)), xmask, eviction_policy='evict_last')
    tmp2 = -3.4028234663852886e+38
    tmp3 = tl.where(tmp0, tmp2, tmp1)
    tmp6 = tl.where(tmp4, tmp2, tmp5)
    tmp7 = triton_helpers.maximum(tmp3, tmp6)
    tmp10 = tl.where(tmp8, tmp2, tmp9)
    tmp11 = triton_helpers.maximum(tmp7, tmp10)
    tmp14 = tl.where(tmp12, tmp2, tmp13)
    tmp15 = triton_helpers.maximum(tmp11, tmp14)
    tmp18 = tl.where(tmp16, tmp2, tmp17)
    tmp19 = triton_helpers.maximum(tmp15, tmp18)
    tmp20 = tmp3 - tmp19
    tmp21 = tl_math.exp(tmp20)
    tmp22 = tmp6 - tmp19
    tmp23 = tl_math.exp(tmp22)
    tmp24 = tmp21 + tmp23
    tmp25 = tmp10 - tmp19
    tmp26 = tl_math.exp(tmp25)
    tmp27 = tmp24 + tmp26
    tmp28 = tmp14 - tmp19
    tmp29 = tl_math.exp(tmp28)
    tmp30 = tmp27 + tmp29
    tmp31 = tmp18 - tmp19
    tmp32 = tl_math.exp(tmp31)
    tmp33 = tmp30 + tmp32
    tl.store(out_ptr0 + (x0), tmp19, xmask)
    tl.store(out_ptr1 + (x0), tmp33, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/is/cisrenddjnxqu6tvoi2hsenqeki76sitqi7tg4ydnyua4xw6aimj.py
# Topologically Sorted Source Nodes: [R_2], Original ATen: [aten.tril]
# Source node to ATen node mapping:
#   R_2 => le, sub_5
# Graph fragment:
#   %sub_5 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%unsqueeze_4, %unsqueeze_5), kwargs = {})
#   %le : [num_users=2] = call_function[target=torch.ops.aten.le.Scalar](args = (%sub_5, -1), kwargs = {})
triton_poi_fused_tril_7 = async_compile.triton('triton_poi_fused_tril_7', '''
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=[32], 
    filename=__file__,
    triton_meta={'signature': {0: '*i1', 1: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0,), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_tril_7', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 0, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_tril_7(out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 5
    x1 = (xindex // 5)
    x2 = xindex
    tmp0 = x0 + ((-1)*x1)
    tmp1 = tl.full([1], -1, tl.int64)
    tmp2 = tmp0 <= tmp1
    tl.store(out_ptr0 + (x2), tmp2, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/tc/ctcsr4z6jiqtjwhyg6kjczs7xdoo3gawcrtqvrkp3uy2j7s5mg35.py
# Topologically Sorted Source Nodes: [R_1, R_2], Original ATen: [aten._softmax, aten.tril]
# Source node to ATen node mapping:
#   R_1 => div_3, exp, sub_4
#   R_2 => full_default_3, where_1
# Graph fragment:
#   %sub_4 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%view_13, %amax), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%sub_4,), kwargs = {})
#   %div_3 : [num_users=2] = call_function[target=torch.ops.aten.div.Tensor](args = (%exp, %sum_2), kwargs = {})
#   %full_default_3 : [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})
#   %where_1 : [num_users=1] = call_function[target=torch.ops.aten.where.self](args = (%le, %div_3, %full_default_3), kwargs = {})
triton_poi_fused__softmax_tril_8 = async_compile.triton('triton_poi_fused__softmax_tril_8', '''
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=[128], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*i1', 2: '*fp32', 3: '*fp32', 4: '*i1', 5: '*fp32', 6: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5, 6), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__softmax_tril_8', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 5, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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_tril_8(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x4 = xindex
    x1 = (xindex // 5)
    x2 = xindex % 20
    tmp0 = tl.load(in_ptr0 + (x4), xmask).to(tl.int1)
    tmp1 = tl.load(in_out_ptr0 + (x4), xmask)
    tmp4 = tl.load(in_ptr1 + (x1), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr2 + (x1), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr3 + (x2), xmask, eviction_policy='evict_last').to(tl.int1)
    tmp2 = -3.4028234663852886e+38
    tmp3 = tl.where(tmp0, tmp2, tmp1)
    tmp5 = tmp3 - tmp4
    tmp6 = tl_math.exp(tmp5)
    tmp8 = tmp6 / tmp7
    tmp10 = 0.0
    tmp11 = tl.where(tmp9, tmp8, tmp10)
    tl.store(in_out_ptr0 + (x4), tmp8, xmask)
    tl.store(out_ptr0 + (x4), tmp11, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    primals_1, primals_2, primals_3, primals_4 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (1, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_3, (1, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [cumsum], Original ATen: [aten.cumsum]
        stream0 = get_raw_stream(0)
        triton_per_fused_cumsum_0.run(primals_1, buf0, 4, 4, grid=grid(4), stream=stream0)
        del primals_1
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [cumsum_1], Original ATen: [aten.cumsum]
        triton_per_fused_cumsum_0.run(primals_4, buf1, 4, 4, grid=grid(4), stream=stream0)
        del primals_4
        buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [sq], Original ATen: [aten.add]
        triton_poi_fused_add_1.run(buf0, primals_2, buf2, 64, grid=grid(64), stream=stream0)
        del primals_2
        buf3 = empty_strided_cuda((4, 5, 4), (20, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [b_k_r, sk, sk_1], Original ATen: [aten.sum, aten.add, aten.constant_pad_nd]
        triton_poi_fused_add_constant_pad_nd_sum_2.run(buf1, primals_3, buf3, 80, grid=grid(80), stream=stream0)
        del primals_3
        buf4 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
        # Topologically Sorted Source Nodes: [R], Original ATen: [aten.bmm]
        extern_kernels.bmm(buf2, reinterpret_tensor(buf3, (4, 4, 5), (20, 1, 4), 0), out=buf4)
        buf5 = empty_strided_cuda((20, ), (1, ), torch.int64)
        # Topologically Sorted Source Nodes: [triu_indices], Original ATen: [aten.triu_indices]
        triton_poi_fused_triu_indices_3.run(buf5, 20, grid=grid(20), stream=stream0)
        buf6 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.bool)
        # Topologically Sorted Source Nodes: [mask], Original ATen: [aten._to_copy]
        triton_poi_fused__to_copy_4.run(buf6, 80, grid=grid(80), stream=stream0)
        # Topologically Sorted Source Nodes: [mask, setitem], Original ATen: [aten._to_copy, aten.lift_fresh, aten.index_put]
        triton_poi_fused__to_copy_index_put_lift_fresh_5.run(buf5, buf6, 40, grid=grid(40), stream=stream0)
        del buf5
        buf8 = reinterpret_tensor(buf1, (4, 4, 1), (4, 1, 16), 0); del buf1  # reuse
        buf9 = reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 16), 0); del buf0  # reuse
        # Topologically Sorted Source Nodes: [R_1], Original ATen: [aten._softmax]
        triton_poi_fused__softmax_6.run(buf6, buf4, buf8, buf9, 16, grid=grid(16), stream=stream0)
        buf11 = empty_strided_cuda((4, 5), (5, 1), torch.bool)
        # Topologically Sorted Source Nodes: [R_2], Original ATen: [aten.tril]
        triton_poi_fused_tril_7.run(buf11, 20, grid=grid(20), stream=stream0)
        buf10 = buf4; del buf4  # reuse
        buf12 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
        # Topologically Sorted Source Nodes: [R_1, R_2], Original ATen: [aten._softmax, aten.tril]
        triton_poi_fused__softmax_tril_8.run(buf10, buf6, buf8, buf9, buf11, buf12, 80, grid=grid(80), stream=stream0)
        del buf8
        del buf9
    return (buf12, buf6, buf10, buf11, reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), buf3, )


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, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((1, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((1, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4])
    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
from torch.nn import functional as F
from functools import partial
from torch import nn


def bucket(buckets, t, dim=1):
    shape = list(t.shape)
    shape[dim:dim + 1] = [buckets, -1]
    return t.reshape(*shape)


def max_neg_value(tensor):
    return -torch.finfo(tensor.dtype).max


def expand_dim(t, dim, k):
    expand_shape = [-1] * len(t.shape)
    expand_shape[dim] = k
    return t.expand(*expand_shape)


def expand_batch_and_merge_head(b, t):
    shape = list(t.squeeze(0).shape)
    t = expand_dim(t, 0, b)
    shape[0] = shape[0] * b
    return t.reshape(*shape)


def cumavg(t, dim):
    r = torch.arange(1, t.shape[dim] + 1, device=t.device)
    expand_slice = [None] * len(t.shape)
    expand_slice[dim] = slice(None, None)
    return t.cumsum(dim=dim) / r[tuple(expand_slice)]


def mask_reordering_matrix(R):
    buckets = R.shape[1]
    mask_value = max_neg_value(R)
    mask = torch.zeros(R.shape, device=R.device).bool()
    i, j = torch.triu_indices(buckets, buckets)
    mask[:, i, j + 1] = True
    R.masked_fill_(mask, mask_value)
    del mask
    R = R.softmax(dim=-1)
    R = R.tril(diagonal=-1)
    return R


class CausalAttentionSortNet(nn.Module):

    def __init__(self, heads, buckets, dim):
        super().__init__()
        self.heads = heads
        self.buckets = buckets
        self.dim = dim
        self.q_pos_emb = nn.Parameter(torch.randn(1, heads, buckets, dim))
        self.k_pos_emb = nn.Parameter(torch.randn(1, heads, buckets, dim))

    def forward(self, q, k):
        bh, *_, h, buckets, _dim = *q.shape, self.heads, self.buckets, self.dim
        b = bh // h
        pos_q, pos_k = map(partial(expand_batch_and_merge_head, b), (self.
            q_pos_emb, self.k_pos_emb))
        q_r = bucket(buckets, cumavg(q, dim=1))
        k_r = bucket(buckets, cumavg(k, dim=1))
        b_q_r = q_r[:, :, 0]
        b_k_r = k_r.sum(dim=2)
        sq = b_q_r + pos_q
        sk = b_k_r + pos_k
        sk = F.pad(sk, (0, 0, 1, 0))
        R = torch.einsum('bie,bje->bij', sq, sk)
        return mask_reordering_matrix(R)


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


def get_init_inputs():
    return [[], {'heads': 4, 'buckets': 4, 'dim': 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 libdevice, math as tl_math
from torch import 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_helper_fn_add0(arg0_0, arg1_0):
    tmp0 = arg0_0 + arg1_0
    return tmp0


@triton.jit
def triton_per_fused_cumsum_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl
    .constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 4
    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 + 4 * x0), xmask, other=0.0)
    tmp1 = tmp0.to(tl.float32)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp3, = tl.associative_scan((tmp2,), 1, _triton_helper_fn_add0)
    tl.store(out_ptr0 + (r1 + 4 * x0), tmp3, xmask)


@triton.jit
def triton_poi_fused_add_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex % 16
    x0 = xindex % 4
    x5 = xindex
    tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + x5, xmask)
    tmp1 = 1 + x0
    tmp2 = tmp1.to(tl.float32)
    tmp3 = tmp0 / tmp2
    tmp5 = tmp3 + tmp4
    tl.store(out_ptr0 + x5, tmp5, xmask)


@triton.jit
def triton_poi_fused_add_constant_pad_nd_sum_2(in_ptr0, in_ptr1, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4 % 5
    x3 = xindex % 20
    x0 = xindex % 4
    x2 = xindex // 20
    x5 = xindex
    tmp0 = -1 + x1
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.load(in_ptr0 + (-4 + x3), tmp2 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp4 = 1 + x0
    tmp5 = tmp4.to(tl.float32)
    tmp6 = tmp3 / tmp5
    tmp7 = tl.load(in_ptr1 + (-4 + x3 + 16 * x2), tmp2 & xmask, other=0.0)
    tmp8 = tmp6 + tmp7
    tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
    tmp10 = tl.where(tmp2, tmp8, tmp9)
    tl.store(out_ptr0 + x5, tmp10, xmask)


@triton.jit
def triton_poi_fused_triu_indices_3(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = x0
    tmp1 = tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 10, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tmp0.to(tl.float64)
    tmp6 = tl.full([1], 2.0, tl.float64)
    tmp7 = tmp5 * tmp6
    tmp8 = tl.full([1], 20.25, tl.float64)
    tmp9 = tmp8 - tmp7
    tmp10 = libdevice.sqrt(tmp9)
    tmp11 = tl.full([1], 4.5, tl.float64)
    tmp12 = tmp11 - tmp10
    tmp13 = libdevice.floor(tmp12)
    tmp14 = tmp13.to(tl.int64)
    tmp15 = tmp14 + tmp1
    tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype)
    tmp17 = tl.where(tmp4, tmp15, tmp16)
    tmp18 = tmp0 >= tmp3
    tl.full([1], 20, tl.int64)
    tmp21 = -10 + x0
    tmp22 = tmp21.to(tl.float64)
    tmp23 = tmp22 * tmp6
    tmp24 = tmp8 - tmp23
    tmp25 = libdevice.sqrt(tmp24)
    tmp26 = tmp11 - tmp25
    tmp27 = libdevice.floor(tmp26)
    tmp28 = tl.full([1], 7.0, tl.float64)
    tmp29 = tmp28 - tmp27
    tmp30 = tmp29 * tmp27
    tmp31 = tl.full([1], 0.5, tl.float64)
    tmp32 = tmp30 * tmp31
    tmp33 = tmp22 - tmp32
    tmp34 = libdevice.floor(tmp33)
    tmp35 = tmp34.to(tl.int64)
    tmp36 = tmp35 + tmp1
    tmp37 = tl.full(tmp36.shape, 0.0, tmp36.dtype)
    tmp38 = tl.where(tmp18, tmp36, tmp37)
    tmp39 = tl.where(tmp4, tmp17, tmp38)
    tl.store(out_ptr0 + x0, tmp39, xmask)


@triton.jit
def triton_poi_fused__to_copy_4(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.full([1], False, tl.int1)
    tl.store(out_ptr0 + x0, tmp0, xmask)


@triton.jit
def triton_poi_fused__to_copy_index_put_lift_fresh_5(in_ptr0, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 40
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 10
    x1 = xindex // 10
    tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (10 + x0), xmask, eviction_policy='evict_last')
    tmp1 = tl.full([XBLOCK], 4, tl.int32)
    tmp2 = tmp0 + tmp1
    tmp3 = tmp0 < 0
    tmp4 = tl.where(tmp3, tmp2, tmp0)
    tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp4 < 4')
    tmp7 = tl.full([1], 1, tl.int64)
    tmp8 = tmp6 + tmp7
    tmp9 = tl.full([XBLOCK], 5, tl.int32)
    tmp10 = tmp8 + tmp9
    tmp11 = tmp8 < 0
    tmp12 = tl.where(tmp11, tmp10, tmp8)
    tl.device_assert((0 <= tmp12) & (tmp12 < 5) | ~xmask,
        'index out of bounds: 0 <= tmp12 < 5')
    tmp14 = tl.full([1], True, tl.int1)
    tl.store(out_ptr0 + (tmp12 + 5 * tmp4 + 20 * x1), tmp14, xmask)


@triton.jit
def triton_poi_fused__softmax_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last').to(tl
        .int1)
    tmp1 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (1 + 5 * x0), xmask, eviction_policy='evict_last'
        ).to(tl.int1)
    tmp5 = tl.load(in_ptr1 + (1 + 5 * x0), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (2 + 5 * x0), xmask, eviction_policy='evict_last'
        ).to(tl.int1)
    tmp9 = tl.load(in_ptr1 + (2 + 5 * x0), xmask, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr0 + (3 + 5 * x0), xmask, eviction_policy='evict_last'
        ).to(tl.int1)
    tmp13 = tl.load(in_ptr1 + (3 + 5 * x0), xmask, eviction_policy='evict_last'
        )
    tmp16 = tl.load(in_ptr0 + (4 + 5 * x0), xmask, eviction_policy='evict_last'
        ).to(tl.int1)
    tmp17 = tl.load(in_ptr1 + (4 + 5 * x0), xmask, eviction_policy='evict_last'
        )
    tmp2 = -3.4028234663852886e+38
    tmp3 = tl.where(tmp0, tmp2, tmp1)
    tmp6 = tl.where(tmp4, tmp2, tmp5)
    tmp7 = triton_helpers.maximum(tmp3, tmp6)
    tmp10 = tl.where(tmp8, tmp2, tmp9)
    tmp11 = triton_helpers.maximum(tmp7, tmp10)
    tmp14 = tl.where(tmp12, tmp2, tmp13)
    tmp15 = triton_helpers.maximum(tmp11, tmp14)
    tmp18 = tl.where(tmp16, tmp2, tmp17)
    tmp19 = triton_helpers.maximum(tmp15, tmp18)
    tmp20 = tmp3 - tmp19
    tmp21 = tl_math.exp(tmp20)
    tmp22 = tmp6 - tmp19
    tmp23 = tl_math.exp(tmp22)
    tmp24 = tmp21 + tmp23
    tmp25 = tmp10 - tmp19
    tmp26 = tl_math.exp(tmp25)
    tmp27 = tmp24 + tmp26
    tmp28 = tmp14 - tmp19
    tmp29 = tl_math.exp(tmp28)
    tmp30 = tmp27 + tmp29
    tmp31 = tmp18 - tmp19
    tmp32 = tl_math.exp(tmp31)
    tmp33 = tmp30 + tmp32
    tl.store(out_ptr0 + x0, tmp19, xmask)
    tl.store(out_ptr1 + x0, tmp33, xmask)


@triton.jit
def triton_poi_fused_tril_7(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 5
    x1 = xindex // 5
    x2 = xindex
    tmp0 = x0 + -1 * x1
    tmp1 = tl.full([1], -1, tl.int64)
    tmp2 = tmp0 <= tmp1
    tl.store(out_ptr0 + x2, tmp2, xmask)


@triton.jit
def triton_poi_fused__softmax_tril_8(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
    in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 80
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x4 = xindex
    x1 = xindex // 5
    x2 = xindex % 20
    tmp0 = tl.load(in_ptr0 + x4, xmask).to(tl.int1)
    tmp1 = tl.load(in_out_ptr0 + x4, xmask)
    tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last').to(tl
        .int1)
    tmp2 = -3.4028234663852886e+38
    tmp3 = tl.where(tmp0, tmp2, tmp1)
    tmp5 = tmp3 - tmp4
    tmp6 = tl_math.exp(tmp5)
    tmp8 = tmp6 / tmp7
    tmp10 = 0.0
    tmp11 = tl.where(tmp9, tmp8, tmp10)
    tl.store(in_out_ptr0 + x4, tmp8, xmask)
    tl.store(out_ptr0 + x4, tmp11, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (1, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_3, (1, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_cumsum_0[grid(4)](primals_1, buf0, 4, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del primals_1
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_per_fused_cumsum_0[grid(4)](primals_4, buf1, 4, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del primals_4
        buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_poi_fused_add_1[grid(64)](buf0, primals_2, buf2, 64, XBLOCK=
            64, num_warps=1, num_stages=1)
        del primals_2
        buf3 = empty_strided_cuda((4, 5, 4), (20, 4, 1), torch.float32)
        triton_poi_fused_add_constant_pad_nd_sum_2[grid(80)](buf1,
            primals_3, buf3, 80, XBLOCK=128, num_warps=4, num_stages=1)
        del primals_3
        buf4 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
        extern_kernels.bmm(buf2, reinterpret_tensor(buf3, (4, 4, 5), (20, 1,
            4), 0), out=buf4)
        buf5 = empty_strided_cuda((20,), (1,), torch.int64)
        triton_poi_fused_triu_indices_3[grid(20)](buf5, 20, XBLOCK=32,
            num_warps=1, num_stages=1)
        buf6 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.bool)
        triton_poi_fused__to_copy_4[grid(80)](buf6, 80, XBLOCK=128,
            num_warps=4, num_stages=1)
        triton_poi_fused__to_copy_index_put_lift_fresh_5[grid(40)](buf5,
            buf6, 40, XBLOCK=64, num_warps=1, num_stages=1)
        del buf5
        buf8 = reinterpret_tensor(buf1, (4, 4, 1), (4, 1, 16), 0)
        del buf1
        buf9 = reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 16), 0)
        del buf0
        triton_poi_fused__softmax_6[grid(16)](buf6, buf4, buf8, buf9, 16,
            XBLOCK=16, num_warps=1, num_stages=1)
        buf11 = empty_strided_cuda((4, 5), (5, 1), torch.bool)
        triton_poi_fused_tril_7[grid(20)](buf11, 20, XBLOCK=32, num_warps=1,
            num_stages=1)
        buf10 = buf4
        del buf4
        buf12 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
        triton_poi_fused__softmax_tril_8[grid(80)](buf10, buf6, buf8, buf9,
            buf11, buf12, 80, XBLOCK=128, num_warps=4, num_stages=1)
        del buf8
        del buf9
    return buf12, buf6, buf10, buf11, reinterpret_tensor(buf2, (4, 4, 4), (
        16, 1, 4), 0), buf3


def bucket(buckets, t, dim=1):
    shape = list(t.shape)
    shape[dim:dim + 1] = [buckets, -1]
    return t.reshape(*shape)


def max_neg_value(tensor):
    return -torch.finfo(tensor.dtype).max


def expand_dim(t, dim, k):
    expand_shape = [-1] * len(t.shape)
    expand_shape[dim] = k
    return t.expand(*expand_shape)


def expand_batch_and_merge_head(b, t):
    shape = list(t.squeeze(0).shape)
    t = expand_dim(t, 0, b)
    shape[0] = shape[0] * b
    return t.reshape(*shape)


def cumavg(t, dim):
    r = torch.arange(1, t.shape[dim] + 1, device=t.device)
    expand_slice = [None] * len(t.shape)
    expand_slice[dim] = slice(None, None)
    return t.cumsum(dim=dim) / r[tuple(expand_slice)]


def mask_reordering_matrix(R):
    buckets = R.shape[1]
    mask_value = max_neg_value(R)
    mask = torch.zeros(R.shape, device=R.device).bool()
    i, j = torch.triu_indices(buckets, buckets)
    mask[:, i, j + 1] = True
    R.masked_fill_(mask, mask_value)
    del mask
    R = R.softmax(dim=-1)
    R = R.tril(diagonal=-1)
    return R


class CausalAttentionSortNetNew(nn.Module):

    def __init__(self, heads, buckets, dim):
        super().__init__()
        self.heads = heads
        self.buckets = buckets
        self.dim = dim
        self.q_pos_emb = nn.Parameter(torch.randn(1, heads, buckets, dim))
        self.k_pos_emb = nn.Parameter(torch.randn(1, heads, buckets, dim))

    def forward(self, input_0, input_1):
        primals_2 = self.q_pos_emb
        primals_3 = self.k_pos_emb
        primals_1 = input_0
        primals_4 = input_1
        output = call([primals_1, primals_2, primals_3, primals_4])
        return output[0]
