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_poi_fused_triu_indices_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 2
    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], 1, 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], 2.25, tl.float64)
    tmp9 = tmp8 - tmp7
    tmp10 = libdevice.sqrt(tmp9)
    tmp11 = tl.full([1], 1.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], 2, tl.int64)
    tmp21 = -1 + 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], 1.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_1(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 8
    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_2(in_ptr0, out_ptr0,
    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 + 0)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
    tmp7 = tl.load(in_ptr0 + 1)
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
    tmp2 = tl.full([XBLOCK], 1, tl.int32)
    tmp3 = tmp1 + tmp2
    tmp4 = tmp1 < 0
    tmp5 = tl.where(tmp4, tmp3, tmp1)
    tl.device_assert((0 <= tmp5) & (tmp5 < 1),
        'index out of bounds: 0 <= tmp5 < 1')
    tmp9 = tl.full([1], 1, tl.int64)
    tmp10 = tmp8 + tmp9
    tmp11 = tl.full([XBLOCK], 2, tl.int32)
    tmp12 = tmp10 + tmp11
    tmp13 = tmp10 < 0
    tmp14 = tl.where(tmp13, tmp12, tmp10)
    tl.device_assert((0 <= tmp14) & (tmp14 < 2),
        'index out of bounds: 0 <= tmp14 < 2')
    tmp16 = tl.full([1], True, tl.int1)
    tl.store(out_ptr0 + (tmp14 + 2 * x0), tmp16, xmask)


@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_3(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl
    .constexpr):
    xnumel = 16
    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)
    r2 = rindex
    x0 = xindex % 4
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + (x0 + 4 * r2 + 16 * x1), 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 + (x0 + 4 * r2 + 16 * x1), tmp3, xmask)


@triton.jit
def triton_poi_fused_constant_pad_nd_sum_4(in_ptr0, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4 % 2
    x0 = xindex % 4
    x2 = xindex // 8
    x3 = xindex
    tmp0 = -1 + x1
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.load(in_ptr0 + (x0 + 16 * x2), tmp2 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp4 = 1.0
    tmp5 = tmp3 / tmp4
    tmp6 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), tmp2 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp7 = 2.0
    tmp8 = tmp6 / tmp7
    tmp9 = tmp5 + tmp8
    tmp10 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), tmp2 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp11 = 3.0
    tmp12 = tmp10 / tmp11
    tmp13 = tmp9 + tmp12
    tmp14 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), tmp2 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp15 = 4.0
    tmp16 = tmp14 / tmp15
    tmp17 = tmp13 + tmp16
    tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype)
    tmp19 = tl.where(tmp2, tmp17, tmp18)
    tl.store(out_ptr0 + x3, tmp19, xmask)


@triton.jit
def triton_poi_fused_div_5(in_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
    x1 = xindex // 4 % 4
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = 1 + x1
    tmp2 = tmp1.to(tl.float32)
    tmp3 = tmp0 / tmp2
    tl.store(in_out_ptr0 + x3, tmp3, xmask)


@triton.jit
def triton_poi_fused__softmax_masked_fill_mul_6(in_ptr0, in_ptr1, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 2
    tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
    tmp1 = tl.load(in_ptr1 + x2, xmask)
    tmp8 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last').to(tl
        .int1)
    tmp9 = tl.load(in_ptr1 + 2 * x1, xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last'
        ).to(tl.int1)
    tmp14 = tl.load(in_ptr1 + (1 + 2 * x1), xmask, eviction_policy='evict_last'
        )
    tmp2 = 0.5
    tmp3 = tmp1 * tmp2
    tmp4 = -3.4028234663852886e+38
    tmp5 = tl.where(tmp0, tmp4, tmp3)
    tmp6 = 1.0
    tmp7 = tmp5 * tmp6
    tmp10 = tmp9 * tmp2
    tmp11 = tl.where(tmp8, tmp4, tmp10)
    tmp12 = tmp11 * tmp6
    tmp15 = tmp14 * tmp2
    tmp16 = tl.where(tmp13, tmp4, tmp15)
    tmp17 = tmp16 * tmp6
    tmp18 = triton_helpers.maximum(tmp12, tmp17)
    tmp19 = tmp7 - tmp18
    tmp20 = 0.25
    tmp21 = tmp19 * tmp20
    tmp22 = tl_math.exp(tmp21)
    tl.store(out_ptr0 + x2, tmp22, xmask)


@triton.jit
def triton_poi_fused__softmax_7(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 2
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
    tmp3 = tmp1 + tmp2
    tmp4 = tmp0 / tmp3
    tl.store(out_ptr0 + x2, tmp4, xmask)


@triton.jit
def triton_poi_fused_scatter_zeros_like_8(out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = 0.0
    tl.store(out_ptr0 + x0, tmp0, xmask)


@triton.jit
def triton_poi_fused_scatter_zeros_like_9(in_ptr0, in_ptr1, out_ptr0,
    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 + x0, xmask)
    tmp2 = tl.load(in_ptr1 + x0, xmask)
    tl.device_assert((0 <= tmp0) & (tmp0 < 2) | ~xmask,
        'index out of bounds: 0 <= tmp0 < 2')
    tl.store(out_ptr0 + (tmp0 + 2 * x0), tmp2, xmask)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(arg1_1, (4, 4, 4), (16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((2,), (1,), torch.int64)
        get_raw_stream(0)
        triton_poi_fused_triu_indices_0[grid(2)](buf0, 2, XBLOCK=2,
            num_warps=1, num_stages=1)
        buf1 = empty_strided_cuda((4, 1, 2), (2, 2, 1), torch.bool)
        triton_poi_fused__to_copy_1[grid(8)](buf1, 8, XBLOCK=8, num_warps=1,
            num_stages=1)
        triton_poi_fused__to_copy_index_put_lift_fresh_2[grid(4)](buf0,
            buf1, 4, XBLOCK=4, num_warps=1, num_stages=1)
        del buf0
        buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_per_fused_cumsum_3[grid(16)](arg0_1, buf3, 16, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del arg0_1
        buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_per_fused_cumsum_3[grid(16)](arg1_1, buf4, 16, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del arg1_1
        buf5 = empty_strided_cuda((4, 2, 4), (8, 4, 1), torch.float32)
        triton_poi_fused_constant_pad_nd_sum_4[grid(32)](buf4, buf5, 32,
            XBLOCK=32, num_warps=1, num_stages=1)
        del buf4
        buf6 = buf3
        del buf3
        triton_poi_fused_div_5[grid(64)](buf6, 64, XBLOCK=64, num_warps=1,
            num_stages=1)
        buf7 = empty_strided_cuda((4, 1, 2), (2, 2, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf6, (4, 1, 4), (16, 0, 1), 
            0), reinterpret_tensor(buf5, (4, 4, 2), (8, 1, 4), 0), out=buf7)
        del buf5
        del buf6
        buf8 = empty_strided_cuda((4, 1, 2), (2, 8, 1), torch.float32)
        triton_poi_fused__softmax_masked_fill_mul_6[grid(8)](buf1, buf7,
            buf8, 8, XBLOCK=8, num_warps=1, num_stages=1)
        del buf1
        buf9 = reinterpret_tensor(buf7, (4, 1, 2), (2, 8, 1), 0)
        del buf7
        triton_poi_fused__softmax_7[grid(8)](buf8, buf9, 8, XBLOCK=8,
            num_warps=1, num_stages=1)
        del buf8
        buf10 = torch.ops.aten.topk.default(buf9, 1)
        buf11 = buf10[0]
        buf12 = buf10[1]
        del buf10
        buf13 = reinterpret_tensor(buf9, (4, 1, 2), (2, 2, 1), 0)
        del buf9
        triton_poi_fused_scatter_zeros_like_8[grid(8)](buf13, 8, XBLOCK=8,
            num_warps=1, num_stages=1)
        triton_poi_fused_scatter_zeros_like_9[grid(4)](buf12, buf11, buf13,
            4, XBLOCK=4, num_warps=1, num_stages=1)
        del buf11
        del buf12
    return buf13,


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


def differentiable_topk(x, k, temperature=1.0):
    *_, n, dim = x.shape
    topk_tensors = []
    for i in range(k):
        is_last = i == k - 1
        values, indices = (x / temperature).softmax(dim=-1).topk(1, dim=-1)
        topks = torch.zeros_like(x).scatter_(-1, indices, values)
        topk_tensors.append(topks)
        if not is_last:
            x.scatter_(-1, indices, float('-inf'))
    topks = torch.cat(topk_tensors, dim=-1)
    return topks.reshape(*_, k * n, dim)


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


def cumavg(t, dim):
    r = torch.arange(1, t.shape[dim] + 1, device=t.device, dtype=t.dtype)
    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, topk, temperature):
    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 + topk] = True
    R.masked_fill_(mask, mask_value)
    return differentiable_topk(R, topk, temperature)


class CausalAttentionSortNetNew(nn.Module):

    def __init__(self, heads, bucket_size, dim, temperature):
        super().__init__()
        self.heads = heads
        self.bucket_size = bucket_size
        self.dim = dim
        self.temperature = temperature

    def forward(self, input_0, input_1):
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1])
        return output[0]


Measured latency_ms: 0.161445