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.

87.0 KB
Raw Blame
from __future__ import annotations
from typing_extensions import override
import torch
from ..model.config import Config
from ..util.rope import RopeSettings, RoPE
from ..util.tensor import get_for_device, to2
from . import Module, Linear, RMSNorm, LayerNorm
from ..constants import PAGE_SIZE
from .multilinear import MultiLinear, SlicedMultiLinear
from .quant.exl3 import MAX_BSZN_GEMV_R, row_pad_pitch
from ..ext import exllamav3_ext as ext
from ..model.model_tp_alloc import TPAllocation
from ..util import profile_opt, knobs
from ..util.row_inv import gguf_ri
import os
from .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_attn, MAX_BSZ as _bc_max_bsz, MAX_QLEN as _bc_max_qlen

# Sliced Q/K/V(/G) projection bundle at decode (one mgemm over equal-width column slices);
# EXL3_QKV_SLICE=0 falls back to the pairwise K/V and Q/G bundles
_qkv_slice_enable = os.environ.get("EXL3_QKV_SLICE", "1") != "0"
_shared_proj = os.environ.get("EXL3_ATTN_SHARED_PROJ", "1") != "0"
_shared_check = os.environ.get("EXL3_ATTN_SHARED_CHECK", "0") != "0"
# EXL3_ATTN_BATCH_QSA (default on): in the row-invariant multi-job step, when every sequence takes the sparse (QSA) path the plane update, the KV append and
# the gathered attention launch once over all sequences (their kernels give each row the bits of the one-sequence launch); the selection stays per sequence
_batch_qsa = os.environ.get("EXL3_ATTN_BATCH_QSA", "1") != "0"
_SHARED_STATS = [0, 0]
_QKV_IG_MULTI = os.environ.get("EXL3_ATTN_QKV_IG_MULTI", "1") != "0"   # (q|gate, k, v one launch)
_QKVCAT = os.environ.get("EXL3_ATTN_QKVCAT", "1" if torch.version.hip else "0") != "0"   # GGUF Q8_0 q / k / v decode in one launch (_qkv_q8cat)


def _sim_kvq_inplace(t: torch.Tensor, bits: int | None, compand_a: float):
    """
    Round one K or V tensor through cache quantization in place (quantize to a temporary buffer,
    dequantize back), so an fp16 cache downstream holds exactly what a quantized cache would
    reproduce.
    """
    if bits is None or bits >= 16:
        return
    assert t.dtype == torch.half and t.size(-1) % 32 == 0
    tc = t.contiguous()
    blocks = t.size(-1) // 32
    q = torch.empty(t.shape[:-1] + (blocks * bits,), dtype = torch.int, device = t.device)
    scales = torch.empty(t.shape[:-1] + (blocks,), dtype = torch.half, device = t.device)
    ext.quant_cache_cont(tc, q, scales, compand_a)
    ext.dequant_cache_cont(q, scales, tc, compand_a)
    if tc is not t:
        t.copy_(tc)

from ..util.tensor import g_tensor_cache
from .attention_fn import attn_dispatch
from ..cache.kvwin import env_capable as _kvwin_capable, make_ctx as _kvwin_ctx, ensure_filled as _kvwin_fill, KVWinLayerState

"""
                   
Flash Attention:
                
    attn_mode: "flash_attn"
    batch_shape: tuple of (bsz, max_seq_len)
    cache: Cache with capacity of at least bsz*max_seq_len tokens
    past_len: int, *OR*
    cache_seqlens: shape (bsz) 
    position: int (overrides past_len for position emb)
    positions: shape (bsz) (overrides cache_seqlens for position emb) *OR*
    position_ids: shape (bsz, seq_len) (overrides cache_seqlens for position emb)
    - max_seq_len must be divisible by 256
    
    attn_mode: "flash_attn"
    block_table: list of page indices, shape (bsz, pages_per_seq)
    cache: Paged cache
    cache_seqlens: shape (bsz)
    positions: shape (bsz) (overrides cache_seqlens for position emb) *OR*
    position_ids: shape (bsz, seq_len) (overrides cache_seqlens for position emb)

    attn_mode: "flash_attn_nc"
    position (optional, default = 0): int *OR*
    positions: shape (bsz) *OR*
    position_ids: shape (bsz, seq_len)    
    - no cache
    - no chunking
    - batch shape is determined by shape of input_ids
"""

def prepare_flash_attn_nc(input_ids: torch.Tensor, params: dict) -> torch.Tensor:
    assert "cache" not in params, \
        f"Cache provided for attn_mode: flash_attn_nc"
    return input_ids


# Rectangular (batch_shape mode) block tables are static per shape; cache them with persistent
# device copies so they aren't rebuilt and re-uploaded every forward pass
_block_tables = {}

def _get_block_table(cache_bsz: int, pages_per_seq: int) -> torch.Tensor:
    key = (cache_bsz, pages_per_seq)
    bt = _block_tables.get(key)
    if bt is None:
        bt = torch.arange(cache_bsz * pages_per_seq, dtype = torch.int32).view(cache_bsz, pages_per_seq)
        bt._static_dev_cache = True
        _block_tables[key] = bt
    return bt


def prepare_flash_attn(input_ids: torch.Tensor, params: dict) -> torch.Tensor:
    bsz, seq_len = input_ids.shape

    if "batch_shape" in params:
        cache = params["cache"]
        cache_bsz, cache_max_seq_len = params["batch_shape"]
        past_len = params.get("past_len")
        cache_seqlens = params.get("cache_seqlens") if past_len is None else None
        position = params.get("position") if past_len is None else None
        positions = params.get("positions") if past_len is None else None
        position_ids = params.get("position_ids") if past_len is None else None
        assert cache_bsz >= bsz, "batch size too large for cache"
        assert cache_max_seq_len % PAGE_SIZE == 0, f"cache seq len must be a multiple of {PAGE_SIZE}"
        # assert (past_len is not None) ^ (cache_seqlens is not None), "Need either past_len or cache_seqlens"
        assert bsz * cache_max_seq_len <= cache.max_num_tokens, "Cache too small for batch shape"
        cache_bsz = min(bsz, cache_bsz)
        block_table = _get_block_table(cache_bsz, cache_max_seq_len // PAGE_SIZE)
        if past_len is not None:
            cache_seqlens = torch.tensor([past_len], dtype = torch.int32).repeat(bsz)
            if position is None: position = past_len
        else:
            if positions is None and position_ids is None: positions = cache_seqlens
        if position is None: position = 0
        params["block_table"] = block_table
        params["cache_seqlens"] = cache_seqlens
        params["position"] = position
        params["positions"] = positions
        params["position_ids"] = position_ids

    elif "block_table" in params:
        positions = params.get("positions")
        position_ids = params.get("position_ids")
        cache_seqlens = params.get("cache_seqlens")
        if positions is None and position_ids is None: positions = cache_seqlens
        params["cache_seqlens"] = cache_seqlens
        params["positions"] = positions
        params["position_ids"] = position_ids

    return input_ids


def split_params_by_sequence(params: dict, bsz: int) -> list[dict]:
    """One params dict per sequence of a paged batch: the block table row, the cache length and the positions of that
    sequence (views, made once per forward and shared by all attention layers). Run after prepare_inputs, which makes
    the positions an alias of the cache lengths."""
    assert params.get("position_ids") is None, "per-sequence attention does not take position_ids"
    positions = params.get("positions")
    out = []
    for b in range(bsz):
        p = dict(params)
        p.pop("dev_cache", None)
        p["block_table"] = params["block_table"][b:b + 1]
        p["cache_seqlens"] = params["cache_seqlens"][b:b + 1]
        # the sequence's own recurrent state (and slot): the KVWIN ring of the attention layer lives in it
        rs = params.get("recurrent_states")
        if rs and len(rs) == bsz:
            p["recurrent_states"] = rs[b:b + 1]
            if torch.is_tensor(params.get("recurrent_slots")):
                p["recurrent_slots"] = params["recurrent_slots"][b:b + 1]
        if positions is not None:
            p["positions"] = p["cache_seqlens"] if positions is params["cache_seqlens"] else positions[b:b + 1]
        out.append(p)
    return out


def prepare_for_attn(input_ids: torch.Tensor, params: dict) -> torch.Tensor:
    """
    Add attn parameters to state
    """
    attn_mode = params.get("attn_mode", "flash_attn_nc")
    match attn_mode:
        case "flash_attn":
            return prepare_flash_attn(input_ids, params)
        case "flash_attn_nc":
            return prepare_flash_attn_nc(input_ids, params)
        case _:
            raise ValueError(f"Unknown attn_mode: {attn_mode}")


def dec_project_o_strided(o_proj, o: torch.Tensor, bsz: int, seqlen: int, num_heads: int, head_dim: int,
                          v_head_dim: int, params: dict):
    """Batch-1 decode o_proj over the first v_head_dim (= 128) lanes of each head_dim-wide head,
    read in place by exl3_dec (no slice copy). None when the fast path does not apply."""
    if (
        bsz * seqlen != 1 or v_head_dim != 128 or head_dim % 8 != 0 or not o.is_contiguous() or
        o.dtype != torch.half or o.numel() != num_heads * head_dim or
        not hasattr(ext, "exl3_dec_gemv_strided") or os.environ.get("EXL3_DEC_OSTRIDE", "1") == "0" or
        "ovr" in params or "capture" in params or o_proj.quant_type != "exl3"
    ):
        return None
    inner = o_proj.inner
    if (
        not getattr(inner, "dec_ok", False) or o_proj.lora_a_tensors or o_proj.pre_scale != 1.0 or
        o_proj.post_scale != 1.0 or o_proj.softcap != 0.0 or inner.bias is not None or
        o_proj.in_features != num_heads * v_head_dim or o_proj.out_features != o_proj.out_features_unpadded
    ):
        return None
    from .quant.exl3 import dec_workspace
    scratch, counters = dec_workspace(o.device)
    y = torch.empty((bsz, seqlen, o_proj.out_features), dtype = inner.default_out_dtype, device = o.device)
    ext.exl3_dec_gemv_strided(o.view(1, -1), inner.trellis, inner.suh, inner.svh, y.view(1, -1),
                              scratch, counters, float(inner.K), num_heads * v_head_dim, head_dim)
    return y


_kv_only_skip = os.environ.get("EXL3_PF_KV_ONLY_ATTN", "1") == "1"

class Attention(Module):

    def __init__(
        self,
        config: Config | None,
        key: str,
        layer_idx: int,
        hidden_size: int,
        head_dim: int,
        num_q_heads: int,
        num_kv_heads: int,
        rope_settings: RopeSettings | None,
        v_head_dim: int | None = None,
        sm_scale: float | None = None,
        key_q: str | None = None,
        key_k: str | None = None,
        key_v: str | None = None,
        key_o: str | None = None,
        key_g: str | None = None,
        key_fused_qkv: str | None = None,
        key_sinks: str | None = None,
        qmap: str | None = None,
        out_dtype: torch.dtype | None = None,
        sliding_window: int = -1,
        window_right: int = 0,
        logit_softcapping: float = 0.0,
        q_norm: RMSNorm | LayerNorm | None = None,
        k_norm: RMSNorm | LayerNorm | None = None,
        v_norm: RMSNorm | LayerNorm | None = None,
        q_proj: Linear | Module | None = None,
        k_proj: Linear | Module | None = None,
        v_proj: Linear | Module | None = None,
        kv_proj: Linear | Module | None = None,
        o_proj: Linear | Module | None = None,
        g_proj: Linear | Module | None = None,
        interleaved_gate: bool = False,
        use_k_as_v: bool = False,
        transpose_qkv: bool = True,
        use_cu_seqlens: bool = False,
        full_gate: bool = False,
        gate_softplus: bool = False,
        tp_split_norm: bool = True,
        select_hq_bits: int = 0,
        qbits_key: str = "bits",
        qsa_indexer: Module | None = None,
    ):
        super().__init__(config, key, None)

        self.q_priority = 2 + select_hq_bits
        self.layer_idx = layer_idx
        self.hidden_size = hidden_size
        self.head_dim = head_dim
        # Asymmetric V head dim (MiMo-V2: QK 192, V 128). The cache, the attention kernels and
        # AttnArgs all carry a single head dim, so V rides along at head_dim with the top
        # head_dim - v_head_dim lanes zero-filled by the loader, and the attention output is
        # trimmed back to v_head_dim before o_proj (which is sized on v_head_dim, so no
        # quantization waste there -- only the V half of the cache is oversized)
        self.v_head_dim = v_head_dim if v_head_dim is not None else head_dim
        assert self.v_head_dim <= head_dim, "Attn: v_head_dim > head_dim is not supported"
        self.num_q_heads = num_q_heads
        self.num_kv_heads = num_kv_heads
        self.gqa = (num_q_heads != num_kv_heads)
        self.sm_scale = sm_scale or self.head_dim ** (-0.5)
        self.rope_settings = rope_settings
        self.rope = None
        self.qsa_indexer = qsa_indexer
        self.register_submodule(qsa_indexer)
        self.out_dtype = out_dtype
        self.sliding_window = sliding_window
        # Right half of the attention window, in keys *after* the query position. 0 is the
        # normal (causal-shaped) sliding window. A positive value lets a block of queries
        # submitted in one forward pass attend to each other bidirectionally while still
        # being bounded on the left -- what a DFlash drafter with `is_causal: false` and a
        # sliding window needs, since `causal = False` alone is cancelled by the implied
        # right bound of 0. See attention_fn/common.py::AttnArgs.get_window_size.
        self.window_right = window_right
        self.logit_softcapping = logit_softcapping
        self.interleaved_gate = interleaved_gate
        self.use_cu_seqlens = use_cu_seqlens
        self.tp_split_norm = tp_split_norm
        self.use_k_as_v = use_k_as_v
        self.full_gate = full_gate
        self.gate_softplus = gate_softplus
        assert not gate_softplus or not (full_gate or interleaved_gate), \
            "Attn: gate_softplus is only implemented for the headwise gate"
        self.key_sinks = key_sinks
        self.sinks = None

        if self.num_kv_heads == 0:
            return

        # Create q, k, v projections
        if key_fused_qkv:
            assert not interleaved_gate, "Attn: interleaved_gate not implemented for fused QKV tensor"
            fkey = f"{key}.{key_fused_qkv}"
            frange_q = (0, num_q_heads * head_dim)
            frange_k = (frange_q[1], frange_q[1] + num_kv_heads * head_dim)
            frange_v = (frange_k[1], frange_k[1] + num_kv_heads * head_dim)
        else:
            fkey, frange_q, frange_k, frange_v = None, None, None, None

        if key_q or frange_q:
            f = 2 if interleaved_gate else 1
            self.q_proj = Linear(
                config,
                f"{key}.{key_q}" if key_q else f"{key}.q_proj",
                hidden_size,
                num_q_heads * head_dim * f,
                qmap = qmap + ".input" if qmap is not None else None,
                fkey = fkey,
                frange = frange_q,
                select_hq_bits = select_hq_bits,
                qgroup = key + ".qkv",
                ftranspose_after_load = transpose_qkv,
                trim_padded_out = True,
                qbits_key = qbits_key,
            )
            self.register_submodule(self.q_proj)
        else:
            assert q_proj
            self.q_proj = q_proj
            self.register_submodule(self.q_proj)

        if key_k or frange_k:
            assert key_v or frange_v or use_k_as_v
            self.k_proj = Linear(
                config,
                f"{key}.{key_k}" if key_k else f"{key}.k_proj",
                hidden_size,
                num_kv_heads * head_dim,
                qmap =  qmap + ".input" if qmap is not None else None,
                fkey = fkey,
                frange = frange_k,
                select_hq_bits = select_hq_bits,
                qgroup = key + ".qkv",
                ftranspose_after_load = transpose_qkv,
                trim_padded_out = True,
                qbits_key = qbits_key,
            )
            self.v_proj = Linear(
                config,
                f"{key}.{key_v}" if key_v else f"{key}.v_proj",
                hidden_size,
                num_kv_heads * head_dim,
                qmap =  qmap + ".input" if qmap is not None else None,
                fkey = fkey,
                frange = frange_v,
                select_hq_bits = select_hq_bits,
                qgroup = key + ".qkv",
                ftranspose_after_load = transpose_qkv,
                trim_padded_out = True,
                qbits_key = qbits_key,
            ) if not use_k_as_v else None
            self.register_submodule(self.k_proj)
            self.register_submodule(self.v_proj)
        else:
            if kv_proj:
                self.kv_proj = kv_proj
                self.register_submodule(self.kv_proj)
            else:
                self.k_proj = k_proj
                self.v_proj = v_proj
                self.register_submodule(self.k_proj)
                if self.v_proj:
                    self.register_submodule(self.v_proj)

        # Create o proj
        if key_o:
            self.o_proj = Linear(
                config,
                f"{key}.{key_o}",
                num_q_heads * self.v_head_dim,
                hidden_size,
                qmap =  qmap + ".o" if qmap is not None else None,
                out_dtype = out_dtype,
                select_hq_bits = select_hq_bits,
                qgroup = key + ".o" if qmap is not None else None,
                trim_padded_out = True,
                qbits_key = qbits_key,
            )
            self.register_submodule(self.o_proj)
        else:
            assert o_proj
            self.o_proj = o_proj
            self.register_submodule(self.o_proj)

        # Register q/k norms
        if q_norm:
            assert k_norm, "Must have both Q and K norms, or neither"
            self.q_norm = q_norm
            self.k_norm = k_norm
            self.register_submodule(self.q_norm)
            self.register_submodule(self.k_norm)
            if isinstance(q_norm, RMSNorm):
                self.norm_eps = q_norm.rms_norm_eps
                self.norm_constant_bias = q_norm.constant_bias
                assert self.norm_eps == k_norm.rms_norm_eps
            else:
                self.norm_eps = q_norm.layernorm_eps
                self.norm_constant_bias = 0.0
        else:
            self.q_norm = None
            self.k_norm = None
            self.norm_eps = 1e-6
            self.norm_constant_bias = 0.0

        # Register v norm
        if v_norm:
            self.v_norm = v_norm
            self.register_submodule(self.v_norm)
        else:
            self.v_norm = None

        # Register headwise gate
        if key_g:
            assert not interleaved_gate, \
                "Cannot apply both interleaved and headwise gate"
            gate_features = num_q_heads * head_dim if full_gate else num_q_heads
            _qmap = ".input" if full_gate else None
            self.g_proj = Linear(
                config,
                f"{key}.{key_g}",
                hidden_size,
                gate_features,
                qmap = _qmap,
                out_dtype = torch.half,
                pad_to = 1,
                select_hq_bits = select_hq_bits,
                qbits_key = qbits_key,
            )
            self.headwise_gate = not full_gate
            self.register_submodule(self.g_proj)
        else:
            if g_proj:
                self.g_proj = g_proj
                self.headwise_gate = not full_gate
                self.register_submodule(self.g_proj)
            else:
                self.g_proj = None
                self.headwise_gate = False

        self.caps.update({
            "kv_cache": True
        })

        # KVWIN (EXL3_KVWIN=sink:window): the fp16 sink + window ring of a quantized cache is a per-job recurrent layer state
        self.recurrent_layers = []
        if _kvwin_capable() and self.num_kv_heads > 0:
            self.caps["recurrent_cache"] = True
            self.layer_state_cls = KVWinLayerState

        self.cache_layers = []
        self.tp_cache_lookup = {}
        self.multi_kv = None
        self.multi_qg = None
        self.tp_reduce = False
        self.dispatch_cache = {}
        knobs.clear_on_change(self, "dispatch_cache")   # the kernel picked per call shape may depend on a knob
        self.bc_attn = {}
        knobs.clear_on_change(self, "bc_attn")         # BCAttn objects bake knob values (EXL3_QDEC_GRAPH, EXL3_BC_KVWIN...)

        self.q_norm_tensor = None
        self.k_norm_tensor = None

        self.has_split_cache = False

        # TP-aware span_heads norm support
        self.tp_span_heads_norm = False
        self.q_global_dim = 0
        self.k_global_dim = 0

        self.prealloc_qgh_1 = None
        self.prealloc_qg_1 = None
        self.prealloc_kvh_1 = None
        self.prealloc_kv_1 = None
        self.multi_qkv = None
        self.prealloc_qkvh_1 = None
        self.prealloc_qkv_out_1 = None
        self.prealloc_qkv_cptrs_1 = None
        self.prealloc_qkv_m = {}
        self.prealloc_qkv_carrier = None


    @override
    def optimizer_targets(self):
        q = self.q_proj.optimizer_targets()
        k = self.k_proj.optimizer_targets()
        v = self.v_proj.optimizer_targets() if self.v_proj is not None else []   # use_k_as_v: no V projection
        o = self.o_proj.optimizer_targets()
        return [[q, k + v, o]]


    def load_local(self, device, **kwargs):

        if self.num_kv_heads == 0:
            return

        # Cache
        for cl in self.cache_layers:
            cl.alloc(device)
        for rl in self.recurrent_layers:
            rl.alloc(device)

        if self.rope_settings:
            self.rope = RoPE(
                device,
                self.rope_settings,
            )

        if self.key_sinks:
            self.sinks = self.config.stc.get_tensor(
                f"{self.key}.{self.key_sinks}", device, no_defer = True
            ).float().contiguous()

        # Test if K and V proj can be fused
        if (
            not self.config.infer_params.no_reconstruct and
            not self.use_k_as_v and
            device != torch.device("cpu") and
            self.k_proj.quant_type == "exl3" and
            self.v_proj is not None and
            self.v_proj.quant_type == "exl3" and
            self.k_proj.out_features == self.v_proj.out_features and
            self.k_proj.inner.K == self.v_proj.inner.K and
            self.k_proj.inner.bias is None and
            self.v_proj.inner.bias is None and
            self.config.infer_params.use_mgemm(
                self.k_proj.inner.K, self.k_proj.out_features,
                self.k_proj.inner.mul1 and self.v_proj.inner.mul1,
                device,
            )
        ):
            self.multi_kv = MultiLinear(self. device, [self.k_proj, self.v_proj])
            # Staging buffers span the padded K, not hidden_size (e.g. NemotronH 3136 -> 3200)
            self.prealloc_kvh_1 = g_tensor_cache.get(device, (2, 1, self.k_proj.in_features), torch.half, "kvh_1")
            self.prealloc_kv_1 = g_tensor_cache.get(device, (2, 1, self.num_kv_heads * self.head_dim), torch.half, "kv_1")

        # Test if Q and G proj can be fused
        if (
            not self.config.infer_params.no_reconstruct and
            self.g_proj is not None and
            device != torch.device("cpu") and
            self.q_proj.quant_type == "exl3" and
            self.g_proj.quant_type == "exl3" and
            self.q_proj.out_features == self.g_proj.out_features and
            self.q_proj.inner.K == self.g_proj.inner.K and
            self.q_proj.inner.bias is None and
            self.g_proj.inner.bias is None and
            self.config.infer_params.use_mgemm(
                self.q_proj.inner.K, self.q_proj.out_features,
                self.q_proj.inner.mul1 and self.g_proj.inner.mul1,
                device,
            )
        ):
            self.multi_qg = MultiLinear(self. device, [self.q_proj, self.g_proj])
            self.prealloc_qgh_1 = g_tensor_cache.get(device, (2, 1, self.q_proj.in_features), torch.half, "qgh_1")
            self.prealloc_qg_1 = g_tensor_cache.get(device, (2, 1, self.num_q_heads * self.head_dim), torch.half, "qg_1")

        # Sliced Q/K/V(/G) bundle: all attention projections as one launch of equal-width column
        # slices (SlicedMultiLinear). Takes precedence over the pairwise bundles at decode. A gate
        # projection must ride along (full, quantized, same K) or there is no bundle
        self.multi_qkv = None
        # Gate: none, interleaved in q_proj (the bundle writes the full q+g row, deinterleaved
        # after), or a full quantized g_proj riding along; a headwise (fp16) gate excludes it
        gate_ok = self.g_proj is None or (
            self.full_gate and not self.interleaved_gate and
            self.g_proj.quant_type == "exl3" and self.g_proj.inner.bias is None
        )
        if self.interleaved_gate and not (self.head_dim % 8 == 0 and self.g_proj is None):
            gate_ok = False
        if (
            _qkv_slice_enable and
            not self.use_k_as_v and
            device != torch.device("cpu") and
            gate_ok and
            self.k_proj is not None and self.v_proj is not None and
            all(p.quant_type == "exl3" and p.inner.bias is None for p in (self.q_proj, self.k_proj, self.v_proj)) and
            all(p.inner.K == self.q_proj.inner.K for p in (self.k_proj, self.v_proj)) and
            all(p.in_features == self.q_proj.in_features for p in (self.k_proj, self.v_proj))
        ):
            linears = [self.q_proj, self.k_proj, self.v_proj] + ([self.g_proj] if self.g_proj is not None else [])
            try:
                self.multi_qkv = SlicedMultiLinear(self.device, linears)
            except (ValueError, AssertionError):
                self.multi_qkv = None
            # The unfusing policy (int8 GEMV vs batched MGEMM) judges whether a matrix is wide
            # enough to fill the GPU on its own: for the bundle that is a slice, not the widest
            # projection, since equal-width slices are what restore utilization
            if self.multi_qkv is not None and not self.config.infer_params.use_mgemm(
                self.multi_qkv.K, self.multi_qkv.width, self.multi_qkv.mul1, device,
            ):
                self.multi_qkv = None
        if self.multi_qkv is not None:
            mq = self.multi_qkv
            n_q, n_kv = self.num_q_heads * self.head_dim, self.num_kv_heads * self.head_dim
            self.prealloc_qkvh_1 = g_tensor_cache.get(device, (mq.num_src, 1, self.q_proj.in_features), torch.half, "qkvh_1")
            # Static m = 1 outputs: q (and g) as a (2, 1, n_q) pair so q can alias qg[0], k/v as the
            # (2, 1, n_kv) pair the existing K/V bundle uses. Interleaved gate: q_proj emits the
            # (1, 2 * n_q) q/g row, deinterleaved into q and g afterwards
            if self.interleaved_gate:
                qg_1 = g_tensor_cache.get(device, (1, 1, 2 * n_q), torch.half, "qgi_1")
                q_out = qg_1[0]
            else:
                qg_1 = g_tensor_cache.get(device, (2, 1, n_q), torch.half, "qg_1")
                q_out = qg_1[0]
            kv_1 = g_tensor_cache.get(device, (2, 1, n_kv), torch.half, "kv_1")
            outs = [q_out, kv_1[0], kv_1[1]] + ([qg_1[1]] if self.g_proj is not None else [])
            self.prealloc_qkv_out_1 = (qg_1, kv_1)
            self.prealloc_qkv_cptrs_1 = mq.c_ptrs(outs)
            # The mgemm C argument only carries the dtype and slice width in sliced mode: one row,
            # expanded to the call's row count
            self.prealloc_qkv_carrier = g_tensor_cache.get(device, (mq.num_slices, 1, mq.width), torch.half, "qkvc_1")

        # Head norm
        if self.q_norm and isinstance(self.q_norm, RMSNorm) and not self.q_norm.span_heads:
            if self.q_norm.unweighted:
                ones = torch.ones(self.head_dim, dtype = torch.half, device = device)
                self.q_norm_tensor = ones
                self.k_norm_tensor = ones
            else:
                self.q_norm_tensor = self.q_norm.weight.data
                self.k_norm_tensor = self.k_norm.weight.data


    @override
    def load(self, device: torch.Device, **kwargs):
        super().load(device, **kwargs)
        self.load_local(device, **kwargs)
        self._q8cat_build()

    def _q8cat_build(self):
        """GGUF Q8_0 q / k / v weights as one [nq + nk + nv, row] tensor, the ForeignLinears re-pointed to views of it (same bytes,
        no copy kept). Done at load, before any decode graph is captured. Nothing for other formats."""
        self._q8cat_w = None
        if not _QKVCAT or self.use_k_as_v:
            return
        from .foreign_linear import ForeignLinear
        lins = (self.q_proj, self.k_proj, self.v_proj)
        if not all(isinstance(l, ForeignLinear) and l.format == "q8_0" and l.packed is not None and l.packed.dtype == torch.uint8
                   for l in lins):
            return
        if len({l.in_features for l in lins}) != 1 or len({l.packed.device for l in lins}) != 1:
            return
        shapes = [l.packed.shape for l in lins]
        cat = torch.cat([l.packed.reshape(l.out_features, -1) for l in lins], dim = 0)
        a = 0
        for l, sh in zip(lins, shapes):
            l.packed = cat[a:a + l.out_features].view(sh)
            a += l.out_features
        self._q8cat_w = cat
        if not getattr(Attention, "_q8cat_said", False):
            Attention._q8cat_said = True
            print(f" -- attention q / k / v Q8_0 decode rows concatenated ({' + '.join(str(l.out_features) for l in lins)})", flush = True)

    def _qkv_q8cat(self, x: torch.Tensor, params: dict, bsz: int, q_len: int):
        """q, k, v of one decode row from ONE fq_gemv_q8_0 launch over the rows concatenated at load: the same per-row q8_1 x Q8_0
        dot as three launches (bit-exact), one quantization instead of three. None = fall back to the three projections."""
        cat = getattr(self, "_q8cat_w", None)
        if cat is None or bsz * q_len != 1 or not x.is_contiguous() or "capture" in params or "ovr" in params:
            return None
        lins = (self.q_proj, self.k_proj, self.v_proj)
        flat = x.reshape(1, -1)
        dts = {l.out_dtype or torch.half for l in lins}
        if len(dts) != 1 or not all(l.q8_fused_gemv_ok(flat) for l in lins):
            return None
        n = [l.out_features for l in lins]
        out = torch.empty((1, sum(n)), dtype = dts.pop(), device = x.device)
        ext.fq_gemv_q8_0(flat, cat.view(sum(n), -1, 34), out)
        q = out[:, :n[0]].view(bsz, q_len, n[0])
        k = out[:, n[0]:n[0] + n[1]].view(bsz, q_len, n[1])
        v = out[:, n[0] + n[1]:].view(bsz, q_len, n[2])
        return q, k, v


    @override
    def get_tensors(self):
        t = {}
        if self.sinks is not None:
            # bf16 -> fp16 is exact at sink-logit magnitudes; stored as loaded
            t[f"{self.key}.{self.key_sinks}"] = self.sinks.half().contiguous()
        return t


    @override
    def unload(self):
        self._dec_qkv = False
        super().unload()

        self.bc_attn = {}
        knobs.clear_on_change(self, "bc_attn")         # BCAttn objects bake knob values (EXL3_QDEC_GRAPH, EXL3_BC_KVWIN...)

        for cl in self.cache_layers:
            cl.free()
        for rl in self.recurrent_layers:
            rl.free()

        self.rope = None
        self.sinks = None

        if self.multi_kv is not None:
            self.multi_kv.unload()
            self.multi_kv = None

        if self.multi_qg is not None:
            self.multi_qg.unload()
            self.multi_qg = None

        self.q_norm_tensor = None
        self.k_norm_tensor = None

        self.prealloc_qgh_1 = None
        self.prealloc_qg_1 = None
        self.prealloc_kvh_1 = None
        self.prealloc_kv_1 = None
        self.multi_qkv = None
        self.prealloc_qkvh_1 = None
        self.prealloc_qkv_out_1 = None
        self.prealloc_qkv_cptrs_1 = None
        self.prealloc_qkv_m = {}
        self.prealloc_qkv_carrier = None


    @override
    def forward(
        self,
        x: torch.Tensor,
        params: dict,
        out_dtype: torch.dtype | None = None
    ) -> torch.Tensor:

        if self.num_kv_heads == 0:
            x = torch.zeros_like(x, dtype = self.out_dtype)
            if self.tp_reduce:
                params["backend"].all_reduce(x, False)
        else:
            bsz, seqlen, _ = x.shape
            attn_mode = params.get("attn_mode", "flash_attn_nc")
            match attn_mode:
                case "flash_attn":
                    if bsz > 1 and params.get("row_inv_per_seq"):
                        # Row-invariant multi-job step (generator/row_groups.py): the attention block of each sequence is the
                        # block it would run alone. The split plan of the paged decode, the QSA selection and the graph path
                        # all follow the batch size and the longest sequence of the batch.
                        seq_params = params.get("row_inv_seq_params")
                        if seq_params is None:
                            seq_params = params["row_inv_seq_params"] = split_params_by_sequence(params, bsz)
                        if self.shared_proj_ok(params):
                            xs = self.decode_flash_attn_shared(x, bsz, seqlen, params, seq_params)
                            if _shared_check:      # debug: the per-sequence blocks as reference, bitwise
                                xr = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
                                _SHARED_STATS[0] += 1
                                if _SHARED_STATS[0] == 1: print("shared-proj check: first call", flush=True)
                                if not torch.equal(xs, xr):
                                    _SHARED_STATS[1] += 1
                                    if _SHARED_STATS[1] <= 5:
                                        print(f"shared-proj MISMATCH layer {self.layer_idx} bsz {bsz} q_len {seqlen} maxdiff {(xs.float() - xr.float()).abs().max().item()}", flush=True)
                                if _SHARED_STATS[0] % 500 == 0:
                                    print(f"shared-proj check: {_SHARED_STATS[1]} mismatching of {_SHARED_STATS[0]} calls", flush=True)
                            x = xs
                        else:
                            x = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
                    else:
                        x = self.decode_flash_attn(x, bsz, seqlen, params)
                case "flash_attn_nc":
                    x = self.decode_flash_attn_nc(x, bsz, seqlen, params)
                case _:
                    raise ValueError(f"Unknown attn_mode: {attn_mode}")
            if self.tp_reduce:
                params["backend"].all_reduce(x)

        if x is None:
            return None                          # kv_only, see decode_flash_attn
        # EXL3_NC2_ATTN_F16 (default off): the block asked for fp16 y (pfe_y_half) and o_proj returned it; keep it
        # instead of the fp32 widen to self.out_dtype (the residual apply / ablit project_widen widen in-kernel)
        if out_dtype is None and x.dtype == torch.half and params.get("pfe_y_half") and \
                os.environ.get("EXL3_NC2_ATTN_F16", "0") == "1":
            return x
        return to2(x, out_dtype, self.out_dtype)


    def _dec_qkv_linears(self):
        """q/k/v Linears when one exl3_dec_gemv_multi launch can replace their three forwards."""
        lins = getattr(self, "_dec_qkv", False)
        if lins is not False:
            return lins
        lins = None
        cand = [self.q_proj, self.k_proj] + ([] if self.use_k_as_v else [self.v_proj])
        if (
            hasattr(ext, "exl3_dec_gemv_multi") and os.environ.get("EXL3_DEC_QKV", "1") != "0" and
            not self.interleaved_gate and self.g_proj is None and all(l is not None for l in cand) and
            all(
                l.quant_type == "exl3" and getattr(l.inner, "dec_ok", False) and not l.lora_a_tensors and
                l.pre_scale == 1.0 and l.post_scale == 1.0 and l.softcap == 0.0 and l.inner.bias is None and
                l.out_features == l.out_features_unpadded and l.in_features == cand[0].in_features and
                l.inner.K == cand[0].inner.K and l.inner.default_out_dtype in (torch.half, torch.float)
                for l in cand
            )
        ):
            lins = cand
        self._dec_qkv = lins
        return lins

    def _dec_qkv_ig_linears(self):
        """q (interleaved q|gate per head) / k / v Linears when one exl3_dec_gemv_multi launch can replace their
        three forwards, else None."""
        lins = getattr(self, "_dec_qkv_ig", False)
        if lins is False:
            from .mla_attn import dec_proj_ok, dec_proj_shapes
            lins = None
            cand = [self.q_proj, self.k_proj] + ([] if self.use_k_as_v else [self.v_proj])
            if self.interleaved_gate and self.g_proj is None and all(l is not None for l in cand) and \
                    all(dec_proj_ok(l) for l in cand) and dec_proj_shapes(cand):
                lins = cand
            self._dec_qkv_ig = lins
        return lins

    def _project_qkv_ig_dec(self, x: torch.Tensor, params: dict, bsz: int, q_len: int):
        rows = bsz * q_len
        if rows > MAX_BSZN_GEMV_R or x.dtype != torch.half or x.shape[-1] != self.q_proj.in_features or \
                not x.is_contiguous() or "capture" in params or "ovr" in params:
            return None
        if rows > 1 and not (params.get("dflash_verify") and hasattr(ext, "exl3_dec_gemv_r_multi") and
                             os.environ.get("EXL3_VERIFY_GEMV_R", os.environ.get("EXL3_DEC_MOE_UNION", "0")) != "0"):
            return None
        lins = self._dec_qkv_ig_linears()
        if lins is None:
            return None
        from .mla_attn import dec_proj_multi
        outs = dec_proj_multi(lins, x, rows)
        qg = outs[0].view(bsz, q_len, -1)
        k = outs[1].view(bsz, q_len, -1)
        v = outs[2].view(bsz, q_len, -1) if len(outs) > 2 else k
        if self.head_dim % 8 == 0 and qg.dtype == torch.half:
            q = torch.empty((bsz, q_len, self.num_q_heads, self.head_dim), dtype = torch.half, device = qg.device)
            g = torch.empty((bsz, q_len, self.num_q_heads * self.head_dim), dtype = torch.half, device = qg.device)
            ext.deinterleave_qg(qg, q, g, self.head_dim)
        else:
            q, g = torch.chunk(qg.view(bsz, q_len, -1, self.head_dim * 2), 2, dim = -1)
            g = g.reshape(bsz, q_len, -1)
        return self.finish_qkv(q, k, v, g, bsz, q_len, params)

    def project_qkv(self, x: torch.Tensor, params: dict) -> tuple:
        bsz, q_len, dim = x.shape

        if _QKV_IG_MULTI and self.interleaved_gate:
            r = self._project_qkv_ig_dec(x, params, bsz, q_len)
            if r is not None:
                return r

        # Batch-1 decode: q, k and v in one exl3_dec launch (both Hadamard stages fused)
        if bsz * q_len == 1 and x.dtype == torch.half and dim == self.q_proj.in_features and \
                "capture" not in params and "ovr" not in params:
            lins = self._dec_qkv_linears()
            if lins is not None:
                from .quant.exl3 import dec_workspace
                scratch, counters = dec_workspace(x.device)
                outs = [torch.empty((bsz, q_len, l.out_features), dtype = l.inner.default_out_dtype, device = x.device)
                        for l in lins]
                ext.exl3_dec_gemv_multi(
                    x.view(1, dim).contiguous(),
                    [l.inner.trellis for l in lins], [l.inner.suh for l in lins], [l.inner.svh for l in lins],
                    [o.view(1, -1) for o in outs], scratch, counters, [float(l.inner.K) for l in lins])
                q, k = outs[0], outs[1]
                v = outs[2] if len(outs) > 2 else k
                return self.finish_qkv(q, k, v, None, bsz, q_len, params)

        # DFlash verify (R rows): same fused launch as the bsz==1 case above,
        # generalized to R rows via exl3_dec_gemv_r_multi -- see sliding_attn.py's identical
        # branch for why the fused multi-matrix call (not per-Linear dec_gemv_r) is required for
        # bit-exactness (shared strips_total -> shared ktw/kbs with the batch-1 launch). This is
        # the Attention (global/full-attention layer) counterpart of that fix -- MiMo has both
        # SlidingAttention and Attention layers, and only the former had this branch until now.
        if (
            1 < bsz * q_len <= MAX_BSZN_GEMV_R and x.dtype == torch.half and
            dim == self.q_proj.in_features and x.is_contiguous() and
            "capture" not in params and "ovr" not in params and
            os.environ.get("EXL3_VERIFY_GEMV_R", os.environ.get("EXL3_DEC_MOE_UNION", "0")) != "0" and
            params.get("dflash_verify") and
            hasattr(ext, "exl3_dec_gemv_r_multi")
        ):
            lins = self._dec_qkv_linears()
            if lins is not None:
                from .quant.exl3 import dec_workspace
                R = bsz * q_len
                scratch, counters = dec_workspace(x.device)
                outs = [torch.empty((R, l.out_features), dtype = l.inner.default_out_dtype, device = x.device)
                        for l in lins]
                ext.exl3_dec_gemv_r_multi(
                    x.view(R, dim).contiguous(),
                    [l.inner.trellis for l in lins], [l.inner.suh for l in lins], [l.inner.svh for l in lins],
                    outs, scratch, counters, [float(l.inner.K) for l in lins])
                outs = [o.view(bsz, q_len, -1) for o in outs]
                q, k = outs[0], outs[1]
                v = outs[2] if len(outs) > 2 else k
                return self.finish_qkv(q, k, v, None, bsz, q_len, params)

        if self.multi_qkv is not None and bsz * q_len <= 32:
            q, k, v, g = self.project_qkv_sliced(x, bsz, q_len)
            return self.finish_qkv(q, k, v, g, bsz, q_len, params)

        qkv8 = self._qkv_q8cat(x, params, bsz, q_len)
        from .foreign_linear import q8_share_begin, q8_share_end
        q8_share_begin()        # EXL3_FQ_MMVQ_EPI: q / k / v ForeignLinear gemvs share one q8_1 quantization of x (no-op when the flag is off)
        if self.multi_qg is None or bsz * q_len > 32:
            q = qkv8[0] if qkv8 is not None else self.q_proj.forward(x, params)
            if self.interleaved_gate:
                if self.head_dim % 8 == 0 and q.dtype == torch.half:
                    qg = q
                    q = torch.empty((bsz, q_len, self.num_q_heads, self.head_dim), dtype = torch.half, device = qg.device)
                    g = torch.empty((bsz, q_len, self.num_q_heads * self.head_dim), dtype = torch.half, device = qg.device)
                    ext.deinterleave_qg(qg, q, g, self.head_dim)
                else:
                    q, g = torch.chunk(q.view(bsz, q_len, -1, self.head_dim * 2), 2, dim = -1)
                    g = g.reshape(bsz, q_len, -1)
            elif self.g_proj:
                g = self.g_proj.forward(x, params)
            else:
                g = None

        else:
            # Unlike Linear.forward, the fused path doesn't zero-extend the input for padded
            # in_features, so do it here (K is the padded width the mgemm kernel reads)
            if x.shape[-1] < self.q_proj.in_features:
                x = torch.nn.functional.pad(x, (0, self.q_proj.in_features - x.shape[-1]))
            x = x.view(1, bsz * q_len, self.q_proj.in_features)
            if bsz * q_len == 1:
                qgh = self.prealloc_qgh_1
                qg = self.prealloc_qg_1
            else:
                qgh = torch.empty((2, bsz * q_len, self.q_proj.in_features), dtype = torch.half, device = x.device)
                qg = torch.empty((2, bsz * q_len, self.num_q_heads * self.head_dim), dtype = torch.half, device = x.device)
            ext.exl3_mgemm(
                x,
                self.multi_qg.ptrs_trellis,
                qg,
                self.multi_qg.ptrs_suh,
                qgh,
                self.multi_qg.ptrs_svh,
                None,
                None,
                self.multi_qg.K,
                -1,
                self.multi_qg.mcg,
                self.multi_qg.mul1,
                -1,
                -1,
                0,
                1, None, None)
            q = qg[0].view(bsz, q_len, self.num_q_heads * self.head_dim)
            g = qg[1].view(bsz, q_len, self.num_q_heads * self.head_dim)

        if qkv8 is not None:
            k, v = qkv8[1], qkv8[2]
        elif self.multi_kv is None or bsz * q_len > 32:
            k = self.k_proj.forward(x, params)
            v = self.v_proj.forward(x, params) if not self.use_k_as_v else k
            q8_share_end()

        else:
            if x.shape[-1] < self.k_proj.in_features:
                x = torch.nn.functional.pad(x, (0, self.k_proj.in_features - x.shape[-1]))
            x = x.view(1, bsz * q_len, self.k_proj.in_features)
            if bsz * q_len == 1:
                kvh = self.prealloc_kvh_1
                kv = self.prealloc_kv_1
            else:
                kvh = torch.empty((2, bsz * q_len, self.k_proj.in_features), dtype = torch.half, device = x.device)
                kv = torch.empty((2, bsz * q_len, self.num_kv_heads * self.head_dim), dtype = torch.half, device = x.device)
            ext.exl3_mgemm(
                x,
                self.multi_kv.ptrs_trellis,
                kv,
                self.multi_kv.ptrs_suh,
                kvh,
                self.multi_kv.ptrs_svh,
                None,
                None,
                self.multi_kv.K,
                -1,
                self.multi_kv.mcg,
                self.multi_kv.mul1,
                -1,
                -1,
                0,
                1, None, None)
            k = kv[0].view(bsz, q_len, self.num_kv_heads * self.head_dim)
            v = kv[1].view(bsz, q_len, self.num_kv_heads * self.head_dim)

        q8_share_end()
        return self.finish_qkv(q, k, v, g, bsz, q_len, params)


    def finish_qkv(self, q, k, v, g, bsz: int, q_len: int, params: dict) -> tuple:
        q = q.view(bsz, q_len, self.num_q_heads, self.head_dim)
        k = k.view(bsz, q_len, self.num_kv_heads, self.head_dim)
        v = v.view(bsz, q_len, self.num_kv_heads, self.head_dim)

        if self.v_norm is not None:
            v = self.v_norm.forward(v, params, out_dtype = torch.half)

        return q, k, v, g


    def project_qkv_sliced(self, x: torch.Tensor, bsz: int, q_len: int) -> tuple:
        """All attention projections as one sliced mgemm (see SlicedMultiLinear); m <= 32 rows"""
        mq = self.multi_qkv
        m = bsz * q_len
        n_q, n_kv = self.num_q_heads * self.head_dim, self.num_kv_heads * self.head_dim
        # The fused path doesn't zero-extend the input for padded in_features
        if x.shape[-1] < self.q_proj.in_features:
            x = torch.nn.functional.pad(x, (0, self.q_proj.in_features - x.shape[-1]))
        x = x.view(1, m, self.q_proj.in_features)
        if m == 1:
            qkvh = self.prealloc_qkvh_1
            qg, kv = self.prealloc_qkv_out_1
            c_ptrs = self.prealloc_qkv_cptrs_1
        else:
            # Per-m buffers + output-pointer table, built once: the pointer upload is a host-to-device copy, which a CUDA graph
            # capture of an m > 1 step (batched decode, MTP / ngram verify) cannot contain, and the addresses stay stable
            pre = self.prealloc_qkv_m.get((m, x.device))
            if pre is None:
                qkvh = torch.empty((mq.num_src, m, self.q_proj.in_features), dtype = torch.half, device = x.device)
                if self.interleaved_gate:
                    qg = torch.empty((1, m, 2 * n_q), dtype = torch.half, device = x.device)
                else:
                    qg = torch.empty((2, m, n_q), dtype = torch.half, device = x.device)
                kv = torch.empty((2, m, n_kv), dtype = torch.half, device = x.device)
                c_ptrs = mq.c_ptrs([qg[0], kv[0], kv[1]] + ([qg[1]] if self.g_proj is not None else []))
                pre = self.prealloc_qkv_m[(m, x.device)] = (qkvh, qg, kv, c_ptrs)
            qkvh, qg, kv, c_ptrs = pre
        ext.exl3_mgemm(
            x,
            mq.ptrs_trellis,
            self.prealloc_qkv_carrier.expand(mq.num_slices, m, mq.width),
            mq.ptrs_suh,
            qkvh,
            mq.ptrs_svh,
            None,
            None,
            mq.K,
            -1,
            mq.mcg,
            mq.mul1,
            -1,
            -1,
            0,
            1,
            mq.size_n_list,
            c_ptrs,
            mq.n_stride_list,
            mq.had_src_list,
            mq.num_src,
        )
        if self.interleaved_gate:
            q = torch.empty((bsz, q_len, self.num_q_heads, self.head_dim), dtype = torch.half, device = x.device)
            g = torch.empty((bsz, q_len, n_q), dtype = torch.half, device = x.device)
            ext.deinterleave_qg(qg[0].view(bsz, q_len, 2 * n_q), q, g, self.head_dim)
        else:
            q = qg[0].view(bsz, q_len, n_q)
            g = qg[1].view(bsz, q_len, n_q) if self.g_proj is not None else None
        k = kv[0].view(bsz, q_len, n_kv)
        v = kv[1].view(bsz, q_len, n_kv)
        return q, k, v, g


    def project_o(self, o: torch.Tensor, bsz: int, seqlen: int, params: dict) -> torch.Tensor:
        # o = o.reshape(bsz, seqlen, self.num_q_heads * self.head_dim)
        if self.v_head_dim != self.head_dim:
            y = dec_project_o_strided(self.o_proj, o, bsz, seqlen, self.num_q_heads, self.head_dim, self.v_head_dim, params)
            if y is not None:
                return y
            # Drop the zero lanes V was padded into so o_proj sees num_q_heads * v_head_dim
            o = o.view(bsz, seqlen, self.num_q_heads, self.head_dim)[..., : self.v_head_dim]
            o = o.reshape(bsz, seqlen, self.num_q_heads * self.v_head_dim).contiguous()
        o_dt = None
        if params.get("pfe_y_half") and os.environ.get("EXL3_PFE_OPROJ", "1") == "1" and \
                "capture" not in params and "quant_preserve" not in params:
            from .quant import exl3 as _exl3
            m = self.o_proj
            rows = o.numel() // o.shape[-1]
            if _exl3._f32_via_f16 and rows > max(_exl3.AUTO_RECONSTRUCT_THRESHOLD, _exl3._f32_via_f16_min_rows - 1) \
                    and type(m.inner).__name__ == "LinearEXL3" and m.inner.bias is None \
                    and not self.config.infer_params.no_reconstruct and not params.get("reconstruct") \
                    and not m.lora_a_tensors and m.pre_scale == 1.0 and m.post_scale == 1.0 \
                    and m.softcap == 0.0 and m.out_features == m.out_features_unpadded:
                o_dt = torch.half
        if o_dt is None and params.get("pfe_y_half") and "capture" not in params and "quant_preserve" not in params:
            from .foreign_linear import pfe_f16_ok
            if pfe_f16_ok(self.o_proj, o):
                o_dt = torch.half
        x = self.o_proj.forward(o, params, o_dt)
        return x


    def apply_qk_norms_tp(
        self,
        q: torch.Tensor,
        k: torch.Tensor,
        params: dict,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        Apply Q/K RMSNorm with TP-aware variance reduction.
        Used when span_heads=True and tp_reduce=True.

        The variance is computed locally, then all-reduced across TP ranks
        to get the true global variance.
        """
        backend = params["backend"]
        orig_q_shape = q.shape
        orig_k_shape = k.shape
        bsz, seq_len = q.shape[0], q.shape[1]

        # Flatten head dimension for norm computation: (bsz, seq, num_heads*head_dim)
        q_flat = q.view(bsz, seq_len, -1).float()
        k_flat = k.view(bsz, seq_len, -1).float()

        # Compute local sum of squares
        q_sq_sum = q_flat.pow(2).sum(dim=-1, keepdim=True)
        k_sq_sum = k_flat.pow(2).sum(dim=-1, keepdim=True)

        # Native TP backend requires data_size (numel * 2 bytes) to be multiple of 16.
        # So numel must be multiple of 8. We have 2 values (q, k) per position.
        # Flatten to 1D and pad to multiple of 8 elements.
        qk_sq_sum = torch.cat([q_sq_sum.view(-1), k_sq_sum.view(-1)])  # (bsz*seq_len*2,)
        numel = qk_sq_sum.numel()
        pad_to = (numel + 7) // 8 * 8
        if pad_to > numel:
            qk_sq_sum = torch.nn.functional.pad(qk_sq_sum, (0, pad_to - numel))
        backend.all_reduce(qk_sq_sum)
        # Extract back (first half is q, second half is k)
        half = bsz * seq_len
        q_sq_sum = qk_sq_sum[:half].view(bsz, seq_len, 1)
        k_sq_sum = qk_sq_sum[half:half*2].view(bsz, seq_len, 1)

        # Compute global variance (sum / global_dim)
        q_var = q_sq_sum / self.q_global_dim
        k_var = k_sq_sum / self.k_global_dim

        # Compute normalization factors
        q_rmf = torch.rsqrt(q_var + self.norm_eps)
        k_rmf = torch.rsqrt(k_var + self.norm_eps)

        # Get weights (handle constant_bias if needed)
        q_w = self.q_norm.weight
        k_w = self.k_norm.weight
        if self.norm_constant_bias != 0.0:
            q_w = q_w + self.norm_constant_bias
            k_w = k_w + self.norm_constant_bias

        # Apply normalization and reshape back
        q = (q_flat * q_rmf * q_w).half().view(orig_q_shape)
        k = (k_flat * k_rmf * k_w).half().view(orig_k_shape)

        return q, k


    def decode_flash_attn_nc(
        self,
        x: torch.Tensor,
        bsz: int,
        seqlen: int,
        params: dict,
    ):
        causal = params.get("causal", True)
        position = params.get("position", 0)
        positions = get_for_device(params, "positions", self.device, None)
        position_ids = get_for_device(params, "position_ids", self.device, None)
        inv_freq = get_for_device(params, "inv_freq", self.device, None)
        cu_seqlens = get_for_device(params, "cu_seqlens", self.device, None) if self.use_cu_seqlens else None
        max_seqlen = params["max_seqlen"] if cu_seqlens is not None else None
        simulate_kv_quant = params.get("sim_kvq", None)

        # QSA: Above sparse threshold, project/pool/select and attend through the gathered-GQA kernel
        # (flat-K/V variant of the BC sparse kernels)
        qsa_q_idx = qsa_pooled = None
        if self.qsa_indexer is not None:
            assert cu_seqlens is None, "QSA indexer: cu_seqlens batching not supported in nc mode"
            assert causal and position == 0 and positions is None
            if seqlen > self.qsa_indexer.sparse_threshold():
                qsa_q_idx, raw_k = self.qsa_indexer.project(x, self.rope, params)
                qsa_pooled = self.qsa_indexer.pool_keys(raw_k, self.rope, params)

        q, k, v, g = self.project_qkv(x, params)

        if self.q_norm:
            if self.tp_span_heads_norm:
                # TP-aware path for span_heads=True
                q, k = self.apply_qk_norms_tp(q, k, params)
            elif not self.rope or self.q_norm_tensor is None:
                q = self.q_norm.forward(q, params, out_dtype = torch.half)
                k = self.k_norm.forward(k, params, out_dtype = torch.half)

        if self.rope:
            q, k = self.rope.apply(
                q, k,
                position,
                positions,
                position_ids,
                True,
                self.q_norm_tensor if not self.tp_span_heads_norm else None,
                self.k_norm_tensor if not self.tp_span_heads_norm else None,
                self.norm_eps,
                self.norm_constant_bias,
                inv_freq,
            )

        if simulate_kv_quant:
            # (k_bits, v_bits) or (k_bits, v_bits, compand_a)
            sq_ca = simulate_kv_quant[2] if len(simulate_kv_quant) > 2 else 0.0
            _sim_kvq_inplace(k, simulate_kv_quant[0], sq_ca)
            _sim_kvq_inplace(v, simulate_kv_quant[1], sq_ca)

        if qsa_q_idx is not None:
            o = self.qsa_indexer.sparse_attend_nc(self, q, k, v, qsa_q_idx, qsa_pooled)
        else:
            o = attn_dispatch(
                q = q,
                k = k,
                v = v,
                cu_seqlens = cu_seqlens,
                max_seqlen = max_seqlen,
                causal = causal,
                sm_scale = self.sm_scale,
                window_size = self.window_arg(),
                softcap = self.logit_softcapping,
                sinks = self.sinks,
                dispatch_cache = self.dispatch_cache,
                v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,
            )

        if self.headwise_gate:
            if self.gate_softplus: ext.mul_softplus_broadcast_(o, g)
            else: ext.mul_sigmoid_broadcast_(o, g)
        o = o.reshape((bsz, seqlen, self.num_q_heads * self.head_dim))
        if self.full_gate or self.interleaved_gate: ext.mul_sigmoid_(o, g)

        o = self.project_o(o, bsz, seqlen, params)
        return o


    def bc_attn_step(self, x, cache, params, block_table, cache_seqlens, host_seqlens = None, kvwin_ctx = None):
        """
        Graph-captured decode attention block (projections through o_proj as one C++ call,
        replayed as one CUDA graph after warmup). Returns the block output, or None when the
        call must take the regular python path.
        """
        from ..cache import CacheLayer

        if cache is None or x.dtype != torch.float16 or not x.is_contiguous():
            return None
        if params.get("sim_kvq") is not None:
            return None
        positions = get_for_device(params, "positions", self.device, None)
        position_ids = get_for_device(params, "position_ids", self.device, None)
        inv_freq = get_for_device(params, "inv_freq", self.device, None)
        position = params.get("position", 0)

        layer = cache if isinstance(cache, CacheLayer) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
        key = id(layer)
        bca = self.bc_attn.get(key)
        if bca is None:
            bca = self.bc_attn[key] = (build_bc_attn(self, layer) or False)
        if bca is False:
            return None
        return bca.step(
            x, cache_seqlens, block_table, position, positions, position_ids, inv_freq,
            causal = params.get("causal", True), host_seqlens = host_seqlens, kvwin_ctx = kvwin_ctx
        )


    def cache_layer_type(self, default, kwargs: dict):
        """QSA modules need the indexer side planes on their cache layer: map the requested
        K/V layer type to its planes-carrying variant (fp16 or quantized)."""
        if self.qsa_indexer is None:
            return default, kwargs
        from ..cache.fp16 import CacheLayer_fp16
        from ..cache.quant import CacheLayer_quant
        from ..cache.qsa import CacheLayer_qsa, CacheLayer_qsa_quant, CacheLayer_qsa_tq
        from ..cache.tq import CacheLayer_tq
        if issubclass(default, CacheLayer_tq):
            return CacheLayer_qsa_tq, kwargs
        if issubclass(default, CacheLayer_quant):
            return CacheLayer_qsa_quant, kwargs
        assert issubclass(default, CacheLayer_fp16), \
            f"{default.__name__} is not supported for QSA layers; use CacheLayer_fp16 or CacheLayer_quant"
        return CacheLayer_qsa, kwargs


    def autosplit_extra_measure(self, params):
        if os.environ.get("EXL3_AUTOSPLIT_WORSTCASE", "1") == "0":
            return
        if self.qsa_indexer is None or self.device is None:
            return
        cache = params.get("cache")
        if cache is None:
            return
        from ..cache import CacheLayer, CacheLayer_quant
        from ..cache.qsa import QSAPlanes
        layer = cache if isinstance(cache, CacheLayer) else \
            cache.layers[self.layer_idx, params.get("layer_instance") or 0]
        if not isinstance(layer, QSAPlanes):
            return
        quant = isinstance(layer, CacheLayer_quant)
        chunk = params["batch_shape"][1]

        # Decode statics: every buffer the (bsz <= MAX_BSZ, q_len <= MAX_QLEN) slot family
        # can request, both regimes (sparse slots are single-job, and the regime-1 score
        # statics are sized to the full pooled-plane capacity at configure time). Backings
        # are bucketed and shared across slots and layers, so configuring the largest and
        # smallest shapes bounds the whole family
        key = id(layer)
        bca = self.bc_attn.get(key)
        if bca is None:
            bca = self.bc_attn[key] = (build_bc_attn(self, layer) or False)
        if bca:
            for b, q in ((1, 1), (_bc_max_bsz, _bc_max_qlen)):
                bca._configure(b, q, True, 0)
            if bca.qsa:
                for q in (1, _bc_max_qlen):
                    bca._configure(1, q, True, 1)

        # Sparse prefill at maximum context. Synthetic state: every block-table entry aliases
        # page 0, zeroed so the math stays finite
        num_pages = (layer.qk if quant else layer.k).shape[0]
        t_syn = num_pages * PAGE_SIZE - chunk
        if t_syn + chunk <= self.qsa_indexer.sparse_threshold():
            return   # cache too small to ever reach the sparse regime
        for t in ((layer.qk, layer.qv, layer.sk, layer.sv) if quant else (layer.k, layer.v)):
            t[0].zero_()
        layer.raw_k[0].zero_()
        layer.pooled[0].zero_()
        p2 = {k2: v2 for k2, v2 in params.items() if k2 not in
              ("dev_cache", "positions", "position_ids")}
        p2["cache_seqlens"] = torch.tensor([t_syn], dtype = torch.int32)
        p2["block_table"] = torch.zeros((1, num_pages), dtype = torch.int32)
        p2["position"] = t_syn
        x = torch.zeros((1, chunk, self.hidden_size), dtype = torch.half, device = self.device)
        self.forward(x, p2)


    def kvwin_ctx(self, cache, params: dict, bsz: int, block_table: torch.Tensor):
        """KVWIN ring context of this attention call (None when off, inert or the call has no job states)."""
        if not self.caps.get("recurrent_cache"):
            return None
        rl = getattr(cache, "recurrent_layers", None)
        if not rl:
            return None
        ctx = _kvwin_ctx(rl.get((self.layer_idx, params.get("layer_instance") or 0)), params, self.device, bsz)
        _kvwin_fill(ctx, params, block_table)
        return ctx


    def decode_flash_attn(
        self,
        x: torch.Tensor,
        bsz: int,
        seqlen: int,
        params: dict,
    ):
        cache = params.get("cache")
        # In TP child processes the cache param arrives as an opaque id; resolve it to the local split
        # CacheLayer before anything (like the BC-attn graph path) inspects it
        if self.has_split_cache:
            cache = self.tp_cache_lookup[cache]
        block_table = get_for_device(params, "block_table", self.device)
        cache_seqlens = get_for_device(params, "cache_seqlens", self.device)
        position = params.get("position", 0)
        positions = get_for_device(params, "positions", self.device, None)
        position_ids = get_for_device(params, "position_ids", self.device, None)
        ov = self.kvwin_ctx(cache, params, bsz, block_table)
        inv_freq = get_for_device(params, "inv_freq", self.device, None)
        causal = params.get("causal", True)
        non_causal_spans = params.get("non_causal_spans")
        simulate_kv_quant = params.get("sim_kvq", None)

        # QSA: the indexer's raw/pooled key planes must be maintained on every cached forward.
        # The BC graph path below maintains them in-graph (both regimes) and runs the gathered
        # sparse attention once some query position exceeds the threshold below which dense
        # attention is exactly equivalent (top-k cannot exclude anything); when BC declines,
        # the eager fallback does both
        qsa_sparse = False
        qsa_q_idx = None
        qsa_layer = None
        qsa_seqlens_cpu = None
        if self.qsa_indexer is not None:
            from ..cache import CacheLayer as _CL
            qsa_layer = cache if isinstance(cache, _CL) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
            qsa_seqlens_cpu = get_for_device(params, "cache_seqlens", "cpu")
            qsa_sparse = int(qsa_seqlens_cpu.max().item()) + seqlen > self.qsa_indexer.sparse_threshold()

        # Graph-captured C++ path for the whole decode attention block (causality is baked
        # into the slot kernels, so non-causal callers like the DFlash draft graph too)
        if (
            _bc_attn_enable and non_causal_spans is None and
            bsz <= _bc_max_bsz and seqlen <= _bc_max_qlen
        ):
            o = self.bc_attn_step(x, cache, params, block_table, cache_seqlens,
                                  host_seqlens = qsa_seqlens_cpu, kvwin_ctx = ov)
            if o is not None:
                return o

        if self.qsa_indexer is not None:
            qsa_q_idx = self.qsa_indexer.update_planes(qsa_layer, x, self.rope, block_table, qsa_seqlens_cpu, params)

        q, k, v, g = self.project_qkv(x, params)

        if self.q_norm:
            if self.tp_span_heads_norm:
                # TP-aware path for span_heads=True
                q, k = self.apply_qk_norms_tp(q, k, params)
            elif not self.rope or self.q_norm_tensor is None:
                q = self.q_norm.forward(q, params, out_dtype = torch.half)
                k = self.k_norm.forward(k, params, out_dtype = torch.half)

        if self.rope:
            q, k = self.rope.apply(
                q, k,
                position,
                positions,
                position_ids,
                True,
                self.q_norm_tensor if not self.tp_span_heads_norm else None,
                self.k_norm_tensor if not self.tp_span_heads_norm else None,
                self.norm_eps,
                self.norm_constant_bias,
                inv_freq,
            )

        if simulate_kv_quant:
            # (k_bits, v_bits) or (k_bits, v_bits, compand_a)
            sq_ca = simulate_kv_quant[2] if len(simulate_kv_quant) > 2 else 0.0
            _sim_kvq_inplace(k, simulate_kv_quant[0], sq_ca)
            _sim_kvq_inplace(v, simulate_kv_quant[1], sq_ca)

        if qsa_sparse:
            qsa_layer.update_kv_sparse(cache_seqlens, block_table, k, v, seqlen)
            if params.get("kv_only") and _kv_only_skip:
                # EXL3_PF_SKIP kv_only (the MTP draft prompt prefill): K/V and the indexer planes are written, the block's
                # output is discarded by the caller, so the selection, the sparse attention and everything after it are skipped.
                # EXL3_PF_KV_ONLY_ATTN=0 runs them again (same cache contents either way).
                return None
            o = self.qsa_indexer.sparse_attend_verify(qsa_layer, self, q, qsa_q_idx, block_table, qsa_seqlens_cpu)
        else:
            # QSA dense regime: the past is bounded by the sparse threshold, which lets the
            # quantized-cache prefill size its staging to the window instead of the job's pages
            max_kv_len = int(qsa_seqlens_cpu.max().item()) if qsa_seqlens_cpu is not None else None
            # CUDA: prefill-sized chunks take the bound from the host copy of cache_seqlens (built on the CPU by the
            # generator, no sync), as upstream exllamav3 1.6.0 (MIT) attn.py does. Without it the quantized-cache prefill
            # stages (dequantizes) the job's whole page span for every chunk (+19.8 % TTFT on a 178K-token prompt, RTX 3090)
            if max_kv_len is None and seqlen > 16 and not torch.version.hip:
                cs_host = params.get("cache_seqlens")
                if isinstance(cs_host, torch.Tensor) and cs_host.device.type == "cpu" and cs_host.numel():
                    max_kv_len = int(cs_host.max())
            # TurboQuant cache: the many-row kernel (cu/qdec_rows.cu) serves every row count 1..32 as one program per kv
            # head (verified against the dequantized reference, relerr 0.7-1.9e-3), so the R verify rows run as ONE batched
            # call like the quantized cache does through the BC graph path. The per-row loop below is a bitwise
            # row-invariance device and costs R x the attention time (128K MTP verify: 49.3 ms/step of 98.0 vs 12.0 of
            # 59.0 for the quant cache). EXL3_TQ_VERIFY_LOOP=1 keeps the loop.
            tq_batch = False
            if 1 < seqlen <= MAX_BSZN_GEMV_R and ov is None and os.environ.get("EXL3_TQ_VERIFY_LOOP", "0") == "0":
                from ..cache import CacheLayer as _CLv
                _lyr = cache if isinstance(cache, _CLv) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
                tq_batch = bool(getattr(_lyr, "tq", False))
            if (
                1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and not tq_batch and
                (knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0") or gguf_ri("attn"))
            ):
                # Row-invariant verify: the R-row paged decode tiles the KV span from the batch's single
                # cache_seqlens/q_len, a different float order than R batch-1 calls. Run the exact
                # batch-1 call per row (each appends its own K/V at cache_seqlens + i and attends i + 1 keys).
                # a one-row slice is only contiguous at batch 1; the paged kernels need contiguous rows
                o = torch.cat([attn_dispatch(
                    q = q[:, i:i + 1].contiguous(),
                    k = k[:, i:i + 1].contiguous(),
                    v = v[:, i:i + 1].contiguous(),
                    cache = cache,
                    cache_idx = self.layer_idx,
                    cache_instance = params.get("layer_instance"),
                    block_table = block_table,
                    cache_seqlens = cache_seqlens + i,
                    causal = causal,
                    sm_scale = self.sm_scale,
                    window_size = self.window_arg(),
                    softcap = self.logit_softcapping,
                    non_causal_spans = None,
                    sinks = self.sinks,
                    dispatch_cache = self.dispatch_cache,
                    max_kv_len = max_kv_len,
                    v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,
                    ov = ov,
                ) for i in range(seqlen)], dim = 1)
            else:
                o = attn_dispatch(
                    q = q,
                    k = k,
                    v = v,
                    cache = cache,
                    cache_idx = self.layer_idx,
                    cache_instance = params.get("layer_instance"),
                    block_table = block_table,
                    cache_seqlens = cache_seqlens,
                    causal = causal,
                    sm_scale = self.sm_scale,
                    window_size = self.window_arg(),
                    softcap = self.logit_softcapping,
                    non_causal_spans = non_causal_spans,
                    sinks = self.sinks,
                    dispatch_cache = self.dispatch_cache,
                    max_kv_len = max_kv_len,
                    v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,
                    ov = ov,
                )

        if self.headwise_gate:
            if self.gate_softplus: ext.mul_softplus_broadcast_(o, g)
            else: ext.mul_sigmoid_broadcast_(o, g)
        o = o.reshape((bsz, seqlen, self.num_q_heads * self.head_dim))
        pitch = 0
        if (self.full_gate or self.interleaved_gate) and self.v_head_dim == self.head_dim and not self.headwise_gate and \
                o.dtype == torch.half and g.dtype == torch.half and o.is_contiguous() and g.is_contiguous() and \
                getattr(ext, "mul_sigmoid_pad", None) is not None:
            pitch = row_pad_pitch(self.o_proj, o.shape[-1], o.numel() // o.shape[-1], params)
        if pitch:
            # same fp16 product as mul_sigmoid_, written at a padded row pitch (o_proj reads it at full rate)
            o2 = torch.empty((o.numel() // o.shape[-1], pitch), dtype = torch.half, device = o.device)[:, :o.shape[-1]].view(o.shape)
            ext.mul_sigmoid_pad(o, g, o2, pitch)
            o = o2
        elif self.full_gate or self.interleaved_gate:
            ext.mul_sigmoid_(o, g)

        o = self.project_o(o, bsz, seqlen, params)
        return o


    def shared_proj_ok(self, params: dict) -> bool:
        """EXL3_ATTN_SHARED_PROJ (default on, ROCm): the row-invariant multi-job step runs the q/k/v and o projections of all
        sequences in one launch and only the cache update + attention per sequence (decode_flash_attn_shared). CUDA keeps the
        graph-captured per-sequence block (BC_Attention)."""
        return (
            _shared_proj and torch.version.hip is not None and self.num_kv_heads > 0 and
            params.get("non_causal_spans") is None and not params.get("sim_kvq") and not params.get("kv_only") and
            params.get("position_ids") is None and not self.tp_reduce
        )


    def decode_flash_attn_shared(self, x: torch.Tensor, bsz: int, seqlen: int, params: dict, seq_params: list):
        """decode_flash_attn for a row-invariant multi-job step (params["row_inv_per_seq"]) with the projections shared by the
        sequences. The kernels of the projections, head norms, rope and gates give each row the bits of the one-row launch
        whatever the row count (util/row_inv.py), so those run once over the bsz * seqlen rows; the parts whose plan follows
        the batch (the QSA plane update and selection, the paged attention split plan) run once per sequence on one-row
        slices, exactly as decode_flash_attn(x[b:b+1], ...) does."""
        cache = params.get("cache")
        block_table = get_for_device(params, "block_table", self.device)
        cache_seqlens = get_for_device(params, "cache_seqlens", self.device)
        position = params.get("position", 0)
        positions = get_for_device(params, "positions", self.device, None)
        inv_freq = get_for_device(params, "inv_freq", self.device, None)
        causal = params.get("causal", True)
        ov_all = self.kvwin_ctx(cache, params, bsz, block_table)
        qsa_layer = qsa_cpu = None
        if self.qsa_indexer is not None:
            from ..cache import CacheLayer as _CL
            qsa_layer = cache if isinstance(cache, _CL) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
            qsa_cpu = get_for_device(params, "cache_seqlens", "cpu")

        q, k, v, g = self.project_qkv(x, params)
        if self.q_norm:
            if self.tp_span_heads_norm:
                q, k = self.apply_qk_norms_tp(q, k, params)
            elif not self.rope or self.q_norm_tensor is None:
                q = self.q_norm.forward(q, params, out_dtype = torch.half)
                k = self.k_norm.forward(k, params, out_dtype = torch.half)
        if self.rope:
            q, k = self.rope.apply(
                q, k, position, positions, None, True,
                self.q_norm_tensor if not self.tp_span_heads_norm else None,
                self.k_norm_tensor if not self.tp_span_heads_norm else None,
                self.norm_eps, self.norm_constant_bias, inv_freq,
            )

        outs = []
        bsz_loop = bsz
        if _batch_qsa and qsa_cpu is not None and bsz > 1:
            thr = self.qsa_indexer.sparse_threshold()
            if all(int(qsa_cpu[b]) + seqlen > thr for b in range(bsz)):
                q_idx = self.qsa_indexer.update_planes(qsa_layer, x, self.rope, block_table, qsa_cpu, params)
                qsa_layer.update_kv_sparse(cache_seqlens, block_table, k, v, seqlen)
                outs.append(self.qsa_indexer.sparse_attend(qsa_layer, self, q, q_idx, block_table, qsa_cpu))
                bsz_loop = 0
        for b in range(bsz_loop):
            sl = slice(b, b + 1)
            bt_b, cs_b = block_table[sl], cache_seqlens[sl]
            if qsa_cpu is not None:
                cpu_b = qsa_cpu[sl]
                sparse = int(cpu_b.max().item()) + seqlen > self.qsa_indexer.sparse_threshold()
                q_idx = self.qsa_indexer.update_planes(qsa_layer, x[sl], self.rope, bt_b, cpu_b, seq_params[b])
            else:
                cpu_b, sparse = None, False
            if sparse:
                qsa_layer.update_kv_sparse(cs_b, bt_b, k[sl], v[sl], seqlen)
                outs.append(self.qsa_indexer.sparse_attend_verify(qsa_layer, self, q[sl], q_idx, bt_b, cpu_b))
            else:
                max_kv_len = int(cpu_b.max().item()) if cpu_b is not None else None
                if max_kv_len is None and seqlen > 16 and not torch.version.hip:
                    max_kv_len = int(params["cache_seqlens"][sl].max())
                # EXL3_VERIFY_ATTN_LOOP: the R-row paged decode as R one-row calls, as decode_flash_attn does
                rows = range(seqlen) if 1 < seqlen <= MAX_BSZN_GEMV_R and (knobs.knob_on("EXL3_VERIFY_ATTN_LOOP", "0") or gguf_ri("attn")) else None
                def call(qq, kk, vv, cs):
                    return attn_dispatch(
                        q = qq, k = kk, v = vv,
                        cache = cache, cache_idx = self.layer_idx, cache_instance = params.get("layer_instance"),
                        block_table = bt_b, cache_seqlens = cs, causal = causal, sm_scale = self.sm_scale,
                        window_size = self.window_arg(), softcap = self.logit_softcapping, non_causal_spans = None,
                        sinks = self.sinks, dispatch_cache = self.dispatch_cache, max_kv_len = max_kv_len,
                        v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,
                        ov = ov_all._replace(slots = ov_all.slots[sl]) if ov_all is not None else None,
                    )
                if rows is None:
                    outs.append(call(q[sl], k[sl], v[sl], cs_b))
                else:
                    outs.append(torch.cat([call(q[sl][:, i:i + 1].contiguous(), k[sl][:, i:i + 1].contiguous(),
                                                v[sl][:, i:i + 1].contiguous(), cs_b + i) for i in rows], dim = 1))
        o = torch.cat(outs, dim = 0)

        if self.headwise_gate:
            if self.gate_softplus: ext.mul_softplus_broadcast_(o, g)
            else: ext.mul_sigmoid_broadcast_(o, g)
        o = o.reshape((bsz, seqlen, self.num_q_heads * self.head_dim))
        pitch = 0
        if (self.full_gate or self.interleaved_gate) and self.v_head_dim == self.head_dim and not self.headwise_gate and \
                o.dtype == torch.half and g.dtype == torch.half and o.is_contiguous() and g.is_contiguous() and \
                getattr(ext, "mul_sigmoid_pad", None) is not None:
            pitch = row_pad_pitch(self.o_proj, o.shape[-1], o.numel() // o.shape[-1], params)
        if pitch:
            o2 = torch.empty((o.numel() // o.shape[-1], pitch), dtype = torch.half, device = o.device)[:, :o.shape[-1]].view(o.shape)
            ext.mul_sigmoid_pad(o, g, o2, pitch)
            o = o2
        elif self.full_gate or self.interleaved_gate:
            ext.mul_sigmoid_(o, g)

        return self.project_o(o, bsz, seqlen, params)


    def window_arg(self):
        """window_size argument for attn_dispatch: an int (left window, right bound 0) or an
        explicit (left, right) pair when window_right is set."""
        if self.window_right:
            return (self.sliding_window, self.window_right)
        return self.sliding_window


    def make_tp_allocation(self, options: dict) -> list[TPAllocation]:
        storage = 0
        storage += self.q_proj.storage_size()
        storage += self.k_proj.storage_size()
        storage += self.v_proj.storage_size() if self.v_proj else 0
        storage += self.o_proj.storage_size()
        for cl in self.cache_layers:
            storage += cl.storage_size()
        overhead_d = 0
        overhead_d += self.hidden_size * (self.out_dtype or torch.half).itemsize
        overhead_s = 0
        for cl in self.cache_layers:
            overhead_s += cl.overhead_size()
        overhead_s += 2 * self.num_q_heads * self.head_dim * torch.half.itemsize  # q, o
        overhead_s += 2 * self.num_kv_heads * self.head_dim * torch.half.itemsize  # k, v
        recons = max(
            self.q_proj.recons_size(),
            self.k_proj.recons_size(),
            self.v_proj.recons_size() if self.v_proj else 0,
            self.o_proj.recons_size(),
        )
        channel_width = 1
        channels_to_split = self.num_kv_heads
        while channel_width * self.head_dim < 128:
            assert channels_to_split % 2 == 0, \
                "Model's K/V heads cannot divide into 128-channel tensors"
            channel_width *= 2
            channels_to_split //= 2
        assert (channel_width * self.head_dim) % 128 == 0, \
            "Model's K/V heads cannot divide into 128-channel tensors"
        # TODO: Account for flash-attn temp VRAM usage
        tpa = TPAllocation(
            key = self.key,
            channel_width = channel_width,
            channel_unit = "heads",
            storage_per_device = 0,
            storage_to_split = storage,
            overhead_per_device = overhead_d,
            overhead_to_split = overhead_s,
            recons_temp = recons,
            channels_to_split = channels_to_split,
            limit_key = "attn"
        )
        return [tpa]


    def tp_export(self, plan, producer):
        assert self.device is not None, "Cannot export module for TP before loading."
        assert getattr(self, "qsa_indexer", None) is None, \
            "TP export of Attention with a QSA indexer is not implemented"

        def _export(child):
            nonlocal producer
            return child.tp_export(plan, producer) if child is not None else None

        # Check if q_norm uses span_heads
        q_norm_span_heads = (
            self.q_norm is not None and
            isinstance(self.q_norm, RMSNorm) and
            self.q_norm.span_heads
        )

        return {
            "cls": Attention,
            "kwargs": {
                "key": self.key,
                "layer_idx": self.layer_idx,
                "hidden_size": self.hidden_size,
                "head_dim": self.head_dim,
                "rope_settings": self.rope_settings,
                "sm_scale": self.sm_scale,
                "out_dtype": self.out_dtype,
                "sliding_window": self.sliding_window,
                "logit_softcapping": self.logit_softcapping,
                "tp_split_norm": self.tp_split_norm,
                "use_k_as_v": self.use_k_as_v,
                "interleaved_gate": self.interleaved_gate,
                "full_gate": self.full_gate,
                "gate_softplus": self.gate_softplus,
                "use_cu_seqlens": self.use_cu_seqlens,
            },
            "num_kv_heads": self.num_kv_heads,
            **{name: _export(getattr(self, name, None)) for name in (
                "q_norm",
                "k_norm",
                "v_norm",
                "q_proj",
                "k_proj",
                "v_proj",
                "kv_proj",
                "o_proj",
                "g_proj",
            )},
            # Learned attention sinks (gpt-oss): one logit per query head, sliced to the local heads on import
            "sinks": producer.send(self.sinks) if self.sinks is not None else None,
            "device": self.device,
            "cache_layers": [
                cl.tp_export(plan) for cl in self.cache_layers
            ],
            "n_gqa": self.num_q_heads // self.num_kv_heads,
            # For TP-aware span_heads norm
            "q_norm_span_heads": q_norm_span_heads,
            "q_global_dim": self.num_q_heads * self.head_dim if self.q_norm else 0,
            "k_global_dim": self.num_kv_heads * self.head_dim if self.k_norm else 0,
        }


    @staticmethod
    def tp_import(local_context, exported, plan, **kwargs):
        key = exported["kwargs"]["key"]
        interleaved_gate = exported["kwargs"]["interleaved_gate"]
        head_dim = exported["kwargs"]["head_dim"]
        n_gqa = exported["n_gqa"]
        device = local_context["device"]
        tp_split_norm = exported["kwargs"]["tp_split_norm"]
        first, last, unit = plan[key]
        assert unit == "heads"
        num_kv_heads = last - first
        num_q_heads = num_kv_heads * n_gqa

        q_split = (True, first * head_dim * n_gqa, last * head_dim * n_gqa) \
            if num_kv_heads else None
        if interleaved_gate and num_kv_heads:
            q_split = q_split[0], q_split[1] * 2, q_split[2] * 2
        # Full gate spans head_dim channels per q head, headwise gate is one channel per q head
        if exported["kwargs"].get("full_gate", False):
            qh_split = (True, first * head_dim * n_gqa, last * head_dim * n_gqa) \
                if num_kv_heads else None
        else:
            qh_split = (True, first * n_gqa, last * n_gqa) \
                if num_kv_heads else None
        kv_split = (True, first * head_dim, last * head_dim) \
            if num_kv_heads else None
        o_split = (False, first * head_dim * n_gqa, last * head_dim * n_gqa) \
            if num_kv_heads else None
        # For span_heads norms, we need element indices (head_idx * head_dim)
        # For regular norms, we use head indices
        q_norm_span_heads = exported.get("q_norm_span_heads", False)
        if q_norm_span_heads:
            # span_heads=True: norm weight is 1D with shape (num_heads * head_dim,)
            norm_q_split = (first * head_dim * n_gqa, last * head_dim * n_gqa) \
                if num_kv_heads else None
            norm_k_split = (first * head_dim, last * head_dim) \
                if num_kv_heads else None
        else:
            # span_heads=False: norm weight is 2D with shape (num_heads, head_dim)
            norm_q_split = (first * n_gqa, last * n_gqa) \
                if num_kv_heads else None
            norm_k_split = (first, last) \
                if num_kv_heads else None

        def _import(name):
            nonlocal exported, plan
            return exported[name]["cls"].tp_import(local_context, exported[name], plan) \
                if exported.get(name) else None

        def _import_split(name, split):
            nonlocal exported, plan
            return exported[name]["cls"].tp_import_split(local_context, exported[name], plan, split) \
                if split and exported.get(name) else None

        module = Attention(
            config = None,
            **exported["kwargs"],
            num_q_heads = num_q_heads,
            num_kv_heads = num_kv_heads,
            q_norm = _import_split("q_norm", norm_q_split) if tp_split_norm else _import("q_norm"),
            k_norm = _import_split("k_norm", norm_k_split) if tp_split_norm else _import("k_norm"),
            # V norm shares the K/V head geometry (gemma4: unweighted, so the split is a no-op there)
            v_norm = _import_split("v_norm", norm_k_split) if tp_split_norm else _import("v_norm"),
            q_proj = _import_split("q_proj", q_split),
            k_proj = _import_split("k_proj", kv_split),
            v_proj = _import_split("v_proj", kv_split),
            kv_proj = _import_split("kv_proj", kv_split),
            o_proj = _import_split("o_proj", o_split),
            g_proj = _import_split("g_proj", qh_split),
        )

        # Attention sinks are one logit per query head; each rank keeps its local head range
        if exported.get("sinks") is not None and num_kv_heads:
            consumer = local_context["consumer"]
            module.sinks = consumer.recv(
                exported["sinks"], cuda = True, slice_dim = 0, first = first * n_gqa, last = last * n_gqa
            )

        if num_kv_heads:
            cache_layers = exported["cache_layers"]
            if len(cache_layers):
                module.has_split_cache = True
                for cl in exported["cache_layers"]:
                    cli = cl["cls"](None, module, **cl["args"])
                    module.cache_layers.append(cli)
                    module.tp_cache_lookup[cl["args"]["cache_id"]] = cli

        module.device = device
        if not kwargs.get("skip_reduction"):
            module.tp_reduce = True

        # Set up TP-aware span_heads norm if needed
        if exported.get("q_norm_span_heads", False):
            module.tp_span_heads_norm = True
            module.q_global_dim = exported.get("q_global_dim", 0)
            module.k_global_dim = exported.get("k_global_dim", 0)

        module.load_local(device)
        torch.cuda.synchronize()
        return module