From f8623d5a0f0a08eefc6888fc6ef182c06c361fec Mon Sep 17 00:00:00 2001 From: Harrison Zhang Date: Thu, 29 Oct 2026 14:34:33 -0700 Subject: [PATCH 1/2] [primsTS][fmha][visual_gen] add the VC-Attention recipes to the PrimTS FMHA QuantAttentionConfig.vc_attention runs a recipe as VC-Attention on the TRTLLM backend: (bf16, fp8, (0, 0, 1)) keeps Q/K in BF16 with V as E4M3 residuals around 128-token tile means that the kernel restores (VC-Attention-QK16), and (fp8, fp8, (128, 128, 1)) adds Hadamard-rotated E4M3 Q/K scaled per 128 tokens (VC-Attention-QK8). vc_repair_budget replaces the tile means by that fraction of tokens as V repair rows and requires vc_attention. The VisualGen backend sends the recipe down the separate-QKV path as forward args, the cache-free adapter owns the per-layer V-Smooth preparation over the denoising steps and keys its plan on the demean phase and repair tile count, and FMHA libraries without the supports_vc_attention capability reject the request. Signed-off-by: Harrison Zhang --- .../features/visualgen-quantized-attention.md | 55 +++++- .../attention/backends/fmha/interface.py | 4 + .../attention/backends/fmha/prims_ts.py | 49 ++++- .../backends/fmha/prims_ts_block_sparse.py | 3 + .../_torch/attention/backends/interface.py | 8 + .../visual_gen/attention/backends/trtllm.py | 167 +++++++++++++++++- .../_torch/visual_gen/models/modeling.py | 19 ++ tensorrt_llm/_torch/visual_gen/pipeline.py | 27 ++- ...trtllm-serve-visual-gen-config.schema.json | 16 ++ tensorrt_llm/visual_gen/args.py | 81 ++++++++- .../integration/test_lists/test-db/l0_cpu.yml | 1 + .../test_prims_ts_attention_backend.py | 134 +++++++++++--- .../test_trtllm_attention_metadata.py | 32 ++++ .../visual_gen/test_vc_smooth_schedule.py | 97 ++++++++++ .../_torch/visual_gen/test_visual_gen_args.py | 129 ++++++++++++++ 15 files changed, 778 insertions(+), 44 deletions(-) create mode 100644 tests/unittest/_torch/visual_gen/test_vc_smooth_schedule.py diff --git a/docs/source/features/visualgen-quantized-attention.md b/docs/source/features/visualgen-quantized-attention.md index 4ecc17b732f1..8cbe280b25f0 100644 --- a/docs/source/features/visualgen-quantized-attention.md +++ b/docs/source/features/visualgen-quantized-attention.md @@ -31,6 +31,8 @@ A recipe is the tuple `(qk_dtype, v_dtype, (q_block_size, k_block_size, v_block_ | `TRTLLM` | `fp8` | `fp8` | `(1, 1, 1)`, `(1, 4, 1)`, `(1, 16, 1)` | SageAttention (FP8 QK) for Blackwell | | `TRTLLM` | `bf16` | `fp8` | `(0, 0, 0)` | PrimTS QK16PV8 for Blackwell (`TLLM_FMHA_LIBS=+prims_ts`) | | `TRTLLM` | `fp8` | `fp8` | `(0, 0, 0)` | PrimTS FP8 for Blackwell (`TLLM_FMHA_LIBS=+prims_ts`) | +| `TRTLLM` | `bf16` | `fp8` | `(0, 0, 1)` | VC-Attention-QK16 for Blackwell, V as E4M3 tile residuals with per-channel scales (`vc_attention: true`, `TLLM_FMHA_LIBS=+prims_ts`) | +| `TRTLLM` | `fp8` | `fp8` | `(128, 128, 1)` | VC-Attention-QK8 for Blackwell, Hadamard-rotated E4M3 Q/K scaled per 128 tokens and the same V treatment (`vc_attention: true`, `TLLM_FMHA_LIBS=+prims_ts`) | | `CUDNN` | `fp8` | `fp8` | `(0, 0, 0)` | cuDNN FP8 | | `CUDNN` | `mxfp8` | `mxfp8` | `(0, 0, 0)` | cuDNN MXFP8 | | `CUTEDSL` | `bf16` | `fp8` | `(0, 0, 0)` | QK16PV8 | @@ -40,7 +42,7 @@ A recipe is the tuple `(qk_dtype, v_dtype, (q_block_size, k_block_size, v_block_ | `FLASHINFER` | `nvfp4` | `fp8` | `(0, 0, 0)` | NVFP4 Q/K | | `FLASHINFER` | `nvfp4` | `nvfp4` | `(0, 0, 0)` | NVFP4 Attention | -The `TRTLLM` backend picks the kernel from the block sizes: SageAttention quantizes per block, and the `(0, 0, 0)` per-tensor recipes run on the PrimTS FMHA library, which `TLLM_FMHA_LIBS=+prims_ts` enables. +The `TRTLLM` backend picks the kernel from the block sizes: SageAttention quantizes per block, and the `(0, 0, 0)` per-tensor recipes run on the PrimTS FMHA library, which `TLLM_FMHA_LIBS=+prims_ts` enables. VC-Attention fixes its block sizes to the recipe's scaling granularity; leave them at `0` and the validator sets them, see [VC-Attention in the `TRTLLM` backend](#vc-attention-in-the-trtllm-backend). ### Choosing and Tuning a Recipe @@ -53,6 +55,7 @@ Video quality is generally more sensitive to BMM1 accuracy than BMM2 accuracy, s - On B300/GB300, start with MXFP8 when optimizing the quality-throughput balance. SageAttention with FP8 Q/K remains an alternative when the `TRTLLM` backend is preferred for the surrounding workload. - For SageAttention with INT8 Q/K, the default `(2, 16, 1)` or `(1, 16, 1)` block-size recipes works well for most cases. Use `(1, 4, 1)` when video quality is not satisfactory. - The `CUDNN` backend requires Q/K and V to use the same format. Use `fp8` for per-tensor scaling or `mxfp8` for block scaling. +- For VC-Attention (`vc_attention: true`), `vc_repair_budget: 0.005` (0.5% of the tokens as repair rows) runs faster than the default tile means at unchanged quality; `0.005` to `0.02` is the useful range. - For `CUTEDSL` MXFP8 or NVFP4 recipes, `v_block_size: 1` uses a separate V scale per head and channel, while `v_block_size: 0` uses one tensor-wide V scale. Try the per-channel variant when the tensor-wide scale loses quality. After a recipe meets the quality target, benchmark its end-to-end throughput with the production workload. @@ -68,6 +71,8 @@ After a recipe meets the quality target, benchmark its end-to-end throughput wit | `v_block_size` | int ≥ 0 | `0` | V block size on the hidden dimension. `0` = one tensor-wide V scale; `1` = one scale per channel. Keep `0` if `v_dtype` defines its own scaling format (e.g., `mxfp8` or `nvfp4`) | | `smooth_k` | bool | `False` | SageAttention only. Subtract the per-channel K mean before quantizing K. | | `smooth_v` | bool | `False` | SageAttention only. Subtract the per-channel V mean before quantizing V and add it back to the output. Applied where attention runs on the PrimTS kernels; see [SageAttention in the `TRTLLM` backend](#sageattention-in-the-trtllm-backend). | +| `vc_attention` | bool | `false` | Run the recipe as VC-Attention on the `TRTLLM` backend. See [VC-Attention in the `TRTLLM` backend](#vc-attention-in-the-trtllm-backend). | +| `vc_repair_budget` | float in `[0, 1)` | `0.0` | Fraction of tokens VC-Attention appends as V repair rows instead of restoring tile means. `0` restores the means. `vc_attention` only. | Routing (`tensorrt_llm/_torch/visual_gen/attention/backends/utils.py`) forwards the validated `quant_attention_config` into the backend constructor: `TrtllmAttention` for `TRTLLM`, `CuDNNAttention` for `CUDNN`, `FlashInferAttention` for `FLASHINFER`, and the dense `CuTeDSLAttention` FMHA backend for `CUTEDSL`. @@ -156,6 +161,52 @@ attention_config: For Hopper SageAttention, set `q_block_size` to `2`. +## VC-Attention in the `TRTLLM` backend + +**What it does.** VC-Attention ([arXiv 2609.15810](https://arxiv.org/abs/2609.15810)) quantizes V around its tile means on the PrimTS FMHA library: + +- **V** is stored per 128-token K/V tile as a bf16 mean plus E4M3 residuals with one scale per head and channel; the kernel adds the mean back inside the softmax. A k-means permutation groups similar value rows into the same tile. +- **Q and K** stay bf16 under VC-Attention-QK16 (`qk_dtype: bf16`). Under VC-Attention-QK8 (`qk_dtype: fp8`) they are Hadamard-rotated E4M3 with one scale per 128-token block. +- **V-Smooth schedule.** Grouping and demeaning run over the first quarter of the denoising steps, regrouping every fourth step; later steps run plain per-channel E4M3 V. The pipeline publishes the step, so the window follows the sampler's step count. +- **Repair rows.** `vc_repair_budget` replaces the tile means by appending that fraction of the tokens with the largest residual as extra K/V rows. `0.005` is faster than the means at unchanged quality. + +**Requirements and behavior.** + +- B200/GB200 and B300/GB300 with `TLLM_FMHA_LIBS=+prims_ts`; other GPUs and backends reject `vc_attention`. +- Separate Q, K and V, equal head counts, head dimension 128, dense mask. Not composable with `sparse_attention_config`, `smooth_k` or `smooth_v`. +- The recipe fixes the block sizes, `(0, 0, 1)` for QK16 and `(128, 128, 1)` for QK8; the validator sets them from the defaults and rejects other values. +- With CUDA graphs the V-Smooth phase is a graph key, so regrouping, smoothing and plain steps replay separate graphs. + +**Configuration.** + +```python +from tensorrt_llm import VisualGenArgs +from tensorrt_llm.visual_gen import AttentionConfig, QuantAttentionConfig + +args = VisualGenArgs( + model="Wan-AI/Wan2.1-T2V-1.3B-Diffusers", + attention_config=AttentionConfig( + backend="TRTLLM", + quant_attention_config=QuantAttentionConfig( + qk_dtype="fp8", + v_dtype="fp8", + vc_attention=True, + vc_repair_budget=0.005, + ), + ), +) +``` + +```yaml +attention_config: + backend: TRTLLM + quant_attention_config: + qk_dtype: fp8 + v_dtype: fp8 + vc_attention: true + vc_repair_budget: 0.005 +``` + ## FP8 and MXFP8 in the cuDNN Backend **What it does.** The `CUDNN` backend uses cuDNN fused SDPA. Its quantized recipes use the same format for BMM1 and BMM2: @@ -285,5 +336,5 @@ attention_config: ## Interaction With Other Features - **Linear-layer quantization** (`VisualGenArgs.quant_config`, e.g. FP8 block scales or NVFP4) is independent and can be combined with any attention recipe. -- **Sparse attention.** On `CUTEDSL`, quantized attention and Video Sparse Attention (VSA) are mutually exclusive and rejected by the validator. On `TRTLLM`, Skip Softmax uses the same backend and the SageAttention unit tests exercise the two together. +- **Sparse attention.** On `CUTEDSL`, quantized attention and Video Sparse Attention (VSA) are mutually exclusive and rejected by the validator. On `TRTLLM`, Skip Softmax uses the same backend and the SageAttention unit tests exercise the two together. VC-Attention (`vc_attention: true`) is rejected together with any `sparse_attention_config`. - **Parallelism.** SageAttention is covered by a multi-GPU Ulysses test (`tests/unittest/_torch/visual_gen/multi_gpu/test_ulysses_sage_attention.py`). The CuTe DSL dense backend produces LSE, so it also composes with Attention2D / Ring context parallelism; the TRTLLM Sage path does not expose LSE through this wrapper. diff --git a/tensorrt_llm/_torch/attention/backends/fmha/interface.py b/tensorrt_llm/_torch/attention/backends/fmha/interface.py index ef5fb88cd156..bc36bab44d99 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/interface.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/interface.py @@ -43,6 +43,7 @@ class Fmha(ABC): supports_skip_correction: ClassVar[bool] = False supports_block_sparse_inputs: ClassVar[bool] = False supports_per_tensor_fp8: ClassVar[bool] = False + supports_vc_attention: ClassVar[bool] = False supports_workspace_reclamation: bool = False supports_fp4_mla: ClassVar[bool] = False # Serves a generation call whose QK-norm / RoPE / KV-append prologue the attention module deferred to the @@ -136,6 +137,9 @@ def is_supported( ): logger.debug(f"{type(self).__name__} does not run a deferred attention prologue.") return False + if getattr(forward_args, "vc_attention", False) and not self.supports_vc_attention: + logger.debug(f"{type(self).__name__} does not support VC-Attention.") + return False return self._is_supported(q, k, v, metadata, forward_args, phase=phase) def _is_supported( diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py index 89ee7d2a8126..e094cabdc21d 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts.py @@ -156,6 +156,7 @@ class PrimsTSFmha(PhasedFmha): """Blackwell task-scheduled paged context and decode FMHA library.""" supports_per_tensor_fp8 = True + supports_vc_attention = True SUPPORTED_SMS = frozenset({100, 103}) SUPPORTED_PAGE_SIZES = {16, 32, 64, 128} @@ -175,6 +176,7 @@ def __init__(self, attn: "TrtllmAttention") -> None: self._context_wrappers: dict[int, "BatchPrefillPagedTSWrapper"] = {} # Cache-free context plans, keyed by (batch, seq_len, q/v/out dtype, mask). self._contiguous_context_wrappers: dict[tuple[Any, ...], "BatchPrefillTSWrapper"] = {} + # VC-Attention-QK16 K/V preparation with its token permutation, one per layer. self._decode_wrappers: dict[int, "BatchDecodePagedTSWrapper"] = {} self._mla_decode_wrappers: dict[int, "BatchMLADecodePagedTSWrapper"] = {} # Dense MLA's quantization scales are fixed for this layer/model. PrimTS @@ -295,6 +297,8 @@ def _is_supported_with_reason( return False, "cache-free attention takes separate Q, K and V." elif k is not None or v is not None or (not attn.is_mla_enable and not fwd.is_fused_qkv): return False, "only fused QKV input is supported." + elif getattr(fwd, "vc_attention", False): + return False, "VC-Attention runs on cache-free context attention only." if meta.is_cross: return False, "cross attention is not supported." output = fwd.output @@ -501,6 +505,13 @@ def _is_supported_without_kv_cache( ) if fwd.v_fp8_per_tensor and not fwd.qk_fp8_per_tensor and q.dtype != torch.bfloat16: return False, f"the attention recipe keeps Q/K in BF16, got {q.dtype}." + if fwd.vc_attention: + if attn.num_heads != attn.num_kv_heads: + return False, "VC-Attention requires equal Q and K/V head counts." + if attn.head_dim != 128: + return False, "VC-Attention requires head dimension 128." + if mask_type != AttentionMaskType.padding: + return False, "VC-Attention requires a dense mask." output = fwd.output if output.dtype != q.dtype: return False, f"output dtype must match query dtype, got {output.dtype} and {q.dtype}." @@ -859,12 +870,38 @@ def _forward_without_kv_cache( q_dequant_scale.float() * k_dequant_scale.float() * (sm_scale * math.log2(math.e)) ).reshape(1) output_scale = None - if forward_args.v_fp8_per_tensor: + vc_params = None + vc_repair_tiles = 0 + vc_demean = True + if forward_args.vc_attention: + # The caller prepared the VC-Attention operands. They carry the V scale and + # tile means (and under QK8 the E4M3 Q/K with their block scales), so no + # per-tensor scale is folded here. + vc_operands = forward_args.vc_operands + if vc_operands is None: + raise RuntimeError("VC-Attention requires prepared operands in vc_operands.") + k_bshd, v_bshd, vc_params = vc_operands.k, vc_operands.v, vc_operands.params + vc_demean = vc_operands.demean + vc_repair_tiles = vc_operands.repair_tiles + if vc_operands.q is not None: + q_bshd = vc_operands.q + elif forward_args.v_fp8_per_tensor: v_bshd, v_dequant_scale = torch.ops.tensorrt_llm.quantize_e4m3_per_tensor(v_bshd) output_scale = v_dequant_scale.float().reshape(1) out = output.view(batch_size, seq_len, num_heads, head_dim) mask_type = self._get_prims_mask_type(forward_args) - key = (batch_size, seq_len, q_bshd.dtype, v_bshd.dtype, out.dtype, mask_type) + # A VC plan is compiled per demean phase and repair tile count, so the + # operands of either V-Smooth phase meet a matching plan. + key = ( + batch_size, + seq_len, + q_bshd.dtype, + v_bshd.dtype, + out.dtype, + mask_type, + vc_demean, + vc_repair_tiles, + ) wrapper = self._contiguous_context_wrappers.get(key) if wrapper is None: if torch.cuda.is_current_stream_capturing(): @@ -872,9 +909,13 @@ def _forward_without_kv_cache( from tensorrt_llm._torch.attention.backends.prims_ts.context import ( BatchPrefillTSWrapper, ) + from tensorrt_llm._torch.attention.backends.prims_ts.vc_attention import ( + VCAttentionConfig, + ) logger.info( f"PrimTS cache-free context: q/k_dtype={q_bshd.dtype} v_dtype={v_bshd.dtype} " + f"vc_attention={forward_args.vc_attention} " f"batch={batch_size} seq_len={seq_len} heads={num_heads}/{num_kv_heads} head_dim={head_dim}" ) wrapper = BatchPrefillTSWrapper() @@ -892,6 +933,9 @@ def _forward_without_kv_cache( out_dtype=out.dtype, mask_type=mask_type, sm_scale=sm_scale, + vc_config=VCAttentionConfig(demean=vc_demean, repair_tiles=vc_repair_tiles) + if vc_params is not None + else None, ) self._contiguous_context_wrappers[key] = wrapper wrapper.run( @@ -901,6 +945,7 @@ def _forward_without_kv_cache( out=out, scale_softmax_log2=scale_softmax_log2, output_scale=output_scale, + vc=vc_params, validate=False, ) diff --git a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py index 7dab70862935..b31b95cd22ef 100644 --- a/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py +++ b/tensorrt_llm/_torch/attention/backends/fmha/prims_ts_block_sparse.py @@ -233,6 +233,9 @@ class PrimsTSBlockSparseFmha(PrimsTSFmha): PLAN_CACHE_KEY = "prims_ts_block_sparse" supports_block_sparse_inputs = True + # VC-Attention is a dense recipe. The block-sparse library must not claim it, or the + # VisualGen layer would accept the recipe without the dense PrimTS library enabled. + supports_vc_attention = False def _is_supported( self, diff --git a/tensorrt_llm/_torch/attention/backends/interface.py b/tensorrt_llm/_torch/attention/backends/interface.py index 70fd1f31f81a..d940683170fc 100644 --- a/tensorrt_llm/_torch/attention/backends/interface.py +++ b/tensorrt_llm/_torch/attention/backends/interface.py @@ -14,6 +14,8 @@ from typing_extensions import Self if TYPE_CHECKING: + from ...attention.backends.prims_ts.vc_attention.quantization import \ + VCAttentionOperands from ...model_config import ModelConfig from ...modules.mamba.mamba2_metadata import Mamba2Metadata from ...pyexecutor.kv_cache.mixed_precision_staging import \ @@ -1062,6 +1064,12 @@ class AttentionForwardArgs: # E4M3 with one scale each, folded into the softmax and output scales. qk_fp8_per_tensor: bool = False v_fp8_per_tensor: bool = False + # VC-Attention recipe of the PrimTS FMHA library. The caller prepares the + # operands (K in grouped token order, V as E4M3 tile residuals with its + # scale and means, under QK8 the rotated E4M3 Q and K with their block + # scales) and the library runs the matching plan on them. + vc_attention: bool = False + vc_operands: Optional["VCAttentionOperands"] = None # Packed QKV for non-MLA attention. MLA always passes a separate query. is_fused_qkv: bool = False diff --git a/tensorrt_llm/_torch/visual_gen/attention/backends/trtllm.py b/tensorrt_llm/_torch/visual_gen/attention/backends/trtllm.py index c660168c64e6..5e26c4a0d45c 100644 --- a/tensorrt_llm/_torch/visual_gen/attention/backends/trtllm.py +++ b/tensorrt_llm/_torch/visual_gen/attention/backends/trtllm.py @@ -20,7 +20,8 @@ """ import functools -from typing import Optional, Union +import math +from typing import TYPE_CHECKING, Optional, Union import torch @@ -30,6 +31,12 @@ from tensorrt_llm.models.modeling_utils import QuantConfig from tensorrt_llm.visual_gen.args import QuantAttentionConfig +if TYPE_CHECKING: + from ....attention.backends.prims_ts.vc_attention.quantization import ( + VCAttentionOperands, + VCAttentionPreprocessor, + ) + from ....attention.backends.interface import ( AttentionForwardArgs, AttentionRuntimeFeatures, @@ -45,6 +52,77 @@ from .interface import AttentionBackend, AttentionTensorLayout, as_fused_qkv, is_fused_qkv +def vc_smooth_phase(denoise_step: Optional[tuple[int, int]]) -> Optional[int]: + """Return the V-Smooth phase of a denoising step for the CUDA graph key. + + ``VCAttentionPreprocessor.prepare`` chooses its path from the step alone, + so a graph captured at one step is only valid for steps on the same path. + 2 regroups the value tokens and demeans V, 1 keeps the last grouping and + demeans V, 0 runs the plain per-channel E4M3 V after the window. ``None`` + means no denoising step is active; CUDA Graph runners omit their phase key + part in that case. The schedule constants are the defaults the layer-owned + preprocessor runs with. + """ + if denoise_step is None: + return None + from ....attention.backends.prims_ts.vc_attention.quantization import ( + VC_PERM_REFRESH_EVERY, + VC_SMOOTH_STEP_FRACTION, + ) + + step, num_steps = denoise_step + if step >= math.ceil(VC_SMOOTH_STEP_FRACTION * num_steps): + return 0 + return 2 if step == 0 or step % VC_PERM_REFRESH_EVERY == 0 else 1 + + +def vc_denoise_step_for_phase(phase: int) -> tuple[int, int]: + """Return a representative denoising step of the schedule in ``phase``. + + Under CUDA graph capture the real step must not change what the graph + records, so the host resolved phase selects one step of that phase on a + schedule whose window holds exactly one refresh period. + """ + from ....attention.backends.prims_ts.vc_attention.quantization import ( + VC_PERM_REFRESH_EVERY, + VC_SMOOTH_STEP_FRACTION, + ) + + num_steps = math.ceil(VC_PERM_REFRESH_EVERY / VC_SMOOTH_STEP_FRACTION) + if phase == 2: + return 0, num_steps + if phase == 1: + return 1, num_steps + return num_steps - 1, num_steps + + +def prepare_vc_operands( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + *, + qk_fp8: bool, + repair_budget: float, + preprocessor: Optional["VCAttentionPreprocessor"], + denoise_step: Optional[tuple[int, int]], +) -> "VCAttentionOperands": + """Quantize ``[B, S, H, D]`` bf16 Q, K and V for one VC-Attention forward. + + With a repair budget the highest-residual tokens are appended as V repair + rows. Otherwise the layer-owned ``preprocessor`` groups the value tokens + and splits V into tile means and E4M3 residuals on the V-Smooth schedule + given by ``denoise_step``. Under QK8 ``q`` is rotated and quantized too. + """ + from ....attention.backends.prims_ts.vc_attention.quantization import vc_quantize_repair + + vc_q = q if qk_fp8 else None + if repair_budget: + return vc_quantize_repair(k, v, budget=repair_budget, q=vc_q) + if preprocessor is None: + raise ValueError("the tile-mean VC-Attention recipe needs a preprocessor") + return preprocessor.prepare(k, v, q=vc_q, denoise_step=denoise_step) + + @functools.lru_cache(maxsize=None) def _paged_context_kernel_exists( head_dim: int, dtype: torch.dtype, tokens_per_page: int, device: int @@ -298,6 +376,7 @@ class TrtllmAttention(BaseTrtllmAttention, AttentionBackend): - No KV cache operation - SageAttention per-block QKV quantization (when a quant_attention_config is provided. requires unfused QKV) - PrimTS per-tensor FP8 recipes (quant_attention_config with zero block sizes, requires unfused QKV) + - VC-Attention recipes (quant_attention_config with vc_attention, requires unfused QKV) - Separate-QKV forwarding for generic block-sparse attention and backends that reject fused QKV """ @@ -341,7 +420,27 @@ def __init__( ) self.quant_attention_config = quant_attention_config - if ( + # The tile-mean VC-Attention recipe keeps its value grouping between denoising + # steps in a preprocessor owned by this layer. + self._vc_preprocessor: Optional["VCAttentionPreprocessor"] = None + # The K/V shape the eager preprocessor currently holds a grouping for. + self._vc_shape: Optional[tuple[int, int, int]] = None + if quant_attention_config is not None and quant_attention_config.vc_attention: + if sparse_params is not None: + raise ValueError("VC-Attention does not compose with sparse attention.") + if not any(fmha.supports_vc_attention for fmha in self._fmha_manager.fmha_libs): + raise RuntimeError( + "The VC-Attention recipe needs the PrimTS FMHA library " + "(TLLM_FMHA_LIBS=+prims_ts), which is not enabled or not available on this " + "platform." + ) + if not quant_attention_config.vc_repair_budget: + from ....attention.backends.prims_ts.vc_attention.quantization import ( + VCAttentionPreprocessor, + ) + + self._vc_preprocessor = VCAttentionPreprocessor() + elif ( quant_attention_config is not None and quant_attention_config.q_block_size == 0 and not any(fmha.supports_per_tensor_fp8 for fmha in self._fmha_manager.fmha_libs) @@ -386,6 +485,55 @@ def _sparse_attn_phase(self, timestep: object) -> Optional[int]: phase = graph_phase_for_timestep(timestep, disabled_until_timestep=self.timestep_cutoff) return phase + @torch.compiler.disable + def _vc_operands( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + batch_size: int, + seq_len: int, + kv_seq_len: int, + timestep: object, + ) -> "VCAttentionOperands": + """Prepare the VC-Attention operands of this call from compact Q, K and V. + + The denoising step comes from the pipeline through the shared attention + metadata state, so the V-Smooth window is a fraction of the schedule's + steps on any scheduler. Under the CUDA graph runner the host resolved + phase stands in for the step, which capture must not record, and + selects a representative step of that phase. + """ + del timestep + quant_cfg = self.quant_attention_config + denoise_step = None + if self._vc_preprocessor is not None: + phase = resolved_extra_key("vc_smooth_phase") + if phase is not None: + denoise_step = vc_denoise_step_for_phase(phase) + else: + denoise_step = self.metadata._metadata_state.get("denoise_step") + # Eager runs keep the grouping of the current K/V shape only. Under + # the CUDA graph runner every captured shape keeps its grouping, as + # the captured graphs read those buffers by address. + shape = (batch_size, kv_seq_len, self.num_kv_heads) + if self._vc_shape is not None and shape != self._vc_shape: + from ....attention.backends.prims_ts.vc_attention.quantization import ( + VCAttentionPreprocessor, + ) + + self._vc_preprocessor = VCAttentionPreprocessor() + self._vc_shape = shape + return prepare_vc_operands( + q.view(batch_size, seq_len, self.num_heads, self.head_dim), + k.view(batch_size, kv_seq_len, self.num_kv_heads, self.head_dim), + v.view(batch_size, kv_seq_len, self.num_kv_heads, self.head_dim), + qk_fp8=quant_cfg.qk_dtype == "fp8", + repair_budget=quant_cfg.vc_repair_budget, + preprocessor=self._vc_preprocessor, + denoise_step=denoise_step, + ) + def should_use_sparse(self, sparse_attn_phase: Optional[int]) -> bool: """Return whether this layer runs its sparse path in ``sparse_attn_phase``. @@ -524,12 +672,19 @@ def forward( kv_seq_len = seq_len_kv if seq_len_kv is not None else seq_len prepared_metadata = self._prepare_metadata(batch_size, seq_len) - sage_kwargs = {} + quantization_kwargs = {} if use_separate_qkv: q, k, v = self._compact_qkv(q, k, v, batch_size, seq_len, kv_seq_len) quant_cfg = self.quant_attention_config - if quant_cfg is not None: - sage_kwargs = { + if quant_cfg is not None and quant_cfg.vc_attention: + quantization_kwargs = { + "vc_attention": True, + "vc_operands": self._vc_operands( + q, k, v, batch_size, seq_len, kv_seq_len, timestep + ), + } + elif quant_cfg is not None: + quantization_kwargs = { "sage_attn_num_elts_per_blk_q": quant_cfg.q_block_size, "sage_attn_num_elts_per_blk_k": quant_cfg.k_block_size, "sage_attn_num_elts_per_blk_v": quant_cfg.v_block_size, @@ -557,7 +712,7 @@ def forward( timestep=timestep, sparse_attn_phase=sparse_attn_phase, sparse_backend_args=sparse_backend_args, - **sage_kwargs, + **quantization_kwargs, ), ) return output.view(batch_size, seq_len, -1) diff --git a/tensorrt_llm/_torch/visual_gen/models/modeling.py b/tensorrt_llm/_torch/visual_gen/models/modeling.py index ac9cb4d8034e..3db7b751fe4f 100644 --- a/tensorrt_llm/_torch/visual_gen/models/modeling.py +++ b/tensorrt_llm/_torch/visual_gen/models/modeling.py @@ -100,6 +100,25 @@ def register_cuda_graph_extra_key_fns(self, runner: "CUDAGraphRunner") -> None: Subclasses should call ``super()`` unless they intentionally replace the shared registrations. """ + quant_config = self.model_config.attention.quant_attention_config + if ( + quant_config is not None + and quant_config.vc_attention + and not quant_config.vc_repair_budget + ): + from tensorrt_llm._torch.visual_gen.attention.backends.trtllm import vc_smooth_phase + + # The tile-mean VC-Attention recipe switches its V-Smooth path by + # denoising step while the tensor shapes stay the same, so each phase + # replays its own graph. The pipeline publishes the step into this + # component's attention metadata state. The repair recipe does not + # follow the schedule. + state = self.model_config.attention_metadata_state or {} + runner.register_extra_key_fn( + "vc_smooth_phase", + lambda *args, **kwargs: vc_smooth_phase(state.get("denoise_step")), + ) + sparse_config = self.model_config.attention.sparse_attention_config if not isinstance(sparse_config, BaseSparseAttentionConfig): return diff --git a/tensorrt_llm/_torch/visual_gen/pipeline.py b/tensorrt_llm/_torch/visual_gen/pipeline.py index 91379a2f0fd6..5e7ea3635c16 100644 --- a/tensorrt_llm/_torch/visual_gen/pipeline.py +++ b/tensorrt_llm/_torch/visual_gen/pipeline.py @@ -189,10 +189,31 @@ def _profile_denoise_steps(self, timesteps: Iterable[Any]) -> Iterator[Tuple[int for i, t in self._profile_denoise_steps(timesteps): ... + + It also publishes each step as ``(step, num_steps)`` under + ``denoise_step`` in every transformer component's attention metadata + state, for the attention recipes that follow the step schedule, and + clears it when the loop ends. """ - if self._is_warmup: - return enumerate(timesteps) - return self._profiler.steps(timesteps) + steps = enumerate(timesteps) if self._is_warmup else self._profiler.steps(timesteps) + num_steps = len(timesteps) if hasattr(timesteps, "__len__") else None + try: + for i, t in steps: + self._publish_denoise_step(None if num_steps is None else (i, num_steps)) + yield i, t + finally: + self._publish_denoise_step(None) + + def _publish_denoise_step(self, denoise_step: Optional[Tuple[int, int]]) -> None: + """Record the current denoising step in each transformer component's attention state.""" + # Partially built pipelines, as the unit tests construct them, may not resolve + # their component list yet; they have no attention state to publish into. + for name in getattr(self, "transformer_components", None) or (): + model = getattr(self, name, None) + model_config = getattr(model, "model_config", None) + state = getattr(model_config, "attention_metadata_state", None) + if state is not None: + state["denoise_step"] = denoise_step def _get_or_create_cuda_graph_shared_pool(self) -> SharedGraphPool: """Return the pipeline-owned pool shared by non-concurrent graph runners.""" diff --git a/tensorrt_llm/schemas/trtllm-serve-visual-gen-config.schema.json b/tensorrt_llm/schemas/trtllm-serve-visual-gen-config.schema.json index 869e4931237c..6d6619608698 100644 --- a/tensorrt_llm/schemas/trtllm-serve-visual-gen-config.schema.json +++ b/tensorrt_llm/schemas/trtllm-serve-visual-gen-config.schema.json @@ -544,6 +544,22 @@ "status": "prototype", "title": "V Dtype", "type": "string" + }, + "vc_attention": { + "default": false, + "description": "Run the recipe as VC-Attention on the TRTLLM backend. V is stored as E4M3 residuals around 128-token tile means with one scale per channel; fp8 Q/K are Hadamard-rotated with one scale per 128 tokens. Requires TLLM_FMHA_LIBS=+prims_ts.", + "status": "prototype", + "title": "Vc Attention", + "type": "boolean" + }, + "vc_repair_budget": { + "default": 0.0, + "description": "Fraction of tokens VC-Attention appends as V repair rows instead of restoring tile means; 0 restores the means. 0.005 to 0.02 are the useful range, 0.005 is the fastest setting measured at unchanged quality. vc_attention only.", + "exclusiveMaximum": 1.0, + "minimum": 0.0, + "status": "prototype", + "title": "Vc Repair Budget", + "type": "number" } }, "title": "QuantAttentionConfig", diff --git a/tensorrt_llm/visual_gen/args.py b/tensorrt_llm/visual_gen/args.py index d829f1647563..b6d109648db1 100644 --- a/tensorrt_llm/visual_gen/args.py +++ b/tensorrt_llm/visual_gen/args.py @@ -112,6 +112,26 @@ class QuantAttentionConfig(StrictBaseModel): "the trtllm-gen kernels quantize V without it." ), ) + vc_attention: bool = Field( + False, + status="prototype", + description=( + "Run the recipe as VC-Attention on the TRTLLM backend. V is stored as E4M3 residuals " + "around 128-token tile means with one scale per channel; fp8 Q/K are Hadamard-rotated " + "with one scale per 128 tokens. Requires TLLM_FMHA_LIBS=+prims_ts." + ), + ) + vc_repair_budget: float = Field( + 0.0, + ge=0.0, + lt=1.0, + status="prototype", + description=( + "Fraction of tokens VC-Attention appends as V repair rows instead of restoring " + "tile means; 0 restores the means. 0.005 to 0.02 are the useful range, 0.005 is the " + "fastest setting measured at unchanged quality. vc_attention only." + ), + ) # Discriminated union of sparse attention configs. @@ -180,6 +200,20 @@ def _validate_quant_attention_config(self) -> "AttentionConfig": ("fp8", "fp8", (0, 0, 0)), }, } + # VC-Attention stores V as E4M3 residuals around tile means with one scale per channel. + # VC-Attention-QK16 keeps Q/K in BF16, VC-Attention-QK8 quantizes the Hadamard-rotated + # Q/K to E4M3 with one scale per 128 tokens. The recipe fixes these block sizes, so the + # config names only the element formats. + VC_ATTENTION_RECIPES = { + 100: { + ("bf16", "fp8"), + ("fp8", "fp8"), + }, + 103: { + ("bf16", "fp8"), + ("fp8", "fp8"), + }, + } # Other recipes verify the hardware at corresponding backend implementations. CUDNN_RECIPES = { ("fp8", "fp8", (0, 0, 0)), @@ -203,30 +237,55 @@ def _validate_quant_attention_config(self) -> "AttentionConfig": return self q_config = self.quant_attention_config - recipe = ( - q_config.qk_dtype, - q_config.v_dtype, - (q_config.q_block_size, q_config.k_block_size, q_config.v_block_size), - ) + block_sizes = (q_config.q_block_size, q_config.k_block_size, q_config.v_block_size) + recipe = (q_config.qk_dtype, q_config.v_dtype, block_sizes) if self.backend == "TRTLLM": sm_version = get_sm_version() - recipes = SAGE_RECIPES.get(sm_version, set()) | PRIMSTS_RECIPES.get(sm_version, set()) + if q_config.vc_attention: + # The recipe fixes its scaling granularity. QK16 keeps bf16 Q/K with one V + # scale per channel, QK8 scales Q and K per 128-token block. The block size + # fields take the defaults or exactly those values and are set to them. + vc_block_sizes = (0, 0, 1) if q_config.qk_dtype == "bf16" else (128, 128, 1) + if block_sizes not in ((0, 0, 0), vc_block_sizes): + raise ValueError( + f"VC-Attention with qk_dtype={q_config.qk_dtype!r} fixes the block sizes " + f"to {vc_block_sizes!r}. Leave them at 0, got {block_sizes!r}." + ) + q_config.q_block_size, q_config.k_block_size, q_config.v_block_size = vc_block_sizes + recipe = (q_config.qk_dtype, q_config.v_dtype) + recipes = VC_ATTENTION_RECIPES.get(sm_version, set()) + family = "VC-Attention" + else: + recipes = SAGE_RECIPES.get(sm_version, set()) | PRIMSTS_RECIPES.get( + sm_version, set() + ) + family = "SAGE and PrimTS" if recipe not in recipes: raise ValueError( f"Unsupported quant_attention_config={self.quant_attention_config!r} " - f"for backend='TRTLLM'. Supported SAGE and PrimTS recipes on this device: " + f"for backend='TRTLLM'. Supported {family} recipes on this device: " f"{sorted(recipes)}." ) - if (q_config.smooth_k or q_config.smooth_v) and q_config.q_block_size == 0: + if (q_config.smooth_k or q_config.smooth_v) and ( + q_config.q_block_size == 0 or q_config.vc_attention + ): raise ValueError( "smooth_k and smooth_v are SageAttention options and do not apply to the " - f"per-tensor recipe {recipe!r}." + f"recipe {recipe!r}." ) if q_config.smooth_v and sm_version not in (100, 103): raise ValueError( "smooth_v needs the PrimTS kernels, which add the V mean back to the " f"attention output and run on SM100 and SM103 only; got SM{sm_version}." ) + if q_config.vc_repair_budget and not q_config.vc_attention: + raise ValueError( + "vc_repair_budget is a VC-Attention option and requires vc_attention=True." + ) + elif q_config.vc_attention or q_config.vc_repair_budget: + raise ValueError( + f"vc_attention is a TRTLLM backend option, got backend='{self.backend}'." + ) elif q_config.smooth_k or q_config.smooth_v: raise ValueError( f"smooth_k and smooth_v are SageAttention options and require backend='TRTLLM', " @@ -299,6 +358,10 @@ def _validate_quant_sparse_mutex(self) -> "AttentionConfig": # The other backends never consume quant_attention_config on that path, # so accepting a recipe there would silently ignore user configuration. # SkipSoftmax is part of the dense path itself and can compose. + # VC-Attention is a dense recipe of the PrimTS kernels and is not + # composed with any sparse algorithm. + if self.quant_attention_config.vc_attention: + raise ValueError("vc_attention does not compose with sparse_attention_config.") if self.backend == "TRTLLM": return self algorithm = self.sparse_attention_config.algorithm diff --git a/tests/integration/test_lists/test-db/l0_cpu.yml b/tests/integration/test_lists/test-db/l0_cpu.yml index 31ba50c6488d..9d1f84296241 100644 --- a/tests/integration/test_lists/test-db/l0_cpu.yml +++ b/tests/integration/test_lists/test-db/l0_cpu.yml @@ -198,6 +198,7 @@ l0_cpu: - unittest/_torch/visual_gen/test_utils.py - unittest/_torch/visual_gen/test_vanilla_key_padding_mask.py - unittest/_torch/visual_gen/test_visual_gen_args.py + - unittest/_torch/visual_gen/test_vc_smooth_schedule.py - unittest/_torch/visual_gen/test_visual_gen_params.py - unittest/_torch/visual_gen/test_visual_gen_utils.py - unittest/_torch/visual_gen/test_wan_i2v_reference_conditioning.py diff --git a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py index d0e61dfb5e54..293eef37c6a8 100644 --- a/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py +++ b/tests/unittest/_torch/attention/test_prims_ts_attention_backend.py @@ -1283,8 +1283,12 @@ def test_prims_ts_decode_wrappers_share_workspace_across_serialized_layers() -> torch.testing.assert_close(actual, reference, atol=3e-2, rtol=3e-3) -def _forward_with_recipe(monkeypatch: pytest.MonkeyPatch, recipe) -> None: - """Make the shared harness send separate Q/K/V with the per-tensor recipe flags.""" +def _forward_with_recipe(monkeypatch: pytest.MonkeyPatch, recipe, vc_operands=None) -> None: + """Make the shared harness send separate Q/K/V with the recipe flags. + + The VisualGen attention layer prepares the VC-Attention operands before the + attention op, so a VC recipe passes them in here. + """ import backend_case from tensorrt_llm._torch.attention.backends.interface import AttentionForwardArgs @@ -1296,12 +1300,35 @@ def _forward_with_recipe(monkeypatch: pytest.MonkeyPatch, recipe) -> None: "AttentionForwardArgs", functools.partial( AttentionForwardArgs, - qk_fp8_per_tensor=recipe.qk_dtype == "fp8", - v_fp8_per_tensor=recipe.v_dtype == "fp8", + qk_fp8_per_tensor=not recipe.vc_attention and recipe.qk_dtype == "fp8", + v_fp8_per_tensor=not recipe.vc_attention and recipe.v_dtype == "fp8", + vc_attention=recipe.vc_attention, + vc_operands=vc_operands, ), ) +def _vc_operands(case: BackendCase, inputs: dict, recipe, denoise_step: tuple[int, int]): + """Prepare the VC operands the way the VisualGen TRTLLM attention layer does.""" + from tensorrt_llm._torch.attention.backends.prims_ts.vc_attention.quantization import ( + VCAttentionPreprocessor, + ) + from tensorrt_llm._torch.visual_gen.attention.backends.trtllm import prepare_vc_operands + + def bshd(x: torch.Tensor) -> torch.Tensor: + return x.view(case.num_seqs, -1, case.num_heads, case.head_dim) + + return prepare_vc_operands( + bshd(inputs["q"]), + bshd(inputs["new_k"]), + bshd(inputs["new_v"]), + qk_fp8=recipe.qk_dtype == "fp8", + repair_budget=recipe.vc_repair_budget, + preprocessor=None if recipe.vc_repair_budget else VCAttentionPreprocessor(), + denoise_step=denoise_step, + ) + + _CACHE_FREE_CASE = dict( num_heads=8, num_kv_heads=8, @@ -1316,21 +1343,46 @@ def _forward_with_recipe(monkeypatch: pytest.MonkeyPatch, recipe) -> None: @pytest.mark.parametrize("outlier", [1.0, 10.0]) -@pytest.mark.parametrize(("qk_dtype", "v_dtype"), [("bf16", "fp8"), ("fp8", "fp8")]) +@pytest.mark.parametrize( + ("qk_dtype", "v_dtype", "vc_attention", "vc_repair_budget", "vc_smooth", "seq_len"), + [ + ("bf16", "fp8", False, 0.0, True, 256), + ("fp8", "fp8", False, 0.0, True, 256), + ("bf16", "fp8", True, 0.0, True, 256), + ("bf16", "fp8", True, 0.0, False, 200), + ("bf16", "fp8", True, 0.01, True, 200), + ("fp8", "fp8", True, 0.0, True, 200), + ("fp8", "fp8", True, 0.0, False, 256), + ("fp8", "fp8", True, 0.01, True, 256), + ], +) def test_prims_ts_cache_free_fp8_recipes( - monkeypatch: pytest.MonkeyPatch, qk_dtype: str, v_dtype: str, outlier: float + monkeypatch: pytest.MonkeyPatch, + qk_dtype: str, + v_dtype: str, + vc_attention: bool, + vc_repair_budget: float, + vc_smooth: bool, + seq_len: int, + outlier: float, ) -> None: """Cache-free recipes plan FP8 operands, fold the per-tensor scales, and match SDPA. ``outlier`` multiplies the second sample's Q and V and divides its K, so the two samples differ in magnitude and set different per-tensor scales while their QK - logits are unchanged. Each sample is checked against SDPA. + logits are unchanged. Each sample is checked against SDPA. The VC rows cover both + V-Smooth phases, inside the window with tile means and after it on the plain + demean-off plan, and a length that is not a multiple of the 128-token tile. """ from tensorrt_llm._torch.attention.backends.prims_ts.context import BatchPrefillTSWrapper from tensorrt_llm.visual_gen.args import QuantAttentionConfig - recipe = QuantAttentionConfig(qk_dtype=qk_dtype, v_dtype=v_dtype) - _forward_with_recipe(monkeypatch, recipe) + recipe = QuantAttentionConfig( + qk_dtype=qk_dtype, + v_dtype=v_dtype, + vc_attention=vc_attention, + vc_repair_budget=vc_repair_budget, + ) plans: list[dict] = [] runs: list[dict] = [] plan, run = BatchPrefillTSWrapper.plan, BatchPrefillTSWrapper.run @@ -1346,12 +1398,19 @@ def recording_run(self, *args, **kwargs): monkeypatch.setattr(BatchPrefillTSWrapper, "plan", recording_plan) monkeypatch.setattr(BatchPrefillTSWrapper, "run", recording_run) monkeypatch.setenv("TLLM_FMHA_LIBS", "+prims_ts") - case = BackendCase(**_CACHE_FREE_CASE) + case = BackendCase(**{**_CACHE_FREE_CASE, "seq_lens": [seq_len, seq_len]}) inputs = generate_inputs(case, seed=0) second = slice(case.seq_lens[0], None) inputs["q"][second] *= outlier inputs["new_k"][second] /= outlier inputs["new_v"][second] *= outlier + # Step 0 of 50 lies inside the V-Smooth window, step 40 after it. + denoise_step = (0, 50) if vc_smooth else (40, 50) + _forward_with_recipe( + monkeypatch, + recipe, + _vc_operands(case, inputs, recipe, denoise_step) if vc_attention else None, + ) out = run_backend(case, "TRTLLM", inputs, kv_dtype=torch.bfloat16, kv_layout="HND") @@ -1376,19 +1435,31 @@ def bhsd(x: torch.Tensor) -> torch.Tensor: def dequant_scale(x: torch.Tensor) -> torch.Tensor: return (x.float().abs().amax() / 448.0).reshape(1) - # The quantize op returns BF16-rounded dequant scales. - torch.testing.assert_close( - run_kwargs["output_scale"], dequant_scale(inputs["new_v"]), rtol=1e-2, atol=0.0 - ) - if qk_dtype == "fp8": - expected = ( - dequant_scale(inputs["q"]) - * dequant_scale(inputs["new_k"]) - * (math.log2(math.e) / math.sqrt(case.head_dim)) - ) - torch.testing.assert_close(run_kwargs["scale_softmax_log2"], expected, rtol=1e-2, atol=0.0) - else: + if vc_attention: + # The VC operands carry the V scale and tile means (and the Q/K block scales under + # QK8); no per-tensor scale is folded. + assert run_kwargs["vc"] is not None + assert (run_kwargs["vc"].q_scale is not None) == (qk_dtype == "fp8") + assert (plan_kwargs["vc_config"].repair_tiles > 0) == (vc_repair_budget > 0) + assert plan_kwargs["vc_config"].demean == (vc_smooth and not vc_repair_budget) + assert run_kwargs["output_scale"] is None assert run_kwargs["scale_softmax_log2"] is None + else: + # The quantize op returns BF16-rounded dequant scales. + torch.testing.assert_close( + run_kwargs["output_scale"], dequant_scale(inputs["new_v"]), rtol=1e-2, atol=0.0 + ) + if qk_dtype == "fp8": + expected = ( + dequant_scale(inputs["q"]) + * dequant_scale(inputs["new_k"]) + * (math.log2(math.e) / math.sqrt(case.head_dim)) + ) + torch.testing.assert_close( + run_kwargs["scale_softmax_log2"], expected, rtol=1e-2, atol=0.0 + ) + else: + assert run_kwargs["scale_softmax_log2"] is None # The second sample's output is ``outlier`` times larger. Normalize it before comparing. sample_gain = torch.tensor([1.0, outlier], device=out.device).view(-1, 1) torch.testing.assert_close( @@ -1414,6 +1485,25 @@ def test_prims_ts_recipe_requires_prims_ts_library(monkeypatch: pytest.MonkeyPat ) +def test_prims_ts_rejects_vc_attention_with_kv_cache() -> None: + """The VC recipe is prepared on the cache-free path only, so paged requests must not claim it.""" + from tensorrt_llm._torch.attention.backends.fmha.prims_ts import PrimsTSFmha + + fmha = object.__new__(PrimsTSFmha) + q = torch.empty(4, 128, device="cuda", dtype=torch.bfloat16) + supported, reason = fmha._is_supported_with_reason( + q, + None, + None, + SimpleNamespace(is_mla_enable=False), + SimpleNamespace(kv_cache_manager=object()), + SimpleNamespace(is_fused_qkv=True, vc_attention=True, sparse_runtime_params=None), + ) + + assert not supported + assert reason == "VC-Attention runs on cache-free context attention only." + + def test_prims_ts_unsupported_context_falls_back(monkeypatch: pytest.MonkeyPatch) -> None: from tensorrt_llm._torch.attention.backends.fmha.fallback import FallbackFmha from tensorrt_llm._torch.attention.backends.fmha.prims_ts import PrimsTSFmha diff --git a/tests/unittest/_torch/visual_gen/test_trtllm_attention_metadata.py b/tests/unittest/_torch/visual_gen/test_trtllm_attention_metadata.py index a8dad92f8c06..a980339b0da3 100644 --- a/tests/unittest/_torch/visual_gen/test_trtllm_attention_metadata.py +++ b/tests/unittest/_torch/visual_gen/test_trtllm_attention_metadata.py @@ -376,3 +376,35 @@ def forward() -> torch.Tensor: torch.cuda.synchronize() torch.testing.assert_close(captured, eager) + + +def test_vc_attention_eager_runs_keep_only_the_current_shape(monkeypatch) -> None: + """Without the CUDA graph runner the layer drops the value grouping of a previous + K/V shape; under the runner every captured shape keeps its grouping.""" + from tensorrt_llm.visual_gen.args import QuantAttentionConfig + + monkeypatch.setenv("TLLM_FMHA_LIBS", "+prims_ts") + attention = visual_trtllm.TrtllmAttention( + layer_idx=0, + num_heads=2, + head_dim=128, + dtype=torch.bfloat16, + attention_metadata_state=create_attention_metadata_state(), + quant_attention_config=QuantAttentionConfig(qk_dtype="bf16", vc_attention=True), + ) + + def operands(seq_len: int) -> None: + x = torch.randn(seq_len, 2 * 128, device="cuda", dtype=torch.bfloat16) + attention._vc_operands(x, x, x, 1, seq_len, seq_len, None) + + first = attention._vc_preprocessor + operands(256) + operands(256) + assert attention._vc_preprocessor is first + operands(384) + second = attention._vc_preprocessor + assert second is not first + with resolved_extra_keys_scope({"vc_smooth_phase": 2}): + operands(512) + operands(256) + assert attention._vc_preprocessor is second diff --git a/tests/unittest/_torch/visual_gen/test_vc_smooth_schedule.py b/tests/unittest/_torch/visual_gen/test_vc_smooth_schedule.py new file mode 100644 index 000000000000..85dfccd211a3 --- /dev/null +++ b/tests/unittest/_torch/visual_gen/test_vc_smooth_schedule.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The V-Smooth schedule of VC-Attention, the step the pipeline publishes and the CUDA graph key.""" + +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +import torch + +from tensorrt_llm._torch.visual_gen.attention.backends.trtllm import ( + vc_denoise_step_for_phase, + vc_smooth_phase, +) +from tensorrt_llm._torch.visual_gen.config import DiffusionModelConfig +from tensorrt_llm._torch.visual_gen.cuda_graph_runner import CUDAGraphRunner, CUDAGraphRunnerConfig +from tensorrt_llm._torch.visual_gen.models.modeling import BaseDiffusionModel +from tensorrt_llm._torch.visual_gen.pipeline import BasePipeline +from tensorrt_llm.visual_gen.args import AttentionConfig, QuantAttentionConfig + +pytestmark = pytest.mark.cpu_only + + +def test_smooth_phase_follows_the_schedule(): + """The first quarter of the steps smooths V and regroups every fourth step; the rest is plain. + The representative step of each phase under CUDA graph capture lands in that phase.""" + schedule = { + None: None, + (0, 50): 2, + (1, 50): 1, + (4, 50): 2, + (12, 50): 2, + (13, 50): 0, + (49, 50): 0, + } + assert [vc_smooth_phase(step) for step in schedule] == list(schedule.values()) + assert [vc_smooth_phase(vc_denoise_step_for_phase(phase)) for phase in (0, 1, 2)] == [0, 1, 2] + + +def test_profile_denoise_steps_publishes_and_clears_the_step(): + """Every transformer component sees ``(step, num_steps)`` during a step and ``None`` after + the loop, whether it ends normally or by an exception.""" + pipeline = object.__new__(BasePipeline) + pipeline._is_warmup = True + state = {"metadata_cache": {}} + pipeline.transformer = SimpleNamespace( + model_config=SimpleNamespace(attention_metadata_state=state) + ) + seen = [(i, t, state["denoise_step"]) for i, t in pipeline._profile_denoise_steps([0.9, 0.5])] + assert seen == [(0, 0.9, (0, 2)), (1, 0.5, (1, 2))] + assert state["denoise_step"] is None + with pytest.raises(RuntimeError, match="step failed"): + for _ in pipeline._profile_denoise_steps([0.9, 0.5]): + assert state["denoise_step"] == (0, 2) + raise RuntimeError("step failed") + assert state["denoise_step"] is None + + +def _model(vc_attention: bool, vc_repair_budget: float = 0.0) -> tuple[BaseDiffusionModel, dict]: + model = object.__new__(BaseDiffusionModel) + torch.nn.Module.__init__(model) + # The attention config validates the recipe against the GPU, so build the whole + # model config under the patch for the CPU-only test workers. + with patch("tensorrt_llm.visual_gen.args.get_sm_version", return_value=100): + model.model_config = DiffusionModelConfig( + attention=AttentionConfig( + backend="TRTLLM", + quant_attention_config=QuantAttentionConfig( + qk_dtype="bf16", vc_attention=vc_attention, vc_repair_budget=vc_repair_budget + ), + ), + attention_metadata_state={"metadata_cache": {}}, + ) + return model, model.model_config.attention_metadata_state + + +def test_graph_key_follows_the_published_step(): + """The tile-mean recipe keys its graphs on the published step's phase; the SageAttention + and repair recipes, which do not follow the schedule, register no key.""" + runner = CUDAGraphRunner(CUDAGraphRunnerConfig(use_cuda_graph=True)) + model, state = _model(vc_attention=True) + model.register_cuda_graph_extra_key_fns(runner) + x = torch.empty(1, 2) + keys = {} + for step in ((0, 8), (1, 8), (4, 8), None): + state["denoise_step"] = step + keys[step] = runner.get_graph_key(x) + assert ("vc_smooth_phase", 2) in keys[(0, 8)] + assert ("vc_smooth_phase", 1) in keys[(1, 8)] + assert ("vc_smooth_phase", 0) in keys[(4, 8)] + assert keys[None] == runner._get_tensor_shape_key(x) + assert len(set(keys.values())) == 4 + for vc_attention, vc_repair_budget in ((False, 0.0), (True, 0.005)): + runner = CUDAGraphRunner(CUDAGraphRunnerConfig(use_cuda_graph=True)) + model, _ = _model(vc_attention, vc_repair_budget) + model.register_cuda_graph_extra_key_fns(runner) + assert "vc_smooth_phase" not in runner._extra_key_fns diff --git a/tests/unittest/_torch/visual_gen/test_visual_gen_args.py b/tests/unittest/_torch/visual_gen/test_visual_gen_args.py index 39c742234b9b..e51807147562 100644 --- a/tests/unittest/_torch/visual_gen/test_visual_gen_args.py +++ b/tests/unittest/_torch/visual_gen/test_visual_gen_args.py @@ -178,6 +178,135 @@ def test_supported_quant_config_trtllm( assert attention.quant_attention_config is not None + @pytest.mark.parametrize("sm_ver", [100, 103]) + @pytest.mark.parametrize("qk_dtype", ["bf16", "fp8"]) + @pytest.mark.parametrize("vc_repair_budget", [0.0, 0.005]) + def test_supported_quant_config_vc_attention(self, sm_ver, qk_dtype, vc_repair_budget): + """VC-Attention-QK16 and VC-Attention-QK8 validate on Blackwell, with tile means or repair rows.""" + with patch("tensorrt_llm.visual_gen.args.get_sm_version", return_value=sm_ver): + attention = AttentionConfig( + backend="TRTLLM", + quant_attention_config=QuantAttentionConfig( + qk_dtype=qk_dtype, vc_attention=True, vc_repair_budget=vc_repair_budget + ), + ) + + assert attention.quant_attention_config.vc_attention + assert attention.quant_attention_config.vc_repair_budget == vc_repair_budget + q_config = attention.quant_attention_config + assert (q_config.q_block_size, q_config.k_block_size, q_config.v_block_size) == ( + (0, 0, 1) if qk_dtype == "bf16" else (128, 128, 1) + ) + + @pytest.mark.parametrize( + ("backend", "sm_ver", "quant", "sparse", "match"), + [ + ( + "TRTLLM", + 100, + dict(qk_dtype="fp8", q_block_size=1, k_block_size=16, v_block_size=1), + None, + "fixes the block sizes", + ), + ( + "TRTLLM", + 100, + dict(qk_dtype="bf16", vc_attention=False, vc_repair_budget=0.005), + None, + "vc_repair_budget is a VC-Attention", + ), + ("TRTLLM", 100, dict(qk_dtype="bf16", vc_repair_budget=-0.1), None, "vc_repair_budget"), + ("TRTLLM", 100, dict(qk_dtype="bf16", vc_repair_budget=1.0), None, "vc_repair_budget"), + ( + "TRTLLM", + 100, + dict(qk_dtype="bf16", smooth_k=True), + None, + "are SageAttention options", + ), + ( + "TRTLLM", + 100, + dict(qk_dtype="bf16", smooth_v=True), + None, + "are SageAttention options", + ), + ("TRTLLM", 90, dict(qk_dtype="bf16"), None, "Supported VC-Attention recipes"), + ("TRTLLM", 120, dict(qk_dtype="bf16"), None, "Supported VC-Attention recipes"), + ( + "TRTLLM", + 100, + dict(qk_dtype="bf16"), + VideoSparseAttentionConfig(vsa_sparsity=0.9), + "does not compose with sparse_attention", + ), + ( + "TRTLLM", + 100, + dict(qk_dtype="bf16"), + SkipSoftmaxAttentionConfig(threshold_scale_factor=0.3), + "does not compose with sparse_attention", + ), + ( + "CUTEDSL", + 100, + dict(qk_dtype="bf16"), + None, + "vc_attention is a TRTLLM backend option", + ), + ("CUDNN", 100, dict(qk_dtype="bf16"), None, "vc_attention is a TRTLLM backend option"), + ( + "FLASHINFER", + 100, + dict(qk_dtype="bf16"), + None, + "vc_attention is a TRTLLM backend option", + ), + ( + "VANILLA", + 100, + dict(qk_dtype="bf16"), + None, + "vc_attention is a TRTLLM backend option", + ), + ( + "VANILLA", + 100, + dict(qk_dtype="bf16", vc_attention=False, vc_repair_budget=0.005), + None, + "vc_attention is a TRTLLM backend option", + ), + ], + ids=[ + "block_sizes", + "repair_without_vc", + "budget_below_zero", + "budget_at_one", + "smooth_k", + "smooth_v", + "sm90", + "sm120", + "vsa", + "skip_softmax", + "cutedsl", + "cudnn", + "flashinfer", + "vanilla", + "vanilla_repair", + ], + ) + def test_vc_attention_rejections(self, backend, sm_ver, quant, sparse, match): + """VC-Attention fixes its block sizes, owns the repair budget, is TRTLLM and Blackwell only, + and never composes with SageAttention smoothing or a sparse algorithm.""" + quant = {"vc_attention": True, **quant} + with patch("tensorrt_llm.visual_gen.args.get_sm_version", return_value=sm_ver): + with pytest.raises(ValidationError, match=match): + AttentionConfig( + backend=backend, + quant_attention_config=QuantAttentionConfig(**quant), + sparse_attention_config=sparse, + ) + @pytest.mark.parametrize("smoothing", ["smooth_k", "smooth_v"]) @pytest.mark.parametrize("backend", ["TRTLLM", "CUTEDSL", "CUDNN", "FLASHINFER", "VANILLA"]) def test_smoothing_rejected_without_sage_recipe(self, backend, smoothing): From 5b5c3a29b4544107752ba94e79daebc927f7f5c6 Mon Sep 17 00:00:00 2001 From: Harrison Zhang Date: Thu, 29 Oct 2026 14:37:48 -0700 Subject: [PATCH 2/2] [primsTS][fmha] sync the vendored VC-Attention prims_ts to flashinfer 7087b06c2 Pins flashinfer-prims-ts to the fork lineage branch harrisonzhy/trtllm-prims-ts-dev_vc-attn-20261029: the canonical trtllm-prims-ts-dev-20261012 tip aa709061 plus the VC-Attention commits of flashinfer PRs 6296 (QK16), 6306 (QK8) and 6721 (fused preparation), cherry-picked. The vendored tree is a byte copy of the fork plus the compatibility patch, regenerated at the new revision with unchanged content. Signed-off-by: Harrison Zhang --- .../vendor_patches/flashinfer-prims-ts.patch | 36 +- 3rdparty/vendor_sources.lock.yaml | 10 +- .../attention/backends/prims_ts/__init__.py | 10 + .../attention/backends/prims_ts/context.py | 249 ++- .../kernels/fmha_context/fmha_kernel.py | 156 +- .../kernels/fmha_context/fmha_resources.py | 783 ++++++++- .../kernels/fmha_context/fmha_tasks.py | 417 ++++- .../prims_ts/kernels/fmha_context/helpers.py | 81 +- .../fmha_context/vc_attention/__init__.py | 7 + .../fmha_context/vc_attention/vc_resources.py | 258 +++ .../fmha_context/vc_attention/vc_scales.py | 129 ++ .../prims_ts/vc_attention/__init__.py | 311 ++++ .../backends/prims_ts/vc_attention/prepare.py | 1498 +++++++++++++++++ .../prims_ts/vc_attention/quantization.py | 503 ++++++ 14 files changed, 4325 insertions(+), 123 deletions(-) create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/__init__.py create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_resources.py create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_scales.py create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/__init__.py create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/prepare.py create mode 100644 tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/quantization.py diff --git a/3rdparty/vendor_patches/flashinfer-prims-ts.patch b/3rdparty/vendor_patches/flashinfer-prims-ts.patch index 6cfb3f7bf8e3..a571cd3474e0 100644 --- a/3rdparty/vendor_patches/flashinfer-prims-ts.patch +++ b/3rdparty/vendor_patches/flashinfer-prims-ts.patch @@ -1,5 +1,5 @@ diff --git a/_compile_cache.py b/_compile_cache.py -index b374a65311402982d818d80e9145ab40ed9727a1..cdfa76294f2d854117db62ad36724254006f8cb8 100644 +index b374a65..cdfa762 100644 --- a/_compile_cache.py +++ b/_compile_cache.py @@ -1,3 +1,4 @@ @@ -194,7 +194,7 @@ index b374a65311402982d818d80e9145ab40ed9727a1..cdfa76294f2d854117db62ad36724254 f"prims_ts_{family}", f"{kind}_sm{major}{minor}_{key}", diff --git a/block_sparse.py b/block_sparse.py -index fa055618705216cddf6b7f3e9ed4c1d680c2af9a..38de4926a045f17c5b6f206f4a20ecbe2532a1c7 100644 +index fa05561..38de492 100644 --- a/block_sparse.py +++ b/block_sparse.py @@ -1,3 +1,4 @@ @@ -256,19 +256,19 @@ index fa055618705216cddf6b7f3e9ed4c1d680c2af9a..38de4926a045f17c5b6f206f4a20ecbe q: torch.Tensor, paged_kv_cache: PagedKVCache, diff --git a/context.py b/context.py -index d3f104e4e34b1bcb7ada697f9e76f7013d6ca100..1ec1080b942f60fad22e3e4a1627cad9592697ad 100644 +index 898859e..564760b 100644 --- a/context.py +++ b/context.py -@@ -48,7 +48,7 @@ from ._hardware import get_max_active_clusters - - import torch +@@ -56,7 +56,7 @@ from .vc_attention import ( + vc_scale_shapes, + ) -from flashinfer.api_logging import flashinfer_experimental_api +from flashinfer.api_logging import flashinfer_api as flashinfer_experimental_api if TYPE_CHECKING: -@@ -493,7 +493,7 @@ def _validate_device(device: torch.device) -> int: +@@ -505,7 +505,7 @@ def _validate_device(device: torch.device) -> int: # Rubin runs through the sm_100f family target; a CuTe DSL older than 4.8 # cannot emit for it unless CUTE_DSL_ARCH=sm_100f is set before import. if capability == (10, 7): @@ -278,7 +278,7 @@ index d3f104e4e34b1bcb7ada697f9e76f7013d6ca100..1ec1080b942f60fad22e3e4a1627cad9 require_cute_dsl_arch(device_index) return device_index diff --git a/decode.py b/decode.py -index 4fb096f39849a3801349758360e71b092ee200e9..f91814650c48dcf5b116273742880ac722fed527 100644 +index 4fb096f..f918146 100644 --- a/decode.py +++ b/decode.py @@ -1,3 +1,4 @@ @@ -327,7 +327,7 @@ index 4fb096f39849a3801349758360e71b092ee200e9..f91814650c48dcf5b116273742880ac7 q: torch.Tensor, paged_kv_cache: PagedKVCache, diff --git a/kernels/fmha_context/fmha_resources.py b/kernels/fmha_context/fmha_resources.py -index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2fe30a922 100644 +index fbd1f12..2efae0a 100644 --- a/kernels/fmha_context/fmha_resources.py +++ b/kernels/fmha_context/fmha_resources.py @@ -1,3 +1,4 @@ @@ -335,7 +335,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 # Copyright (c) 2026 by FlashInfer team. # # Licensed under the Apache License, Version 2.0 (the "License"); -@@ -1199,8 +1200,6 @@ class GmemQKVResource(MemoryResource): +@@ -1310,8 +1311,6 @@ class GmemQKVResource(MemoryResource): if cutlass.const_expr(self.cfg.has_uniform_varlen): seqlen_k = Int32(self.cfg.uniform_seq_len_k) else: @@ -344,7 +344,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 seqlen_k = _load_runtime_seq_len_kv( self.seqlens_kv, self.max_seq_len_kv, batch_coord ) -@@ -1223,8 +1222,6 @@ class GmemQKVResource(MemoryResource): +@@ -1334,8 +1333,6 @@ class GmemQKVResource(MemoryResource): kv_request_begin = batch_coord * Int32(self.block_table_row_stride) kv_page_idx_ub = Int32(self.cfg.max_num_pages_per_seq_kv - 1) else: @@ -353,7 +353,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 kv_request_begin, kv_page_idx_ub = _load_block_table_row_bounds( Int32(self.block_table_row_stride), self.cfg, -@@ -1300,13 +1297,9 @@ class GmemQKVResource(MemoryResource): +@@ -1411,13 +1408,9 @@ class GmemQKVResource(MemoryResource): kv_request_begin = batch_coord * Int32(self.block_table_row_stride) kv_page_idx_ub = Int32(self.cfg.max_num_pages_per_seq_kv - 1) else: @@ -367,7 +367,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 kv_request_begin, kv_page_idx_ub = _load_block_table_row_bounds( Int32(self.block_table_row_stride), self.cfg, -@@ -1743,8 +1736,6 @@ class SmemPageOffsetsKvResource(MemoryResource): +@@ -1854,8 +1847,6 @@ class SmemPageOffsetsKvResource(MemoryResource): kv_request_begin: Int32, kv_page_idx_ub: Int32, ) -> None: @@ -376,7 +376,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 cfg = self.cfg # Context's K/V tile index is kv_tile_start + loop_offset; for V the # producer runs one tile ahead in TAIL, so reuse the same expression -@@ -1835,8 +1826,6 @@ class SmemPageOffsetsKvResource(MemoryResource): +@@ -1946,8 +1937,6 @@ class SmemPageOffsetsKvResource(MemoryResource): tile_offset: cutlass.Constexpr[int] = 0, ) -> cutlass.Array: """Retain one tile's page IDs after its SMEM window is released.""" @@ -385,7 +385,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 tile_idx = _resolve_kv_tile_idx_context( stage_info, kv_tile_start, tile_offset=tile_offset ) -@@ -5770,3 +5759,14 @@ class GmemOResource(MemoryResource): +@@ -6541,3 +6530,14 @@ class GmemOResource(MemoryResource): prims.cp_async_bulk_commit_group() if cutlass.const_expr(self.cfg.gmem_o_store_wait_after_write): prims.cp_async_bulk_wait_group(0, read=True) @@ -401,7 +401,7 @@ index d17584b725e24235ce0ec90caac174a29d4ab965..af69ee7d51bc1179352d0bf2ba71fad2 + _resolve_kv_tile_idx_context, +) diff --git a/kernels/fmha_decode/fmha_decode_resources/tmem_transformed_kv.py b/kernels/fmha_decode/fmha_decode_resources/tmem_transformed_kv.py -index b22f0f413b7312bab9a5f8e296255fe9aeabe901..a4a87200ca5d3ace5cf899caa9672a1a32c5289e 100644 +index b22f0f4..a4a8720 100644 --- a/kernels/fmha_decode/fmha_decode_resources/tmem_transformed_kv.py +++ b/kernels/fmha_decode/fmha_decode_resources/tmem_transformed_kv.py @@ -1,3 +1,4 @@ @@ -419,7 +419,7 @@ index b22f0f413b7312bab9a5f8e296255fe9aeabe901..a4a87200ca5d3ace5cf899caa9672a1a from .helpers_common import ( _TASK_CACHE_TMEM_BASE_OFFSET, diff --git a/mla_decode.py b/mla_decode.py -index b62bd1081fbae0e18e0950008bae87c8986677b4..7a305b1ec6f2e860b3627e6d71c562e231c98a52 100644 +index b62bd10..7a305b1 100644 --- a/mla_decode.py +++ b/mla_decode.py @@ -1,3 +1,4 @@ @@ -742,7 +742,7 @@ index b62bd1081fbae0e18e0950008bae87c8986677b4..7a305b1ec6f2e860b3627e6d71c562e2 def get_prims_ts_sparse_mla_decode_workspace_size(*plan_args, **plan_kwargs): """Return workspace bytes using the same arguments as wrapper.plan(). diff --git a/q_token_kv_block_sparse_metadata.py b/q_token_kv_block_sparse_metadata.py -index e2bbef13c0f552030875e6b433e0fcdb20686cf6..17025dbc49ef997993009ddab7ff2250308f035c 100644 +index e2bbef1..17025db 100644 --- a/q_token_kv_block_sparse_metadata.py +++ b/q_token_kv_block_sparse_metadata.py @@ -1,3 +1,4 @@ diff --git a/3rdparty/vendor_sources.lock.yaml b/3rdparty/vendor_sources.lock.yaml index 02bae0bde8cf..cf63dba55aec 100644 --- a/3rdparty/vendor_sources.lock.yaml +++ b/3rdparty/vendor_sources.lock.yaml @@ -13,16 +13,16 @@ vendors: patch_digest: sha256:bc9b96a69873e0ddfcba66ab899c666cf52766976f24d850048d2a0bf8d967ff digest: sha256-tree-v1:d2d382335ccb68b55078523e63835c28b699607227afb81308cb7bb1d85845ac flashinfer-prims-ts: - url: https://github.com/yuxianq/flashinfer.git - branch: trtllm-prims-ts-dev-20261012 - commit: aa709061230a58858375c513056e7733fa74294a + url: https://github.com/harrisonzhy/flashinfer.git + branch: harrisonzhy/trtllm-prims-ts-dev_vc-attn-20261029 + commit: 7087b06c22ceb116b2236a938038a00b39f752d1 source: flashinfer/attention/prims_ts destination: tensorrt_llm/_torch/attention/backends/prims_ts include: - '**/*.py' patch: 3rdparty/vendor_patches/flashinfer-prims-ts.patch - patch_digest: sha256:5cbcaf2b60029742c55f622eadc84b32f49e574038c417972955706157715141 - digest: sha256-tree-v1:fa20dc33e52628519dba7f071f5b28a4eb7963768adb6b46eb8000e4fdb805c4 + patch_digest: sha256:b4e502ee5bf3d4b4477d42d96d6fa953f1819e82398b40d17812f6fda7165b22 + digest: sha256-tree-v1:de7e56b151091c462d22b3c578cc6703167d0a7de995807f83cd25f3f5736354 openengine-proto: url: https://github.com/ai-dynamo/openengine.git tag: v0.1.0 diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/__init__.py b/tensorrt_llm/_torch/attention/backends/prims_ts/__init__.py index 477f52de75cf..f1a20be84cbd 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/__init__.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/__init__.py @@ -50,6 +50,13 @@ q_token_kv_block_sparse_attention_with_paged_kv_cache, ) from .sage import SageAttentionConfig, SageAttentionParams +from .vc_attention import ( + VCAttentionConfig, + VCAttentionParams, +) +from .vc_attention.quantization import ( + VCAttentionPreprocessor, +) __all__ = [ "BatchSparseMLADecodePagedTSWrapper", @@ -58,6 +65,9 @@ "BlockSparseTSWrapper", "SageAttentionConfig", "SageAttentionParams", + "VCAttentionConfig", + "VCAttentionParams", + "VCAttentionPreprocessor", "BlockSparsePagedTSWrapper", "block_sparse_attention", "block_sparse_attention_with_paged_kv_cache", diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/context.py b/tensorrt_llm/_torch/attention/backends/prims_ts/context.py index 1ec1080b942f..564760b83705 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/context.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/context.py @@ -35,7 +35,7 @@ register trace templates. """ -from dataclasses import dataclass +from dataclasses import dataclass, replace import functools import itertools import math @@ -48,6 +48,14 @@ import torch +from .vc_attention import ( + VCAttentionConfig, + VCAttentionParams, + validate_vc_params, + vc_repair_kv_len, + vc_scale_shapes, +) + from flashinfer.api_logging import flashinfer_api as flashinfer_experimental_api @@ -142,6 +150,8 @@ class _ContextPlanGeometry: causal_single_kv_tile: bool packed_dense_k_mask: bool head_dim_vo: int | None = None + # VC-Attention recipe, or ``None`` for a plain plan. + vc: Optional[VCAttentionConfig] = None @dataclass(frozen=True) @@ -156,6 +166,9 @@ class _ContextPlanState: variable_window_cta_starts: torch.Tensor compiled: Callable[..., None] policy: tuple[tuple[str, object], ...] + vc_scale_shapes: Optional[dict[str, tuple[int, ...]]] = None + # Output scale of VC runs: the per-channel V scale times the planned or passed scale. + vc_output_scale: Optional[torch.Tensor] = None @dataclass(frozen=True) @@ -234,6 +247,7 @@ class _ContextCompileSpec: scheduler: _ContextScheduler head_dim_vo: int | None = None two_cta_umma: bool = False + vc: Optional[VCAttentionConfig] = None @dataclass(frozen=True) @@ -281,6 +295,7 @@ def _make_context_kernel( two_cta_umma: bool = False, page_size: int | None = None, max_kv_len: int | None = None, + vc_attention: str | None = None, ): """Build one context kernel from its batch-independent static topology.""" @@ -289,19 +304,15 @@ def _make_context_kernel( from .kernels.fmha_context.fmha_kernel import FmhaTs use_paged_kv = page_size is not None - if use_paged_kv != (max_kv_len is not None): + if use_paged_kv and max_kv_len is None: raise ValueError("paged context requires both page geometry values") is_persistent = scheduler != "nonpersistent" is_clc_dynamic = scheduler == "clc_dynamic_persistent" paged_kwargs = ( - { - "use_paged_kv": True, - "num_tokens_per_page": page_size, - "max_kv_len": max_kv_len, - } - if use_paged_kv - else {} + {"use_paged_kv": True, "num_tokens_per_page": page_size} if use_paged_kv else {} ) + if max_kv_len is not None: + paged_kwargs["max_kv_len"] = max_kv_len fmha = FmhaTs( qk_acc_dtype=cutlass.Float32, pv_acc_dtype=cutlass.Float32, @@ -333,6 +344,7 @@ def _make_context_kernel( use_blackwell_tma_oob_workaround=( torch.cuda.get_device_capability(device_index) in ((10, 0), (10, 3)) ), + vc_attention=vc_attention, **paged_kwargs, ) return fmha @@ -1595,8 +1607,13 @@ def _two_cta_umma_geometry_eligible(geometry: _ContextPlanGeometry) -> bool: The two-CTA launch is non-persistent with heads on grid Y and batch on grid Z. CUDA limits grid Y and Z to 65,535. Oversized geometries keep the persistent flattened grid so the valid int32 plans stay launchable.""" + # VC-Attention-QK16 always runs two-CTA. With P in SMEM, the bf16 K ring, + # tile-mean ring and row-sum operands leave room for one K/V stage per CTA + # at one CTA and three in the halved form. The VC tail needs two. + # VC-Attention-QK8 keeps the E4M3 K ring and follows the device default. + vc_qk16 = geometry.vc is not None and geometry.qk_dtype != torch.float8_e4m3fn return ( - _default_two_cta_umma(geometry.device_index) + (_default_two_cta_umma(geometry.device_index) or vc_qk16) and geometry.head_dim == 128 and geometry.head_dim_vo in (None, 128) and geometry.mask_type == "dense" @@ -1677,6 +1694,13 @@ def _resolve_paged_context_scheduler( return "static_persistent" +def _fixed_kv_rows(max_seq_len_k: int, vc: Optional[VCAttentionConfig]) -> int: + """K/V rows of a fixed plan. V repair adds its tiles to the sequence.""" + if vc is not None and vc.repair_tiles: + return vc_repair_kv_len(max_seq_len_k, vc.repair_tiles) + return max_seq_len_k + + def _context_compile_spec(geometry: _ContextPlanGeometry) -> _ContextCompileSpec: """Build the contiguous compile key, including separate QK and PV dtype keys.""" return _ContextCompileSpec( @@ -1700,6 +1724,7 @@ def _context_compile_spec(geometry: _ContextPlanGeometry) -> _ContextCompileSpec packed_dense_k_mask=geometry.packed_dense_k_mask, scheduler=_resolve_context_scheduler(geometry), two_cta_umma=_two_cta_umma_geometry_eligible(geometry), + vc=geometry.vc, ) @@ -1755,6 +1780,8 @@ def _get_compiled_context( packed_dense_k_mask = compile_spec.packed_dense_k_mask scheduler = compile_spec.scheduler two_cta_umma = compile_spec.two_cta_umma + vc_attention = compile_spec.vc is not None + vc_qk8 = vc_attention and qk_dtype_key == "float8_e4m3fn" import cutlass import cutlass.cute as cute @@ -1789,9 +1816,19 @@ def _get_compiled_context( two_cta_umma=two_cta_umma, uses_ldtm_stat=_default_uses_ldtm_stat(device_index), fp8_psmem_early_token=_default_fp8_psmem_early_token(device_index), + vc_attention=("means" if compile_spec.vc.demean else "outliers") + if vc_attention + else None, + # The QK8 K-scale table is sized from the K/V rows of the fixed plan. + max_kv_len=_fixed_kv_rows(max_seq_len_k, compile_spec.vc) if vc_qk8 else None, ) fmha.cfg.has_varlen = packed fmha.cfg.has_uniform_varlen = uniform_packed_lengths + if vc_qk8: + # The QK8 scale tables are addressed with the fixed plan lengths, the K/V + # rows including the repair tiles. + fmha.cfg.uniform_seq_len_q = max_seq_len_q + fmha.cfg.uniform_seq_len_k = _fixed_kv_rows(max_seq_len_k, compile_spec.vc) if uniform_packed_lengths: fmha.cfg.uniform_seq_len_q = max_seq_len_q fmha.cfg.uniform_seq_len_k = max_seq_len_k @@ -1820,11 +1857,15 @@ def tensor_adapter( variable_window_token_starts: cute.Tensor, variable_window_token_ends: cute.Tensor, variable_window_cta_starts: cute.Tensor, + vc_mu: cute.Tensor | None, + vc_q_scale: cute.Tensor | None, + vc_k_scale: cute.Tensor | None, stream: cuda_drv.CUstream, static_max_active_clusters: cutlass.Constexpr[int], static_packed: cutlass.Constexpr[bool], static_max_seq_len_q: cutlass.Constexpr[int], static_max_seq_len_k: cutlass.Constexpr[int], + static_vc_repair_tiles: cutlass.Constexpr[int], ) -> None: """Adapt torch TVM-FFI tensors to the FmhaTs host entry point.""" @@ -1845,6 +1886,10 @@ def tensor_adapter( variable_window_token_starts=variable_window_token_starts, variable_window_token_ends=variable_window_token_ends, variable_window_cta_starts=variable_window_cta_starts, + vc_mu=vc_mu, + vc_q_scale=vc_q_scale, + vc_k_scale=vc_k_scale, + vc_repair_tiles=static_vc_repair_tiles, ) else: fmha( @@ -1859,6 +1904,10 @@ def tensor_adapter( variable_window_token_starts=variable_window_token_starts, variable_window_token_ends=variable_window_token_ends, variable_window_cta_starts=variable_window_cta_starts, + vc_mu=vc_mu, + vc_q_scale=vc_q_scale, + vc_k_scale=vc_k_scale, + vc_repair_tiles=static_vc_repair_tiles, ) def fake_compact(dtype, shape, assumed_align): @@ -1885,7 +1934,12 @@ def fake_compact(dtype, shape, assumed_align): else: batch_size = cute.sym_int() q_shape = (batch_size, max_seq_len_q, num_qo_heads, head_dim) - kv_shape = (batch_size, max_seq_len_k, num_kv_heads, head_dim) + kv_shape = ( + batch_size, + _fixed_kv_rows(max_seq_len_k, compile_spec.vc), + num_kv_heads, + head_dim, + ) out_shape = (*q_shape[:-1], head_dim_vo) qo_indptr_shape = (1,) kv_indptr_shape = (1,) @@ -1894,7 +1948,13 @@ def fake_compact(dtype, shape, assumed_align): v_fake = fake_compact(input_pv_dtype, (*kv_shape[:-1], head_dim_vo), 16) out_fake = fake_compact(output_dtype, out_shape, 16) scale_fake = fake_compact(cutlass.Float32, (1,), 4) - output_scale_fake = fake_compact(cutlass.Float32, (1,), 4) + if vc_attention: + # Per-channel V residual scale table, one row per batch and head. + output_scale_fake = fake_compact( + cutlass.Float32, (batch_size, num_qo_heads, head_dim_vo), 64 + ) + else: + output_scale_fake = fake_compact(cutlass.Float32, (1,), 4) qo_indptr_fake = fake_compact(cutlass.Int32, qo_indptr_shape, 4) kv_indptr_fake = fake_compact(cutlass.Int32, kv_indptr_shape, 4) if has_variable_window: @@ -1913,6 +1973,38 @@ def fake_compact(dtype, shape, assumed_align): variable_window_cta_starts_fake = fake_compact( cutlass.Int32, variable_window_cta_shape, 4 ) + vc_mu_fake = None + vc_q_scale_fake = None + vc_k_scale_fake = None + if vc_attention: + if packed: + raise RuntimeError("VC-Attention context requires fixed tensors") + # The plan fixes every VC operand shape, so the kernel addresses the + # tile means and the Q and K scale tables with compile-time extents. + vc_shapes = vc_scale_shapes( + compile_spec.vc, + batch_size=batch_size, + seq_len_kv=max_seq_len_k, + num_kv_heads=num_kv_heads, + head_dim=head_dim_vo or head_dim, + seq_len_q=max_seq_len_q, + num_qo_heads=num_qo_heads, + qk_fp8=vc_qk8, + ) + if compile_spec.vc.demean: + vc_mu_fake = fake_compact(cutlass.BFloat16, vc_shapes["tile_means"], 16) + if vc_qk8: + # The kernel reads the Q and K scale tables as one row of blocks per head. + vc_q_scale_fake = fake_compact( + cutlass.Float32, + (num_qo_heads, batch_size * vc_shapes["q_scale"][2]), + 16, + ) + vc_k_scale_fake = fake_compact( + cutlass.Float32, + (num_kv_heads, batch_size * vc_shapes["k_scale"][2]), + 16, + ) stream_fake = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) # Task objects carry loop-local state through generated control flow, so @@ -1931,11 +2023,15 @@ def compile_kernel(): variable_window_starts_fake, variable_window_ends_fake, variable_window_cta_starts_fake, + vc_mu_fake, + vc_q_scale_fake, + vc_k_scale_fake, stream_fake, max_active_clusters, packed, max_seq_len_q, max_seq_len_k, + compile_spec.vc.repair_tiles if vc_attention else 0, options=_COMPILE_OPTIONS, ) @@ -1954,6 +2050,7 @@ def compile_kernel(): ("uniform_packed_lengths", uniform_packed_lengths), ("causal_single_kv_tile", causal_single_kv_tile), ("packed_dense_k_mask", packed_dense_k_mask), + ("vc_attention", vc_attention), ) return compiled, policy @@ -2263,7 +2360,7 @@ def _validate_runtime_inputs( ) kv_shape = ( geometry.batch_size, - geometry.max_seq_len_k, + _fixed_kv_rows(geometry.max_seq_len_k, geometry.vc), geometry.num_kv_heads, geometry.head_dim, ) @@ -2494,7 +2591,8 @@ class BatchPrefillTSWrapper: all captured runtime tensors alive until every graph using the current plan is destroyed. Before running on a CUDA stream that is not already ordered after the planning stream, the caller must establish that - dependency. + dependency. VC plans also own the output-scale buffer that every run + refreshes, so launches of one VC plan must not overlap either. """ @flashinfer_experimental_api @@ -2523,9 +2621,18 @@ def plan( window_left: int = -1, sm_scale: Optional[float] = None, output_scale: float = 1.0, + vc_config: Optional[VCAttentionConfig] = None, ) -> None: """Compile one reusable specialization from explicit static geometry. + ``vc_config`` selects a VC-Attention recipe and the planned Q/K dtype + picks its Q/K side. bf16 Q/K runs VC-Attention-QK16 and E4M3 + Q/K runs VC-Attention-QK8, whose Hadamard-rotated, per-block scaled Q + and K need ``vc.q_scale`` and ``vc.k_scale`` on every :meth:`run`. V is + E4M3 in both, stored as per-128-token-tile residuals whose bf16 tile + means the kernel restores. Every :meth:`run` then supplies the permuted + K, the E4M3 V and ``vc=VCAttentionParams(...)``. + Packed plans conservatively support any positive per-request Q and K/V lengths bounded by ``max_seq_len_q`` and ``max_kv_len``. Fixed plans use those bounds as their exact tensor extents. ``batch_size`` is exact. @@ -2574,6 +2681,10 @@ def plan( Softmax scale; defaults to the inverse square root of head size. output_scale : float Scale applied to the attention output. + vc_config : VCAttentionConfig, optional + A VC-Attention recipe. Requires fixed dense tensors, head_dim 128, + equal Q and K/V head counts and E4M3 V. bf16 Q/K selects + VC-Attention-QK16, E4M3 Q/K selects VC-Attention-QK8. """ resolved_out_dtype = q_dtype if out_dtype is None else out_dtype @@ -2599,6 +2710,14 @@ def plan( window_left=window_left, output_dtype=resolved_out_dtype, ) + if vc_config is not None and not isinstance(vc_config, VCAttentionConfig): + raise TypeError("vc_config must be a VCAttentionConfig instance") + if vc_config is not None and (packed or mask_type != "dense"): + raise ValueError( + "vc_config requires a dense contiguous fixed-length plan; VC-Attention " + "has no packed, causal or variable-window kernel" + ) + geometry = replace(geometry, vc=vc_config) if sm_scale is None: sm_scale = 1.0 / math.sqrt(geometry.head_dim) sm_scale = _validate_scale(sm_scale, "sm_scale") @@ -2609,9 +2728,23 @@ def plan( scale_tensor = torch.tensor( [scale_softmax_log2], dtype=torch.float32, device=geometry.device ) - output_scale_tensor = torch.tensor( - [output_scale], dtype=torch.float32, device=geometry.device - ) + vc_output_scale_buffer = None + if geometry.vc is not None: + output_scale_tensor = torch.full( + ( + geometry.batch_size, + geometry.num_qo_heads, + geometry.head_dim_vo or geometry.head_dim, + ), + output_scale, + dtype=torch.float32, + device=geometry.device, + ) + vc_output_scale_buffer = torch.empty_like(output_scale_tensor) + else: + output_scale_tensor = torch.tensor( + [output_scale], dtype=torch.float32, device=geometry.device + ) empty_i32 = torch.empty(1, dtype=torch.int32, device=geometry.device) if geometry.mask_type == "variable_window": tile_size_q = _variable_window_tile_size_q(geometry.head_dim) @@ -2638,6 +2771,18 @@ def plan( # making plan publication atomic, this lets compute-sanitizer patch the # generated attention kernel without interleaving later PyTorch setup # launches with the DSL compiler/runtime callbacks. + vc_shapes = None + if vc_config is not None: + vc_shapes = vc_scale_shapes( + vc_config, + batch_size=geometry.batch_size, + seq_len_kv=geometry.max_seq_len_k, + num_kv_heads=geometry.num_kv_heads, + head_dim=geometry.head_dim_vo or geometry.head_dim, + seq_len_q=geometry.max_seq_len_q, + num_qo_heads=geometry.num_qo_heads, + qk_fp8=geometry.qk_dtype == torch.float8_e4m3fn, + ) compiled, policy = _get_compiled_context(_context_compile_spec(geometry)) self._plan_state = _ContextPlanState( geometry=geometry, @@ -2648,6 +2793,8 @@ def plan( variable_window_cta_starts=variable_window_cta_starts, compiled=compiled, policy=policy, + vc_scale_shapes=vc_shapes, + vc_output_scale=vc_output_scale_buffer, ) @flashinfer_experimental_api @@ -2665,6 +2812,7 @@ def run( out: Optional[torch.Tensor] = None, scale_softmax_log2: Optional[torch.Tensor] = None, output_scale: Optional[torch.Tensor] = None, + vc: Optional[VCAttentionParams] = None, validate: bool = True, ) -> torch.Tensor: """Launch the compiled specialization with per-request tensors. @@ -2672,7 +2820,9 @@ def run( Parameters ---------- q, k, v : torch.Tensor - Runtime query, key, and value tensors matching the plan. + Runtime query, key, and value tensors matching the plan. Under a + VC plan ``k`` is in the permuted token order and ``v`` holds the + E4M3 residuals, as :class:`VCAttentionPreprocessor` produces them. qo_indptr, kv_indptr : torch.Tensor, optional Cumulative packed Q and K/V offsets. Required by packed plans and forbidden by fixed plans. @@ -2692,11 +2842,16 @@ def run( to the scale retained by the plan. output_scale : torch.Tensor, optional Per-run one-element float32 output scale. Defaults to the plan. + A VC plan multiplies it by the per-channel V residual scale. + vc : VCAttentionParams, optional + Operands of this run. Required by a VC plan and rejected + otherwise. validate : bool Validate tensor structure and metadata values. Disable only when the caller guarantees these contracts. Output must not overlap any live input or plan-owned buffer in either mode; storage - overlap and lifetime are caller preconditions. Defaults to ``True``. + overlap and lifetime are caller preconditions. The VC operand + requirement is checked in both modes. Defaults to ``True``. """ state = self._plan_state @@ -2720,6 +2875,34 @@ def run( runtime_qo_indptr = state.empty_i32 runtime_kv_indptr = state.empty_i32 + if (vc is None) == (geometry.vc is not None): + raise ValueError( + "vc=VCAttentionParams(...) is required by a VC plan and rejected " + "by a plan without vc_config" + ) + vc_output_scale: Optional[torch.Tensor] = None + vc_mu: Optional[torch.Tensor] = None + vc_q_scale: Optional[torch.Tensor] = None + vc_k_scale: Optional[torch.Tensor] = None + if vc is not None: + if validate: + validate_vc_params(vc, state.vc_scale_shapes, device=geometry.device) + if geometry.qk_dtype == torch.float8_e4m3fn: + if vc.q_scale is None or vc.k_scale is None: + raise ValueError( + "VC-Attention-QK8 plans require vc.q_scale and vc.k_scale" + ) + vc_q_scale = vc.q_scale.view(geometry.num_qo_heads, -1) + vc_k_scale = vc.k_scale.view(geometry.num_kv_heads, -1) + elif vc.q_scale is not None or vc.k_scale is not None: + raise ValueError( + "vc.q_scale and vc.k_scale belong to VC-Attention-QK8 plans with " + "E4M3 Q/K" + ) + vc_mu = vc.tile_means + # VC plans have equal Q and K/V head counts, so the per-channel V + # scale is already in output order. + vc_output_scale = vc.v_scale if validate: _validate_runtime_inputs( q, @@ -2791,6 +2974,12 @@ def run( "output_scale", device=geometry.device, ) + if vc_output_scale is not None: + # The per-channel V residual scale multiplies the planned/passed scale + # into the plan-owned buffer. + output_scale = torch.mul( + vc_output_scale, output_scale, out=state.vc_output_scale + ) if out is None: out = torch.empty( @@ -2817,6 +3006,9 @@ def run( runtime_window_starts, runtime_window_ends, runtime_window_cta_starts, + vc_mu, + vc_q_scale, + vc_k_scale, ) return out @@ -3163,6 +3355,8 @@ def batch_prefill( output_scale: float = 1.0, out_dtype: Optional[torch.dtype] = None, out: Optional[torch.Tensor] = None, + vc: Optional[VCAttentionParams] = None, + vc_config: Optional[VCAttentionConfig] = None, ) -> torch.Tensor: """Run one-shot fixed or packed-ragged task-scheduled context attention. @@ -3220,6 +3414,21 @@ def batch_prefill( "batch_prefill cannot derive host plan bounds during CUDA graph " "capture; plan BatchPrefillTSWrapper before capture" ) + if vc_config is not None and vc is None: + raise ValueError("vc_config requires the vc operands of this call") + if (vc_config is not None and vc_config.repair_tiles) or ( + vc_config is None and vc is not None and vc.tile_means is None + ): + # The K/V rows of V repair operands include the repair tiles, so the + # plan bounds cannot be derived from the operands alone. Without a + # config, operands with no tile means may be repair operands. + raise NotImplementedError( + "batch_prefill does not run V repair operands; plan " + "BatchPrefillTSWrapper with VCAttentionConfig(repair_tiles=...), or " + "pass vc_config=VCAttentionConfig(demean=False) for plain operands" + ) + if vc is not None and vc_config is None: + vc_config = VCAttentionConfig(demean=vc.tile_means is not None) geometry = _resolve_geometry( q, k, @@ -3249,6 +3458,7 @@ def batch_prefill( window_left=window_left, sm_scale=sm_scale, output_scale=output_scale, + vc_config=vc_config, ) return wrapper.run( q, @@ -3259,6 +3469,7 @@ def batch_prefill( variable_window_token_starts=variable_window_token_starts, variable_window_token_ends=variable_window_token_ends, out=out, + vc=vc, ) diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_kernel.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_kernel.py index 0c5a915d0bcf..6811b03c1165 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_kernel.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_kernel.py @@ -33,6 +33,13 @@ schedule before the repeated K/V tile loop, LOOP is the repeated K/V tile body, and TAIL is the one-time cleanup and drain after LOOP exits. +VC-Attention is the low-bit attention recipe of Li et al. 2026, arXiv +2609.15810, value smoothing with a softmax cast. Names with the ``vc`` prefix +belong to its recipes: QK16 keeps bf16 Q and K, QK8 adds centred, Hadamard +rotated E4M3 Q and K with block scales, and both store E4M3 V as residuals +around each 128-token tile mean, which the kernel restores inside the online +softmax. + Feature Support Matrix: | Feature | Support | @@ -181,6 +188,8 @@ TmemStatsDoneResource, TmemPPrefixReadyResource, ) +from ...vc_attention import vc_mean_operand_shape +from .vc_attention.vc_resources import SmemMuResource from .fmha_tasks import ( PackedContextWorkQueue, create_correction_task, @@ -683,6 +692,10 @@ def build_context_task_manager( tma_k_desc: cutlass.Pointer | None, tma_v_desc: cutlass.Pointer | None, tma_o_desc: cutlass.Pointer | None, + tma_mu_desc: cutlass.Pointer | None = None, + vc_q_scale: cute.Tensor | None = None, + vc_k_scale: cute.Tensor | None = None, + vc_repair_tiles: int = 0, cum_seqlen_q: cute.Tensor | None, cum_seqlen_k: cute.Tensor | None, variable_window_token_starts: cute.Tensor | None = None, @@ -741,6 +754,16 @@ def build_context_task_manager( TMA descriptor pointers for Q, K, V, O. cum_seqlen_q, cum_seqlen_k : cute.Tensor, optional Cumulative sequence-length metadata for varlen launches. + tma_mu_desc : cutlass.Pointer, optional + TMA descriptor of the VC-Attention tile-mean operands, the B operand of + the mean UMMA step. None unless the kernel restores means. + vc_q_scale, vc_k_scale : cute.Tensor, optional + VC-Attention-QK8 dequantization scales, one per 128-token Q block and + per K/V tile, in the flat per-sequence slot order of ``vc_scales``. + None under QK16. + vc_repair_tiles : int + VC-Attention repair tiles appended to the K/V sequence, kept out of + the softmax denominator. Zero without V repair. num_kv_tiles : int or Int32 Number of KV tiles in the loop domain. q_offset : int or Int32 @@ -1086,6 +1109,35 @@ def make_page_offsets_pipeline_cfg(num_stages: int) -> PipelineConfig: name="smem_v", **kv_resource_kwargs, ) + # Mu is the per-tile mean of V. V tile t is stored as E4M3 residuals + # V8_t = V_t - mu_t, so the PV product splits into + # O = sum_t P_t V8_t + sum_t rowsum(P_t) mu_t + # and the second term is a bf16 K=16 UMMA per group of sixteen tiles with + # the row sums as A and the means as B. Mu is therefore a UMMA operand + # like K and V and must sit in shared memory. The load warp stages it + # beside each V tile and the UMMA warp consumes it. + smem_mu: SmemMuResource | None = None + if cfg.vc_restores_means: + smem_mu_pipeline_cfg = PipelineConfig.create_tma_umma_pipeline_cfg( + num_stages=cfg.vc_mean_stages, + # Under two-CTA UMMA each CTA stages the N/2 channels of the mean + # operand its half of the M=256 step reads (like V columns). + num_bytes=cfg.vc_mean_tile_bytes, + producer_group=tma_producer_group, + consumer_group=pipeline.CooperativeGroup(Agent.Thread), + cta_layout_vmnk=cluster_shape_vmnk, + advance_on_wait=True, + num_bytes_per_warp_per_cta=cfg.vc_mean_tile_bytes // cfg.cta_group_size + if two_cta + else None, + **tma_umma_leader_kwargs, + ) + smem_mu = SmemMuResource( + tma_mu_desc=tma_mu_desc, + pipeline_config=smem_mu_pipeline_cfg, + cfg=cfg, + name="smem_mu", + ) # WorkQueue: persistent tile scheduler state (static or CLC dynamic), not # Q/K/V/O dataflow. Non-persistent launches omit it so each CTA executes @@ -1198,6 +1250,9 @@ def make_page_offsets_pipeline_cfg(num_stages: int) -> PipelineConfig: variable_window_q_stride=variable_window_q_stride, scale_softmax_log2=scale_softmax_log2, smem_p=smem_p0, + vc_q_scale=vc_q_scale, + vc_k_scale=vc_k_scale, + vc_repair_tiles=vc_repair_tiles, name="tmem_sp0", ) tmem_p0: TmemPResource | None = None @@ -1291,6 +1346,9 @@ def make_page_offsets_pipeline_cfg(num_stages: int) -> PipelineConfig: variable_window_q_stride=variable_window_q_stride, scale_softmax_log2=scale_softmax_log2, smem_p=smem_p1, + vc_q_scale=vc_q_scale, + vc_k_scale=vc_k_scale, + vc_repair_tiles=vc_repair_tiles, name="tmem_sp1", ) tmem_vec1 = TmemStatsResource( @@ -1373,6 +1431,7 @@ def scheduler_deps(*resources: MemoryResource) -> list[MemoryResource]: work_queue, smem_page_offsets_kv=smem_page_offsets_kv, smem_page_offsets_v=smem_page_offsets_v, + smem_mu=smem_mu, **domain_n_kwargs, ) mma_task = create_mma_task( @@ -1391,6 +1450,7 @@ def scheduler_deps(*resources: MemoryResource) -> list[MemoryResource]: tmem_p_prefix_ready_1=tmem_p_prefix_ready_1, smem_p0=smem_p0, smem_p1=smem_p1, + smem_mu=smem_mu, **mma_domain_kwargs, ) @@ -1544,6 +1604,8 @@ def scheduler_deps(*resources: MemoryResource) -> list[MemoryResource]: if smem_page_offsets_v is not None: smem_v_deps.append(smem_page_offsets_v) resource_dependency_graph[smem_v] = scheduler_deps(*smem_v_deps) + if smem_mu is not None: + resource_dependency_graph[smem_mu] = scheduler_deps(gmem_qkv) resource_dependency_graph.update( { tmem_sp0: scheduler_deps( @@ -1605,6 +1667,8 @@ def add_smem_resource(resource: MemoryResource | None) -> None: add_smem_resource(smem_kv) if cfg.split_kv_pipelines: add_smem_resource(smem_v) + if smem_mu is not None: + add_smem_resource(smem_mu) if smem_page_offsets_kv is not None: add_smem_resource(smem_page_offsets_kv) if smem_page_offsets_v is not None: @@ -1812,6 +1876,7 @@ def _context_pipeline_stage_counts( "s0s1_seq": 0 if cfg.single_qkv_instance else 1, "tmem_p_prefix_ready": 2 if cfg.pv_half_overlap else 0, "smem_p": cfg.num_qkv_instances if cfg.p_in_smem else 0, + "smem_mu": cfg.vc_mean_stages if cfg.vc_restores_means else 0, "tmem_stats_done": 0 if cfg.stats_via_smem else cfg.num_qkv_instances, "work_queue": 1 if is_clc_dynamic else 0, } @@ -1872,8 +1937,15 @@ def _kv_ring_smem_budget_bytes( align = cfg.buffer_align_bytes smem_p_bytes = 0 if cfg.p_in_smem: + p_block_bytes = cfg.smem_p_bytes + if cfg.vc_restores_means: + # The row-sum operand lives behind each P tile. + p_block_bytes += cfg.vc_rowsum_tile_bytes + if cfg.vc_qk8: + # VC-Attention-QK8 keeps its K-scale table behind the P tile. + p_block_bytes += cfg.vc_kscale_table_bytes smem_p_bytes = ( - (cfg.smem_p_bytes + align - 1) // align * align * cfg.num_qkv_instances + (p_block_bytes + align - 1) // align * align * cfg.num_qkv_instances ) control_bytes = (2 * cutlass.Int32.width + cutlass.Int64.width) // 8 if is_clc_dynamic: @@ -1885,6 +1957,9 @@ def _kv_ring_smem_budget_bytes( is_clc_dynamic=is_clc_dynamic, ).values() ) + if cfg.vc_restores_means: + # The callers charge the tile-mean ring per K/V stage. + fixed_barrier_stages -= cfg.vc_mean_stages fixed_smem_bytes = ( (q_tile_bytes * cfg.q_stage + align - 1) // align * align + (o_stage_bytes + align - 1) // align * align * cfg.num_qkv_instances @@ -1924,6 +1999,10 @@ def _infer_single_instance_kv_stages( cfg.qk_mma_tiler[1] // cfg.cta_group_size * kv_head_dim * kv_dtype_width // 8 ) kv_stage_footprint_bytes = kv_stage_bytes + _PIPELINE_BARRIER_BYTES_PER_STAGE + if cfg.vc_restores_means: + kv_stage_footprint_bytes += ( + cfg.vc_mean_tile_bytes + _PIPELINE_BARRIER_BYTES_PER_STAGE + ) memory_fit_stages = kv_budget_bytes // kv_stage_footprint_bytes cadence_stages = cfg.num_head_dim_stages_k + cfg.num_head_dim_stages_v if require_cadence and memory_fit_stages < cadence_stages: @@ -1968,6 +2047,8 @@ def _configure_kv_ring_depths(cfg: FmhaConfig, *, is_clc_dynamic: bool) -> None: kv_rows_per_cta * kv_head_dim * cfg.v_dtype.width // 8 + _PIPELINE_BARRIER_BYTES_PER_STAGE ) + if cfg.vc_restores_means: + v_stage_footprint += cfg.vc_mean_tile_bytes + _PIPELINE_BARRIER_BYTES_PER_STAGE # K and V share the same head_dim and head_dim_per_stage_kv, so their # minimum ring depths (num_head_dim_stages) are equal and both rings are sized identically. cadence = cfg.num_head_dim_stages_k @@ -1978,6 +2059,12 @@ def _configure_kv_ring_depths(cfg: FmhaConfig, *, is_clc_dynamic: bool) -> None: f"({cadence * (k_stage_footprint + v_stage_footprint)} bytes), but the " f"shared-memory budget fits only {budget_bytes} bytes" ) + if cfg.vc_restores_means and n_stages < 2: + # The tail holds the last two tile-mean operands at once. + raise ValueError( + f"VC-Attention needs at least 2 stages per K/V ring, but the " + f"shared-memory budget of {budget_bytes} bytes fits only {n_stages}" + ) cfg.kv_stage_k = n_stages cfg.kv_stage_v = n_stages @@ -2586,6 +2673,10 @@ def build_fmha_task_manager( block_table_row_stride: int | Int32 = 0, g_seq_lens_kv: cute.Pointer | None = None, max_seq_len_kv: int | Int32 | None = None, + tma_mu_desc: cutlass.Pointer | None = None, + vc_q_scale: cute.Tensor | None = None, + vc_k_scale: cute.Tensor | None = None, + vc_repair_tiles: int = 0, is_persistent: bool = True, is_clc_dynamic: bool = False, clc_response_ptr: cute.Pointer | None = None, @@ -2666,6 +2757,10 @@ def build_fmha_task_manager( tma_k_desc=tma_k_desc, tma_v_desc=tma_v_desc, tma_o_desc=tma_o_desc, + tma_mu_desc=tma_mu_desc, + vc_q_scale=vc_q_scale, + vc_k_scale=vc_k_scale, + vc_repair_tiles=vc_repair_tiles, cum_seqlen_q=cum_seqlen_q, cum_seqlen_k=cum_seqlen_k, variable_window_token_starts=variable_window_token_starts, @@ -2794,6 +2889,7 @@ def __init__( exhaustive_deadlock_race_check: bool = True, d_v: int | None = None, use_blackwell_tma_oob_workaround: bool = False, + vc_attention: str | None = None, ) -> None: """Initialize mode-specific tiling, dtype, and schedule configuration.""" head_paired = resolve_head_paired_mode( @@ -2878,6 +2974,8 @@ def __init__( cfg.two_cta_umma = two_cta_umma if two_cta_umma: cfg.cluster_shape_mn = (2, 1) + cfg.vc_attention = vc_attention + cfg.fp8_psmem_early_token = fp8_psmem_early_token self.cfg = cfg # Compact Q and staged O fit two resident query tiles plus the K/V # ring. Pairing overlaps the two softmax groups with MMA work. @@ -2908,7 +3006,10 @@ def __init__( cfg.num_regs_correction = 88 cfg.num_regs_other = 56 cfg.enable_skip_correction = enable_skip_correction - if enable_skip_correction: + # VC-Attention skips no correction. The skip keeps a stale row max, + # under which a larger score codes past VC_EXPCAST_CODE_BIAS and out of + # the E4M3 range. The exact per-tile max keeps every code at or below it. + if enable_skip_correction and not cfg.vc_attention: cfg.corr_skip_threshold_log2 = _CORR_SKIP_THRESHOLD_LOG2 cfg.uses_ldtm_stat = uses_ldtm_stat cfg.fp8_psmem_early_token = fp8_psmem_early_token @@ -2922,10 +3023,17 @@ def __init__( cfg.o_dtype = o_dtype cfg.head_paired = head_paired cfg.is_causal = is_causal + cfg.h_r = h_r + cfg.has_variable_window = has_variable_window balance_causal_workload = balance_causal_workload or ( is_causal and is_clc_dynamic and not cfg.single_qkv_instance ) + if head_paired and cfg.vc_attention: + raise ValueError( + "VC-Attention requires the query-paired context kernel; a positive " + "window_left selects the head-paired kernel" + ) if head_paired: _configure_head_paired_tilers(cfg, mma_tiler_mn=mma_tiler_mn, d=d) _configure_head_dim_staging(cfg) @@ -2961,6 +3069,7 @@ def __init__( cfg.pv_mma_tiler = (mma_tiler[0], d_v, mma_tiler[1]) cfg.epi_tile = cfg.pv_mma_tiler[:2] cfg.p_in_smem = _uses_smem_p(cfg, has_variable_window=has_variable_window) + cfg.validate_vc_profile() _configure_head_dim_staging(cfg) _configure_pipeline_stages( cfg, is_clc_dynamic=is_clc_dynamic, is_persistent=is_persistent @@ -3065,9 +3174,19 @@ def __call__( variable_window_token_starts: cute.Tensor | None = None, variable_window_token_ends: cute.Tensor | None = None, variable_window_cta_starts: cute.Tensor | None = None, + vc_mu: cute.Tensor | None = None, + vc_q_scale: cute.Tensor | None = None, + vc_k_scale: cute.Tensor | None = None, + vc_repair_tiles: int = 0, ) -> None: """Set up TMA descriptors, compute grid, and launch the kernel. + VC-Attention adds the tile means, the bf16 UMMA operands packed by the + host with sixteen tiles per group, and the repair tile count, a + compile-time constant giving how many outlier tiles end the K/V loop of + an outlier plan. VC-Attention-QK8 also takes the Q and K dequant scales + as ``[H, B, blocks]`` tables with one scale per 128-token block. + ``scale_softmax_log2`` and ``output_scale`` must be one-element float32 device tensors. Example host values are ``[math.log2(math.e) / math.sqrt(d)]`` for the softmax scale and @@ -3288,6 +3407,25 @@ def __call__( l2_promotion=cuda.TensorMapL2Promotion.none, ) + # VC-Attention tile-mean operands, one packed tile per K/V tile. + tma_mu_desc = tma_v_desc + if cutlass.const_expr( + cfg.vc_qk8 and (vc_q_scale is None or vc_k_scale is None) + ): + raise ValueError("VC-Attention-QK8 requires vc_q_scale and vc_k_scale") + if cutlass.const_expr(cfg.vc_restores_means): + if cutlass.const_expr(vc_mu is None): + raise ValueError("VC-Attention requires vc_mu") + mu_rows, mu_cols = vc_mean_operand_shape(cfg.pv_mma_tiler[1]) + tma_mu_desc = cuda.create_tensor_map_tiled_from_view( + vc_mu, + # Two-CTA loads the half of the rows its channels need. + box_dims=(1, 1, 1, mu_rows // cfg.cta_group_size, mu_cols), + stride_order=(4, 3, 2, 1, 0), + swizzle=cuda.TensorMapSwizzle.none, + l2_promotion=cuda.TensorMapL2Promotion.none, + ) + # Compute tile scheduler and grid if cutlass.const_expr(cum_seqlen_q is None): b = o_cute.shape[0] @@ -3380,6 +3518,9 @@ def __call__( tma_k_desc, tma_v_desc, tma_o_desc, + tma_mu_desc, + vc_q_scale, + vc_k_scale, tile_sched_params, scale_softmax_log2, output_scale, @@ -3396,6 +3537,7 @@ def __call__( variable_window_token_ends, variable_window_cta_starts, Int32(s_q), + vc_repair_tiles, self.is_persistent, self.is_clc_dynamic, ).launch( @@ -3416,6 +3558,9 @@ def kernel( tma_k_desc: cutlass.GridConstant[cuda.TensorMap], tma_v_desc: cutlass.GridConstant[cuda.TensorMap], tma_o_desc: cutlass.GridConstant[cuda.TensorMap], + tma_mu_desc: cutlass.GridConstant[cuda.TensorMap], + vc_q_scale: cute.Tensor | None, + vc_k_scale: cute.Tensor | None, tile_sched_params: ( utils.PersistentTileSchedulerParams | utils.ClcDynamicPersistentTileSchedulerParams @@ -3436,6 +3581,7 @@ def kernel( variable_window_token_ends: cute.Tensor | None, variable_window_cta_starts: cute.Tensor | None, variable_window_q_stride: Int32, + vc_repair_tiles: cutlass.Constexpr[int] = 0, is_persistent: cutlass.Constexpr[bool] = True, is_clc_dynamic: cutlass.Constexpr[bool] = False, ) -> None: @@ -3466,6 +3612,8 @@ def kernel( prims.prefetch_tensormap(tma_k_desc.get_ptr()) prims.prefetch_tensormap(tma_v_desc.get_ptr()) prims.prefetch_tensormap(tma_o_desc.get_ptr()) + if cutlass.const_expr(cfg.vc_restores_means): + prims.prefetch_tensormap(tma_mu_desc.get_ptr()) # 2. CLC dynamic: the response buffer is declared by the builder and # bound from the unified task-manager SMEM allocation below. @@ -3501,6 +3649,10 @@ def kernel( scale_softmax_log2=scale_softmax_log2, output_scale=output_scale, q_offset=q_offset, + tma_mu_desc=tma_mu_desc.get_ptr() if cfg.vc_restores_means else None, + vc_q_scale=vc_q_scale if cfg.vc_qk8 else None, + vc_k_scale=vc_k_scale if cfg.vc_qk8 else None, + vc_repair_tiles=vc_repair_tiles, is_persistent=is_persistent, is_clc_dynamic=is_clc_dynamic, clc_response_ptr=clc_response_ptr, diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_resources.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_resources.py index af69ee7d51bc..2efae0a160c6 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_resources.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_resources.py @@ -25,6 +25,15 @@ schedule before the repeated K/V tile loop, LOOP is the repeated K/V tile body, and TAIL is the one-time cleanup and drain after LOOP exits. +VC-Attention is the low-bit attention recipe of Li et al. 2026, arXiv +2609.15810, value smoothing with a softmax cast. Names with the ``vc`` prefix +belong to its recipes, QK16 with bf16 Q and K and QK8 with centred, Hadamard +rotated E4M3 Q and K under block scales, both with E4M3 V stored as residuals +around each 128-token tile mean. The kernel restores the means inside the +online softmax as ``O += sum_t rowsum(P_t) * mu_t``, one bf16 K=16 UMMA step +per group of sixteen tiles, and casts the probabilities straight to E4M3 +codes. ``vc_resources`` holds the mean operand ring and the cast helpers. + SMEM resources (TMA pipelines) ------------------------------ - SmemQResource : SMEM Q buffer, TmaUmma pipeline. Load -> MMA. @@ -68,7 +77,7 @@ import cutlass import cutlass.cute as cute -from cutlass import Float32, Int16, Int32 +from cutlass import Float32, Int16, Int32, Int64 from ..tensor_map import transform_ragged_coords from cutlass.experimental.task_scheduling.enums import WorkAttr @@ -89,10 +98,22 @@ from ..placeholder_helpers import _placeholder_smem_array, _placeholder_tmem_ptr from ..tcgen05_compat import tcgen05_ld_32x32b_max +from ...vc_attention import VC_MEAN_GROUP_TILES, VC_MEAN_MMA_K, VC_MEAN_OPERANDS +from ..fmha_decode.fmha_decode_resources.helpers_common import _placeholder_local_array +from .vc_attention.vc_resources import ( + E4M3_CODES_PER_OCTAVE, + VC_EXPCAST_CODE_BIAS, + VC_MEAN_TILE_LBO, + VC_MEAN_TILE_SBO, +) +from .vc_attention.vc_scales import VCKScaleTable, vc_flat_k_base, vc_flat_q_slot from .helpers import ( bottom_right_window_left_bound, bottom_right_window_tile_start, + expcast_e4m3_quad_relu, + f16x2_sum4, freeze_smem_descriptor, + split_bf16_hi_lo_word, variable_window_cta_min_start, ) from cutlass.experimental import primitives as prims @@ -112,6 +133,10 @@ _tmem_sp_sdata: dict[int, list] = {} # Packed fp8 P words carried from exp2_p to store_p when P is staged in SMEM. _tmem_sp_pwords: dict[int, tuple] = {} +# VC-Attention: the log2 softmax scale carried from the row-max pass to exp2_p +# and the fp32 tile row sum carried from exp2_p to store_p. +_tmem_sp_tile_scale: dict[int, Any] = {} +_tmem_sp_tile_sum: dict[int, Any] = {} @cute.jit @@ -413,6 +438,13 @@ class FmhaConfig: two_cta_umma: bool = False # exp2 pairs per 16-pair softmax chunk computed on the FMA pipe. exp2_fma_pairs: int = 0 + # VC-Attention mode on the E4M3 V kernel with 16-bit or E4M3 Q/K. V stores + # residuals around a per-tile mean and the output scale is a per-channel + # table. In "means" mode the kernel adds each tile mean back into the + # output with one UMMA step. In "outliers" mode the kernel skips the means + # and instead consumes extra K/V tiles of the largest residuals that + # follow the sequence. None turns VC-Attention off. + vc_attention: str | None = None # Variable sequence length mode stores Q/K/V/O as flattened # [sum_seqlen, head, dim] tensors and uses cum_seqlen_* for per-batch @@ -421,6 +453,11 @@ class FmhaConfig: # Uniform packed plans retain the ragged tensor-map ABI but derive their # cumulative offsets arithmetically, avoiding dependent indptr loads on # every persistent work tile. + # VC-Attention-QK8 fixed plans also set the two lengths while + # has_uniform_varlen stays False. There they are the Q tokens and the K/V + # rows of the fixed plan, the rows including the repair tiles, and they fold + # the flat scale table slots at compile time so the P store addresses stay + # out of the loop. has_uniform_varlen: bool = False uniform_seq_len_q: int = 0 uniform_seq_len_k: int = 0 @@ -487,9 +524,83 @@ class FmhaConfig: # a public tuning input. page_table_window_entries: int = 32 + @property + def vc_qk8(self) -> bool: + """VC-Attention-QK8, the E4M3 Q/K recipe with per-block dequant scales.""" + return self.vc_attention is not None and self.q_dtype.width == 8 + + @property + def vc_restores_means(self) -> bool: + """Whether the kernel adds the tile means back into O.""" + return self.vc_attention == "means" + + def validate_vc_profile(self) -> None: + """Validate the VC-Attention recipe against the configured kernel.""" + if self.vc_attention is None: + return + if self.vc_attention not in ("means", "outliers"): + raise ValueError(f"unknown vc_attention mode {self.vc_attention!r}") + if ( + self.is_causal + or self.has_variable_window + or self.head_paired + or self.use_paged_kv + or self.h_r != 1 + ): + raise ValueError( + "VC-Attention requires the dense contiguous query-paired context " + "kernel with equal Q and K/V head counts" + ) + # The packed mean operand and the row-sum operand are laid out for 128 + # channels and 128 query rows. + if self.logical_head_dim_qk != 128 or self.pv_mma_tiler[1] != 128: + raise ValueError("VC-Attention requires head_dim 128") + if self.q_dtype.width not in (8, 16) or self.v_dtype.width != 8: + raise ValueError("VC-Attention requires 16-bit or E4M3 Q/K and E4M3 V") + if not self.p_in_smem: + raise ValueError( + "VC-Attention requires P staged in SMEM, the dense paired D128 " + "schedule with a 16-bit output" + ) + + @property + def vc_mean_operand_bytes(self) -> int: + """Bytes of one bf16 [D x 16] K-major mean operand (B of one mean UMMA step).""" + return self.pv_mma_tiler[1] * VC_MEAN_MMA_K * 2 + + @property + def vc_mean_tile_bytes(self) -> int: + """Bytes of the mean operands of one tile group (one ring stage).""" + return VC_MEAN_OPERANDS * self.vc_mean_operand_bytes + + @property + def vc_mean_stages(self) -> int: + """Tile-mean ring depth: one operand per staged V tile.""" + return self.kv_stage_v if self.split_kv_pipelines else self.kv_stage_k + + @property + def vc_rowsum_operand_bytes(self) -> int: + """Bytes of one bf16 [128 x 16] K-major row-sum operand (A of one mean UMMA step).""" + return self.qk_mma_tiler[0] * VC_MEAN_MMA_K * 2 + + @property + def vc_rowsum_tile_bytes(self) -> int: + """Bytes of the row-sum operands of one tile group.""" + return VC_MEAN_OPERANDS * self.vc_rowsum_operand_bytes + # Work-tile mapping for the two peer Q/O tiles handled by each CTA: # query-paired maps peers to two sequence tiles in one Q head, while # head-paired mode maps peers to two Q heads at one sequence tile. + @property + def vc_kscale_table_bytes(self) -> int: + """Bytes of one softmax group's fp32 K-scale table, one word per K/V + tile of the K/V length the kernel was built with, 16-byte padded. The + table is sized at construction from ``max_kv_len``, before the fixed + plan lengths reach ``cfg``.""" + max_kv_len = self.max_num_pages_per_seq_kv * self.num_tokens_per_page + entries = max((max_kv_len + self.kv_tile_n - 1) // self.kv_tile_n, 1) + return (entries * 4 + 15) // 16 * 16 + @property def smem_q_head_dim(self) -> int: """Q storage rounded to one 128-byte TMA fragment.""" @@ -2464,13 +2575,35 @@ def __init__( ) -> None: super().__init__(pipeline_config=pipeline_config, **kwargs) self.cfg = cfg + # VC-Attention appends the group's bf16 [128 x 16] row-sum operands behind + # the P tile when it restores the tile means, and VC-Attention-QK8 its + # K-scale table behind those. + extra_bytes = 0 + if cfg.vc_restores_means: + extra_bytes += cfg.vc_rowsum_tile_bytes + if cfg.vc_qk8: + extra_bytes += cfg.vc_kscale_table_bytes self._alloc = SmemAllocation( - f"smem_p{group_idx}", cfg.smem_p_bytes, alignment=cfg.buffer_align_bytes + f"smem_p{group_idx}", + cfg.smem_p_bytes + extra_bytes, + alignment=cfg.buffer_align_bytes, ) def get_smem_requirements(self) -> list[SmemAllocation]: return [self._alloc] + @property + def rowsum_tile_offset(self) -> int: + """Byte offset of the VC-Attention row-sum operands inside this allocation.""" + return self.cfg.smem_p_bytes + + @property + def kscale_table_offset(self) -> int: + """Byte offset of the VC-Attention-QK8 K-scale table inside this allocation, + behind the row-sum operand when the tile means are restored.""" + rowsum = self.cfg.vc_rowsum_tile_bytes if self.cfg.vc_restores_means else 0 + return self.cfg.smem_p_bytes + rowsum + @property def row_bytes(self) -> int: return self.cfg.qk_mma_tiler[1] * self.cfg.v_dtype.width // 8 @@ -2541,6 +2674,25 @@ class TmemSPResource(MemoryResource): variable_window_end: Constexpr[TaskLocalVariable] = ( TaskLocalVariable.uninitialized() ) + # VC-Attention-QK8 dequant scales in the flat layout: Q [Hq, numel] and K/V + # tile [Hkv, numel], both fp32. + vc_q_scale: cute.Tensor | None = field(init=False, default=None) + vc_k_scale: cute.Tensor | None = field(init=False, default=None) + # VC-Attention: the row's softmax scale in log2 units (per work tile, times + # sfQ under QK8) and the previous tile's fp32 row sum awaiting its deferred + # mean step. + vc_row_scale: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + vc_prev_tile_sum: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + vc_kept_row_sum: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + # VC-Attention-QK8: sfK of the next K/V tile, read from the SMEM table one + # tile ahead so no shared load sits on the row-max critical chain. + vc_k_scale_next: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + # Row sums of the sixteen K/V tiles of the current mean group, in the running max's + # units. The mean restore is one bf16 K=16 UMMA per group, O += sum_t rowsum(P_t) * mu_t + # with these sums as the A operand and the tile means as B, so each tile's sum stays live + # until its group closes and is rescaled by every later max correction. One register + # array of VC_MEAN_GROUP_TILES values. + vc_meansums: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() def __init__( self, @@ -2559,11 +2711,21 @@ def __init__( variable_window_q_stride: int | Int32 = 0, scale_softmax_log2: cute.Tensor | None = None, smem_p: Optional[SmemPResource] = None, + vc_q_scale: cute.Tensor | None = None, + vc_k_scale: cute.Tensor | None = None, + vc_repair_tiles: int = 0, **kwargs: Any, ) -> None: - """Bind S/P TMEM offsets, Q peer index, and optional varlen metadata.""" + """Bind S/P TMEM offsets, Q peer index, and optional varlen metadata. + + The repair tile count is a compile-time constant. It says how many + K/V tiles at the end of the loop are VC-Attention outlier tiles. It is + zero on plans that restore the tile means. VC-Attention-QK8 plans carry + the fixed Q and K/V lengths on ``cfg``, which address the scale tables. + """ super().__init__(pipeline_config=pipeline_config, **kwargs) self.cfg = cfg + self.vc_repair_tiles = vc_repair_tiles self.tmem_s_offset = tmem_s_offset self.tmem_p_offset = tmem_p_offset self.q_half = q_half @@ -2577,6 +2739,8 @@ def __init__( self.variable_window_cta_starts = variable_window_cta_starts self.variable_window_q_stride = variable_window_q_stride self.scale_softmax_log2 = scale_softmax_log2 + self.vc_q_scale = vc_q_scale + self.vc_k_scale = vc_k_scale self._alloc = TmemAllocation( f"tmem_sp_q{q_half}", cfg.qk_mma_tiler[1] * cfg.mma_softmax_stage, @@ -2644,6 +2808,32 @@ def __init__( default=Float32(0.0), docs="Softmax scale cached from the runtime scale tensor.", ) + self.vc_row_scale = TaskLocalVariable( + dtype=Float32, + default=Float32(0.0), + docs="VC-Attention: the softmax scale in log2 units.", + ) + self.vc_prev_tile_sum = TaskLocalVariable( + dtype=Float32, + default=Float32(0.0), + docs="VC-Attention: previous tile's row sum, stored one tile late.", + ) + self.vc_kept_row_sum = TaskLocalVariable( + dtype=Float32, + default=Float32(0.0), + docs="VC-Attention V repair, row sum over the original tokens.", + ) + self.vc_k_scale_next = TaskLocalVariable( + dtype=Float32, + default=Float32(1.0), + docs="VC-Attention-QK8: K dequant scale of the next K/V tile.", + ) + self.vc_meansums = TaskLocalVariable( + dtype=cutlass.Array, + default=_placeholder_local_array(Float32, VC_MEAN_GROUP_TILES), + docs="VC-Attention: row sums of the tiles of the current mean group, " + "in the running max's units, lanes of the K=16 mean UMMA A operand.", + ) def get_tmem_requirements(self) -> list[TmemAllocation]: """Return the TMEM allocation for this S/P ping-pong resource.""" @@ -2986,6 +3176,10 @@ def init_mma_state(self, stage_info: StageInfo) -> None: def init_softmax_state_early(self, stage_info: StageInfo) -> None: """Initialize softmax TMEM state without a function-lifetime P value.""" self._init_function_state(stage_info) + if cutlass.const_expr(self.cfg.vc_restores_means): + # The row-sum operand exists behind the P tile only when the tile + # means are restored; V repair plans have no such buffer. + self._zero_vc_rowsum_row(stage_info) @consumer_work(work_attrs=WorkAttr.AUXILIARY, returns=p_chunk) @cute.jit @@ -3003,6 +3197,141 @@ def load_scale_softmax_log2(self, stage_info: StageInfo) -> Float32: return Float32(0.0) return self.scale_softmax_log2[0] + @consumer_work( + work_attrs=WorkAttr.AUXILIARY, + returns=( + vc_row_scale, + vc_prev_tile_sum, + vc_meansums, + vc_kept_row_sum, + vc_k_scale_next, + ), + ) + @cute.jit + def vc_init_row_scale(self, stage_info: StageInfo) -> tuple[Float32, ...]: + """VC-Attention work-tile setup. Returns the softmax scale in log2 units, + a zero previous-tile row sum, the zeroed group row sum array, a zero kept row sum + (V repair) and tile 0's sfK. + + Under VC-Attention-QK8 the row scale also carries this row's sfQ, and the + group's SMEM sfK table is filled with one coalesced pass. Both named + barrier syncs of the fill cover the group's four warps: the first keeps + a fast warp from refilling while a peer still reads the previous work + tile's entries, the second publishes the new table. + """ + row_scale = self.scale_softmax_log2[0] + k_scale_next = Float32(1.0) + if cutlass.const_expr(self.cfg.vc_qk8): + batch_coord, head, row = self._vc_coords(stage_info) + kv_head = head // self.cfg.h_r + q_slot = vc_flat_q_slot( + batch_coord, + row, + self.cfg.uniform_seq_len_q, + self.cfg.kv_tile_n.bit_length() - 1, + ) + row_scale = row_scale * Float32(self.vc_q_scale[(head, q_slot)]) + k_base = vc_flat_k_base( + batch_coord, self.cfg.uniform_seq_len_k, self.cfg.kv_tile_n + ) + num_tiles = ( + self.cfg.uniform_seq_len_k + self.cfg.kv_tile_n - 1 + ) // self.cfg.kv_tile_n + k_scale_next = self._vc_k_scales.fill( + stage_info, self.vc_k_scale, kv_head, k_base, num_tiles + ) + sums = cutlass.Array( + Float32, VC_MEAN_GROUP_TILES, space=cutlass.AddressSpace.rmem + ) + for i in cutlass.range_constexpr(VC_MEAN_GROUP_TILES): + sums[i] = Float32(0.0) + return (row_scale, Float32(0.0), sums, Float32(0.0), k_scale_next) + + @cute.jit + def _vc_coords(self, stage_info: StageInfo) -> tuple[Int32, Int32, Int32]: + """Return ``(batch, head, q_row)`` of this softmax thread's row.""" + seq_coord, head_coord, batch_coord = _resolve_work_tile_coords( + self.cfg, stage_info.work_tile.tile_idx + ) + warp_id_in_sg = cute.arch.warp_idx() % len(self.cfg.softmax0_warp_ids) + row_in_tile = warp_id_in_sg * cute.arch.WARP_SIZE + cute.arch.lane_idx() + row = ( + seq_coord * self.cfg.q_tile_m * self.cfg.work_tile_q_seq_tiles + + self.q_half * self.cfg.peer_q_seq_tile_stride * self.cfg.q_tile_m + + row_in_tile + ) + head = head_coord * self.cfg.work_tile_q_heads + return batch_coord, head, row + + @property + def _vc_k_scales(self) -> VCKScaleTable: + """This softmax group's staged ``sfK`` table (see ``vc_scales``).""" + return VCKScaleTable(self.cfg, self.smem_p, self.q_half) + + @consumer_work(returns=(old_row_max, row_max, vc_k_scale_next)) + @cute.jit + def vc_compute_row_max( + self, + stage_info: StageInfo, + *, + row_max: SoftmaxScalar, + vc_row_scale: SoftmaxScalar, + vc_k_scale_next: SoftmaxScalar, + ) -> tuple[SoftmaxScalar, SoftmaxScalar, Float32]: + """VC-Attention K-loop row max in log2 units. Under QK8 the tile maximum is + scaled by ``vc_row_scale * sfK[tile]`` (prefetched) and the next tile's + ``sfK`` is read.""" + tile_scale = vc_row_scale + k_scale_after = vc_k_scale_next + if cutlass.const_expr(self.cfg.vc_qk8): + k_scale_after = self._vc_k_scales.next_scale( + stage_info, Int32(stage_info.loop_offset) + ) + tile_scale = vc_row_scale * vc_k_scale_next + if cutlass.const_expr(self.cfg.uses_ldtm_stat): + old_row_max, new_row_max = self._load_s_chunks_and_reduce_row_max( + stage_info, row_max, tile_scale=tile_scale + ) + else: + s_data = self._load_s_chunks(stage_info) + old_row_max, new_row_max = self._reduce_row_max(s_data, row_max, tile_scale) + return old_row_max, new_row_max, k_scale_after + + @consumer_work(returns=(old_row_max, row_max)) + @cute.jit + def vc_fixed_dense_k_tail_masked_row_max( + self, + stage_info: StageInfo, + *, + row_max: SoftmaxScalar, + vc_row_scale: SoftmaxScalar, + vc_k_scale_next: SoftmaxScalar, + ) -> tuple[SoftmaxScalar, SoftmaxScalar]: + """VC-Attention dense tail: mask the zero-filled lanes of the partial last + K/V tile before the row max; under QK8 the tile's prefetched ``sfK`` scales it.""" + tmem_x = self.cfg.tmem_x_load_s + num_chunks = self.cfg.qk_mma_tiler[1] // tmem_x + tile_scale = vc_row_scale + if cutlass.const_expr(self.cfg.vc_qk8): + tile_scale = vc_row_scale * vc_k_scale_next + s_data = self._load_s_chunks(stage_info) + neg_inf = cutlass.vector.full( + [tmem_x], + self.cfg.qk_acc_dtype(-Float32.inf), + dtype=self.cfg.qk_acc_dtype, + ) + for chunk_idx in cutlass.range_constexpr(num_chunks): + valid_in_chunk = cute.math.min( + cute.math.max( + Int32(self.cfg.fixed_dense_k_tail) - Int32(chunk_idx * tmem_x), + Int32(0), + ), + Int32(tmem_x), + ) + mask = cutlass.vector.create_mask([tmem_x], [valid_in_chunk]) + s_data[chunk_idx] = cutlass.vector.where(mask, s_data[chunk_idx], neg_inf) + return self._reduce_row_max(s_data, row_max, tile_scale) + @cute.jit def _init_work_tile_state(self, stage_info: StageInfo) -> None: """Reset softmax state and recompute per-warp TMEM addresses each tile. @@ -3157,8 +3486,14 @@ def _reduce_row_max( self, s_data: SoftmaxChunks, row_max: SoftmaxScalar, + tile_scale: SoftmaxScalar | None = None, ) -> tuple[SoftmaxScalar, SoftmaxScalar]: - """Reduce per-chunk maximums into row_max, stash s_data.""" + """Reduce per-chunk maximums into row_max, stash s_data. + + VC-Attention passes ``tile_scale``: the raw tile maximum is scaled into + log2 units (the scale is positive, so max commutes with it) before the + running maximum merge, and the scale is stashed for ``exp2_p``. + """ tmem_x = self.cfg.tmem_x_load_s num_chunks = self.cfg.qk_mma_tiler[1] // tmem_x old_row_max = row_max @@ -3192,6 +3527,9 @@ def _reduce_row_max( row_values += (s_data[chunk_idx][elem_idx],) row_vector = cutlass.Vector.from_elements(row_values, self.cfg.qk_acc_dtype) tile_row_max = row_vector.reduce("max") + if cutlass.const_expr(self.cfg.vc_attention): + tile_row_max = tile_row_max * tile_scale + _tmem_sp_tile_scale[id(self)] = tile_scale row_max = cute.math.max(row_max, tile_row_max) _tmem_sp_sdata[id(self)] = s_data row_max_safe = row_max @@ -3207,6 +3545,7 @@ def _load_s_chunks_and_reduce_row_max( *, causal_loop_mask: cutlass.Constexpr[bool] = False, q_offset: Int32 = 0, + tile_scale: SoftmaxScalar | None = None, ) -> tuple[SoftmaxScalar, SoftmaxScalar]: """LDTM.STAT: fuse S load and per-chunk row_max via tcgen05.ld.red.max. @@ -3215,6 +3554,10 @@ def _load_s_chunks_and_reduce_row_max( reduction happens as part of the TMEM load. For causal loop masking, only tiles crossing the runtime right bound need a software reduction of masked scores; wholly visible tiles retain the hardware maximum. + + VC-Attention keeps the row max in log2 units. ``tile_scale`` is + the softmax scale, applied to the hardware tile maximum before the + merge and carried to ``exp2_p`` like the loaded S chunks. """ tmem_s_addr = self.tmem_s_addr_cached + self._stage_col_offset(stage_info) tmem_x = self.cfg.tmem_x_load_s @@ -3233,6 +3576,9 @@ def _load_s_chunks_and_reduce_row_max( tile_max = cutlass.Vector.from_elements( chunk_maxima, self.cfg.qk_acc_dtype ).reduce("max") + if cutlass.const_expr(self.cfg.vc_attention): + tile_max = tile_max * tile_scale + _tmem_sp_tile_scale[id(self)] = tile_scale row_max = cute.math.max(row_max, tile_max) if cutlass.const_expr(causal_loop_mask): seq_coord, _, _ = _resolve_work_tile_coords( @@ -3303,6 +3649,9 @@ def _exp2_p_store( partial = chunk_lo > 0 or chunk_hi < num_chunks p_packing_ratio = self.cfg.qk_acc_dtype.width // self.cfg.v_dtype.width scale = scale_softmax_log2 + if cutlass.const_expr(self.cfg.vc_attention): + # The row-max pass kept row_max in log2 units of the scaled scores. + scale = _tmem_sp_tile_scale.pop(id(self)) if cutlass.const_expr(not partial and self.cfg.uses_d256_fp8_softmax_cadence): return self._exp2_p_store_d256_fp8_cadence( tmem_p_addr, @@ -3322,6 +3671,10 @@ def _exp2_p_store( dtype=self.cfg.v_dtype, ) p_scale_log2 = Float32(self.cfg.pv_p_scale_log2) + if cutlass.const_expr(self.cfg.vc_attention): + # The paper's 2^8 P scaling is part of VC_EXPCAST_CODE_BIAS, so + # p_scale_log2 is not added here. + return self._exp2_p_store_expcast(scale, Float32(0.0) - row_max) minus_row_max_scale = (Float32(0.0) - row_max) * scale + p_scale_log2 if cutlass.const_expr(chunk_hi < num_chunks): # A later range reads the same S data. @@ -3469,6 +3822,55 @@ def _exp2_p_store( result.append(s_data[chunk_idx]) return result + @cute.jit + def _exp2_p_store_expcast( + self, scale: SoftmaxScalar, minus_row_max_scale: SoftmaxScalar + ) -> Float32: + """VC-Attention ExpCast-FP8 P with one packed FFMA per element. + + ``code = 8 * (s * scale - m) + VC_EXPCAST_CODE_BIAS`` + + Packed P words go to ``store_p``. Returns the tile row sum of the + quantized P. + """ + assert self.cfg.p_in_smem and self.enable_early_tile_sum + tmem_x = self.cfg.tmem_x_load_s + num_chunks = self.cfg.qk_mma_tiler[1] // tmem_x + # The exact per-tile row max keeps u <= 0, so codes stay at or below + # the code bias. + code_scale = scale * Float32(E4M3_CODES_PER_OCTAVE) + code_bias = minus_row_max_scale * Float32(E4M3_CODES_PER_OCTAVE) + Float32( + VC_EXPCAST_CODE_BIAS + ) + s_data = _tmem_sp_sdata.pop(id(self)) + packed_words: tuple[Any, ...] = () + acc: list[Any] = [Int32(0)] * 4 + for chunk_idx in cutlass.range_constexpr(num_chunks): + for elem_idx in cutlass.range_constexpr(0, tmem_x, 4): + quad_idx = (chunk_idx * tmem_x + elem_idx) // 4 + chain = 2 * (quad_idx % 2) + c0, c1 = cute.arch.fma_packed_f32x2( + (s_data[chunk_idx][elem_idx], s_data[chunk_idx][elem_idx + 1]), + (code_scale, code_scale), + (code_bias, code_bias), + ) + c2, c3 = cute.arch.fma_packed_f32x2( + ( + s_data[chunk_idx][elem_idx + 2], + s_data[chunk_idx][elem_idx + 3], + ), + (code_scale, code_scale), + (code_bias, code_bias), + ) + word, acc_lo, acc_hi = expcast_e4m3_quad_relu( + c0, c1, c2, c3, acc[chain], acc[chain + 1], quad_idx < 2 + ) + acc[chain] = acc_lo + acc[chain + 1] = acc_hi + packed_words += (word,) + _tmem_sp_pwords[id(self)] = packed_words + return f16x2_sum4(acc[0], acc[1], acc[2], acc[3]) + @cute.jit def _store_p_row_smem( self, stage_info: StageInfo, packed_words: tuple[Any, ...] @@ -3498,6 +3900,71 @@ def _store_p_row_smem( chunk_words, alignment=16 ) + @cute.jit + def _vc_rowsum_view(self, stage_info: StageInfo) -> cutlass.Array: + """This group's bf16 row-sum operand: K-major 32-byte rows in 8-row core + matrices (``k`` 0-7 in the first 128 bytes of a group, 8-15 in the next).""" + assert self.smem_p is not None + context = stage_info.context + return cutlass.Array( + context.smem_base.data_ptr() + + self.smem_p._alloc.offset + + self.smem_p.rowsum_tile_offset, + dtype=cutlass.BFloat16, + shape=(self.cfg.vc_rowsum_tile_bytes // 2,), + addrspace=3, + ) + + @cute.jit + def _vc_row_base(self) -> Int32: + """Element offset of this thread's row inside the row-sum operand.""" + warp_id_in_sg = cute.arch.warp_idx() % len(self.cfg.softmax0_warp_ids) + row = Int32(warp_id_in_sg * cute.arch.WARP_SIZE + cute.arch.lane_idx()) + return (row >> Int32(3)) * Int32(128) + (row & Int32(7)) * Int32(8) + + @cute.jit + def _zero_vc_rowsum_row(self, stage_info: StageInfo) -> None: + """Clear this thread's 32-byte row of every row-sum operand once.""" + view = self._vc_rowsum_view(stage_info) + base = self._vc_row_base() + zero = cutlass.BFloat16(0.0) + zeros = cutlass.Vector.from_elements((zero,) * 8, cutlass.BFloat16) + for operand in cutlass.range_constexpr(VC_MEAN_OPERANDS): + row = base + Int32(operand * self.cfg.vc_rowsum_operand_bytes // 2) + view.subview(row).data_ptr().store(zeros, alignment=16) + view.subview(row + Int32(64)).data_ptr().store(zeros, alignment=16) + + @cute.jit + def _store_vc_rowsum_group( + self, stage_info: StageInfo, sums: cutlass.Array + ) -> None: + """Write the group's row sums as bf16 hi/lo pairs: tile ``8o+i`` in K slots + ``2i``, ``2i+1`` of operand ``o``, as one 16-byte store per core matrix + (slots 0-7 in the first, 8-15 in the next). + + The split truncates and the low half carries the remainder, so each + pair is exact to 2^-16 and runs on the integer pipe. + """ + view = cutlass.Array( + self._vc_rowsum_view(stage_info).data_ptr(), + dtype=Int32, + shape=(self.cfg.vc_rowsum_tile_bytes // 4,), + addrspace=3, + ) + base = self._vc_row_base() >> Int32(1) + tiles_per_operand = VC_MEAN_MMA_K // 2 + for operand in cutlass.range_constexpr(VC_MEAN_OPERANDS): + words = [ + split_bf16_hi_lo_word(sums[operand * tiles_per_operand + i]) + for i in range(tiles_per_operand) + ] + row = base + Int32(operand * self.cfg.vc_rowsum_operand_bytes // 4) + for half in cutlass.range_constexpr(2): + vec = cutlass.Vector.from_elements( + tuple(words[half * 4 : half * 4 + 4]), Int32 + ) + view.subview(row + Int32(half * 32)).data_ptr().store(vec, alignment=16) + @cute.jit def _exp2_p_store_d128_fp8_cadence( self, @@ -3819,8 +4286,6 @@ def fixed_dense_k_tail_masked_row_max( ``section=Tail``: called once for the last tile, mask always applied. ``section=Loop``: used in loop, masks only on the last iteration. """ - tmem_x = self.cfg.tmem_x_load_s - num_chunks = self.cfg.qk_mma_tiler[1] // tmem_x s_data = self._load_s_chunks(stage_info) if cutlass.const_expr(section == FmhaStage.Tail): @@ -3828,6 +4293,8 @@ def fixed_dense_k_tail_masked_row_max( else: is_tail_tile = stage_info.loop_offset == stage_info.loop_end - Int32(1) if is_tail_tile: + tmem_x = self.cfg.tmem_x_load_s + num_chunks = self.cfg.qk_mma_tiler[1] // tmem_x neg_inf = cutlass.vector.full( [tmem_x], self.cfg.qk_acc_dtype(-Float32.inf), @@ -4044,6 +4511,114 @@ def store_p(self, stage_info: StageInfo) -> None: space=prims.SharedSpace.shared_cta, ) + @consumer_work( + returns=( + vc_prev_tile_sum, + row_sum, + vc_meansums, + ) + ) + @cute.jit + def vc_store_p( + self, + stage_info: StageInfo, + *, + old_row_max: SoftmaxScalar, + row_max: SoftmaxScalar, + row_sum: SoftmaxScalar, + vc_prev_tile_sum: SoftmaxScalar, + p_chunk: SoftmaxRowSumContribution, + vc_meansums: cutlass.Array, + is_tail: cutlass.Constexpr[bool] = False, + ) -> tuple[Float32, ...]: + """VC-Attention P store. Writes the P row, rescales the group row sums + by this tile's max correction and slots in the previous tile's sum. Every + 8th tile writes the completed group operand under the same P-ready + handoff. Returns this tile's sum, the updated row sum and the group sums. + """ + self._store_p_row_smem(stage_info, _tmem_sp_pwords.pop(id(self))) + acc_scale = cute.math.exp2(old_row_max - row_max, fastmath=True) + # The peeled tail entry carries the loop offset of the previous tile. + if cutlass.const_expr(is_tail): + tile = Int32(stage_info.loop_end) + else: + tile = Int32(stage_info.loop_offset) + slot = (tile - Int32(1)) & Int32(VC_MEAN_GROUP_TILES - 1) + new_sum = vc_prev_tile_sum * acc_scale + for i in cutlass.range_constexpr(VC_MEAN_GROUP_TILES): + scaled = vc_meansums[i] * acc_scale + if slot == Int32(i): + scaled = new_sum + vc_meansums[i] = scaled + keep = Float32(1.0) + if ((tile & Int32(VC_MEAN_GROUP_TILES - 1)) == Int32(0)) & (tile > Int32(0)): + self._store_vc_rowsum_group(stage_info, vc_meansums) + keep = Float32(0.0) + prims.fence_proxy( + kind=prims.Proxy.ASYNC_SHARED, + space=prims.SharedSpace.shared_cta, + ) + for i in cutlass.range_constexpr(VC_MEAN_GROUP_TILES): + vc_meansums[i] = vc_meansums[i] * keep + return (p_chunk, row_sum * acc_scale + p_chunk, vc_meansums) + + @consumer_work(returns=(vc_kept_row_sum, row_sum)) + @cute.jit + def vc_store_p_repair( + self, + stage_info: StageInfo, + *, + old_row_max: SoftmaxScalar, + row_max: SoftmaxScalar, + row_sum: SoftmaxScalar, + vc_kept_row_sum: SoftmaxScalar, + p_chunk: SoftmaxRowSumContribution, + is_tail: cutlass.Constexpr[bool] = False, + ) -> tuple[Float32, Float32]: + """VC-Attention V repair P store. The last ``vc_repair_tiles`` of the + loop domain stay out of the kept row sum that normalizes the output.""" + self._store_p_row_smem(stage_info, _tmem_sp_pwords.pop(id(self))) + prims.fence_proxy( + kind=prims.Proxy.ASYNC_SHARED, + space=prims.SharedSpace.shared_cta, + ) + acc_scale = cute.math.exp2(old_row_max - row_max, fastmath=True) + kept_chunk = p_chunk + if cutlass.const_expr(not is_tail): + first_repair = Int32(stage_info.loop_end) - Int32(self.vc_repair_tiles) + if Int32(stage_info.loop_offset) >= first_repair: + kept_chunk = Float32(0.0) + return ( + vc_kept_row_sum * acc_scale + kept_chunk, + row_sum * acc_scale + p_chunk, + ) + + @consumer_work + @cute.jit + def vc_store_rowsum_final( + self, + stage_info: StageInfo, + *, + vc_prev_tile_sum: SoftmaxScalar, + vc_meansums: cutlass.Array, + ) -> None: + """VC-Attention: slot the last tile's row sum into its group and + store the group operands for the tail mean step.""" + last_tile = Int32(stage_info.loop_end) + if cutlass.const_expr(not self.uses_fixed_dense_k_tail_mask): + last_tile = last_tile - Int32(1) + slot = last_tile & Int32(VC_MEAN_GROUP_TILES - 1) + for i in cutlass.range_constexpr(VC_MEAN_GROUP_TILES): + value = vc_meansums[i] + if slot == Int32(i): + value = vc_prev_tile_sum + vc_meansums[i] = value + self._store_vc_rowsum_group(stage_info, vc_meansums) + prims.fence_proxy( + kind=prims.Proxy.ASYNC_SHARED, + space=prims.SharedSpace.shared_cta, + ) + @consumer_work(returns=p_chunk) @cute.jit def exp2_p( @@ -4336,6 +4911,9 @@ def softmax_aux_reduce( ) -> SoftmaxScalar: """Accumulate row_sum from vector P fragments or their scalar sum.""" _ = stage_info + if cutlass.const_expr(self.cfg.vc_attention): + # VC-Attention keeps the row max in log2 units. + scale_softmax_log2 = Float32(1.0) if cutlass.const_expr(self.enable_early_tile_sum): acc_scale = cute.math.exp2( scale_softmax_log2 * (old_row_max - row_max), @@ -4376,6 +4954,9 @@ def freeze_row_max( _ = stage_info threshold = Float32(self.cfg.corr_skip_threshold_log2) frozen = row_max + if cutlass.const_expr(self.cfg.vc_attention): + # VC-Attention keeps the row max in log2 units. + scale_softmax_log2 = Float32(1.0) if (row_max - old_row_max) * scale_softmax_log2 <= threshold: frozen = old_row_max return frozen @@ -4650,6 +5231,9 @@ def init_read_state(self, stage_info: StageInfo) -> None: def load_scale_softmax_log2(self, stage_info: StageInfo) -> Float32: """Load the runtime softmax scale once before the correction loop.""" _ = stage_info + if cutlass.const_expr(self.cfg.vc_attention): + # VC-Attention softmax publishes row maxima already in log2 units. + return Float32(1.0) if cutlass.const_expr(self.scale_softmax_log2 is None): # Safe fallback for validation-only resource construction. return Float32(0.0) @@ -4663,6 +5247,10 @@ def load_output_scale(self, stage_info: StageInfo) -> Float32: if cutlass.const_expr(self.output_scale is None): # Identity fallback for validation-only resource construction. return Float32(1.0) + if cutlass.const_expr(self.cfg.vc_attention): + # VC-Attention: output_scale is the per-(batch, head, channel) V + # residual scale table, applied per column in SmemOResource._store_o. + return Float32(1.0) return self.output_scale[0] @cute.jit @@ -4870,6 +5458,16 @@ class TmemOResource(MemoryResource): tmem_addr_cached: TmemAddr | None = field(init=False, default=None) # Precomputed TMEM raw pointer (inttoptr of tmem_addr_cached). tmem_ptr_raw_cached: TmemPtr | None = field(init=False, default=None) + # VC-Attention mean step state, set once per kernel in the prologue. + # Whether this CTA issues the mean UMMA. Under two-CTA UMMA only the leader + # CTA of the pair issues, so this is block_idx_in_cluster() == 0 made warp + # uniform; otherwise it is True. + vc_mean_issue_cached: Any | None = field(init=False, default=None) + # SMEM descriptors of the two row-sum A operands of the mean step, one per + # UMMA step of a tile group. + vc_desc_l_cached: Any | None = field(init=False, default=None) + # UMMA instruction descriptor of the bf16 K=16 mean step. + vc_idesc_mu_cached: Any | None = field(init=False, default=None) # Precomputed per-warp TMEM O address base: (row_id << 16) | tmem_base_col. # consumer_work adds tmem_o_offset to get the final O0/O1 address. tmem_o_addr_base_cached: TmemAddr | None = field(init=False, default=None) @@ -4943,6 +5541,24 @@ def _init_function_state(self, stage_info: StageInfo) -> None: self.tmem_addr_cached, cutlass.Int8 ) self.tmem_o_addr_base_cached = Int32(0) + if cutlass.const_expr(self.cfg.vc_restores_means): + issue = cutlass.Boolean(True) + if cutlass.const_expr(self.cfg.two_cta_umma): + issue = ( + cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) == 0 + ) + self.vc_mean_issue_cached = issue + self.vc_desc_l_cached = tuple( + self._vc_rowsum_desc(stage_info, smem_p) + for smem_p in (self.smem_p0_resource, self.smem_p1_resource) + ) + self.vc_idesc_mu_cached = prims.Tcgen05InstrDesc.build( + c_dtype=cutlass.Float32, + a_dtype=cutlass.BFloat16, + b_dtype=cutlass.BFloat16, + n_dim=self.cfg.pv_mma_tiler[1], + m_dim=self.cfg.pv_mma_tiler[0] * self.cfg.cta_group_size, + ) self.tmem_p_base_cached = Int32(0) _ = stage_info @@ -4997,6 +5613,68 @@ def pv_mma( inst_idx: cutlass.Constexpr[int] = 0, is_tail: cutlass.Constexpr[bool] = False, k_half: cutlass.Constexpr[int | None] = None, + ) -> None: + """PV MMA: P*V -> O (double-buffered O0/O1). See ``_pv_mma_impl``.""" + self._pv_mma_impl( + stage_info, + desc_v_base=desc_v_base, + section=section, + head_dim_stage_idx=head_dim_stage_idx, + inst_idx=inst_idx, + is_tail=is_tail, + k_half=k_half, + ) + + @producer_work + @cute.jit + def vc_mean_mma( + self, + stage_info: StageInfo, + *, + desc_mu_base: prims.Tcgen05SmemDesc, + inst_idx: cutlass.Constexpr[int] = 0, + is_tail: cutlass.Constexpr[bool] = False, + ) -> None: + """VC-Attention: ``O += sum_i rowsum(P_i) * mean_i`` over the 16 tiles + before this one for query group ``inst_idx``, two bf16 K=16 UMMA steps + after that group's PV steps every 16th tile. At tile i this adds the + group that ended at tile i - 1, so the loop never adds the last group. + The tail call adds it with the operand loaded after the loop.""" + if cutlass.const_expr(is_tail): + tile = Int32(stage_info.loop_end) + else: + tile = Int32(stage_info.loop_offset) + group_done = ((tile & Int32(VC_MEAN_GROUP_TILES - 1)) == Int32(0)) & ( + tile > Int32(0) + ) + self._vc_mean_mma( + inst_idx, desc_mu_base, self.vc_mean_issue_cached & group_done + ) + + @producer_work + @cute.jit + def vc_mean_mma_last( + self, + stage_info: StageInfo, + *, + desc_mu_last: prims.Tcgen05SmemDesc, + inst_idx: cutlass.Constexpr[int] = 0, + ) -> None: + """Tail variant of ``vc_mean_mma``. Adds the last group, the only one with + no loop tile after it, from the operand the loader fetched after the loop.""" + self._vc_mean_mma(inst_idx, desc_mu_last, self.vc_mean_issue_cached) + + @cute.jit + def _pv_mma_impl( + self, + stage_info: StageInfo, + *, + desc_v_base: prims.Tcgen05SmemDesc, + section: cutlass.Constexpr[FmhaStage], + head_dim_stage_idx: cutlass.Constexpr[int] = 0, + inst_idx: cutlass.Constexpr[int] = 0, + is_tail: cutlass.Constexpr[bool] = False, + k_half: cutlass.Constexpr[int | None] = None, ) -> None: """PV MMA: P*V -> O (double-buffered O0/O1). @@ -5251,6 +5929,74 @@ def pv_mma( ) scale_d_stage = True + def _vc_mean_cta_group(self): + """cta_group::2 under two-CTA UMMA (M=256 over both CTAs' row sums).""" + if self.cfg.two_cta_umma: + return prims.CTAGroup.CTA_2 + return prims.CTAGroup.CTA_1 + + @cute.jit + def _vc_rowsum_desc( + self, stage_info: StageInfo, smem_p: SmemPResource + ) -> prims.Tcgen05SmemDesc: + """K-major descriptor of a query group's row-sum operands (A of the mean steps).""" + sL = cutlass.Array( + stage_info.context.smem_base.data_ptr() + + smem_p._alloc.offset + + smem_p.rowsum_tile_offset, + dtype=cutlass.Int8, + shape=(self.cfg.vc_rowsum_tile_bytes,), + addrspace=3, + ) + return freeze_smem_descriptor( + prims.Tcgen05SmemDesc.build( + sL, + leading_byte_offset=VC_MEAN_TILE_LBO, + stride_byte_offset=VC_MEAN_TILE_SBO, + layout=prims.Tcgen05SmemSwizzle.NONE, + ) + ) + + @cute.jit + def _vc_mean_mma( + self, + inst_idx: cutlass.Constexpr[int], + desc_mu_base: prims.Tcgen05SmemDesc, + issue_mma: Any, + ) -> None: + """Issue ``O += sum_i rowsum(P_i) * mean_i`` for query group ``inst_idx`` as + ``VC_MEAN_OPERANDS`` bf16 K=16 UMMA steps back to back. + + A is the query group's row-sum operands behind its P tile, B the + TMA-staged mean operands of the tile group. + """ + if issue_mma: + if prims.elect_sync(): + if cutlass.const_expr(inst_idx == 0): + tmem_ptr_o = self.tmem_ptr_raw_cached.subview(self.tmem_o0_offset) + else: + tmem_ptr_o = self.tmem_ptr_raw_cached.subview(self.tmem_o1_offset) + desc_l = self.vc_desc_l_cached[inst_idx] + desc_mu = freeze_smem_descriptor(desc_mu_base) + for operand in cutlass.range_constexpr(VC_MEAN_OPERANDS): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F16, + self._vc_mean_cta_group(), + tmem_ptr_o, + desc_l + ((operand * self.cfg.vc_rowsum_operand_bytes) >> 4), + desc_mu + + ( + ( + operand + * self.cfg.vc_mean_operand_bytes + // self.cfg.cta_group_size + ) + >> 4 + ), + self.vc_idesc_mu_cached, + True, + ) + @consumer_work @cute.jit def correct( @@ -5545,6 +6291,23 @@ def _store_o( tidx, _, _ = cute.arch.thread_idx() tid_in_wg = tidx % (cute.arch.WARP_SIZE * num_correction_warps) + vc_scale_row = Int64(0) + if cutlass.const_expr(self.cfg.vc_attention): + # Start of this batch and head row in the per-channel V scale table. + assert self.tmem_vec_resource is not None + assert self.tmem_vec_resource.output_scale is not None + assert self.cfg.work_tile_q_heads == 1 + vc_scale = self.tmem_vec_resource.output_scale + _, head_coord_wt, batch_coord = _resolve_work_tile_coords( + self.cfg, stage_info.work_tile.tile_idx + ) + vc_scale_row = vc_scale.iterator.toint() + Int64( + cute.crd2idx( + (batch_coord, head_coord_wt * self.cfg.work_tile_q_heads, 0), + vc_scale.layout, + ) + ) * Int64(4) + o_head_dim = self.cfg.epi_tile[1] tma_copy_o_iters = self.cfg.tma_copy_o_iters if cutlass.const_expr(self.cfg.stage_o_by_head_dim): @@ -5580,6 +6343,14 @@ def _store_o( scale_vec = cutlass.vector.full_like(o_rmem, scale) o_rmem = o_rmem * scale_vec + if cutlass.const_expr(self.cfg.vc_attention): + # The tile means were stored divided by the per-channel V scale, + # so the whole accumulator is rescaled by it here. + col0 = head_dim_stage_idx * o_head_dim + i * tmem_x + chan_scale = cutlass.inttoptr( + vc_scale_row + Int64(col0) * Int64(4), mem_space=1, dtype=Float32 + ).load(count=tmem_x, alignment=64) + o_rmem = o_rmem * chan_scale o_rmem_dtype = o_rmem.to(self.cfg.o_dtype) diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_tasks.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_tasks.py index 2e2d8581378e..6c14daea4054 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_tasks.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/fmha_tasks.py @@ -59,6 +59,7 @@ TmemStatsDoneResource, TmemPPrefixReadyResource, ) +from .vc_attention.vc_resources import SmemMuResource @dataclass(kw_only=True) @@ -188,10 +189,14 @@ def create_load_task( task_class: type[Task] = Task, smem_page_offsets_kv: SmemPageOffsetsKvResource | None = None, smem_page_offsets_v: SmemPageOffsetsKvResource | None = None, + smem_mu: SmemMuResource | None = None, **task_kwargs: Any, ) -> Task: """Create the one-warp TMA load task. + ``smem_mu`` (VC-Attention) stages one bf16 tile-mean operand per K/V tile + beside V. + When ``smem_page_offsets_kv`` is provided, each K/V TMA load consumes page IDs prefetched by the auxiliary warp through the ordinary asynchronous page-offset pipeline. @@ -205,6 +210,8 @@ def create_load_task( raise ValueError("split K/V staging requires a separate V buffer") kv_resources = (smem_k_or_kv, smem_v) if split_kv else (smem_k_or_kv,) dst = [smem_q, *kv_resources] + if smem_mu is not None: + dst.append(smem_mu) if smem_page_offsets_kv is not None: src.append(smem_page_offsets_kv) if smem_page_offsets_v is not None: @@ -652,11 +659,14 @@ def load_schedule_body( sk: SmemKVResource, sv: SmemKVResource, wq: WorkQueue | None, + smu: SmemMuResource | None = None, ) -> None: """Load paired Q instances and their directly addressed K/V tiles.""" sq.init_load_state() sk.init_load_state() sv.init_load_state() + if smu is not None: + smu.init_load_state() with _work_tile_schedule_loop(wq, skip_if=skip_work_tile_if): # noqa: SIM117 # The first K-loop iteration also loads Q0/Q1. Later iterations # only stream the next K/V tiles through their respective pipelines. @@ -758,6 +768,68 @@ def load_schedule_body( kv_page_idx_ub=kv_page_idx_ub, ) sv.commit() + if smu is not None: + # VC-Attention: the mean operand of tile i-1 rides beside V_i. + smu.try_acquire() + smu.acquire() + smu.mu_load( + kv_head_coord=kv_head_coord, + batch_coord=batch_coord, + kv_tile_start=kv_tile_start, + ) + smu.commit() + if smu is not None: + # The loop step at tile i adds the means of the group that ended + # at tile i - 1, so the loop covers groups 0 .. N - 2 and the + # group of the last tile never meets a following loop tile. Its + # operand is fetched once more here for the tail mean step. + ( + _seq_coord, + _head_coord, + kv_head_coord, + _head_coord_kv, + batch_coord, + _seq_coord_q, + _cuseqlen_q, + _cuseqlen_k, + _seqlen_q, + _seqlen_k, + kv_tile_start, + _kv_request_begin, + _kv_page_idx_ub, + ) = gqkv.compute_coords() + smu.try_acquire() + smu.acquire() + smu.mu_load( + kv_head_coord=kv_head_coord, + batch_coord=batch_coord, + kv_tile_start=kv_tile_start, + is_tail=True, + ) + smu.commit() + + @schedule + def load_schedule_mu( + gqkv: GmemQKVResource, + sq: SmemQResource, + skv: SmemKVResource, + smu: SmemMuResource, + wq: WorkQueue | None = None, + ) -> None: + """Shared K/V buffer plus the VC-Attention tile-mean ring.""" + load_schedule_body(gqkv, sq, skv, skv, wq, smu) # type: ignore[call-arg] + + @schedule + def load_split_schedule_mu( + gqkv: GmemQKVResource, + sq: SmemQResource, + sk: SmemKVResource, + sv: SmemKVResource, + smu: SmemMuResource, + wq: WorkQueue | None = None, + ) -> None: + """Split K and V buffers plus the VC-Attention tile-mean ring.""" + load_schedule_body(gqkv, sq, sk, sv, wq, smu) # type: ignore[call-arg] @schedule def load_schedule( @@ -781,13 +853,23 @@ def load_split_schedule( """Contiguous-KV captured schedule over split K and V buffers.""" load_schedule_body(gqkv, sq, sk, sv, wq) # type: ignore[call-arg] - captured_schedule = _schedule_with_work_queue( - load_split_schedule if split_kv else load_schedule, - gmem_qkv, - smem_q, - *kv_resources, - work_queue=work_queue, - ) + if smem_mu is not None: + captured_schedule = _schedule_with_work_queue( + load_split_schedule_mu if split_kv else load_schedule_mu, + gmem_qkv, + smem_q, + *kv_resources, + smem_mu, + work_queue=work_queue, + ) + else: + captured_schedule = _schedule_with_work_queue( + load_split_schedule if split_kv else load_schedule, + gmem_qkv, + smem_q, + *kv_resources, + work_queue=work_queue, + ) return task_class( src_resources=src, dst_resources=dst, @@ -817,9 +899,14 @@ def create_mma_task( tmem_p_prefix_ready_1: TmemPPrefixReadyResource | None = None, smem_p0: SmemPResource | None = None, smem_p1: SmemPResource | None = None, + smem_mu: SmemMuResource | None = None, **task_kwargs: Any, ) -> Task: - """Create the one-warp MMA compute task.""" + """Create the one-warp MMA compute task. + + ``smem_mu`` (VC-Attention) supplies the bf16 tile-mean operand consumed by + one extra ``kind::f16`` step after each tile's PV steps. + """ loop_start, loop_end, loop_step = _captured_loop_bounds(task_class, task_kwargs) skip_work_tile_if = _packed_context_skip_predicate(work_queue) # Only paged MMA schedules read request coordinates from global metadata. @@ -840,12 +927,14 @@ def create_mma_task( if p_in_smem and (smem_p0 is None or smem_p1 is None): raise ValueError("p_in_smem requires both SMEM P resources") smem_p_resources = (smem_p0, smem_p1) if p_in_smem else () + mu_resources = (smem_mu,) if smem_mu is not None else () src = _src_resources( *qkv_resources, smem_q, *kv_resources, *p_prefix_resources, *smem_p_resources, + *mu_resources, work_queue=work_queue, ) num_head_dim_stages_k = smem_k_or_kv.cfg.num_head_dim_stages_k @@ -1285,8 +1374,12 @@ def mma_schedule_body( pr1: TmemPPrefixReadyResource | None = None, pb0: SmemPResource | None = None, pb1: SmemPResource | None = None, + smu: SmemMuResource | None = None, ) -> None: """Interleave paired QK/PV while retaining each K slice for both Qs.""" + # VC-Attention: the current tile's mean-operand descriptor, waited and + # released in lockstep with V. + mu_state: dict[str, Any] = {"desc": None} def pv( sp: TmemSPResource, @@ -1301,6 +1394,14 @@ def pv( if p_in_smem: pb.wait() to.pv_mma(inst_idx=group, **kw) + if smu is not None: + # VC-Attention: a group's row sums travel with the P of the + # tile after it, so its mean step follows that tile's PV steps. + to.vc_mean_mma( + inst_idx=group, + desc_mu_base=mu_state["desc"], + is_tail=kw.get("is_tail", False), + ) pb.release() return if pv_half_overlap: @@ -1314,6 +1415,8 @@ def pv( sq.init_descriptor_state() sk.init_descriptor_state() sv.init_descriptor_state() + if smu is not None: + smu.init_descriptor_state() sp0.init_mma_state() sp1.init_mma_state() to.init_mma_state() @@ -1414,6 +1517,17 @@ def wait_next_v() -> Any: ) return sv.v_desc() + def release_mu() -> None: + """Release the mean operand of the tile whose PV steps were issued.""" + if smu is not None: + smu.release() + + def wait_next_mu() -> None: + """Wait for the next tile's mean operand and cache its descriptor.""" + if smu is not None: + smu.wait() + mu_state["desc"] = smu.mu_desc() + if p_in_smem: # With P in SMEM, softmax releases the S stage right after loading # S, so QK(i+1) overlaps exp2(i). The MMA issues QK0(i+1), PV0(i), @@ -1423,6 +1537,8 @@ def wait_next_v() -> Any: sp0.acquire() k_descriptors = qk_mma_stages(sk, sp0, desc_q0_base, FmhaStage.Loop) sp0.commit() + # Wait for the mean operand here, off the QK issue path. + wait_next_mu() to.acquire() pv( sp0, @@ -1449,9 +1565,27 @@ def wait_next_v() -> Any: ) to.commit() sv.release() + release_mu() desc_v_base = wait_next_v() sq.release() sq.release() + if smu is not None: + # The loop issued the mean step of group g at the first tile + # after it, so with N groups it covered 0 .. N - 2. The tail + # O window of each query group adds group N - 1 from the + # operand the loader fetched after the loop. Both ring slots + # are held until then. + wait_next_mu() + smu.wait() + desc_mu_last = smu.mu_desc_last() + + def tail_mean(group: int, pb: Any) -> None: + """Issue the final mean step of ``group`` inside its O window.""" + if smu is not None: + pb.wait() + to.vc_mean_mma_last(inst_idx=group, desc_mu_last=desc_mu_last) + pb.release() + to.acquire() pv( sp0, @@ -1462,6 +1596,7 @@ def wait_next_v() -> Any: section=FmhaStage.Tail, is_tail=True, ) + tail_mean(0, pb0) to.commit() to.acquire() pv( @@ -1473,8 +1608,11 @@ def wait_next_v() -> Any: section=FmhaStage.Tail, is_tail=True, ) + tail_mean(1, pb1) to.commit() sv.release() + release_mu() + release_mu() else: # QK0 -> PV1 -> QK1 -> PV0: retain each K slice and the previous V # until both peer query tiles have consumed the corresponding data. @@ -1635,7 +1773,52 @@ def mma_schedule_pb( gqkv, sq, skv, skv, sp0, sp1, to, vd0, vd1, wq, None, None, pb0, pb1 ) - if p_in_smem: + @schedule + def mma_split_schedule_pb_mu( + gqkv: GmemQKVResource, + sq: SmemQResource, + sk: SmemKVResource, + sv: SmemKVResource, + sp0: TmemSPResource, + sp1: TmemSPResource, + to: TmemOResource, + vd0: TmemStatsDoneResource, + vd1: TmemStatsDoneResource, + pb0: SmemPResource, + pb1: SmemPResource, + smu: SmemMuResource, + wq: WorkQueue | None = None, + ) -> None: + """Split K/V captured schedule with P in SMEM and VC tile means.""" + mma_schedule_body( + gqkv, sq, sk, sv, sp0, sp1, to, vd0, vd1, wq, None, None, pb0, pb1, smu + ) + + @schedule + def mma_schedule_pb_mu( + gqkv: GmemQKVResource, + sq: SmemQResource, + skv: SmemKVResource, + sp0: TmemSPResource, + sp1: TmemSPResource, + to: TmemOResource, + vd0: TmemStatsDoneResource, + vd1: TmemStatsDoneResource, + pb0: SmemPResource, + pb1: SmemPResource, + smu: SmemMuResource, + wq: WorkQueue | None = None, + ) -> None: + """Shared-buffer captured schedule with P in SMEM and VC tile means.""" + mma_schedule_body( + gqkv, sq, skv, skv, sp0, sp1, to, vd0, vd1, wq, None, None, pb0, pb1, smu + ) + + if smem_mu is not None: + selected_mma_schedule = ( + mma_split_schedule_pb_mu if split_kv else mma_schedule_pb_mu + ) + elif p_in_smem: selected_mma_schedule = mma_split_schedule_pb if split_kv else mma_schedule_pb elif pv_half_overlap: selected_mma_schedule = mma_split_schedule_pr if split_kv else mma_schedule_pr @@ -1653,6 +1836,7 @@ def mma_schedule_pb( tmem_vec_done_1, *p_prefix_resources, *smem_p_resources, + *mu_resources, work_queue=work_queue, ) return task_class( @@ -2190,6 +2374,10 @@ def softmax_schedule( if smem_p is None: raise ValueError("p_in_smem requires the group's SMEM P resource") dst.append(smem_p) + vc_attention = tmem_sp.cfg.vc_attention + # VC-Attention V treatment: tile means restored in-kernel, or V repair tiles. + vc_restores_means = tmem_sp.cfg.vc_restores_means + vc_repairs_v = vc_attention and not vc_restores_means def softmax_schedule_body( sp: TmemSPResource, @@ -2208,10 +2396,29 @@ def softmax_schedule_body( p_chunk = sp.init_softmax_state() scale_softmax_log2 = sp.load_scale_softmax_log2() - def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: + # VC-Attention sums the E4M3 probability codes inside the P store, + # so vc_store_p returns the row sum and softmax_aux_reduce is skipped. + vc_state: dict[str, Any] = { + "prev_sum": None, + "row_sum": None, + "sums": None, + "k_next": None, + "kept": None, + } + + def exp2_p( + sp: TmemSPResource, + *, + row_max: Any, + scale_softmax_log2: Any, + old_row_max: Any = None, + is_tail: bool = False, + ) -> Any: """Softmax and P store. With P in SMEM the store goes to the SMEM P tile, with the half overlap the leading half is published behind ``pr``, else P goes - to the TMEM S/P stage.""" + to the TMEM S/P stage. VC-Attention then carries the group row sums + (rescaled to this tile's max) and stores the completed group's operand + for the deferred mean step.""" if p_in_smem: # The S stage is released already, so exp2 and the P store are # auxiliary work on the loaded S and the SMEM P tile. @@ -2219,7 +2426,30 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: row_max=row_max, scale_softmax_log2=scale_softmax_log2 ) pb.acquire() - sp.store_p() + if vc_repairs_v: + out = sp.vc_store_p_repair( + old_row_max=old_row_max, + row_max=row_max, + row_sum=vc_state["row_sum"], + vc_kept_row_sum=vc_state["kept"], + p_chunk=p_chunk, + is_tail=is_tail, + ) + vc_state["kept"], vc_state["row_sum"] = out[0], out[1] + elif vc_restores_means: + out = sp.vc_store_p( + old_row_max=old_row_max, + row_max=row_max, + row_sum=vc_state["row_sum"], + vc_prev_tile_sum=vc_state["prev_sum"], + p_chunk=p_chunk, + is_tail=is_tail, + vc_meansums=vc_state["sums"], + ) + vc_state["prev_sum"], vc_state["row_sum"] = out[0], out[1] + vc_state["sums"] = out[2] + else: + sp.store_p() pb.commit() return p_chunk if not pv_half_overlap: @@ -2236,6 +2466,13 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: # Recompute per-tile SP/Vec TMEM state. old_row_max, row_max, row_sum, q_offset = sp.init_softmax_work_tile_state() vec.init_store_work_tile_state() + vc_state["row_sum"] = row_sum + if vc_attention: + init = sp.vc_init_row_scale() + vc_row_scale, vc_state["prev_sum"] = init[0], init[1] + vc_state["sums"] = init[2] + vc_state["kept"] = init[3] + vc_state["k_next"] = init[4] if tmem_sp.uses_varlen_q_offset_cache: q_offset = sp.cache_q_offset() if tmem_sp.uses_packed_dense_k_mask: @@ -2277,6 +2514,12 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: seqlen_k=seqlen_k, section=FmhaStage.Loop, ) + elif vc_attention: + old_row_max, row_max, vc_state["k_next"] = sp.vc_compute_row_max( + row_max=row_max, + vc_row_scale=vc_row_scale, + vc_k_scale_next=vc_state["k_next"], + ) else: old_row_max, row_max = sp.compute_row_max(row_max=row_max) if tmem_sp.cfg.corr_skip_threshold_log2 > 0: @@ -2317,6 +2560,7 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: sp, row_max=row_max, scale_softmax_log2=scale_softmax_log2, + old_row_max=old_row_max, ) if s0s1_seq is None or early_token: pass @@ -2327,15 +2571,44 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: if not p_in_smem: sp.release() # Reduction. - row_sum = sp.softmax_aux_reduce( + if vc_attention: + row_sum = vc_state["row_sum"] + else: + row_sum = sp.softmax_aux_reduce( + old_row_max=old_row_max, + row_max=row_max, + row_sum=row_sum, + p_chunk=p_chunk, + scale_softmax_log2=scale_softmax_log2, + ) + # Acquire vec for next iter. + vec.acquire() + + def publish_final_stats(row_max: Any, row_sum: Any) -> None: + """Store the last mean-group row sums or take the repair denominator, drain + the final SP slot and publish the identity stats of the work tile.""" + if vc_restores_means: + # The last row sums ride a second P handoff to the tail step. + pb.acquire() + sp.vc_store_rowsum_final( + vc_prev_tile_sum=vc_state["prev_sum"], + vc_meansums=vc_state["sums"], + ) + pb.commit() + elif vc_repairs_v: + # The repair tiles stay out of the denominator. + row_sum = vc_state["kept"] + if not p_in_smem: + sp.wait() + sp.release() + old_row_max = sp.softmax_aux_identity(row_max=row_max) + vec.store_vec( old_row_max=old_row_max, row_max=row_max, row_sum=row_sum, - p_chunk=p_chunk, - scale_softmax_log2=scale_softmax_log2, + final_stats=True, ) - # Acquire vec for next iter. - vec.acquire() + vec.commit() if tmem_sp.uses_head_paired_causal_tail_mask: # Head-paired maps Q0/Q1 to adjacent Hq slices at the same S @@ -2370,13 +2643,16 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: else: seq.release() sp.release() - row_sum = sp.softmax_aux_reduce( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - p_chunk=p_chunk, - scale_softmax_log2=scale_softmax_log2, - ) + if vc_attention: + row_sum = vc_state["row_sum"] + else: + row_sum = sp.softmax_aux_reduce( + old_row_max=old_row_max, + row_max=row_max, + row_sum=row_sum, + p_chunk=p_chunk, + scale_softmax_log2=scale_softmax_log2, + ) vec.acquire() sp.wait() sp.release() @@ -2424,13 +2700,16 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: seq.commit() if not p_in_smem: sp.release() - row_sum = sp.softmax_aux_reduce( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - p_chunk=p_chunk, - scale_softmax_log2=scale_softmax_log2, - ) + if vc_attention: + row_sum = vc_state["row_sum"] + else: + row_sum = sp.softmax_aux_reduce( + old_row_max=old_row_max, + row_max=row_max, + row_sum=row_sum, + p_chunk=p_chunk, + scale_softmax_log2=scale_softmax_log2, + ) if tmem_sp.uses_query_paired_invalid_tail: sp.wait() old_row_max, row_max = sp.invalid_row_max(row_max=row_max) @@ -2497,13 +2776,16 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: seq.release() if not p_in_smem: sp.release() - row_sum = sp.softmax_aux_reduce( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - p_chunk=p_chunk, - scale_softmax_log2=scale_softmax_log2, - ) + if vc_attention: + row_sum = vc_state["row_sum"] + else: + row_sum = sp.softmax_aux_reduce( + old_row_max=old_row_max, + row_max=row_max, + row_sum=row_sum, + p_chunk=p_chunk, + scale_softmax_log2=scale_softmax_log2, + ) if not p_in_smem: sp.wait() sp.release() @@ -2519,10 +2801,17 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: elif tmem_sp.uses_fixed_dense_k_tail_mask: # Dense tail: one more loop step with the zero-filled lanes masked out. sp.wait() - old_row_max, row_max = sp.fixed_dense_k_tail_masked_row_max( - row_max=row_max, - section=FmhaStage.Tail, - ) + if vc_attention: + old_row_max, row_max = sp.vc_fixed_dense_k_tail_masked_row_max( + row_max=row_max, + vc_row_scale=vc_row_scale, + vc_k_scale_next=vc_state["k_next"], + ) + else: + old_row_max, row_max = sp.fixed_dense_k_tail_masked_row_max( + row_max=row_max, + section=FmhaStage.Tail, + ) vec.store_vec( old_row_max=old_row_max, row_max=row_max, @@ -2541,6 +2830,8 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: sp, row_max=row_max, scale_softmax_log2=scale_softmax_log2, + old_row_max=old_row_max, + is_tail=True, ) if s0s1_seq is None: pass @@ -2550,39 +2841,21 @@ def exp2_p(sp: TmemSPResource, *, row_max: Any, scale_softmax_log2: Any) -> Any: seq.release() if not p_in_smem: sp.release() - row_sum = sp.softmax_aux_reduce( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - p_chunk=p_chunk, - scale_softmax_log2=scale_softmax_log2, - ) + if vc_attention: + row_sum = vc_state["row_sum"] + else: + row_sum = sp.softmax_aux_reduce( + old_row_max=old_row_max, + row_max=row_max, + row_sum=row_sum, + p_chunk=p_chunk, + scale_softmax_log2=scale_softmax_log2, + ) vec.acquire() - # Cleanup: drain the final SP slot and publish identity stats. - if not p_in_smem: - sp.wait() - sp.release() - old_row_max = sp.softmax_aux_identity(row_max=row_max) - vec.store_vec( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - final_stats=True, - ) - vec.commit() + publish_final_stats(row_max, row_sum) else: # Non-causal tail: no more tiles, just publish the final stats. - if not p_in_smem: - sp.wait() - sp.release() - old_row_max = sp.softmax_aux_identity(row_max=row_max) - vec.store_vec( - old_row_max=old_row_max, - row_max=row_max, - row_sum=row_sum, - final_stats=True, - ) - vec.commit() + publish_final_stats(row_max, row_sum) @schedule def softmax_schedule( diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/helpers.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/helpers.py index bdaf9790be14..d23f55f1f9c8 100644 --- a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/helpers.py +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/helpers.py @@ -17,7 +17,8 @@ import cutlass import cutlass.cute as cute -from cutlass import Int32, Int64 +from cutlass import Float16, Float32, Int32, Int64, Uint32 +from cutlass.cutlass_dsl import Constexpr @cute.jit @@ -94,3 +95,81 @@ def freeze_smem_descriptor(desc): write_only_types=[Int64], read_only_args=[desc], ) + + +@cute.jit +def split_bf16_hi_lo_word(value: Float32) -> Int32: + """Pack ``value`` as two bf16 halves: low 16 bits = truncated high part, + high 16 bits = truncated remainder ``value - hi``.""" + bits = cutlass.Vector.from_elements((value,), Float32).bitcast(Uint32)[0] + hi_bits = bits >> Uint32(16) + hi = cutlass.Vector.from_elements((hi_bits << Uint32(16),), Uint32).bitcast( + Float32 + )[0] + lo_bits = cutlass.Vector.from_elements((value - hi,), Float32).bitcast(Uint32)[0] + word = hi_bits | (lo_bits & Uint32(0xFFFF0000)) + return cutlass.Vector.from_elements((word,), Uint32).bitcast(Int32)[0] + + +@cute.jit +def expcast_e4m3_quad_relu( + c0: Float32, + c1: Float32, + c2: Float32, + c3: Float32, + acc01: Int32, + acc23: Int32, + init: Constexpr[bool], +) -> tuple[Int32, Int32, Int32]: + """ExpCast four unclamped codes into one packed E4M3 word and accumulate + their values into two f16x2 row-sum registers. + + With ``init`` the quad starts a chain and the accumulators are ignored. The + returned sums are then the quantized values themselves. + + ``c = 8 * (s * scale - m) + VC_EXPCAST_CODE_BIAS`` + + ``cvt.rn.relu.f16x2.f32`` packs a pair and clamps underflow to code 0, an + f16 FMA adds 1024 so the low byte of each half is the rounded code, one + ``prmt`` gathers the four bytes, and the E4M3-pair to f16x2 conversion + with one f16 FMA per pair accumulates the quantized values. + """ + sum_pair = ( + "mov.b32 {$w1}, v01;\n mov.b32 {$w2}, v23;" + if init + else "fma.rn.f16x2 {$w1}, v01, one2, {$r4};\n" + " fma.rn.f16x2 {$w2}, v23, one2, {$r5};" + ) + return cute.arch.inline_ptx( + """ + { + .reg .b32 h01, h23, y01, y23, v01, v23, one2, k1024; + .reg .b16 c01, c23; + mov.b32 one2, 0x3C003C00; + mov.b32 k1024, 0x64006400; + cvt.rn.relu.f16x2.f32 h01, {$r1}, {$r0}; + cvt.rn.relu.f16x2.f32 h23, {$r3}, {$r2}; + fma.rn.f16x2 y01, h01, one2, k1024; + fma.rn.f16x2 y23, h23, one2, k1024; + prmt.b32 {$w0}, y01, y23, 0x6420; + mov.b32 {c01, c23}, {$w0}; + cvt.rn.f16x2.e4m3x2 v01, c01; + cvt.rn.f16x2.e4m3x2 v23, c23; + """ + + sum_pair + + """ + }""", + write_only_types=[Int32, Int32, Int32], + read_only_args=[c0, c1, c2, c3, acc01, acc23], + ) + + +@cute.jit +def f16x2_sum4(a0: Int32, a1: Int32, a2: Int32, a3: Int32) -> Float32: + """fp32 sum of the eight fp16 halves of four f16x2 registers.""" + f = [] + for word in (a0, a1, a2, a3): + halves = cutlass.Vector.from_elements((word,), Int32).bitcast(Float16) + f.append(halves[0].to(Float32)) + f.append(halves[1].to(Float32)) + return ((f[0] + f[1]) + (f[2] + f[3])) + ((f[4] + f[5]) + (f[6] + f[7])) diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/__init__.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/__init__.py new file mode 100644 index 000000000000..76a82805fe5a --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""VC-Attention pieces of the context kernel. + +``vc_resources`` holds the tile-mean operand ring and the ExpCast helpers, +``vc_scales`` the per-block Q/K scale tables of VC-Attention-QK8. +""" diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_resources.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_resources.py new file mode 100644 index 000000000000..7753b1b30b1d --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_resources.py @@ -0,0 +1,258 @@ +# Copyright (c) 2026 by FlashInfer team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""VC-Attention operands and helpers of the context kernel. + +VC-Attention stores E4M3 V as residuals around the bf16 mean of each +128-token K/V tile and restores the mean inside the online softmax with one +bf16 K=16 UMMA step per tile, ``O += rowsum(P_tile) * mean_tile``. +:class:`SmemMuResource` is the TMA-fed ring of the ``mean_tile`` operands. The +ExpCast helpers in ``helpers`` code the probabilities directly as E4M3 bytes +and accumulate the quantized row sums that become the step's A operand. +The resources in ``fmha_resources`` own the row-sum operand (behind the +SMEM P tile), the exp2 and store paths and the mean UMMA issue. +""" + +from ....vc_attention import VC_MEAN_GROUP_TILES, VC_MEAN_OPERANDS +from dataclasses import dataclass, field +from typing import Any, Optional + +import cutlass +import cutlass.cute as cute +from cutlass import Int16, Int32 +from cutlass.cutlass_dsl import Constexpr +from cutlass.experimental import primitives as prims +from cutlass.experimental.task_scheduling.enums import WorkAttr +from cutlass.experimental.task_scheduling.memory import SmemAllocation +from cutlass.experimental.task_scheduling.resources import ( + MemoryResource, + PipelineConfig, + StageInfo, + TaskLocalVariable, + consumer_work, + producer_work, +) + +from ...placeholder_helpers import _placeholder_smem_array + +# VC-Attention mean-restore operands of the bf16 K=16 UMMA step that adds +# ``rowsum(P_tile) * mean_tile`` into O. Unswizzled K-major 32-byte rows with +# LBO 128 between the two K core matrices and SBO 256 between 8-row groups. +VC_MEAN_TILE_LBO = 128 +VC_MEAN_TILE_SBO = 256 + +# ExpCast-FP8 (VC-Attention). An E4M3 byte read as an integer equals +# ``8*log2(v) + 56 + eps``. With ``u`` the log2-domain probability and the +# paper's 2^8 P scaling, ``code = round(8*u + VC_EXPCAST_CODE_BIAS)`` replaces +# exp2 and the E4M3 cast by one FMA. beta is the paper's centering of +# Mitchell's error. +_E4M3_EXP_BIAS = 7 +E4M3_CODES_PER_OCTAVE = 8 +_VC_EXPCAST_BETA = -0.35 +_VC_EXPCAST_P_SCALE_LOG2 = 8 +VC_EXPCAST_CODE_BIAS = ( + E4M3_CODES_PER_OCTAVE * (_E4M3_EXP_BIAS + _VC_EXPCAST_P_SCALE_LOG2) + + _VC_EXPCAST_BETA +) + + +# --------------------------------------------------------------------------- +# SmemMuResource -- VC-Attention bf16 tile-mean operand ring +# --------------------------------------------------------------------------- +@dataclass(kw_only=True) +class SmemMuResource(MemoryResource): + """Shared memory buffer for mu, the paper's name for the per-tile mean of V. + + One buffer holds the bf16 means of a group of sixteen K/V tiles, packed as + K-major UMMA operands. The means are a tensor core B operand and the MMA + instruction reads its operands through shared memory descriptors. They + therefore follow the same path as K and V in SmemKVResource and are staged + into shared memory by TMA with a TmaUmma pipeline. + + Producer: the load warp TMA-loads the operands of the group holding K/V tile + ``i-1`` beside V tile ``i``. Consumer: the UMMA warp issues two + ``kind::f16`` K=16 steps ``O += sum_j rowsum(P_j) * mean_j`` over the group's + tiles after the PV steps of the tile that follows the group, so the means + restored into O are rescaled by the same correction as the residual + product. Rows ``k=2i`` and ``k=2i+1`` of operand ``o`` hold the mean of tile + ``8o+i`` of the group (divided by the V dequant scale). + """ + + cfg: Constexpr[Any] = field(init=False, default=None) + tma_mu_desc: cutlass.Pointer | None = field(init=False, default=None) + sMu_array: cutlass.Array = field(init=False, default=None) + _alloc: Constexpr[Optional[SmemAllocation]] = field(init=False, default=None) + desc_mu_base: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + # Second live handle for the tail, where the last tile's operand is waited + # while the previous tile's is still in use. + desc_mu_last: Constexpr[TaskLocalVariable] = TaskLocalVariable.uninitialized() + + def __init__( + self, + tma_mu_desc: cutlass.Pointer | None, + pipeline_config: PipelineConfig, + cfg: Any, + **kwargs: Any, + ) -> None: + super().__init__(pipeline_config=pipeline_config, **kwargs) + self.cfg = cfg + self.tma_mu_desc = tma_mu_desc + self._alloc = SmemAllocation( + "smem_mu", + pipeline_config.num_stages * cfg.vc_mean_tile_bytes, + alignment=cfg.buffer_align_bytes, + ) + self.sMu_array = _placeholder_smem_array(cutlass.BFloat16) + self.desc_mu_base = TaskLocalVariable( + dtype=cutlass.Int64, + default=cutlass.Int64(0), + docs="SMEM descriptor base for the current tile-mean operand.", + ) + self.desc_mu_last = TaskLocalVariable( + dtype=cutlass.Int64, + default=cutlass.Int64(0), + docs="SMEM descriptor base for the last tile's mean operand.", + ) + + def get_smem_requirements(self) -> list[SmemAllocation]: + return [self._alloc] + + @property + def stage_elements(self) -> int: + return self.cfg.vc_mean_tile_bytes // 2 + + @cute.jit + def _init_smem_state(self, stage_info: StageInfo) -> None: + smem_base = stage_info.context.smem_base + self.sMu_array = cutlass.Array( + smem_base.data_ptr() + self._alloc.offset, + dtype=cutlass.BFloat16, + shape=(self.pipeline_config.num_stages * self.stage_elements,), + addrspace=3, + ) + + @producer_work(work_attrs=WorkAttr.AUXILIARY) + @cute.jit + def init_load_state(self, stage_info: StageInfo) -> None: + self._init_smem_state(stage_info) + + @consumer_work(work_attrs=WorkAttr.AUXILIARY) + @cute.jit + def init_descriptor_state(self, stage_info: StageInfo) -> None: + self._init_smem_state(stage_info) + + @property + def loop_offset_sensitive(self) -> bool: + return True + + @cute.jit + def _tma_load_tile( + self, + stage_info: StageInfo, + tile_idx: Int32, + kv_head_coord: Int32, + batch_coord: Int32, + ) -> None: + if prims.elect_sync(): + operand_rows = self.cfg.vc_mean_operand_bytes // 512 + operand_elems = ( + self.cfg.vc_mean_operand_bytes // self.cfg.cta_group_size // 2 + ) + for operand in cutlass.range_constexpr(VC_MEAN_OPERANDS): + sMu_curr = self.sMu_array.subview( + stage_info.stage_idx * self.stage_elements + operand * operand_elems + ) + row = Int32(operand * operand_rows) + if cutlass.const_expr(self.cfg.two_cta_umma): + # Each CTA stages the 4 packed rows (64 channels) its half of + # the M=256 mean step reads, like K/V. + cta_rank = cute.arch.make_warp_uniform( + cute.arch.block_idx_in_cluster() + ) + prims.cp_async_bulk_tensor_shared_cluster_global( + sMu_curr, + self.tma_mu_desc, + ( + Int32(0), + row + cta_rank * Int32(operand_rows // 2), + tile_idx, + kv_head_coord, + batch_coord, + ), + cutlass.Array( + stage_info.barrier.data_ptr(), dtype=cutlass.Int64 + ), + [], + multicast_mask=Int16(Int32(1) << cta_rank), + group=prims.CTAGroup.CTA_2, + ) + else: + prims.cp_async_bulk_tensor_shared_cta_global( + sMu_curr, + self.tma_mu_desc, + (Int32(0), row, tile_idx, kv_head_coord, batch_coord), + stage_info.barrier, + ) + + @producer_work + @cute.jit + def mu_load( + self, + stage_info: StageInfo, + *, + kv_head_coord: Int32, + batch_coord: Int32, + kv_tile_start: Int32, + is_tail: Constexpr[bool] = False, + ) -> None: + """TMA-load the mean operand of the group holding K/V tile ``loop_offset - 1``. + + A group's mean step is issued one tile late, beside PV of the tile after + the group, so the ring runs one tile behind V. The tail call loads the + group of the last tile for the tail mean step. + """ + if cutlass.const_expr(is_tail): + tile_idx = kv_tile_start + Int32(stage_info.loop_end) - Int32(1) + else: + tile_idx = cute.math.max( + kv_tile_start + stage_info.loop_offset - Int32(1), Int32(0) + ) + self._tma_load_tile( + stage_info, + tile_idx // Int32(VC_MEAN_GROUP_TILES), + kv_head_coord, + batch_coord, + ) + + @cute.jit + def _build_desc(self, stage_info: StageInfo) -> prims.Tcgen05SmemDesc: + sMu_curr = self.sMu_array.subview(stage_info.stage_idx * self.stage_elements) + return prims.Tcgen05SmemDesc.build( + sMu_curr, + leading_byte_offset=VC_MEAN_TILE_LBO, + stride_byte_offset=VC_MEAN_TILE_SBO, + layout=prims.Tcgen05SmemSwizzle.NONE, + ) + + @consumer_work(returns=desc_mu_base) + @cute.jit + def mu_desc(self, stage_info: StageInfo) -> prims.Tcgen05SmemDesc: + """Build the unswizzled K-major descriptor of the current mean operand.""" + return self._build_desc(stage_info) + + @consumer_work(returns=desc_mu_last) + @cute.jit + def mu_desc_last(self, stage_info: StageInfo) -> prims.Tcgen05SmemDesc: + """Descriptor of the last tile's mean operand, held beside the previous one.""" + return self._build_desc(stage_info) diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_scales.py b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_scales.py new file mode 100644 index 000000000000..7cc0097ba5cb --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/kernels/fmha_context/vc_attention/vc_scales.py @@ -0,0 +1,129 @@ +# Copyright (c) 2026 by FlashInfer team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""VC-Attention scale addressing for the context softmax. + +Every dequant-scale load of the VC-Attention context kernel goes through this +module, the context counterpart of the decode kernels' +:mod:`..fmha_decode.fmha_decode_resources.sage_scales`. ``sfQ`` and ``sfK`` use +the trtllm-gen flat layout (``flat_scale_slot`` of +:mod:`flashinfer.attention.prims_ts.sage`): per head, sequence ``b`` of length +``S`` starts at slot ``(b * S >> log2(blk)) + b`` and token ``t`` uses slot +``t >> log2(blk)`` inside it. Q rows past the valid row count clamp to the +last valid slot, so masked rows keep a finite scale. + +:class:`VCKScaleTable` is one softmax group's ``sfK`` words for the whole K/V +loop of a work tile: the group fills it with one coalesced pass before the +loop (published by a named barrier that also keeps a fast warp from refilling +while a peer still reads the previous work tile's words) and every softmax +step reads the next tile's word one iteration ahead. The words live behind the +group's SMEM P tile (``SmemPResource.kscale_table_offset``). +""" + +from __future__ import annotations + +import cutlass +import cutlass.cute as cute +from cutlass import Float32, Int32 +from cutlass.experimental.task_scheduling.resources import StageInfo + +# First of the two named barrier ids, one per softmax group, that publish a +# refilled K-scale table. +VC_KSCALE_BARRIER_ID = 8 + + +@cute.jit +def vc_flat_q_slot( + batch_coord: Int32, + row: Int32, + seq_len_q: cutlass.Constexpr[int], + q_block_log2: cutlass.Constexpr[int], +) -> Int32: + """Slot of query ``row`` of sequence ``batch_coord`` in the Q scale table, which + holds one scale per block of every sequence in turn.""" + lbq = Int32(q_block_log2) + row_c = cute.math.min(row, Int32(seq_len_q - 1)) + blocks = (seq_len_q + (1 << q_block_log2) - 1) >> q_block_log2 + return batch_coord * Int32(blocks) + (row_c >> lbq) + + +@cute.jit +def vc_flat_k_base( + batch_coord: Int32, + seq_len_k: cutlass.Constexpr[int], + kv_tile_n: cutlass.Constexpr[int], +) -> Int32: + """Slot of K/V tile 0 of sequence ``batch_coord`` in the K scale table, which + holds one scale per tile of every sequence in turn. Tile ``t`` is ``base + t``.""" + return batch_coord * Int32((seq_len_k + kv_tile_n - 1) // kv_tile_n) + + +class VCKScaleTable: + """One softmax group's ``sfK`` table for the work tile, staged in SMEM.""" + + def __init__(self, cfg, smem_p, q_half: int) -> None: + self.cfg = cfg + self.smem_p = smem_p + self.q_half = q_half + + @property + def words(self) -> int: + return self.cfg.vc_kscale_table_bytes // 4 + + @cute.jit + def view(self, stage_info: StageInfo) -> cutlass.Array: + """The table as an fp32 SMEM array.""" + context = stage_info.context + return cutlass.Array( + context.smem_base.data_ptr() + + self.smem_p._alloc.offset + + self.smem_p.kscale_table_offset, + dtype=Float32, + shape=(self.words,), + addrspace=3, + ) + + @cute.jit + def fill( + self, + stage_info: StageInfo, + vc_k_scale: cute.Tensor, + kv_head: Int32, + k_base: Int32, + num_tiles: cutlass.Constexpr[int], + ) -> Float32: + """Gather this work tile's ``sfK`` words from the flat layout and publish + the table to the group's four warps; returns tile 0's scale.""" + cfg = self.cfg + num_threads = len(cfg.softmax0_warp_ids) * cute.arch.WARP_SIZE + barrier_id = VC_KSCALE_BARRIER_ID + self.q_half + table = self.view(stage_info) + num_tiles = Int32(num_tiles) + warp_id_in_sg = cute.arch.warp_idx() % len(cfg.softmax0_warp_ids) + thread = warp_id_in_sg * cute.arch.WARP_SIZE + cute.arch.lane_idx() + cute.arch.barrier(barrier_id=barrier_id, number_of_threads=num_threads) + for pass_idx in cutlass.range_constexpr( + (self.words + num_threads - 1) // num_threads + ): + tile_idx = Int32(pass_idx * num_threads) + thread + if tile_idx < num_tiles: + table[tile_idx] = Float32(vc_k_scale[(kv_head, k_base + tile_idx)]) + cute.arch.barrier(barrier_id=barrier_id, number_of_threads=num_threads) + return Float32(table[Int32(0)]) + + @cute.jit + def next_scale(self, stage_info: StageInfo, tile_idx: Int32) -> Float32: + """``sfK`` of tile ``tile_idx + 1`` (clamped to the table), read one tile ahead.""" + table = self.view(stage_info) + next_idx = cute.math.min(tile_idx + Int32(1), Int32(self.words) - Int32(1)) + return Float32(table[next_idx]) diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/__init__.py b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/__init__.py new file mode 100644 index 000000000000..20257ea3618f --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/__init__.py @@ -0,0 +1,311 @@ +# Copyright (c) 2026 by FlashInfer team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""VC-Attention operand contract of the prims_ts context kernel. + +VC-Attention (arXiv 2609.15810) adds two changes on the value side of +attention: a token permutation that groups similar value rows into the same +128-token K/V tile, and per-tile value smoothing. Each V tile is stored as E4M3 +residuals around its tile mean; the kernel restores the mean inside the online +softmax as ``O += rowsum(P_tile) * mean_tile`` (bf16 K=16 UMMA steps), so the +residual quantization error no longer carries the value DC component. P is +E4M3 through the ExpCast path in both recipes of the Q/K side: + +* VC-Attention-QK16 keeps Q and K in bf16 (plan ``q_dtype`` bf16); +* VC-Attention-QK8 (plan ``q_dtype`` E4M3) centres K by its per-head channel + mean, rotates Q and K by the normalised 128-point Hadamard matrix and + quantizes them to E4M3 with one scale per 128-token Q block and per + 128-token K tile, as the paper does. + +This module holds what the kernel and the plan need: the tile constants, the +mean operand shapes, ``VCAttentionConfig`` and ``VCAttentionParams`` with +their validation, the repair tile arithmetic and ``vc_reference``, the fp32 +attention over the dequantized operands. The quantizer that produces the +operands lives in ``quantization`` beside this module and its CuTe DSL +kernels in ``prepare``. + +The kernel takes the means and the per-channel V scale through +``BatchPrefillTSWrapper.run`` (``vc=VCAttentionParams(...)``), which folds the +scale into ``output_scale``. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from .quantization import VCAttentionOperands + + +# The head dimension the preparation kernels and the attention plans support. +VC_HEAD_DIM = 128 +# The K/V tile whose value mean the kernel restores, its only supported size. +VC_K_BLOCK_SIZE = 128 +# Q tokens per E4M3 Q scale of VC-Attention-QK8, powers of two up to the Q tile. +# K of the bf16 UMMA mean step, one kind::f16 K step. +VC_MEAN_MMA_K = 16 +# Mean UMMA steps issued back to back per group of tiles; each tile takes two of a +# step's 16 K slots (bf16 hi/lo row sum). +VC_MEAN_OPERANDS = 2 +VC_MEAN_GROUP_TILES = VC_MEAN_OPERANDS * VC_MEAN_MMA_K // 2 +E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max + + +def vc_mean_group_shape(head_dim: int) -> tuple[int, int]: + """Shape of the packed mean operands of one tile group: the ``VC_MEAN_OPERANDS`` + operands of ``vc_mean_operand_shape`` stacked along the row axis.""" + rows, cols = vc_mean_operand_shape(head_dim) + return (VC_MEAN_OPERANDS * rows, cols) + + +def vc_mean_operand_shape(head_dim: int) -> tuple[int, int]: + """Shape of one packed bf16 ``[head_dim x VC_MEAN_MMA_K]`` mean operand, in + rows of 256 elements (the kernel's 512-byte TMA box row).""" + return (head_dim * VC_MEAN_MMA_K // 256, 256) + + +@dataclass(frozen=True) +class VCAttentionConfig: + """Compile-time VC-Attention recipe of one plan. + + With demean on, the default, the kernel restores the tile means. Each + 128-token K/V tile stores E4M3 residuals around its bf16 mean and the + kernel adds the mean back. With demean off the means are zero and the + kernel skips that step. This is the plan for the steps after the V-Smooth + window. The demean flag changes per denoising step while a plan is + compiled once, so a caller holds one plan of each kind. + + A positive repair tile count selects V repair and needs demean off. The + preprocessor appends that many 128-row tiles of the largest quantization + residuals after the sequence and the kernel adds them to the output. Each + repair tile costs one extra K/V tile of attention work. Budgets of two to + five percent of the sequence were used so far and the count cannot exceed + the number of sequence tiles. + + Under VC-Attention-QK8, the plan with E4M3 Q and K, every 128-token Q + block shares one E4M3 Q scale and every 128-token K/V tile one K scale. + """ + + demean: bool = True + repair_tiles: int = 0 + + def __post_init__(self) -> None: + if self.repair_tiles < 0: + raise ValueError(f"repair_tiles must be >= 0, got {self.repair_tiles}") + if self.repair_tiles and self.demean: + raise ValueError("repair_tiles requires demean=False") + + +def vc_repair_tiles(seq_len_kv: int, budget: float) -> int: + """Repair tiles of a V repair run, whole 128-row tiles holding the selected + tokens, ``budget`` times the sequence length rounded and at least one.""" + if not (0.0 < budget < 1.0): + raise ValueError(f"budget must be in (0, 1), got {budget}") + return _blocks(max(1, round(budget * seq_len_kv)), VC_K_BLOCK_SIZE) + + +def vc_repair_kv_len(seq_len_kv: int, repair_tiles: int) -> int: + """K/V rows of a V repair run, the sequence zero-padded to whole tiles plus + the repair tiles.""" + return (_blocks(seq_len_kv, VC_K_BLOCK_SIZE) + repair_tiles) * VC_K_BLOCK_SIZE + + +@dataclass(frozen=True, kw_only=True) +class VCAttentionParams: + """Per-run VC-Attention operands beyond ``q``, the permuted ``k`` and the + E4M3 ``v`` residuals. + + VC-Attention-QK8 plans take ``q_scale`` ``[Hq, B, ceil(Sq / 128)]`` and + ``k_scale`` ``[Hkv, B, ceil(Skv / 128)]``, fp32, one scale per 128-token + block. QK16 plans take neither. ``v_scale`` is the ``[B, Hkv, D]`` fp32 + per-channel E4M3 residual scale. ``tile_means`` is the packed bf16 mean + operand ``[B, Hkv, ceil(num_kv_tiles / 16), 16, 256]`` the preparation + writes, the means already divided by ``v_scale``. The scale must be positive + and finite. The kernel does not check it. A plan with demean off takes no + ``tile_means``. + """ + + q_scale: torch.Tensor | None = None + k_scale: torch.Tensor | None = None + v_scale: torch.Tensor + tile_means: torch.Tensor | None + + +def vc_scale_shapes( + config: VCAttentionConfig, + *, + batch_size: int, + seq_len_kv: int, + num_kv_heads: int, + head_dim: int, + seq_len_q: int | None = None, + num_qo_heads: int | None = None, + qk_fp8: bool = False, +) -> dict[str, tuple[int, ...]]: + """Return the shape of every ``VCAttentionParams`` tensor a plan consumes, by + field name. ``qk_fp8`` adds the Q/K scales of VC-Attention-QK8, which need + ``seq_len_q`` and ``num_qo_heads``.""" + num_kv_tiles = _blocks(seq_len_kv, VC_K_BLOCK_SIZE) + if config.repair_tiles: + # The repair tiles follow the whole tiles. + seq_len_kv = vc_repair_kv_len(seq_len_kv, config.repair_tiles) + shapes: dict[str, tuple[int, ...]] = {} + if qk_fp8: + if seq_len_q is None or num_qo_heads is None: + raise ValueError("qk_fp8 scale shapes need seq_len_q and num_qo_heads") + shapes["q_scale"] = ( + num_qo_heads, + batch_size, + _blocks(seq_len_q, VC_K_BLOCK_SIZE), + ) + shapes["k_scale"] = ( + num_kv_heads, + batch_size, + _blocks(seq_len_kv, VC_K_BLOCK_SIZE), + ) + shapes["v_scale"] = (batch_size, num_kv_heads, head_dim) + if config.demean: + shapes["tile_means"] = ( + batch_size, + num_kv_heads, + _blocks(num_kv_tiles, VC_MEAN_GROUP_TILES), + *vc_mean_group_shape(head_dim), + ) + return shapes + + +_VC_PARAM_DTYPES = { + "q_scale": torch.float32, + "k_scale": torch.float32, + "v_scale": torch.float32, + "tile_means": torch.bfloat16, +} + + +def validate_vc_params( + params: VCAttentionParams, + expected_shapes: dict[str, tuple[int, ...]], + *, + device: torch.device, +) -> None: + """Validate the operands of one run against the plan's expected shapes. + + ``expected_shapes`` is the plan's ``vc_scale_shapes`` result. + """ + if not isinstance(params, VCAttentionParams): + raise TypeError("vc must be a VCAttentionParams instance") + if "tile_means" not in expected_shapes and params.tile_means is not None: + raise ValueError("tile_means must be None on a plan with demean off") + for name, expected_shape in expected_shapes.items(): + tensor = getattr(params, name) + if not isinstance(tensor, torch.Tensor): + raise TypeError(f"{name} must be a torch.Tensor") + if tensor.dtype != _VC_PARAM_DTYPES[name]: + raise ValueError( + f"{name} must have dtype {_VC_PARAM_DTYPES[name]}, got {tensor.dtype}" + ) + if tuple(tensor.shape) != tuple(expected_shape): + raise ValueError( + f"{name} must have shape {tuple(expected_shape)}, got {tuple(tensor.shape)}" + ) + if not tensor.is_contiguous(): + raise ValueError(f"{name} must be contiguous") + if tensor.data_ptr() % 16 != 0: + raise ValueError(f"{name} data pointer must be 16-byte aligned") + if tensor.device != device: + raise ValueError(f"{name} must be on device {device}, got {tensor.device}") + + +def _blocks(length: int, block: int) -> int: + return (length + block - 1) // block + + +def _per_token_scales(scale: torch.Tensor, s: int, block: int) -> torch.Tensor: + """Expand ``[B, H, nb]`` block scales to ``[B, S, H]``.""" + return scale.permute(0, 2, 1).repeat_interleave(block, dim=1)[:, :s] + + +@torch.no_grad() +def vc_reference( + q: torch.Tensor, ops: VCAttentionOperands, *, sm_scale: float | None = None +) -> torch.Tensor: # noqa: D401 + """fp32 attention of ``q`` over the dequantized VC operands (what the kernel + computes, up to E4M3 P rounding), as ``[B, S_q, H, D]`` fp32. Under + VC-Attention-QK8 the rotated E4M3 ``ops.q`` and ``ops.k`` are dequantized + with their scales and ``q`` is unused.""" + b, s_k, h, d = ops.k.shape + if sm_scale is None: + sm_scale = 1.0 / math.sqrt(d) + if ops.q_scale is not None: + s_q = ops.q.shape[1] + q_scale = ops.q_scale.permute(1, 0, 2) + k_scale = ops.k_scale.permute(1, 0, 2) + q = ops.q.float() * _per_token_scales(q_scale, s_q, VC_K_BLOCK_SIZE).unsqueeze( + -1 + ) + k = ops.k.float() * _per_token_scales(k_scale, s_k, VC_K_BLOCK_SIZE).unsqueeze( + -1 + ) + else: + q = q.float() + k = ops.k.float() + v = ops.v.float() * ops.v_scale.unsqueeze(1) + repairs_v = ops.repair_tiles > 0 + if repairs_v: + # Repair rows add to the numerator only, the zero padding of the partial + # last tile is masked, and the denominator runs over the original tokens. + repair = ops.repair_tiles * VC_K_BLOCK_SIZE + whole = ops.seq_len_kv // VC_K_BLOCK_SIZE * VC_K_BLOCK_SIZE + end = ops.seq_len_kv + repair + row = torch.arange(s_k, device=k.device) + original = (row < whole) | ((row >= whole + repair) & (row < end)) + scores = torch.einsum("bqhd,bkhd->bhqk", q, k) * sm_scale + scores = scores.masked_fill(row >= end, -torch.inf) + weights = torch.exp(scores - scores.amax(dim=-1, keepdim=True)) + out = torch.einsum("bhqk,bkhd->bqhd", weights, v) + denom = weights[..., original].sum(dim=-1).permute(0, 2, 1) # [B, Sq, H] + return out / denom.unsqueeze(-1) + # The kernel restores bf16(mean / v_scale) * v_scale, per channel. + vs = ops.v_scale.reshape(b, ops.k.shape[2], 1, d) # [B, H, 1, D] + mean = (ops.mean / vs).to(torch.bfloat16).float() * vs + mean_tokens = mean.permute(0, 2, 1, 3).repeat_interleave(VC_K_BLOCK_SIZE, dim=1)[ + :, :s_k + ] + v = v + mean_tokens + scores = torch.einsum("bqhd,bkhd->bhqk", q, k) * sm_scale + probs = torch.softmax(scores, dim=-1) + return torch.einsum("bhqk,bkhd->bqhd", probs, v) + + +__all__ = [ + "E4M3_MAX", + "VC_HEAD_DIM", + "VC_K_BLOCK_SIZE", + "VC_MEAN_MMA_K", + "VCAttentionConfig", + "VCAttentionParams", + "validate_vc_params", + "vc_repair_kv_len", + "vc_repair_tiles", + "vc_mean_group_shape", + "vc_mean_operand_shape", + "VC_MEAN_GROUP_TILES", + "VC_MEAN_OPERANDS", + "vc_reference", + "vc_scale_shapes", +] diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/prepare.py b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/prepare.py new file mode 100644 index 000000000000..c67acd80a71d --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/prepare.py @@ -0,0 +1,1498 @@ +"""VC-Attention operand preparation kernels (CuTe DSL). + +``_prepare`` turns bf16 or fp16 ``[B, S, H, D]`` K and V, and Q under +VC-Attention-QK8, into the prims_ts VC-Attention operands with one CTA per +batch, head and 128-token tile. Each input tensor is read once, V twice, and +each output written once. Shapes are compile-time constants of the kernels and +the launches take tensors only. An operand a recipe does not use is ``None`` +and the kernels take their mode from that. + +* ``VcKvPass1`` writes the V tile means and the per-channel residual amax, plus + the permuted K rows under QK16 or the K tile channel sums under QK8. +* ``VcKvPass2`` writes the V scale, the E4M3 V residuals and the packed bf16 + tile-mean UMMA operand, the K centre under QK8 and the residual energies + under repair. +* ``VcQKPass`` writes the centred, Hadamard-rotated E4M3 Q and K with one + scale per 128-token block in the flat per-sequence scale tables, QK8 only. +* ``VcSelectPass`` and ``VcRepairRowsPass`` pick the tokens of largest + residual energy and write their repair rows, repair only. + +Mean recipes take tokens in ``perm`` order. Repair recipes keep the input +order, move the partial last tile past the repair tiles and write each token's +residual energy instead of the mean operand. Following the paper, V residuals +get one E4M3 scale per batch, head and channel, and the tile means are stored +divided by that scale. Under QK16 Q and K stay in their input dtype. + +Every kernel runs 256 threads. Thread ``t`` owns head_dim columns +``(t % 16) * 8`` to ``+ 8``, one 16-byte vector, of rows ``t // 16 + 16 * i`` +for ``i < 8``. Rows stream through registers and the per-column state stays 8 +wide, with every load of a thread issued before the guarded math. The pre-pass +is memory-latency bound, so it needs that small register footprint for the +occupancy that keeps enough loads in flight. +""" + +from __future__ import annotations + +import functools +import math + +import cutlass +import cutlass.cute as cute +import torch +from cutlass import Float32, Int32, Int64 + +from . import ( + E4M3_MAX, + VC_HEAD_DIM, + VC_K_BLOCK_SIZE, + VC_MEAN_GROUP_TILES, + VC_MEAN_MMA_K, + VC_MEAN_OPERANDS, + vc_mean_group_shape, + vc_mean_operand_shape, + vc_repair_kv_len, +) +from .._compile_cache import build_and_load_attention_kernel +from ..kernels.fmha_decode.fmha_decode_resources.helpers_common import ( + _pack_float2_to_bf16, +) +from ..kernels.fmha_decode.fmha_decode_resources.helpers_softmax import ( + _pack_float4_to_fp8_e4m3, +) + +_COMPILE_OPTIONS = "--enable-tvm-ffi --opt-level 3" +_THREADS = 256 +_COLS_PER_THREAD = 8 +_COL_GROUPS = VC_HEAD_DIM // _COLS_PER_THREAD +_ROW_GROUPS = _THREADS // _COL_GROUPS +_ROWS_PER_THREAD = VC_K_BLOCK_SIZE // _ROW_GROUPS +_WORDS = _COLS_PER_THREAD // 2 +_MU_ELEMS = math.prod(vc_mean_operand_shape(VC_HEAD_DIM)) +_HADAMARD_NORM = 1.0 / math.sqrt(VC_HEAD_DIM) +_SELECT_BINS = 256 +assert _THREADS == _SELECT_BINS, "VcSelectPass owns one histogram bin per thread" + + +@cute.jit +def _hadamard128_row(vals, base: cutlass.Constexpr[int], cg: Int32): + """Unnormalised 128-point Walsh-Hadamard transform of one row in place. + + This thread holds 8 columns and the 15 lanes of its column group hold the + rest. The caller folds the normalisation into its scale. The butterflies run + as packed f32x2 pairs because the pass is issue-bound. + """ + for h in (1, 2, 4): + lo = [i for i in range(_COLS_PER_THREAD) if (i & h) == 0] + for q in cutlass.range_constexpr(0, len(lo), 2): + i0, i1 = lo[q], lo[q + 1] + a = (vals[base + i0], vals[base + i1]) + b = (vals[base + (i0 ^ h)], vals[base + (i1 ^ h)]) + vals[base + i0], vals[base + i1] = cute.arch.add_packed_f32x2(a, b) + vals[base + (i0 ^ h)], vals[base + (i1 ^ h)] = cute.arch.sub_packed_f32x2( + a, b + ) + for sbit in cutlass.range_constexpr(4): + stride = 1 << sbit + sign = Float32(1.0) - Float32(2.0) * Float32((cg >> sbit) & 1) + for j in cutlass.range_constexpr(0, _COLS_PER_THREAD, 2): + m0 = vals[base + j] + m1 = vals[base + j + 1] + o0 = cute.arch.shuffle_sync_bfly(m0, stride) + o1 = cute.arch.shuffle_sync_bfly(m1, stride) + vals[base + j], vals[base + j + 1] = cute.arch.fma_packed_f32x2( + (m0, m1), (sign, sign), (o0, o1) + ) + + +@cute.jit +def _block_max(v: Float32, red_smem, tidx: Int32) -> Float32: + """Max over the threads of the CTA. + + The pre-pass is a plain streaming kernel with no tensor memory allocation, so + the reduction is the usual warp shuffle tree followed by one word per warp in + shared memory. The attention kernel's TMEM reductions are not available here. + """ + for shift in cutlass.range_constexpr(5): + v = cute.arch.fmax(v, cute.arch.shuffle_sync_bfly(v, 1 << shift)) + if tidx % 32 == 0: + red_smem[tidx // 32] = v + cute.arch.sync_threads() + r = red_smem[0] + for w in cutlass.range_constexpr(1, _THREADS // 32): + r = cute.arch.fmax(r, red_smem[w]) + cute.arch.sync_threads() + return r + + +@cute.jit +def _load_raw(raw, base: cutlass.Constexpr[int], addr: Int64): + """Load this thread's 16 bytes at ``addr`` into four words of ``raw``.""" + regs = cutlass.inttoptr(addr, mem_space=1, dtype=Int32).load( + count=_WORDS, alignment=16 + ) + for q in cutlass.range_constexpr(_WORDS): + raw[base + q] = regs[q] + + +@cute.jit +def _row(raw, base: cutlass.Constexpr[int], is_bf16: cutlass.Constexpr[bool]): + """The 8 bf16 or fp16 values held in four words of ``raw`` as Float32.""" + regs = (raw.data_ptr() + base).load(count=_WORDS, alignment=16) + if cutlass.const_expr(is_bf16): + return regs.bitcast(cutlass.BFloat16).to(Float32) + return regs.bitcast(cutlass.Float16).to(Float32) + + +@cute.jit +def _load_row_f32(addr: Int64): + return cutlass.inttoptr(addr, mem_space=1, dtype=Float32).load( + count=_COLS_PER_THREAD, alignment=32 + ) + + +@cute.jit +def _pack_row_fp8(vals, base: cutlass.Constexpr[int], scale_inv: Float32): + """This thread's 8 values from ``base`` times ``scale_inv`` as two E4M3 words.""" + packed = cutlass.Array( + Int32, _COLS_PER_THREAD // 4, space=cutlass.AddressSpace.rmem + ) + for j in cutlass.range_constexpr(_COLS_PER_THREAD // 4): + packed[j] = _pack_float4_to_fp8_e4m3( + vals[base + 4 * j] * scale_inv, + vals[base + 4 * j + 1] * scale_inv, + vals[base + 4 * j + 2] * scale_inv, + vals[base + 4 * j + 3] * scale_inv, + ) + return packed.data_ptr().load(count=_COLS_PER_THREAD // 4, alignment=8) + + +@cute.jit +def _coords(num_heads: cutlass.Constexpr[int]): + """This CTA's tile, batch and head, this thread's row group and first column.""" + tidx, _, _ = cute.arch.thread_idx() + t, bh, _ = cute.arch.block_idx() + return ( + t, + bh, + bh // num_heads, + bh % num_heads, + tidx // _COL_GROUPS, + (tidx % _COL_GROUPS) * _COLS_PER_THREAD, + ) + + +@cute.jit +def _row_base( + base: Int64, + b: Int32, + rows: cutlass.Constexpr[int], + h: Int32, + col0: Int32, + elem_bytes: cutlass.Constexpr[int], + row_bytes: cutlass.Constexpr[int], +) -> Int64: + """Address of this thread's columns of row 0 of batch ``b`` in a ``[B, rows, H, D]`` tensor.""" + return ( + base + + Int64(b) * rows * row_bytes + + (Int64(h) * VC_HEAD_DIM + col0) * elem_bytes + ) + + +@cute.jit +def _store_tile_cols( + base: Int64, + bh: Int32, + num_tiles: cutlass.Constexpr[int], + t: Int32, + col0: Int32, + vals, +): + """Store this thread's 8 columns of tile ``t`` of a ``[B, H, T, D]`` fp32 tensor.""" + cutlass.inttoptr( + base + ((Int64(bh) * num_tiles + t) * VC_HEAD_DIM + col0) * 4, + mem_space=1, + dtype=Float32, + ).store(vals.data_ptr().load(count=_COLS_PER_THREAD, alignment=32), alignment=32) + + +@cute.jit +def _cta_col_reduce( + col_sums, vals, rg: Int32, col0: Int32, is_max: cutlass.Constexpr[bool] +): + """Reduce this thread's 8 column values over the row groups through shared memory.""" + cute.arch.sync_threads() + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + col_sums[rg * VC_K_BLOCK_SIZE + col0 + j] = vals[j] + cute.arch.sync_threads() + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + acc = col_sums[col0 + j] + for g in cutlass.range_constexpr(1, _ROW_GROUPS): + if cutlass.const_expr(is_max): + acc = cute.arch.fmax(acc, col_sums[g * VC_K_BLOCK_SIZE + col0 + j]) + else: + acc = acc + col_sums[g * VC_K_BLOCK_SIZE + col0 + j] + vals[j] = acc + + +@cute.jit +def _v_scale(vmax: Float32) -> Float32: + return cute.arch.fmax(vmax * Float32(1.0 / E4M3_MAX), Float32(1e-12)) + + +@cute.jit +def _stats_addr( + mStats: cute.Tensor, bh: Int32, slot: cutlass.Constexpr[int], col0: Int32 +) -> Int64: + """Slot 0 holds the K channel sums and slot 1 the V residual amax.""" + return mStats.iterator.toint() + ((Int64(bh) * 2 + slot) * VC_HEAD_DIM + col0) * 4 + + +@cute.jit +def _scale_slot( + bh: Int32, + block: Int32, + num_heads: cutlass.Constexpr[int], + batch: cutlass.Constexpr[int], + rows: cutlass.Constexpr[int], +) -> Int64: + """Element of block ``block`` of sequence ``bh`` in the ``[H, B, blocks]`` scale table.""" + blocks = (rows + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE + return Int64(bh % num_heads) * (batch * blocks) + Int64( + (bh // num_heads) * blocks + block + ) + + +class _Shape: + """Compile-time geometry shared by the kernels of one preparation.""" + + def __init__( + self, + is_bf16: bool, + batch: int, + seq_len_kv: int, + num_heads: int, + repair_tiles: int, + ): + self.is_bf16 = is_bf16 + self.batch = batch + self.seq_len_kv = seq_len_kv + self.num_heads = num_heads + self.num_tiles = (seq_len_kv + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE + self.repair_tiles = repair_tiles + self.repair = repair_tiles > 0 + self.rows = ( + vc_repair_kv_len(seq_len_kv, repair_tiles) if self.repair else seq_len_kv + ) + self.tail = ( + seq_len_kv // VC_K_BLOCK_SIZE * VC_K_BLOCK_SIZE + if self.repair + else seq_len_kv + ) + self.shift = repair_tiles * VC_K_BLOCK_SIZE + self.row_bytes = num_heads * VC_HEAD_DIM * 2 + self.row_bytes8 = num_heads * VC_HEAD_DIM + + +class VcKvPass1(_Shape): + def __init__( + self, is_bf16, batch, seq_len_kv, num_heads, repair_tiles, demean: bool + ): + super().__init__(is_bf16, batch, seq_len_kv, num_heads, repair_tiles) + self.demean = demean + + @cute.kernel + def kernel( + self, + mK: cute.Tensor, + mV: cute.Tensor, + mPerm: cute.Tensor | None, + mKPerm: cute.Tensor | None, + mMean: cute.Tensor, + mKSum: cute.Tensor | None, + mStats: cute.Tensor, + ): + """Pass 1 over one 128-token K/V tile of one batch head. + + Reads K and V once. With a permutation it writes the permuted K rows, + otherwise it accumulates the K channel sums the QK8 centre needs. From + V it writes the tile mean and folds the tile's residual amax into the + per-channel statistics that pass 2 turns into the V scale. + """ + # Thread t owns 8 columns of rows t // 16 + 16 i for i < 8. col_sums is + # the scratch of the CTA-wide per-column reductions. + t, bh, b, h, rg, col0 = _coords(self.num_heads) + smem = cutlass.utils.SmemAllocator() + col_sums = smem.allocate_array(Float32, _ROW_GROUPS * VC_K_BLOCK_SIZE) + k_base = _row_base( + mK.iterator.toint(), b, self.seq_len_kv, h, col0, 2, self.row_bytes + ) + v_base = _row_base( + mV.iterator.toint(), b, self.seq_len_kv, h, col0, 2, self.row_bytes + ) + if cutlass.const_expr(mKPerm is not None): + kp_base = _row_base( + mKPerm.iterator.toint(), b, self.rows, h, col0, 2, self.row_bytes + ) + + # Rows past the sequence read token 0 and skip the math, so every load + # of a thread is in flight together. + toks = cutlass.Array(Int32, _ROWS_PER_THREAD, space=cutlass.AddressSpace.rmem) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + tok = Int32(0) + if pos < self.seq_len_kv: + tok = pos + if cutlass.const_expr(mPerm is not None): + tok = cutlass.inttoptr( + mPerm.iterator.toint() + + (Int64(bh) * self.seq_len_kv + pos) * 4, + mem_space=1, + dtype=Int32, + ).load() + toks[i] = tok + raw = cutlass.Array( + Int32, _ROWS_PER_THREAD * _WORDS, space=cutlass.AddressSpace.rmem + ) + + # K. Either copy the permuted rows to their output slot, shifted past the + # repair tiles for the partial tail, or sum the channels for the centre. + if cutlass.const_expr(mKPerm is not None): + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + _load_raw(raw, i * _WORDS, k_base + Int64(toks[i]) * self.row_bytes) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if pos < self.seq_len_kv: + out_row = pos + self.shift * Int32(pos >= self.tail) + cutlass.inttoptr( + kp_base + Int64(out_row) * self.row_bytes, + mem_space=1, + dtype=Int32, + ).store( + (raw.data_ptr() + i * _WORDS).load(count=_WORDS, alignment=16), + alignment=16, + ) + else: + # K channel sums of the tile in input order. Pass 2 sums the tiles + # in a fixed order so the centre is deterministic. + ksum = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + ksum[j] = Float32(0.0) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + kpos = Int32(0) + if pos < self.seq_len_kv: + kpos = pos + _load_raw(raw, i * _WORDS, k_base + Int64(kpos) * self.row_bytes) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if pos < self.seq_len_kv: + row = _row(raw, i * _WORDS, self.is_bf16) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + ksum[j] = ksum[j] + row[j] + _cta_col_reduce(col_sums, ksum, rg, col0, False) + if rg == 0: + _store_tile_cols( + mKSum.iterator.toint(), bh, self.num_tiles, t, col0, ksum + ) + + # V. Per-column sum, max and min of the tile's rows give the mean and the + # residual amax exactly, since max |v - mean| is max(vmax - mean, mean - vmin). + psum = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + pmax = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + pmin = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + psum[j] = Float32(0.0) + pmax[j] = -Float32.inf + pmin[j] = Float32.inf + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + _load_raw(raw, i * _WORDS, v_base + Int64(toks[i]) * self.row_bytes) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if pos < self.seq_len_kv: + row = _row(raw, i * _WORDS, self.is_bf16) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + psum[j] = psum[j] + row[j] + pmax[j] = cute.arch.fmax(pmax[j], row[j]) + pmin[j] = cute.arch.fmin(pmin[j], row[j]) + valid_rows = self.seq_len_kv - t * VC_K_BLOCK_SIZE + if valid_rows > VC_K_BLOCK_SIZE: + valid_rows = Int32(VC_K_BLOCK_SIZE) + inv_count = Float32(1.0) / Float32(valid_rows) + _cta_col_reduce(col_sums, psum, rg, col0, False) + mean = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + mean[j] = psum[j] * inv_count + if cutlass.const_expr(not self.demean): + mean[j] = Float32(0.0) + if rg == 0: + _store_tile_cols(mMean.iterator.toint(), bh, self.num_tiles, t, col0, mean) + # The residual amax of this tile joins the per-channel maximum over all + # tiles with one atomic per column. Pass 2 derives the V scale from it. + cmax = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + cmax[j] = Float32(0.0) + if pmax[j] >= pmin[j]: + cmax[j] = cute.arch.fmax(pmax[j] - mean[j], mean[j] - pmin[j]) + _cta_col_reduce(col_sums, cmax, rg, col0, True) + if rg == 0: + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + cute.arch.atomic_fmax( + cutlass.inttoptr( + _stats_addr(mStats, bh, 1, col0) + j * 4, + mem_space=1, + dtype=Float32, + ), + cmax[j], + sign_bit=False, + ) + + @cute.jit + def __call__(self, mK, mV, mPerm, mKPerm, mMean, mKSum, mStats, stream): + self.kernel(mK, mV, mPerm, mKPerm, mMean, mKSum, mStats).launch( + grid=[self.num_tiles, self.batch * self.num_heads, 1], + block=[_THREADS, 1, 1], + smem=_ROW_GROUPS * VC_K_BLOCK_SIZE * 4, + stream=stream, + ) + + +class VcKvPass2(_Shape): + @cute.kernel + def kernel( + self, + mV: cute.Tensor, + mPerm: cute.Tensor | None, + mMean: cute.Tensor, + mKSum: cute.Tensor | None, + mStats: cute.Tensor, + mVScale: cute.Tensor, + mV8: cute.Tensor, + mMu: cute.Tensor | None, + mEnergy: cute.Tensor | None, + ): + """Pass 2 over one 128-token K/V tile of one batch head. + + With the per-channel residual amax of pass 1 known, it derives the E4M3 + V scale, stores the E4M3 residuals of the permuted V rows, the per-token + residual energy for the repair selection when asked, and the packed bf16 + mean operand of the tile's group for the kernel's mean UMMA step. Tile 0 + also writes the V scale and finishes the QK8 K centre sum. + """ + tidx, _, _ = cute.arch.thread_idx() + t, bh, _ = cute.arch.block_idx() + b = bh // self.num_heads + h = bh % self.num_heads + cg = tidx % _COL_GROUPS + rg = tidx // _COL_GROUPS + col0 = cg * _COLS_PER_THREAD + v_base = ( + mV.iterator.toint() + + Int64(b) * self.seq_len_kv * self.row_bytes + + (Int64(h) * VC_HEAD_DIM + col0) * 2 + ) + mean_base = mMean.iterator.toint() + (Int64(bh) * self.num_tiles + t) * ( + VC_HEAD_DIM * 4 + ) + smem = cutlass.utils.SmemAllocator() + energy_part = smem.allocate_array(Float32, _THREADS * _ROWS_PER_THREAD) + + # Step 1. The V scale of this thread's channels from the residual amax. + vmax_base = _stats_addr(mStats, bh, 1, 0) + vmax = _load_row_f32(vmax_base + col0 * 4) + vs = cutlass.Array(Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem) + vs_inv = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + vs[j] = _v_scale(vmax[j]) + vs_inv[j] = Float32(1.0) / vs[j] + if (t == 0) & (rg == 0): + cutlass.inttoptr( + mVScale.iterator.toint() + (Int64(bh) * VC_HEAD_DIM + col0) * 4, + mem_space=1, + dtype=Float32, + ).store( + vs.data_ptr().load(count=_COLS_PER_THREAD, alignment=32), alignment=32 + ) + # Tile 0 sums the per-tile K channel sums of pass 1 in a fixed order, so + # the QK8 centre is deterministic. + if cutlass.const_expr(mKSum is not None): + if (t == 0) & (tidx < VC_HEAD_DIM): + ksum_base = ( + mKSum.iterator.toint() + + (Int64(bh) * self.num_tiles * VC_HEAD_DIM + tidx) * 4 + ) + acc = Float32(0.0) + for i in cutlass.range(self.num_tiles): + acc = ( + acc + + cutlass.inttoptr( + ksum_base + Int64(i) * (VC_HEAD_DIM * 4), + mem_space=1, + dtype=Float32, + ).load() + ) + cutlass.inttoptr( + _stats_addr(mStats, bh, 0, 0) + tidx * 4, mem_space=1, dtype=Float32 + ).store(acc) + + # Step 2. Reload the permuted V rows, subtract the tile mean, quantize the + # residuals to E4M3 and store them at the shifted output row. + mean = _load_row_f32(mean_base + col0 * 4) + raw = cutlass.Array( + Int32, _ROWS_PER_THREAD * _WORDS, space=cutlass.AddressSpace.rmem + ) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + tok = Int32(0) + if pos < self.seq_len_kv: + tok = pos + if cutlass.const_expr(mPerm is not None): + tok = cutlass.inttoptr( + mPerm.iterator.toint() + + (Int64(bh) * self.seq_len_kv + pos) * 4, + mem_space=1, + dtype=Int32, + ).load() + _load_raw(raw, i * _WORDS, v_base + Int64(tok) * self.row_bytes) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + energy = Float32(0.0) + if pos < self.seq_len_kv: + row = _row(raw, i * _WORDS, self.is_bf16) + res = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + res[j] = (row[j] - mean[j]) * vs_inv[j] + out_row = pos + self.shift * Int32(pos >= self.tail) + out_addr = ( + mV8.iterator.toint() + + (Int64(b) * self.rows + out_row) * self.row_bytes8 + + Int64(h) * VC_HEAD_DIM + + col0 + ) + if cutlass.const_expr(mEnergy is not None): + # The squared E4M3 rounding error in value units ranks the + # tokens for repair. + words = _pack_row_fp8(res, 0, Float32(1.0)) + codes = words.bitcast(cutlass.Float8E4M3FN).to(Float32) + for c in cutlass.range_constexpr(_COLS_PER_THREAD): + err = (res[c] - codes[c]) * vs[c] + energy = energy + err * err + cutlass.inttoptr(out_addr, mem_space=1, dtype=Int32).store( + words, alignment=8 + ) + else: + cutlass.inttoptr(out_addr, mem_space=1, dtype=Int32).store( + _pack_row_fp8(res, 0, Float32(1.0)), alignment=8 + ) + if cutlass.const_expr(mEnergy is not None): + energy_part[(rg + _ROW_GROUPS * i) * _COL_GROUPS + cg] = energy + # Step 3. V repair only. Sum each row's partial energies over the 16 + # column groups and store one energy per token. + if cutlass.const_expr(mEnergy is not None): + cute.arch.sync_threads() + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = t * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if (cg == 0) & (pos < self.seq_len_kv): + acc = Float32(0.0) + for c in cutlass.range_constexpr(_COL_GROUPS): + acc = ( + acc + energy_part[(rg + _ROW_GROUPS * i) * _COL_GROUPS + c] + ) + cutlass.inttoptr( + mEnergy.iterator.toint() + + (Int64(bh) * self.seq_len_kv + pos) * 4, + mem_space=1, + dtype=Float32, + ).store(acc) + + if cutlass.const_expr(mMu is not None): + # Step 4. Means only. + # Mean operand of this tile's group in core-matrix order. Tile 8o+i + # of a group owns K slots 2i and 2i+1 of operand o. Each of the first + # 128 threads stores its two rows' slots, and the last tile stores + # zero slots for the tiles its group lacks. Means are stored divided + # by the per-channel scale. + k_per_core = VC_MEAN_MMA_K // 2 + idx0 = tidx * (2 * k_per_core) + g = idx0 // (8 * VC_MEAN_MMA_K) + c = (idx0 // (8 * k_per_core)) % 2 + d0 = g * 8 + (idx0 // k_per_core) % 8 + num_groups = ( + self.num_tiles + VC_MEAN_GROUP_TILES - 1 + ) // VC_MEAN_GROUP_TILES + group0 = t - t % VC_MEAN_GROUP_TILES + if tidx < 128: + m0 = cutlass.inttoptr( + mean_base + Int64(d0) * 4, mem_space=1, dtype=Float32 + ).load() + m1 = cutlass.inttoptr( + mean_base + Int64(d0 + 1) * 4, mem_space=1, dtype=Float32 + ).load() + s0 = _v_scale( + cutlass.inttoptr( + vmax_base + Int64(d0) * 4, mem_space=1, dtype=Float32 + ).load() + ) + s1 = _v_scale( + cutlass.inttoptr( + vmax_base + Int64(d0 + 1) * 4, mem_space=1, dtype=Float32 + ).load() + ) + own0 = _pack_float2_to_bf16(m0 / s0, m0 / s0) + own1 = _pack_float2_to_bf16(m1 / s1, m1 / s1) + for i in cutlass.range_constexpr(VC_MEAN_GROUP_TILES): + operand = i // k_per_core + slot = 2 * (i % k_per_core) + if cutlass.const_expr(slot // k_per_core == 0): + mine = c == 0 + else: + mine = c == 1 + tile = group0 + i + if mine & ((tile == t) | ((t == self.num_tiles - 1) & (tile > t))): + val0 = Int32(0) + val1 = Int32(0) + if tile == t: + val0 = own0 + val1 = own1 + dst = ( + mMu.iterator.toint() + + ( + ( + (Int64(bh) * num_groups + t // VC_MEAN_GROUP_TILES) + * VC_MEAN_OPERANDS + + operand + ) + * _MU_ELEMS + + idx0 + + slot % k_per_core + ) + * 2 + ) + cutlass.inttoptr(dst, mem_space=1, dtype=Int32).store(val0) + cutlass.inttoptr( + dst + k_per_core * 2, mem_space=1, dtype=Int32 + ).store(val1) + + @cute.jit + def __call__( + self, mV, mPerm, mMean, mKSum, mStats, mVScale, mV8, mMu, mEnergy, stream + ): + self.kernel(mV, mPerm, mMean, mKSum, mStats, mVScale, mV8, mMu, mEnergy).launch( + grid=[self.num_tiles, self.batch * self.num_heads, 1], + block=[_THREADS, 1, 1], + smem=_THREADS * _ROWS_PER_THREAD * 4, + stream=stream, + ) + + +class VcQKPass(_Shape): + """QK8 quantization of Q and K in one launch, one CTA per 128-token block. + + The first ``blocks_q`` blocks are Q, the rest are K through ``perm`` or the + repair row map, with the repair tiles through the selection index. K is + centred with the channel sums of the statistics. The rotated block stays + in registers between the amax and the store. + """ + + def __init__( + self, + is_bf16, + batch, + seq_len_kv, + num_heads, + repair_tiles, + seq_len_q: int, + repair_tokens: int = 0, + ): + super().__init__(is_bf16, batch, seq_len_kv, num_heads, repair_tiles) + self.seq_len_q = seq_len_q + self.repair_tokens = repair_tokens + self.blocks_q = (seq_len_q + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE + + @cute.jit + def _block( + self, + nb: Int32, + co, + mX: cute.Tensor, + mPerm: cute.Tensor | None, + mIndex: cute.Tensor | None, + mStats: cute.Tensor | None, + mX8: cute.Tensor, + mScale: cute.Tensor, + red, + rows_out: cutlass.Constexpr[int], + src: cutlass.Constexpr[int], + ): + """One block of Q, of K when ``mStats`` is given, or of the repair tiles + when ``mIndex`` is given. ``co`` carries the CTA and thread coordinates.""" + # One CTA per 128-token block of one batch head. Thread t owns 8 columns of + # rows t // 16 + 16 i for i < 8, so the 256 threads cover the 128 x 128 block. + _, bh, b, h, rg, col0 = co + cg = col0 // _COLS_PER_THREAD + tidx = rg * _COL_GROUPS + cg + x_base = _row_base(mX.iterator.toint(), b, src, h, col0, 2, self.row_bytes) + centre = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + centre[j] = Float32(0.0) + # K only. The per head channel mean from the statistics pass, subtracted + # before the rotation. + if cutlass.const_expr(mStats is not None): + c = _load_row_f32(_stats_addr(mStats, bh, 0, col0)) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + centre[j] = c[j] * Float32(1.0 / src) + + # Step 1. Load this thread's 8 rows of the block, through the row map when + # gathering, centre them and keep them in registers for the whole kernel. + # The source token per row is -1 for rows outside the sequence and for + # zero rows. Loads read token 0 for those and the math is skipped. + toks = cutlass.Array(Int32, _ROWS_PER_THREAD, space=cutlass.AddressSpace.rmem) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = nb * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + tok = Int32(-1) + if pos < rows_out: + tok = pos + if cutlass.const_expr(mIndex is not None): + tok = Int32(-1) + sel = pos - self.tail + if (sel >= 0) & (sel < self.repair_tokens): + tok = cutlass.inttoptr( + mIndex.iterator.toint() + + (Int64(bh) * self.repair_tokens + sel) * 4, + mem_space=1, + dtype=Int32, + ).load() + elif cutlass.const_expr(mPerm is not None): + tok = cutlass.inttoptr( + mPerm.iterator.toint() + + (Int64(bh) * self.seq_len_kv + pos) * 4, + mem_space=1, + dtype=Int32, + ).load() + elif cutlass.const_expr(mStats is not None and self.repair): + if pos >= self.tail: + tok = Int32(-1) + if (pos >= self.tail + self.shift) & ( + pos < self.seq_len_kv + self.shift + ): + tok = pos - self.shift + toks[i] = tok + raw = cutlass.Array( + Int32, _ROWS_PER_THREAD * _WORDS, space=cutlass.AddressSpace.rmem + ) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + tok = toks[i] + if tok < 0: + tok = Int32(0) + _load_raw(raw, i * _WORDS, x_base + Int64(tok) * self.row_bytes) + vals = cutlass.Array( + Float32, + _ROWS_PER_THREAD * _COLS_PER_THREAD, + space=cutlass.AddressSpace.rmem, + ) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + if toks[i] >= 0: + row = _row(raw, i * _WORDS, self.is_bf16) + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + vals[i * _COLS_PER_THREAD + j] = row[j] - centre[j] + else: + # The rotation shuffles need all 16 lanes of a row. + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + vals[i * _COLS_PER_THREAD + j] = Float32(0.0) + # Step 2. Rotate every row by the 128 point Hadamard transform. The 16 + # threads of a row exchange values through warp shuffles, so this needs no + # shared memory and the rows stay in registers. + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + _hadamard128_row(vals, i * _COLS_PER_THREAD, cg) + # Step 3. Block amax of the rotated values over the valid rows, reduced + # across the CTA. One E4M3 scale per block follows from it. + amax = Float32(0.0) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = nb * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if pos < rows_out: + for j in cutlass.range_constexpr(_COLS_PER_THREAD): + v = vals[i * _COLS_PER_THREAD + j] + amax = cute.arch.fmax(amax, cute.arch.fmax(v, -v)) + amax = _block_max(amax, red, tidx) + scale = cute.arch.fmax( + amax * Float32(_HADAMARD_NORM / E4M3_MAX), Float32(1e-12) + ) + # Step 4. Thread 0 writes the block scale to its flat slot in the table. + if tidx == 0: + cutlass.inttoptr( + mScale.iterator.toint() + + _scale_slot(bh, nb, self.num_heads, self.batch, rows_out) * 4, + mem_space=1, + dtype=Float32, + ).store(scale) + # Step 5. Quantize the rotated rows with that scale and store the E4M3 + # block in output row order. + scale_inv = Float32(_HADAMARD_NORM) / scale + x8_base = _row_base( + mX8.iterator.toint(), b, rows_out, h, col0, 1, self.row_bytes8 + ) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + pos = nb * VC_K_BLOCK_SIZE + rg + _ROW_GROUPS * i + if pos < rows_out: + cutlass.inttoptr( + x8_base + Int64(pos) * self.row_bytes8, mem_space=1, dtype=Int32 + ).store( + _pack_row_fp8(vals, i * _COLS_PER_THREAD, scale_inv), alignment=8 + ) + + @cute.kernel + def kernel( + self, + mQ: cute.Tensor, + mK: cute.Tensor, + mPerm: cute.Tensor | None, + mIndex: cute.Tensor | None, + mStats: cute.Tensor, + mQ8: cute.Tensor, + mK8: cute.Tensor, + mQScale: cute.Tensor, + mKScale: cute.Tensor, + ): + """One launch over the Q blocks, then the K tiles, then the repair tiles. + + Block ``nb`` below ``blocks_q`` quantizes Q block ``nb``. Above it, K + tile ``nb - blocks_q`` is read through the permutation, except the repair + tiles after the whole tiles, which gather the selected tokens through the + index. Every block runs ``_block`` with its own source and row map. + """ + co = _coords(self.num_heads) + nb = co[0] + smem = cutlass.utils.SmemAllocator() + red = smem.allocate_array(Float32, _THREADS // 32) + kb = nb - self.blocks_q + if nb < self.blocks_q: + self._block( + nb, + co, + mQ, + None, + None, + None, + mQ8, + mQScale, + red, + self.seq_len_q, + self.seq_len_q, + ) + elif cutlass.const_expr(mIndex is not None) and ( + (kb >= self.tail // VC_K_BLOCK_SIZE) + & (kb < self.tail // VC_K_BLOCK_SIZE + self.repair_tiles) + ): + self._block( + kb, + co, + mK, + None, + mIndex, + mStats, + mK8, + mKScale, + red, + self.rows, + self.seq_len_kv, + ) + else: + self._block( + kb, + co, + mK, + mPerm, + None, + mStats, + mK8, + mKScale, + red, + self.rows, + self.seq_len_kv, + ) + + @cute.jit + def __call__( + self, mQ, mK, mPerm, mIndex, mStats, mQ8, mK8, mQScale, mKScale, stream + ): + self.kernel(mQ, mK, mPerm, mIndex, mStats, mQ8, mK8, mQScale, mKScale).launch( + grid=[ + self.blocks_q + (self.rows + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE, + self.batch * self.num_heads, + 1, + ], + block=[_THREADS, 1, 1], + smem=(_THREADS // 32) * 4, + stream=stream, + ) + + +class VcSelectPass(_Shape): + """The ``repair_tokens`` tokens of largest residual energy per sequence. + + A radix select over the four bytes of the non-negative fp32 bits with one + histogram per warp, then the indices above the threshold and the first + ones at it, in arbitrary order. + """ + + def __init__( + self, is_bf16, batch, seq_len_kv, num_heads, repair_tiles, repair_tokens: int + ): + super().__init__(is_bf16, batch, seq_len_kv, num_heads, repair_tiles) + self.repair_tokens = repair_tokens + + @cute.kernel + def kernel(self, mEnergy: cute.Tensor, mIndex: cute.Tensor): + """Select the ``repair_tokens`` largest energies of one batch head. + + Four radix passes over the bytes of the fp32 bit pattern, most significant + first. Each pass histograms the energies that match the prefix found so + far, scans the bins from the top and keeps the bin where the wanted count + falls, which fixes one more byte of the threshold. A final sweep writes + the indices above the threshold and as many at it as are still wanted. + """ + tidx, _, _ = cute.arch.thread_idx() + bh, _, _ = cute.arch.block_idx() + warp = tidx // 32 + lane = tidx % 32 + smem = cutlass.utils.SmemAllocator() + hist = smem.allocate_array(Int32, (_THREADS // 32) * _SELECT_BINS) + warp_tot = smem.allocate_array(Int32, _THREADS // 32) + # The threshold prefix, the count still wanted at it, the count stored + # above it and the count seen at it. + state = smem.allocate_array(Int32, 4) + e_base = mEnergy.iterator.toint() + Int64(bh) * self.seq_len_kv * 4 + out_base = mIndex.iterator.toint() + Int64(bh) * self.repair_tokens * 4 + # One CTA streams the whole row, so four loads per thread and + # iteration set the memory parallelism. + chunks = (self.seq_len_kv + 4 * _THREADS - 1) // (4 * _THREADS) + if tidx == 0: + state[0] = Int32(0) + state[1] = Int32(self.repair_tokens) + state[2] = Int32(0) + state[3] = Int32(0) + cute.arch.sync_threads() + # Step 1. One radix pass per byte. Per-warp histograms avoid contention + # on the atomics, the scan adds them up. + for p in cutlass.range_constexpr(4): + shift = 24 - 8 * p + for w in cutlass.range_constexpr(_THREADS // 32): + hist[w * _SELECT_BINS + tidx] = Int32(0) + prefix = state[0] + rem = state[1] + cute.arch.sync_threads() + for it in cutlass.range(chunks): + vals = cutlass.Array(Int32, 4, space=cutlass.AddressSpace.rmem) + for u in cutlass.range_constexpr(4): + i = tidx + (it * 4 + u) * _THREADS + vals[u] = Int32(-1) + if i < self.seq_len_kv: + vals[u] = cutlass.inttoptr( + e_base + Int64(i) * 4, mem_space=1, dtype=Int32 + ).load() + for u in cutlass.range_constexpr(4): + bits = vals[u] + hit = bits >= 0 + if cutlass.const_expr(p > 0): + hit = hit & ((bits >> (shift + 8)) == prefix) + if hit: + cute.arch.atomic_add( + hist + + ( + warp * _SELECT_BINS + + ((bits >> shift) & (_SELECT_BINS - 1)) + ), + Int32(1), + ) + cute.arch.sync_threads() + # Thread tidx owns bin 255 - tidx and the scan runs in descending bin order. + mybin = _SELECT_BINS - 1 - tidx + cnt = Int32(0) + for w in cutlass.range_constexpr(_THREADS // 32): + cnt = cnt + hist[w * _SELECT_BINS + mybin] + incl = cnt + for sbit in cutlass.range_constexpr(5): + other = cute.arch.shuffle_sync_up(incl, 1 << sbit) + if lane >= (1 << sbit): + incl = incl + other + if lane == 31: + warp_tot[warp] = incl + cute.arch.sync_threads() + excl = incl - cnt + for w in cutlass.range_constexpr(_THREADS // 32): + if w < warp: + excl = excl + warp_tot[w] + if (excl < rem) & (rem <= excl + cnt): + state[0] = (prefix << 8) | mybin + state[1] = rem - excl + cute.arch.sync_threads() + # Step 2. Emit the indices. Energies above the threshold all qualify, + # energies equal to it fill the remaining slots in arrival order. + threshold = state[0] + rem = state[1] + n_above = self.repair_tokens - rem + for it in cutlass.range(chunks): + vals = cutlass.Array(Int32, 4, space=cutlass.AddressSpace.rmem) + for u in cutlass.range_constexpr(4): + i = tidx + (it * 4 + u) * _THREADS + vals[u] = Int32(-1) + if i < self.seq_len_kv: + vals[u] = cutlass.inttoptr( + e_base + Int64(i) * 4, mem_space=1, dtype=Int32 + ).load() + for u in cutlass.range_constexpr(4): + i = tidx + (it * 4 + u) * _THREADS + bits = vals[u] + if bits > threshold: + slot = cute.arch.atomic_add(state + 2, Int32(1)) + cutlass.inttoptr( + out_base + Int64(slot) * 4, mem_space=1, dtype=Int32 + ).store(i) + elif bits == threshold: + slot = cute.arch.atomic_add(state + 3, Int32(1)) + if slot < rem: + cutlass.inttoptr( + out_base + Int64(n_above + slot) * 4, + mem_space=1, + dtype=Int32, + ).store(i) + + @cute.jit + def __call__(self, mEnergy, mIndex, stream): + self.kernel(mEnergy, mIndex).launch( + grid=[self.batch * self.num_heads, 1, 1], + block=[_THREADS, 1, 1], + smem=((_THREADS // 32) * _SELECT_BINS + _THREADS // 32 + 4) * 4, + stream=stream, + ) + + +class VcRepairRowsPass(_Shape): + """The repair tiles and the padding after the shifted tail. + + One CTA per repair tile writes the selected tokens' E4M3 value residuals + and, when ``mKOut`` is given, their keys, with zero rows for unused slots. + One more CTA zeroes the padding rows. + """ + + def __init__( + self, is_bf16, batch, seq_len_kv, num_heads, repair_tiles, repair_tokens: int + ): + super().__init__(is_bf16, batch, seq_len_kv, num_heads, repair_tiles) + self.repair_tokens = repair_tokens + + @cute.kernel + def kernel( + self, + mK: cute.Tensor | None, + mV: cute.Tensor, + mIndex: cute.Tensor, + mStats: cute.Tensor, + mKOut: cute.Tensor | None, + mV8: cute.Tensor, + ): + """Fill repair tile ``j`` of one batch head, or the padding after the tail. + + Row ``rr`` of repair tile ``j`` holds selected token ``j * 128 + rr``. Its + value row is the E4M3 residual left by pass 2's code, so the kernel adds + back what the first code missed. Its key row is a copy of the key. Slots + past the selected count and the padding rows are zero. + """ + j, bh, b, h, rg, col0 = _coords(self.num_heads) + v_base = _row_base( + mV.iterator.toint(), b, self.seq_len_kv, h, col0, 2, self.row_bytes + ) + v8_base = _row_base( + mV8.iterator.toint(), b, self.rows, h, col0, 1, self.row_bytes8 + ) + if cutlass.const_expr(mKOut is not None): + k_base = _row_base( + mK.iterator.toint(), b, self.seq_len_kv, h, col0, 2, self.row_bytes + ) + kout_base = _row_base( + mKOut.iterator.toint(), b, self.rows, h, col0, 2, self.row_bytes + ) + vmax = _load_row_f32(_stats_addr(mStats, bh, 1, col0)) + vs_inv = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for c in cutlass.range_constexpr(_COLS_PER_THREAD): + vs_inv[c] = Float32(1.0) / _v_scale(vmax[c]) + zeros = cutlass.Array(Int32, 4, space=cutlass.AddressSpace.rmem) + for c in cutlass.range_constexpr(4): + zeros[c] = Int32(0) + raw = cutlass.Array(Int32, _WORDS, space=cutlass.AddressSpace.rmem) + for i in cutlass.range_constexpr(_ROWS_PER_THREAD): + rr = rg + _ROW_GROUPS * i + tok = Int32(-1) + out_row = self.seq_len_kv + self.shift + rr + if j < self.repair_tiles: + out_row = self.tail + j * VC_K_BLOCK_SIZE + rr + sel = j * VC_K_BLOCK_SIZE + rr + if sel < self.repair_tokens: + tok = cutlass.inttoptr( + mIndex.iterator.toint() + + (Int64(bh) * self.repair_tokens + sel) * 4, + mem_space=1, + dtype=Int32, + ).load() + if out_row < self.rows: + v_dst = v8_base + Int64(out_row) * self.row_bytes8 + if tok >= 0: + src_off = Int64(tok) * self.row_bytes + _load_raw(raw, 0, v_base + src_off) + row = _row(raw, 0, self.is_bf16) + # The residual of the E4M3 code pass 2 stored for this token. + res = cutlass.Array( + Float32, _COLS_PER_THREAD, space=cutlass.AddressSpace.rmem + ) + for c in cutlass.range_constexpr(_COLS_PER_THREAD): + res[c] = row[c] * vs_inv[c] + codes = ( + _pack_row_fp8(res, 0, Float32(1.0)) + .bitcast(cutlass.Float8E4M3FN) + .to(Float32) + ) + for c in cutlass.range_constexpr(_COLS_PER_THREAD): + res[c] = res[c] - codes[c] + cutlass.inttoptr(v_dst, mem_space=1, dtype=Int32).store( + _pack_row_fp8(res, 0, Float32(1.0)), alignment=8 + ) + if cutlass.const_expr(mKOut is not None): + _load_raw(raw, 0, k_base + src_off) + cutlass.inttoptr( + kout_base + Int64(out_row) * self.row_bytes, + mem_space=1, + dtype=Int32, + ).store( + raw.data_ptr().load(count=_WORDS, alignment=16), + alignment=16, + ) + else: + cutlass.inttoptr(v_dst, mem_space=1, dtype=Int32).store( + zeros.data_ptr().load(count=2, alignment=8), alignment=8 + ) + if cutlass.const_expr(mKOut is not None): + cutlass.inttoptr( + kout_base + Int64(out_row) * self.row_bytes, + mem_space=1, + dtype=Int32, + ).store( + zeros.data_ptr().load(count=4, alignment=16), alignment=16 + ) + + @cute.jit + def __call__(self, mK, mV, mIndex, mStats, mKOut, mV8, stream): + self.kernel(mK, mV, mIndex, mStats, mKOut, mV8).launch( + grid=[self.repair_tiles + 1, self.batch * self.num_heads, 1], + block=[_THREADS, 1, 1], + smem=0, + stream=stream, + ) + + +def _fake1d(dtype, align=32): + return cute.runtime.make_fake_compact_tensor( + dtype, (cute.sym_int(),), assumed_align=align + ) + + +def _in_dtype(dtype: torch.dtype): + if dtype == torch.bfloat16: + return cutlass.BFloat16, True + if dtype == torch.float16: + return cutlass.Float16, False + raise TypeError(f"VC fused preparation needs bf16/fp16 inputs, got {dtype}") + + +@functools.lru_cache(maxsize=None) +def _compiled( + dtype: torch.dtype, + demean: bool, + batch: int, + seq_len_kv: int, + num_heads: int, + repair_tiles: int, + seq_len_q: int, + repair_tokens: int, +): + """The kernels of one geometry. ``seq_len_q`` is 0 under QK16 and ``repair_tokens`` is 0 + without repair. Absent operands are ``None`` at compile time as at run time. + + Each kernel goes through the PrimTS on-disk CuTe DSL cache like the context + kernels, keyed by this geometry and the attention source tree, so a process + loads a kernel it or an earlier process compiled on this machine. + """ + cdt, is_bf16 = _in_dtype(dtype) + spec = ( + str(dtype), + demean, + batch, + seq_len_kv, + num_heads, + repair_tiles, + seq_len_q, + repair_tokens, + ) + + def build(kind, compile_fn): + return build_and_load_attention_kernel( + "vc_prepare", kind, spec, _COMPILE_OPTIONS, compile_fn + ) + + stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) + f32 = lambda: _fake1d(Float32, 64) # noqa: E731 + i32 = lambda: _fake1d(Int32, 16) # noqa: E731 + e4m3 = lambda: _fake1d(cutlass.Float8E4M3FN, 16) # noqa: E731 + x16 = lambda: _fake1d(cdt) # noqa: E731 + qk8, repair = seq_len_q > 0, repair_tiles > 0 + shape = (is_bf16, batch, seq_len_kv, num_heads, repair_tiles) + perm = None if repair else i32() + kperm = None if qk8 else x16() + ksum = f32() if qk8 else None + k = { + "p1": build( + "p1", + lambda: cute.compile( + VcKvPass1(*shape, demean), + x16(), + x16(), + perm, + kperm, + f32(), + ksum, + f32(), + stream, + options=_COMPILE_OPTIONS, + ), + ), + "p2": build( + "p2", + lambda: cute.compile( + VcKvPass2(*shape), + x16(), + perm, + f32(), + ksum, + f32(), + f32(), + e4m3(), + None if repair else _fake1d(cutlass.BFloat16), + f32() if repair else None, + stream, + options=_COMPILE_OPTIONS, + ), + ), + } + if repair: + k["select"] = build( + "select", + lambda: cute.compile( + VcSelectPass(*shape, repair_tokens), + f32(), + i32(), + stream, + options=_COMPILE_OPTIONS, + ), + ) + k["rows"] = build( + "rows", + lambda: cute.compile( + VcRepairRowsPass(*shape, repair_tokens), + None if qk8 else x16(), + x16(), + i32(), + f32(), + None if qk8 else x16(), + e4m3(), + stream, + options=_COMPILE_OPTIONS, + ), + ) + if qk8: + k["qk"] = build( + "qk", + lambda: cute.compile( + VcQKPass(*shape, seq_len_q, repair_tokens), + x16(), + x16(), + perm, + i32() if repair else None, + f32(), + e4m3(), + e4m3(), + f32(), + f32(), + stream, + options=_COMPILE_OPTIONS, + ), + ) + return k + + +@torch.no_grad() +def vc_prepare( + k: torch.Tensor, v: torch.Tensor, perm: torch.Tensor, *, demean: bool = True +): + """VC-Attention-QK16 operands ``(k_perm, v8, v_scale, mean, mu)`` of + contiguous ``[B, S, H, D]`` K and V in ``perm`` order.""" + return _prepare(None, k, v, perm, demean=demean, repair_tiles=0, repair_tokens=0)[ + :5 + ] + + +@torch.no_grad() +def vc_prepare_fp8( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + perm: torch.Tensor, + *, + demean: bool = True, +): + """VC-Attention-QK8 operands ``(q8, k8, v8, q_scale, k_scale, v_scale, mean, + mu)`` of contiguous ``[B, S, H, D]`` Q, K and V, K and V in ``perm`` order.""" + if q.shape[-1] != VC_HEAD_DIM or not q.is_contiguous(): + raise ValueError( + f"VC fused preparation needs contiguous head_dim {VC_HEAD_DIM} Q" + ) + k8, v8, v_scale, mean, mu, q8, q_scale, k_scale = _prepare( + q, k, v, perm, demean=demean, repair_tiles=0, repair_tokens=0 + ) + return q8, k8, v8, q_scale, k_scale, v_scale, mean, mu + + +@torch.no_grad() +def vc_prepare_repair( + q: torch.Tensor | None, + k: torch.Tensor, + v: torch.Tensor, + *, + repair_tiles: int, + repair_tokens: int, +): + """V repair operands ``(q8, k_all, v_all, q_scale, k_scale, v_scale)`` in + input order plus ``repair_tiles`` tiles of the ``repair_tokens`` largest-residual + tokens. The QK8 entries are ``None`` under QK16.""" + if q is not None and (q.shape[-1] != VC_HEAD_DIM or not q.is_contiguous()): + raise ValueError( + f"VC fused preparation needs contiguous head_dim {VC_HEAD_DIM} Q" + ) + if not 0 < repair_tokens <= min(repair_tiles * VC_K_BLOCK_SIZE, k.shape[1]): + raise ValueError("repair_tokens must fit the repair tiles and the sequence") + k_all, v_all, v_scale, _, _, q8, q_scale, k_scale = _prepare( + q, + k, + v, + None, + demean=False, + repair_tiles=repair_tiles, + repair_tokens=repair_tokens, + ) + return q8, k_all, v_all, q_scale, k_scale, v_scale + + +def _prepare(q, k, v, perm, *, demean: bool, repair_tiles: int, repair_tokens: int): + """Run the passes and return ``(k_out, v8, v_scale, mean, mu, q8, q_scale, + k_scale)``. ``q`` selects QK8 and the QK8 outputs are ``None`` without it.""" + b, s_k, h, d = k.shape + if d != VC_HEAD_DIM: + raise ValueError(f"VC fused preparation supports head_dim {VC_HEAD_DIM} only") + if not (k.is_contiguous() and v.is_contiguous()): + raise ValueError("k and v must be contiguous") + dev = k.device + t = (s_k + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE + repair = repair_tiles > 0 + rows = vc_repair_kv_len(s_k, repair_tiles) if repair else s_k + s_q = 0 if q is None else q.shape[1] + with torch.cuda.device(dev): + ker = _compiled( + k.dtype, bool(demean), b, s_k, h, repair_tiles, s_q, repair_tokens + ) + if not repair and ( + perm is None or tuple(perm.shape) != (b, h, s_k) or perm.device != dev + ): + raise ValueError(f"perm must be a [B, H, S_k] index tensor on {dev}") + perm32 = None if repair else perm.to(torch.int32).contiguous() + stats = torch.zeros((b, h, 2, d), dtype=torch.float32, device=dev) + mean = torch.empty((b, h, t, d), dtype=torch.float32, device=dev) + v8 = torch.empty((b, rows, h, d), dtype=torch.float8_e4m3fn, device=dev) + v_scale = torch.empty((b, h, d), dtype=torch.float32, device=dev) + k_perm = k_sum = mu = energy = index = None + if q is None: + k_perm = torch.empty((b, rows, h, d), dtype=k.dtype, device=dev) + else: + k_sum = torch.empty((b, h, t, d), dtype=torch.float32, device=dev) + if repair: + energy = torch.empty((b, h, s_k), dtype=torch.float32, device=dev) + index = torch.empty((b, h, repair_tokens), dtype=torch.int32, device=dev) + else: + groups = (t + VC_MEAN_GROUP_TILES - 1) // VC_MEAN_GROUP_TILES + mu = torch.empty( + (b, h, groups, *vc_mean_group_shape(d)), dtype=torch.bfloat16, device=dev + ) + flat = lambda x: None if x is None else x.view(-1) # noqa: E731 + ker["p1"]( + flat(k), + flat(v), + flat(perm32), + flat(k_perm), + flat(mean), + flat(k_sum), + flat(stats), + ) + ker["p2"]( + flat(v), + flat(perm32), + flat(mean), + flat(k_sum), + flat(stats), + flat(v_scale), + flat(v8), + flat(mu), + flat(energy), + ) + if repair: + ker["select"](flat(energy), flat(index)) + ker["rows"]( + flat(k) if q is None else None, + flat(v), + flat(index), + flat(stats), + flat(k_perm), + flat(v8), + ) + if q is None: + return k_perm, v8, v_scale, mean, mu, None, None, None + k8 = torch.empty((b, rows, h, d), dtype=torch.float8_e4m3fn, device=dev) + q8 = torch.empty((b, s_q, h, d), dtype=torch.float8_e4m3fn, device=dev) + k_scale = torch.empty( + (h, b, (rows + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE), + dtype=torch.float32, + device=dev, + ) + q_scale = torch.empty( + (h, b, (s_q + VC_K_BLOCK_SIZE - 1) // VC_K_BLOCK_SIZE), + dtype=torch.float32, + device=dev, + ) + ker["qk"]( + flat(q), + flat(k), + flat(perm32), + flat(index), + flat(stats), + flat(q8), + flat(k8), + flat(q_scale), + flat(k_scale), + ) + return k8, v8, v_scale, mean, mu, q8, q_scale, k_scale diff --git a/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/quantization.py b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/quantization.py new file mode 100644 index 000000000000..3d42d1b718c3 --- /dev/null +++ b/tensorrt_llm/_torch/attention/backends/prims_ts/vc_attention/quantization.py @@ -0,0 +1,503 @@ +# Copyright (c) 2026 by FlashInfer team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""VC-Attention quantization of Q, K and V for the prims_ts context kernel. + +VC-Attention (arXiv 2609.15810) adds two changes on the value side of +attention: a token permutation that groups similar value rows into the same +128-token K/V tile, and per-tile value smoothing. Each V tile is stored as E4M3 +residuals around its tile mean and the kernel restores the mean inside the +online softmax, so the residual quantization error no longer carries the value +DC component. P is E4M3 through the ExpCast path in both recipes of the Q/K +side. VC-Attention-QK16 keeps Q and K in bf16. VC-Attention-QK8 centres K by +its per-head channel mean, rotates Q and K by the normalised 128-point Hadamard +matrix and quantizes them to E4M3 with one scale per 128-token Q block and per +128-token K tile, as the paper does. + +* ``vc_token_permutation`` runs an online k-means over value rows, one + permutation per batch and head, applied to K and V. Attention is invariant + to a common key and value permutation. +* ``vc_quantize`` permutes K, subtracts the V tile means, quantizes the + residuals per channel to E4M3 and packs the kernel operands with the CuTe + DSL kernels of ``prepare``. +* ``vc_quantize_fp8`` does the same plus the E4M3 Q/K operands and scales. +* ``vc_quantize_repair`` writes V repair rows instead of tile means, for + either recipe. +* ``VCAttentionPreprocessor`` applies the paper's V-Smooth schedule over the + denoising steps on top of the two. + +The operand contract the kernel consumes is defined in +``flashinfer.attention.prims_ts.vc_attention``. +""" + +from __future__ import annotations + +import functools +import math +from dataclasses import dataclass +from typing import Any + +import torch + +from . import ( + VC_HEAD_DIM, + VCAttentionParams, + vc_repair_tiles, +) + +# V-Smooth schedule. The paper groups and demeans on the first quarter of the +# denoising steps and keeps the permutation afterwards. The refresh cadence +# inside that window and the k-means size are not fixed by the paper. 64 +# clusters sort the values into 128-token tiles of similar rows while keeping +# the online k-means a small fraction of the attention call, and 3 iterations +# are enough because every refresh warm-starts from the previous centroids. +VC_SMOOTH_STEP_FRACTION = 0.25 +VC_PERM_REFRESH_EVERY = 4 +VC_KMEANS_CLUSTERS = 64 +VC_KMEANS_ITERS = 3 + + +@dataclass(frozen=True) +class VCAttentionOperands: + """Everything one VC-Attention forward needs, in kernel layout. + + ``k`` is the input in permuted token order; ``v`` is E4M3 ``[B, S, H, D]`` + in the same order holding the tile residuals ``(V[perm] - mean) / v_scale``. + Under VC-Attention-QK8 ``q`` and ``k`` are the rotated E4M3 operands and + ``q_scale`` and ``k_scale`` their per-block scales; under QK16 those + three are ``None`` and the caller's bf16 ``q`` is used as is. With + ``repair_tiles`` the token order is the input order, ``mean``, ``mu`` and + ``perm`` are ``None`` and the K/V rows are the whole 128-token tiles, the + repair tiles of key copies and E4M3 value residuals, then the zero-padded + partial last tile. + """ + + k: torch.Tensor + v: torch.Tensor + v_scale: ( + torch.Tensor + ) # [B, H, D] fp32 per-channel E4M3 residual scale (feeds output_scale) + mean: ( + torch.Tensor | None + ) # [B, H, num_kv_tiles, D] fp32 tile means (permuted order) + mu: ( + torch.Tensor | None + ) # [B, H, ceil(num_kv_tiles / 16), 16, 256] bf16 packed kernel operands + perm: torch.Tensor | None # [B, H, S_k] int32/int64 token permutation + demean: bool = True # whether the means were subtracted (else zero) + repair_tiles: int = 0 + seq_len_kv: int | None = None # K/V tokens before the repair tiles and padding + q: torch.Tensor | None = None # [B, S_q, H, D] E4M3 rotated Q (QK8) + q_scale: torch.Tensor | None = None # [H, B, ceil(S_q / 128)] fp32 + k_scale: torch.Tensor | None = None # [H, B, ceil(S_k / 128)] fp32 + + @property + def params(self) -> "VCAttentionParams": + """The per-run operands ``BatchPrefillTSWrapper.run`` takes as ``vc``.""" + return VCAttentionParams( + q_scale=self.q_scale, + k_scale=self.k_scale, + v_scale=self.v_scale, + tile_means=self.mu, + ) + + +@functools.lru_cache(maxsize=None) +def _hadamard_matrix_cached(d: int, device: str) -> torch.Tensor: + h = torch.ones((1, 1), dtype=torch.float32) + while h.shape[0] < d: + h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0) + return (h / math.sqrt(d)).to(device) + + +def hadamard_matrix(d: int, device: torch.device) -> torch.Tensor: + """Normalised Sylvester Hadamard matrix ``[d, d]`` (``d`` a power of two).""" + if d & (d - 1): + raise ValueError("head_dim must be a power of two for the Hadamard rotation") + return _hadamard_matrix_cached(d, str(device)) + + +@torch.no_grad() +def vc_token_permutation( + v: torch.Tensor, + *, + num_clusters: int | None = None, + iters: int = VC_KMEANS_ITERS, + generator: torch.Generator | None = None, + init_centroids: torch.Tensor | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Group similar value rows by k-means per batch and head, then argsort the labels. + + Returns the int64 permutation ``[B, H, S]`` and the ``[B*H, k, D]`` centroids. + ``V[b, perm[b, h], h]`` lists the tokens cluster by cluster, so 128-token K/V + tiles hold similar values and their tile means remove most of the value + energy. ``init_centroids`` from a previous call warm-starts the clustering, + as the paper does when the grouping is refreshed a few denoising steps later. + """ + b, s, h, d = v.shape + if num_clusters is None: + num_clusters = VC_KMEANS_CLUSTERS + # Seeding draws distinct value rows, so a short sequence caps the clusters. + num_clusters = min(num_clusters, s) + n_groups = b * h + # Work on a few heads at a time so the fp32 copy of V and the distance + # matrix each stay under 0.75 GB. + per_group = 4 * s * max(d, num_clusters) + chunk_h = max(1, min(h, int(0.75e9 // per_group))) + perm_out = torch.empty((b, h, s), dtype=torch.int64, device=v.device) + cent_out = torch.empty( + (n_groups, num_clusters, d), dtype=torch.float32, device=v.device + ) + warm = init_centroids is not None and tuple(init_centroids.shape) == ( + n_groups, + num_clusters, + d, + ) + for bi in range(b): + for h0 in range(0, h, chunk_h): + h1 = min(h, h0 + chunk_h) + gsz = h1 - h0 + g0 = bi * h + h0 + x = v[bi, :, h0:h1, :].permute(1, 0, 2).float() # [G, S, D] + if warm: + centroids = init_centroids[g0 : g0 + gsz].to(x.dtype) + else: + idx = torch.stack( + [ + torch.randperm(s, device=v.device, generator=generator)[ + :num_clusters + ] + for _ in range(gsz) + ] + ) # [G, k] + centroids = torch.gather( + x, 1, idx.unsqueeze(-1).expand(-1, -1, d) + ) # [G, k, D] + x_sq = (x * x).sum(-1, keepdim=True) # [G, S, 1] + labels = None + for _ in range(iters): + c_sq = (centroids * centroids).sum(-1).unsqueeze(1) # [G, 1, k] + dist = x_sq + c_sq - 2.0 * torch.bmm(x, centroids.transpose(1, 2)) + labels = dist.argmin(dim=-1) # [G, S] + del dist + counts = torch.zeros( + gsz, num_clusters, device=v.device, dtype=torch.float32 + ) + counts.scatter_add_( + 1, labels, torch.ones_like(labels, dtype=torch.float32) + ) + sums = torch.zeros_like(centroids) + sums.scatter_add_(1, labels.unsqueeze(-1).expand(-1, -1, d), x) + nonempty = counts > 0 + centroids = torch.where( + nonempty.unsqueeze(-1), + sums / counts.clamp_min(1.0).unsqueeze(-1), + centroids, + ) + assert labels is not None + perm_out[bi, h0:h1] = torch.argsort(labels, dim=-1, stable=True) + cent_out[g0 : g0 + gsz] = centroids + del x, x_sq + return perm_out, cent_out + + +# --------------------------------------------------------------------------- +# Preprocessing (CuTe DSL kernels in prepare.py) +# --------------------------------------------------------------------------- +def _check_prepare_inputs(x: torch.Tensor) -> None: + if ( + x.shape[-1] != VC_HEAD_DIM + or x.dtype not in (torch.bfloat16, torch.float16) + or not x.is_cuda + ): + raise ValueError( + f"VC-Attention preparation needs CUDA bf16/fp16 inputs with head_dim {VC_HEAD_DIM}, " + f"got {x.dtype} {tuple(x.shape)} on {x.device}" + ) + + +@torch.no_grad() +def vc_quantize( + k: torch.Tensor, + v: torch.Tensor, + *, + perm: torch.Tensor | None = None, + kmeans_iters: int = VC_KMEANS_ITERS, + generator: torch.Generator | None = None, + demean: bool = True, +) -> VCAttentionOperands: + """Turn ``[B, S, H, D]`` bf16/fp16 K/V into VC-Attention-QK16 kernel + operands with two CuTe DSL kernels (``prepare``). + + Keys are permuted with the values and kept in their dtype. Values are + permuted, split into 128-token tile means and residuals (``demean=False`` + keeps the means at zero), and the residuals are quantized to E4M3 with one + scale per (batch, head, channel), returned as ``v_scale`` for the run's + ``vc`` operands. Pass 1 gathers each permuted tile once, writes the + permuted K rows, the V tile mean and residual amax; pass 2 writes the E4M3 + residuals and the packed bf16 mean operand. Requires CUDA bf16/fp16 inputs + with head_dim 128. + """ + if k.dim() != 4 or k.shape != v.shape or k.dtype != v.dtype: + raise ValueError("k and v must be [B, S, H, D] with matching shapes and dtype") + _check_prepare_inputs(k) + from .prepare import vc_prepare + + if perm is None: + perm = vc_token_permutation(v, iters=kmeans_iters, generator=generator)[0] + k_p, v8, v_scale, mean, mu = vc_prepare( + k.contiguous(), + v.contiguous(), + perm, + demean=demean, + ) + return VCAttentionOperands( + k=k_p, + v=v8, + v_scale=v_scale, + mean=mean, + mu=mu if demean else None, + perm=perm, + demean=demean, + ) + + +@torch.no_grad() +def vc_quantize_fp8( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + *, + perm: torch.Tensor | None = None, + kmeans_iters: int = VC_KMEANS_ITERS, + generator: torch.Generator | None = None, + demean: bool = True, +) -> VCAttentionOperands: + """Turn ``[B, S, H, D]`` bf16/fp16 Q/K/V into VC-Attention-QK8 kernel + operands with four CuTe DSL kernels (``prepare``). + + Keys are centred by their per-(batch, head) channel mean over tokens + (softmax-invariant), permuted with the values, rotated with Q by the + normalised Hadamard matrix and quantized to E4M3 with one scale per + 128-token tile; queries take one E4M3 scale per 128-token block. Values + are prepared as in ``vc_quantize``. Requires CUDA bf16/fp16 inputs with + head_dim 128. + """ + if ( + q.dim() != 4 + or k.shape != v.shape + or q.shape[0] != k.shape[0] + or q.shape[2:] != k.shape[2:] + or q.dtype != k.dtype + or k.dtype != v.dtype + ): + raise ValueError( + "q, k, v must be [B, S, H, D] with matching batch, heads, head_dim and dtype" + ) + _check_prepare_inputs(q) + from .prepare import vc_prepare_fp8 + + if perm is None: + perm = vc_token_permutation(v, iters=kmeans_iters, generator=generator)[0] + q8, k8, v8, q_scale, k_scale, v_scale, mean, mu = vc_prepare_fp8( + q.contiguous(), k.contiguous(), v.contiguous(), perm, demean=demean + ) + return VCAttentionOperands( + k=k8, + v=v8, + v_scale=v_scale, + mean=mean, + mu=mu if demean else None, + perm=perm, + demean=demean, + q=q8, + q_scale=q_scale, + k_scale=k_scale, + ) + + +@torch.no_grad() +def vc_quantize_repair( + k: torch.Tensor, + v: torch.Tensor, + *, + budget: float, + q: torch.Tensor | None = None, +) -> VCAttentionOperands: + """Turn ``[B, S, H, D]`` K/V into V repair operands, of VC-Attention-QK8 + with ``q``. + + Values are quantized to E4M3 in input order with one scale per batch, + head and channel. The ``budget`` fraction of tokens with the largest + residual energy per batch and head gets a repair row, a copy of the key + (under QK8 re-centred, rotated and quantized with the repair tile's own + scale) with the E4M3 residual of the value. + """ + if k.dim() != 4 or k.shape != v.shape or k.dtype != v.dtype: + raise ValueError("k and v must be [B, S, H, D] with matching shapes and dtype") + if q is not None and ( + q.dim() != 4 + or q.shape[0] != k.shape[0] + or q.shape[2:] != k.shape[2:] + or q.dtype != k.dtype + ): + raise ValueError( + "q must be [B, S, H, D] with the batch, heads, head_dim and dtype of k" + ) + _check_prepare_inputs(k) + from .prepare import vc_prepare_repair + + s_k = k.shape[1] + repair_tiles = vc_repair_tiles(s_k, budget) + repair_tokens = max(1, round(budget * s_k)) + q8, k_all, v_all, q_scale, k_scale, v_scale = vc_prepare_repair( + None if q is None else q.contiguous(), + k.contiguous(), + v.contiguous(), + repair_tiles=repair_tiles, + repair_tokens=repair_tokens, + ) + return VCAttentionOperands( + k=k_all, + v=v_all, + v_scale=v_scale, + mean=None, + mu=None, + perm=None, + demean=False, + repair_tiles=repair_tiles, + seq_len_kv=s_k, + q=q8, + q_scale=q_scale, + k_scale=k_scale, + ) + + +class VCAttentionPreprocessor: + """Caller-owned preparation of bf16 K/V with the paper's V-Smooth schedule. + + Value grouping and demeaning run on the first ``smooth_step_fraction`` of + the denoising steps. Inside that window the token permutation is + recomputed every ``perm_refresh_every`` steps (k-means warm-started from + the previous centroids) and kept afterwards, when the plain per-channel + E4M3 V runs with zero tile means. ``kmeans_clusters`` (``None`` = 64) and + ``kmeans_iters`` parametrize the online k-means. Without a denoise step + the grouping is computed once per K/V geometry and kept. With ``q`` the + preparation is the VC-Attention-QK8 one (one E4M3 Q scale per 128 tokens). + """ + + def __init__( + self, + *, + smooth_step_fraction: float = VC_SMOOTH_STEP_FRACTION, + perm_refresh_every: int = VC_PERM_REFRESH_EVERY, + kmeans_clusters: int | None = None, + kmeans_iters: int = VC_KMEANS_ITERS, + ) -> None: + if not (0.0 <= smooth_step_fraction <= 1.0): + raise ValueError("smooth_step_fraction must be in [0, 1]") + if perm_refresh_every < 1: + raise ValueError("perm_refresh_every must be at least 1") + if kmeans_clusters is not None and kmeans_clusters < 1: + raise ValueError("kmeans_clusters must be at least 1") + if kmeans_iters < 1: + raise ValueError("kmeans_iters must be at least 1") + self.smooth_step_fraction = smooth_step_fraction + self.perm_refresh_every = perm_refresh_every + self.kmeans_clusters = kmeans_clusters + self.kmeans_iters = kmeans_iters + # Per (batch, seq_len_k, num_kv_heads): perm, centroids, step of the last refresh. + self._groupings: dict[tuple[int, int, int], dict[str, Any]] = {} + + @torch.no_grad() + @torch.compiler.disable + def prepare( + self, + k: torch.Tensor, + v: torch.Tensor, + *, + q: torch.Tensor | None = None, + denoise_step: tuple[int, int] | None = None, + ) -> VCAttentionOperands: + """Return the operands of one run for ``[B, S, H, D]`` bf16 K/V, and Q + under VC-Attention-QK8. + + ``denoise_step`` is the sampler's ``(step_index, num_steps)``. Kept + out of torch.compile so the step index and the k-means refresh do not + recompile the caller per step. + """ + key = (k.shape[0], k.shape[1], k.shape[2]) + entry = self._groupings.get(key) + smooth = True + refresh = entry is None + if denoise_step is not None: + step_idx, num_steps = denoise_step + smooth = step_idx < math.ceil(self.smooth_step_fraction * num_steps) + # Step 0 starts a new generation, so it always regroups. + refresh = smooth and ( + entry is None + or step_idx == 0 + or ( + step_idx % self.perm_refresh_every == 0 + and entry["step"] != step_idx + ) + ) + if smooth: + if refresh: + perm, centroids = vc_token_permutation( + v, + num_clusters=self.kmeans_clusters, + iters=self.kmeans_iters, + init_centroids=None if entry is None else entry["centroids"], + ) + step = None if denoise_step is None else denoise_step[0] + if entry is None: + entry = { + "perm": perm.to(torch.int32), + "centroids": centroids, + "step": step, + } + self._groupings[key] = entry + else: + # The buffers keep their addresses, so a CUDA graph captured around one call + # reads the grouping that later calls or replays write into them. + entry["perm"].copy_(perm.to(torch.int32)) + entry["centroids"].copy_(centroids) + entry["step"] = step + perm = entry["perm"] + elif entry is not None: + # V-Smooth off (paper Section 3.4). The plain kernel runs on the last + # permutation with zero tile means. + perm = entry["perm"] + else: + perm = torch.arange(k.shape[1], device=k.device, dtype=torch.int32) + perm = perm.view(1, 1, -1).expand(k.shape[0], k.shape[2], -1).contiguous() + if q is not None: + return vc_quantize_fp8(q, k, v, perm=perm, demean=smooth) + return vc_quantize(k, v, perm=perm, demean=smooth) + + +__all__ = [ + "VC_KMEANS_CLUSTERS", + "VC_KMEANS_ITERS", + "VC_PERM_REFRESH_EVERY", + "VC_SMOOTH_STEP_FRACTION", + "VCAttentionOperands", + "VCAttentionPreprocessor", + "hadamard_matrix", + "vc_quantize", + "vc_quantize_fp8", + "vc_quantize_repair", + "vc_token_permutation", +]