Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

53.2 KB
Raw Blame
from __future__ import annotations
import os
from typing_extensions import override
import math
import torch
import torch.nn.functional as F
from .module import Module
from .linear import Linear
from .rmsnorm import RMSNorm
from ..model.config import Config

# row-invariant verify in the sparse regime. In a verify forward (R = 2..8 rows) the indexer's qk
# projection, the per-row top-k selection and the gathered sparse attention are launched once for R rows, a different
# float order than the R = 1 launches plain decode makes. Both knobs run the exact R = 1 call per row.
#   EXL3_VERIFY_QSA_PROJ=1   qk projection per row
#   EXL3_VERIFY_QSA_ATTN=all|sel|att   selection and attention per row / selection only / attention only
# EXL3_QSA_SHADOW=1 (diagnostic): also run the per-row twin and count bitwise mismatches in SHADOW.
VERIFY_QSA_PROJ = {"on": os.environ.get("EXL3_VERIFY_QSA_PROJ", "0") not in ("", "0")}
VERIFY_QSA_ATTN = {"mode": {"": "", "0": "", "1": "all", "all": "all", "sel": "sel", "att": "att"}.get(os.environ.get("EXL3_VERIFY_QSA_ATTN", ""), "")}
QSA_SHADOW = {"on": os.environ.get("EXL3_QSA_SHADOW", "0") not in ("", "0")}
SHADOW: dict = {}


def shadow_note(key: str, a: torch.Tensor, b: torch.Tensor) -> None:
    n = SHADOW.setdefault(key, [0, 0, 0.0])
    n[0] += 1
    if not torch.equal(a, b):
        n[1] += 1
        if a.is_floating_point():
            n[2] = max(n[2], float((a.float() - b.float()).abs().max()))

"""
QSA (Qwen sparse attention) indexer: selects which tokens each query may attend to, at 4-token
block granularity (Qwen3.8-Flash-Next full-attention layers).

Per token, the indexer projects a raw 128-D key (cached unnormed and unroped) and index_n_heads
query heads (RMS-normed, partially roped at the query position). Every COMPLETE compress_ratio
block of raw keys is mean-pooled in fp32, RMS-normed, and roped at the block's START position.
Deterministic once the block completes, so pooled keys are cacheable/incremental. Block scores are
relu(q dot k) summed over the index heads / sqrt(head_dim); each query keeps the top
token_budget / compress_ratio blocks plus, always, the incomplete tail block. The selection is
ANDed into the causal mask of the main attention.

This module implements the eager batch path (no padding, contiguous positions). The rope tables
(cos/sin over the full history, matching the main attention's partial-rotary width) are supplied
by the caller.
"""


def _rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """
    Partial rotary on the first cos.shape[-1] dims of x. cos/sin broadcast over head dims.
    """
    r = cos.shape[-1]
    x_rope, x_pass = x[..., :r], x[..., r:]
    h = r // 2
    rot = torch.cat((-x_rope[..., h:], x_rope[..., :h]), dim = -1)
    return torch.cat((x_rope * cos + rot * sin, x_pass), dim = -1)


_PF_HIP = {"ok": {}}
def _pf_hip_ready(device) -> bool:
    """EXL3_QSA_PF_HIP (default 1, 0 = Triton pair): per-device first use loads the
    proven HIP prefill kernel; a missing compiler or proof disables it only on that device."""
    from exllamav3.util.arch_list import device_index
    idx = device_index(device)
    ok = _PF_HIP["ok"].get(idx)
    if ok is None:
        try:
            from .attention_fn.qsa_prefill_hip import _load
            _load("", device)
            ok = True
        except Exception as e:
            print(f" !! QSA prefill HIP kernel unavailable on cuda:{idx}, using the Triton pair: {str(e)[:200]}")
            ok = False
        _PF_HIP["ok"][idx] = ok
    return ok


def tile_candidates(scores, tile_idx, t0):
    """One tile's top-k as composite int64 keys: the top-k kernel's 16-bit order key (topk_key) above, 0xFFFFFFFF - global
    index below, -1 for padding and -inf scores (the kernel's own validity test). scores (R, W) fp16 view, tile_idx (R, kp)
    int32 local indices (-1 padded) as the kernel wrote them, t0 the tile's first pool."""
    li = tile_idx.long()
    bits = torch.gather(scores, 1, li.clamp(min = 0)).view(torch.int16).to(torch.int32) & 0xFFFF
    key = torch.where(bits >= 0x8000, ~bits & 0xFFFF, bits | 0x8000).long()
    return torch.where((li >= 0) & (key > 0x03FF), (key << 32) | (0xFFFFFFFF - (li + t0)), -1)


def merge_candidates(cand, k):
    """Top-k of the concatenated tile candidates under (score descending, index ascending), the single-pass kernel's order,
    returned as ascending global indices, -1 padded: (R, k) int32. Valid keys are unique, so the selection is exact."""
    top = torch.topk(torch.cat(cand, dim = 1), k, dim = 1, largest = True, sorted = False).values
    gi = torch.where(top >= 0, 0xFFFFFFFF - (top & 0xFFFFFFFF), 0x7FFFFFFF).sort(dim = 1).values
    return torch.where(gi == 0x7FFFFFFF, -1, gi).to(torch.int32)


def gather_tile(scores, tile_idx, t0, cand_s, cand_i):
    """Write one tile's top-k into its slot of the candidate buffers: the tile's own fp16 scores (bits untouched, -inf at the
    -1 pads) into cand_s (R, kp) and global pool indices (-1 pads) into cand_i (R, kp). Valid entries are ascending."""
    li = tile_idx.long()
    ok = li >= 0
    cand_s.copy_(torch.where(ok, torch.gather(scores, 1, li.clamp(min = 0)), float("-inf")))
    cand_i.copy_(torch.where(ok, li + t0, -1))


def merge_tiles_topk(topk_fn, cand_s, cand_i, pos_out, pool_idx, k):
    """Exact merge: one top-k pass of the single-pass kernel over the concatenated candidates (R, W), W a multiple of 128.
    Tiles are disjoint and ascending and each tile's valid entries ascend, so buffer position order is global index order:
    the kernel's rule (score descending, lowest position first among ties, ascending output) is the single pass's rule.
    pos_out (R, kp) int32 scratch, pool_idx (R, kp) int32 result (-1 padded)."""
    topk_fn(cand_s, pos_out, k, None, 0)
    pool_idx.copy_(torch.where(pos_out >= 0, torch.gather(cand_i, 1, pos_out.long().clamp(min = 0)), -1))


# EXL3_TOPK_PAR (read per call, default off in the library; the GLM and Qwen servers set it to 1). ROCm's dsa_topk
# runs ONE block per row, so a decode selection of a wide row leaves 39 of 40 CUs idle (2.63 ms/token over 12 layers
# at 459K). dsa_topk_par (dsa_topk_par.cu) cuts the same two-pass radix select into four kernels over nb blocks per
# row and is bitwise identical to ext.dsa_topk on the same buffer; it saves 0.91 ms/token at 500K. "1" = on;
# EXL3_TOPK_PAR_MIN_ROWS widens the row count beyond decode (kernel limit 16).
TOPK_PAR_MIN_T = int(os.environ.get("EXL3_TOPK_PAR_MIN_T", "32768"))
TOPK_PAR_MIN_ROWS = int(os.environ.get("EXL3_TOPK_PAR_MIN_ROWS", "1"))


def topk_par_ok(sc, k):
    """Whether dsa_topk_par may serve this call: few rows, a wide row, and the gfx12 kernel's own
    input contract (fp16 (R, T) with a 128-aligned row stride, k <= 512 <= output width), so the
    one-block kernel stays legal on the same buffer as the fallback."""
    from ..ext import exllamav3_ext as ext
    R, T = sc.shape
    return (os.environ.get("EXL3_TOPK_PAR", "0") == "1" and torch.version.hip is not None and
            hasattr(ext, "dsa_topk_par") and 1 <= R <= TOPK_PAR_MIN_ROWS <= 16 and
            T >= TOPK_PAR_MIN_T and 1 <= k <= 512 and sc.dtype == torch.half and
            sc.stride(1) == 1 and sc.stride(0) >= T and sc.stride(0) % 128 == 0)


# EXL3_TOPK_SPANS (read per call, default off): few-row, wide selections (decode / verify at depth) on the span-parallel route
# below. ROCm's dsa_topk runs ONE block per row, so R <= 16 rows of >= 32K pools use R blocks of a 40-CU GPU. 1 = spans
TOPK_SPAN_W = 8192


def topk_spans_ok(sc, k):
    """Whether dsa_topk_spans may serve this call: few rows, a wide row, and a score view whose row stride is a multiple of
    the span width (the power-of-two scoring workspaces)."""
    R, T = sc.shape
    return (os.environ.get("EXL3_TOPK_SPANS", "0") == "1" and torch.version.hip is not None and 1 <= R <= 16 and T >= 32768 and k <= 512
            and sc.stride(1) == 1 and sc.stride(0) % TOPK_SPAN_W == 0 and sc.dtype == torch.half)


def dsa_topk_spans(topk_fn, sc, out, k):
    """Exactly topk_fn(sc, out, k, None, 0) for a few-row selection, with the row cut into spans that run in parallel.
    sc (R, T) fp16 view of a WORKSPACE with row stride S (a multiple of TOPK_SPAN_W): the columns [T, S) are overwritten
    with -inf, the whole rows are then read as (R * S / w, w) span rows, one launch selects each span's local top-k, and
    merge_tiles_topk merges the (R, G * kp) candidates under the kernel's own total order (score descending, index
    ascending; spans are disjoint and ascending, each span's output ascends) = the single pass's result.
    out (R, kp) int32 (-1 padded)."""
    R, T = sc.shape
    S = sc.stride(0); w = TOPK_SPAN_W; G = S // w; kp = out.shape[1]
    full = sc.as_strided((R, S), (S, 1))
    full[:, T:].fill_(float("-inf"))
    sp = full.view(R * G, w)
    dev = sc.device
    out_sp = torch.empty((R * G, kp), dtype = torch.int32, device = dev)
    topk_fn(sp, out_sp, k, None, 0)
    li = out_sp.long()
    ok = li >= 0
    cand_s = torch.where(ok, torch.gather(sp, 1, li.clamp(min = 0)), float("-inf")).view(R, G * kp)
    off = (torch.arange(R * G, device = dev, dtype = torch.int32) % G * w).view(R * G, 1)
    cand_i = torch.where(ok, out_sp + off, -1).view(R, G * kp)
    W = -(-(G * kp) // 128) * 128
    if W != G * kp:
        cand_s = torch.nn.functional.pad(cand_s, (0, W - G * kp), value = float("-inf"))
        cand_i = torch.nn.functional.pad(cand_i, (0, W - G * kp), value = -1)
    pos = torch.empty((R, kp), dtype = torch.int32, device = dev)
    merge_tiles_topk(topk_fn, cand_s, cand_i, pos, out, k)


class QSAIndexer(Module):

    def __init__(
        self,
        config: Config | None,
        key: str,
        hidden_size: int,
        n_heads: int,
        kv_heads: int,
        head_dim: int,
        token_budget: int,
        compress_ratio: int,
        rms_norm_eps: float,
        qmap: str | None = None,
        out_dtype: torch.dtype | None = None,
        qbits_key: str = "bits",
    ):
        super().__init__(config = config, key = key, qmap = None)
        assert kv_heads == 1, "QSAIndexer assumes a single raw key head"
        self.hidden_size = hidden_size
        self.n_heads = n_heads
        self.head_dim = head_dim
        self.token_budget = token_budget
        self.compress_ratio = compress_ratio
        self.block_topk = token_budget // compress_ratio
        self.scale = 1.0 / math.sqrt(head_dim)

        self.index_qk_proj = Linear(
            config = config,
            key = f"{key}.index_qk_proj",
            in_features = hidden_size,
            out_features = (n_heads + kv_heads) * head_dim,
            qmap = qmap + ".input" if qmap is not None else None,
            out_dtype = torch.half,
            qbits_key = qbits_key,
        )
        self.q_layernorm = RMSNorm(config, f"{key}.q_layernorm", rms_norm_eps, constant_bias = 1.0)
        self.k_layernorm = RMSNorm(config, f"{key}.k_layernorm", rms_norm_eps, constant_bias = 1.0)
        self.register_submodule(self.index_qk_proj)
        self.register_submodule(self.q_layernorm)
        self.register_submodule(self.k_layernorm)

    @override
    def optimizer_targets(self):
        return self.index_qk_proj.optimizer_targets()

    @override
    def forward(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None = None):
        raise RuntimeError("QSAIndexer is not a standalone graph module; use project()/select()")

    def project(self, x: torch.Tensor, rope, params: dict, position: int = 0):
        """
        x: (bsz, seq, hidden); queries roped in-kernel at position + token index (sin/cos
        computed on the fly from inv_freq -- no cached tables). Returns (q (bsz, seq, n_heads,
        head_dim) normed + roped, raw_k (bsz, seq, head_dim) unnormed/unroped -- this is what
        the indexer key cache stores).
        """
        bsz, seq, _ = x.shape
        qk = self.index_qk_proj.forward(x.contiguous(), params)
        q, raw_k = qk.split([self.n_heads * self.head_dim, self.head_dim], dim = -1)
        q = self.q_layernorm.forward(q.reshape(bsz, seq, self.n_heads, self.head_dim).contiguous(), params)
        rope.apply(q, None, position, None, None, True)
        return q, raw_k

    def pool_keys(self, raw_k: torch.Tensor, rope, params: dict):
        """
        raw_k: (bsz, total_len, head_dim) full raw key history. Returns pooled block keys
        (bsz, num_blocks, head_dim): fp32 mean over each complete block, normed, roped in-kernel
        at the block START position (a stride-cr position_ids ramp).
        """
        bsz, total, dk = raw_k.shape
        cr = self.compress_ratio
        nb = total // cr
        if nb == 0:
            return raw_k.new_zeros((bsz, 0, dk))
        pooled = raw_k[:, : nb * cr].view(bsz, nb, cr, dk).float().mean(dim = 2).to(raw_k.dtype)
        pooled = self.k_layernorm.forward(pooled, params)
        starts = (torch.arange(nb, dtype = torch.int32, device = raw_k.device) * cr) \
            .unsqueeze(0).expand(bsz, nb).contiguous()
        rope.apply(pooled.view(bsz, nb, 1, dk), None, 0, None, starts, True)
        return pooled

    def project_ref(self, x: torch.Tensor, cos_q: torch.Tensor, sin_q: torch.Tensor, params: dict):
        """
        x: (bsz, seq, hidden); cos_q/sin_q: rope tables for the query positions, broadcastable to
        (bsz, seq, 1, rope_dim).
        Returns:
            q (bsz, seq, n_heads, head_dim) normed + roped
            raw_k (bsz, seq, head_dim) unnormed/unroped (this is what the indexer key cache stores).
        """
        bsz, seq, _ = x.shape
        qk = self.index_qk_proj.forward(x.contiguous(), params)
        q, raw_k = qk.split([self.n_heads * self.head_dim, self.head_dim], dim = -1)
        q = self.q_layernorm.forward(q.reshape(bsz, seq, self.n_heads, self.head_dim).contiguous(), params)
        q = _rope(q, cos_q.unsqueeze(-2), sin_q.unsqueeze(-2))
        return q, raw_k

    def pool_keys_ref(self, raw_k: torch.Tensor, cos_full: torch.Tensor, sin_full: torch.Tensor, params: dict):
        """
        raw_k: (bsz, total_len, head_dim) full raw key history; cos_full/sin_full: rope tables for
        positions 0..total_len-1, broadcastable to (bsz, total_len, rope_dim).
        Returns:
             pooled block keys (bsz, num_blocks, head_dim): fp32 mean over each complete block, normed,
            roped at the block start position.
        """
        bsz, total, dk = raw_k.shape
        cr = self.compress_ratio
        nb = total // cr
        if nb == 0:
            return raw_k.new_zeros((bsz, 0, dk))
        pooled = raw_k[:, : nb * cr].view(bsz, nb, cr, dk).float().mean(dim = 2).to(raw_k.dtype)
        pooled = self.k_layernorm.forward(pooled, params)
        starts = torch.arange(0, nb * cr, cr, device = raw_k.device)
        return _rope(pooled, cos_full[..., starts, :], sin_full[..., starts, :])

    def block_scores(self, q: torch.Tensor, pooled: torch.Tensor):
        """
        q (bsz, seq, H, dk), pooled (bsz, nb, dk) -> (bsz, seq, nb) fp32
        """
        s = torch.einsum("bshd,bnd->bshn", q.float(), pooled.float())
        return F.relu(s).sum(dim = 2) * self.scale

    def token_mask(self, q: torch.Tensor, pooled: torch.Tensor, past_len: int, total_len: int):
        """
        Selection mask for causal, unpadded attention: (bsz, seq, total_len) bool, True = may
        attend (already includes causality). past_len = absolute position of the first query
        """
        bsz, seq = q.shape[:2]
        cr = self.compress_ratio
        dev = q.device
        abs_pos = past_len + torch.arange(seq, device = dev)                     # (seq,)
        kv_pos = torch.arange(total_len, device = dev)                           # (total,)
        nb_q = (abs_pos + 1) // cr                                               # complete blocks per query
        nb = pooled.shape[1]

        # tail (incomplete visible block) and causality
        mask = (kv_pos.unsqueeze(0) >= nb_q.unsqueeze(1) * cr) & \
               (kv_pos.unsqueeze(0) <= abs_pos.unsqueeze(1))                     # (seq, total)
        mask = mask.unsqueeze(0).expand(bsz, -1, -1).contiguous()

        if nb > 0:
            scores = self.block_scores(q, pooled)                                # (bsz, seq, nb)
            block_j = torch.arange(nb, device = dev)
            scores = scores.masked_fill(block_j.unsqueeze(0) >= nb_q.unsqueeze(1), -torch.inf)
            k = min(self.block_topk, nb)
            sel = scores.topk(k, dim = -1).indices                               # (bsz, seq, k)
            block_mask = torch.zeros((bsz, seq, nb), dtype = torch.bool, device = dev)
            block_mask.scatter_(-1, sel, True)
            # blocks selected past a query's visible range only cover future tokens (or the
            # force-included tail block), so causality below keeps the mask correct
            token_sel = block_mask.repeat_interleave(cr, dim = -1)
            if token_sel.shape[-1] < total_len:
                token_sel = F.pad(token_sel, (0, total_len - token_sel.shape[-1]))
            else:
                token_sel = token_sel[..., :total_len]
            mask |= token_sel & (kv_pos.view(1, 1, -1) <= abs_pos.view(1, -1, 1))
        return mask

    # ---- selection kernels -------------------------------------------------------------------
    # Selection = score -> top-k -> expand, three launches per (sequence, row slab), the same
    # kernels the BC sparse-decode graph runs (row-tiled scorer for many queries). Every scalar
    # comes from the host-side cache lengths: no per-layer H2D copy, no sync, and none of the
    # arange/where/cat elementwise chains of the torch references kept below for the tests

    # Rows per launch (also the expand kernel's fixed SEQ constexpr) and pools per score tile.
    # Selection scores are computed tile by tile into a fixed SEL_SLAB x SEL_TILE fp16 slab
    # (16 MiB, sharing the DSA indexer's backing) with a running top-k candidate set, so the
    # workspace never scales with the context (a single rows x T buffer would be 128 MiB per
    # slab at 256K). The slab stays wide: the scorer's pooled-key reuse is per row slab, so
    # narrower slabs cost more than the extra top-k passes save
    SEL_SLAB = 1024
    SEL_TILE = int(os.environ.get("EXL3_QSA_SCORE_TILE", 8192))
    # Scorer launch shape "block_m,block_n,num_warps,num_stages" (EXL3_QSA_SCORE_CFG, read per call; "0" = the scorer's
    # own 64,128,8,2). Every output element is computed by the same MMA sequence whatever the tile, so the scores are
    # bit-identical. 4 indexer heads give 4 small dots per key tile: on gfx1151, 1024-row slabs, 32,64,4,2 is x1.50 at
    # 2K-8K pools, x1.31 at 16K, x1.33 at 32K (bitwise equal; sweep of 72 shapes); in a served Qwen load the scorer time
    # drops x1.10-1.31 at 16K-64K prompts, logits bitwise. CUDA keeps the scorer's own default (not measured there)
    SCORE_CFG = "32,64,4,2" if torch.version.hip else "0"
    # ROCm has no dsa_topk_tile / dsa_topk_merge_tiles: its one-block-per-row top-k scans a row three times, and
    # beyond ~32K pools the row no longer stays cache resident (about 10x the cost per column at 64K pools). N > 0 never
    # lets that kernel see a row wider than N pools: a longer selection is cut into equal tiles of at most N pools (a
    # multiple of 128), each run through the same kernel, and the candidates are merged in torch under the kernel's own
    # total order. Rows up to N pools stay one pass. Default 32768; 0 = always one full-width pass
    TOPK_TILE = int(os.environ.get("EXL3_QSA_TOPK_TILE", 32768))
    # The tiled selection serves prefill chunks only: calls of at most TOPK_MIN_ROWS rows (decode, MTP verify rounds,
    # bsz > 1 fallbacks) keep the single pass, whose result is identical. "topk" merges the tile candidates with one more
    # pass of the same kernel over the (R, tiles * kp) candidate buffer; "torch" is the elementwise merge kept for A/B runs
    TOPK_MIN_ROWS = int(os.environ.get("EXL3_QSA_TOPK_MIN_ROWS", 32))
    TOPK_MERGE = os.environ.get("EXL3_QSA_TOPK_MERGE", "topk")
    # Row count up to which the plane-update workspaces come from g_tensor_cache (decode-class
    # calls: MTP verify, bsz > 1 fallbacks, where allocation latency matters); prefill chunks
    # allocate per call, the static cache being meant for small buffers only
    STATIC_ROWS = 32

    @staticmethod
    def _workspace(rows: int, numel: int, dtype, tag: str, device):
        from ..util.tensor import g_tensor_cache
        if rows <= QSAIndexer.STATIC_ROWS:
            return g_tensor_cache.get_bucketed(device, numel, dtype, tag)
        # Power-of-two size so the caching allocator reuses the freed block across chunks: the
        # score width grows with the context, and exact sizes would cache one segment per chunk
        nb = 1 << max(numel - 1, 0).bit_length()
        return torch.empty((nb,), dtype = dtype, device = device)[:numel]

    def k_pad(self):
        cr = self.compress_ratio
        return -(-(self.block_topk * cr + cr - 1) // 32) * 32

    def _sel_weights(self, rows: int, device):
        w = getattr(self, "_sel_w", None)
        if w is None or w.device != device:
            w = self._sel_w = torch.ones((self.SEL_SLAB, self.n_heads), dtype = torch.half, device = device)
        return w[:rows]

    def _select_rows(self, q_rows, pool_flat, pos0, T, out_rows, block_table = None, epp = 0):
        """
        One sequence's selection for consecutive query rows starting at absolute position pos0:
        q_rows (R, H, dk) roped, pool_flat (rows, dk) pooled keys (contiguous, or the paged plane
        with block_table/epp), T visible complete pools for the last row. Writes out_rows
        (R, K_pad) int32: selected pools expanded to tokens plus each row's tail, -1 padded.

        Scores are computed per SEL_TILE pools into a fixed slab. Beyond one tile the per-tile
        top-k candidates are merged under dsa_topk's own total order (score desc, index asc), so
        the result is identical to a single pass over the whole row.
        """
        import triton
        from .attention_fn.dsa_triton import dsa_indexer_scores, _dsa_pool_expand_kernel
        from ..ext import exllamav3_ext as ext
        from ..util.tensor import g_tensor_cache
        R = q_rows.shape[0]
        cr = self.compress_ratio
        dev = q_rows.device
        k_pad = out_rows.shape[1]
        k_sel = self.block_topk
        kp = -(-k_sel // 32) * 32
        tiled_topk = hasattr(ext, "dsa_topk_tile") and hasattr(ext, "dsa_topk_merge_tiles")
        torch_merge = not tiled_topk and self.TOPK_TILE > 0 and R > self.TOPK_MIN_ROWS
        t_tile = self.TOPK_TILE // 128 * 128 if torch_merge else self.SEL_TILE
        if block_table is not None:
            t_tile = max(epp, t_tile // epp * epp)   # tiles must start on a pool page
        # Fixed score-row stride for every tile: it is a constexpr of the scoring kernel, so a
        # stride that followed the visible length recompiled it at every new 128-pool boundary
        s_stride = -(-t_tile // 128) * 128
        s_backing = g_tensor_cache.get(dev, (self.SEL_SLAB * s_stride,), torch.half, "dsa_stile")

        cfg = {}
        score_cfg = os.environ.get("EXL3_QSA_SCORE_CFG", self.SCORE_CFG)
        if score_cfg != "0":
            bm, bn, nw, ns = (int(x) for x in score_cfg.split(","))
            cfg = dict(block_m = bm, block_n = bn, num_warps = nw, num_stages = ns)

        def tile_scores(q_slab, rows, t0, t1):
            # Tile [t0, t1) of the pooled plane scored as if it started at pool 0: the row-0
            # position shifts by t0 * cr so the causal bounds shift by t0. Contiguous pools:
            # the launcher scans k_idx.shape[0] rows, so hand it exactly the visible ones
            if t1 - t0 > t_tile:
                # Full-width pass (the untiled route scores beyond one tile): the fixed tile
                # stride cannot hold it, so score into a separate backing whose power-of-two
                # stride also bounds the scoring kernel's constexpr recompiles by log2 of the
                # context
                s_full = max(128, triton.next_power_of_2(t1 - t0))
                sc = g_tensor_cache.get_bucketed(dev, rows * s_full, torch.half, "dsa_sfull") \
                        .view(rows, s_full)
            else:
                sc = s_backing[: rows * s_stride].view(rows, s_stride)
            if block_table is None:
                return dsa_indexer_scores(
                    q_slab, self._sel_weights(rows, dev), pool_flat[t0 : t1], pos0 + r0 - t0 * cr,
                    cr, t1 - t0, scores = sc, scale = self.scale, **cfg,
                )
            bt = block_table[t0 // epp : -(-t1 // epp)] if t0 else block_table
            return dsa_indexer_scores(
                q_slab, self._sel_weights(rows, dev), pool_flat, pos0 + r0 - t0 * cr, cr, t1 - t0,
                scores = sc, block_table = bt, epp = epp, scale = self.scale, **cfg,
            )

        for r0 in range(0, R, self.SEL_SLAB):
            r1 = min(r0 + self.SEL_SLAB, R)
            rows = r1 - r0
            T_slab = min(T, (pos0 + r1) // cr)
            pool_idx = g_tensor_cache.get_bucketed(dev, rows * kp, torch.int32, "qsa_sel_pool") \
                .view(rows, kp)
            q_slab = q_rows[r0 : r1]
            if T_slab <= 0:
                pool_idx.fill_(-1)
            elif T_slab <= t_tile or (not tiled_topk and not torch_merge):
                sc = tile_scores(q_slab, rows, 0, T_slab)
                k_call = min(k_sel, T_slab)
                if topk_par_ok(sc, k_call):
                    ext.dsa_topk_par(sc, pool_idx, k_call)
                elif topk_spans_ok(sc, k_call):
                    dsa_topk_spans(ext.dsa_topk, sc, pool_idx, k_call)
                else:
                    ext.dsa_topk(sc, pool_idx, k_call, None, 0)
            elif torch_merge and self.TOPK_MERGE == "torch":
                cand = []
                tile_idx = torch.empty((rows, kp), dtype = torch.int32, device = dev)
                n_tiles = -(-T_slab // t_tile)
                w = -(-(-(-T_slab // n_tiles)) // 128) * 128   # equal tiles, 128 aligned
                for t0 in range(0, T_slab, w):
                    t1 = min(t0 + w, T_slab)
                    sc = tile_scores(q_slab, rows, t0, t1)
                    ext.dsa_topk(sc, tile_idx, min(k_sel, t1 - t0), None, 0)
                    cand.append(tile_candidates(sc, tile_idx, t0))
                pool_idx[:, :k_sel] = merge_candidates(cand, k_sel)
                pool_idx[:, k_sel:] = -1
            elif torch_merge:
                tile_idx = torch.empty((rows, kp), dtype = torch.int32, device = dev)
                n_tiles = -(-T_slab // t_tile)
                w = -(-(-(-T_slab // n_tiles)) // 128) * 128   # equal tiles, 128 aligned
                W = -(-(n_tiles * kp) // 128) * 128
                cand_s = torch.full((rows, W), float("-inf"), dtype = torch.half, device = dev)
                cand_i = torch.full((rows, W), -1, dtype = torch.int32, device = dev)
                for n, t0 in enumerate(range(0, T_slab, w)):
                    t1 = min(t0 + w, T_slab)
                    sc = tile_scores(q_slab, rows, t0, t1)
                    ext.dsa_topk(sc, tile_idx, min(k_sel, t1 - t0), None, 0)
                    gather_tile(sc, tile_idx, t0, cand_s[:, n * kp : (n + 1) * kp], cand_i[:, n * kp : (n + 1) * kp])
                merge_tiles_topk(ext.dsa_topk, cand_s, cand_i, tile_idx, pool_idx, k_sel)
            else:
                # Tiled: each tile's local top-k becomes candidate slot 1 next to the running set
                # in slot 0, and the native merge reduces the pair under the single-pass kernel's
                # own total order (score descending, index ascending), emitting the merged set --
                # with scores -- into slot 0 of the other workspace for the next tile. Workspaces
                # are fixed-size per call, so the allocator reuses them across chunks
                ws = [(torch.empty((rows, 2, kp), dtype = torch.int32, device = dev),
                       torch.empty((rows, 2, kp), dtype = torch.half, device = dev),
                       torch.zeros((rows, 2), dtype = torch.int32, device = dev)) for _ in range(2)]
                cur = 0
                tiles = list(range(0, T_slab, t_tile))
                for n, t0 in enumerate(tiles):
                    t1 = min(t0 + t_tile, T_slab)
                    sc = tile_scores(q_slab, rows, t0, t1)
                    w_idx, w_scr, w_cnt = ws[cur]
                    ext.dsa_topk_tile(sc, w_idx, w_scr, w_cnt, 1, min(k_sel, t1 - t0), t0)
                    if n == len(tiles) - 1:
                        ext.dsa_topk_merge_tiles(w_idx, w_scr, w_cnt, pool_idx, None, None, k_sel)
                    else:
                        n_idx, n_scr, n_cnt = ws[cur ^ 1]
                        ext.dsa_topk_merge_tiles(
                            w_idx, w_scr, w_cnt, n_idx[:, 0], n_scr[:, 0], n_cnt[:, 0], k_sel)
                        cur ^= 1
            with torch.cuda.device(dev):
                _dsa_pool_expand_kernel[(rows, triton.cdiv(k_pad, 256))](
                    pool_idx, out_rows[r0 : r1], pos0 + r0,
                    P = cr, SEL = self.block_topk, K_pad = k_pad, KP_pool = kp, TAIL = 1,
                    SEQ = self.SEL_SLAB, MULTIROW = 0, BLOCK = 256,
                )

    def select_indices(
        self,
        q_idx: torch.Tensor,
        pooled: torch.Tensor,
        past_len: int,
        batch_stride: int,
    ) -> torch.Tensor:
        """
        Selection as index lists instead of a mask: per query row, the top block_topk complete
        visible blocks expanded to tokens plus the tail block, as FLAT row indices (batch b's
        token t at b * batch_stride + t), -1 padded. q_idx (bsz, seq, H, dk) roped;
        pooled (bsz, nb, dk). Returns (bsz * seq, K_pad) int32 for the gathered attention
        kernel (K_pad matching the BC selection width).
        """
        bsz, seq = q_idx.shape[:2]
        nb = pooled.shape[1]
        out = torch.empty((bsz * seq, self.k_pad()), dtype = torch.int32, device = q_idx.device)
        pooled = pooled.contiguous()
        for b in range(bsz):
            rows = out[b * seq : (b + 1) * seq]
            self._select_rows(q_idx[b].contiguous(), pooled[b], past_len, nb, rows)
            if b:
                # flat row offset of this sequence's tokens (the nc gather is unpaged)
                rows.copy_(torch.where(rows >= 0, rows + b * batch_stride, rows))
        return out

    def select_indices_ref(
        self,
        q_idx: torch.Tensor,
        pooled: torch.Tensor,
        past_len: int,
        batch_stride: int,
        q_chunk: int = 1024,
    ) -> torch.Tensor:
        """Torch reference of select_indices (tests)."""
        bsz, seq = q_idx.shape[:2]
        cr = self.compress_ratio
        dev = q_idx.device
        nb = pooled.shape[1]
        k_pad = -(-(self.block_topk * cr + cr - 1) // 32) * 32
        out = torch.full((bsz, seq, k_pad), -1, dtype = torch.int32, device = dev)
        boffs = (torch.arange(bsz, device = dev) * batch_stride).view(bsz, 1, 1)

        for c0 in range(0, seq, q_chunk):
            c1 = min(c0 + q_chunk, seq)
            qpos = past_len + torch.arange(c0, c1, device = dev)                 # (C,)
            nbq = (qpos + 1) // cr
            scores = self.block_scores(q_idx[:, c0 : c1], pooled)                # (bsz, C, nb)
            scores = scores.masked_fill(
                torch.arange(nb, device = dev).view(1, 1, -1) >= nbq.view(1, -1, 1), -torch.inf)
            ksel = min(self.block_topk, nb)
            top = scores.topk(ksel, dim = -1)
            sel_ok = top.values > -torch.inf                                     # (bsz, C, ksel)
            sel_tok = (top.indices * cr).unsqueeze(-1) + torch.arange(cr, device = dev)
            sel_tok = sel_tok.flatten(2)                                         # (bsz, C, ksel*cr)
            sel_ok = sel_ok.unsqueeze(-1).expand(-1, -1, -1, cr).flatten(2)
            tail_tok = (nbq * cr).view(1, -1, 1) + torch.arange(cr, device = dev)
            tail_tok = tail_tok.expand(bsz, -1, -1)
            tok = torch.cat((sel_tok, tail_tok), dim = 2)                        # (bsz, C, L)
            ok = torch.cat((sel_ok, torch.ones_like(tail_tok, dtype = torch.bool)), dim = 2)
            ok &= tok <= qpos.view(1, -1, 1)
            out[:, c0 : c1, : tok.shape[2]] = \
                torch.where(ok, tok + boffs, tok.new_full((), -1)).int()
        return out.view(bsz * seq, k_pad)

    def sparse_attend_nc(self, attn, q, k, v, q_idx, pooled):
        """
        Non-cached sparse attention: gathered-GQA kernel over the per-row selection instead of
        a materialized (bsz, seq, seq) mask (whose SDPA fallback also expands K/V per q head).
        q (bsz, seq, qh, hd) roped, k/v (bsz, seq, kvh, hd); returns (bsz, seq, qh, hd) fp16.
        """
        from .attention_fn.qsa_triton import qsa_sparse_attend_rows
        bsz, seq = q.shape[:2]
        indices = self.select_indices(q_idx, pooled, past_len = 0, batch_stride = seq)
        o = qsa_sparse_attend_rows(
            q.reshape(bsz * seq, attn.num_q_heads, attn.head_dim).contiguous(),
            k.reshape(bsz * seq, attn.num_kv_heads, attn.head_dim).contiguous(),
            v.reshape(bsz * seq, attn.num_kv_heads, attn.head_dim).contiguous(),
            indices, attn.sm_scale,
        )
        return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)

    def build_mask(
        self,
        x: torch.Tensor,
        raw_k_past: torch.Tensor | None,
        rope,
        params: dict,
    ):
        """
        Eager reference form of the selection (mask over all positions), kept for the parity
        tests: project current tokens, append to the raw key history, pool, select. Returns
        (mask (bsz, seq, total_len) bool, raw_k_full for the caller's cache).
        """
        past_len = 0 if raw_k_past is None else raw_k_past.shape[1]
        q, raw_k = self.project(x, rope, params, position = past_len)
        raw_k_full = raw_k if raw_k_past is None else torch.cat([raw_k_past, raw_k], dim = 1)
        pooled = self.pool_keys(raw_k_full, rope, params)
        mask = self.token_mask(q, pooled, past_len, raw_k_full.shape[1])
        return mask, raw_k_full

    # ---- cached (paged) path -------------------------------------------------------------------
    #
    # The side planes (raw per-token keys, pooled per-block keys) live in the attention layer's
    # CacheLayer_qsa and are maintained on EVERY cached forward; the sparse attention itself only
    # engages once some query position exceeds sparse_threshold()

    def sparse_threshold(self) -> int:
        # Highest query position for which dense attention is still exact + 1
        return 4 * self.block_topk + 3

    def _norm_w_half(self, which: str, device):
        """fp16 copy of a layernorm weight for the plane kernels (they add the +1 bias)."""
        attr = f"_{which}_norm_w_h"
        w = getattr(self, attr, None)
        if w is None or w.device != device:
            src = self.q_layernorm if which == "q" else self.k_layernorm
            w = src.weight.data.to(device = device, dtype = torch.half).contiguous()
            setattr(self, attr, w)
        return w

    def update_planes(
        self,
        layer,
        x: torch.Tensor,
        rope,
        block_table: torch.Tensor,
        cache_seqlens_cpu: torch.Tensor,
        params: dict,
    ) -> torch.Tensor:
        """
        Project the current tokens, write raw keys into the paged plane, (re)pool the blocks the
        chunk touches. Returns the roped indexer queries (bsz, seq, n_heads, head_dim) for
        selection (a reused static, valid until the next call). The BC graph's plane kernels,
        JIT-launched: fused qk GEMM -> split + q RMS norm -> in-place partial rope with the
        device cache lengths as positions -> raw append -> pool update. No rope-table gathers,
        no per-layer H2D copy of the positions, no index arithmetic in torch. The pool kernel
        also writes the chunk's trailing incomplete pool (never selected; rebuilt once complete).
        """
        from .attention_fn.qsa_triton import _qsa_stage_kernel, _qsa_pool_update_kernel
        from .attention_fn.mla_triton import _mla_plane_update_kernel
        from ..util.tensor import g_tensor_cache, get_for_device
        bsz, seqlen, _ = x.shape
        dev = x.device
        cr, H, dk = self.compress_ratio, self.n_heads, self.head_dim
        R = bsz * seqlen
        seqlens = get_for_device(params, "cache_seqlens", dev, None)
        if seqlens is None or seqlens.dtype != torch.int32:
            seqlens = cache_seqlens_cpu.to(device = dev, dtype = torch.int32)
        bt = block_table if block_table.dtype == torch.int32 else block_table.int()
        bt = bt.contiguous()
        npr = bt.shape[1]
        page_size = layer.raw_k.shape[1]

        # the HC mix hands the attention site a row-padded view (hc_pad_ok); q/k/v read it as is, so the indexer
        # projection does too instead of compacting the whole block input (same bytes into the GEMM, bit-exact).
        # EXL3_QSA_IDX_PAD=0 (read per call) goes back to the copy
        from .quant.exl3 import _pad_view_ok, _pad_eligible
        if not x.is_contiguous() and os.environ.get("EXL3_QSA_IDX_PAD", "1") != "0" and _pad_view_ok(x) \
                and _pad_eligible(self.index_qk_proj, x.shape[-1], R, params):
            xc = x
        else:
            xc = x.contiguous()
        qk = self.index_qk_proj.forward(xc, params).view(R, (H + 1) * dk)
        if bsz == 1 and 1 < seqlen <= 8 and params.get("dflash_verify") and (VERIFY_QSA_PROJ["on"] or QSA_SHADOW["on"]):
            qk = qk.clone()
            p1 = dict(params, dflash_verify = False)
            rows1 = torch.cat([self.index_qk_proj.forward(xc[:, i:i + 1], p1).reshape(1, (H + 1) * dk).clone()
                               for i in range(seqlen)], dim = 0)
            if QSA_SHADOW["on"]:
                shadow_note("proj", qk, rows1)
            if VERIFY_QSA_PROJ["on"]:
                qk = rows1
        q = self._workspace(R, R * H * dk, torch.half, "qsa_up_q", dev) \
            .view(bsz, seqlen, H, dk)
        kraw = self._workspace(R, R * dk, torch.half, "qsa_up_k", dev) \
            .view(bsz, seqlen, dk)
        with torch.cuda.device(dev):
            _qsa_stage_kernel[(R, H + 1)](
                qk, self._norm_w_half("q", dev), q, kraw, R,
                eps = float(self.q_layernorm.rms_norm_eps), H_i = H, D = dk,
            )
            rope.apply(q, None, 0, seqlens, None, True)
            _mla_plane_update_kernel[(R,)](
                kraw, layer.raw_k, bt, seqlens, npr, seqlen,
                page_size = page_size, D = dk, DST_D = 0, DST_OFF = 0,
            )
            # MAXPOOLS is documentation of the grid height only (unused in the body); a fixed
            # value keeps one compile across chunk lengths
            _qsa_pool_update_kernel[(bsz, seqlen // cr + 1)](
                layer.raw_k.view(-1, dk), layer.pooled.view(-1, dk), self._norm_w_half("k", dev),
                rope.inv_freq, bt, seqlens, npr, seqlen,
                page_size = page_size, P = cr, D = dk, ROPE_R = 2 * rope.inv_freq.numel(),
                attn_factor = float(rope.attn_factor),
                eps = float(self.k_layernorm.rms_norm_eps), MAXPOOLS = 1,
            )
        return q

    def update_planes_ref(
        self,
        layer,
        x: torch.Tensor,
        rope,
        block_table: torch.Tensor,
        cache_seqlens_cpu: torch.Tensor,
        params: dict,
    ) -> torch.Tensor:
        """Torch reference of update_planes (tests): writes only the completed pools."""
        bsz, seqlen, _ = x.shape
        dev = x.device
        cr = self.compress_ratio
        dk = self.head_dim
        max_pos = int(cache_seqlens_cpu.max().item()) + seqlen
        rope.expand_cache(max_pos)
        cos_all = rope.cached_cos
        sin_all = rope.cached_sin

        pos0 = cache_seqlens_cpu.long().to(dev)                                    # (bsz,)
        pos_ids = pos0.unsqueeze(1) + torch.arange(seqlen, device = dev)           # (bsz, seq)
        q, raw_k = self.project_ref(x, cos_all[pos_ids].half(), sin_all[pos_ids].half(), params)

        page_sz = layer.raw_k.shape[1]
        blocks_per_page = layer.pooled.shape[1]
        bt = block_table.long()
        raw_flat = layer.raw_k.view(-1, dk)
        pooled_flat = layer.pooled.view(-1, dk)

        # raw key write (row pages are disjoint, scatter is race-free)
        flat = bt.gather(1, pos_ids // page_sz) * page_sz + pos_ids % page_sz
        raw_flat[flat.flatten()] = raw_k.reshape(-1, dk).half()

        # pool blocks completed by this chunk: rows have different (b0, b1) ranges; pad to the max
        b0 = pos0 // cr
        b1 = (pos0 + seqlen) // cr
        nb_max = int((b1 - b0).max().item())
        if nb_max > 0:
            blocks = b0.unsqueeze(1) + torch.arange(nb_max, device = dev)          # (bsz, nbm)
            valid = blocks < b1.unsqueeze(1)
            blocks_c = torch.where(valid, blocks, b0.unsqueeze(1))                 # safe indices
            tok = (blocks_c * cr).unsqueeze(-1) + torch.arange(cr, device = dev)   # (bsz, nbm, cr)
            tflat = bt.unsqueeze(1).expand(-1, nb_max, -1) \
                .gather(2, tok // page_sz) * page_sz + tok % page_sz
            pooled = raw_flat[tflat].float().mean(dim = 2).to(torch.half)          # (bsz, nbm, dk)
            pooled = self.k_layernorm.forward(pooled, params)
            starts = blocks_c * cr
            pooled = _rope(pooled, cos_all[starts].half(), sin_all[starts].half())
            pflat = bt.gather(1, starts // page_sz) * blocks_per_page + blocks_c % blocks_per_page
            vm = valid.flatten()
            pooled_flat[pflat.flatten()[vm]] = pooled.reshape(-1, dk)[vm]
        return q

    def select_indices_paged(
        self,
        layer,
        q_idx: torch.Tensor,
        block_table: torch.Tensor,
        cache_seqlens_cpu: torch.Tensor,
    ) -> torch.Tensor:
        """
        Cache-resident form of select_indices: pooled block keys are read from the paged plane
        through the block table and each row's positions are offset by its sequence's cache
        position. Emits per-SEQUENCE cache positions, (bsz * seq, K_pad) int32 -1-padded. The
        paged attention kernel maps them through the block table.
        """
        bsz, seq = q_idx.shape[:2]
        cr = self.compress_ratio
        epp = layer.pooled.shape[1]
        pool_flat = layer.pooled.view(-1, self.head_dim)
        bt = block_table.int()
        out = torch.empty((bsz * seq, self.k_pad()), dtype = torch.int32, device = q_idx.device)
        for b in range(bsz):
            pos0 = int(cache_seqlens_cpu[b])
            self._select_rows(
                q_idx[b].contiguous(), pool_flat, pos0, (pos0 + seq) // cr,
                out[b * seq : (b + 1) * seq], block_table = bt[b], epp = epp,
            )
        return out

    def select_indices_paged_ref(
        self,
        layer,
        q_idx: torch.Tensor,
        block_table: torch.Tensor,
        cache_seqlens_cpu: torch.Tensor,
        q_chunk: int = 1024,
    ) -> torch.Tensor:
        """Torch reference of select_indices_paged (tests)."""
        bsz, seq = q_idx.shape[:2]
        cr = self.compress_ratio
        dk = self.head_dim
        dev = q_idx.device
        page_sz = layer.raw_k.shape[1]
        bpp = layer.pooled.shape[1]
        pooled_flat = layer.pooled.view(-1, dk)
        bt = block_table.long()
        pos0 = cache_seqlens_cpu.long().to(dev)
        nbf = (pos0 + seq) // cr                                                 # (bsz,)
        nbm = int(nbf.max().item())
        k_pad = -(-(self.block_topk * cr + cr - 1) // 32) * 32
        out = torch.full((bsz, seq, k_pad), -1, dtype = torch.int32, device = dev)

        blocks = torch.arange(nbm, device = dev).unsqueeze(0).expand(bsz, -1)    # (bsz, nbm)
        blk_c = torch.where(blocks < nbf.unsqueeze(1), blocks, torch.zeros_like(blocks))
        pflat = bt.gather(1, (blk_c * cr) // page_sz) * bpp + blk_c % bpp
        pk = pooled_flat[pflat]                                                  # (bsz, nbm, dk)

        for c0 in range(0, seq, q_chunk):
            c1 = min(c0 + q_chunk, seq)
            qpos = pos0.unsqueeze(1) + torch.arange(c0, c1, device = dev)        # (bsz, C)
            nbq = (qpos + 1) // cr
            scores = self.block_scores(q_idx[:, c0 : c1], pk)                    # (bsz, C, nbm)
            scores = scores.masked_fill(blocks.unsqueeze(1) >= nbq.unsqueeze(-1), -torch.inf)
            ksel = min(self.block_topk, nbm)
            top = scores.topk(ksel, dim = -1)
            sel_ok = top.values > -torch.inf                                     # (bsz, C, ksel)
            sel_tok = (top.indices * cr).unsqueeze(-1) + torch.arange(cr, device = dev)
            sel_tok = sel_tok.flatten(2)                                         # (bsz, C, ksel*cr)
            sel_ok = sel_ok.unsqueeze(-1).expand(-1, -1, -1, cr).flatten(2)
            tail_tok = (nbq * cr).unsqueeze(-1) + torch.arange(cr, device = dev)
            tok = torch.cat((sel_tok, tail_tok), dim = 2)                        # (bsz, C, L)
            ok = torch.cat((sel_ok, torch.ones_like(tail_tok, dtype = torch.bool)), dim = 2)
            ok &= tok <= qpos.unsqueeze(-1)
            out[:, c0 : c1, : tok.shape[2]] = \
                torch.where(ok, tok, tok.new_full((), -1)).int()
        return out.view(bsz * seq, k_pad)

    def sparse_attend(
        self,
        layer,
        attn,
        q: torch.Tensor,
        q_idx: torch.Tensor,
        block_table: torch.Tensor,
        cache_seqlens_cpu: torch.Tensor,
        indices: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """
        Sparse paged attention through the gathered-GQA kernel: per-row selection over the
        pooled plane, then one split + combine launch over the cache pages -- nothing S x L is
        ever materialized (the einsum/flash predecessors gathered K/V per query chunk, which
        OOMed on long prefills). Serves cached prefill chunks and every eager sparse fallback
        (bsz > 1, MTP verify). K/V for the current tokens must already be written to the cache.
        q: (bsz, seq, num_q_heads, head_dim) roped; q_idx: roped indexer queries from
        update_planes. indices: precomputed selection (bsz * seq, K_pad), else computed here.
        Returns (bsz, seq, num_q_heads, head_dim) fp16.
        """
        from .attention_fn.qsa_triton import qsa_sparse_attend_rows
        from ..cache.quant import CacheLayer_quant
        bsz, seq = q.shape[:2]
        if indices is None:
            indices = self.select_indices_paged(layer, q_idx, block_table, cache_seqlens_cpu)
        if isinstance(layer, CacheLayer_quant):
            # Packed pages, dequantized online by the gather kernel
            qk, sk, qv, sv, kb, vb = layer.get_qkv()
            k_arg, v_arg, qc, page_size = qk, qv, (sk, sv, kb, vb), qk.shape[1]
        else:
            k_arg = layer.k.view(-1, attn.num_kv_heads, attn.head_dim)
            v_arg = layer.v.view(-1, attn.num_kv_heads, attn.head_dim)
            qc, page_size = None, layer.k.shape[1]
        q_rows = q.reshape(bsz * seq, attn.num_q_heads, attn.head_dim).contiguous()
        tq = layer.get_tq() if getattr(layer, "tq", False) else None
        if tq is not None:
            # TurboQuant: the pool is in the rotated domain, so q goes in rotated and the output comes back through R^T
            q_rows = tq.rotate(q_rows)
        if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and qc is None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
                and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
                and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready(q.device)):
            # one wave per (row, kv head) HIP kernel, bit-identical to the Triton pair (fp16 cache, prefill chunks only); on gfx1151 the
            # 4-row union WMMA kernel by default (fp16 rounding-level difference, live switch EXL3_HIP_ATTN_WMMA)
            from .attention_fn.qsa_prefill_hip import qsa_prefill_hip, qsa_prefill_wmma, wmma_enabled
            if wmma_enabled(q.device):
                o = qsa_prefill_wmma(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)
            else:
                o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)
            return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
        if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
                and tq is None and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4
                and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
                and q_rows.dtype == torch.half and _pf_hip_ready(q.device)):
            # stage the used pages as rotated-domain fp16 (one elementwise pass), run the proven fp16 HIP kernel on q rotated by H32/sqrt(32), rotate the output back
            from .attention_fn.qdeq_triton import qsa_prefill_q8
            n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
            o = qsa_prefill_q8(q_rows, qk, sk, qv, sv, indices, attn.sm_scale, block_table[0], n_used, page_size)
            return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)
        if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
                and tq is not None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
                and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
                and q_rows.dtype == torch.half and _pf_hip_ready(q.device)):
            # TurboQuant prefill chunk: stage the used pages as rotated-domain fp16 (codebook lookup, one pass), run the fp16 HIP kernel
            # on the rotated q, rotate the output back (the Triton split kernel below is ~70x slower per chunk on this shape)
            from .attention_fn.qsa_prefill_hip import qsa_prefill_hip
            from .attention_fn.tq_triton import tq_dequant_window
            n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
            kd = torch.empty((n_used, page_size, attn.num_kv_heads, attn.head_dim), dtype = torch.half, device = q.device)
            vd = torch.empty_like(kd)
            bt = block_table[:, :n_used].int().contiguous()
            sl = cache_seqlens_cpu[:1].to(device = q.device, dtype = torch.int32)
            tq_dequant_window(qk, sk, tq.cbk, kd, sl, bt, page_size, seq, qc[2], attn.num_kv_heads, attn.head_dim)
            tq_dequant_window(qv, sv, tq.cbv, vd, sl, bt, page_size, seq, qc[3], attn.num_kv_heads, attn.head_dim)
            ids = torch.arange(n_used, dtype = torch.int32, device = q.device)
            o = qsa_prefill_hip(q_rows, kd.view(-1, attn.num_kv_heads, attn.head_dim), vd.view(-1, attn.num_kv_heads, attn.head_dim),
                                indices, attn.sm_scale, ids, page_size)
            return tq.unrotate(o).view(bsz, seq, attn.num_q_heads, attn.head_dim)
        # Built only for the Triton fallback: the HIP paths above read block_table[0], and this copy is
        # rows x pages x 4 B (33 MB per layer per 4096-row chunk at -c 524288) written for nothing
        bt_rows = block_table.int().unsqueeze(1).expand(bsz, seq, -1) \
            .reshape(bsz * seq, -1).contiguous()
        o = qsa_sparse_attend_rows(
            q_rows,
            k_arg, v_arg, indices, attn.sm_scale,
            block_table = bt_rows, page_size = page_size,
            qc = qc, n_kv_heads = attn.num_kv_heads, tq = tq,
        )
        if tq is not None:
            o = tq.unrotate(o)
        return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)

    def sparse_attend_verify(self, layer, attn, q, q_idx, block_table, cache_seqlens_cpu) -> torch.Tensor:
        """sparse_attend for a verify forward: optionally row-invariant (the R = 1 call per row, as plain decode)."""
        bsz, seq = q.shape[:2]
        mode = VERIFY_QSA_ATTN["mode"]
        if not (bsz == 1 and 1 < seq <= 8) or not (mode or QSA_SHADOW["on"]):
            return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu)
        def row_idx(i):
            return self.select_indices_paged(layer, q_idx[:, i:i + 1], block_table, cache_seqlens_cpu + i).clone()
        def attend_rows(idx):
            return torch.cat([self.sparse_attend(layer, attn, q[:, i:i + 1], q_idx[:, i:i + 1], block_table,
                                                 cache_seqlens_cpu + i, indices = idx[i:i + 1]).clone()
                              for i in range(seq)], dim = 1)
        idx_rows = torch.cat([row_idx(i) for i in range(seq)], dim = 0)
        idx_all = self.select_indices_paged(layer, q_idx, block_table, cache_seqlens_cpu)
        if QSA_SHADOW["on"]:
            o_all = self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_all)
            shadow_note("sel", idx_all, idx_rows)
            shadow_note("att_rowwise_vs_batched_same_idx", o_all, attend_rows(idx_all))
            shadow_note("att_rowwise_vs_batched_row_idx", self.sparse_attend(
                layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_rows), attend_rows(idx_rows))
        if mode == "all":
            return attend_rows(idx_rows)
        if mode == "sel":     # per-row selection, one attention launch
            return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_rows)
        if mode == "att":     # one selection, per-row attention
            return attend_rows(idx_all)
        return self.sparse_attend(layer, attn, q, q_idx, block_table, cache_seqlens_cpu, indices = idx_all)