# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang

import warnings
from typing import Optional, Union

import torch
import triton
import triton.language as tl
from einops import rearrange

import sys
import os

# Get the directory of the current file
current_dir = os.path.dirname(__file__)

# Build the relative path to nsa_lib
target_dir = os.path.abspath(
    os.path.join(current_dir, '..', '..')
)

# Add to sys.path
sys.path.append(target_dir)
from fla.ops.common.utils import prepare_chunk_indices, prepare_chunk_offsets, prepare_lens, prepare_token_indices
from fla.ops.utils import mean_pooling
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, contiguous

try:
    from flash_attn import flash_attn_func, flash_attn_varlen_func
except ImportError:
    warnings.warn(
        "Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
        category=ImportWarning
    )
    flash_attn_func = None


@triton.heuristics({
    'USE_OFFSETS': lambda args: args['offsets'] is not None,
})
@triton.autotune(
    configs=[
        triton.Config({}, num_warps=num_warps)
        for num_warps in [1, 2, 4, 8, 16]
    ],
    key=['BS', 'BK', 'BV'],
)
@triton.jit
def parallel_hir_fwd_kernel(
    q,
    k,
    v,
    o,
    lse,
    scale,
    q_indices,
    k_indices,
    offsets,
    # token_indices,
    T,
    H: tl.constexpr,
    HQ: tl.constexpr,
    G: tl.constexpr,
    K: tl.constexpr,
    V: tl.constexpr,
    S: tl.constexpr,
    BS: tl.constexpr,
    BK: tl.constexpr,
    BV: tl.constexpr,
    USE_OFFSETS = 0,
    # USE_OFFSETS: tl.constexpr,
    # USE_BLOCK_COUNTS: tl.constexpr
):
    i_t, i_v, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H
 
    bos, eos = i_b * T, i_b * T + T  # begin idx, end idx
    # (T, NV, B * H)
    k += (bos * H + i_h) * K  # [2, 4096, 4, 64]  # (i_h)-th head
    v += (bos * H + i_h) * V  # [2, 4096, 4, 64]
    # query_idx: torch.Size([2, 4096, 8, 1]), key_idx: torch.Size([2, 256, 4, 16])
    q_indices += (bos + i_t) * H*S + i_h * S
    k_indices += (bos * H + i_h)

    NS = S

    # At compile-time: pick a candidate pad (16/32/64...)
    CAND_PAD: tl.constexpr = 16   # for example
    # At run-time: make sure we never under-pad (if G > CAND_PAD, just use G)
    G_PAD = G if G > CAND_PAD else CAND_PAD
    # Mask: only first G rows valid for this head
    if G>CAND_PAD:
        row_idx = tl.arange(0, G)
        p_q = q + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, G))[:, None] * K + tl.arange(0, BK)[None, :]
        b_m = tl.full([G], float('-inf'), dtype=tl.float32)
        p_lse = lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, G)
        p_o = (o + (bos + i_t) * HQ * V+ (i_h * G + tl.arange(0, G))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :])
        b_o = tl.zeros([G, BV], dtype=tl.float32)
        b_acc = tl.zeros([G], dtype=tl.float32)

    else:
        row_idx = tl.arange(0, CAND_PAD)
        p_q = q + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, CAND_PAD))[:, None] * K + tl.arange(0, BK)[None, :]
        b_m = tl.full([CAND_PAD], float('-inf'), dtype=tl.float32)
        p_lse = lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, CAND_PAD)
        p_o = (o + (bos + i_t) * HQ * V+ (i_h * G + tl.arange(0, CAND_PAD))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :])
        b_o = tl.zeros([CAND_PAD, BV], dtype=tl.float32)
        b_acc = tl.zeros([CAND_PAD], dtype=tl.float32)
    mask_q = row_idx < G
    # the Q block is kept in the shared memory throughout the whole kernel
    # [G, BK]
    b_q = tl.load(p_q, mask=mask_q[:, None], other=0)
    b_q = (b_q * scale).to(b_q.dtype)

    for i in range(NS):
        # i_s = tl.load(block_indices + i).to(tl.int32) * BS
        i_s = tl.load(q_indices + i).to(tl.int32) * BS
        p_k_idx = tl.make_block_ptr(k_indices, (T, 1), (H*1, 1), (i_s, 0), (BS, 1), (1, 0))
        b_k_idx = tl.load(p_k_idx, boundary_check=(0, 1))

        if i_s >= 0 and tl.sum(i_t>=b_k_idx)>0:   # i_s <= i_t and (T, NV, B * H) -> i_t, i_v, i_bh
            # q: [2, 4096, 4, 64] k,v: [2, 4096, 8, 64]
            p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
            p_v = tl.make_block_ptr(v, (T, V), (H*V, 1), (i_s, i_v * BV), (BS, BV), (1, 0))
            # [BK, BS]
            b_k = tl.load(p_k, boundary_check=(0, 1))
            # [BS, BV]
            b_v = tl.load(p_v, boundary_check=(0, 1))
            # [G, BS]
            b_s = tl.dot(b_q, b_k)
            b_s = tl.where(tl.trans((i_t >= b_k_idx), (1, 0)), b_s, float('-inf')) 
            # [G]
            b_m, b_mp = tl.maximum(b_m, tl.max(b_s, 1)), b_m
            b_r = tl.exp(b_mp - b_m)
            # [G, BS]
            b_p = tl.exp(b_s - b_m[:, None])
            # [G]
            b_acc = b_acc * b_r + tl.sum(b_p, 1)
            # [G, BV]
            b_o = b_o * b_r[:, None] + tl.dot(b_p.to(b_q.dtype), b_v)

            b_mp = b_m
    if tl.sum(b_acc)!=0:
        b_o = b_o / b_acc[:, None]
        b_m += tl.log(b_acc)
    tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_q[:,None])
    tl.store(p_lse, b_m.to(p_lse.dtype.element_ty),mask=mask_q)

@triton.jit
def parallel_hir_kernel_mask(
    q_indices,
    block_mask,
    T: tl.constexpr,
    H: tl.constexpr,
    S: tl.constexpr,
    BS: tl.constexpr,
    NS: tl.constexpr,
):
    i_t, i_b, i_hs = tl.program_id(0), tl.program_id(1), tl.program_id(2)  # (T, B, H*S)
    i_h, i_s = i_hs // S, i_hs % S

    b_i = tl.load(q_indices + i_b * T * H * S + i_t * H * S + i_h * S + i_s)  # block_indices

    if b_i < NS and b_i >= 0:
        tl.store(block_mask + i_b * T * H * NS + i_t * H * NS + i_h * NS + b_i, 1.)  # b_m.to(block_mask.dtype.element_ty)


@triton.jit
def parallel_hir_bwd_kernel_preprocess(
    o,
    do,
    delta,
    B: tl.constexpr,
    V: tl.constexpr
):
    i_n = tl.program_id(0)
    o_d = tl.arange(0, B)
    m_d = o_d < V

    b_o = tl.load(o + i_n * V + o_d, mask=m_d, other=0)
    b_do = tl.load(do + i_n * V + o_d, mask=m_d, other=0).to(tl.float32)
    b_delta = tl.sum(b_o * b_do)

    tl.store(delta + i_n, b_delta.to(delta.dtype.element_ty))


@triton.heuristics({
    'USE_OFFSETS': lambda args: args['offsets'] is not None,
})
@triton.autotune(
    configs=[
        triton.Config({}, num_warps=num_warps)
        for num_warps in [1, 2, 4, 8, 16]
    ],
    key=['BS', 'BK', 'BV'],
)
@triton.jit(do_not_specialize=['T'])
def parallel_hir_bwd_kernel_dq(
    q,
    k,
    v,
    lse,
    delta,
    do,
    dq,
    scale,
    q_indices,
    k_indices,
    # block_indices,
    # block_counts,
    offsets,
    # token_indices,
    T,
    B: tl.constexpr,
    H: tl.constexpr,
    HQ: tl.constexpr,
    G: tl.constexpr,
    K: tl.constexpr,
    V: tl.constexpr,
    S: tl.constexpr,
    BS: tl.constexpr,
    BK: tl.constexpr,
    BV: tl.constexpr,
    USE_OFFSETS=0,
    # USE_BLOCK_COUNTS: tl.constexpr
):
    i_t, i_v, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H

    bos, eos = i_b * T, i_b * T + T

    do += (bos + i_t) * HQ*V

    q_indices += (bos + i_t) * H*S + i_h * S
    k_indices += (bos * H + i_h)

    NS = S

    k += (bos * H + i_h) * K
    v += (bos * H + i_h) * V

    # At compile-time: pick a candidate pad (16/32/64...)
    CAND_PAD: tl.constexpr = 16   # for example
    # At run-time: make sure we never under-pad (if G > CAND_PAD, just use G)
    G_PAD = G if G > CAND_PAD else CAND_PAD
    # Mask: only first G rows valid for this head
    if G>CAND_PAD:
        row_idx = tl.arange(0, G)
        p_q = q + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, G))[:, None] * K + tl.arange(0, BK)[None, :]
        p_dq = dq + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, G))[:, None] * K + tl.arange(0, BK)[None, :]
        p_do = do + (i_h * G + tl.arange(0, G))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :]
        p_lse = lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, G)
        p_delta = delta + (bos + i_t) * HQ + i_h * G + tl.arange(0, G)

        b_dq = tl.zeros([G, BK], dtype=tl.float32)

    else:
        row_idx = tl.arange(0, CAND_PAD)
        p_q = q + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, CAND_PAD))[:, None] * K + tl.arange(0, BK)[None, :]
        p_dq = dq + (bos + i_t) * HQ * K + (i_h * G + tl.arange(0, CAND_PAD))[:, None] * K + tl.arange(0, BK)[None, :]
        p_do = do + (i_h * G + tl.arange(0, CAND_PAD))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :]
        p_lse = lse + (bos + i_t) * HQ + i_h * G + tl.arange(0, CAND_PAD)
        p_delta = delta + (bos + i_t) * HQ + i_h * G + tl.arange(0, CAND_PAD)
        
        b_dq = tl.zeros([CAND_PAD, BK], dtype=tl.float32)
    mask_q = row_idx < G

    # [G, BK]
    b_q = tl.load(p_q, mask=mask_q[:, None], other=0)
    b_q = (b_q * scale).to(b_q.dtype)

    # [G, BV]
    b_do = tl.load(p_do, mask=mask_q[:, None], other=0)
    # [G]
    b_lse = tl.load(p_lse, mask=mask_q, other=0)
    b_delta = tl.load(p_delta, mask=mask_q, other=0)

    # [G, BK]
    for i in range(NS):
        i_s = tl.load(q_indices + i).to(tl.int32) * BS
        p_k_idx = tl.make_block_ptr(k_indices, (T, 1), (H*1, 1), (i_s, 0), (BS, 1), (1, 0))
        b_k_idx = tl.load(p_k_idx, boundary_check=(0, 1))
        if i_s >= 0 and tl.sum(i_t>=b_k_idx)>0:  # i_s <= i_t and i_s >= 0:
            p_k = tl.make_block_ptr(k, (K, T), (1, H*K), (0, i_s), (BK, BS), (0, 1))
            p_v = tl.make_block_ptr(v, (V, T), (1, H*V), (i_v * BV, i_s), (BV, BS), (0, 1))
            # [BK, BS]
            b_k = tl.load(p_k, boundary_check=(0, 1))
            # [BV, BS]
            b_v = tl.load(p_v, boundary_check=(0, 1))

            # [G, BS]
            b_s = tl.dot(b_q, b_k)
            b_p = tl.exp(b_s - b_lse[:, None])
            b_p = tl.where(tl.trans((i_t >= b_k_idx), (1, 0)), b_p, 0)  # i_t >= (i_s + tl.arange(0, BS)))[None, :]

            # [G, BV] @ [BV, BS] -> [G, BS]
            b_dp = tl.dot(b_do, b_v)
            b_ds = b_p * (b_dp.to(tl.float32) - b_delta[:, None])
            # [G, BS] @ [BS, BK] -> [G, BK]
            b_dq += tl.dot(b_ds.to(b_k.dtype), tl.trans(b_k))
    b_dq *= scale
    tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), mask=mask_q[:, None])
    


@triton.heuristics({
    'USE_OFFSETS': lambda args: args['offsets'] is not None
})
@triton.autotune(
    configs=[
        triton.Config({}, num_warps=num_warps)
        for num_warps in [1, 2, 4, 8, 16]
    ],
    key=['BS', 'BK', 'BV'],
)
@triton.jit(do_not_specialize=['T'])
def parallel_hir_bwd_kernel_dkv(
    q,
    k,
    v,
    lse,
    delta,
    do,
    dk,
    dv,
    q_indices,
    k_indices,
    block_mask,
    offsets,
    chunk_indices,
    scale,
    T,
    B: tl.constexpr,
    H: tl.constexpr,
    HQ: tl.constexpr,
    G: tl.constexpr,
    K: tl.constexpr,
    V: tl.constexpr,
    M: tl.constexpr,
    BS: tl.constexpr,
    BK: tl.constexpr,
    BV: tl.constexpr,
    USE_OFFSETS=0
):
    i_v, i_s, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
    i_b, i_h = i_bh // H, i_bh % H

    bos, eos = i_b * T, i_b * T + T

    p_k = tl.make_block_ptr(k + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_s * BS, 0), (BS, BK), (1, 0))
    p_v = tl.make_block_ptr(v + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s * BS, i_v * BV), (BS, BV), (1, 0))
    p_dk = tl.make_block_ptr(dk + (i_v * B*T*H + bos * H + i_h) * K, (T, K), (H*K, 1), (i_s * BS, 0), (BS, BK), (1, 0))
    p_dv = tl.make_block_ptr(dv + (bos * H + i_h) * V, (T, V), (H*V, 1), (i_s * BS, i_v * BV), (BS, BV), (1, 0))

    p_k_idx = tl.make_block_ptr(k_indices + (bos * H + i_h) , (T, 1), (H*1, 1), (i_s * BS, 0), (BS, 1), (1, 0))

    # [BS, BK]
    b_k = tl.load(p_k, boundary_check=(0, 1))
    b_dk = tl.zeros([BS, BK], dtype=tl.float32)
    # p_k_idx = tl.make_block_ptr(k_indices, (1, T), (1, H*1), (0, i_s), (BK, BS), (0, 1))
    b_k_idx = tl.load(p_k_idx, boundary_check=(0, 1))
    # [BS, BV]
    b_v = tl.load(p_v, boundary_check=(0, 1))
    b_dv = tl.zeros([BS, BV], dtype=tl.float32)

    
    # At compile-time: pick a candidate pad (16/32/64...)
    CAND_PAD: tl.constexpr = 16   # for example
    # At run-time: make sure we never under-pad (if G > CAND_PAD, just use G)
    G_PAD = G if G > CAND_PAD else CAND_PAD
    # Mask: only first G rows valid for this head
    # given b_q, load b_v and b_k

    for i in range(T):  # (i_s * BS, T):
        b_m = tl.load(block_mask + (bos + i) * H*M + i_h * M + i_s)
        if b_m: 
            if G>CAND_PAD:
                row_idx = tl.arange(0, G)
                p_q = q + (bos + i) * HQ * K + (i_h * G + tl.arange(0, G))[:, None] * K + tl.arange(0, BK)[None, :]
                p_do = do + (bos + i) * HQ*V+  (i_h * G + tl.arange(0, G))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :]
                p_lse = lse + (bos + i) * HQ + i_h * G + tl.arange(0, G)
                p_delta = delta + (bos + i) * HQ + i_h * G + tl.arange(0, G)
            else:
                row_idx = tl.arange(0, CAND_PAD)
                p_q = q + (bos + i) * HQ * K + (i_h * G + tl.arange(0, CAND_PAD))[:, None] * K + tl.arange(0, BK)[None, :]
                p_do = do + (bos + i) * HQ*V+ (i_h * G + tl.arange(0, CAND_PAD))[:, None] * V+ (i_v * BV + tl.arange(0, BV))[None, :]
                p_lse = lse + (bos + i) * HQ + i_h * G + tl.arange(0, CAND_PAD)
                p_delta = delta + (bos + i) * HQ + i_h * G + tl.arange(0, CAND_PAD)
            mask_q = row_idx < G
            # [G, BK]
            b_q = tl.load(p_q, mask=mask_q[:, None], other=0)
            b_q = (b_q * scale).to(b_q.dtype)
            # [G, BV]
            b_do = tl.load(p_do, mask=mask_q[:, None], other=0)
            # [G]
            b_lse = tl.load(p_lse, mask=mask_q, other=0)
            b_delta = tl.load(p_delta, mask=mask_q, other=0)
            # [BS, G]
            b_s = tl.dot(b_k, tl.trans(b_q))
            b_p = tl.exp(b_s - b_lse[None, :])

            b_p = tl.where((i >= b_k_idx), b_p, 0)  # (i_s * BS + tl.arange(0, BS)))[:, None]
            # [BS, G] @ [G, BV] -> [BS, BV]
            b_dv += tl.dot(b_p.to(b_do.dtype), b_do)
            # [BS, BV] @ [BV, G] -> [BS, G]
            b_dp = tl.dot(b_v, tl.trans(b_do))
            # [BS, G]
            b_ds = b_p * (b_dp - b_delta[None, :])
            # [BS, G] @ [G, BK] -> [BS, BK]
            b_dk += tl.dot(b_ds.to(b_q.dtype), b_q)

    tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
    tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), boundary_check=(0, 1))


def parallel_hir_fwd(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    q_indices: torch.LongTensor,
    k_indices: torch.LongTensor,  
    block_size: int,
    scale: float,
    offsets: Optional[torch.LongTensor] = None,
    token_indices: Optional[torch.LongTensor] = None,
):
    B, T, H, K, V, S = *k.shape, v.shape[-1], q_indices.shape[-1]
    HQ = q.shape[2]
    G = HQ // H
    BS = block_size
    if torch.cuda.get_device_capability()[0] >= 9:
        BK = min(256, triton.next_power_of_2(K))
        BV = min(256, triton.next_power_of_2(V))
    else:
        BK = min(128, triton.next_power_of_2(K))
        BV = min(128, triton.next_power_of_2(V))
    NK = triton.cdiv(K, BK)
    NV = triton.cdiv(V, BV)
    assert NK == 1, "The key dimension can not be larger than 256"

    grid = (T, NV, B * H)
    o = torch.empty(B, T, HQ, V, dtype=v.dtype, device=q.device)
    lse = torch.empty(B, T, HQ, dtype=torch.float, device=q.device)
    parallel_hir_fwd_kernel[grid](
        q=q,
        k=k,
        v=v,
        o=o,
        lse=lse,
        scale=scale,
        q_indices=q_indices,   
        k_indices=k_indices,   
        offsets=offsets,
        T=T,
        H=H,
        HQ=HQ,
        G=G,
        K=K,
        V=V,
        S=S,
        BS=BS,
        BK=BK,
        BV=BV,
    )
    return o, lse


def parallel_hir_block_mask(
    q_indices: torch.LongTensor,
    offsets: torch.LongTensor,
    block_size: int,
):
    B, T, H, S = q_indices.shape
    BS = block_size
    NS = triton.cdiv(T, BS)
    block_mask = torch.zeros(B, T, H, NS, dtype=torch.bool, device=q_indices.device)

    parallel_hir_kernel_mask[(T, B, H*S)](
        q_indices=q_indices,
        block_mask=block_mask,
        T=T,
        H=H,
        S=S,
        BS=BS,
        NS=NS
    )
    return block_mask


def parallel_hir_bwd_preprocess(
    o: torch.Tensor,
    do: torch.Tensor
):
    V = o.shape[-1]
    delta = torch.empty_like(o[..., 0], dtype=torch.float32)
    parallel_hir_bwd_kernel_preprocess[(delta.numel(),)](
        o=o,
        do=do,
        delta=delta,
        B=triton.next_power_of_2(V),
        V=V,
    )
    return delta


def parallel_hir_bwd(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    o: torch.Tensor,
    lse: torch.Tensor,
    do: torch.Tensor,
    q_indices: torch.Tensor,
    k_indices: torch.Tensor,
    block_size: int = 64,
    scale: float = None,
    offsets: Optional[torch.LongTensor] = None,
    token_indices: Optional[torch.LongTensor] = None,
):
    B, T, H, K, V, S = *k.shape, v.shape[-1], q_indices.shape[-1] 
    HQ = q.shape[2]
    G = HQ // H
    BS = block_size
    BK = triton.next_power_of_2(K)
    BV = min(128, triton.next_power_of_2(v.shape[-1]))
    NV = triton.cdiv(V, BV)

    delta = parallel_hir_bwd_preprocess(o, do)
    dq = torch.empty(NV, *q.shape, dtype=q.dtype if NV == 1 else torch.float, device=q.device)
    grid = (T, NV, B * H)
    parallel_hir_bwd_kernel_dq[grid](
        q=q,
        k=k,
        v=v,
        lse=lse,
        delta=delta,
        do=do,
        dq=dq,
        q_indices=q_indices,
        k_indices=k_indices,
        offsets=offsets,
        scale=scale,
        T=T,
        B=B,
        H=H,
        HQ=HQ,
        G=G,
        K=K,
        V=V,
        S=S,
        BS=BS,
        BK=BK,
        BV=BV
    )
    dq = dq.sum(0)

    if offsets is not None:
        chunk_indices = prepare_chunk_indices(offsets, BS)
        NS = len(chunk_indices)
    else:
        chunk_indices = None
        NS = triton.cdiv(T, BS)

    # [B, T, H, M]  
    block_mask = parallel_hir_block_mask(q_indices, offsets, block_size)  # block_indices, block_counts
    dk = torch.empty(NV, *k.shape, dtype=k.dtype if NV == 1 else torch.float, device=q.device)
    dv = torch.empty(v.shape, dtype=v.dtype, device=q.device)

    grid = (NV, NS, B * H)
    parallel_hir_bwd_kernel_dkv[grid](
        q=q,
        k=k,
        v=v,
        lse=lse,
        delta=delta,
        do=do,
        dk=dk,
        dv=dv,
        q_indices=q_indices,
        k_indices=k_indices,
        block_mask=block_mask,
        offsets=offsets,
        chunk_indices=chunk_indices,
        scale=scale,
        T=T,
        B=B,
        H=H,
        HQ=HQ,
        G=G,
        K=K,
        V=V,
        M=block_mask.shape[-1],
        BS=BS,
        BK=BK,
        BV=BV
    )
    dk = dk.sum(0)
    return dq, dk, dv


@torch.compile
class ParallelhirFunction(torch.autograd.Function):

    @staticmethod
    @contiguous
    @autocast_custom_fwd   # block_indices  block_counts
    def forward(ctx, q, k, v, q_indices, k_indices, block_size, scale, offsets):
        ctx.dtype = q.dtype
        # 2-d sequence indices denoting the offsets of tokens in each sequence
        # for example, if the passed `offsets` is [0, 2, 6],
        # then there are 2 and 4 tokens in the 1st and 2nd sequences respectively, and `token_indices` will be
        # [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2], [1, 3]]
        o, lse = parallel_hir_fwd(
            q=q,
            k=k,
            v=v,
            q_indices=q_indices, #block_indices,
            k_indices=k_indices, # k_indices
            block_size=block_size,
            scale=scale,
            offsets=offsets,
        )
        ctx.save_for_backward(q, k, v, o, lse)
        ctx.q_indices = q_indices
        ctx.k_indices = k_indices
        ctx.offsets = offsets
        ctx.block_size = block_size
        ctx.scale = scale
        return o.to(q.dtype)

    @staticmethod
    @contiguous
    @autocast_custom_bwd
    def backward(ctx, do):
        q, k, v, o, lse = ctx.saved_tensors
        dq, dk, dv = parallel_hir_bwd(
            q=q,
            k=k,
            v=v,
            o=o,
            lse=lse,
            do=do,
            q_indices=ctx.q_indices,
            k_indices=ctx.k_indices,
            block_size=ctx.block_size,
            scale=ctx.scale,
            offsets=ctx.offsets,
        )
        return dq.to(q), dk.to(k), dv.to(v), None, None, None, None, None, None, None, None



def parallel_hir(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    g_topk: torch.Tensor,
    bucket_keys: torch.Tensor,
    bucket_values: torch.Tensor,
    q_indices: torch.LongTensor,
    k_indices: torch.LongTensor,
    block_size: int = 64,
    window_size: int = 0,
    scale: Optional[float] = None,
    cu_seqlens: Optional[torch.LongTensor] = None,
    head_first: bool = False
) -> torch.Tensor:
    r"""
    Args:
        q (torch.Tensor):
            queries of shape `[B, T, HQ, K]` if `head_first=False` else `[B, HQ, T, K]`.
        k (torch.Tensor):
            keys of shape `[B, T, H, K]` if `head_first=False` else `[B, H, T, K]`.
            GQA is enforced here. The ratio of query heads (HQ) to key/value heads (H) must be a power of 2 and >=16.
        v (torch.Tensor):
            values of shape `[B, T, H, V]` if `head_first=False` else `[B, H, T, V]`.
        g_cmp (torch.Tensor):
            Gate score for compressed attention of shape `[B, T, HQ]` if  `head_first=False` else `[B, HQ, T]`.
        g_slc (torch.Tensor):
            Gate score for selected attention of shape `[B, T, HQ]` if  `head_first=False` else `[B, HQ, T]`.
        g_swa (torch.Tensor):
            Gate score for sliding attentionof shape `[B, T, HQ]` if  `head_first=False` else `[B, HQ, T]`.
        block_indices (torch.LongTensor):
            Block indices of shape `[B, T, H, S]` if `head_first=False` else `[B, H, T, S]`.
            `S` is the number of selected blocks for each query token, which is set to 16 in the paper.
            If `g_cmp` is provided, the passed `block_indices` will be ignored.
        block_counts (Optional[Union[torch.LongTensor, int]]):
            Number of selected blocks for each query.
            If a tensor is provided, with shape `[B, T, H]` if `head_first=False` else `[B, H, T]`,
            each query can select the same number of blocks.
            If not provided, it will default to 16.
        block_size (int):
            Selected block size. Default: 64.
        window_size (int):
            Sliding window size. Default: 0.
        scale (Optional[int]):
            Scale factor for attention scores.
            If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
        head_first (Optional[bool]):
            Whether the inputs are in the head-first format. Default: `False`.
        cu_seqlens (torch.LongTensor):
            Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
            consistent with the FlashAttention API.

    Returns:
        o (torch.Tensor):
            Outputs of shape `[B, T, HQ, V]` if `head_first=False` else `[B, HQ, T, V]`.
    """
    # assert block_counts is not None, "block counts must be provided for selection"
    if scale is None:
        scale = k.shape[-1] ** -0.5
    if cu_seqlens is not None:
        assert q.shape[0] == 1, "batch size must be 1 when cu_seqlens are provided"
    if head_first:
        q, k, v = map(lambda x: rearrange(x, 'b h t d -> b t h d'), (q, k, v))
        g_topk = map(lambda x: rearrange(x, 'b h t -> b t h') if x is not None else None, g_topk)
                            # q: [2, 4096, 8, 64] bucket_kyes: [2, 4096, 4, 64]
                         # q_indices: [16->8, 4096, 1] k_indices: [8, 256, 16]. BS=16
    o_slc = ParallelhirFunction.apply(q, bucket_keys, bucket_values, q_indices, k_indices, block_size, scale, cu_seqlens)

    o = o_slc * g_topk[...,[0]]# for benchmark: g_topk[..., None] 
    if window_size > 0:
        if cu_seqlens is not None:
            max_seqlen = q.shape[1]
            o_swa = flash_attn_varlen_func(
                q.squeeze(0), k.squeeze(0), v.squeeze(0),
                cu_seqlens_q=cu_seqlens,
                cu_seqlens_k=cu_seqlens,
                max_seqlen_q=max_seqlen,
                max_seqlen_k=max_seqlen,
                causal=True,
                window_size=(window_size-1, 0)
            ).unsqueeze(0)
        else:
            o_swa = flash_attn_func(
                q, k, v,
                causal=True,
                window_size=(window_size-1, 0)
            )
        o = torch.addcmul(o, o_swa, g_topk[...,[1]])#  g_topk[..., None])
    if head_first:
        o = rearrange(o, 'b t h d -> b h t d')
    return o
