# Adapted from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/common/chunk_delta_h.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang

# from typing import Optional, Tuple

# import torch
# import triton
# import triton.language as tl

# from sglang.srt.layers.attention.fla.index import (
#     prepare_chunk_indices,
#     prepare_chunk_offsets,
# )
# from sglang.srt.layers.attention.fla.op import exp, safe_exp
# from sglang.srt.layers.attention.fla.utils import is_nvidia_hopper

# NUM_WARPS = [2, 4] if is_nvidia_hopper else [2, 4, 8, 16]


# @triton.heuristics(
#     {
#         "USE_G": lambda args: args["g"] is not None,
#         "USE_INITIAL_STATE": lambda args: args["h0"] is not None,
#         "STORE_FINAL_STATE": lambda args: args["ht"] is not None,
#         "SAVE_NEW_VALUE": lambda args: args["v_new"] is not None,
#         "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
#     }
# )
# # @triton.autotune(
# #     configs=[
# #         triton.Config({"BV": BV}, num_warps=num_warps, num_stages=num_stages)
# #         for num_warps in [2, 4]
# #         for num_stages in [2, 3, 4]
# #         for BV in [32, 64]
# #     ],
# #     key=["H", "K", "V", "BT", "USE_G"],
# #     use_cuda_graph=use_cuda_graph,
# # )
# @triton.jit(do_not_specialize=["T"])
# def chunk_gated_delta_rule_fwd_kernel_h_blockdim64(
#     k,
#     v,
#     w,
#     v_new,
#     g,
#     h,
#     h0,
#     ht,
#     cu_seqlens,
#     chunk_offsets,
#     T,
#     H: tl.constexpr,
#     Hg: tl.constexpr,
#     K: tl.constexpr,
#     V: tl.constexpr,
#     BT: tl.constexpr,
#     BV: tl.constexpr,
#     USE_G: tl.constexpr,
#     USE_INITIAL_STATE: tl.constexpr,
#     STORE_FINAL_STATE: tl.constexpr,
#     SAVE_NEW_VALUE: tl.constexpr,
#     IS_VARLEN: tl.constexpr,
# ):
#     i_v, i_nh = tl.program_id(0), tl.program_id(1)
#     i_n, i_h = i_nh // H, i_nh % H
#     if IS_VARLEN:
#         bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(
#             cu_seqlens + i_n + 1
#         ).to(tl.int32)
#         T = eos - bos
#         NT = tl.cdiv(T, BT)
#         boh = tl.load(chunk_offsets + i_n).to(tl.int32)
#     else:
#         bos, eos = i_n * T, i_n * T + T
#         NT = tl.cdiv(T, BT)
#         boh = i_n * NT

#     # [BK, BV]
#     b_h1 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 64:
#         b_h2 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 128:
#         b_h3 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 192:
#         b_h4 = tl.zeros([64, BV], dtype=tl.float32)

#     # calculate offset
#     h += (boh * H + i_h) * K * V
#     v += (bos * H + i_h) * V
#     k += (bos * Hg + i_h // (H // Hg)) * K
#     w += (bos * H + i_h) * K
#     if SAVE_NEW_VALUE:
#         v_new += (bos * H + i_h) * V
#     stride_v = H * V
#     stride_h = H * K * V
#     stride_k = Hg * K
#     stride_w = H * K
#     if USE_INITIAL_STATE:
#         h0 = h0 + i_nh * K * V
#     if STORE_FINAL_STATE:
#         ht = ht + i_nh * K * V

#     # load initial state
#     if USE_INITIAL_STATE:
#         p_h0_1 = tl.make_block_ptr(h0, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
#         b_h1 += tl.load(p_h0_1, boundary_check=(0, 1)).to(tl.float32)
#         if K > 64:
#             p_h0_2 = tl.make_block_ptr(
#                 h0, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0)
#             )
#             b_h2 += tl.load(p_h0_2, boundary_check=(0, 1)).to(tl.float32)
#         if K > 128:
#             p_h0_3 = tl.make_block_ptr(
#                 h0, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0)
#             )
#             b_h3 += tl.load(p_h0_3, boundary_check=(0, 1)).to(tl.float32)
#         if K > 192:
#             p_h0_4 = tl.make_block_ptr(
#                 h0, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0)
#             )
#             b_h4 += tl.load(p_h0_4, boundary_check=(0, 1)).to(tl.float32)

#     # main recurrence
#     for i_t in range(NT):
#         p_h1 = tl.make_block_ptr(
#             h + i_t * stride_h, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0)
#         )
#         tl.store(p_h1, b_h1.to(p_h1.dtype.element_ty), boundary_check=(0, 1))
#         if K > 64:
#             p_h2 = tl.make_block_ptr(
#                 h + i_t * stride_h, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_h2, b_h2.to(p_h2.dtype.element_ty), boundary_check=(0, 1))
#         if K > 128:
#             p_h3 = tl.make_block_ptr(
#                 h + i_t * stride_h, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_h3, b_h3.to(p_h3.dtype.element_ty), boundary_check=(0, 1))
#         if K > 192:
#             p_h4 = tl.make_block_ptr(
#                 h + i_t * stride_h, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_h4, b_h4.to(p_h4.dtype.element_ty), boundary_check=(0, 1))

#         p_v = tl.make_block_ptr(
#             v, (T, V), (stride_v, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0)
#         )
#         p_v_new = (
#             tl.make_block_ptr(
#                 v_new, (T, V), (stride_v, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0)
#             )
#             if SAVE_NEW_VALUE
#             else None
#         )
#         b_v_new = tl.zeros([BT, BV], dtype=tl.float32)
#         p_w = tl.make_block_ptr(
#             w, (T, K), (stride_w, 1), (i_t * BT, 0), (BT, 64), (1, 0)
#         )
#         b_w = tl.load(p_w, boundary_check=(0, 1))
#         b_v_new += tl.dot(b_w, b_h1.to(b_w.dtype))
#         if K > 64:
#             p_w = tl.make_block_ptr(
#                 w, (T, K), (stride_w, 1), (i_t * BT, 64), (BT, 64), (1, 0)
#             )
#             b_w = tl.load(p_w, boundary_check=(0, 1))
#             b_v_new += tl.dot(b_w, b_h2.to(b_w.dtype))
#         if K > 128:
#             p_w = tl.make_block_ptr(
#                 w, (T, K), (stride_w, 1), (i_t * BT, 128), (BT, 64), (1, 0)
#             )
#             b_w = tl.load(p_w, boundary_check=(0, 1))
#             b_v_new += tl.dot(b_w, b_h3.to(b_w.dtype))
#         if K > 192:
#             p_w = tl.make_block_ptr(
#                 w, (T, K), (stride_w, 1), (i_t * BT, 192), (BT, 64), (1, 0)
#             )
#             b_w = tl.load(p_w, boundary_check=(0, 1))
#             b_v_new += tl.dot(b_w, b_h4.to(b_w.dtype))
#         b_v_new = -b_v_new + tl.load(p_v, boundary_check=(0, 1))

#         if SAVE_NEW_VALUE:
#             p_v_new = tl.make_block_ptr(
#                 v_new, (T, V), (stride_v, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0)
#             )
#             tl.store(
#                 p_v_new, b_v_new.to(p_v_new.dtype.element_ty), boundary_check=(0, 1)
#             )

#         if USE_G:
#             last_idx = min((i_t + 1) * BT, T) - 1
#             b_g_last = tl.load(g + bos * H + last_idx * H + i_h)
#             p_g = tl.make_block_ptr(
#                 g + bos * H + i_h, (T,), (H,), (i_t * BT,), (BT,), (0,)
#             )
#             b_g = tl.load(p_g, boundary_check=(0,))
#             b_v_new = b_v_new * safe_exp(b_g_last - b_g)[:, None]
#             b_g_last = exp(b_g_last)
#             b_h1 = b_h1 * b_g_last
#             if K > 64:
#                 b_h2 = b_h2 * b_g_last
#             if K > 128:
#                 b_h3 = b_h3 * b_g_last
#             if K > 192:
#                 b_h4 = b_h4 * b_g_last
#         b_v_new = b_v_new.to(k.dtype.element_ty)
#         p_k = tl.make_block_ptr(
#             k, (K, T), (1, stride_k), (0, i_t * BT), (64, BT), (0, 1)
#         )
#         b_k = tl.load(p_k, boundary_check=(0, 1))
#         b_h1 += tl.dot(b_k, b_v_new)
#         if K > 64:
#             p_k = tl.make_block_ptr(
#                 k, (K, T), (1, stride_k), (64, i_t * BT), (64, BT), (0, 1)
#             )
#             b_k = tl.load(p_k, boundary_check=(0, 1))
#             b_h2 += tl.dot(b_k, b_v_new)
#         if K > 128:
#             p_k = tl.make_block_ptr(
#                 k, (K, T), (1, stride_k), (128, i_t * BT), (64, BT), (0, 1)
#             )
#             b_k = tl.load(p_k, boundary_check=(0, 1))
#             b_h3 += tl.dot(b_k, b_v_new)
#         if K > 192:
#             p_k = tl.make_block_ptr(
#                 k, (K, T), (1, stride_k), (192, i_t * BT), (64, BT), (0, 1)
#             )
#             b_k = tl.load(p_k, boundary_check=(0, 1))
#             b_h4 += tl.dot(b_k, b_v_new)

#     # epilogue
#     if STORE_FINAL_STATE:
#         p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
#         tl.store(p_ht, b_h1.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 64:
#             p_ht = tl.make_block_ptr(
#                 ht, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_ht, b_h2.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 128:
#             p_ht = tl.make_block_ptr(
#                 ht, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_ht, b_h3.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 192:
#             p_ht = tl.make_block_ptr(
#                 ht, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0)
#             )
#             tl.store(p_ht, b_h4.to(p_ht.dtype.element_ty), boundary_check=(0, 1))


# def chunk_gated_delta_rule_fwd_h(
#     k: torch.Tensor,
#     w: torch.Tensor,
#     u: torch.Tensor,
#     g: Optional[torch.Tensor] = None,
#     initial_state: Optional[torch.Tensor] = None,
#     output_final_state: bool = False,
#     chunk_size: int = 64,  # SY: remove this argument and force chunk size 64?
#     save_new_value: bool = True,
#     cu_seqlens: Optional[torch.LongTensor] = None,
# ) -> Tuple[torch.Tensor, torch.Tensor]:
#     B, T, Hg, K, V = *k.shape, u.shape[-1]
#     H = u.shape[-2]
#     BT = chunk_size

#     chunk_indices = (
#         prepare_chunk_indices(cu_seqlens, chunk_size)
#         if cu_seqlens is not None
#         else None
#     )
#     # N: the actual number of sequences in the batch with either equal or variable lengths
#     if cu_seqlens is None:
#         N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
#     else:
#         N, NT, chunk_offsets = (
#             len(cu_seqlens) - 1,
#             len(chunk_indices),
#             prepare_chunk_offsets(cu_seqlens, BT),
#         )
#     assert K <= 256, "current kernel does not support head dimension larger than 256."

#     h = k.new_empty(B, NT, H, K, V)
#     final_state = (
#         k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
#     )

#     v_new = torch.empty_like(u) if save_new_value else None

#     def grid(meta):
#         return (triton.cdiv(V, meta["BV"]), N * H)
#     # if hasattr(torch.version, 'hip') and torch.version.hip is not None:
#     # # HIP环境回退实现
#     #     return h, v_new, final_state
#     chunk_gated_delta_rule_fwd_kernel_h_blockdim64[grid](
#         k=k,
#         v=u,
#         w=w,
#         v_new=v_new,
#         g=g,
#         h=h,
#         h0=initial_state,
#         ht=final_state,
#         cu_seqlens=cu_seqlens,
#         chunk_offsets=chunk_offsets,
#         T=T,
#         H=H,
#         Hg=Hg,
#         K=K,
#         V=V,
#         BT=BT,
#         BV=32,
#         num_warps=4,
#         num_stages=2,
#     )
#     return h, v_new, final_state


from typing import Optional, Tuple
import math
import torch
import triton
import triton.language as tl

from sglang.srt.layers.attention.fla.index import (
    prepare_chunk_indices,
    prepare_chunk_offsets,
)
from sglang.srt.layers.attention.fla.op import exp, safe_exp
from sglang.srt.layers.attention.fla.utils import is_nvidia_hopper

# 保守一些在 HIP/ROCm 上更稳；NVIDIA 可调大
NUM_WARPS = [2, 4] if is_nvidia_hopper else [2, 4, 8, 16]


@triton.heuristics(
    {
        "USE_G": lambda args: args["g"] is not None,
        "USE_INITIAL_STATE": lambda args: args["h0"] is not None,
        "STORE_FINAL_STATE": lambda args: args["ht"] is not None,
        "SAVE_NEW_VALUE": lambda args: args["v_new"] is not None,
        "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
    }
)
@triton.jit(do_not_specialize=["T"])
def chunk_gated_delta_rule_fwd_kernel_h_blockdim64(
    k,            # [B, T, Hg, K]
    v,            # [B, T, H,  V]
    w,            # [B, T, H,  K]
    v_new,        # [B, T, H,  V] or None
    g,            # [B, T, H] or None
    h,            # [B, NT, H, K, V]
    h0,           # [B, H, K, V] or None
    ht,           # [B, H, K, V] or None
    cu_seqlens,   # [N+1] or None
    chunk_offsets,# [N] or None
    T,            # 全局 T（固定长时就是实际长度）
    H: tl.constexpr,
    Hg: tl.constexpr,
    K: tl.constexpr,
    V: tl.constexpr,
    BT: tl.constexpr,    # chunk size（通常 64）
    BV: tl.constexpr,    # V 方向 tile 宽度（通常 32）
    NT: tl.constexpr,    # host 计算的上界（chunk 数）
    USE_G: tl.constexpr,
    USE_INITIAL_STATE: tl.constexpr,
    STORE_FINAL_STATE: tl.constexpr,
    SAVE_NEW_VALUE: tl.constexpr,
    IS_VARLEN: tl.constexpr,
):
    # 程序实例：X 维为 V/BV，Y 维为 N*H
    i_v, i_nh = tl.program_id(0), tl.program_id(1)
    i_n = i_nh // H
    i_h = i_nh % H

    # 计算该序列 runtime 真实长度 TR、时间起点 bos、h 的 chunk 偏移 boh
    if IS_VARLEN:
        bos = tl.load(cu_seqlens + i_n).to(tl.int32)
        eos = tl.load(cu_seqlens + i_n + 1).to(tl.int32)
        TR = (eos - bos).to(tl.int32)
        TR = tl.maximum(TR, 0)
        boh = tl.load(chunk_offsets + i_n).to(tl.int32)
    else:
        bos = (i_n * T).to(tl.int32)
        eos = (i_n * T + T).to(tl.int32)
        TR = T.to(tl.int32)
        boh = (i_n * NT).to(tl.int32)

    # 预计算步长（以扁平指针计）
    stride_h_t = H * K * V      # h 时间块步长
    stride_k_hg = Hg * K        # k 的 Hg*K 步长
    stride_w_hk = H * K         # w 的 H*K 步长
    stride_v_hv = H * V         # v/v_new 的 H*V 步长

    # 移动到当前 sequence/head 的基址
    h = h + (boh * H + i_h) * (K * V)
    v = v + (bos * stride_v_hv + i_h * V)
    if SAVE_NEW_VALUE:
        v_new = v_new + (bos * stride_v_hv + i_h * V)
    k = k + (bos * stride_k_hg + (i_h // (H // Hg)) * K)
    w = w + (bos * stride_w_hk + i_h * K)

    # hidden state tiles
    b_h1 = tl.zeros([64, BV], dtype=tl.float32)
    if K > 64:
        b_h2 = tl.zeros([64, BV], dtype=tl.float32)
    if K > 128:
        b_h3 = tl.zeros([64, BV], dtype=tl.float32)
    if K > 192:
        b_h4 = tl.zeros([64, BV], dtype=tl.float32)

    # 初始状态
    if USE_INITIAL_STATE:
        h0 = h0 + i_nh * (K * V)
        p_h0_1 = tl.make_block_ptr(h0, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
        b_h1 += tl.load(p_h0_1, boundary_check=(0, 1)).to(tl.float32)
        if K > 64:
            p_h0_2 = tl.make_block_ptr(h0, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
            b_h2 += tl.load(p_h0_2, boundary_check=(0, 1)).to(tl.float32)
        if K > 128:
            p_h0_3 = tl.make_block_ptr(h0, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
            b_h3 += tl.load(p_h0_3, boundary_check=(0, 1)).to(tl.float32)
        if K > 192:
            p_h0_4 = tl.make_block_ptr(h0, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
            b_h4 += tl.load(p_h0_4, boundary_check=(0, 1)).to(tl.float32)

    # 最终状态写回基址
    if STORE_FINAL_STATE:
        ht = ht + i_nh * (K * V)

    # 主循环（上界 NT）
    for i_t in range(NT):
        # 先把当前 hidden state 写到 h（合法，因为 h 的时间维是 NT 上界）
        p_h1 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
        tl.store(p_h1, b_h1.to(p_h1.dtype.element_ty), boundary_check=(0, 1))
        if K > 64:
            p_h2 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
            tl.store(p_h2, b_h2.to(p_h2.dtype.element_ty), boundary_check=(0, 1))
        if K > 128:
            p_h3 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
            tl.store(p_h3, b_h3.to(p_h3.dtype.element_ty), boundary_check=(0, 1))
        if K > 192:
            p_h4 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
            tl.store(p_h4, b_h4.to(p_h4.dtype.element_ty), boundary_check=(0, 1))

        # 这个 chunk 是否有效（t0 >= TR 则整个 tile 越界 -> 跳过所有 block_ptr 操作）
        t0 = i_t * BT
        active = t0 < TR
        if active:
            # v_new = v - w @ h
            # --- w @ h ---
            b_v_new = tl.zeros([BT, BV], dtype=tl.float32)

            # w 的 0..63 列
            p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 0), (BT, 64), (1, 0))
            b_w = tl.load(p_w, boundary_check=(0, 1))        # 不能使用 mask
            b_v_new += tl.dot(b_w, b_h1.to(b_w.dtype))

            if K > 64:
                p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 64), (BT, 64), (1, 0))
                b_w = tl.load(p_w, boundary_check=(0, 1))
                b_v_new += tl.dot(b_w, b_h2.to(b_w.dtype))
            if K > 128:
                p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 128), (BT, 64), (1, 0))
                b_w = tl.load(p_w, boundary_check=(0, 1))
                b_v_new += tl.dot(b_w, b_h3.to(b_w.dtype))
            if K > 192:
                p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 192), (BT, 64), (1, 0))
                b_w = tl.load(p_w, boundary_check=(0, 1))
                b_v_new += tl.dot(b_w, b_h4.to(b_w.dtype))

            # v - (w @ h)
            p_v = tl.make_block_ptr(v, (TR, V), (stride_v_hv, 1), (t0, i_v * BV), (BT, BV), (1, 0))
            b_v_chunk = tl.load(p_v, boundary_check=(0, 1))   # 不能使用 mask
            b_v_new = -b_v_new + b_v_chunk

            # 保存 v_new
            if SAVE_NEW_VALUE:
                p_vn = tl.make_block_ptr(v_new, (TR, V), (stride_v_hv, 1), (t0, i_v * BV), (BT, BV), (1, 0))
                tl.store(p_vn, b_v_new.to(p_vn.dtype.element_ty), boundary_check=(0, 1))

            # gating：对 g 用普通指针 + mask 读取（不是 block_ptr）
            if USE_G:
                offs_t = t0 + tl.arange(0, BT)                 # [BT]
                t_mask = offs_t < TR                            # [BT]
                g_base = g + bos * H + i_h
                b_g = tl.load(g_base + offs_t * H, mask=t_mask, other=0.0)  # ✔ 这里不是 block_ptr，可用 mask

                t_end = tl.minimum(t0 + BT, TR)
                last_idx = tl.maximum(t_end - 1, 0).to(tl.int32)
                b_g_last = tl.load(g_base + last_idx * H, mask=(TR > 0), other=0.0)

                gating_factor = safe_exp(b_g_last - b_g)[:, None]
                b_v_new = b_v_new * gating_factor

                g_last_exp = exp(b_g_last)
                b_h1 = b_h1 * g_last_exp
                if K > 64:
                    b_h2 = b_h2 * g_last_exp
                if K > 128:
                    b_h3 = b_h3 * g_last_exp
                if K > 192:
                    b_h4 = b_h4 * g_last_exp

            # h += k^T @ v_new
            b_v_new_cast = b_v_new.to(k.dtype.element_ty)
            p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (0, t0), (64, BT), (0, 1))
            b_k = tl.load(p_k, boundary_check=(0, 1))         # 不能使用 mask
            b_h1 += tl.dot(b_k, b_v_new_cast)

            if K > 64:
                p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (64, t0), (64, BT), (0, 1))
                b_k = tl.load(p_k, boundary_check=(0, 1))
                b_h2 += tl.dot(b_k, b_v_new_cast)
            if K > 128:
                p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (128, t0), (64, BT), (0, 1))
                b_k = tl.load(p_k, boundary_check=(0, 1))
                b_h3 += tl.dot(b_k, b_v_new_cast)
            if K > 192:
                p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (192, t0), (64, BT), (0, 1))
                b_k = tl.load(p_k, boundary_check=(0, 1))
                b_h4 += tl.dot(b_k, b_v_new_cast)

    # 末态写回
    if STORE_FINAL_STATE:
        p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
        tl.store(p_ht, b_h1.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
        if K > 64:
            p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
            tl.store(p_ht, b_h2.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
        if K > 128:
            p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
            tl.store(p_ht, b_h3.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
        if K > 192:
            p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
            tl.store(p_ht, b_h4.to(p_ht.dtype.element_ty), boundary_check=(0, 1))


def chunk_gated_delta_rule_fwd_h(
    k: torch.Tensor,                    # [B, T, Hg, K]
    w: torch.Tensor,                    # [B, T, H,  K]
    u: torch.Tensor,                    # [B, T, H,  V]
    g: Optional[torch.Tensor] = None,   # [B, T, H]
    initial_state: Optional[torch.Tensor] = None,  # [B, H, K, V]
    output_final_state: bool = False,
    chunk_size: int = 64,
    save_new_value: bool = True,
    cu_seqlens: Optional[torch.LongTensor] = None, # [N+1] 或 None
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
    """
    Host wrapper：
    - 计算 NT（以 chunk 为单位的上界，constexpr）；
    - kernel 内对块是否有效做 runtime 守卫（active）；
    - block_ptr 的读写只用 boundary_check，严禁 mask/other；
    - 对 g 使用标量指针 + mask 读取。
    """
    B, T, Hg, K = k.shape
    H, V = u.shape[-2], u.shape[-1]
    BT = chunk_size

    if cu_seqlens is None:
        N = B
        NT = math.ceil(T / BT)                 # 固定长：全局上界
        chunk_offsets = None
    else:
        N = len(cu_seqlens) - 1
        chunk_indices = prepare_chunk_indices(cu_seqlens, BT)
        NT = len(chunk_indices)                # 变长：所有序列的总 chunk 数
        chunk_offsets = prepare_chunk_offsets(cu_seqlens, BT)

    assert K <= 256, "current kernel does not support head dimension larger than 256."

    h = k.new_empty(B, NT, H, K, V)
    final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
    v_new = torch.empty_like(u) if save_new_value else None

    def grid(meta):
        return (triton.cdiv(V, meta["BV"]), N * H)

    chunk_gated_delta_rule_fwd_kernel_h_blockdim64[grid](
        k=k,
        v=u,
        w=w,
        v_new=v_new,
        g=g,
        h=h,
        h0=initial_state,
        ht=final_state,
        cu_seqlens=cu_seqlens,
        chunk_offsets=chunk_offsets,
        T=T,
        H=H,
        Hg=Hg,
        K=K,
        V=V,
        BT=BT,
        BV=32,
        NT=NT,
        num_warps=2,
        num_stages=1,
    )
    return h, v_new, final_state




# from typing import Optional, Tuple
# import math
# import torch
# import triton
# import triton.language as tl

# from sglang.srt.layers.attention.fla.index import (
#     prepare_chunk_indices,
#     prepare_chunk_offsets,
# )
# from sglang.srt.layers.attention.fla.op import exp, safe_exp
# from sglang.srt.layers.attention.fla.utils import is_nvidia_hopper

# # 保守一些在 HIP/ROCm 上更稳；NVIDIA 可调大
# NUM_WARPS = [2, 4] if is_nvidia_hopper else [2, 4, 8, 16]


# @triton.heuristics(
#     {
#         "USE_G": lambda args: args["g"] is not None,
#         "USE_INITIAL_STATE": lambda args: args["h0"] is not None,
#         "STORE_FINAL_STATE": lambda args: args["ht"] is not None,
#         "SAVE_NEW_VALUE": lambda args: args["v_new"] is not None,
#         "IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
#     }
# )
# @triton.jit(do_not_specialize=["T"])
# def chunk_gated_delta_rule_fwd_kernel_h_blockdim64(
#     k,            # [B, T, Hg, K]
#     v,            # [B, T, H,  V]
#     w,            # [B, T, H,  K]
#     v_new,        # [B, T, H,  V] or None
#     g,            # [B, T, H] or None
#     h,            # [B, NT, H, K, V]
#     h0,           # [B, H, K, V] or None
#     ht,           # [B, H, K, V] or None
#     cu_seqlens,   # [N+1] or None
#     chunk_offsets,# [N] or None
#     T,            # 全局 T（固定长时就是实际长度）
#     H: tl.constexpr,
#     Hg: tl.constexpr,
#     K: tl.constexpr,
#     V: tl.constexpr,
#     BT: tl.constexpr,    # chunk size（通常 64）
#     BV: tl.constexpr,    # V 方向 tile 宽度（通常 32）
#     NT: tl.constexpr,    # host 计算的上界（chunk 数）
#     USE_G: tl.constexpr,
#     USE_INITIAL_STATE: tl.constexpr,
#     STORE_FINAL_STATE: tl.constexpr,
#     SAVE_NEW_VALUE: tl.constexpr,
#     IS_VARLEN: tl.constexpr,
# ):
#     # 程序实例：X 维为 V/BV，Y 维为 N*H
#     i_v, i_nh = tl.program_id(0), tl.program_id(1)
#     i_n = i_nh // H
#     i_h = i_nh % H

#     # 计算该序列 runtime 真实长度 TR、时间起点 bos、h 的 chunk 偏移 boh
#     if IS_VARLEN:
#         bos = tl.load(cu_seqlens + i_n).to(tl.int32)
#         eos = tl.load(cu_seqlens + i_n + 1).to(tl.int32)
#         TR = (eos - bos).to(tl.int32)
#         TR = tl.maximum(TR, 0)
#         boh = tl.load(chunk_offsets + i_n).to(tl.int32)
#     else:
#         bos = (i_n * T).to(tl.int32)
#         eos = (i_n * T + T).to(tl.int32)
#         TR = T.to(tl.int32)
#         boh = (i_n * NT).to(tl.int32)

#     # 预计算步长（以扁平指针计）
#     stride_h_t = H * K * V      # h 时间块步长
#     stride_k_hg = Hg * K        # k 的 Hg*K 步长
#     stride_w_hk = H * K         # w 的 H*K 步长
#     stride_v_hv = H * V         # v/v_new 的 H*V 步长

#     # 移动到当前 sequence/head 的基址
#     h = h + (boh * H + i_h) * (K * V)
#     v = v + (bos * stride_v_hv + i_h * V)
#     if SAVE_NEW_VALUE:
#         v_new = v_new + (bos * stride_v_hv + i_h * V)
#     k = k + (bos * stride_k_hg + (i_h // (H // Hg)) * K)
#     w = w + (bos * stride_w_hk + i_h * K)

#     # hidden state tiles
#     b_h1 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 64:
#         b_h2 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 128:
#         b_h3 = tl.zeros([64, BV], dtype=tl.float32)
#     if K > 192:
#         b_h4 = tl.zeros([64, BV], dtype=tl.float32)

#     # 初始状态
#     if USE_INITIAL_STATE:
#         h0 = h0 + i_nh * (K * V)
#         p_h0_1 = tl.make_block_ptr(h0, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
#         b_h1 += tl.load(p_h0_1, boundary_check=(0, 1)).to(tl.float32)
#         if K > 64:
#             p_h0_2 = tl.make_block_ptr(h0, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
#             b_h2 += tl.load(p_h0_2, boundary_check=(0, 1)).to(tl.float32)
#         if K > 128:
#             p_h0_3 = tl.make_block_ptr(h0, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
#             b_h3 += tl.load(p_h0_3, boundary_check=(0, 1)).to(tl.float32)
#         if K > 192:
#             p_h0_4 = tl.make_block_ptr(h0, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
#             b_h4 += tl.load(p_h0_4, boundary_check=(0, 1)).to(tl.float32)

#     # 最终状态写回基址
#     if STORE_FINAL_STATE:
#         ht = ht + i_nh * (K * V)

#     # 主循环（上界 NT）
#     for i_t in range(NT):
#         # 先把当前 hidden state 写到 h（合法，因为 h 的时间维是 NT 上界）
#         p_h1 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
#         tl.store(p_h1, b_h1.to(p_h1.dtype.element_ty), boundary_check=(0, 1))
#         if K > 64:
#             p_h2 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_h2, b_h2.to(p_h2.dtype.element_ty), boundary_check=(0, 1))
#         if K > 128:
#             p_h3 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_h3, b_h3.to(p_h3.dtype.element_ty), boundary_check=(0, 1))
#         if K > 192:
#             p_h4 = tl.make_block_ptr(h + i_t * stride_h_t, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_h4, b_h4.to(p_h4.dtype.element_ty), boundary_check=(0, 1))

#         # 这个 chunk 是否有效（t0 >= TR 则整个 tile 越界 -> 跳过所有 block_ptr 操作）
#         t0 = i_t * BT
#         active = t0 < TR
#         if active:
#             # v_new = v - w @ h
#             # --- w @ h ---
#             b_v_new = tl.zeros([BT, BV], dtype=tl.float32)

#             # w 的 0..63 列
#             p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 0), (BT, 64), (1, 0))
#             b_w = tl.load(p_w, boundary_check=(0, 1))        # 不能使用 mask
#             b_v_new += tl.dot(b_w, b_h1.to(b_w.dtype))

#             if K > 64:
#                 p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 64), (BT, 64), (1, 0))
#                 b_w = tl.load(p_w, boundary_check=(0, 1))
#                 b_v_new += tl.dot(b_w, b_h2.to(b_w.dtype))
#             if K > 128:
#                 p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 128), (BT, 64), (1, 0))
#                 b_w = tl.load(p_w, boundary_check=(0, 1))
#                 b_v_new += tl.dot(b_w, b_h3.to(b_w.dtype))
#             if K > 192:
#                 p_w = tl.make_block_ptr(w, (TR, K), (stride_w_hk, 1), (t0, 192), (BT, 64), (1, 0))
#                 b_w = tl.load(p_w, boundary_check=(0, 1))
#                 b_v_new += tl.dot(b_w, b_h4.to(b_w.dtype))

#             # v - (w @ h)
#             p_v = tl.make_block_ptr(v, (TR, V), (stride_v_hv, 1), (t0, i_v * BV), (BT, BV), (1, 0))
#             b_v_chunk = tl.load(p_v, boundary_check=(0, 1))   # 不能使用 mask
#             b_v_new = -b_v_new + b_v_chunk

#             # 保存 v_new
#             if SAVE_NEW_VALUE:
#                 p_vn = tl.make_block_ptr(v_new, (TR, V), (stride_v_hv, 1), (t0, i_v * BV), (BT, BV), (1, 0))
#                 tl.store(p_vn, b_v_new.to(p_vn.dtype.element_ty), boundary_check=(0, 1))

#             # gating：对 g 用普通指针 + mask 读取（不是 block_ptr）
#             if USE_G:
#                 offs_t = t0 + tl.arange(0, BT)                 # [BT]
#                 t_mask = offs_t < TR                            # [BT]
#                 g_base = g + bos * H + i_h
#                 b_g = tl.load(g_base + offs_t * H, mask=t_mask, other=0.0)  # ✔ 这里不是 block_ptr，可用 mask

#                 t_end = tl.minimum(t0 + BT, TR)
#                 last_idx = tl.maximum(t_end - 1, 0).to(tl.int32)
#                 b_g_last = tl.load(g_base + last_idx * H, mask=(TR > 0), other=0.0)

#                 gating_factor = safe_exp(b_g_last - b_g)[:, None]
#                 b_v_new = b_v_new * gating_factor

#                 g_last_exp = exp(b_g_last)
#                 b_h1 = b_h1 * g_last_exp
#                 if K > 64:
#                     b_h2 = b_h2 * g_last_exp
#                 if K > 128:
#                     b_h3 = b_h3 * g_last_exp
#                 if K > 192:
#                     b_h4 = b_h4 * g_last_exp

#             # h += k^T @ v_new
#             b_v_new_cast = b_v_new.to(k.dtype.element_ty)
#             p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (0, t0), (64, BT), (0, 1))
#             b_k = tl.load(p_k, boundary_check=(0, 1))         # 不能使用 mask
#             b_h1 += tl.dot(b_k, b_v_new_cast)

#             if K > 64:
#                 p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (64, t0), (64, BT), (0, 1))
#                 b_k = tl.load(p_k, boundary_check=(0, 1))
#                 b_h2 += tl.dot(b_k, b_v_new_cast)
#             if K > 128:
#                 p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (128, t0), (64, BT), (0, 1))
#                 b_k = tl.load(p_k, boundary_check=(0, 1))
#                 b_h3 += tl.dot(b_k, b_v_new_cast)
#             if K > 192:
#                 p_k = tl.make_block_ptr(k, (K, TR), (1, stride_k_hg), (192, t0), (64, BT), (0, 1))
#                 b_k = tl.load(p_k, boundary_check=(0, 1))
#                 b_h4 += tl.dot(b_k, b_v_new_cast)

#     # 末态写回
#     if STORE_FINAL_STATE:
#         p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (0, i_v * BV), (64, BV), (1, 0))
#         tl.store(p_ht, b_h1.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 64:
#             p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (64, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_ht, b_h2.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 128:
#             p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (128, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_ht, b_h3.to(p_ht.dtype.element_ty), boundary_check=(0, 1))
#         if K > 192:
#             p_ht = tl.make_block_ptr(ht, (K, V), (V, 1), (192, i_v * BV), (64, BV), (1, 0))
#             tl.store(p_ht, b_h4.to(p_ht.dtype.element_ty), boundary_check=(0, 1))


# def chunk_gated_delta_rule_fwd_h(
#     k: torch.Tensor,                    # [B, T, Hg, K]
#     w: torch.Tensor,                    # [B, T, H,  K]
#     u: torch.Tensor,                    # [B, T, H,  V]
#     g: Optional[torch.Tensor] = None,   # [B, T, H]
#     initial_state: Optional[torch.Tensor] = None,  # [B, H, K, V]
#     output_final_state: bool = False,
#     chunk_size: int = 64,
#     save_new_value: bool = True,
#     cu_seqlens: Optional[torch.LongTensor] = None, # [N+1] 或 None
# ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
#     """
#     Host wrapper：
#     - 计算 NT（以 chunk 为单位的上界，constexpr）；
#     - kernel 内对块是否有效做 runtime 守卫（active）；
#     - block_ptr 的读写只用 boundary_check，严禁 mask/other；
#     - 对 g 使用标量指针 + mask 读取。
#     """
#     B, T, Hg, K = k.shape
#     H, V = u.shape[-2], u.shape[-1]
#     BT = chunk_size

#     if cu_seqlens is None:
#         N = B
#         NT = math.ceil(T / BT)                 # 固定长：全局上界
#         chunk_offsets = None
#     else:
#         N = len(cu_seqlens) - 1
#         chunk_indices = prepare_chunk_indices(cu_seqlens, BT)
#         NT = len(chunk_indices)                # 变长：所有序列的总 chunk 数
#         chunk_offsets = prepare_chunk_offsets(cu_seqlens, BT)

#     assert K <= 256, "current kernel does not support head dimension larger than 256."

#     h = k.new_empty(B, NT, H, K, V)
#     final_state = k.new_empty(N, H, K, V, dtype=torch.float32) if output_final_state else None
#     v_new = torch.empty_like(u) if save_new_value else None

#     def grid(meta):
#         return (triton.cdiv(V, meta["BV"]), N * H)

#     chunk_gated_delta_rule_fwd_kernel_h_blockdim64[grid](
#         k=k,
#         v=u,
#         w=w,
#         v_new=v_new,
#         g=g,
#         h=h,
#         h0=initial_state,
#         ht=final_state,
#         cu_seqlens=cu_seqlens,
#         chunk_offsets=chunk_offsets,
#         T=T,
#         H=H,
#         Hg=Hg,
#         K=K,
#         V=V,
#         BT=BT,
#         BV=32,
#         NT=NT,
#         num_warps=2,
#         num_stages=1,
#     )
#     return h, v_new, final_state
