diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/README.md b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/README.md new file mode 100644 index 000000000000..be14a7a4d196 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/README.md @@ -0,0 +1,131 @@ + + + +# specDSA (speculative DSA) + +Fused decode kernels for the DeepSeek sparse attention (DSA) of a decode step on Blackwell: the indexer logits, the +exact top-K selection, the loads of the selected KV rows and the dense attention over them. The selection is exact. The +megakernel (few rows) guesses the top-K threshold from a sample of the row's own logits, with the rung formulas of the +sampling ladder of the GVR V2 top-K (a copy in this package, nothing is imported), and checks the guess with a count +certificate; a row where the guess does not hold takes an exact fallback. The large-batch kernels (many rows) take no +sample: each CTA keeps the candidates of its row segment above a floor that it raises from the candidates it has +admitted so far, and selects the exact top-K from the ones kept. The tail-attention hybrid (a middle range of rows of +the FP4 spec) keeps the production indexer logits kernel and replaces the rest of the chain with a multi-CTA exact +top-K and a fused attention kernel. "spec" here is this speculation on the selection threshold, not speculative +decoding (MTP). + +The kernels of this package are specialized for the specs of one model, DS-V4-Flash with an FP8 or an MXFP4 indexer K +cache. `config.py` defines what a spec is and which specs have kernels; the rest of this file says where the parts that +differ between models live and how to add a model. + +## Files + +| File | Role | +| --- | --- | +| `config.py` | `SpecDsaConfig` (the compile-time shape of a model), the specs, the support check | +| `op.py` | the interface (`prepare`, `run`, `precompile`, `error_bits`, `implementation_for`, `is_supported`); picks the implementation of a batch size (`implementation=` forces another one that can serve it) | +| `megakernel_op.py`, `large_batch_op.py` | host side of each implementation (state, argument checks, engine cache); import-safe without CuTe DSL | +| `hybrid_op.py` | host side of the tail-attention hybrid behind the same interface (FP4 spec, 5 to 26 rows): the state holds the compressed lengths, the scheduler metadata of the production logits kernel and the sinks; `run` is the production logits op, the multi-CTA top-K and the tail attention; `precompile` also warms the production logits op; import-safe without CuTe DSL | +| `megakernel.py`, `megakernel_attention.py`, `megakernel_lib.py` | megakernel: kernel and row descriptors, attention (KV gather, MMA, softmax), PTX helpers and selection primitives | +| `large_batch.py`, `large_batch_lib.py` | large-batch kernels: indexer kernel and attention tail, selection routines and the ready queue | +| `tail_attention.py`, `tail_op.py` | tail attention: the decode sparse MLA of up to 26 rows behind any exact top-K kernel, the KV tiles of a row split over a cluster of 5 CTAs with the combine inside the cluster (host side: `run_attention`, `run_hybrid`) | +| `topk_multicta.py`, `topk_multicta_op.py` | multi-CTA exact top-512 of the fp32 indexer logits for the tail-attention hybrid (1 to 26 rows): a cluster of 4 to 8 CTAs per row, a sampled threshold, one all-gather round of the candidate histograms, an in-kernel exact fallback (host side: `run`, `precompile`, `is_supported`, `is_profitable`) | + +## Implementations and specs + +- Megakernel: one cooperative launch per step, up to `megakernel_max_batch` rows. +- Large-batch kernels: a persistent indexer kernel and an attention kernel behind it (programmatic dependent launch), + every batch size up to `max_batch`; one compile per knob range (`large_batch_op`) serves every batch size in it. + +- Tail attention (decomposed hybrid): the production indexer kernel and the production top-K kernel, then one kernel + that replaces the local-to-global mapping, the sparse MLA and its reduction kernel of the unfused chain. A cluster of + 5 CTAs serve a row (up to 26 rows, the clusters of 5 that fit one wave at one CTA per SM): + every CTA runs the attention of its KV tiles with a local softmax maximum, the partial outputs are combined through + distributed shared memory. Plain stream-ordered launch behind the production top-K kernel (it never triggers a dependent + launch); behind the multi-CTA top-K (below) a programmatic dependent launch (`pdl`). + Against the production FP4 chain (1M-token captures, B200) the fastest path per batch size is the megakernel up to 4 rows, + the tail attention from 5 to 26 rows and the large-batch kernels above. + The top-K stage of the hybrid can be the multi-CTA top-K (`tail_op.run_hybrid(..., topk_fn=None, ctx_lens=...)`, or + `topk_multicta_op.run`): a cluster of 8 / 6 / 5 / 4 CTAs per row (1-15 / 16 / 17-24 / 25-26 rows) selects the exact + top-512 of the logits in one pass over the row. It is exact for every input (a row whose sampled threshold does not + certify the fast path takes an in-kernel radix select) and is the faster top-K stage when every row has 16,384 + positions or more (`topk_multicta_op.is_profitable`; 64K tokens at the compression ratio 4); shorter rows are exact too + but win nothing, so the caller keeps its production top-K for them. Its CTAs launch the tail attention (programmatic + dependent launch, `trigger`) when their stream phase is done, so that the tail attention's prologue (barrier and TMEM + setup, query load, sliding-window tile) overlaps the end of the top-K kernel: `run_hybrid` does it by default with this + top-K up to 24 rows (`pdl=None`, `tail_op.default_pdl`; at 25 and 26 rows the clusters of the tail attention fill + the wave and the plain launches are faster), the results are the same. With `poll` (default: on with `pdl` up to 23 + rows, `tail_op.default_poll`) the tail attention does not even wait for the end of the top-K grid: the top-K marks + its output entries -2 at its start (`arm`) and writes each one exactly once, and the tail attention reads the + entries of its row as they appear, so that a row is served when its own top-K cluster is done and not when the + slowest row of the batch is. The two flags go together (`topk_multicta_op.run(trigger=True, arm=True)`, + `run_attention(pdl=True, poll=True)` behind it on the same `topk` tensor); `run_hybrid` sets both. + +### Dispatch + +`op.implementation_for(batch_size, config)` picks the implementation: the tail hybrid inside the spec's +`tail_hybrid_range`, else the megakernel up to `megakernel_max_batch`, else the large-batch kernels. The range is +host-side dispatch data, not part of `kernel_key`. The last three columns of the table below are the default ranges. + +For the FP4 spec `op.run` runs the hybrid at 5 to 26 rows (`hybrid_op.py`): the indexer logits op of the production +MXFP4 chain (`torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits`, into a logits buffer of `max_index_len` columns so that +a captured launch has fixed shapes; the kernel writes each row's valid length), the multi-CTA top-K and the tail +attention, with the `pdl` / `poll` defaults of `tail_op.run_hybrid`. `prepare` keeps the compressed lengths on the +device and builds the scheduler metadata of the logits op (`tensorrt_llm.deep_gemm.get_paged_mqa_logits_metadata`) from +them, both in persistent buffers that it refreshes in place, so a captured graph replays over them. The logits op and +the top-K read that copy of the lengths, never the `ctx_lens` argument of `run`. `precompile` compiles the two kernels +in the variant `run` launches and launches the logits op once on dummy data (its first call compiles it, which must not +happen inside a capture). + +The hybrid is the one implementation that is not self-contained: the production logits op has to be registered (CuTe +DSL installed) together with its scheduler metadata function. Both are resolved when first used; a missing one is a +`RuntimeError` that names it (`hybrid_op.is_supported`, or `op.is_supported(..., batch_size=)`, tells beforehand), there +is no fallback. It has no device-side error flag: `error_bits` is a zero view, and a state that was not refreshed for +the step is not detected (the launch computes for the lengths of the last `prepare`). It takes contiguous +`idx_block_table`, `bt_swa` and `bt_c` and an int32 [B] `kv_lens` only (the megakernel also takes strided block tables). +The logits buffer belongs to the production op, so hybrid launches, and that op's other users, must be stream-ordered +with respect to each other, also across states. + +The hybrid is tuned for rows of 1M tokens. Its top-K is exact for every row length, but the faster top-K stage only for +rows of 16,384 positions or more (`topk_multicta_op.is_profitable`). The megakernel can serve up to 20 rows of the FP4 +spec (`megakernel_max_batch`) and stays selectable there: `prepare(..., implementation="megakernel")` and +`precompile(..., implementation="megakernel")` force an implementation that can serve the batch size (the large-batch +kernels any batch size, the hybrid its range). A state remembers its implementation. + +| Spec | Indexer (heads x dim, K dtype) | Top-K | Compression | KV rows | Megakernel | Tail hybrid | Large batch | +| --- | --- | --- | --- | --- | --- | --- | --- | +| DS-V4-Flash | 64 x 128, fp8 | 512 | 4 | E4M3 rows, window 128, sink | 1 to 47 rows | none | 48 to 1,024 rows | +| DS-V4-Flash-FP4 | 64 x 128, fp4 | 512 | 4 | E4M3 rows, window 128, sink | 1 to 4 rows | 5 to 26 rows | 27 to 1,024 rows | + +`is_supported(device, config)` and `implementation_for(batch_size, config)` answer from this table. For a config that is +not in it `is_supported` returns `(False, reason)` and `precompile`, `prepare` and `implementation_for` raise +`NotImplementedError` (a state carries the spec it was prepared for, so `run` needs no config); the caller keeps the +existing kernels for it. A config with lower batch-size limits or a narrower `tail_hybrid_range` is served (the other +batch sizes go to the other implementations); one with a range the spec does not have is refused. Indexer shapes of +other DeepSeek models are in `config.KNOWN_SHAPES` (V3.2: 64 x 128, top-2048, no compression; V4-Pro: top-1024, 4x +compression); they have no spec yet. + +## What differs between models, and where it goes + +| Axis | Examples | Where | +| --- | --- | --- | +| Numbers | top-K, compression ratio, heads, head dim, page sizes, window, longest row | `SpecDsaConfig` fields; the kernels define their structural constants from the spec and reject another `kernel_key` | +| Indexer K cache | fp8 or fp4 | `index_k_dtype`; a logits front end per dtype in the megakernel's stream CTAs and in the indexer kernel (fp4: block-scaled MXF4 MMA, the scale factors go to tensor memory with UTCCP; `run` takes the query scales as `q_scale`) | +| Selection | K sets the candidate buffers, the certificate bounds and the ladder of the megakernel's threshold guess | the selection primitives (`*_lib.py`); tuning that depends on K lives with them | +| KV format and dense attention | MLA latent KV (V3.2), E4M3 rows with a footer scale, window and sink (V4), the CSA2 cache (V4.1) | `kv_format`; one attention module per format (today `megakernel_attention.py` and the attention part of `large_batch.py`) | +| Schedule | teams, ring depth, batch-size ranges per implementation | the knob tables of the host modules, keyed by `kernel_key`; `megakernel_max_batch`, `large_batch` and `tail_hybrid_range` of the spec | + +Model names appear in `config.py` only. The code that builds a config from a model's configuration and decides when to +use these kernels belongs with the model's attention backend (`attention/backends/sparse/`), not here. + +## Adding a model + +1. Add the fields the model needs to `SpecDsaConfig` (with validation), and a spec to `SUPPORTED_SPECS`. Do not fork a + kernel: a number becomes a field, a different layout becomes a variant selected by a field. +2. Turn the module constants of the kernels that depend on the new fields into arguments of the kernel constructors + (today they come from `DS_V4_FLASH`). The code generated for DS-V4-Flash must not change: compare the PTX and IR of + the existing spec before and after (the megakernel at every batch-size range and both large-batch kernels). +3. Add the kernel variants (attention for a new KV format, logits for a new K dtype) and register them by the config field. +4. Validate the new spec on its own: the unit tests with its shapes, the 252-case real-capture gates (decode steps of + real captures of the model, strict top-K and attention checks), a mixed-length stress, and the batch-size sweep. +5. Document the spec in the table above. diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/__init__.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/__init__.py new file mode 100644 index 000000000000..41b92cbbd800 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/__init__.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA (speculative DSA): fused decode sparse attention of the DeepSeek DSA models for Blackwell. + +The indexer logits, the exact top-K selection, the mapping to compressed-KV rows and the sparse attention over the +selected rows run in one megakernel (few rows), in two kernels (many rows) or, for a middle range of rows of the MXFP4 +spec, in the tail-attention hybrid (the production indexer logits kernel, a multi-CTA top-K and a tail attention). The +megakernel guesses the top-K threshold from a sample of the row's own logits (the sampling ladder of the GVR V2 top-K) +and checks it with a count certificate; a row where the guess does not hold takes an exact fallback. The two-kernel path +takes no sample: it learns a floor from the candidates it has already admitted in the row and selects the exact top-K +from the ones kept. The selection is exact in all three. + +The kernels are specialized for a spec (:mod:`.config`); DeepSeek-V4-Flash is the one with kernels today (``README.md`` +lists the specs and how to add one). Import :mod:`.op` for the host side and :mod:`.config` for the specs; nothing is +re-exported here. +""" diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/config.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/config.py new file mode 100644 index 000000000000..2d97573e653f --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/config.py @@ -0,0 +1,370 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA configuration: the compile-time shape of one DSA model. + +A ``SpecDsaConfig`` holds what a specDSA kernel is specialized for: the indexer (heads, head dim, K-cache dtype and +page size, compression ratio), the selection (top-K, longest row), the attention (heads, KV row layout, sliding window, +attention sink) and the batch-size limits of the implementations. The limits are host-side dispatch data and not part +of ``kernel_key``. A ``SpecDsaConfig`` is frozen and hashable, validated when it is built, and independent of torch and +CuTe DSL, so it can be imported anywhere. + +The kernels of this package are specialized for one spec, ``DS_V4_FLASH``. ``SUPPORTED_SPECS`` lists the specs they were +built and validated for; their structural constants are defined from it and their constructors reject a config that +differs in ``kernel_key``. A model with another top-K, KV layout or indexer is a new spec plus the kernel variants it +needs, not a fork of the kernels (see ``README.md``). +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, replace + +__all__ = [ + "DS_V4_FLASH", + "DS_V4_FLASH_FP4", + "INDEX_TILE", + "KNOWN_SHAPES", + "NUM_SMS", + "SUPPORTED_SPECS", + "SpecDsaConfig", + "check_device", + "require_built_for", + "resolve_spec", + "supported_spec", +] + +# SMs of the device the kernels are built for (B200): one persistent CTA per SM. +NUM_SMS = 148 +# Compressed positions per indexer MMA tile (a property of the kernels, not of a model). +INDEX_TILE = 128 + +INDEX_K_DTYPES = ("fp8", "fp4") +KV_FORMATS = ("v4_e4m3_rows",) + + +@dataclass(frozen=True) +class SpecDsaConfig: + """The shape of one DSA model, as far as the specDSA kernels depend on it. + + Attributes: + name: label of the spec (the key of the model tables, e.g. ``"DS-V4-Flash"``); not part of ``kernel_key``. + index_heads: heads of the indexer. + index_head_dim: head dim of the indexer. + index_k_dtype: dtype of the indexer K cache, ``"fp8"`` (one E4M3 byte per element and a float32 scale per + 128 elements) or ``"fp4"`` (packed E2M1 and a UE8M0 exponent per 32 elements), as in the cache manager of + the DeepSeek-V4 attention backend. + index_page_tokens: compressed positions per indexer K page. + compress_ratio: positions of the sequence per compressed (indexer) position. + topk: positions selected per row. + max_index_len: longest row, in compressed positions. + attn_heads: heads of the attention. + kv_dim: elements (E4M3 bytes) of one KV row. + kv_format: layout of the KV cache rows, one of ``KV_FORMATS``. + kv_page_rows: compressed KV rows per page. + window: rows of the sliding window. + swa_page_rows: sliding-window rows per page. + has_sink: whether the attention has a per-head sink. + megakernel_max_batch: largest batch size the megakernel can serve (0: no megakernel). + large_batch: whether the large-batch kernels serve the batch sizes above the megakernel's. + max_batch: largest batch size. + tail_hybrid_range: first and last batch size of the tail-attention hybrid (the production indexer logits kernel, + the multi-CTA top-K and the tail attention), or None for no hybrid. Dispatch data only + (``op.implementation_for``): the hybrid's kernels do not depend on the spec, so it is not part of + ``kernel_key``. + """ + + name: str + index_heads: int + index_head_dim: int + index_k_dtype: str + index_page_tokens: int + compress_ratio: int + topk: int + max_index_len: int + attn_heads: int + kv_dim: int + kv_format: str + kv_page_rows: int + window: int + swa_page_rows: int + has_sink: bool + megakernel_max_batch: int + large_batch: bool + max_batch: int + tail_hybrid_range: tuple[int, int] | None = None + + def __post_init__(self): + def bad(msg): + raise ValueError(f"SpecDsaConfig {self.name!r}: {msg}") + + if not self.name: + raise ValueError("SpecDsaConfig: name must not be empty") + for field in ( + "index_heads", + "index_head_dim", + "index_page_tokens", + "compress_ratio", + "topk", + "max_index_len", + "attn_heads", + "kv_dim", + "kv_page_rows", + "window", + "swa_page_rows", + "max_batch", + ): + if not isinstance(getattr(self, field), int) or getattr(self, field) < 1: + bad(f"{field} must be a positive int, got {getattr(self, field)!r}") + if not isinstance(self.megakernel_max_batch, int) or self.megakernel_max_batch < 0: + bad(f"megakernel_max_batch must be an int >= 0, got {self.megakernel_max_batch!r}") + if self.index_k_dtype not in INDEX_K_DTYPES: + bad(f"index_k_dtype must be one of {INDEX_K_DTYPES}, got {self.index_k_dtype!r}") + if self.index_k_dtype == "fp8" and self.index_head_dim % 128: + bad( + "fp8 indexer K (a scale per 128 elements) needs index_head_dim to be a multiple of 128" + ) + if self.index_k_dtype == "fp4" and self.index_head_dim % 32: + bad("fp4 indexer K needs index_head_dim to be a multiple of 32") + if self.kv_format not in KV_FORMATS: + bad(f"kv_format must be one of {KV_FORMATS}, got {self.kv_format!r}") + if self.topk > self.max_index_len: + bad(f"topk {self.topk} exceeds max_index_len {self.max_index_len}") + if self.max_index_len % self.index_page_tokens: + bad("max_index_len must be a multiple of index_page_tokens") + if INDEX_TILE % self.index_page_tokens: + bad(f"index_page_tokens must divide the indexer tile ({INDEX_TILE})") + if self.megakernel_max_batch > self.max_batch: + bad("megakernel_max_batch exceeds max_batch") + if not self.large_batch and self.max_batch > self.megakernel_max_batch: + bad("batch sizes above megakernel_max_batch need the large-batch kernels") + rng = self.tail_hybrid_range + if rng is not None: + if ( + not isinstance(rng, tuple) + or len(rng) != 2 + or not all(isinstance(n, int) for n in rng) + ): + bad(f"tail_hybrid_range must be None or a tuple (first, last) of ints, got {rng!r}") + if not 1 <= rng[0] <= rng[1] <= self.max_batch: + bad( + f"tail_hybrid_range {rng} must satisfy 1 <= first <= last <= max_batch " + f"({self.max_batch})" + ) + + @property + def shape_key(self) -> tuple[int, int, int, int]: + """(index heads, index head dim, top-k, compression ratio): the key of the repository's model tables.""" + return (self.index_heads, self.index_head_dim, self.topk, self.compress_ratio) + + @property + def kernel_key(self) -> tuple: + """Everything the kernels are specialized for (the spec without its label and batch-size limits).""" + return ( + self.index_heads, + self.index_head_dim, + self.index_k_dtype, + self.index_page_tokens, + self.compress_ratio, + self.topk, + self.max_index_len, + self.attn_heads, + self.kv_dim, + self.kv_format, + self.kv_page_rows, + self.window, + self.swa_page_rows, + self.has_sink, + ) + + @property + def min_index_len(self) -> int: + """Shortest row: a row selects ``topk`` of its positions.""" + return self.topk + + @property + def selected_rows(self) -> int: + """KV rows an attention row reads: the sliding window, then the selection.""" + return self.window + self.topk + + @property + def pages_per_tile(self) -> int: + """Indexer K pages of one indexer tile.""" + return INDEX_TILE // self.index_page_tokens + + @property + def index_page_bytes(self) -> int: + """Bytes of one indexer K page: the token bytes of the cache manager times the tokens of a page.""" + if self.index_k_dtype == "fp8": + return self.index_page_tokens * (self.index_head_dim + self.index_head_dim // 128 * 4) + return self.index_page_tokens * (self.index_head_dim // 2 + self.index_head_dim // 32) + + @property + def default_softmax_scale(self) -> float: + return 1.0 / math.sqrt(self.kv_dim) + + +# DeepSeek-V4-Flash, CSA layers: 64 x 128 FP8 indexer over 32-position pages of the 4x-compressed sequence, top-512, +# 64 attention heads over 512-byte E4M3 KV rows, a 128-row sliding window and a per-head sink. +DS_V4_FLASH = SpecDsaConfig( + name="DS-V4-Flash", + index_heads=64, + index_head_dim=128, + index_k_dtype="fp8", + index_page_tokens=32, + compress_ratio=4, + topk=512, + max_index_len=1 << 18, + attn_heads=64, + kv_dim=512, + kv_format="v4_e4m3_rows", + kv_page_rows=32, + window=128, + swa_page_rows=128, + has_sink=True, + # the megakernel is built for up to 48 rows; at 48 the large-batch kernels are the faster ones + megakernel_max_batch=47, + large_batch=True, + max_batch=1024, +) + +# The same model with the MXFP4 indexer K cache of the cache manager (E2M1 data and a UE8M0 scale per 32 elements, +# 68 bytes per position) and an FP4 indexer query with a scale per 32 elements. +# The FP4 K stream is twice as fast per byte, but the megakernel row cost (the epilogue warps' hand-over of every +# row, the teams' selection and attention) does not shrink with it: the megakernel can serve up to 20 rows but is the +# default for 1 to 4, the tail-attention hybrid for 5 to 26 rows, the large-batch kernels from 27 rows. +DS_V4_FLASH_FP4 = replace( + DS_V4_FLASH, + name="DS-V4-Flash-FP4", + index_k_dtype="fp4", + megakernel_max_batch=20, + tail_hybrid_range=(5, 26), +) + +# The specs the kernels were built and validated for. +SUPPORTED_SPECS = {DS_V4_FLASH.name: DS_V4_FLASH, DS_V4_FLASH_FP4.name: DS_V4_FLASH_FP4} + +# Indexer shapes of the DeepSeek models (index heads, index head dim, top-k, compression ratio), as in the model tables +# of the top-K adapter; only the ones in SUPPORTED_SPECS have kernels. +KNOWN_SHAPES = { + "DS-V3.2": (64, 128, 2048, 1), + "DS-V4-Flash": (64, 128, 512, 4), + "DS-V4-Pro": (64, 128, 1024, 4), +} + + +def _not_supported(what: str) -> NotImplementedError: + supported = ", ".join(f"{s.name} {s.shape_key}" for s in SUPPORTED_SPECS.values()) + return NotImplementedError(f"specDSA has no kernels for {what}; supported: {supported}") + + +def _range_within(inner: tuple[int, int] | None, outer: tuple[int, int] | None) -> bool: + """Whether the batch-size range ``inner`` lies inside ``outer`` (None is the empty range).""" + if inner is None: + return True + return outer is not None and outer[0] <= inner[0] and inner[1] <= outer[1] + + +def resolve_spec( + index_heads: int, + index_head_dim: int, + topk: int, + compress_ratio: int, + *, + index_k_dtype: str = "fp8", + kv_format: str = "v4_e4m3_rows", +) -> SpecDsaConfig: + """The supported spec of an indexer shape ``(heads, head dim, top-k, compression ratio)``. + + The shape alone does not identify a model (two models can share it with different KV caches), so the K-cache dtype + and the KV row format take part in the match. + """ + shape = (index_heads, index_head_dim, topk, compress_ratio) + for spec in SUPPORTED_SPECS.values(): + if ( + spec.shape_key == shape + and spec.index_k_dtype == index_k_dtype + and spec.kv_format == kv_format + ): + return spec + known = next((n for n, s in KNOWN_SHAPES.items() if s == shape), None) + raise _not_supported( + f"the indexer shape {shape} with a {index_k_dtype} K cache and {kv_format!r} KV rows" + + (f" ({known})" if known else "") + ) + + +def supported_spec(config: SpecDsaConfig | None = None) -> SpecDsaConfig: + """``config`` (default: ``DS_V4_FLASH``) if the kernels serve it, else ``NotImplementedError``. + + The kernels serve a config whose ``kernel_key`` is one of ``SUPPORTED_SPECS`` and whose batch-size limits are not + above that spec's, and whose tail-hybrid range lies inside that spec's (none if the spec has none); a config with + lower limits or a narrower range is accepted (it routes more batch sizes to the other implementations or rejects + them). + """ + if config is None: + return DS_V4_FLASH + for spec in SUPPORTED_SPECS.values(): + if spec.kernel_key == config.kernel_key: + if ( + config.megakernel_max_batch > spec.megakernel_max_batch + or config.max_batch > spec.max_batch + or (config.large_batch and not spec.large_batch) + ): + raise _not_supported( + f"{config.name!r} with batch-size limits above those of {spec.name}" + ) + if not _range_within(config.tail_hybrid_range, spec.tail_hybrid_range): + raise _not_supported( + f"{config.name!r} with a tail-hybrid range {config.tail_hybrid_range} outside " + f"the one of {spec.name} {spec.tail_hybrid_range}" + ) + return config + raise _not_supported(f"{config.name!r} {config.shape_key}") + + +def require_built_for(config: SpecDsaConfig | None, built_for: SpecDsaConfig) -> SpecDsaConfig: + """The config a kernel object is built with. + + ``built_for`` if ``config`` is None, else ``config`` after checking that it has the same ``kernel_key`` (the kernels + are specialized for ``built_for``). + """ + if config is None: + return built_for + if config.kernel_key != built_for.kernel_key: + raise NotImplementedError( + f"this specDSA kernel is specialized for {built_for.name!r} {built_for.shape_key}, " + f"got {config.name!r} {config.shape_key}" + ) + return config + + +def check_device(device=None) -> tuple[bool, str]: + """Whether ``device`` can run the kernels: CuTe DSL installed, SM100 with all ``NUM_SMS`` SMs (one CTA per SM).""" + import torch + + from tensorrt_llm._torch.cute_dsl_utils import IS_CUTLASS_DSL_AVAILABLE + + if not IS_CUTLASS_DSL_AVAILABLE: + return False, "nvidia-cutlass-dsl is not available" + if not torch.cuda.is_available(): + return False, "CUDA is not available" + props = torch.cuda.get_device_properties( + device if device is not None else torch.cuda.current_device() + ) + if (props.major, props.minor) != (10, 0): + return False, f"requires SM100, got SM{props.major}{props.minor}" + if props.multi_processor_count != NUM_SMS: + return False, f"requires {NUM_SMS} SMs, got {props.multi_processor_count}" + return True, "" diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/hybrid_op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/hybrid_op.py new file mode 100644 index 000000000000..14c029e773e8 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/hybrid_op.py @@ -0,0 +1,465 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA tail-attention hybrid, host side: decode of 5 to 26 rows (``tail_hybrid_range`` of the spec) of an MXFP4 +indexer K cache on B200 (SM100, 148 SMs), behind the interface of the other implementations. + +Three launches per call, back to back on the current stream: the indexer logits kernel of the production MXFP4 chain +(``torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits``, called as the chain calls it), the multi-CTA exact top-512 of +``topk_multicta_op`` and the tail attention of ``tail_op``. That is ``tail_op.run_hybrid`` with the multi-CTA top-K and +the defaults of its ``pdl`` and ``poll`` (``tail_op.default_pdl`` / ``default_poll``: up to 24 rows the tail attention +is launched programmatically behind the top-K, up to 23 rows it also polls the top-K's output entries). The logits +kernel is the repository's production one and not a kernel of this package: it needs +``tensorrt_llm._torch.custom_ops`` with CuTe DSL and ``tensorrt_llm.deep_gemm.get_paged_mqa_logits_metadata``. They are +resolved when first used; a missing one is a ``RuntimeError`` that names it, and there is no fallback +(``op.prepare(..., implementation="megakernel")`` serves 5 to 20 rows without them). + +``prepare`` builds the per-step state (the compressed lengths on the device, the scheduler metadata of the logits kernel +built from them, the sinks copy); ``run`` launches the three kernels and writes ``topk`` (int32 compressed positions) +and ``out`` (bf16). The kernels are compiled on first use, outside CUDA-graph capture, or ahead of it by +``precompile``, which also launches the logits kernel once on dummy data: its first call compiles it. + +The logits buffer has ``config.max_index_len`` columns whatever the lengths (the logits kernel writes each row's valid +length), so a captured launch has fixed shapes: the production op returns a view of its persistent logits buffer +([B, 2**18] float32). The hybrid is tuned for rows of 1M tokens (2**18 compressed positions). Its top-K is exact for +every row length, but it is the faster stage only for rows of 16,384 positions or more +(``topk_multicta_op.is_profitable``); the megakernel stays selectable at 5 to 20 rows. + +Contract: +- A state belongs to one batch size and one caller. ``prepare`` refreshes it in place (a launch captured earlier reads + the same addresses), so launches that share a state and ``prepare`` calls on it must be stream-ordered. +- The logits live in the process-global buffer of the production op: hybrid launches, and the other users of that op, + must be stream-ordered with respect to each other, also across states. +- ``ctx_lens`` and ``kv_lens`` are read on the host by ``prepare``: pass host (CPU) tensors to avoid a device-to-host + copy; device tensors work but synchronize. The logits kernel and the top-K read the compressed lengths from the state + (the device copy that ``prepare`` keeps and built the schedule from), so ``run`` checks its ``ctx_lens`` and does not + read it. The tail attention reads the ``kv_lens`` of ``run`` at every launch. +- ``idx_block_table``, ``bt_swa`` and ``bt_c`` must be contiguous int32 [B, pages] tensors and ``kv_lens`` a contiguous + int32 [B] tensor: the kernels are compiled for compact tensors. The megakernel also takes strided block tables. +- ``topk`` and ``out`` must not alias any input. The multi-CTA top-K marks the entries of ``topk`` "not written yet" + when it starts and writes each one once; the tail attention polls them. +- The launches need all 148 SMs and clusters of up to 8 CTAs; they fail at launch on a partitioned device (MPS limits, + green contexts). +- Block tables must hold valid page ids for every page a row touches: the indexer table covers whole 128-position tiles + (``4 * ceil(n / 128)`` entries per row), the compressed-KV table ``ceil(n / 32)`` entries. +- There is no device-side error flag (``error_bits`` is a zero view). A state that was not refreshed for the step is not + detected: the launch computes for the lengths of the last ``prepare`` and its outputs are undefined. +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass + +import torch + +from . import tail_op, topk_multicta_op +from .config import ( + DS_V4_FLASH_FP4, + INDEX_TILE, + NUM_SMS, + SpecDsaConfig, + check_device, + supported_spec, +) + +__all__ = [ + "SpecDsaHybridState", + "error_bits", + "is_supported", + "precompile", + "prepare", + "run", + "supported_batch_sizes", +] + +# Positions per block of the scheduler metadata of the production paged-MQA logits kernels (``_DG_SCHEDULE_BLOCK_KV`` +# of the DSA indexer, ``INDEX_PAGE_ROWS`` of the CSA2 one): a property of the schedule, not of the K cache page. +_SCHEDULE_BLOCK_KV = 64 + +_lock = threading.Lock() +# Device indexes on which the logits kernel has been launched outside a capture, i.e. is compiled. +_k1_ready: set[int] = set() + + +def _k1_op(): + """The production MXFP4 paged-MQA logits op, or a RuntimeError if this build does not register it.""" + try: + import tensorrt_llm._torch.custom_ops # noqa: F401 (registers the trtllm::cute_dsl_* ops) + except ImportError as e: + raise RuntimeError( + "the specDSA tail hybrid needs tensorrt_llm._torch.custom_ops for the production indexer logits op " + f"torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits, which failed to import: {e}" + ) from e + try: + return torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits + except AttributeError as e: + raise RuntimeError( + "the specDSA tail hybrid needs the production indexer logits op " + "torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits, which is not registered (it needs CuTe DSL, " + "nvidia-cutlass-dsl, on SM100)" + ) from e + + +def _metadata_fn(): + """The scheduler metadata function of the production paged-MQA logits kernels, or a RuntimeError.""" + try: + from tensorrt_llm.deep_gemm import get_paged_mqa_logits_metadata + except ImportError as e: + raise RuntimeError( + "the specDSA tail hybrid needs tensorrt_llm.deep_gemm.get_paged_mqa_logits_metadata, the scheduler " + f"metadata of the production indexer logits op, which failed to import: {e}" + ) from e + return get_paged_mqa_logits_metadata + + +def _spec(config: SpecDsaConfig | None) -> SpecDsaConfig: + """``config`` (default: DS-V4-Flash-FP4, the spec with a tail-hybrid range) if the kernels serve it.""" + return supported_spec(DS_V4_FLASH_FP4 if config is None else config) + + +def supported_batch_sizes(config: SpecDsaConfig | None = None) -> range: + """Batch sizes of the tail-hybrid range of ``config`` (default: DS-V4-Flash-FP4); empty without a range.""" + rng = _spec(config).tail_hybrid_range + return range(0) if rng is None else range(rng[0], rng[1] + 1) + + +def is_supported( + device: torch.device | None = None, config: SpecDsaConfig | None = None +) -> tuple[bool, str]: + """Whether the tail hybrid serves ``config`` (default: DS-V4-Flash-FP4) on ``device``, and why not if it does not. + + That takes a spec with a tail-hybrid range and an MXFP4 indexer K cache, CuTe DSL installed, SM100 with all 148 SMs + and the production logits op and its scheduler metadata function. The batch size is checked by ``prepare``. + """ + try: + spec = _spec(config) + except NotImplementedError as e: + return False, str(e) + if spec.tail_hybrid_range is None: + return False, f"{spec.name} has no tail-hybrid range" + if spec.index_k_dtype != "fp4": + return ( + False, + f"the tail hybrid serves the MXFP4 indexer K cache, {spec.name} has {spec.index_k_dtype}", + ) + ok, why = check_device(device) + if not ok: + return False, why + try: + _k1_op() + _metadata_fn() + except RuntimeError as e: + return False, str(e) + return True, "" + + +def _check_batch_size(batch_size: int, config: SpecDsaConfig) -> None: + rng = config.tail_hybrid_range + if rng is None: + raise ValueError(f"{config.name} has no tail-hybrid range") + if config.index_k_dtype != "fp4": + raise ValueError( + f"the tail hybrid serves the MXFP4 indexer K cache, {config.name} has {config.index_k_dtype}" + ) + if not rng[0] <= batch_size <= rng[1]: + raise ValueError(f"batch size {batch_size} not in [{rng[0]}, {rng[1]}]") + + +def _device_index(device: torch.device) -> int: + device = torch.device(device) + return device.index if device.index is not None else torch.cuda.current_device() + + +def _warm_k1(device: torch.device, batch_size: int, config: SpecDsaConfig) -> None: + """Launch the production logits op once on dummy data (one tile per row): its first call compiles it and sizes its + logits buffer, and the scheduler metadata function builds its kernel for ``batch_size`` rows.""" + k1, metadata = _k1_op(), _metadata_fn() + heads, q_values = config.index_heads, config.index_head_dim // 2 + page_tokens = config.index_page_tokens + pages = config.pages_per_tile + ctx = torch.full((batch_size,), INDEX_TILE, dtype=torch.int32, device=device) + table = torch.arange(pages, dtype=torch.int32, device=device).repeat(batch_size, 1) + k1( + torch.zeros((batch_size, 1, heads, q_values), dtype=torch.uint8, device=device), + torch.zeros((batch_size, 1, heads), dtype=torch.int32, device=device), + torch.zeros( + (pages, page_tokens, 1, config.index_page_bytes // page_tokens), + dtype=torch.uint8, + device=device, + ), + torch.zeros((batch_size, heads), dtype=torch.float32, device=device), + ctx, + table, + metadata(ctx.view(-1, 1), _SCHEDULE_BLOCK_KV, NUM_SMS), + config.max_index_len, + ) + torch.cuda.current_stream(device).synchronize() + with _lock: + _k1_ready.add(_device_index(device)) + + +def precompile(device: torch.device, batch_size: int, config: SpecDsaConfig | None = None) -> None: + """Compile what ``batch_size`` rows need on ``device``: the multi-CTA top-K and the tail attention in the variant + ``run`` launches (``tail_op.default_pdl`` / ``default_poll``), and the production logits kernel. + + Must run outside CUDA-graph capture; ``run`` compiles on first use otherwise. + """ + config = _spec(config) + _check_batch_size(batch_size, config) + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError("spec_dsa tail hybrid: compile (precompile) before CUDA-graph capture") + _k1_op() + _metadata_fn() + pdl, poll = tail_op.default_pdl(batch_size), tail_op.default_poll(batch_size) + topk_multicta_op.precompile(device, batch_size, config, trigger=pdl, arm=poll) + tail_op.precompile(device, batch_size, config, pdl=pdl, poll=poll) + _warm_k1(device, batch_size, config) + + +@dataclass +class SpecDsaHybridState: + """Per-step metadata of one caller; see ``prepare``. + + ``ctx_lens`` is the int32 [B] copy of the compressed lengths that the logits kernel and the top-K read, ``sched`` + the int32 [NUM_SMS + 1, 2] scheduler metadata of the production logits kernel built from them, ``sinks`` the + float32 [attn_heads] copy of the attention sinks that the tail attention reads, ``status`` an int32 [1] zero that + ``error_bits`` returns and ``config`` the spec the state was built for. + """ + + batch_size: int + ctx_lens: torch.Tensor + sched: torch.Tensor + sinks: torch.Tensor + status: torch.Tensor + config: SpecDsaConfig + + +def _host_ints(t: torch.Tensor, count: int, name: str) -> list[int]: + v = t.reshape(-1) + if v.numel() != count: + raise ValueError(f"{name} must have {count} entries, got {v.numel()}") + return [int(x) for x in v.tolist()] + + +def prepare( + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + idx_block_table: torch.Tensor, + sinks: torch.Tensor, + state: SpecDsaHybridState | None = None, + *, + config: SpecDsaConfig | None = None, +) -> SpecDsaHybridState: + """Build (or refresh in place) the per-step state for ``B = ctx_lens.numel()`` rows. + + Args: + ctx_lens: int32 [B], compressed (indexer) length of each row, in [512, 2**18]; the state keeps a device copy + that the logits kernel and the top-K read. + kv_lens: int32 [B], uncompressed length of each row (>= 128); exactly B entries. + idx_block_table: contiguous int32 [B, pages] on the target device, indexer K pages of each row (32 compressed + positions per page; whole 128-position tiles, so at least ``4 * ceil(n / 128)`` valid entries). + sinks: float32 [64] on the target device, per-head attention sink. + state: a state of the same batch size to refresh; keeps its buffers (a captured launch reads them) and its spec. + config: the spec (default: DS-V4-Flash-FP4). A new state is built for it; a refreshed state keeps its own. + + The lengths are checked on the host: pass host (CPU) tensors to avoid a device-to-host copy; device tensors work + but synchronize. + """ + if state is not None: + if config is not None and config.kernel_key != state.config.kernel_key: + raise ValueError(f"state is for {state.config.name!r}, got {config.name!r}") + config = state.config + config = _spec(config) + batch_size = int(ctx_lens.numel()) + _check_batch_size(batch_size, config) + device = idx_block_table.device + if device.type != "cuda": + raise ValueError("idx_block_table must be a CUDA tensor") + if sinks.numel() != config.attn_heads: + raise ValueError(f"sinks must have {config.attn_heads} entries, got {tuple(sinks.shape)}") + ctx_host = _host_ints(ctx_lens, batch_size, "ctx_lens") + kv_host = _host_ints(kv_lens, batch_size, "kv_lens") + if any(not config.min_index_len <= n <= config.max_index_len for n in ctx_host): + raise ValueError( + f"compressed lengths must lie in [{config.min_index_len}, {config.max_index_len}], got {ctx_host}" + ) + if any(n < config.window for n in kv_host): + raise ValueError(f"uncompressed lengths must be at least {config.window}, got {kv_host}") + need_pages = config.pages_per_tile * math.ceil(max(ctx_host) / INDEX_TILE) + _check_block_table("idx_block_table", idx_block_table, batch_size) + if idx_block_table.shape[1] < need_pages: + raise ValueError( + f"idx_block_table has {idx_block_table.shape[1]} pages per row, need {need_pages}" + ) + if state is not None and state.batch_size != batch_size: + raise ValueError(f"state is for {state.batch_size} rows, got {batch_size}") + _k1_op() + metadata = _metadata_fn() + if state is None: + state = SpecDsaHybridState( + batch_size=batch_size, + ctx_lens=torch.empty(batch_size, dtype=torch.int32, device=device), + sched=torch.empty((NUM_SMS + 1, 2), dtype=torch.int32, device=device), + sinks=torch.empty(config.attn_heads, dtype=torch.float32, device=device), + status=torch.zeros(1, dtype=torch.int32, device=device), + config=config, + ) + # one copy of the lengths feeds the schedule, the logits kernel and the top-K + state.ctx_lens.copy_(torch.tensor(ctx_host, dtype=torch.int32), non_blocking=True) + state.sched.copy_(metadata(state.ctx_lens.view(-1, 1), _SCHEDULE_BLOCK_KV, NUM_SMS)) + state.sinks.copy_(sinks.reshape(-1)) + return state + + +def error_bits(state: SpecDsaHybridState) -> torch.Tensor: + """An int32 [1] device zero: the tail hybrid has no device-side error flag. No sync. + + A state that was not refreshed for the step (``prepare`` not called with its lengths) is not detected. + """ + return state.status + + +def _check_numel(name: str, t: torch.Tensor, numel: int, dtype: torch.dtype | None = None) -> None: + if t.numel() != numel or (dtype is not None and t.dtype != dtype) or not t.is_contiguous(): + raise ValueError( + f"{name} must be contiguous with {numel} elements" + + (f" of {dtype}" if dtype is not None else "") + + f", got {t.dtype} {tuple(t.shape)}" + ) + + +def _check_block_table(name: str, t: torch.Tensor, batch_size: int) -> None: + if t.dtype != torch.int32 or t.dim() != 2 or t.shape[0] < batch_size or not t.is_contiguous(): + raise ValueError( + f"{name} must be a contiguous int32 [B, pages] tensor with B >= {batch_size} (the tail hybrid takes no " + f"strided block table, the megakernel does), got {t.dtype} {tuple(t.shape)} with strides {t.stride()}" + ) + + +def run( + state: SpecDsaHybridState, + q_idx: torch.Tensor, + w_idx: torch.Tensor, + k_cache: torch.Tensor, + idx_block_table: torch.Tensor, + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + topk: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + q_scale: torch.Tensor | None = None, +) -> None: + """Launch the logits kernel, the top-K and the tail attention on the current stream. + + Args: + state: from ``prepare`` for these lengths and block tables. + q_idx: packed E2M1 indexer queries, 1 byte per two values ([B, 64, 64], or [B, 1, 64, 64]); contiguous. + w_idx: float32 [B, 64], indexer head weights. + k_cache: uint8 [pages, ...] with ``config.index_page_bytes`` (2176) bytes per page, indexer K pages (32 x 64 + bytes of E2M1 pairs, then 32 int32 of four UE8M0 scales, one per 32 values). + idx_block_table: contiguous int32 [B, pages], as given to ``prepare``. + ctx_lens: int32 [B] on the device, the lengths given to ``prepare``; checked, not read (the launch uses the + lengths of the state). + kv_lens: contiguous int32 [B] on the device, uncompressed lengths (the window is the last 128 positions). + q_att: float8_e4m3fn [B, 64, 512], attention queries. + swa_pool: float8_e4m3fn [..., 512], sliding-window KV rows (128 rows per page); bt_swa: contiguous int32 + [B, pages]. + c_pool: float8_e4m3fn [..., 512], compressed KV rows (32 rows per page); bt_c: contiguous int32 [B, pages]. + topk: int32 [B, 512] output, the selected compressed positions (in no particular order). + out: bfloat16 [B, 64 * 512] output. + softmax_scale: attention softmax scale (default: ``1 / sqrt(kv_dim)`` of the spec). + q_scale: int32 [B, 64] (or [B, 1, 64]), the four UE8M0 query scales of each head in one int32. + + The arguments are checked before the first launch. Inside a CUDA-graph capture the logits kernel has to be + compiled already (``precompile``, or an earlier launch outside the capture). + """ + config = state.config + b = state.batch_size + heads, q_values = config.index_heads, config.index_head_dim // 2 + if q_scale is None: + raise ValueError("an FP4 spec needs q_scale (the UE8M0 scales of the FP4 queries)") + _check_numel("q_idx", q_idx, b * heads * q_values) + if q_idx.element_size() != 1: + raise ValueError(f"q_idx must be packed FP4 (1 byte per two values), got {q_idx.dtype}") + _check_numel("q_scale", q_scale, b * heads, torch.int32) + _check_numel("w_idx", w_idx, b * heads, torch.float32) + _check_numel("ctx_lens", ctx_lens, b, torch.int32) + if ctx_lens.device != q_idx.device: + raise ValueError( + f"ctx_lens must be on the device of q_idx ({q_idx.device}), got {ctx_lens.device}" + ) + _check_numel("kv_lens", kv_lens, b, torch.int32) + _check_numel("topk", topk, b * config.topk, torch.int32) + for name, table in (("idx_block_table", idx_block_table), ("bt_swa", bt_swa), ("bt_c", bt_c)): + _check_block_table(name, table, b) + pages = int(k_cache.shape[0]) + if k_cache.element_size() != 1 or k_cache.numel() != pages * config.index_page_bytes: + raise ValueError( + f"k_cache must hold {config.index_page_bytes} bytes per page, got {tuple(k_cache.shape)}" + ) + topk = topk.view(b, config.topk) + kv_lens = kv_lens.view(b) + # the tail attention's own checks, so that a bad argument is refused before the first launch + tail_op._check_arguments( + config, b, topk, q_att, swa_pool, bt_swa, c_pool, bt_c, kv_lens, state.sinks, out + ) + k1 = _k1_op() + device_index = _device_index(q_idx.device) + if torch.cuda.is_current_stream_capturing() and device_index not in _k1_ready: + raise RuntimeError( + "spec_dsa tail hybrid: compile the logits kernel (precompile, or a launch outside the capture) before " + "CUDA-graph capture" + ) + page_tokens = config.index_page_tokens + + def logits_fn() -> torch.Tensor: + logits = k1( + q_idx.reshape(b, 1, heads, q_values).view(torch.uint8), + q_scale.reshape(b, 1, heads), + k_cache.view(pages, page_tokens, 1, config.index_page_bytes // page_tokens), + w_idx.reshape(b, heads), + state.ctx_lens, + idx_block_table[:b], + state.sched, + config.max_index_len, + ) + if not torch.cuda.is_current_stream_capturing(): + with _lock: + _k1_ready.add(device_index) + return logits + + tail_op.run_hybrid( + logits_fn, + None, + topk, + q_att, + swa_pool, + bt_swa, + c_pool, + bt_c, + kv_lens, + state.sinks, + out, + softmax_scale, + config=config, + ctx_lens=state.ctx_lens, + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch.py new file mode 100644 index 000000000000..158fd0177b90 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch.py @@ -0,0 +1,6161 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""specDSA large-batch kernels (CuTe DSL, SM100): the persistent indexer kernel (one CTA per SM: FP8 logits, +in-stream top-512 with a learned floor, mapping to compressed-KV rows, ready queue) and the attention kernel launched +behind it with programmatic dependent launch. + +The kernels are specialized for the ``DS_V4_FLASH`` spec of ``config.py``: their structural constants are defined from +it and the kernel classes reject a config with another ``kernel_key``. +""" + +from __future__ import annotations + +import math + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as xcuda +import cutlass.pipeline as pipeline +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +from cutlass import Boolean, Float4E2M1FN, Float8E8M0FNU, Float32, Int32, Int64, Uint32, Uint64 +from cutlass._mlir.dialects import llvm as _llvm +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cute.nvgpu.tcgen05 import find_tmem_tensor_col_offset +from cutlass.cutlass_dsl import T as _T +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.experimental import primitives as prims +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from . import large_batch_lib as L +from .config import DS_V4_FLASH as SPEC +from .config import DS_V4_FLASH_FP4 as SPEC_FP4 +from .config import NUM_SMS, SpecDsaConfig, require_built_for + +# ==================================================================================================================== +# Sparse MLA tile loads, MMA and softmax helpers shared by the two kernels. +# ==================================================================================================================== + +HEADS = SPEC.attn_heads +LATENT = SPEC.kv_dim +WINDOW = SPEC.window +NROWS = SPEC.selected_rows +TILE_N = 128 +NTILES = NROWS // TILE_N +SLICE = 128 +NSLICE = LATENT // SLICE +Q_SLICE_BYTES = HEADS * SLICE +SLOT_BYTES = TILE_N * SLICE +LOG2_E = 1.4426950408889634 +LOG2_448 = 8.8073549 +NEG_FLT_MAX = -3.4028235e38 +PANEL1 = 16 << 16 +TM_S = 128 +TM_O = 256 +E4M3 = cutlass.Float8E4M3FN +BF16 = cutlass.BFloat16 + + +@cute.jit +def _sleep_us(us: cutlass.Constexpr): + t0 = Int64(cute.arch.globaltimer()) + t1 = Int64(cute.arch.globaltimer()) + while t1 - t0 < Int64(us * 1000): + _nsleep(Int32(1000)) + t1 = Int64(cute.arch.globaltimer()) + + +@cute.jit +def _pace_us(us: cutlass.Constexpr, pace_ptr, pace_lim): + if pace_lim >= Int32(0): + t0 = Int64(cute.arch.globaltimer()) + t1 = t0 + pend = cute.arch.load(pace_ptr, Int32, sem="acquire", scope="cta") + while (t1 - t0 < Int64(us * 1000)) & (pend <= pace_lim): + _nsleep(Int32(500)) + t1 = Int64(cute.arch.globaltimer()) + pend = cute.arch.load(pace_ptr, Int32, sem="acquire", scope="cta") + + +@dsl_user_op +def _nsleep(ns, *, loc=None, ip=None): + _llvm.inline_asm( + None, + [Int32(ns).ir_value(loc=loc, ip=ip)], + "nanosleep.u32 $0;", + "r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@cute.jit +def _wait(mbar, phase): + while not prims.mbarrier_try_wait_parity(mbar, phase): + pass + + +@cute.jit +def _wait_mma(bmma, ph, wl, bar_id: cutlass.Constexpr): + if wl == Int32(0): + _wait(bmma, ph >> Int32(8) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=bar_id, number_of_threads=128) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + return ph ^ Int32(1 << 8) + + +@cute.jit +def _tma_gather4(smem_dst, tma_desc, mbar, col, r0, r1, r2, r3, pol=None) -> None: + bar = prims.cvta_to(mbar, prims.CvtaSpace.SHARED) + if cutlass.const_expr(pol is None): + prims.inline_ptx_hl( + "{\n\t.reg .pred leader;\n\telect.sync _|leader, -1;\n\t" + "@leader cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes " + "[{$r0}], [{$r1}, {{$r2}, {$r3}, {$r4}, {$r5}, {$r6}}], [{$r7}];\n\t}", + read_only_args=[smem_dst, tma_desc, col, r0, r1, r2, r3, bar], + ) + else: + prims.inline_ptx_hl( + "{\n\t.reg .pred leader;\n\telect.sync _|leader, -1;\n\t" + "@leader cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes" + ".L2::cache_hint " + "[{$r0}], [{$r1}, {{$r2}, {$r3}, {$r4}, {$r5}, {$r6}}], [{$r7}], {$r8};\n\t}", + read_only_args=[smem_dst, tma_desc, col, r0, r1, r2, r3, bar, pol], + ) + + +@dsl_user_op +def l2_policy(kind: int, *, loc=None, ip=None): + asm = { + 1: "createpolicy.fractional.L2::evict_last.b64 $0, 1.0;", + 2: "createpolicy.fractional.L2::evict_first.b64 $0, 1.0;", + 3: "createpolicy.fractional.L2::evict_normal.b64 $0, 1.0;", + }[kind] + return Int64( + _llvm.inline_asm( + _T.i64(), + [], + asm, + "=l", + has_side_effects=True, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _pack4_e4m3(v0: Float32, v1: Float32, v2: Float32, v3: Float32): + return cute.arch.inline_ptx( + "{\n .reg .b16 lo;\n .reg .b16 hi;\n " + "cvt.rn.satfinite.e4m3x2.f32 lo, {$r1}, {$r0};\n cvt.rn.satfinite.e4m3x2.f32 hi, {$r3}, {$r2};\n " + "mov.b32 {$w0}, {lo, hi};\n}", + write_only_types=[Int32], + read_only_args=[v0, v1, v2, v3], + ) + + +@cute.jit +def _tmem_st_p8(tmem_addr, regs) -> None: + body = ", ".join(("{$r%d}" % (i + 1) for i in range(8))) + cute.arch.inline_ptx( + f"tcgen05.st.sync.aligned.16x32bx2.x8.b32 [{{$r0}}], 16, {{ {body} }};", + read_only_args=[tmem_addr] + [regs[i] for i in range(8)], + ) + + +@cute.jit +def _shfl_xor_f32(x: Float32, dist: cutlass.Constexpr[int]) -> Float32: + return Float32( + prims.shfl_sync( + thread_mask=4294967295, val=x, offset=dist, mask_and_clamp=31, kind=prims.Shfl.BFLY + ) + ) + + +@cute.jit +def _shfl_idx_i32(x: Int32, src) -> Int32: + return Int32( + prims.shfl_sync( + thread_mask=4294967295, val=x, offset=src, mask_and_clamp=31, kind=prims.Shfl.IDX + ) + ) + + +@cute.jit +def _pack_bf16x2(v0: Float32, v1: Float32): + return cutlass.Vector.from_elements((v0, v1), Float32).to(BF16).bitcast(Int32)[0] + + +@dsl_user_op +def _mul_rn(a, b, *, loc=None, ip=None): + return Float32( + _llvm.inline_asm( + _T.f32(), + [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)], + "mul.rn.f32 $0, $1, $2;", + "=f,f,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _fma_rn(a, b, c, *, loc=None, ip=None): + return Float32( + _llvm.inline_asm( + _T.f32(), + [ + Float32(a).ir_value(loc=loc, ip=ip), + Float32(b).ir_value(loc=loc, ip=ip), + Float32(c).ir_value(loc=loc, ip=ip), + ], + "fma.rn.f32 $0, $1, $2, $3;", + "=f,f,f,f", + has_side_effects=False, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _final_norm( + final_max: Float32, reduced_sum: Float32, sink: Float32, scale_log2: Float32 +) -> Float32: + t = _mul_rn(final_max, scale_log2) + delta = _fma_rn(sink, Float32(LOG2_E), -t) + attention_rescale = cute.math.exp2(-cute.math.max(delta, Float32(0)), approx=True) + sink_mass = cute.math.exp2(cute.math.min(delta, Float32(0)), approx=True) + sink_mass *= Float32(448.0) + return ( + Float32(1.0) + * attention_rescale + * cute.math.rcp(reduced_sum * attention_rescale + sink_mass, approx=True) + ) + + +@cute.jit +def _rescale_o(tmem, lane_base, scale: Float32): + for v in cutlass.range_constexpr(NSLICE): + o_addr = tmem + lane_base + Int32(TM_O + v % 2 * 128 + v // 2 * PANEL1) + for h in cutlass.range_constexpr(2): + ptr = prims.make_tmem_ptr(o_addr + Int32(32 * h), Float32) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, ptr, num=32, offset=Int64(64) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + vals = [] + for r in cutlass.range_constexpr(0, 32, 2): + pr = cute.arch.mul_packed_f32x2( + (Float32(o[r]), Float32(o[r + 1])), (scale, scale), ftz=False, rnd="rn" + ) + vals.append(pr[0]) + vals.append(pr[1]) + prims.tcgen05_st( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + cutlass.Vector.from_elements(tuple(vals), Float32), + offset=Int64(64), + ) + + +@cute.jit +def _issue_kv_slice(slot_ptr, mbar, tma_swa, tma_cmp, use_swa, gidx_t, c, wl, lane, pol=None): + if wl == Int32(0): + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(mbar, SLOT_BYTES) + dst0 = slot_ptr + wl * Int32(32 * SLICE) + for q in cutlass.range(8, unroll=1): + r0 = _shfl_idx_i32(gidx_t, Int32(4 * q)) + r1 = _shfl_idx_i32(gidx_t, Int32(4 * q + 1)) + r2 = _shfl_idx_i32(gidx_t, Int32(4 * q + 2)) + r3 = _shfl_idx_i32(gidx_t, Int32(4 * q + 3)) + if use_swa: + _tma_gather4( + dst0 + Int32(4 * q * SLICE), + tma_swa.get_ptr(), + mbar, + c * Int32(SLICE), + r0, + r1, + r2, + r3, + pol, + ) + else: + _tma_gather4( + dst0 + Int32(4 * q * SLICE), + tma_cmp.get_ptr(), + mbar, + c * Int32(SLICE), + r0, + r1, + r2, + r3, + pol, + ) + + +@cute.jit +def issue_row_loads( + tid, + b, + s_gv, + deep_base, + kv_slot0, + kv_slot7, + deep_q, + q_slot0, + bq, + bkv, + gfree, + tma_q, + tma_swa, + tma_cmp, + bar_id: cutlass.Constexpr, + jb=None, + je=None, +): + wl = tid >> Int32(5) + lane = tid & Int32(31) + j_b = Int32(0) + j_e = Int32(NTILES) + if cutlass.const_expr(jb is not None): + j_b = jb + j_e = je + if j_b == Int32(0): + if tid == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(bq + c, Q_SLICE_BYTES) + prims.cp_async_bulk_tensor_shared_cta_global( + _q_slot(deep_q, q_slot0, Int32(c)), + tma_q.get_ptr(), + [Int32(c * SLICE), Int32(0), b], + bq + c, + ) + for j in cutlass.range(j_b, j_e, unroll=1): + g4 = (j & Int32(1)) * Int32(4) + if j >= Int32(2): + _wait(gfree + (j & Int32(1)), j - Int32(2) >> Int32(1) & Int32(1)) + grow = _grow(Int32(s_gv[j * Int32(TILE_N) + tid])) + for c in cutlass.range_constexpr(NSLICE): + _issue_kv_slice( + _kv_slot(deep_base, kv_slot0, g4 + Int32(c), kv_slot7), + bkv + g4 + Int32(c), + tma_swa, + tma_cmp, + j == Int32(0), + grow, + Int32(c), + wl, + lane, + ) + + +OOB_ROW = 2147483647 + + +@cute.jit +def _grow(g): + r = g + if g < Int32(0): + r = Int32(OOB_ROW) + return r + + +@cute.jit +def _pick(j, g0, g1, g2, g3, g4): + g = g0 + if j == Int32(1): + g = g1 + elif j == Int32(2): + g = g2 + elif j == Int32(3): + g = g3 + elif j == Int32(4): + g = g4 + return g + + +@cute.jit +def _kv_slot(deep_base, kv_slot0, k, kv_slot7): + a = deep_base + k * Int32(SLOT_BYTES) + if k >= Int32(6): + a = kv_slot0 + if k >= Int32(7): + a = kv_slot7 + return a + + +@cute.jit +def deep_ok(hi_ptr): + a = cute.arch.load(hi_ptr + Int32(11), Int32, sem="acquire", scope="cta") + b = cute.arch.load(hi_ptr + Int32(3), Int32, sem="acquire", scope="cta") + cute.arch.fence_acq_rel_cta() + r = Int32(0) + if (a != Int32(0)) & (b != Int32(0)): + r = Int32(1) + return r + + +@cute.jit +def _q_slot(deep_q, q_slot0, c): + a = deep_q + c * Int32(Q_SLICE_BYTES) + if c == Int32(3): + a = q_slot0 + return a + + +@cute.jit +def att_row( + rtid, + b, + gv0, + gv1, + gv2, + gv3, + gv4, + tmem, + deep0, + q_slot0, + kv_slot0, + deep_base, + deep_q, + bq, + bkv, + bmma, + ph, + tma_q, + tma_swa, + tma_cmp, + sink_ptr, + out_addr: Int64, + scale_log2: Float32, + s_msk, + dflag_ptr, + bar_id: cutlass.Constexpr, + skip: cutlass.Constexpr = 0, + allow_deep: cutlass.Constexpr = True, + prof: cutlass.Constexpr = False, + pst=None, + pbase=None, + kv_slot7=None, + ext=None, + gfree=None, + ahint: cutlass.Constexpr = 0, + phased: cutlass.Constexpr = False, + j0=None, + j1=None, + st_in=None, + apace: cutlass.Constexpr = 0, + kv_slotB=None, + two=None, + pace_lim=None, + tbase=None, + qfree=None, +): + TW = two is not None + tw = Int32(0) + tb = Int32(0) + if cutlass.const_expr(tbase is not None): + tb = tbase + if cutlass.const_expr(TW): + tw = two + wl = rtid >> Int32(5) + lane = rtid & Int32(31) + head = wl * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = wl * Int32(32) << Int32(16) + s_addr = tmem + Int32(TM_S) + sink = Float32((sink_ptr + head).load()) + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, a_major=0, b_major=1, n_dim=SLICE, m_dim=HEADS + ) + pol_keep = None + pol_drop = None + if cutlass.const_expr(ahint == 1): + pol_keep = l2_policy(1) + pol_drop = l2_policy(2) + m_run = Float32(NEG_FLT_MAX) + l_run = Float32(0.0) + dp = deep0 + qres = Int32(0) + pre = Int32(0) + jb = Int32(0) + je = Int32(NTILES) + if cutlass.const_expr(phased): + m_run = Float32(st_in[0]) + l_run = Float32(st_in[1]) + qres = Int32(st_in[2]) + pre = Int32(st_in[3]) + dp = Int32(st_in[4]) + jb = j0 + je = j1 + for j in cutlass.range(jb, je, unroll=1): + gsel = _pick(j, gv0, gv1, gv2, gv3, gv4) + valid = gsel >= Int32(0) + grow = _grow(gsel) + vm = Int32(cute.arch.vote_ballot_sync(valid)) + if lane == Int32(0): + s_msk[wl] = vm + if rtid == Int32(0): + dnow = dp + if cutlass.const_expr(allow_deep): + if dp == Int32(0): + dnow = deep_ok(dflag_ptr) + if cutlass.const_expr(ext is not None): + if ext != Int32(0): + dnow = Int32(1) + s_msk[4] = dnow + cute.arch.barrier(barrier_id=bar_id, number_of_threads=128) + if cutlass.const_expr(apace > 0): + if j > jb: + if s_msk[4] == Int32(0): + if rtid == Int32(0): + if cutlass.const_expr(pace_lim is None): + _sleep_us(apace) + else: + _pace_us(apace, dflag_ptr, pace_lim) + cute.arch.barrier(barrier_id=bar_id, number_of_threads=128) + if cutlass.const_expr(prof): + if rtid == Int32(0): + pst[pbase + Int32(4) * j] = Int64(cute.arch.globaltimer()) + dp = Int32(0) + if s_msk[4] != Int32(0): + dp = Int32(1) + use_swa = j == Int32(0) + grp4 = (tb + j & Int32(1)) * Int32(4) + if dp != Int32(0): + ldq = qres == Int32(0) + iss = Boolean(True) + if cutlass.const_expr(ext is not None): + if ext != Int32(0): + iss = Boolean(False) + if cutlass.const_expr(skip & 16 == 0): + if ldq & iss: + if rtid == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(bq + c, Q_SLICE_BYTES) + prims.cp_async_bulk_tensor_shared_cta_global( + _q_slot(deep_q, q_slot0, Int32(c)), + tma_q.get_ptr(), + [Int32(c * SLICE), Int32(0), b], + bq + c, + ) + if (pre == Int32(0)) & iss: + for c in cutlass.range_constexpr(NSLICE): + _issue_kv_slice( + _kv_slot(deep_base, kv_slot0, grp4 + Int32(c), kv_slot7), + bkv + grp4 + Int32(c), + tma_swa, + tma_cmp, + use_swa, + grow, + Int32(c), + wl, + lane, + pol_drop, + ) + if (j + Int32(1) < Int32(NTILES)) & iss: + gnx = _grow(_pick(j + Int32(1), gv0, gv1, gv2, gv3, gv4)) + ng4 = Int32(4) - grp4 + for c in cutlass.range_constexpr(NSLICE): + _issue_kv_slice( + _kv_slot(deep_base, kv_slot0, ng4 + Int32(c), kv_slot7), + bkv + ng4 + Int32(c), + tma_swa, + tma_cmp, + Boolean(False), + gnx, + Int32(c), + wl, + lane, + pol_drop, + ) + if wl == Int32(0): + for c in cutlass.range(NSLICE, unroll=1): + if cutlass.const_expr(skip & 16 == 0): + if ldq: + _wait(bq + c, ph >> c & Int32(1)) + _wait(bkv + grp4 + c, ph >> Int32(16) + grp4 + c & Int32(1)) + qdesc = prims.Tcgen05SmemDesc.build( + _q_slot(deep_q, q_slot0, c), + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + kdesc = prims.Tcgen05SmemDesc.build( + _kv_slot(deep_base, kv_slot0, grp4 + c, kv_slot7), + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if prims.elect_sync(): + if cutlass.const_expr(skip & 8 == 0): + for kb in cutlass.range_constexpr(SLICE // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(c > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(kb * 32), + kdesc.advance_start_address(kb * 32), + idesc_qk, + en, + ) + if prims.elect_sync(): + prims.tcgen05_commit(bmma, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(qfree is not None): + if j == Int32(NTILES - 1): + prims.tcgen05_commit(qfree, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(skip & 16 == 0): + if ldq: + ph = ph ^ Int32(15) + ph = ph ^ Int32(15) << Int32(16) + grp4 + qres = Int32(1) + pre = Int32(0) + if j + Int32(1) < Int32(NTILES): + pre = Int32(1) + ph = _wait_mma(bmma, ph, wl, bar_id) + else: + if cutlass.const_expr(TW and skip & 16 == 0): + if tw != Int32(0): + _issue_kv_slice( + kv_slot0, bkv, tma_swa, tma_cmp, use_swa, grow, Int32(0), wl, lane, pol_keep + ) + for c in cutlass.range(NSLICE, unroll=1): + sb = tw & c & Int32(1) + if cutlass.const_expr(skip & 16 == 0): + ldq_s = Boolean(True) + if cutlass.const_expr(skip & 128 != 0): + ldq_s = j == jb + if ldq_s: + if rtid == Int32(0): + prims.mbarrier_arrive_expect_tx(bq, Q_SLICE_BYTES) + prims.cp_async_bulk_tensor_shared_cta_global( + q_slot0, tma_q.get_ptr(), [c * Int32(SLICE), Int32(0), b], bq + ) + if cutlass.const_expr(TW): + if tw != Int32(0): + if c + Int32(1) < Int32(NSLICE): + if c & Int32(1) == Int32(0): + _issue_kv_slice( + kv_slotB, + bkv + Int32(1), + tma_swa, + tma_cmp, + use_swa, + grow, + c + Int32(1), + wl, + lane, + pol_keep, + ) + else: + _issue_kv_slice( + kv_slot0, + bkv, + tma_swa, + tma_cmp, + use_swa, + grow, + c + Int32(1), + wl, + lane, + pol_keep, + ) + else: + _issue_kv_slice( + kv_slot0, + bkv, + tma_swa, + tma_cmp, + use_swa, + grow, + c, + wl, + lane, + pol_keep, + ) + else: + _issue_kv_slice( + kv_slot0, bkv, tma_swa, tma_cmp, use_swa, grow, c, wl, lane, pol_keep + ) + if ldq_s: + _wait(bq, ph & Int32(1)) + ph = ph ^ Int32(1) + _wait(bkv + sb, ph >> Int32(16) + sb & Int32(1)) + ph = ph ^ Int32(1) << Int32(16) + sb + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + kslot = kv_slot0 + if cutlass.const_expr(TW): + if sb != Int32(0): + kslot = kv_slotB + qdesc = prims.Tcgen05SmemDesc.build( + q_slot0, + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + kdesc = prims.Tcgen05SmemDesc.build( + kslot, + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if wl == Int32(0): + if prims.elect_sync(): + if cutlass.const_expr(skip & 8 == 0): + for kb in cutlass.range_constexpr(SLICE // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(c > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(kb * 32), + kdesc.advance_start_address(kb * 32), + idesc_qk, + en, + ) + prims.tcgen05_commit(bmma, group=prims.CTAGroup.CTA_1) + ph = _wait_mma(bmma, ph, wl, bar_id) + pre = Int32(0) + if cutlass.const_expr(prof): + if rtid == Int32(0): + pst[pbase + Int32(4) * j + Int32(1)] = Int64(cute.arch.globaltimer()) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + L = scale_log2 + mk = Int32(s_msk[half * Int32(2)]) + mk2 = Int32(s_msk[half * Int32(2) + Int32(1)]) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + tsa = s_addr + lane_base + for ch in cutlass.range_constexpr(2): + s = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa + Int32(32 * ch), Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + mword = mk + if cutlass.const_expr(ch == 1): + mword = mk2 + for i in cutlass.range_constexpr(0, 32, 4): + x0 = Float32(s[i]) + x1 = Float32(s[i + 1]) + x2 = Float32(s[i + 2]) + x3 = Float32(s[i + 3]) + if mword >> Int32(i) & Int32(1) == Int32(0): + x0 = Float32(-float("inf")) + if mword >> Int32(i + 1) & Int32(1) == Int32(0): + x1 = Float32(-float("inf")) + if mword >> Int32(i + 2) & Int32(1) == Int32(0): + x2 = Float32(-float("inf")) + if mword >> Int32(i + 3) & Int32(1) == Int32(0): + x3 = Float32(-float("inf")) + mx0 = cute.math.max(mx0, x0, ftz=True) + mx1 = cute.math.max(mx1, x1, ftz=True) + mx2 = cute.math.max(mx2, x2, ftz=True) + mx3 = cute.math.max(mx3, x3, ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + neg_scaled = -L * safe_max + bias = neg_scaled + Float32(LOG2_448) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for ch in cutlass.range_constexpr(2): + s = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa + Int32(32 * ch), Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + mword = mk + if cutlass.const_expr(ch == 1): + mword = mk2 + for pk in cutlass.range_constexpr(8): + xs = [Float32(s[4 * pk + u]) for u in range(4)] + for u in cutlass.range_constexpr(4): + if mword >> Int32(4 * pk + u) & Int32(1) == Int32(0): + xs[u] = Float32(-float("inf")) + x01 = cute.arch.fma_packed_f32x2( + (xs[0], xs[1]), (L, L), (bias, bias), ftz=False, rnd="rn" + ) + x23 = cute.arch.fma_packed_f32x2( + (xs[2], xs[3]), (L, L), (bias, bias), ftz=False, rnd="rn" + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = tsa + Int32(TILE_N // 4) + if cutlass.const_expr(skip & 1 == 0): + _tmem_st_p8(p_addr, regs[0:8]) + _tmem_st_p8(p_addr + Int32(8), regs[8:16]) + _tmem_st_p8(p_addr + Int32(PANEL1), regs[0:8]) + _tmem_st_p8(p_addr + Int32(PANEL1 + 8), regs[8:16]) + exp_scale = cute.math.exp2(L * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if j > Int32(0): + ident = old_max == new_max + scale = Float32(1.0) + if not ident: + scale = exp_scale + skip_c = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip_c: + if cutlass.const_expr(skip & 2 == 0): + _rescale_o(tmem, lane_base, scale) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=bar_id, number_of_threads=128) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(prof): + if rtid == Int32(0): + pst[pbase + Int32(4) * j + Int32(2)] = Int64(cute.arch.globaltimer()) + if dp != Int32(0): + if wl == Int32(0): + if prims.elect_sync(): + if cutlass.const_expr(skip & 4 == 0): + for v in cutlass.range_constexpr(NSLICE): + vdesc = prims.Tcgen05SmemDesc.build( + _kv_slot(deep_base, kv_slot0, grp4 + Int32(v), kv_slot7), + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d_addr = tmem + Int32(TM_O + (v & 1) * 128 + (v >> 1) * PANEL1) + a_addr = s_addr + Int32(TILE_N // 4 + (v >> 1) * PANEL1) + for kb in cutlass.range_constexpr(TILE_N // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(j > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(bmma, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(ext is not None): + if ext != Int32(0): + prims.tcgen05_commit( + gfree + (tb + j & Int32(1)), group=prims.CTAGroup.CTA_1 + ) + ph = _wait_mma(bmma, ph, wl, bar_id) + else: + n1 = Int32(NSLICE) + if cutlass.const_expr(TW): + if tw != Int32(0): + n1 = Int32(0) + for hh in cutlass.range_constexpr(2): + if cutlass.const_expr(hh == 1): + if cutlass.const_expr(skip & (16 | 64) == 0): + _issue_kv_slice( + kv_slot0, + bkv, + tma_swa, + tma_cmp, + use_swa, + grow, + Int32(0), + wl, + lane, + pol_drop, + ) + _issue_kv_slice( + kv_slotB, + bkv + Int32(1), + tma_swa, + tma_cmp, + use_swa, + grow, + Int32(1), + wl, + lane, + pol_drop, + ) + _wait(bkv, ph >> Int32(16) & Int32(1)) + ph = ph ^ Int32(1 << 16) + _wait(bkv + Int32(1), ph >> Int32(17) & Int32(1)) + ph = ph ^ Int32(1 << 17) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if wl == Int32(0): + if prims.elect_sync(): + if cutlass.const_expr(skip & 4 == 0): + for vv in cutlass.range_constexpr(2): + v2 = 2 - 2 * hh + vv + slot2 = kv_slot0 + if cutlass.const_expr(vv == 1): + slot2 = kv_slotB + vdesc2 = prims.Tcgen05SmemDesc.build( + slot2, + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d2 = tmem + Int32( + TM_O + (v2 & 1) * 128 + (v2 >> 1) * PANEL1 + ) + a2 = s_addr + Int32(TILE_N // 4 + (v2 >> 1) * PANEL1) + for kb in cutlass.range_constexpr(TILE_N // 32): + en2 = Boolean(True) + if cutlass.const_expr(kb == 0): + en2 = Boolean(j > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d2, Float32), + prims.make_tmem_ptr(a2 + Int32(8 * kb), E4M3), + vdesc2.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en2, + ) + prims.tcgen05_commit(bmma, group=prims.CTAGroup.CTA_1) + ph = _wait_mma(bmma, ph, wl, bar_id) + for vi in cutlass.range(n1, unroll=1): + v = vi + Int32(3) & Int32(3) + if v != Int32(3): + if cutlass.const_expr(skip & (16 | 64) == 0): + _issue_kv_slice( + kv_slot0, bkv, tma_swa, tma_cmp, use_swa, grow, v, wl, lane, pol_drop + ) + _wait(bkv, ph >> Int32(16) & Int32(1)) + ph = ph ^ Int32(1 << 16) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + vdesc = prims.Tcgen05SmemDesc.build( + kv_slot0, + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d_addr = ( + tmem + + Int32(TM_O) + + (v & Int32(1)) * Int32(128) + + (v >> Int32(1)) * Int32(PANEL1) + ) + a_addr = s_addr + Int32(TILE_N // 4) + (v >> Int32(1)) * Int32(PANEL1) + if wl == Int32(0): + if prims.elect_sync(): + if cutlass.const_expr(skip & 4 == 0): + for kb in cutlass.range_constexpr(TILE_N // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(j > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(bmma, group=prims.CTAGroup.CTA_1) + ph = _wait_mma(bmma, ph, wl, bar_id) + if cutlass.const_expr(prof): + if rtid == Int32(0): + pst[pbase + Int32(4) * j + Int32(3)] = Int64(cute.arch.globaltimer()) + do_epi = Int32(1) + if cutlass.const_expr(phased): + if je != Int32(NTILES): + do_epi = Int32(0) + if do_epi != Int32(0): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + l_tot = l_run + _shfl_xor_f32(l_run, 16) + norm = _final_norm(m_run, l_tot, sink, scale_log2) + out_base = ( + out_addr + + Int64(b) * Int64(HEADS * LATENT * 2) + + Int64((head * Int32(LATENT) + half * Int32(64)) * Int32(2)) + ) + for v in cutlass.range_constexpr(NSLICE): + for hc in cutlass.range_constexpr(2): + o_addr = tmem + lane_base + Int32(TM_O + v % 2 * 128 + v // 2 * PANEL1 + 32 * hc) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + ob = [] + for pi in cutlass.range_constexpr(16): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), + (Float32(o[2 * pi]), Float32(o[2 * pi + 1])), + ftz=False, + rnd="rn", + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + for k in cutlass.range_constexpr(4): + dst = cutlass.inttoptr( + out_base + Int64((v * SLICE + hc * 32 + k * 8) * 2), + mem_space=1, + dtype=Int32, + ) + dst.store( + cutlass.Vector.from_elements( + tuple((ob[4 * k + i] for i in range(4))), Int32 + ), + alignment=16, + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=bar_id, number_of_threads=128) + if cutlass.const_expr(phased): + return (ph, m_run, l_run, qres, pre, dp) + return ph + + +# ==================================================================================================================== +# Persistent sparse-attention tail, consuming exact indexer-selected rows as the indexer publishes them. +# ==================================================================================================================== + +# mbarrier slots (all single-arrival) +NKVG = 3 # KV slot groups (one tile each): tile t uses group t % NKVG +B_Q = 0 # four Q slices loader -> MMA warp +B_KV = 4 # 4 * NKVG KV slots loader -> MMA warp +B_SFULL = 16 # two S buffers: QK done MMA warp -> softmax +B_PV = 18 # PV done MMA warp -> softmax +B_GFREE = 19 # NKVG KV groups, released by the PV that used them MMA warp -> loader +B_QFREE = 22 # Q slices, released after the last QK of a row MMA warp -> loader +B_PRDY = 23 # P stored and O rescaled softmax -> MMA warp +B_ROW = 24 # two row hand-off slots loader -> MMA warp, softmax +B_DRAIN = 26 +NBAR = 27 +TM_SB = 128 # S buffer t & 1 at column 128 * (t & 1); O at A.TM_O (columns 256-511, both 16-lane panels) + + +@cute.jit +def _issue_pv(abar, tp, jp, tmem, kv_base, idesc_pv): + # O += P(tp) V(tp) once the softmax warps have stored P and rescaled O; releases the tile's KV group. + _wait(abar + Int32(B_PRDY), tp & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if prims.elect_sync(): + gp = tp - tp // Int32(NKVG) * Int32(NKVG) + g4 = gp * Int32(4) + s_addr = tmem + (tp & Int32(1)) * Int32(TM_SB) + for v in cutlass.range_constexpr(NSLICE): + vdesc = prims.Tcgen05SmemDesc.build( + kv_base + (g4 + Int32(v)) * Int32(SLOT_BYTES), + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d_addr = tmem + Int32(TM_O + (v & 1) * 128 + (v >> 1) * PANEL1) + a_addr = s_addr + Int32(TILE_N // 4 + (v >> 1) * PANEL1) + for kb in cutlass.range_constexpr(TILE_N // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(jp > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(abar + Int32(B_PV), group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(abar + Int32(B_GFREE) + gp, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def _mma_warp(abar, sRow, q_base, kv_base, tmem): + # Tensor-pipe order per row: QK0, QK1, PV0, QK2, PV1, ..., QK4, PV3, PV4. QK(t) lands in S buffer t & 1 while + # the softmax warps work on S buffer (t - 1) & 1; the pipe executes in issue order, so QK(t) never overwrites + # P(t - 2) before PV(t - 2) has read it. + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=E4M3, + b_dtype=E4M3, + a_major=0, + b_major=1, + n_dim=SLICE, + m_dim=HEADS, + ) + n = Int32(0) + t = Int32(0) + ph = Int32(0) + _wait(abar + Int32(B_ROW) + (n & Int32(1)), n >> Int32(1) & Int32(1)) + b = Int32(sRow[n & Int32(1)]) + while b >= Int32(0): + for j in cutlass.range(NTILES, unroll=1): + tt = t + j + g4 = (tt - tt // Int32(NKVG) * Int32(NKVG)) * Int32(4) + s_addr = tmem + (tt & Int32(1)) * Int32(TM_SB) + if j == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + _wait(abar + Int32(B_Q + c), ph >> Int32(c) & Int32(1)) + ph = ph ^ Int32(15) + for c in cutlass.range_constexpr(NSLICE): + _wait( + abar + Int32(B_KV) + g4 + Int32(c), ph >> Int32(16) + g4 + Int32(c) & Int32(1) + ) + ph = ph ^ Int32(15) << Int32(16) + g4 + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if prims.elect_sync(): + for c in cutlass.range_constexpr(NSLICE): + qdesc = prims.Tcgen05SmemDesc.build( + q_base + Int32(c * Q_SLICE_BYTES), + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + kdesc = prims.Tcgen05SmemDesc.build( + kv_base + (g4 + Int32(c)) * Int32(SLOT_BYTES), + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + for kb in cutlass.range_constexpr(SLICE // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(c > 0) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(kb * 32), + kdesc.advance_start_address(kb * 32), + idesc_qk, + en, + ) + prims.tcgen05_commit( + abar + Int32(B_SFULL) + (tt & Int32(1)), group=prims.CTAGroup.CTA_1 + ) + if j == Int32(NTILES - 1): + prims.tcgen05_commit(abar + Int32(B_QFREE), group=prims.CTAGroup.CTA_1) + if j >= Int32(1): + _issue_pv(abar, tt - Int32(1), j - Int32(1), tmem, kv_base, idesc_pv) + _issue_pv(abar, t + Int32(NTILES - 1), Int32(NTILES - 1), tmem, kv_base, idesc_pv) + t = t + Int32(NTILES) + n = n + Int32(1) + _wait(abar + Int32(B_ROW) + (n & Int32(1)), n >> Int32(1) & Int32(1)) + b = Int32(sRow[n & Int32(1)]) + if prims.elect_sync(): + prims.tcgen05_commit(abar + Int32(B_DRAIN), group=prims.CTAGroup.CTA_1) + _wait(abar + Int32(B_DRAIN), Int32(0)) + + +@cute.jit +def _softmax_row( + rtid, + b, + t, + gv0, + gv1, + gv2, + gv3, + gv4, + tmem, + abar, + s_msk, + sink_ptr, + out_addr: Int64, + scale_log2: Float32, + wide_store: cutlass.Constexpr = False, +): + # Same arithmetic as att_row (online softmax with sinks, P in E4M3 scaled by 448), with S read + # from TMEM once per tile and the PV of the previous tile running underneath. + wl = rtid >> Int32(5) + lane = rtid & Int32(31) + head = wl * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = wl * Int32(32) << Int32(16) + sink = Float32((sink_ptr + head).load()) + Ls = scale_log2 + m_run = Float32(NEG_FLT_MAX) + l_run = Float32(0.0) + for j in cutlass.range(NTILES, unroll=1): + tt = t + j + sb = tt & Int32(1) + gsel = _pick(j, gv0, gv1, gv2, gv3, gv4) + vm = Int32(cute.arch.vote_ballot_sync(gsel >= Int32(0))) + if lane == Int32(0): + s_msk[sb * Int32(4) + wl] = vm + cute.arch.barrier(barrier_id=4, number_of_threads=128) + mk = Int32(s_msk[sb * Int32(4) + half * Int32(2)]) + mk2 = Int32(s_msk[sb * Int32(4) + half * Int32(2) + Int32(1)]) + _wait(abar + Int32(B_SFULL) + sb, tt >> Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tsa = tmem + sb * Int32(TM_SB) + lane_base + s0 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa, Float32), + num=32, + offset=Int64(64), + ) + s1 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa + Int32(32), Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + xs = [] + for ch in cutlass.range_constexpr(2): + for i in cutlass.range_constexpr(32): + x = Float32(s0[i]) + mword = mk + if cutlass.const_expr(ch == 1): + x = Float32(s1[i]) + mword = mk2 + if mword >> Int32(i) & Int32(1) == Int32(0): + x = Float32(-float("inf")) + xs.append(x) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + for i in cutlass.range_constexpr(0, 64, 4): + mx0 = cute.math.max(mx0, xs[i], ftz=True) + mx1 = cute.math.max(mx1, xs[i + 1], ftz=True) + mx2 = cute.math.max(mx2, xs[i + 2], ftz=True) + mx3 = cute.math.max(mx3, xs[i + 3], ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + neg_scaled = -Ls * safe_max + bias = neg_scaled + Float32(LOG2_448) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for pk in cutlass.range_constexpr(16): + x01 = cute.arch.fma_packed_f32x2( + (xs[4 * pk], xs[4 * pk + 1]), (Ls, Ls), (bias, bias), ftz=False, rnd="rn" + ) + x23 = cute.arch.fma_packed_f32x2( + (xs[4 * pk + 2], xs[4 * pk + 3]), (Ls, Ls), (bias, bias), ftz=False, rnd="rn" + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = tsa + Int32(TILE_N // 4) + _tmem_st_p8(p_addr, regs[0:8]) + _tmem_st_p8(p_addr + Int32(8), regs[8:16]) + _tmem_st_p8(p_addr + Int32(PANEL1), regs[0:8]) + _tmem_st_p8(p_addr + Int32(PANEL1 + 8), regs[8:16]) + exp_scale = cute.math.exp2(Ls * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if j > Int32(0): + # O is still being accumulated by PV(tt - 1): wait before rescaling it. + _wait(abar + Int32(B_PV), tt - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + scale = Float32(1.0) + if not ident: + scale = exp_scale + skip_c = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip_c: + _rescale_o(tmem, lane_base, scale) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=4, number_of_threads=128) + if rtid == Int32(0): + prims.mbarrier_arrive(abar + Int32(B_PRDY)) + tl = t + Int32(NTILES - 1) + _wait(abar + Int32(B_PV), tl & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + l_tot = l_run + _shfl_xor_f32(l_run, 16) + norm = _final_norm(m_run, l_tot, sink, scale_log2) + out_base = ( + out_addr + + Int64(b) * Int64(HEADS * LATENT * 2) + + Int64((head * Int32(LATENT) + half * Int32(64)) * Int32(2)) + ) + for v in cutlass.range_constexpr(NSLICE): + for hc in cutlass.range_constexpr(2): + o_addr = tmem + lane_base + Int32(TM_O + v % 2 * 128 + v // 2 * PANEL1 + 32 * hc) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + ob = [] + for pi in cutlass.range_constexpr(16): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), (Float32(o[2 * pi]), Float32(o[2 * pi + 1])), ftz=False, rnd="rn" + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + if cutlass.const_expr(wide_store): + for k in cutlass.range_constexpr(2): + dst = cutlass.inttoptr( + out_base + Int64((v * SLICE + hc * 32 + k * 16) * 2), + mem_space=1, + dtype=Int32, + ) + dst.store( + cutlass.Vector.from_elements( + tuple((ob[8 * k + i] for i in range(8))), Int32 + ), + alignment=32, + ) + else: + for k in cutlass.range_constexpr(4): + dst = cutlass.inttoptr( + out_base + Int64((v * SLICE + hc * 32 + k * 8) * 2), + mem_space=1, + dtype=Int32, + ) + dst.store( + cutlass.Vector.from_elements( + tuple((ob[4 * k + i] for i in range(4))), Int32 + ), + alignment=16, + ) + # O has been read: the next row's first PV (after its P-ready barrier) may overwrite it. + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + + +@cute.jit +def _issue_kv_tile(slot_base, mbar_base, tma_swa, tma_cmp, use_swa, gidx_t, wl, lane): + # All four 128-B slices of each gathered 512-B row are requested back to back, so the row's DRAM page is + # opened once instead of once per slice. + if wl == Int32(0): + if prims.elect_sync(): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(mbar_base + Int32(c), SLOT_BYTES) + dst0 = slot_base + wl * Int32(32 * SLICE) + for q in cutlass.range(8, unroll=1): + r0 = _shfl_idx_i32(gidx_t, Int32(4 * q)) + r1 = _shfl_idx_i32(gidx_t, Int32(4 * q + 1)) + r2 = _shfl_idx_i32(gidx_t, Int32(4 * q + 2)) + r3 = _shfl_idx_i32(gidx_t, Int32(4 * q + 3)) + for c in cutlass.range_constexpr(NSLICE): + dst = dst0 + Int32(c * SLOT_BYTES) + Int32(4 * q * SLICE) + if use_swa: + _tma_gather4( + dst, tma_swa.get_ptr(), mbar_base + Int32(c), Int32(c * SLICE), r0, r1, r2, r3 + ) + else: + _tma_gather4( + dst, tma_cmp.get_ptr(), mbar_base + Int32(c), Int32(c * SLICE), r0, r1, r2, r3 + ) + + +class AttentionTail: + def __init__( + self, + config: SpecDsaConfig | None = None, + exit_early: bool = False, + wide_store: bool = False, + ): + # wide_store: the output epilogue writes 32-byte stores (st.global.v8) instead of 16-byte ones, half the store + # instructions of a row; it needs ``out`` to be 32-byte aligned + self.wide_store = bool(wide_store) + require_built_for( + config, SPEC_FP4 if config is not None and config.index_k_dtype == "fp4" else SPEC + ) + self.threads = 288 # warps 0-3 loader, 4-7 softmax/epilogue, 8 MMA issue + # exit_early: the "last CTA to leave resets the ready queue" accounting runs on the loader thread right + # after the CTA's final claim, not behind the last row's epilogue (where its fence waits for the output stores) + self.exit_early = bool(exit_early) + + @cute.jit + def __call__( + self, + q_att: cute.Tensor, + swa_pool: cute.Tensor, + c_pool: cute.Tensor, + gidx: cute.Tensor, + sinks: cute.Tensor, + out: cute.Tensor, + aq: cute.Tensor, + softmax_scale: Float32, + nctas: Int32, + stream: cuda.CUstream, + ): + tma_q = xcuda.create_tensor_map_tiled( + global_address=q_att.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, HEADS, q_att.shape[0]], + global_strides=[LATENT // 16, HEADS * LATENT // 16], + box_dims=[SLICE, HEADS, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_swa = xcuda.create_tensor_map_tiled( + global_address=swa_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, swa_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_cmp = xcuda.create_tensor_map_tiled( + global_address=c_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, c_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + self.kernel(tma_q, tma_swa, tma_cmp, gidx, sinks, out, aq, softmax_scale).launch( + grid=(nctas, 1, 1), + block=(self.threads, 1, 1), + stream=stream, + min_blocks_per_mp=1, + use_pdl=True, + ) + + @cute.jit + def _claim(self, tid, aq_base: Int64, nrows, sRow, sLd, abar, n): + # Loader thread 0 takes the next completed row (-1 once all rows are taken) and hands it to both groups. + if tid == Int32(0): + k = L.atom_add_i32(aq_base + Int64(L.AQ_CLAIM * 4), Int32(1)) + b = Int32(-1) + if k < nrows: + ea = aq_base + Int64(L.AQ_ENTRY * 4) + Int64(k) * Int64(4) + b = L.ld_acquire_i32(ea) + while b < Int32(0): + L.nanosleep(Int32(256)) + b = L.ld_acquire_i32(ea) + L.st_relaxed_i32(ea, Int32(-1)) + sRow[n & Int32(1)] = b + sLd[n & Int32(1)] = b + prims.mbarrier_arrive(abar + Int32(B_ROW) + (n & Int32(1))) + cute.arch.barrier(barrier_id=2, number_of_threads=128) + return Int32(sLd[n & Int32(1)]) + + @cute.kernel + def kernel( + self, + tma_q: cutlass.GridConstant[xcuda.TensorMap], + tma_swa: cutlass.GridConstant[xcuda.TensorMap], + tma_cmp: cutlass.GridConstant[xcuda.TensorMap], + gidx: cute.Tensor, + sinks: cute.Tensor, + out: cute.Tensor, + aq: cute.Tensor, + softmax_scale: Float32, + ): + tid, _, _ = cute.arch.thread_idx() + gdim, _, _ = cute.arch.grid_dim() + smem = cutlass.utils.SmemAllocator() + sQ = smem.allocate_tensor( + cutlass.Float8E4M3FN, cute.make_layout(NSLICE * Q_SLICE_BYTES), byte_alignment=1024 + ) + sKV = smem.allocate_tensor( + cutlass.Float8E4M3FN, cute.make_layout(4 * NKVG * SLOT_BYTES), byte_alignment=1024 + ) + sBar = smem.allocate_tensor(Int64, cute.make_layout(32), byte_alignment=16) + sMask = smem.allocate_tensor(Int32, cute.make_layout(8), byte_alignment=16) + sRow = smem.allocate_tensor(Int32, cute.make_layout(4), byte_alignment=16) + sLd = smem.allocate_tensor(Int32, cute.make_layout(4), byte_alignment=16) + sTmem = smem.allocate_tensor(Int32, cute.make_layout(1), byte_alignment=16) + if tid < Int32(NBAR): + prims.mbarrier_init(sBar.iterator.raw_ptr() + tid, 1) + prims.fence_mbarrier_init() + tmem_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=self.threads) + tmem = cutlass.utils.TmemAllocator( + sTmem.iterator, barrier_for_retrieve=tmem_barrier, allocator_warp_id=0, is_two_cta=False + ) + tmem.allocate(512) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(Float32) + tmem_addr = cute.arch.load(sTmem.iterator, Int32, sem="relaxed", scope="cta") + q_base = sQ.iterator.raw_ptr() + kv_base = sKV.iterator.raw_ptr() + abar = sBar.iterator.raw_ptr() + aq_base = aq.iterator.toint() + gidx_base = gidx.iterator.toint() + nrows = Int32(gidx.shape[0]) + if tid < Int32(128): + wl = tid >> Int32(5) + lane = tid & Int32(31) + n = Int32(0) + t = Int32(0) + b = self._claim(tid, aq_base, nrows, sRow, sLd, abar, n) + while b >= Int32(0): + if n >= Int32(1): + _wait(abar + Int32(B_QFREE), n - Int32(1) & Int32(1)) + if tid == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(abar + Int32(B_Q + c), Q_SLICE_BYTES) + prims.cp_async_bulk_tensor_shared_cta_global( + q_base + Int32(c * Q_SLICE_BYTES), + tma_q.get_ptr(), + [Int32(c * SLICE), Int32(0), b], + abar + Int32(B_Q + c), + ) + grow_base = gidx_base + Int64(b) * Int64(NROWS * 4) + Int64(tid * Int32(4)) + for j in cutlass.range(NTILES, unroll=1): + tq = t // Int32(NKVG) + g = t - tq * Int32(NKVG) + if t >= Int32(NKVG): + _wait(abar + Int32(B_GFREE) + g, tq - Int32(1) & Int32(1)) + grow = _grow(L.ld_cg_i32(grow_base + Int64(j * Int32(TILE_N * 4)))) + _issue_kv_tile( + kv_base + g * Int32(4 * SLOT_BYTES), + abar + Int32(B_KV) + g * Int32(4), + tma_swa, + tma_cmp, + j == Int32(0), + grow, + wl, + lane, + ) + t = t + Int32(1) + n = n + Int32(1) + b = self._claim(tid, aq_base, nrows, sRow, sLd, abar, n) + if cutlass.const_expr(self.exit_early): + if tid == Int32(0): + L.fence_acq_rel_gpu() + d_e = L.atom_add_i32(aq_base + Int64(L.AQ_DONE * 4), Int32(1)) + if d_e == Int32(gdim) - Int32(1): + L.fence_acq_rel_gpu() + L.st_relaxed_i32(aq_base + Int64(L.AQ_PUB * 4), Int32(0)) + L.st_relaxed_i32(aq_base + Int64(L.AQ_CLAIM * 4), Int32(0)) + L.st_relaxed_i32(aq_base + Int64(L.AQ_DONE * 4), Int32(0)) + elif tid < Int32(256): + rtid = tid - Int32(128) + scale_log2 = softmax_scale * Float32(LOG2_E) + out_addr = out.iterator.toint() + n = Int32(0) + t = Int32(0) + _wait(abar + Int32(B_ROW) + (n & Int32(1)), n >> Int32(1) & Int32(1)) + b = Int32(sRow[n & Int32(1)]) + while b >= Int32(0): + gb = gidx_base + Int64(b) * Int64(NROWS * 4) + Int64(rtid * Int32(4)) + gv0 = L.ld_cg_i32(gb) + gv1 = L.ld_cg_i32(gb + Int64(TILE_N * 4)) + gv2 = L.ld_cg_i32(gb + Int64(2 * TILE_N * 4)) + gv3 = L.ld_cg_i32(gb + Int64(3 * TILE_N * 4)) + gv4 = L.ld_cg_i32(gb + Int64(4 * TILE_N * 4)) + _softmax_row( + rtid, + b, + t, + gv0, + gv1, + gv2, + gv3, + gv4, + tmem_addr, + abar, + sMask, + sinks.iterator.raw_ptr() + b * Int32(HEADS), + out_addr, + scale_log2, + self.wide_store, + ) + t = t + Int32(NTILES) + n = n + Int32(1) + _wait(abar + Int32(B_ROW) + (n & Int32(1)), n >> Int32(1) & Int32(1)) + b = Int32(sRow[n & Int32(1)]) + else: + _mma_warp(abar, sRow, q_base, kv_base, tmem_addr) + cute.arch.fence_view_async_tmem_load() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=3, number_of_threads=self.threads) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + if tid == Int32(0): + # Every CTA has made its final claim; the last one to leave resets the counters for the next call. + # All rows were published before they could be claimed, so the indexer no longer touches the queue. + if cutlass.const_expr(not self.exit_early): + L.fence_acq_rel_gpu() + d = L.atom_add_i32(aq_base + Int64(L.AQ_DONE * 4), Int32(1)) + if d == Int32(gdim) - Int32(1): + L.fence_acq_rel_gpu() + L.st_relaxed_i32(aq_base + Int64(L.AQ_PUB * 4), Int32(0)) + L.st_relaxed_i32(aq_base + Int64(L.AQ_CLAIM * 4), Int32(0)) + L.st_relaxed_i32(aq_base + Int64(L.AQ_DONE * 4), Int32(0)) + # Do not complete before the indexer grid: the next call's indexer reuses its workspaces. + cute.arch.griddepcontrol_wait() + + +def compile_tail(tail: AttentionTail): + rt = cute.runtime + qa_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + sp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + cp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + sb = cute.sym_int() + gi_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, NROWS), stride_order=(1, 0)) + sk_fake = rt.make_fake_compact_tensor( + cutlass.Float32, (sb, 64), stride_order=(1, 0), assumed_align=16 + ) + ou_fake = rt.make_fake_compact_tensor( + cutlass.BFloat16, (sb, 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + aq_fake = rt.make_fake_compact_tensor( + cutlass.Int32, (sb, 16), stride_order=(1, 0), assumed_align=16 + ) + stream = rt.make_fake_stream(use_tvm_ffi_env_stream=True) + return cute.compile( + tail, + qa_fake, + sp_fake, + cp_fake, + gi_fake, + sk_fake, + ou_fake, + aq_fake, + Float32(1.0), + Int32(1), + stream, + options="--enable-tvm-ffi --generate-line-info", + ) + + +# ==================================================================================================================== +# Persistent indexer kernel: FP8 indexer logits, exact top-512 selection and KV-row mapping. +# ==================================================================================================================== + +_RND_RN = "rn" +NEG_INF = -math.inf +K_TOP = SPEC.topk +RING = 256 +RING_CHUNK = 64 +MAIN_CAP = 2048 +TRIG = 1280 +PMAX_SMEM = 4 +PMAX = 8 +SEGW = 520 +MARK_HI = 4294967295 +SEL_BAR = 2 +ROW_BAR = 4 +END_BAR = 5 +SEL_NTHR = 128 +ATTQ = 8 +DQ_CAP = 128 +DEFER_LONG = 512 +ST_SCHED = 1 +ST_ROW = 2 +ST_DQFULL = 4 +COV_CAP = 32 # capacity of the list of the other pieces of a row (merge1) + + +@dsl_user_op +def _consume_f32(x, *, loc=None, ip=None): + return Float32( + _llvm.inline_asm( + _T.f32(), + [Float32(x).ir_value(loc=loc, ip=ip)], + "mov.b32 $0, $1;", + "=f,f", + has_side_effects=True, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _warp_atomic_i32(ptr, lane): + # One atomic poll per warp; propagate the acquire edge to every reader. + value = Int32(0) + if lane == Int32(0): + value = cute.arch.load(ptr, Int32, sem="acquire", scope="cta") + value = cute.arch.shuffle_sync(value, 0) + cute.arch.sync_warp() + return value + + +@cute.jit +def _warp_atomic_u32(ptr, lane): + # The packed tag and conservative floor are the complete atomic payload. + value = Uint32(0) + if lane == Int32(0): + value = cute.arch.load(ptr, Uint32, sem="relaxed", scope="cta") + return cute.arch.shuffle_sync(value, 0) + + +@cute.jit +def _pack_floor_key(key, seg): + # At most 1024 segments per CTA in scope, so the epoch fits in ten bits. + # Rounding an ordered key down can only admit additional candidates. + return (Uint32(key) & Uint32(0xFFFFFC00)) | Uint32(seg) + + +@cute.jit +def _wait_chunk_empty(empty_ptr, stage, phase, stall, prof: cutlass.Constexpr = False): + ready = prims.mbarrier_wait_parity( + empty_ptr + stage, phase, prims.MBarrierWait.TEST, scope="cta", order="acquire" + ) + ready = cute.arch.vote_all_sync(ready) + if not ready: + t_s = Int64(0) + if cutlass.const_expr(prof): + t_s = cutlass.Int64(cute.arch.globaltimer()) + ready = cutlass.Boolean(False) + while not ready: + ready = prims.mbarrier_try_wait_parity( + empty_ptr + stage, phase, scope="cta", order="acquire" + ) + ready = cute.arch.vote_all_sync(ready) + if cutlass.const_expr(prof): + stall = stall + (cutlass.Int64(cute.arch.globaltimer()) - t_s) + return stall + + +@cute.jit +def _push_ring( + hit, + entry, + head, + s_ring, + ring_off, + empty_ptr, + full_ptr, + lane, + lt_mask, + stall, + prof: cutlass.Constexpr = False, +): + mask = Int32(cute.arch.vote_ballot_sync(hit)) + if mask != Int32(0): + n = Int32(cute.arch.popc(mask)) + offset = head & Int32(RING_CHUNK - 1) + stage = (head >> Int32(6)) & Int32(RING // RING_CHUNK - 1) + if offset == Int32(0): + phase = ((head >> Int32(8)) & Int32(1)) ^ Int32(1) + stall = _wait_chunk_empty(empty_ptr, stage, phase, stall, prof) + first = Int32(RING_CHUNK) - offset + if first > n: + first = n + rank = Int32(cute.arch.popc(mask & lt_mask)) + if hit & (rank < first): + slot = (head + rank) & Int32(RING - 1) + s_ring[ring_off + slot] = entry + head = head + first + if offset + first == Int32(RING_CHUNK): + # All 32 writers publish their own stores, including earlier pushes. + prims.mbarrier_arrive(full_ptr + stage, scope="cta", relaxed=False) + if first < n: + # Publish the completed chunk before waiting on the spill chunk. + stage = (head >> Int32(6)) & Int32(RING // RING_CHUNK - 1) + phase = ((head >> Int32(8)) & Int32(1)) ^ Int32(1) + stall = _wait_chunk_empty(empty_ptr, stage, phase, stall, prof) + if hit & (rank >= first): + slot = (head + rank - first) & Int32(RING - 1) + s_ring[ring_off + slot] = entry + head = head + n - first + return (head, stall) + + +@cute.jit +def _push_marker(seg_ord, head, s_ring, ring_off, empty_ptr, full_ptr, lane): + offset = head & Int32(RING_CHUNK - 1) + stage = (head >> Int32(6)) & Int32(RING // RING_CHUNK - 1) + if offset == Int32(0): + phase = ((head >> Int32(8)) & Int32(1)) ^ Int32(1) + _wait_chunk_empty(empty_ptr, stage, phase, Int64(0)) + chunk_base = head - offset + # The consumer reads all 64 slots; initialize the complete marker suffix. + if lane >= offset: + s_ring[ring_off + ((chunk_base + lane) & Int32(RING - 1))] = Uint64(MARK_HI) << Uint64( + 32 + ) | Uint64(Uint32(seg_ord)) + if lane + Int32(32) >= offset: + s_ring[ring_off + ((chunk_base + lane + Int32(32)) & Int32(RING - 1))] = Uint64( + MARK_HI + ) << Uint64(32) | Uint64(Uint32(seg_ord)) + prims.mbarrier_arrive(full_ptr + stage, scope="cta", relaxed=False) + return chunk_base + Int32(RING_CHUNK) + + +@cute.jit +def _floor_of(tw_ptr, seg_ord, lane): + tw = _warp_atomic_u32(tw_ptr, lane) + t = Float32(NEG_INF) + if (tw & Uint32(1023)) == Uint32(seg_ord): + key = tw & Uint32(0xFFFFFC00) + # Zero initialization and rounded -inf lie in the negative-NaN range. + if key >= Uint32(0x007FFFFF): + t = L.invkey(key) + return t + + +@cute.jit +def _drain_ring( + r, + tail_r, + done_r, + kth_key, + s_ring, + full_ptr, + empty_ptr, + sMain, + cnt_ptr, + lane, + lt_mask, + kmin_ptr, + kmax_ptr, +): + used = Int32(0) + prog = Int32(0) + if done_r == Int32(0): + stage = (tail_r >> Int32(6)) & Int32(RING // RING_CHUNK - 1) + phase = (tail_r >> Int32(8)) & Int32(1) + # A selector warp services two rings, so probe rather than park on one. + ready = prims.mbarrier_wait_parity( + full_ptr + stage, phase, prims.MBarrierWait.TEST, scope="cta", order="acquire" + ) + ready = cute.arch.vote_all_sync(ready) + if ready: + e0 = Uint64(s_ring[r * Int32(RING) + ((tail_r + lane) & Int32(RING - 1))]) + e1 = Uint64(s_ring[r * Int32(RING) + ((tail_r + lane + Int32(32)) & Int32(RING - 1))]) + ism0 = Uint32(e0 >> Uint64(32)) == Uint32(MARK_HI) + ism1 = Uint32(e1 >> Uint64(32)) == Uint32(MARK_HI) + mm0 = Int32(cute.arch.vote_ballot_sync(ism0)) + mm1 = Int32(cute.arch.vote_ballot_sync(ism1)) + # Markers occupy a suffix and every slot in that suffix is initialized. + nuse = Int32(RING_CHUNK) - Int32(cute.arch.popc(mm0)) - Int32(cute.arch.popc(mm1)) + if (mm0 | mm1) != Int32(0): + done_r = Int32(1) + fk0 = L.fkey_bits(L.entry_bits(e0)) + fk1 = L.fkey_bits(L.entry_bits(e1)) + # _select_role always passes a score-only floor (low 32 bits zero). + floor = Uint32(kth_key >> Uint64(32)) + keep0 = (not ism0) & (fk0 >= floor) + keep1 = (not ism1) & (fk1 >= floor) + km0 = Int32(cute.arch.vote_ballot_sync(keep0)) + km1 = Int32(cute.arch.vote_ballot_sync(keep1)) + nk0 = Int32(cute.arch.popc(km0)) + nk = nk0 + Int32(cute.arch.popc(km1)) + fmn = Uint32(4294967295) + fmx = Uint32(0) + if keep0: + fmn = fk0 + fmx = fk0 + if keep1: + if fk1 < fmn: + fmn = fk1 + if fk1 > fmx: + fmx = fk1 + fmn = L.warp_min_u32(fmn) + fmx = L.warp_max_u32(fmx) + base = Int32(0) + if lane == Int32(0): + if nk > Int32(0): + base = Int32(cute.arch.atomic_add(cnt_ptr, nk, sem="relaxed", scope="cta")) + cute.arch.atomic_min(kmin_ptr, fmn, sem="relaxed", scope="cta") + cute.arch.atomic_max(kmax_ptr, fmx, sem="relaxed", scope="cta") + base = cute.arch.shuffle_sync(base, 0) + if keep0: + sMain[base + Int32(cute.arch.popc(km0 & lt_mask))] = e0 + if keep1: + sMain[base + nk0 + Int32(cute.arch.popc(km1 & lt_mask))] = e1 + used = nuse + tail_r = tail_r + Int32(RING_CHUNK) + # Every reader releases its own load before this chunk can be reused. + prims.mbarrier_arrive(empty_ptr + stage, scope="cta", relaxed=False) + prog = Int32(1) + return (tail_r, done_r, used, prog) + + +EPT = MAIN_CAP // SEL_NTHR +KEEP_CAP = 1280 + + +@cute.jit +def _compact_approx( + sMain, + C, + sHist, + sRes, + cnt_ptr, + kmin_ptr, + kmax_ptr, + kmin2_ptr, + sScal, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + prof=None, + keep_cap: cutlass.Constexpr = KEEP_CAP, + nb: cutlass.Constexpr = 1024, + tw_ptr=None, + seg=None, + tiebin: cutlass.Constexpr = False, + sTb=None, + fast_cmp: cutlass.Constexpr = False, +): + lane = tid & Int32(31) + tp0 = Int64(0) + if cutlass.const_expr(prof is not None): + tp0 = cutlass.Int64(cute.arch.globaltimer()) + lo = L.invkey(Uint32(cute.arch.load(kmin_ptr, Uint32, sem="relaxed", scope="cta"))) + hi = L.invkey(Uint32(cute.arch.load(kmax_ptr, Uint32, sem="relaxed", scope="cta"))) + wv = (hi - lo) * Float32(1.0 / nb) + sc = Float32(0.0) + if wv > Float32(0.0): + if wv < Float32(3e38): + sc = cute.arch.rcp_approx(wv) + for z_ in cutlass.range_constexpr(max(1, nb // nthr)): + if tid + Int32(z_ * nthr) < Int32(nb): + sHist[tid + Int32(z_ * nthr)] = Int32(0) + if tid == Int32(0): + sScal[24] = Int32(0) + cute.arch.store(kmin2_ptr, Uint32(4294967295), sem="relaxed", scope="cta") + L.bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + tp1 = cutlass.Int64(cute.arch.globaltimer()) + prof[0] = prof[0] + (tp1 - tp0) + tp0 = tp1 + ev = [Uint64(0)] * EPT + i = tid + if cutlass.const_expr(fast_cmp): + # all loads first, then the bins, then the histogram atomics + for k in cutlass.range_constexpr(EPT): + ev[k] = Uint64(sMain[cutlass.min(tid + Int32(k * nthr), C - Int32(1))]) + hb = [] + for k in cutlass.range_constexpr(EPT): + hb.append(L._vbin(ev[k], lo, sc, nb)) + for k in cutlass.range_constexpr(EPT): + if tid + Int32(k * nthr) < C: + cute.arch.atomic_add(sHist.iterator + hb[k], Int32(1), sem="relaxed", scope="cta") + else: + for k in cutlass.range_constexpr(EPT): + i = tid + Int32(k * nthr) + if i < C: + ev[k] = Uint64(sMain[i]) + cute.arch.atomic_add( + sHist.iterator + L._vbin(ev[k], lo, sc, nb), + Int32(1), + sem="relaxed", + scope="cta", + ) + L.bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + tp1 = cutlass.Int64(cute.arch.globaltimer()) + prof[1] = prof[1] + (tp1 - tp0) + tp0 = tp1 + L.find_cross(sHist, Int32(K_TOP), tid, sRes, nb) + L.bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + tp1 = cutlass.Int64(cute.arch.globaltimer()) + prof[2] = prof[2] + (tp1 - tp0) + tp0 = tp1 + B = sRes[L.RES_B] + kept = sRes[L.RES_ABOVE] + sRes[L.RES_M] + mode2 = Int32(0) + idx_thr = Int32(2147483647) + if cutlass.const_expr(tiebin): + if kept > Int32(keep_cap): + above = sRes[L.RES_ABOVE] + if tid == Int32(0): + sTb[0] = Uint32(4294967295) + sTb[1] = Uint32(0) + sTb[2] = Uint32(4294967295) + sTb[3] = Uint32(0) + for z_ in cutlass.range_constexpr(max(1, nb // nthr)): + if tid + Int32(z_ * nthr) < Int32(nb): + sHist[tid + Int32(z_ * nthr)] = Int32(0) + L.bar(bar_id, nthr) + fmn_b = Uint32(4294967295) + fmx_b = Uint32(0) + imn_b = Uint32(4294967295) + imx_b = Uint32(0) + for k in cutlass.range(EPT, unroll=1): + i = tid + k * Int32(nthr) + if i < C: + e = Uint64(sMain[i]) + if L._vbin(e, lo, sc, nb) == B: + fk = L.fkey_bits(L.entry_bits(e)) + ix = Uint32(e >> Uint64(32)) + if fk < fmn_b: + fmn_b = fk + if fk > fmx_b: + fmx_b = fk + if ix < imn_b: + imn_b = ix + if ix > imx_b: + imx_b = ix + fmn_b = L.warp_min_u32(fmn_b) + fmx_b = L.warp_max_u32(fmx_b) + imn_b = L.warp_min_u32(imn_b) + imx_b = L.warp_max_u32(imx_b) + if lane == Int32(0): + cute.arch.atomic_min(sTb.iterator, fmn_b, sem="relaxed", scope="cta") + cute.arch.atomic_max(sTb.iterator + 1, fmx_b, sem="relaxed", scope="cta") + cute.arch.atomic_min(sTb.iterator + 2, imn_b, sem="relaxed", scope="cta") + cute.arch.atomic_max(sTb.iterator + 3, imx_b, sem="relaxed", scope="cta") + L.bar(bar_id, nthr) + fmn_b = Uint32(sTb[0]) + fmx_b = Uint32(sTb[1]) + imn_b = Uint32(sTb[2]) + imx_b = Uint32(sTb[3]) + if fmn_b == fmx_b: + mode2 = Int32(1) + span = imx_b - imn_b + sh = Uint32(0) + while span >> sh >= Uint32(nb): + sh = sh + Uint32(1) + for k in cutlass.range(EPT, unroll=1): + i = tid + k * Int32(nthr) + if i < C: + e = Uint64(sMain[i]) + if L._vbin(e, lo, sc, nb) == B: + b2 = Int32(imx_b - Uint32(e >> Uint64(32)) >> sh) + cute.arch.atomic_add( + sHist.iterator + b2, Int32(1), sem="relaxed", scope="cta" + ) + L.bar(bar_id, nthr) + L.find_cross(sHist, Int32(K_TOP) - above, tid, sRes, nb) + L.bar(bar_id, nthr) + B2 = sRes[L.RES_B] + kept = above + sRes[L.RES_ABOVE] + sRes[L.RES_M] + idx_thr = Int32(imx_b - (Uint32(B2) << sh)) + if cutlass.const_expr(tw_ptr is not None): + if tid < Int32(8): + if (kept <= Int32(keep_cap)) & (mode2 == Int32(0)): + if B >= Int32(2): + te = lo + Float32(B - Int32(2)) * wv + mag = cute.math.max(abs(lo), abs(hi)) + if wv > mag * Float32(1e-05): + if te > lo: + cute.arch.atomic_exch( + tw_ptr + tid, + _pack_floor_key(L.fkey(te), seg), + sem="relaxed", + scope="cta", + ) + tf = Uint32(0) + if kept <= Int32(keep_cap): + lm = Int32(cute.arch.lanemask_lt()) + fmn = Uint32(4294967295) + kmask = [Int32(0)] * EPT + wtot = Int32(0) + if cutlass.const_expr(fast_cmp): + kpl = [] + ceq = [] + for k in cutlass.range_constexpr(EPT): + bbk = L._vbin(ev[k], lo, sc, nb) + kpk = (tid + Int32(k * nthr) < C) & (bbk >= B) + if cutlass.const_expr(tiebin): + kpk = kpk & ((bbk != B) | (Int32(Uint32(ev[k] >> Uint64(32))) <= idx_thr)) + kpl.append(kpk) + ceq.append(kpk & (bbk == B)) + for k in cutlass.range_constexpr(EPT): + fkk = L.fkey_bits(L.entry_bits(ev[k])) + fcand = Uint32(cutlass.select_(ceq[k], fkk, Uint32(4294967295))) + fmn = Uint32(cutlass.select_(fcand < fmn, fcand, fmn)) + kmask[k] = Int32(cute.arch.vote_ballot_sync(kpl[k])) + wtot = wtot + Int32(cute.arch.popc(kmask[k])) + else: + for k in cutlass.range_constexpr(EPT): + i = tid + Int32(k * nthr) + kp = False + bb = Int32(-1) + if i < C: + bb = L._vbin(ev[k], lo, sc, nb) + if bb >= B: + kp = True + if cutlass.const_expr(tiebin): + if bb == B: + if Int32(Uint32(ev[k] >> Uint64(32))) > idx_thr: + kp = False + if kp & (bb == B): + fk = L.fkey_bits(L.entry_bits(ev[k])) + if fk < fmn: + fmn = fk + kmask[k] = Int32(cute.arch.vote_ballot_sync(kp)) + wtot = wtot + Int32(cute.arch.popc(kmask[k])) + base = Int32(0) + if lane == Int32(0): + if wtot > Int32(0): + base = Int32( + cute.arch.atomic_add( + sScal.iterator + Int32(24), wtot, sem="relaxed", scope="cta" + ) + ) + base = cute.arch.shuffle_sync(base, 0) + for k in cutlass.range_constexpr(EPT): + if kmask[k] >> lane & Int32(1) != Int32(0): + sMain[base + Int32(cute.arch.popc(kmask[k] & lm))] = ev[k] + base = base + Int32(cute.arch.popc(kmask[k])) + fmn = L.warp_min_u32(fmn) + if lane == Int32(0): + cute.arch.atomic_min(kmin2_ptr, fmn, sem="relaxed", scope="cta") + L.bar(bar_id, nthr) + tf = Uint32(cute.arch.load(kmin2_ptr, Uint32, sem="relaxed", scope="cta")) + if tid == Int32(0): + cute.arch.store(cnt_ptr, kept, sem="relaxed", scope="cta") + cute.arch.store(kmin_ptr, tf, sem="relaxed", scope="cta") + L.bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + tp1 = cutlass.Int64(cute.arch.globaltimer()) + prof[3] = prof[3] + (tp1 - tp0) + else: + kept = Int32(-1) + return (kept, tf) + + +@cute.jit +def _parts_of_row(q, cta, sched, num_sms, lane): + P = Int32(0) + p = Int32(0) + nit = (num_sms + Int32(31)) // Int32(32) + it = Int32(0) + while it < nit: + c = lane + it * Int32(32) + v = False + if c < num_sms: + sq0 = sched[c, 0] + skv0 = sched[c, 1] + sq1 = sched[c + 1, 0] + skv1 = sched[c + 1, 1] + hi = sq1 + if skv1 == Int32(0): + hi = sq1 - Int32(1) + if (sq0 != sq1) | (skv0 != skv1): + if sq0 <= q: + if q <= hi: + v = True + bv = Int32(cute.arch.vote_ballot_sync(v)) + bl = Int32(cute.arch.vote_ballot_sync(v & (c < cta))) + P = P + Int32(cute.arch.popc(bv)) + p = p + Int32(cute.arch.popc(bl)) + it = it + Int32(1) + return (P, p) + + +@cute.jit +def _parts_cov(q, cta, sched, num_sms, lane, s_cov): + # _parts_of_row that also lists the other pieces of the row: s_cov[j] = slot (cta * 2 + side) + # of the j-th other covering CTA in CTA order, side 0 when the row is the first row of that + # CTA's range, else 1 (the slot its piece of the row was written to). + P = Int32(0) + p = Int32(0) + ncov = Int32(0) + lm = Int32(cute.arch.lanemask_lt()) + nit = (num_sms + Int32(31)) // Int32(32) + it = Int32(0) + while it < nit: + c = lane + it * Int32(32) + v = False + side = Int32(1) + if c < num_sms: + sq0 = sched[c, 0] + skv0 = sched[c, 1] + sq1 = sched[c + 1, 0] + skv1 = sched[c + 1, 1] + hi = sq1 + if skv1 == Int32(0): + hi = sq1 - Int32(1) + if (sq0 != sq1) | (skv0 != skv1): + if sq0 <= q: + if q <= hi: + v = True + if sq0 == q: + side = Int32(0) + bv = Int32(cute.arch.vote_ballot_sync(v)) + bl = Int32(cute.arch.vote_ballot_sync(v & (c < cta))) + vx = v & (c != cta) + bx = Int32(cute.arch.vote_ballot_sync(vx)) + if vx: + pos = ncov + Int32(cute.arch.popc(bx & lm)) + if pos < Int32(COV_CAP): + s_cov[pos] = c * Int32(2) + side + ncov = ncov + Int32(cute.arch.popc(bx)) + P = P + Int32(cute.arch.popc(bv)) + p = p + Int32(cute.arch.popc(bl)) + it = it + Int32(1) + return (P, p) + + +@cute.jit +def _cover_ballot(q, cta, sched, num_sms, lane, it): + c = lane + it * Int32(32) + v = False + if c < num_sms: + if c != cta: + sq0 = sched[c, 0] + skv0 = sched[c, 1] + sq1 = sched[c + 1, 0] + skv1 = sched[c + 1, 1] + hi = sq1 + if skv1 == Int32(0): + hi = sq1 - Int32(1) + if (sq0 != sq1) | (skv0 != skv1): + if sq0 <= q: + if q <= hi: + v = True + return Int32(cute.arch.vote_ballot_sync(v)) + + +@cute.jit +def _write_row_outputs_regs( + row, n, s_out, nout, short, topk_out, gidx, bt_swa, bt_c, pos, req, mbs, mbc, tid +): + gv = [] + for q in cutlass.range_constexpr(5): + col = tid + Int32(q * 128) + g = Int32(-1) + if cutlass.const_expr(q == 0): + g = L.l2g_swa(col, pos, req, bt_swa, mbs, Int32(0)) + else: + i = col - Int32(L.SWA) + idx = Int32(-1) + if short != Int32(0): + if i < n: + idx = i + elif i < nout: + idx = Int32(Uint32(4294967295) - Uint32(Uint64(s_out[i]) & Uint64(4294967295))) + topk_out[row, i] = idx + g = L.l2g_compressed(idx, req, bt_c, mbc, Int32(0)) + gv.append(g) + for q in cutlass.range_constexpr(5): + gidx[row, tid + Int32(q * 128)] = gv[q] + return (gv[0], gv[1], gv[2], gv[3], gv[4]) + + +@cute.jit +def _final512_token32(sHand, nout, tid, bar_id: cutlass.Constexpr): + # topk is a set and attention does not depend on row order: convert the completed row's entries to the + # output writer's inverted-token low word in place instead of sorting them. + base = tid * Int32(4) + for i in cutlass.range_constexpr(4): + if base + Int32(i) < nout: + sHand[base + Int32(i)] = Uint64( + Uint32(4294967295) - Uint32(Uint64(sHand[base + Int32(i)]) >> Uint64(32)) + ) + L.bar(bar_id, 128) + + +@cute.jit +def _pick_final32(a, b, first): + r = cutlass.min(a, b) + if not first: + r = cutlass.max(a, b) + return r + + +@cute.jit +def _sort_final512_token32(sHand, nout, sScratch, tid, bar_id: cutlass.Constexpr): + # Sort only the completed row. Four keys per thread keep the small + # exchanges in registers; three large exchanges use dead merge scratch. + base = tid * Int32(4) + e0 = Uint32(4294967295) + e1 = Uint32(4294967295) + e2 = Uint32(4294967295) + e3 = Uint32(4294967295) + if base < nout: + e0 = Uint32(Uint64(sHand[base]) >> Uint64(32)) + if base + Int32(1) < nout: + e1 = Uint32(Uint64(sHand[base + Int32(1)]) >> Uint64(32)) + if base + Int32(2) < nout: + e2 = Uint32(Uint64(sHand[base + Int32(2)]) >> Uint64(32)) + if base + Int32(3) < nout: + e3 = Uint32(Uint64(sHand[base + Int32(3)]) >> Uint64(32)) + sx = cute.make_tensor(cute.recast_ptr(sScratch.iterator, dtype=Uint32), cute.make_layout(512)) + kk = Int32(1) + while kk < Int32(10): + jj = kk - Int32(1) + while jj >= Int32(0): + if jj >= Int32(7): + # Transposed exchange gives contiguous words to each warp. + # Scratch is separate from sHand: initial raw loads cannot + # race with the first exchange's stores from another warp. + sx[tid] = e0 + sx[tid + Int32(128)] = e1 + sx[tid + Int32(256)] = e2 + sx[tid + Int32(384)] = e3 + L.bar(bar_id, 128) + peer = tid ^ (Int32(1) << (jj - Int32(2))) + p0 = Uint32(sx[peer]) + p1 = Uint32(sx[peer + Int32(128)]) + p2 = Uint32(sx[peer + Int32(256)]) + p3 = Uint32(sx[peer + Int32(384)]) + L.bar(bar_id, 128) + first = (((base >> jj) ^ (base >> kk)) & Int32(1)) == Int32(0) + e0 = _pick_final32(e0, p0, first) + e1 = _pick_final32(e1, p1, first) + e2 = _pick_final32(e2, p2, first) + e3 = _pick_final32(e3, p3, first) + elif jj >= Int32(2): + delta = Int32(1) << (jj - Int32(2)) + p0 = cute.arch.shuffle_sync_bfly(e0, delta) + p1 = cute.arch.shuffle_sync_bfly(e1, delta) + p2 = cute.arch.shuffle_sync_bfly(e2, delta) + p3 = cute.arch.shuffle_sync_bfly(e3, delta) + first = (((base >> jj) ^ (base >> kk)) & Int32(1)) == Int32(0) + e0 = _pick_final32(e0, p0, first) + e1 = _pick_final32(e1, p1, first) + e2 = _pick_final32(e2, p2, first) + e3 = _pick_final32(e3, p3, first) + elif jj == Int32(1): + first = ((base >> kk) & Int32(1)) == Int32(0) + a0 = e0 + b0 = e2 + a1 = e1 + b1 = e3 + e0 = _pick_final32(a0, b0, first) + e2 = _pick_final32(a0, b0, not first) + e1 = _pick_final32(a1, b1, first) + e3 = _pick_final32(a1, b1, not first) + else: + first0 = ((base >> kk) & Int32(1)) == Int32(0) + first2 = (((base + Int32(2)) >> kk) & Int32(1)) == Int32(0) + a0 = e0 + b0 = e1 + a2 = e2 + b2 = e3 + e0 = _pick_final32(a0, b0, first0) + e1 = _pick_final32(a0, b0, not first0) + e2 = _pick_final32(a2, b2, first2) + e3 = _pick_final32(a2, b2, not first2) + jj = jj - Int32(1) + kk = kk + Int32(1) + # The existing output writer consumes only the inverted token index in + # the low word. No score data is needed after the completed-row sort. + sHand[base] = Uint64(Uint32(4294967295) - e0) + sHand[base + Int32(1)] = Uint64(Uint32(4294967295) - e1) + sHand[base + Int32(2)] = Uint64(Uint32(4294967295) - e2) + sHand[base + Int32(3)] = Uint64(Uint32(4294967295) - e3) + L.bar(bar_id, 128) + + +@cute.jit +def _finalize_seg( + tid, + bar_id: cutlass.Constexpr, + cta, + start_q, + q, + n, + P, + p, + sMb, + cbuf, + rel_ptr, + sHand, + sAttB, + sAttO, + sHistS, + sCkS, + sResS, + sRedS, + sWcS, + s_flag, + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRowStat, + mSched, + ws_seg_base, + ws_ctr_base, + mbs, + mbc, + num_sms: cutlass.Constexpr, + skew_ns: cutlass.Constexpr, + skew_seed, + salt, + stamps: cutlass.Constexpr, + mStamps, + sbase, + dly_t=None, + dly_us: cutlass.Constexpr = 0, + rel_keep=None, + rsort: cutlass.Constexpr = False, + rel_bar=None, + merge1: cutlass.Constexpr = 0, + sBig=None, + sCov=None, + big_cap: cutlass.Constexpr = 0, + sel_fast: cutlass.Constexpr = False, +): + NT: cutlass.Constexpr[int] = SEL_NTHR + if cutlass.const_expr(stamps): + if tid == Int32(0): + mStamps[sbase] = cutlass.Int64(cute.arch.globaltimer()) + fast = Int32(0) + if (n <= Int32(K_TOP)) & (P == Int32(1)): + fast = Int32(1) + nout = Int32(0) + if fast == Int32(0): + nout, kth_, m_, inf_ = L.select_topk_list( + sMb, + cbuf, + Int32(K_TOP), + sHand, + sHistS, + sCkS, + sResS, + sRedS, + sWcS, + tid, + False, + NT, + bar_id, + fast_loops=sel_fast, + ) + # Keep this parity slot until all raw segment unions have been selected. + # The 2048-entry source buffer is also our bounded <=1024-entry merge list. + if cutlass.const_expr(dly_us > 0): + if dly_t >= Int32(0): + if tid == Int32(0): + t_n = Int32(Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(10))) + while t_n - dly_t < Int32(dly_us): + L.nanosleep(Int32(1000)) + t_n = Int32(Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(10))) + L.bar(bar_id, NT) + if cutlass.const_expr(stamps): + if tid == Int32(0): + mStamps[sbase + Int32(1)] = cutlass.Int64(cute.arch.globaltimer()) + if cutlass.const_expr(stamps): + if tid == Int32(0): + mStamps[sbase + Int32(2)] = cutlass.Int64(cute.arch.globaltimer()) + pos = Int32(mKvLens[q]) - Int32(1) + req = Int32(mReq[q]) + short = Int32(0) + if n <= Int32(K_TOP): + short = Int32(1) + done_row = Int32(0) + gv0 = Int32(-1) + gv1 = Int32(-1) + gv2 = Int32(-1) + gv3 = Int32(-1) + gv4 = Int32(-1) + if P == Int32(1): + if short == Int32(0): + _final512_token32(sHand, nout, tid, bar_id) + gv0, gv1, gv2, gv3, gv4 = _write_row_outputs_regs( + q, n, sHand, nout, short, mTopk, mGidx, mBtSwa, mBtC, pos, req, mbs, mbc, tid + ) + done_row = Int32(1) + else: + pside = Int64(1) + if q == start_q: + pside = Int64(0) + so = ws_seg_base + (Int64(cta) * Int64(2) + pside) * Int64(SEGW * 8) + out_i = tid + while out_i < nout: + L.st_g_u64(so + Int64(out_i) * Int64(8), Uint64(sHand[out_i])) + out_i = out_i + Int32(NT) + if tid == Int32(0): + L.st_g_u32(so + Int64(512 * 8), nout) + L.bar(bar_id, NT) + if tid == Int32(0): + if cutlass.const_expr(skew_ns > 0): + L.skew_sleep(skew_seed, salt, Int32(skew_ns)) + ca = ws_ctr_base + Int64(q) * Int64(128) + old = L.gc_arrive(ca) + lst = Int32(0) + if Int32(Uint32(old & Uint64(65535))) == P - Int32(1): + lst = Int32(1) + L.gc_pad(ca, P) + L.fence_acq_rel_gpu() + s_flag[0] = lst + L.bar(bar_id, NT) + if cutlass.const_expr(stamps): + if tid == Int32(0): + mStamps[sbase + Int32(3)] = cutlass.Int64(cute.arch.globaltimer()) + if s_flag[0] != Int32(0): + na = nout + rlane = tid & Int32(31) + nit = (Int32(num_sms) + Int32(31)) // Int32(32) + if cutlass.const_expr(merge1 > 0): + # One-shot merge (last segment of the CTA, K stages idle): the lists of the other + # pieces, merge1 sources in flight at a time, go densely into sBig and one selection + # runs over the union (its top-512 set is unique: entries are totally ordered by key + # and position). More pieces than sBig holds: the serial merge below. + ncov = P - Int32(1) + if P * Int32(K_TOP) <= Int32(big_cap): + i0 = tid + while i0 < na: + sBig[i0] = Uint64(sHand[i0]) + i0 = i0 + Int32(NT) + off = na + j0 = Int32(0) + while j0 < ncov: + es = [] + nbs = [] + for g in cutlass.range_constexpr(merge1): + jj = cutlass.min(j0 + Int32(g), ncov - Int32(1)) + slot = Int32(sCov[jj]) + src = ws_seg_base + Int64(slot) * Int64(SEGW * 8) + nbs.append(L.ld_cg_i32(src + Int64(512 * 8))) + for k in cutlass.range_constexpr(K_TOP // NT): + es.append(L.ld_cg_u64(src + Int64(tid + k * NT) * Int64(8))) + for g in cutlass.range_constexpr(merge1): + nb = cutlass.select_(j0 + Int32(g) < ncov, nbs[g], Int32(0)) + for k in cutlass.range_constexpr(K_TOP // NT): + if tid + Int32(k * NT) < nb: + sBig[off + tid + Int32(k * NT)] = es[g * (K_TOP // NT) + k] + off = off + nb + j0 = j0 + Int32(merge1) + L.bar(bar_id, NT) + nm1, kth_m1, m_m1, inf_m1 = L.select_topk_list( + sBig, + off, + Int32(K_TOP), + sHand, + sHistS, + sCkS, + sResS, + sRedS, + sWcS, + tid, + False, + NT, + bar_id, + fast_loops=sel_fast, + ) + na = nm1 + nit = Int32(0) + it = Int32(0) + while it < nit: + bv = _cover_ballot(q, cta, mSched, Int32(num_sms), rlane, it) + while bv != Int32(0): + low = bv & Int32(0) - bv + cs = it * Int32(32) + Int32(cute.arch.popc(low - Int32(1))) + sside = Int64(1) + if mSched[cs, 0] == q: + sside = Int64(0) + src = ws_seg_base + (Int64(cs) * Int64(2) + sside) * Int64(SEGW * 8) + nb = L.ld_cg_i32(src + Int64(512 * 8)) + ia = tid + while ia < na: + sMb[ia] = Uint64(sHand[ia]) + ia = ia + Int32(NT) + ib = tid + while ib < nb: + sMb[na + ib] = L.ld_cg_u64(src + Int64(ib) * Int64(8)) + ib = ib + Int32(NT) + L.bar(bar_id, NT) + nm, kth_m, m_m, inf_m = L.select_topk_list( + sMb, + na + nb, + Int32(K_TOP), + sHand, + sHistS, + sCkS, + sResS, + sRedS, + sWcS, + tid, + False, + NT, + bar_id, + fast_loops=sel_fast, + ) + na = nm + bv = bv ^ low + it = it + Int32(1) + if cutlass.const_expr(stamps): + if tid == Int32(0): + mStamps[sbase + Int32(4)] = cutlass.Int64(cute.arch.globaltimer()) + if short == Int32(0): + _final512_token32(sHand, na, tid, bar_id) + gv0, gv1, gv2, gv3, gv4 = _write_row_outputs_regs( + q, n, sHand, na, short, mTopk, mGidx, mBtSwa, mBtC, pos, req, mbs, mbc, tid + ) + done_row = Int32(1) + L.bar(bar_id, NT) + if done_row != Int32(0): + if tid == Int32(0): + L.publish_row(mRowStat.iterator.toint(), q) + if cutlass.const_expr(rel_bar is not None): + rk = Int32(0) + if cutlass.const_expr(rel_keep is not None): + rk = rel_keep + if rk == Int32(0): + # Release the parity slot only after every union selection read. + prims.mbarrier_arrive(rel_bar) + return (done_row, gv0, gv1, gv2, gv3, gv4) + + +def _shared_storage(kv_stages: int, q_stages: int, umma_stages: int, fp4: bool): + """The shared-storage struct of the indexer kernel; the FP4 variant adds the SFB write-after-read mbarrier.""" + # real annotation objects: this module postpones annotation evaluation, which cute.struct cannot resolve for + # local names + fields = { + "kv_mbar_0": cute.struct.MemRange[cutlass.Int64, kv_stages * 2], + "kv_mbar_1": cute.struct.MemRange[cutlass.Int64, kv_stages * 2], + "q_mbar": cute.struct.MemRange[cutlass.Int64, q_stages * 2], + "umma_mbar_0": cute.struct.MemRange[cutlass.Int64, umma_stages * 2], + "umma_mbar_1": cute.struct.MemRange[cutlass.Int64, umma_stages * 2], + } + if fp4: + fields["sfb_war_mbar"] = cute.struct.MemRange[cutlass.Int64, 2] + fields["tmem_holding_buf"] = cutlass.Int32 + return cute.struct(type("SharedStorage", (), {"__annotations__": fields})) + + +class IndexerKernel: + def __init__( + self, + num_sms: int = NUM_SMS, + block_kv: int = 128, + phys_block_kv: int = SPEC.index_page_tokens, + num_heads: int = SPEC.index_heads, + head_dim: int = SPEC.index_head_dim, + policy: int = L.POL_NONE, + debug_dump: bool = False, + admit: bool = True, + kv_stages: int = 3, + q_stages: int = 3, + math_regs: int = 136, + sel_regs: int = 88, + row_regs: int = 96, + trig: int = TRIG, + stamps: bool = False, + floor_mask: int = 6, + nolock: bool = False, + lim_loop2: bool = False, + lim_loop: bool = False, + num_w_in_reg: int = 64, + attn: bool = False, + dbg_dup: bool = False, + row_noop: bool = False, + dbg_hand: bool = False, + skew_ns: int = 0, + no_deep: bool = False, + dbg_addr: bool = False, + att_skip: int = 0, + late_release: bool = True, + tmem_fences: bool = False, + keep_cap: int = KEEP_CAP, + desc: bool = False, + rot: bool = False, + sel_fin: bool = False, + gath: bool = False, + cbins: int = 1024, + efl: bool = False, + ahint: int = 0, + etile: bool = False, + spin_ns: int = 0, + pfence: bool = True, + sel_idle_ns: int = 32, + rdelay: int = 0, + apace: int = 0, + ring2: bool = False, + rsort: bool = False, + trig0: int = 0, + kfloor: bool = False, + pace_adapt: bool = True, + defer: bool = True, + dq_cap: int = DQ_CAP, + validate: bool = True, + tiebin: bool = True, + merge1: int = 0, + fast_verdict: bool = False, + sel_fast: bool = False, + cmp_fast: bool = False, + sel_hand2: bool = False, + config: SpecDsaConfig | None = None, + ): + # merge1 = G > 0: the last piece of a split row merges the other pieces in one selection, G + # sources gathered at a time (see _finalize_seg); fast_verdict: the schedule verdict issues + # its global loads before the first branch + self.merge1 = int(merge1) + if not 0 <= self.merge1 <= 8: + raise ValueError("merge1") + self.fast_verdict = bool(fast_verdict) + self.sel_fast = bool(sel_fast) + self.cmp_fast = bool(cmp_fast) + # sel_hand2: the selector warps finalize the last segment into their own 512-entry result list and do not + # wait for the row warps to finish the segment before it (a two-segment CTA made the call 5 - 12 us slower at + # 40 - 92 rows) + self.sel_hand2 = bool(sel_hand2) + self.fp4 = config is not None and config.index_k_dtype == "fp4" + require_built_for(config, SPEC_FP4 if self.fp4 else SPEC) + self.block_kv = block_kv + self.phys_block_kv = phys_block_kv + self.num_blocks_per_mma = block_kv // phys_block_kv + self.num_heads = num_heads + self.head_dim = head_dim + self.next_n_atom = 1 + self.N = num_heads + self.num_sms = num_sms + self.epi_dtype = cutlass.Float32 + self.acc_dtype = cutlass.Float32 + self.output_dtype = cutlass.Float32 + self.epi_bytes = 4 + w_stage_bytes = self.N * self.epi_bytes + self.w_stage_stride = (w_stage_bytes + 127) // 128 * 128 // self.epi_bytes + self.num_math_threads = 256 + self.num_math_warps = 8 + self.threads_per_cta = 640 + self.num_q_stages = q_stages + self.num_umma_stages = 2 + self.num_kv_stages = kv_stages + self.cta_group = tcgen05.CtaGroup.ONE + self.cluster_shape_mn = (1, 1) + self.mma_tiler_mn = (block_kv, self.N) + if policy not in L.POL_NAMES: + raise ValueError(f"unknown cache policy {policy}") + self.policy = policy + self.debug_dump = bool(debug_dump) + self.admit = bool(admit) + if attn and q_stages < 3: + raise ValueError( + "the deep attention ring keeps Q slices 0-2 in the 3 indexer Q stages (q_stages >= 3)" + ) + if ( + math_regs * 256 + (24 + sel_regs + row_regs) * 128 > 96 * 640 + or (math_regs | sel_regs | row_regs) % 8 + ): + raise ValueError("register budget (CTA pool 61,440)") + self.math_regs = math_regs + self.sel_regs = sel_regs + self.row_regs = row_regs + if not K_TOP < trig <= MAIN_CAP - 512: + raise ValueError("trig must be in (512, MAIN_CAP - 512]") + self.trig = trig + self.stamps = bool(stamps) + self.floor_mask = int(floor_mask) + self.nolock = bool(nolock) + self.lim_loop2 = bool(lim_loop2) + # lim_loop: the math warps' tile loop ends on kv_idx < kv_lim (limit computed once per segment) + self.lim_loop = bool(lim_loop) + if num_heads != 64 or num_w_in_reg != num_heads: + raise ValueError("split epilogue requires 64 heads and all head weights in registers") + self.num_w_in_reg = num_w_in_reg + self.attn = bool(attn) + self.dbg_dup = bool(dbg_dup) + self.row_noop = bool(row_noop) + self.dbg_hand = bool(dbg_hand) + self.skew_ns = int(skew_ns) + self.no_deep = bool(no_deep) + self.dbg_addr = bool(dbg_addr) + self.att_skip = int(att_skip) + self.late_release = bool(late_release) + self.keep_cap = int(keep_cap) + self.tmem_fences = bool(tmem_fences) + self.desc = bool(desc) + self.rot = bool(rot) + self.sel_fin = bool(sel_fin) + self.gath = bool(gath) and self.sel_fin and self.attn and (int(att_skip) == 0) + if cbins not in (128, 256, 512, 1024): + raise ValueError("cbins") + self.cbins = int(cbins) + self.etile = bool(etile) and self.gath + self.pfence = bool(pfence) + self.sel_idle_ns = int(sel_idle_ns) + self.spin_ns = int(spin_ns) + self.rdelay = int(rdelay) + self.apace = int(apace) + self.ahint = int(ahint) + self.efl = bool(efl) + self.ring2 = bool(ring2) and self.attn + self.rsort = bool(rsort) + if trig0 and trig0 <= K_TOP: + raise ValueError("trig0 must be > 512") + self.trig0 = min(int(trig0), int(trig)) if trig0 else 0 + self.kfloor = bool(kfloor) + self.pace_adapt = bool(pace_adapt) + if defer and (etile or ring2 or rdelay): + raise ValueError( + "defer is built for the shipped tail (gath without etile / ring2 / rdelay)" + ) + self.defer = bool(defer) and self.attn + if not 1 <= int(dq_cap) <= 1024: + raise ValueError("dq_cap") + self.dq_cap = int(dq_cap) + self.validate = bool(validate) + self.tiebin = bool(tiebin) + if self.fp4: + # MXFP4 block-scaled MMA (E2M1 data, a UE8M0 scale per 32 elements): the SF TMEM regions are not + # staged, so there is one accumulator stage + self.num_umma_stages = 1 + self.num_groups = 2 + self.sf_dtype = Float8E8M0FNU + self.sf_vec_size = 32 + self.umma_inst_k = 64 + # entries of the idle K-stage smem of the first group (merge1 gathers the pieces' lists) + self.merge_cap = ( + self.num_kv_stages * self.block_kv * self.head_dim * (4 if self.fp4 else 8) // 64 + ) + + def _epi_half(self, tTR_rAcc, w_cache, head_start, s0x, s0y, s1x, s1y): + # The same four FMA chains continue across the two 32-head TMEM loads. + acc_vec = tTR_rAcc.load() + for h in range(0, 32, 4): + x0 = acc_vec[h] + x1 = acc_vec[h + 1] + x2 = acc_vec[h + 2] + x3 = acc_vec[h + 3] + a0, a1 = cute.arch.add_packed_f32x2((x0, x1), (abs(x0), abs(x1)), rnd=_RND_RN) + a2, a3 = cute.arch.add_packed_f32x2((x2, x3), (abs(x2), abs(x3)), rnd=_RND_RN) + w0 = w_cache[head_start + h] + w1 = w_cache[head_start + h + 1] + w2 = w_cache[head_start + h + 2] + w3 = w_cache[head_start + h + 3] + s0x, s0y = cute.arch.fma_packed_f32x2((a0, a1), (w0, w1), (s0x, s0y), rnd=_RND_RN) + s1x, s1y = cute.arch.fma_packed_f32x2((a2, a3), (w2, w3), (s1x, s1y), rnd=_RND_RN) + return (s0x, s0y, s1x, s1y) + + @cute.jit + def _nseg(self, start_q, start_kv_half, end_q_idx, end_kv_half): + qb = end_q_idx + if end_kv_half == Int32(0): + qb = end_q_idx - Int32(1) + ns = qb - start_q + Int32(1) + if (start_q == end_q_idx) & (start_kv_half == end_kv_half): + ns = Int32(0) + return ns + + @cute.jit + def _tiles(self, q, mContextLens, batch_size): + return ( + self._ctx_of(cutlass.min(q, batch_size - 1), mContextLens, batch_size) + + Int32(self.block_kv - 1) + ) // Int32(self.block_kv) + + @cute.jit + def _walk_init(self, start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size): + end_kv_idx = end_kv_half * Int32(2) + nq = start_q + nk = start_kv_half * Int32(2) + ph = Int32(2) + stop_kv = end_kv_idx + rot_on = Int32(0) + if cutlass.const_expr(self.rot): + if (end_kv_half > Int32(0)) & (end_q_idx > start_q): + rot_on = Int32(1) + nq = end_q_idx + nk = Int32(0) + ph = Int32(1) + stop_kv = Int32(0) + nn = self._tiles(nq, mContextLens, batch_size) + hw = (ph == Int32(1)) | ((nq != end_q_idx) | (nk != stop_kv)) + return (nq, nk, nn, ph, stop_kv, hw, rot_on) + + @cute.jit + def _walk_next( + self, + q, + nk, + num_kv, + nn, + ph, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + seg_end: cutlass.Constexpr = False, + ): + nq = q + nk2 = nk + nn2 = nn + ph2 = ph + if ph == Int32(1): + if nk >= end_kv_idx: + nq = start_q + nk2 = start_kv_half * Int32(2) + ph2 = Int32(2) + nn2 = self._tiles(start_q, mContextLens, batch_size) + elif nk >= num_kv: + nq = q + Int32(1) + nk2 = Int32(0) + if nq < batch_size: + nn2 = self._tiles(nq, mContextLens, batch_size) + hw = (ph2 == Int32(1)) | ((nq != end_q_idx) | (nk2 != stop_kv)) + return (nq, nk2, nn2, ph2, hw) + + @cute.jit + def _walk_qnext(self, q, ph, rot_on, start_q, end_q_idx, end_kv_idx): + pq = q + Int32(1) + ok = Int32(0) + if ph == Int32(1): + pq = start_q + ok = Int32(1) + elif pq < end_q_idx: + ok = Int32(1) + elif pq == end_q_idx: + if end_kv_idx > Int32(0): + if rot_on == Int32(0): + ok = Int32(1) + return (pq, ok) + + @cute.jit + def _kv_limit(self, kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx): + # the loop bound of a segment (see _seg_s): the row length rounded up to an even tile, or the end tile of the + # CTA in its last row, at least one pair beyond the first tile + b2 = num_kv + Int32(1) & Int32(-2) + if q_idx == end_q_idx: + b2 = end_kv_idx + if b2 < kv_idx + Int32(2): + b2 = kv_idx + Int32(2) + return b2 + + @cute.jit + def _seg_s(self, kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx): + b2 = num_kv + Int32(1) & Int32(-2) + if q_idx == end_q_idx: + b2 = end_kv_idx + if b2 < kv_idx + Int32(2): + b2 = kv_idx + Int32(2) + return kv_idx + b2 - Int32(2) + + @cute.jit + def _sched_verdict(self, mSched, mContextLens, batch_size, lane): + G = self.num_sms + bad = Int32(0) + for it in cutlass.range_constexpr((G + 1 + 31) // 32): + s = lane + Int32(it * 32) + if s <= Int32(G): + q = mSched[s, 0] + k = mSched[s, 1] + if (q < Int32(0)) | (q > batch_size) | (k < Int32(0)): + bad = Int32(1) + elif q == batch_size: + if k != Int32(0): + bad = Int32(1) + else: + u = (mContextLens[q] + Int32(255)) // Int32(256) + if (k > Int32(0)) & (k >= u): + bad = Int32(1) + if s < Int32(G): + q1 = mSched[s + Int32(1), 0] + k1 = mSched[s + Int32(1), 1] + if (q1 < q) | (q1 == q) & (k1 < k): + bad = Int32(1) + elif q != batch_size: + bad = Int32(1) + q0 = cutlass.min(cutlass.max(mSched[0, 0], Int32(0)), batch_size) + r = lane + while r < q0: + if mContextLens[r] != Int32(0): + bad = Int32(1) + r = r + Int32(32) + if mSched[0, 1] != Int32(0): + bad = Int32(1) + v = Int32(0) + if Int32(cute.arch.vote_ballot_sync(bad != Int32(0))) != Int32(0): + v = Int32(ST_SCHED) + return v + + @cute.jit + def _sched_verdict_fast(self, mSched, mContextLens, batch_size, lane): + # The verdict of _sched_verdict with every global load issued before the first branch. + G = self.num_sms + n_it = (G + 1 + 31) // 32 + qs = [] + ks = [] + q1s = [] + k1s = [] + for it in cutlass.range_constexpr(n_it): + s = lane + Int32(it * 32) + sc = cutlass.min(s, Int32(G)) + s1 = cutlass.min(s + Int32(1), Int32(G)) + qs.append(mSched[sc, 0]) + ks.append(mSched[sc, 1]) + q1s.append(mSched[s1, 0]) + k1s.append(mSched[s1, 1]) + us = [] + for it in cutlass.range_constexpr(n_it): + qc = cutlass.min(cutlass.max(qs[it], Int32(0)), batch_size - Int32(1)) + us.append((mContextLens[qc] + Int32(255)) // Int32(256)) + q00 = mSched[0, 0] + k00 = mSched[0, 1] + bad = Int32(0) + for it in cutlass.range_constexpr(n_it): + s = lane + Int32(it * 32) + q = qs[it] + k = ks[it] + q1 = q1s[it] + k1 = k1s[it] + b1 = (q < Int32(0)) | (q > batch_size) | (k < Int32(0)) + b2 = (q == batch_size) & (k != Int32(0)) + b3 = (q >= Int32(0)) & (q < batch_size) & (k > Int32(0)) & (k >= us[it]) + b4 = (s < Int32(G)) & ((q1 < q) | ((q1 == q) & (k1 < k))) + b5 = (s == Int32(G)) & (q != batch_size) + bad = cutlass.select_((s <= Int32(G)) & (b1 | b2 | b3 | b4 | b5), Int32(1), bad) + q0 = cutlass.min(cutlass.max(q00, Int32(0)), batch_size) + r = lane + while r < q0: + if mContextLens[r] != Int32(0): + bad = Int32(1) + r = r + Int32(32) + if k00 != Int32(0): + bad = Int32(1) + v = Int32(0) + if Int32(cute.arch.vote_ballot_sync(bad != Int32(0))) != Int32(0): + v = Int32(ST_SCHED) + return v + + @cute.jit + def _ctx_of(self, q, mContextLens, batch_size): + ctx = cutlass.Int32(0) + if q < batch_size: + ctx = mContextLens[q] + return ctx + + def _setup_mma(self, a_dtype, b_dtype, a_major, b_major): + if self.fp4: + return self._setup_mma_fp4(a_dtype, b_dtype, a_major, b_major) + self.a_dtype = a_dtype + self.b_dtype = b_dtype + self.mma_tiler = (*self.mma_tiler_mn, 1) + tiled_mma = sm100_utils.make_trivial_tiled_mma( + a_dtype, b_dtype, a_major, b_major, self.acc_dtype, self.cta_group, self.mma_tiler_mn + ) + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + mma_inst_tile_k = self.head_dim // mma_inst_shape_k + full_k = mma_inst_shape_k * mma_inst_tile_k + self.mma_tiler = (self.mma_tiler_mn[0], self.mma_tiler_mn[1], full_k) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), (tiled_mma.thr_id.shape,) + ) + self.epi_tile = self.cta_tile_shape_mnk[:2] + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, self.mma_tiler, a_dtype, self.num_kv_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, self.mma_tiler, b_dtype, self.num_q_stages + ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + self.num_tmem_alloc_cols = cutlass.utils.get_num_tmem_alloc_cols(tCtAcc_fake) + self.num_tmem_alloc_cols_total = self.num_tmem_alloc_cols * 2 * self.num_umma_stages + return tiled_mma + + def _setup_mma_fp4(self, a_dtype, b_dtype, a_major, b_major): + """The block-scaled MXF4 MMA (K 64 per instruction, two per head dim) and its scale-factor layouts.""" + self.a_dtype = a_dtype + self.b_dtype = b_dtype + self.mma_tiler = (*self.mma_tiler_mn, 1) + tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + a_dtype, + b_dtype, + a_major, + b_major, + self.sf_dtype, + self.sf_vec_size, + self.cta_group, + self.mma_tiler_mn, + ) + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + mma_inst_tile_k = self.head_dim // mma_inst_shape_k + full_k = mma_inst_shape_k * mma_inst_tile_k + self.mma_tiler = (self.mma_tiler_mn[0], self.mma_tiler_mn[1], full_k) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), (tiled_mma.thr_id.shape,) + ) + self.epi_tile = self.cta_tile_shape_mnk[:2] + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, self.mma_tiler, a_dtype, self.num_kv_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, self.mma_tiler, b_dtype, self.num_q_stages + ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + self.num_tmem_alloc_cols = find_tmem_tensor_col_offset(tCtAcc_fake) + sfa_smem = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + sfb_smem = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + tmem_sfa = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfa_smem, (None, None, None, 0)), + ) + tmem_sfb = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfb_smem, (None, None, None, 0)), + ) + # a degenerate stage mode keeps the rank-4 slices of the MMA loop valid on both DSL versions + self.tmem_sfa_layout = cute.append(tmem_sfa, cute.make_layout(1, stride=0)) + self.tmem_sfb_layout = cute.append(tmem_sfb, cute.make_layout(1, stride=0)) + sf_k_modes = cute.size(tmem_sfa, mode=[2]) + sf_tile_k = self.head_dim // self.umma_inst_k + assert sf_k_modes % sf_tile_k == 0 + self.sf_k_step = sf_k_modes // sf_tile_k + self.N_padded = ((self.N + 127) // 128) * 128 + self.num_sfa_tmem_cols = (self.cta_tile_shape_mnk[0] // 32) * sf_tile_k + self.num_sfb_tmem_cols = (self.N_padded // 32) * sf_tile_k + raw_cols = ( + self.num_tmem_alloc_cols * self.num_groups * self.num_umma_stages + + self.num_sfa_tmem_cols * self.num_groups + + self.num_sfb_tmem_cols + ) + self.num_tmem_alloc_cols_total = max(1 << math.ceil(math.log2(raw_cols)), 32) + assert self.num_tmem_alloc_cols_total <= 512, "FP4 TMEM columns exceed the 512 of SM100" + self.sfa_chunk_smem_layout = sfa_smem + self.sfb_chunk_smem_layout = sfb_smem + self.copy_atom_s2t = cute.make_copy_atom( + tcgen05.Cp4x32x128bOp(self.cta_group), self.sf_dtype + ) + return tiled_mma + + def _fp4_views(self, kv_fused, b, num_phys_blocks): + """FP4 views of a K page pool [pages, 32 * 68 bytes] and of the queries. + + A page: the E2M1 data of 32 positions, then 32 int32 of four UE8M0 scales each. + """ + phys_block_kv = self.phys_block_kv + kv_fp4 = cute.recast_tensor(kv_fused, Float4E2M1FN) + b = cute.recast_tensor(b, Float4E2M1FN) + block_stride_bytes = kv_fused.layout.stride[0] + a = cute.make_tensor( + kv_fp4.iterator, + cute.make_layout( + (phys_block_kv, self.head_dim, num_phys_blocks), + stride=(self.head_dim, 1, block_stride_bytes * 2), + ), + ) + sf_bytes = cute.make_tensor( + kv_fused.iterator + phys_block_kv * (self.head_dim // 2), + cute.make_layout((phys_block_kv * 4, num_phys_blocks), stride=(1, block_stride_bytes)), + ) + return a, b, cute.recast_tensor(sf_bytes, cutlass.Int32) + + def _fp4_sf_q_atom(self, sf_q, tma_load_op): + """TMA atom of the query scales [64, B] int32 (the SMEM stage is padded to the 128-token UTCCP atom).""" + stage_stride = (self.N_padded * 4 + 127) // 128 * 128 // 4 + self.sf_q_smem_layout_staged = cute.make_layout( + (self.N_padded, self.num_q_stages), stride=(1, stage_stride) + ) + self.sf_q_tma_smem_layout_staged = cute.make_layout( + (self.N, self.num_q_stages), stride=(1, stage_stride) + ) + return cpasync.make_tiled_tma_atom( + tma_load_op, + sf_q, + cute.select(self.sf_q_tma_smem_layout_staged, mode=[0]), + (self.N,), + ) + + @cute.jit + def __call__( + self, + kv_fused: cute.Tensor, + b: cute.Tensor, + weights: cute.Tensor, + logits: cute.Tensor, + block_table: cute.Tensor, + context_lens: cute.Tensor, + schedule_meta: cute.Tensor, + kv_lens: cute.Tensor, + req_id: cute.Tensor, + bt_swa: cute.Tensor, + bt_c: cute.Tensor, + topk_out: cute.Tensor, + gidx: cute.Tensor, + ws_seg: cute.Tensor, + ws_ctr: cute.Tensor, + rowstat: cute.Tensor, + stamps: cute.Tensor, + q_att: cute.Tensor, + swa_pool: cute.Tensor, + c_pool: cute.Tensor, + sinks: cute.Tensor, + out: cute.Tensor, + status: cute.Tensor, + softmax_scale: cutlass.Float32, + num_phys_blocks: cutlass.Int32, + batch_size: cutlass.Int32, + stream: cuda.CUstream, + sf_q: cute.Tensor = None, + ): + phys_block_kv = self.phys_block_kv + scale_offset_elems = phys_block_kv * self.head_dim + if cutlass.const_expr(self.fp4): + a, b, scales = self._fp4_views(kv_fused, b, num_phys_blocks) + else: + kv_fp8 = cute.recast_tensor(kv_fused, cutlass.Float8E4M3FN) + b = cute.recast_tensor(b, cutlass.Float8E4M3FN) + kv_block_stride = kv_fused.layout.stride[0] + kv_layout = cute.make_layout( + (phys_block_kv, self.head_dim, num_phys_blocks), + stride=(self.head_dim, 1, kv_block_stride), + ) + a = cute.make_tensor(kv_fp8.iterator, kv_layout) + scale_fp8_layout = cute.make_layout( + (phys_block_kv * 4, num_phys_blocks), stride=(1, kv_block_stride) + ) + scale_fp8 = cute.make_tensor(kv_fp8.iterator + scale_offset_elems, scale_fp8_layout) + scales = cute.recast_tensor(scale_fp8, cutlass.Float32) + a_dtype = a.element_type + b_dtype = b.element_type + a_major = cutlass.utils.LayoutEnum.from_tensor(a).mma_major_mode() + b_major = cutlass.utils.LayoutEnum.ROW_MAJOR.mma_major_mode() + tiled_mma = self._setup_mma(a_dtype, b_dtype, a_major, b_major) + atom_thr_size = cute.size(tiled_mma.thr_id.shape) + tma_load_op = cpasync.CopyBulkTensorTileG2SOp() + self.a_tma_view_layout = sm100_utils.make_smem_layout( + cute.nvgpu.OperandMajorMode.K, + (self.block_kv, self.head_dim), + a_dtype, + self.num_kv_stages, + ) + self.a_tma_view_layout = cute.tiled_divide( + self.a_tma_view_layout, (self.phys_block_kv, self.head_dim) + ) + self.a_tma_view_layout = cute.select(self.a_tma_view_layout, mode=[0, 1, 3]) + tma_atom_a, tma_tensor_a = cpasync.make_tiled_tma_atom( + tma_load_op, a, self.a_tma_view_layout[0], (self.phys_block_kv, self.head_dim) + ) + b_op = sm100_utils.cluster_shape_to_tma_atom_B(self.cluster_shape_mn, tiled_mma.thr_id) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, b, b_smem_layout, self.mma_tiler, tiled_mma, self.cluster_layout_vmnk.shape + ) + self.w_smem_layout_staged = cute.make_layout( + (self.N, self.num_q_stages), stride=(1, self.w_stage_stride) + ) + w_smem_per_stage = cute.select(self.w_smem_layout_staged, mode=[0]) + tma_atom_w, tma_tensor_w = cpasync.make_tiled_tma_atom( + tma_load_op, weights, w_smem_per_stage, self.w_smem_layout_staged.shape[:1] + ) + self.s_smem_layout_staged = cute.make_layout((self.block_kv, self.num_kv_stages)) + s_smem_per_subblock = cute.make_layout((phys_block_kv,)) + tma_atom_s, tma_tensor_s = cpasync.make_tiled_tma_atom( + tma_load_op, scales, s_smem_per_subblock, (phys_block_kv,) + ) + b_copy_size = cute.size_in_bytes(b_dtype, b_smem_layout) + w_copy_size = self.N * self.epi_bytes + kv_tma_bytes_per_subblock = phys_block_kv * self.head_dim // (2 if self.fp4 else 1) + scale_tma_bytes_per_subblock = phys_block_kv * 4 + self.num_kv_scale_tma_bytes = self.num_blocks_per_mma * ( + kv_tma_bytes_per_subblock + scale_tma_bytes_per_subblock + ) + self.num_q_tma_bytes = b_copy_size * atom_thr_size + w_copy_size + tma_atom_sf_q = None + tma_tensor_sf_q = None + sf_q_smem_layout_staged = None + sf_q_tma_smem_layout_staged = None + tmem_sfa_layout = None + tmem_sfb_layout = None + sfa_chunk_smem_layout = None + sfb_chunk_smem_layout = None + copy_atom_s2t = None + if cutlass.const_expr(self.fp4): + tma_atom_sf_q, tma_tensor_sf_q = self._fp4_sf_q_atom(sf_q, tma_load_op) + self.num_q_tma_bytes = self.num_q_tma_bytes + self.N * 4 + sf_q_smem_layout_staged = self.sf_q_smem_layout_staged + sf_q_tma_smem_layout_staged = self.sf_q_tma_smem_layout_staged + tmem_sfa_layout = self.tmem_sfa_layout + tmem_sfb_layout = self.tmem_sfb_layout + sfa_chunk_smem_layout = self.sfa_chunk_smem_layout + sfb_chunk_smem_layout = self.sfb_chunk_smem_layout + copy_atom_s2t = self.copy_atom_s2t + + SharedStorage = _shared_storage( + self.num_kv_stages, self.num_q_stages, self.num_umma_stages, self.fp4 + ) + + tma_q = xcuda.create_tensor_map_tiled( + global_address=q_att.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, HEADS, q_att.shape[0]], + global_strides=[LATENT // 16, HEADS * LATENT // 16], + box_dims=[SLICE, HEADS, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_swa = xcuda.create_tensor_map_tiled( + global_address=swa_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, swa_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_cmp = xcuda.create_tensor_map_tiled( + global_address=c_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, c_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_w, + tma_tensor_w, + tma_atom_s, + tma_tensor_s, + tma_q, + tma_swa, + tma_cmp, + sinks, + out, + status, + softmax_scale, + logits, + block_table, + context_lens, + schedule_meta, + kv_lens, + req_id, + bt_swa, + bt_c, + topk_out, + gidx, + ws_seg, + ws_ctr, + rowstat, + stamps, + batch_size, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.w_smem_layout_staged, + self.s_smem_layout_staged, + self.a_tma_view_layout, + self.epi_tile, + SharedStorage, + tma_atom_sf_q, + tma_tensor_sf_q, + sf_q_smem_layout_staged, + sf_q_tma_smem_layout_staged, + tmem_sfa_layout, + tmem_sfb_layout, + sfa_chunk_smem_layout, + sfb_chunk_smem_layout, + copy_atom_s2t, + ).launch( + grid=(1, 1, self.num_sms), + block=[self.threads_per_cta, 1, 1], + cluster=(*self.cluster_shape_mn, 1), + stream=stream, + min_blocks_per_mp=1, + ) + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_w: cute.CopyAtom, + mW_tma: cute.Tensor, + tma_atom_s: cute.CopyAtom, + mS_tma: cute.Tensor, + tma_q: cutlass.GridConstant[xcuda.TensorMap], + tma_swa: cutlass.GridConstant[xcuda.TensorMap], + tma_cmp: cutlass.GridConstant[xcuda.TensorMap], + mSinks: cute.Tensor, + mOut: cute.Tensor, + mStatus: cute.Tensor, + softmax_scale: cutlass.Float32, + mLogits: cute.Tensor, + mBlockTable: cute.Tensor, + mContextLens: cute.Tensor, + mScheduleMeta: cute.Tensor, + mKvLens: cute.Tensor, + mReq: cute.Tensor, + mBtSwa: cute.Tensor, + mBtC: cute.Tensor, + mTopk: cute.Tensor, + mGidx: cute.Tensor, + mWsSeg: cute.Tensor, + mWsCtr: cute.Tensor, + mRowStat: cute.Tensor, + mStamps: cute.Tensor, + batch_size: cutlass.Int32, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + w_smem_layout_staged: cute.Layout, + s_smem_layout_staged: cute.Layout, + a_tma_view_layout: cute.ComposedLayout, + epi_tile: cute.Tile, + SharedStorage: cutlass.Constexpr, + tma_atom_sf_q: cute.CopyAtom = None, + mSF_Q_tma: cute.Tensor = None, + sf_q_smem_layout_staged: cute.Layout = None, + sf_q_tma_smem_layout_staged: cute.Layout = None, + tmem_sfa_layout: cute.Layout = None, + tmem_sfb_layout: cute.Layout = None, + sfa_chunk_smem_layout: cute.Layout = None, + sfb_chunk_smem_layout: cute.Layout = None, + copy_atom_s2t: cute.CopyAtom = None, + ): + # Let the attention grid start on the SMs this grid leaves free; it consumes rows as they are published. + cute.arch.griddepcontrol_launch_dependents() + warp_idx = cute.arch.warp_idx() + warp_idx = cute.arch.make_warp_uniform(warp_idx) + use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2 + bidx, bidy, bidz = cute.arch.block_idx() + mma_tile_coord_v = bidx % cute.size(tiled_mma.thr_id.shape) + is_leader_cta = mma_tile_coord_v == 0 + cta_rank_in_cluster = cute.arch.make_warp_uniform(cute.arch.block_idx_in_cluster()) + block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord(cta_rank_in_cluster) + tidx, _, _ = cute.arch.thread_idx() + warpgroup_idx = warp_idx // 4 + is_math_warp = warp_idx < 8 + is_tma_warp_0 = warp_idx == 8 + is_tma_warp_1 = warp_idx == 9 + is_tma_warp = is_tma_warp_0 | is_tma_warp_1 + is_umma_warp_0 = warp_idx == 10 + is_umma_warp_1 = warp_idx == 11 + is_sel_warp = (warp_idx >= 12) & (warp_idx < 16) + is_row_warp = warp_idx >= 16 + if cutlass.const_expr(self.stamps): + if tidx == 0: + mStamps[bidz * 256 + 0] = cutlass.Int64(cute.arch.globaltimer()) + mStamps[bidz * 256 + 15] = cutlass.Int64(cute.arch.smid()) + mStamps[bidz * 256 + 13] = L.clk64() + NUM_MATH_WG = 2 + NUM_BLOCKS_PER_MMA = self.num_blocks_per_mma + sm_idx = bidz + start_q = mScheduleMeta[sm_idx, 0] + start_kv_half = mScheduleMeta[sm_idx, 1] + end_q_idx = mScheduleMeta[sm_idx + 1, 0] + end_kv_half = mScheduleMeta[sm_idx + 1, 1] + refused = Int32(0) + if cutlass.const_expr(self.validate): + if cutlass.const_expr(self.fast_verdict): + refused = self._sched_verdict_fast( + mScheduleMeta, mContextLens, batch_size, tidx % 32 + ) + else: + refused = self._sched_verdict(mScheduleMeta, mContextLens, batch_size, tidx % 32) + if refused != Int32(0): + start_q = batch_size + start_kv_half = Int32(0) + end_q_idx = batch_size + end_kv_half = Int32(0) + if is_tma_warp: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_w) + cpasync.prefetch_descriptor(tma_atom_s) + if cutlass.const_expr(self.fp4): + cpasync.prefetch_descriptor(tma_atom_sf_q) + smem = cutlass.utils.SmemAllocator() + storage = smem.allocate(SharedStorage) + block_kv_val = self.block_kv + prod_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + q_cons_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 8) + q_pipeline = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.q_mbar.data_ptr(), + num_stages=self.num_q_stages, + producer_group=prod_group, + consumer_group=q_cons_group, + tx_count=self.num_q_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + q_prod_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_q_stages + ) + q_cons_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_q_stages + ) + q_cons_state_umma_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_q_stages + ) + q_cons_state_umma_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_q_stages + ) + math_warps_per_group = self.num_math_warps // 2 + if cutlass.const_expr(self.fp4): + # The tensor core consumes the K tile and its scale factors: the UMMA warp releases the stage + # (tcgen05.commit). + kv_cons_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1) + kv_pipeline_0 = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.kv_mbar_0.data_ptr(), + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + kv_pipeline_1 = pipeline.PipelineTmaUmma.create( + barrier_storage=storage.kv_mbar_1.data_ptr(), + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + else: + kv_cons_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, math_warps_per_group) + kv_pipeline_0 = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.kv_mbar_0.data_ptr(), + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + kv_pipeline_1 = pipeline.PipelineTmaAsync.create( + barrier_storage=storage.kv_mbar_1.data_ptr(), + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + kv_prod_state_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_kv_stages + ) + kv_prod_state_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_kv_stages + ) + kv_cons_state_umma_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_umma_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_math_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_math_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + math_threads_per_group = self.num_math_threads // 2 + umma_pipeline_0 = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.umma_mbar_0.data_ptr(), + num_stages=self.num_umma_stages, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, math_threads_per_group), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + umma_pipeline_1 = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.umma_mbar_1.data_ptr(), + num_stages=self.num_umma_stages, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, math_threads_per_group), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + umma_prod_state_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_umma_stages + ) + umma_prod_state_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_umma_stages + ) + umma_cons_state_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_umma_stages + ) + umma_cons_state_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_umma_stages + ) + if cutlass.const_expr(self.fp4): + # At a q transition UMMA warp 0 overwrites the SFB TMEM region that both UMMA warps' previous MMAs + # read; each warp's tcgen05.commit lands on this mbarrier and warp 0 waits for both before the copy. + # The named barrier locksteps the two warps. + sfb_war_pipeline = pipeline.PipelineUmmaAsync.create( + barrier_storage=storage.sfb_war_mbar.data_ptr(), + num_stages=1, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 2), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 1), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + sfb_war_prod_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, 1) + sfb_war_cons_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, 1) + sfb_sync_barrier = pipeline.NamedBarrier(barrier_id=6, num_threads=64) + tmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=640) + tmem = cutlass.utils.TmemAllocator( + storage.tmem_holding_buf.ptr, + barrier_for_retrieve=tmem_alloc_barrier, + allocator_warp_id=0, + is_two_cta=False, + ) + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + sKV_0 = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=a_smem_layout_staged.inner, + ) + sKV_1 = smem.allocate_tensor( + element_type=self.a_dtype, + layout=a_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=a_smem_layout_staged.inner, + ) + sQ = smem.allocate_tensor( + element_type=self.b_dtype, + layout=b_smem_layout_staged.outer, + byte_alignment=1024, + swizzle=b_smem_layout_staged.inner, + ) + sW = smem.allocate_tensor( + element_type=self.epi_dtype, layout=w_smem_layout_staged, byte_alignment=128 + ) + scale_dtype = cutlass.Int32 if self.fp4 else cutlass.Float32 + sScales_0 = smem.allocate_tensor( + element_type=scale_dtype, layout=s_smem_layout_staged, byte_alignment=128 + ) + sScales_1 = smem.allocate_tensor( + element_type=scale_dtype, layout=s_smem_layout_staged, byte_alignment=128 + ) + if cutlass.const_expr(self.fp4): + sSF_Q = smem.allocate_tensor( + element_type=cutlass.Int32, + layout=sf_q_smem_layout_staged, + byte_alignment=128, + ) + s_ring = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(RING * 8), byte_alignment=1024 + ) + sMain = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(2 * MAIN_CAP), byte_alignment=1024 + ) + sOut = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sHand = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sHand2 = sHand + if cutlass.const_expr(self.sel_hand2): # the selector warps' own result list (4 KB) + sHand2 = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sHB = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sHist = cute.make_tensor( + cute.recast_ptr(sHB.iterator, dtype=Int32), cute.make_layout(L.NB_SEL) + ) + sAttB = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sAttO = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(K_TOP), byte_alignment=128 + ) + sHI = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(16), byte_alignment=16 + ) + # In the split path these arguments are unused: no attention role runs. + # Alias existing storage instead of reserving the 24 KiB shallow ring. + if cutlass.const_expr(self.attn): + sQatt = smem.allocate_tensor( + element_type=cutlass.Float8E4M3FN, + layout=cute.make_layout(Q_SLICE_BYTES), + byte_alignment=1024, + ) + sKVatt = smem.allocate_tensor( + element_type=cutlass.Float8E4M3FN, + layout=cute.make_layout(SLOT_BYTES), + byte_alignment=1024, + ) + else: + sQatt = cute.make_tensor( + cute.recast_ptr(sQ.iterator, dtype=cutlass.Float8E4M3FN), + cute.make_layout(Q_SLICE_BYTES), + ) + sKVatt = cute.make_tensor( + cute.recast_ptr(sKV_0.iterator, dtype=cutlass.Float8E4M3FN), + cute.make_layout(SLOT_BYTES), + ) + sAbar = smem.allocate_tensor( + element_type=Int64, layout=cute.make_layout(16), byte_alignment=16 + ) + sMsk = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=16 + ) + sRS = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(16), byte_alignment=16 + ) + smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(ATTQ + 4), byte_alignment=16 + ) + sKr = smem.allocate_tensor( + element_type=Uint32, layout=cute.make_layout(4), byte_alignment=16 + ) + sTb = smem.allocate_tensor( + element_type=Uint32, layout=cute.make_layout(8), byte_alignment=16 + ) + sCk = smem.allocate_tensor( + element_type=Uint64, layout=cute.make_layout(L.QUADC), byte_alignment=16 + ) + sHead = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=128 + ) + sTail = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=128 + ) + sTw = smem.allocate_tensor( + element_type=Uint32, layout=cute.make_layout(8), byte_alignment=128 + ) + sCnt = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(4), byte_alignment=16 + ) + sRes = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=16 + ) + sRed = smem.allocate_tensor( + element_type=Uint32, layout=cute.make_layout(8), byte_alignment=16 + ) + sWc = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=16 + ) + sScal = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(32), byte_alignment=16 + ) + sHQ = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(16), byte_alignment=16 + ) + sRres = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=16 + ) + sRred = smem.allocate_tensor( + element_type=Uint32, layout=cute.make_layout(8), byte_alignment=16 + ) + sRwc = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(8), byte_alignment=16 + ) + sGv = cute.make_tensor( + cute.recast_ptr(sOut.iterator, dtype=Int32), cute.make_layout(2 * K_TOP) + ) + sDQ = smem.allocate_tensor( + element_type=Int32, + layout=cute.make_layout(self.dq_cap if self.defer else 4), + byte_alignment=16, + ) + sRingBar = smem.allocate_tensor( + element_type=Int64, + layout=cute.make_layout(2 * 8 * (RING // RING_CHUNK)), + byte_alignment=16, + ) + if tidx < 2 * 8 * (RING // RING_CHUNK): + prims.mbarrier_init(sRingBar.iterator.raw_ptr() + tidx, 32) + # full[2], empty[2], final row scratch ownership, TMEM-address ready. + sRowBar = smem.allocate_tensor( + element_type=Int64, layout=cute.make_layout(6), byte_alignment=16 + ) + sCov = None + if cutlass.const_expr(self.merge1 > 0): + sCov = smem.allocate_tensor( + element_type=Int32, layout=cute.make_layout(COV_CAP + 8), byte_alignment=16 + ) + if tidx == 0: + for i in cutlass.range_constexpr(5): + prims.mbarrier_init(sRowBar.iterator.raw_ptr() + i, 128) + prims.mbarrier_init(sRowBar.iterator.raw_ptr() + 5, 1) + prims.fence_mbarrier_init() + if tidx < 8: + sHead[tidx] = Int32(0) + sTail[tidx] = Int32(0) + if cutlass.const_expr(self.dbg_addr): + if tidx == 0: + bufs = [ + sKV_0, + sKV_1, + sQ, + sW, + sScales_0, + sScales_1, + s_ring, + sMain, + sOut, + sHand, + sHB, + sAttB, + sAttO, + sHI, + sQatt, + sKVatt, + sAbar, + sMsk, + ] + for k in cutlass.range_constexpr(len(bufs)): + mStamps[bidz * 256 + 64 + k] = cutlass.Int64(bufs[k].iterator.toint()) + if tidx < 8: + sTw[tidx] = Uint32(0) + if tidx == 0: + sCnt[0] = Int32(0) + if tidx < 16: + sHI[tidx] = Int32(0) + if cutlass.const_expr(self.attn): + if warp_idx == 16: + if prims.elect_sync(): + for i in cutlass.range_constexpr(15): + prims.mbarrier_init(sAbar.iterator.raw_ptr() + i, 1) + prims.fence_mbarrier_init() + a_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2 + ) + b_mcast_mask = cpasync.create_tma_multicast_mask( + cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1 + ) + thr_mma = tiled_mma.get_slice(mma_tile_coord_v) + sKV_0_for_tma = cute.make_tensor(sKV_0.iterator, a_tma_view_layout.outer) + sKV_1_for_tma = cute.make_tensor(sKV_1.iterator, a_tma_view_layout.outer) + gA = cute.local_tile(mA_mkl, (self.phys_block_kv, self.head_dim), coord=(None, None, None)) + tAsA_0, tAgA_0 = cpasync.tma_partition( + tma_atom_a, 0, cute.make_layout(1), sKV_0_for_tma, cute.group_modes(gA, 0, 2) + ) + tAsA_1, tAgA_1 = cpasync.tma_partition( + tma_atom_a, 0, cute.make_layout(1), sKV_1_for_tma, cute.group_modes(gA, 0, 2) + ) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + tCgB = thr_mma.partition_B(gB_nkl) + b_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, + block_in_cluster_coord_vmnk[1], + b_cta_layout, + cute.group_modes(sQ, 0, 3), + cute.group_modes(tCgB, 0, 3), + ) + tBgB = tBgB[None, 0, None, None] + w_cta_layout = cute.make_layout((1,)) + tWsW, tWgW = cpasync.tma_partition( + tma_atom_w, 0, w_cta_layout, cute.group_modes(sW, 0, 1), cute.group_modes(mW_tma, 0, 1) + ) + s_tma_view_layout = cute.make_layout( + (self.phys_block_kv, self.num_blocks_per_mma, self.num_kv_stages), + stride=(1, self.phys_block_kv, self.block_kv), + ) + sScales_0_for_tma = cute.make_tensor(sScales_0.iterator, s_tma_view_layout) + sScales_1_for_tma = cute.make_tensor(sScales_1.iterator, s_tma_view_layout) + gS = cute.local_tile(mS_tma, (self.phys_block_kv,), coord=(None, None)) + tSsS_0, tSgS_0 = cpasync.tma_partition( + tma_atom_s, 0, cute.make_layout(1), sScales_0_for_tma, gS + ) + tSsS_1, tSgS_1 = cpasync.tma_partition( + tma_atom_s, 0, cute.make_layout(1), sScales_1_for_tma, gS + ) + if cutlass.const_expr(self.fp4): + sSF_Q_for_tma = cute.make_tensor(sSF_Q.iterator, sf_q_tma_smem_layout_staged) + tSF_Q_sSF_Q, tSF_Q_gSF_Q = cpasync.tma_partition( + tma_atom_sf_q, + 0, + cute.make_layout((1,)), + cute.group_modes(sSF_Q_for_tma, 0, 1), + cute.group_modes(mSF_Q_tma, 0, 1), + ) + tCrA_0 = tiled_mma.make_fragment_A(sKV_0) + tCrA_1 = tiled_mma.make_fragment_A(sKV_1) + tCrB = tiled_mma.make_fragment_B(sQ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + us = self.num_umma_stages + cols = self.num_tmem_alloc_cols + acc_shape_staged = cute.append(acc_shape, us) + tCtAcc_fake_staged = tiled_mma.make_fragment_C(acc_shape_staged) + cols_per_group = cols * us * (32 // self.acc_dtype.width) + num_tmem_alloc_cols_total = self.num_tmem_alloc_cols_total + c_layout = cutlass.utils.LayoutEnum.ROW_MAJOR + epi_sub_mn = (epi_tile[0], 32) + copy_atom_t2r = sm100_utils.get_tmem_load_op( + self.cta_tile_shape_mnk, + c_layout, + self.acc_dtype, + self.acc_dtype, + epi_sub_mn, + use_2cta_instrs, + ) + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + # All participants retrieve TMEM at the same static barrier site. + # Separate waits inside the role branches violate aligned-barrier rules. + if cutlass.const_expr(self.attn): + tmem.allocate(512) + else: + tmem.allocate(num_tmem_alloc_cols_total) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + if warpgroup_idx == 2: + cute.arch.warpgroup_reg_dealloc(24) + if is_tma_warp_0: + pol = None + if cutlass.const_expr(self.policy != L.POL_NONE): + pol = L.make_l2_policy(self.policy) + end_kv_idx = end_kv_half * NUM_MATH_WG + next_q_idx, next_kv_idx, next_num_kv, phase, stop_kv, has_work, rot_on = ( + self._walk_init( + start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size + ) + ) + q_idx = batch_size + lane_idx = tidx % 32 + cached_blks = [cutlass.Int32(0) for _ in range(NUM_BLOCKS_PER_MMA)] + kv_blk_ptr = cutlass.Int32(32) + bt_cols = cute.size(mBlockTable, mode=[1]) + if has_work: + q_pipeline.producer_acquire(q_prod_state) + q_bar = q_pipeline.producer_get_barrier(q_prod_state) + cute.copy( + tma_atom_b, + tBgB[None, 0, next_q_idx], + tBsB[None, q_prod_state.index], + tma_bar_ptr=q_bar, + mcast_mask=b_mcast_mask, + ) + cute.copy( + tma_atom_w, + tWgW[None, next_q_idx], + tWsW[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + if cutlass.const_expr(self.fp4): + cute.copy( + tma_atom_sf_q, + tSF_Q_gSF_Q[None, next_q_idx], + tSF_Q_sSF_Q[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + q_prod_state.advance() + seg_s = Int32(0) + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.lim_loop2): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if cutlass.const_expr(self.desc): + seg_s = self._seg_s(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + kv_blk_ptr = cutlass.Int32(32) + prefetch_next, pf_ok = self._walk_qnext( + q_idx, phase, rot_on, start_q, end_q_idx, end_kv_idx + ) + if pf_ok != Int32(0): + q_pipeline.producer_acquire(q_prod_state) + q_bar = q_pipeline.producer_get_barrier(q_prod_state) + cute.copy( + tma_atom_b, + tBgB[None, 0, prefetch_next], + tBsB[None, q_prod_state.index], + tma_bar_ptr=q_bar, + mcast_mask=b_mcast_mask, + ) + cute.copy( + tma_atom_w, + tWgW[None, prefetch_next], + tWsW[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + if cutlass.const_expr(self.fp4): + cute.copy( + tma_atom_sf_q, + tSF_Q_gSF_Q[None, prefetch_next], + tSF_Q_sSF_Q[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + q_prod_state.advance() + # Keep row metadata and Q handoffs outside the per-tile loop. + # One dummy pair is still issued for a zero-length row. + kv_go = cutlass.Boolean(True) + while kv_go: + kv_d = kv_idx + if cutlass.const_expr(self.desc): + kv_d = seg_s - kv_idx + if kv_blk_ptr == 32: + kv_blk_ptr = cutlass.Int32(0) + prefetch_kv = kv_idx + lane_idx * NUM_MATH_WG + if cutlass.const_expr(self.desc): + prefetch_kv = kv_d - lane_idx * NUM_MATH_WG + base_phys = prefetch_kv * NUM_BLOCKS_PER_MMA + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cached_blks[i] = mBlockTable[ + q_idx, cutlass.min(cutlass.max(base_phys + i, 0), bt_cols - 1) + ] + tile_ok = kv_d + 0 < num_kv + phys_blks = [cutlass.Int32(0)] * NUM_BLOCKS_PER_MMA + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + pv = cute.arch.shuffle_sync(cached_blks[i], kv_blk_ptr) + phys_blks[i] = cutlass.select_(tile_ok, pv, cutlass.Int32(0)) + kv_blk_ptr = kv_blk_ptr + 1 + kv_pipeline_0.producer_acquire(kv_prod_state_0) + bar = kv_pipeline_0.producer_get_barrier(kv_prod_state_0) + stage = kv_prod_state_0.index + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_0[None, 0, 0, phys_blks[i]], + tAsA_0[None, i, stage], + tma_bar_ptr=bar, + mcast_mask=a_mcast_mask, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_0[None, 0, phys_blks[i]], + tSsS_0[None, i, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_0.advance() + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.lim_loop2): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ((q_idx != end_q_idx) | (kv_idx != end_kv_idx)) + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + elif is_tma_warp_1: + pol = None + if cutlass.const_expr(self.policy != L.POL_NONE): + pol = L.make_l2_policy(self.policy) + end_kv_idx = end_kv_half * NUM_MATH_WG + next_q_idx, next_kv_idx, next_num_kv, phase, stop_kv, has_work, rot_on = ( + self._walk_init( + start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size + ) + ) + q_idx = batch_size + lane_idx = tidx % 32 + cached_blks = [cutlass.Int32(0) for _ in range(NUM_BLOCKS_PER_MMA)] + kv_blk_ptr = cutlass.Int32(32) + bt_cols = cute.size(mBlockTable, mode=[1]) + seg_s = Int32(0) + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.lim_loop2): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if cutlass.const_expr(self.desc): + seg_s = self._seg_s(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + kv_blk_ptr = cutlass.Int32(32) + # Keep row metadata and Q handoffs outside the per-tile loop. + # One dummy pair is still issued for a zero-length row. + kv_go = cutlass.Boolean(True) + while kv_go: + kv_d = kv_idx + if cutlass.const_expr(self.desc): + kv_d = seg_s - kv_idx + if kv_blk_ptr == 32: + kv_blk_ptr = cutlass.Int32(0) + prefetch_kv = kv_idx + 1 + lane_idx * NUM_MATH_WG + if cutlass.const_expr(self.desc): + prefetch_kv = kv_d + 1 - lane_idx * NUM_MATH_WG + base_phys = prefetch_kv * NUM_BLOCKS_PER_MMA + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cached_blks[i] = mBlockTable[ + q_idx, cutlass.min(cutlass.max(base_phys + i, 0), bt_cols - 1) + ] + tile_ok = kv_d + 1 < num_kv + phys_blks = [cutlass.Int32(0)] * NUM_BLOCKS_PER_MMA + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + pv = cute.arch.shuffle_sync(cached_blks[i], kv_blk_ptr) + phys_blks[i] = cutlass.select_(tile_ok, pv, cutlass.Int32(0)) + kv_blk_ptr = kv_blk_ptr + 1 + kv_pipeline_1.producer_acquire(kv_prod_state_1) + bar = kv_pipeline_1.producer_get_barrier(kv_prod_state_1) + stage = kv_prod_state_1.index + for i in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_1[None, 0, 0, phys_blks[i]], + tAsA_1[None, i, stage], + tma_bar_ptr=bar, + mcast_mask=a_mcast_mask, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_1[None, 0, phys_blks[i]], + tSsS_1[None, i, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_1.advance() + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.lim_loop2): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ((q_idx != end_q_idx) | (kv_idx != end_kv_idx)) + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + elif is_umma_warp_0: + end_kv_idx = end_kv_half * NUM_MATH_WG + next_q_idx, next_kv_idx, next_num_kv, phase, stop_kv, has_work, rot_on = ( + self._walk_init( + start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size + ) + ) + q_idx = batch_size + tCtAcc_base_0 = cute.make_tensor(tmem_ptr, tCtAcc_fake_staged.layout) + if cutlass.const_expr(self.fp4): + sf_base = self.num_tmem_alloc_cols * self.num_groups * self.num_umma_stages + tCtSFA = cute.make_tensor( + cute.recast_ptr(tmem_ptr + sf_base, dtype=self.sf_dtype), tmem_sfa_layout + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + sf_base + self.num_sfa_tmem_cols * self.num_groups, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + if is_leader_cta: + num_k_blocks = cute.size(tCrA_0.shape[2]) + q_stage_0 = cutlass.Int32(0) + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.lim_loop2): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if q_idx_old < batch_size: + if cutlass.const_expr(self.fp4): + sfb_war_pipeline.producer_commit(sfb_war_prod_state) + q_cons_state_umma_0.advance() + q_pipeline.consumer_wait(q_cons_state_umma_0) + q_stage_0 = q_cons_state_umma_0.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.N_padded // 128): + L.sf_atom_transpose( + sSF_Q.iterator + + q_stage_0 * sSF_Q.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + if q_idx_old < batch_size: + sfb_war_pipeline.consumer_wait(sfb_war_cons_state) + sfb_war_cons_state.advance() + sSF_Q_ue8m0 = cute.recast_tensor(sSF_Q, Float8E8M0FNU) + sSF_Q_chunk = cute.make_tensor( + sSF_Q_ue8m0.iterator + q_stage_0 * sSF_Q_ue8m0.layout.stride[1], + sfb_chunk_smem_layout, + ) + tCsSFB_compact = cute.filter_zeros(sSF_Q_chunk) + tCtSFB_compact = cute.filter_zeros(tCtSFB) + tiled_copy_s2t_sfb = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFB_compact + ) + thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0) + tCsSFB_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact) + tCsSFB_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfb, tCsSFB_s2t_ + ) + tCtSFB_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact) + cute.copy(tiled_copy_s2t_sfb, tCsSFB_s2t, tCtSFB_s2t) + cute.arch.fence_view_async_tmem_store() + sfb_sync_barrier.arrive_and_wait() + # Keep row metadata and Q handoffs outside the per-tile loop. + # One dummy pair is still issued for a zero-length row. + kv_go = cutlass.Boolean(True) + while kv_go: + kv_pipeline_0.consumer_wait(kv_cons_state_umma_0) + umma_pipeline_0.producer_acquire(umma_prod_state_0) + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage = kv_cons_state_umma_0.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_0.iterator + + kv_stage * sScales_0.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_0_ue8m0 = cute.recast_tensor(sScales_0, Float8E8M0FNU) + sSF_KV_0_chunk = cute.make_tensor( + sSF_KV_0_ue8m0.iterator + + kv_stage * sSF_KV_0_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact_0 = cute.filter_zeros(sSF_KV_0_chunk) + tCtSFA_compact_0 = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa_0 = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact_0 + ) + thr_copy_s2t_sfa_0 = tiled_copy_s2t_sfa_0.get_slice(0) + tCsSFA_s2t_0_ = thr_copy_s2t_sfa_0.partition_S(tCsSFA_compact_0) + tCsSFA_s2t_0 = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa_0, tCsSFA_s2t_0_ + ) + tCtSFA_s2t_0 = thr_copy_s2t_sfa_0.partition_D(tCtSFA_compact_0) + cute.copy(tiled_copy_s2t_sfa_0, tCsSFA_s2t_0, tCtSFA_s2t_0) + tCtAcc_0 = tCtAcc_base_0[None, None, None, umma_prod_state_0.index] + for k_block in cutlass.range_constexpr(num_k_blocks): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_0, + tCrA_0[None, None, k_block, kv_stage], + tCrB[None, None, k_block, q_stage_0], + tCtAcc_0, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_0.consumer_release(kv_cons_state_umma_0) + kv_cons_state_umma_0.advance() + umma_pipeline_0.producer_commit(umma_prod_state_0) + umma_prod_state_0.advance() + if cutlass.const_expr(self.fp4 and not self.nolock): + sfb_sync_barrier.arrive_and_wait() + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.lim_loop2): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ( + (q_idx != end_q_idx) | (kv_idx != end_kv_idx) + ) + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + elif is_umma_warp_1: + end_kv_idx = end_kv_half * NUM_MATH_WG + next_q_idx, next_kv_idx, next_num_kv, phase, stop_kv, has_work, rot_on = ( + self._walk_init( + start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size + ) + ) + q_idx = batch_size + tCtAcc_base_1 = cute.make_tensor(tmem_ptr + cols_per_group, tCtAcc_fake_staged.layout) + if cutlass.const_expr(self.fp4): + sf_base = self.num_tmem_alloc_cols * self.num_groups * self.num_umma_stages + tCtSFA = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + sf_base + self.num_sfa_tmem_cols, dtype=self.sf_dtype + ), + tmem_sfa_layout, + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + sf_base + self.num_sfa_tmem_cols * self.num_groups, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + if is_leader_cta: + num_k_blocks_1 = cute.size(tCrA_1.shape[2]) + q_stage_1 = cutlass.Int32(0) + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.lim_loop2): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if q_idx_old < batch_size: + if cutlass.const_expr(self.fp4): + sfb_war_pipeline.producer_commit(sfb_war_prod_state) + q_cons_state_umma_1.advance() + q_pipeline.consumer_wait(q_cons_state_umma_1) + q_stage_1 = q_cons_state_umma_1.index + if cutlass.const_expr(self.fp4): + sfb_sync_barrier.arrive_and_wait() + # Keep row metadata and Q handoffs outside the per-tile loop. + # One dummy pair is still issued for a zero-length row. + kv_go = cutlass.Boolean(True) + while kv_go: + kv_pipeline_1.consumer_wait(kv_cons_state_umma_1) + umma_pipeline_1.producer_acquire(umma_prod_state_1) + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage_1 = kv_cons_state_umma_1.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_1.iterator + + kv_stage_1 * sScales_1.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_1_ue8m0 = cute.recast_tensor(sScales_1, Float8E8M0FNU) + sSF_KV_1_chunk = cute.make_tensor( + sSF_KV_1_ue8m0.iterator + + kv_stage_1 * sSF_KV_1_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact_1 = cute.filter_zeros(sSF_KV_1_chunk) + tCtSFA_compact_1 = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa_1 = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact_1 + ) + thr_copy_s2t_sfa_1 = tiled_copy_s2t_sfa_1.get_slice(0) + tCsSFA_s2t_1_ = thr_copy_s2t_sfa_1.partition_S(tCsSFA_compact_1) + tCsSFA_s2t_1 = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa_1, tCsSFA_s2t_1_ + ) + tCtSFA_s2t_1 = thr_copy_s2t_sfa_1.partition_D(tCtSFA_compact_1) + cute.copy(tiled_copy_s2t_sfa_1, tCsSFA_s2t_1, tCtSFA_s2t_1) + tCtAcc_1 = tCtAcc_base_1[None, None, None, umma_prod_state_1.index] + for k_block in cutlass.range_constexpr(num_k_blocks_1): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_1, + tCrA_1[None, None, k_block, kv_stage_1], + tCrB[None, None, k_block, q_stage_1], + tCtAcc_1, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_1.consumer_release(kv_cons_state_umma_1) + kv_cons_state_umma_1.advance() + umma_pipeline_1.producer_commit(umma_prod_state_1) + umma_prod_state_1.advance() + if cutlass.const_expr(self.fp4 and not self.nolock): + sfb_sync_barrier.arrive_and_wait() + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.lim_loop2): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ( + (q_idx != end_q_idx) | (kv_idx != end_kv_idx) + ) + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + elif is_math_warp: + cute.arch.warpgroup_reg_alloc(self.math_regs) + end_kv_idx = end_kv_half * NUM_MATH_WG + next_q_idx, next_kv_idx, next_num_kv, phase, stop_kv, has_work, rot_on = ( + self._walk_init( + start_q, start_kv_half, end_q_idx, end_kv_half, mContextLens, batch_size + ) + ) + q_idx = batch_size + if cutlass.const_expr(self.attn): + if tidx == 0: + sHI[9] = cute.arch.load( + storage.tmem_holding_buf.ptr, Int32, sem="relaxed", scope="cta" + ) + prims.mbarrier_arrive(sRowBar.iterator.raw_ptr() + Int32(5)) + local_tidx = tidx % 128 + m_lane = tidx % 32 + cC = cute.make_identity_tensor(epi_sub_mn) + NUM_W_IN_REG = self.num_w_in_reg + if cutlass.const_expr(self.debug_dump): + logits_stride0 = cutlass.Int64(mLogits.layout.stride[0]) + mLogits_flat = cute.make_tensor( + mLogits.iterator, + cute.make_layout(cute.size(mLogits, mode=[0]) * logits_stride0), + ) + out_row_off = cutlass.Int64(0) + grp = warpgroup_idx + tCtAcc_base_g = cute.make_tensor( + tmem_ptr + grp * cols_per_group, tCtAcc_fake_staged.layout + ) + tAcc_ref = tCtAcc_base_g[None, None, None, 0][(None, None), 0, 0] + tAcc_ref_epi = cute.flat_divide(tAcc_ref, epi_sub_mn) + tiled_copy_ref = tcgen05.make_tmem_copy(copy_atom_t2r, tAcc_ref_epi[None, None, 0, 0]) + thr_copy_ref = tiled_copy_ref.get_slice(local_tidx) + tTR_cC = thr_copy_ref.partition_D(cC) + m_coord = tTR_cC[0][0] + tTR_rAcc = cute.make_fragment_like(tTR_cC, self.acc_dtype) + w_cache = cute.make_rmem_tensor((max(NUM_W_IN_REG, 1),), self.epi_dtype) + q_stage_local = cutlass.Int32(0) + ctx_q = cutlass.Int32(0) + lt_mask = cutlass.Int32(cute.arch.lanemask_lt()) + ring_off = warp_idx * Int32(RING) + head = Int32(0) + seg_ord = Int32(0) + tw_ptr = sTw.iterator + warp_idx + full_ptr = sRingBar.iterator.raw_ptr() + warp_idx * Int32(RING // RING_CHUNK) + empty_ptr = full_ptr + Int32(8 * (RING // RING_CHUNK)) + T = Float32(NEG_INF) + stall_ns = Int64(0) + skew_seed = Int32(0) + if cutlass.const_expr(self.skew_ns > 0): + skew_seed = Int32( + Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(5)) + ) + bidz * Int32(7919) + seg_s = Int32(0) + tcount = Int32(0) + if warpgroup_idx == 0: + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.desc): + seg_s = self._seg_s(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if cutlass.const_expr(self.lim_loop): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if q_idx_old < batch_size: + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + q_pipeline.consumer_release(q_cons_state) + q_cons_state.advance() + q_pipeline.consumer_wait(q_cons_state) + q_stage_local = q_cons_state.index + if cutlass.const_expr(self.debug_dump): + out_row_off = cutlass.Int64(q_idx) * logits_stride0 + for w_j in cutlass.range_constexpr(NUM_W_IN_REG): + w_cache[w_j] = sW[w_j, q_stage_local] + ctx_q = self._ctx_of(q_idx, mContextLens, batch_size) + # A saved floor is valid only for this row segment. + T = Float32(NEG_INF) + kv_go = cutlass.Boolean(True) + while kv_go: + kv_pos = kv_idx * block_kv_val + m_coord + if cutlass.const_expr(self.desc): + kv_pos = (seg_s - kv_idx) * block_kv_val + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready_0 = kv_pipeline_0.consumer_try_wait(kv_cons_state_math_0) + umma_ready_0 = umma_pipeline_0.consumer_try_wait(umma_cons_state_0) + if cutlass.const_expr(not self.fp4): + kv_pipeline_0.consumer_wait(kv_cons_state_math_0, kv_ready_0) + scale_val = sScales_0[m_coord, kv_cons_state_math_0.index] + umma_pipeline_0.consumer_wait(umma_cons_state_0, umma_ready_0) + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tCtAcc_c0 = tCtAcc_base_g[None, None, None, umma_cons_state_0.index] + tAcc_c0 = tCtAcc_c0[(None, None), 0, 0] + tAcc_c0_epi = cute.flat_divide(tAcc_c0, epi_sub_mn) + tTR_0 = thr_copy_ref.partition_S(tAcc_c0_epi) + if cutlass.const_expr(not self.late_release and not self.fp4): + scale_val = _consume_f32(scale_val) + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + kv_pipeline_0.consumer_release(kv_cons_state_math_0) + kv_cons_state_math_0.advance() + cute.copy(tiled_copy_ref, tTR_0[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + s0x, s0y, s1x, s1y = self._epi_half( + tTR_rAcc, + w_cache, + 0, + Float32(0.0), + Float32(0.0), + Float32(0.0), + Float32(0.0), + ) + cute.copy(tiled_copy_ref, tTR_0[None, None, None, 0, 1], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + umma_pipeline_0.consumer_release(umma_cons_state_0) + umma_cons_state_0.advance() + s0x, s0y, s1x, s1y = self._epi_half( + tTR_rAcc, w_cache, 32, s0x, s0y, s1x, s1y + ) + result_t = s0x + s0y + s1x + s1y + if cutlass.const_expr(self.fp4): + # the block-scaled MMA applies the scales; result_t is twice the sum (relu as x + |x|) + val = self.output_dtype(result_t * 0.5) + else: + scale_mul = scale_val * 0.5 + val = self.output_dtype(result_t * scale_mul) + if cutlass.const_expr(self.late_release and not self.fp4): + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + kv_pipeline_0.consumer_release(kv_cons_state_math_0) + kv_cons_state_math_0.advance() + if cutlass.const_expr(self.debug_dump): + mLogits_flat[out_row_off + kv_pos] = val + if cutlass.const_expr(self.admit): + # Stale same-segment floors remain conservative. + if (kv_idx & Int32(self.floor_mask)) == Int32(0): + T = _floor_of(tw_ptr, seg_ord, m_lane) + hit = (kv_pos < ctx_q) & (val >= T) + ent = L.pack_entry(L.u32_of_f32(val), kv_pos) + head, stall_ns = _push_ring( + hit, + ent, + head, + s_ring, + ring_off, + empty_ptr, + full_ptr, + m_lane, + lt_mask, + stall_ns, + self.stamps, + ) + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.stamps): + tcount = tcount + Int32(1) + if tcount & Int32(63) == Int32(0): + if warp_idx == Int32(0): + if m_lane == Int32(0): + tslot = tcount >> Int32(6) + if tslot < Int32(94): + mStamps[bidz * 256 + 162 + tslot] = cutlass.Int64( + cute.arch.globaltimer() + ) + if cutlass.const_expr(self.lim_loop): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ( + (q_idx != end_q_idx) | (kv_idx != end_kv_idx) + ) + if cutlass.const_expr(self.admit): + if cutlass.const_expr(self.skew_ns > 0): + L.skew_sleep( + skew_seed + warp_idx, + seg_ord * Int32(8) + Int32(1), + Int32(self.skew_ns), + ) + head = _push_marker( + seg_ord, head, s_ring, ring_off, empty_ptr, full_ptr, m_lane + ) + if cutlass.const_expr(self.stamps): + if m_lane == Int32(0): + if seg_ord < Int32(8): + mStamps[bidz * 256 + 32 + warp_idx * 8 + seg_ord] = stall_ns + mStamps[bidz * 256 + 96 + seg_ord] = cutlass.Int64( + cute.arch.globaltimer() + ) + seg_ord = seg_ord + 1 + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + if q_idx < batch_size: + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + q_pipeline.consumer_release(q_cons_state) + q_cons_state.advance() + else: + while has_work: + q_idx_old = q_idx + q_idx = next_q_idx + kv_idx = next_kv_idx + num_kv = next_num_kv + if cutlass.const_expr(self.desc): + seg_s = self._seg_s(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if cutlass.const_expr(self.lim_loop): + kv_lim = self._kv_limit(kv_idx, num_kv, q_idx, end_q_idx, end_kv_idx) + if q_idx != q_idx_old: + if q_idx_old < batch_size: + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + q_pipeline.consumer_release(q_cons_state) + q_cons_state.advance() + q_pipeline.consumer_wait(q_cons_state) + q_stage_local = q_cons_state.index + if cutlass.const_expr(self.debug_dump): + out_row_off = cutlass.Int64(q_idx) * logits_stride0 + for w_j in cutlass.range_constexpr(NUM_W_IN_REG): + w_cache[w_j] = sW[w_j, q_stage_local] + ctx_q = self._ctx_of(q_idx, mContextLens, batch_size) + # A saved floor is valid only for this row segment. + T = Float32(NEG_INF) + kv_go = cutlass.Boolean(True) + while kv_go: + kv_idx_1 = kv_idx + 1 + kv_pos = kv_idx_1 * block_kv_val + m_coord + if cutlass.const_expr(self.desc): + kv_pos = (seg_s - kv_idx + 1) * block_kv_val + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready_1 = kv_pipeline_1.consumer_try_wait(kv_cons_state_math_1) + umma_ready_1 = umma_pipeline_1.consumer_try_wait(umma_cons_state_1) + if cutlass.const_expr(not self.fp4): + kv_pipeline_1.consumer_wait(kv_cons_state_math_1, kv_ready_1) + scale_val = sScales_1[m_coord, kv_cons_state_math_1.index] + umma_pipeline_1.consumer_wait(umma_cons_state_1, umma_ready_1) + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tCtAcc_c1 = tCtAcc_base_g[None, None, None, umma_cons_state_1.index] + tAcc_c1 = tCtAcc_c1[(None, None), 0, 0] + tAcc_c1_epi = cute.flat_divide(tAcc_c1, epi_sub_mn) + tTR_1 = thr_copy_ref.partition_S(tAcc_c1_epi) + if cutlass.const_expr(not self.late_release and not self.fp4): + scale_val = _consume_f32(scale_val) + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + kv_pipeline_1.consumer_release(kv_cons_state_math_1) + kv_cons_state_math_1.advance() + cute.copy(tiled_copy_ref, tTR_1[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + s0x, s0y, s1x, s1y = self._epi_half( + tTR_rAcc, + w_cache, + 0, + Float32(0.0), + Float32(0.0), + Float32(0.0), + Float32(0.0), + ) + cute.copy(tiled_copy_ref, tTR_1[None, None, None, 0, 1], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + if cutlass.const_expr(self.tmem_fences): + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + umma_pipeline_1.consumer_release(umma_cons_state_1) + umma_cons_state_1.advance() + s0x, s0y, s1x, s1y = self._epi_half( + tTR_rAcc, w_cache, 32, s0x, s0y, s1x, s1y + ) + result_t = s0x + s0y + s1x + s1y + if cutlass.const_expr(self.fp4): + # the block-scaled MMA applies the scales; result_t is twice the sum (relu as x + |x|) + val = self.output_dtype(result_t * 0.5) + else: + scale_mul = scale_val * 0.5 + val = self.output_dtype(result_t * scale_mul) + if cutlass.const_expr(self.late_release and not self.fp4): + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + cute.arch.sync_warp() + kv_pipeline_1.consumer_release(kv_cons_state_math_1) + kv_cons_state_math_1.advance() + if cutlass.const_expr(self.debug_dump): + mLogits_flat[out_row_off + kv_pos] = val + if cutlass.const_expr(self.admit): + # Stale same-segment floors remain conservative. + if (kv_idx & Int32(self.floor_mask)) == Int32(0): + T = _floor_of(tw_ptr, seg_ord, m_lane) + hit = (kv_pos < ctx_q) & (val >= T) + ent = L.pack_entry(L.u32_of_f32(val), kv_pos) + head, stall_ns = _push_ring( + hit, + ent, + head, + s_ring, + ring_off, + empty_ptr, + full_ptr, + m_lane, + lt_mask, + stall_ns, + self.stamps, + ) + kv_idx = kv_idx + NUM_MATH_WG + if cutlass.const_expr(self.stamps): + tcount = tcount + Int32(1) + if tcount & Int32(63) == Int32(0): + if warp_idx == Int32(0): + if m_lane == Int32(0): + tslot = tcount >> Int32(6) + if tslot < Int32(94): + mStamps[bidz * 256 + 162 + tslot] = cutlass.Int64( + cute.arch.globaltimer() + ) + if cutlass.const_expr(self.lim_loop): + kv_go = kv_idx < kv_lim + else: + kv_go = (kv_idx < num_kv) & ( + (q_idx != end_q_idx) | (kv_idx != end_kv_idx) + ) + if cutlass.const_expr(self.admit): + if cutlass.const_expr(self.skew_ns > 0): + L.skew_sleep( + skew_seed + warp_idx, + seg_ord * Int32(8) + Int32(1), + Int32(self.skew_ns), + ) + head = _push_marker( + seg_ord, head, s_ring, ring_off, empty_ptr, full_ptr, m_lane + ) + if cutlass.const_expr(self.stamps): + if m_lane == Int32(0): + if seg_ord < Int32(8): + mStamps[bidz * 256 + 32 + warp_idx * 8 + seg_ord] = stall_ns + mStamps[bidz * 256 + 96 + seg_ord] = cutlass.Int64( + cute.arch.globaltimer() + ) + seg_ord = seg_ord + 1 + next_q_idx, next_kv_idx, next_num_kv, phase, has_work = self._walk_next( + q_idx, + kv_idx, + num_kv, + next_num_kv, + phase, + stop_kv, + start_q, + start_kv_half, + end_q_idx, + end_kv_idx, + mContextLens, + batch_size, + ) + if q_idx < batch_size: + if cutlass.const_expr(self.pfence): + cute.arch.fence_view_async_shared() + q_pipeline.consumer_release(q_cons_state) + q_cons_state.advance() + if cutlass.const_expr(self.stamps): + if tidx == 0: + mStamps[bidz * 256 + 1] = cutlass.Int64(cute.arch.globaltimer()) + if m_lane == Int32(0): + mStamps[bidz * 256 + 4 + warp_idx] = stall_ns + cute.arch.fence_view_async_shared() + cute.arch.fence_view_async_tmem_load() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=3, number_of_threads=self.num_math_threads) + if cutlass.const_expr(self.attn): + if tidx == 0: + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch( + sHI.iterator + Int32(11), Int32(1), sem="release", scope="cta" + ) + cute.arch.barrier(barrier_id=END_BAR, number_of_threads=self.num_math_threads + 128) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + elif is_sel_warp: + cute.arch.warpgroup_reg_dealloc(self.sel_regs) + if cutlass.const_expr(self.admit): + self._select_role( + tidx - 384, + bidz, + start_q, + start_kv_half, + end_q_idx, + end_kv_half, + batch_size, + mContextLens, + mScheduleMeta, + mRowStat, + mStamps, + s_ring, + sMain, + sOut, + sHist, + sCk, + sHead, + sTail, + sTw, + sCnt, + sRes, + sRed, + sWc, + sScal, + sKr, + sHI, + sHQ, + sHand, + sAttB, + sAttO, + sGv, + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mWsSeg, + mWsCtr, + sKV_0, + sQ, + sQatt, + sKVatt, + sAbar, + tma_q, + tma_swa, + tma_cmp, + sTb, + sRowBar, + sRingBar, + sCov, + sHand2, + ) + elif is_row_warp: + if cutlass.const_expr(self.row_regs >= 96): + cute.arch.warpgroup_reg_alloc(self.row_regs) + else: + cute.arch.warpgroup_reg_dealloc(self.row_regs) + if cutlass.const_expr(self.admit): + self._row_role( + tidx - 512, + bidz, + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mWsSeg, + mWsCtr, + mRowStat, + mStamps, + sHand, + sAttB, + sAttO, + sHI, + sRS, + tma_q, + tma_swa, + tma_cmp, + mSinks, + mOut, + softmax_scale, + sQatt, + sKVatt, + sAbar, + sMsk, + sKV_0, + sQ, + start_q, + batch_size, + mScheduleMeta, + sMain, + sHQ, + sRres, + sRred, + sRwc, + s_ring, + sGv, + self._nseg(start_q, start_kv_half, end_q_idx, end_kv_half), + sDQ, + refused, + mStatus, + sRowBar, + ) + if cutlass.const_expr(self.attn): + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier_arrive( + barrier_id=END_BAR, number_of_threads=self.num_math_threads + 128, aligned=False + ) + + @cute.jit + def _select_role( + self, + sel_tid, + cta, + start_q, + start_kv_half, + end_q_idx, + end_kv_half, + batch_size, + mContextLens, + mSched, + mRowStat, + mStamps, + s_ring, + sMain, + sOut, + sHist, + sCk, + sHead, + sTail, + sTw, + sCnt, + sRes, + sRed, + sWc, + sScal, + sKr, + sHI, + sHQ, + sHand, + sAttB, + sAttO, + sGv, + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mWsSeg, + mWsCtr, + sKV_0, + sQ, + sQatt, + sKVatt, + sAbar, + tma_q, + tma_swa, + tma_cmp, + sTb, + sRowBar, + sRingBar, + sCov=None, + sHand2=None, + ): + NT: cutlass.Constexpr[int] = SEL_NTHR + lane = sel_tid & Int32(31) + swarp = sel_tid >> Int32(5) + lt_mask = Int32(cute.arch.lanemask_lt()) + r0 = swarp * Int32(2) + r1 = r0 + Int32(1) + empty = (start_q == end_q_idx) & (start_kv_half == end_kv_half) + qb = end_q_idx + if end_kv_half == Int32(0): + qb = end_q_idx - Int32(1) + nseg = qb - start_q + Int32(1) + if empty: + nseg = Int32(0) + tail0 = Int32(0) + tail1 = Int32(0) + skew_seed = Int32(0) + if cutlass.const_expr(self.skew_ns > 0): + skew_seed = ( + Int32(Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(5))) + + cta * Int32(7919) + + Int32(13) + ) + t_comp = Int64(0) + prof_t = None + if cutlass.const_expr(self.stamps): + prof_t = cute.make_tensor( + mStamps.iterator + cta * Int32(256) + Int32(16), cute.make_layout(4) + ) + rot_on = Int32(0) + if cutlass.const_expr(self.rot): + if (end_kv_half > Int32(0)) & (end_q_idx > start_q): + rot_on = Int32(1) + seg = Int32(0) + while seg < nseg: + q = start_q + seg + if rot_on != Int32(0): + q = start_q + seg - Int32(1) + if seg == Int32(0): + q = qb + n = Int32(mContextLens[q]) + bsel = seg & Int32(1) + sMb = cute.make_tensor( + sMain.iterator + bsel * Int32(MAIN_CAP), cute.make_layout(MAIN_CAP) + ) + if swarp == Int32(0): + Pq = Int32(1) + pq_ = Int32(0) + if (q == start_q) | (q == qb): + if cutlass.const_expr(self.merge1 > 0): + Pq, pq_ = _parts_cov(q, cta, mSched, Int32(self.num_sms), lane, sCov) + else: + Pq, pq_ = _parts_of_row(q, cta, mSched, Int32(self.num_sms), lane) + if lane == Int32(0): + sScal[0] = Pq + sScal[1] = pq_ + # Empty barriers start at phase 0; generation 0 waits against 1. + _wait( + sRowBar.iterator.raw_ptr() + Int32(2) + bsel, + ((seg >> Int32(1)) & Int32(1)) ^ Int32(1), + ) + if sel_tid == Int32(0): + sCnt[0] = Int32(0) + sKr[0] = Uint32(4294967295) + sKr[1] = Uint32(0) + if cutlass.const_expr(self.defer): + t_lo = Int32(0) + if q == start_q: + t_lo = start_kv_half * Int32(2) + t_hi = (n + Int32(self.block_kv - 1)) // Int32(self.block_kv) + Int32( + 1 + ) & Int32(-2) + if q == end_q_idx: + t_hi = end_kv_half * Int32(2) + cute.arch.atomic_exch( + sHI.iterator + Int32(5), t_hi - t_lo, sem="release", scope="cta" + ) + if sel_tid < Int32(8): + cute.arch.atomic_exch( + sTw.iterator + sel_tid, Uint32(seg), sem="relaxed", scope="cta" + ) + L.bar(SEL_BAR, NT) + P = sScal[0] + p = sScal[1] + kth_key = Uint64(0) + done0 = Int32(0) + done1 = Int32(0) + adm = Int32(0) + ncomp = Int32(0) + alldone = Int32(0) + kf_done = Int32(0) + while alldone == Int32(0): + cnow = cute.arch.load(sCnt.iterator, Int32, sem="relaxed", scope="cta") + mydone = done0 & done1 + trg = Int32(self.trig) + if cutlass.const_expr(self.trig0 > 0): + if ncomp == Int32(0): + trg = Int32(self.trig0) + lite = Int32(0) + if cutlass.const_expr(self.kfloor): + if (kf_done == Int32(0)) & (ncomp == Int32(0)) & (cnow >= Int32(K_TOP)): + lite = Int32(1) + if (cnow >= trg) | (mydone != Int32(0)) | (lite != Int32(0)): + if lane == Int32(0): + sScal[4 + swarp] = done0 + done1 + L.bar(SEL_BAR, NT) + c = sCnt[0] + nd = sScal[4] + sScal[5] + sScal[6] + sScal[7] + L.bar(SEL_BAR, NT) + if c >= trg: + if cutlass.const_expr(self.skew_ns > 0): + if sel_tid == Int32(0): + L.skew_sleep( + skew_seed, ncomp * Int32(16) + seg, Int32(self.skew_ns) + ) + t_c0 = Int64(0) + if cutlass.const_expr(self.stamps): + t_c0 = cutlass.Int64(cute.arch.globaltimer()) + tw_e = None + if cutlass.const_expr(self.efl): + tw_e = sTw.iterator + kept, tf = _compact_approx( + sMb, + c, + sHist, + sRes, + sCnt.iterator, + sKr.iterator, + sKr.iterator + 1, + sKr.iterator + 2, + sScal, + sel_tid, + NT, + SEL_BAR, + prof_t, + min(self.keep_cap, self.trig - 1), + self.cbins, + tw_e, + seg, + self.tiebin, + sTb, + fast_cmp=self.cmp_fast, + ) + if kept < Int32(0): + no_, kth, m_, inf_ = L.select_topk_list( + sMb, + c, + Int32(K_TOP), + sOut, + sHist, + sCk, + sRes, + sRed, + sWc, + sel_tid, + False, + NT, + SEL_BAR, + True, + ) + ic = sel_tid + while ic < Int32(K_TOP): + sMb[ic] = Uint64(sOut[ic]) + ic = ic + Int32(NT) + tf = Uint32(kth >> Uint64(32)) + L.bar(SEL_BAR, NT) + if sel_tid == Int32(0): + sCnt[0] = Int32(K_TOP) + sKr[0] = tf + L.bar(SEL_BAR, NT) + kth_key = Uint64(tf) << Uint64(32) + if sel_tid < Int32(8): + cute.arch.atomic_exch( + sTw.iterator + sel_tid, + _pack_floor_key(tf, seg), + sem="relaxed", + scope="cta", + ) + ncomp = ncomp + Int32(1) + if cutlass.const_expr(self.stamps): + t_comp = t_comp + (cutlass.Int64(cute.arch.globaltimer()) - t_c0) + elif nd == Int32(8): + alldone = Int32(1) + if cutlass.const_expr(self.kfloor): + if ( + (kf_done == Int32(0)) + & (ncomp == Int32(0)) + & (alldone == Int32(0)) + & (c >= Int32(K_TOP)) + ): + kf_done = Int32(1) + tfk = Uint32(sKr[0]) + kth_key = Uint64(tfk) << Uint64(32) + if sel_tid < Int32(8): + cute.arch.atomic_exch( + sTw.iterator + sel_tid, + _pack_floor_key(tfk, seg), + sem="relaxed", + scope="cta", + ) + L.bar(SEL_BAR, NT) + else: + tail0, done0, u0, g0 = _drain_ring( + r0, + tail0, + done0, + kth_key, + s_ring, + sRingBar.iterator.raw_ptr() + r0 * Int32(RING // RING_CHUNK), + sRingBar.iterator.raw_ptr() + + Int32(8 * (RING // RING_CHUNK)) + + r0 * Int32(RING // RING_CHUNK), + sMb, + sCnt.iterator, + lane, + lt_mask, + sKr.iterator, + sKr.iterator + 1, + ) + tail1, done1, u1, g1 = _drain_ring( + r1, + tail1, + done1, + kth_key, + s_ring, + sRingBar.iterator.raw_ptr() + r1 * Int32(RING // RING_CHUNK), + sRingBar.iterator.raw_ptr() + + Int32(8 * (RING // RING_CHUNK)) + + r1 * Int32(RING // RING_CHUNK), + sMb, + sCnt.iterator, + lane, + lt_mask, + sKr.iterator, + sKr.iterator + 1, + ) + adm = adm + u0 + u1 + if g0 | g1 == Int32(0): + L.nanosleep(Int32(self.sel_idle_ns)) + if cutlass.const_expr(self.stamps): + if sel_tid == Int32(0): + if seg == nseg - Int32(1): + mStamps[cta * 256 + 2] = cutlass.Int64(cute.arch.globaltimer()) + if seg < Int32(8): + mStamps[cta * 256 + 104 + seg] = cutlass.Int64(cute.arch.globaltimer()) + cfin = sCnt[0] + if lane == Int32(0): + sScal[12 + swarp] = adm + if seg == nseg - Int32(1): + cute.arch.fence_view_async_shared() + L.bar(SEL_BAR, NT) + pref = Int32(0) + sdone = Int32(1) + if seg == nseg - Int32(1): + if sel_tid == Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch( + sHI.iterator + Int32(3), Int32(1), sem="release", scope="cta" + ) + if cutlass.const_expr(self.etile): + if sel_tid == Int32(0): + az = cute.arch.load( + sHI.iterator + Int32(15), Int32, sem="acquire", scope="cta" + ) + og = cute.arch.load( + sHI.iterator + Int32(4), Int32, sem="acquire", scope="cta" + ) + dk = deep_ok(sHI.iterator) + ear = Int32(0) + if (az >= seg) & (dk != Int32(0)) & (og != Int32(0)): + ear = Int32(1) + sScal[9] = ear + L.bar(SEL_BAR, NT) + if sScal[9] != Int32(0): + sGv[sel_tid] = L.l2g_swa( + sel_tid, + Int32(mKvLens[q]) - Int32(1), + Int32(mReq[q]), + mBtSwa, + Int32(cute.size(mBtSwa, mode=[1])), + Int32(0), + ) + L.bar(SEL_BAR, NT) + abar_e = sAbar.iterator.raw_ptr() + issue_row_loads( + sel_tid, + q, + sGv, + cute.recast_ptr(sKV_0.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + sKVatt.iterator.raw_ptr(), + cute.recast_ptr(s_ring.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + cute.recast_ptr(sQ.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + sQatt.iterator.raw_ptr(), + abar_e, + abar_e + Int32(4), + abar_e + Int32(13), + tma_q, + tma_swa, + tma_cmp, + SEL_BAR, + Int32(0), + Int32(1), + ) + if sel_tid == Int32(0): + sHQ[14] = q + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch( + sHI.iterator + Int32(1), Int32(1), sem="release", scope="cta" + ) + if cutlass.const_expr(self.sel_fin): + # sHand is the only buffer this finalize shares with the row warps' finalize of the earlier segment + # (sAttB / sAttO are not used by it), so with sHand2 there is nothing to wait for. + if cutlass.const_expr(not self.sel_hand2): + if seg > Int32(0): + # One-shot transfer after every earlier row finalizer. + _wait(sRowBar.iterator.raw_ptr() + Int32(4), Int32(0)) + L.bar(SEL_BAR, NT) + pref = Int32(1) + sHand_f = sHand + if cutlass.const_expr(self.sel_hand2): + sHand_f = sHand2 + sdone, s0, s1, s2, s3, s4 = _finalize_seg( + sel_tid, + SEL_BAR, + cta, + start_q, + q, + n, + P, + p, + sMb, + cfin, + None, + sHand_f, + sAttB, + sAttO, + sHist, + sCk, + sRes, + sRed, + sWc, + cute.make_tensor(sScal.iterator + Int32(8), cute.make_layout(1)), + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRowStat, + mSched, + mWsSeg.iterator.toint(), + mWsCtr.iterator.toint(), + Int32(cute.size(mBtSwa, mode=[1])), + Int32(cute.size(mBtC, mode=[1])), + self.num_sms, + self.skew_ns, + skew_seed, + seg * Int32(16) + Int32(7), + self.stamps, + mStamps, + cta * Int32(256) + Int32(153), + None, + 0, + None, + self.rsort, + merge1=self.merge1, + sBig=cute.make_tensor( + cute.recast_ptr(sKV_0.iterator, dtype=Uint64), + cute.make_layout(self.merge_cap), + ) + if self.merge1 > 0 + else None, + sCov=sCov, + big_cap=self.merge_cap, + sel_fast=self.sel_fast, + ) + if sdone != Int32(0): + sGv[sel_tid] = s0 + sGv[sel_tid + Int32(128)] = s1 + sGv[sel_tid + Int32(256)] = s2 + sGv[sel_tid + Int32(384)] = s3 + sGv[sel_tid + Int32(512)] = s4 + L.bar(SEL_BAR, NT) + if sel_tid == Int32(0): + hs = bsel * Int32(8) + sHQ[hs + Int32(0)] = q + sHQ[hs + Int32(1)] = n + sHQ[hs + Int32(2)] = P + sHQ[hs + Int32(3)] = p + sHQ[hs + Int32(4)] = cfin + sHQ[hs + Int32(5)] = bsel + sHQ[hs + Int32(6)] = pref + sHQ[hs + Int32(7)] = Int32( + Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(10)) + ) + if cutlass.const_expr(self.skew_ns > 0): + L.skew_sleep(skew_seed, seg * Int32(16) + Int32(5), Int32(self.skew_ns)) + if sdone != Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch(sHI.iterator, seg + Int32(1), sem="release", scope="cta") + if cutlass.const_expr(self.stamps): + if seg < Int32(8): + mStamps[cta * 256 + 112 + seg] = cutlass.Int64(cute.arch.globaltimer()) + if sdone != Int32(0): + # Every selector releases its own sMain/sGv writes; thread 0 + # also publishes sHQ before its arrival completes this phase. + prims.mbarrier_arrive(sRowBar.iterator.raw_ptr() + bsel) + if cutlass.const_expr(self.gath): + if (pref != Int32(0)) & (sdone != Int32(0)): + if sel_tid == Int32(0): + az = cute.arch.load( + sHI.iterator + Int32(15), Int32, sem="acquire", scope="cta" + ) + og = cute.arch.load( + sHI.iterator + Int32(4), Int32, sem="acquire", scope="cta" + ) + dk = deep_ok(sHI.iterator) + while (az < seg) | (dk == Int32(0)) | (og == Int32(0)): + L.nanosleep(Int32(64)) + az = cute.arch.load( + sHI.iterator + Int32(15), Int32, sem="acquire", scope="cta" + ) + og = cute.arch.load( + sHI.iterator + Int32(4), Int32, sem="acquire", scope="cta" + ) + dk = deep_ok(sHI.iterator) + cute.arch.fence_acq_rel_cta() + if cutlass.const_expr(self.stamps): + mStamps[cta * 256 + 158] = cutlass.Int64(cute.arch.globaltimer()) + L.bar(SEL_BAR, NT) + abar_s = sAbar.iterator.raw_ptr() + jfirst = Int32(0) + if cutlass.const_expr(self.etile): + jfirst = sScal[9] + issue_row_loads( + sel_tid, + q, + sGv, + cute.recast_ptr(sKV_0.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + sKVatt.iterator.raw_ptr(), + cute.recast_ptr(s_ring.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + cute.recast_ptr(sQ.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr(), + sQatt.iterator.raw_ptr(), + abar_s, + abar_s + Int32(4), + abar_s + Int32(13), + tma_q, + tma_swa, + tma_cmp, + SEL_BAR, + jfirst, + Int32(NTILES), + ) + if cutlass.const_expr(self.stamps): + if sel_tid == Int32(0): + mStamps[cta * 256 + 159] = cutlass.Int64(cute.arch.globaltimer()) + seg = seg + Int32(1) + if sel_tid == Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch(sHI.iterator + Int32(3), Int32(1), sem="release", scope="cta") + cute.arch.atomic_exch(sHI.iterator + Int32(2), Int32(1), sem="release", scope="cta") + if cutlass.const_expr(self.stamps): + if sel_tid == Int32(0): + mStamps[cta * 256 + 3] = cutlass.Int64(cute.arch.globaltimer()) + mStamps[cta * 256 + 12] = t_comp + + @cute.jit + def _row_role( + self, + rtid, + cta, + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mWsSeg, + mWsCtr, + mRowStat, + mStamps, + sHand, + sAttB, + sAttO, + sHI, + sRS, + tma_q, + tma_swa, + tma_cmp, + mSinks, + mOut, + softmax_scale, + sQatt, + sKVatt, + sAbar, + sMsk, + sKV_0, + sQ, + start_q, + batch_size, + mSched, + sMain, + sHQ, + sRres, + sRred, + sRwc, + s_ring, + sGv, + nseg_r, + sDQ, + refused, + mStatus, + sRowBar, + ): + NT: cutlass.Constexpr[int] = SEL_NTHR + mbs = Int32(cute.size(mBtSwa, mode=[1])) + mbc = Int32(cute.size(mBtC, mode=[1])) + ws_seg_base = mWsSeg.iterator.toint() + ws_ctr_base = mWsCtr.iterator.toint() + nh = Int32(0) + live = Int32(1) + aph = Int32(0) + skew_seed = Int32(0) + if cutlass.const_expr(self.skew_ns > 0): + skew_seed = ( + Int32(Uint32(cutlass.Int64(cute.arch.globaltimer()) >> Int64(5))) + + cta * Int32(7919) + + Int32(29) + ) + scale_log2 = softmax_scale * Float32(LOG2_E) + tmem_att = Int32(0) + q_slot0 = sQatt.iterator.raw_ptr() + kv_slot0 = sKVatt.iterator.raw_ptr() + deep_base = cute.recast_ptr(sKV_0.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr() + deep_q = cute.recast_ptr(sQ.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr() + abar = sAbar.iterator.raw_ptr() + out_addr = mOut.iterator.toint() + sink_base = mSinks.iterator.raw_ptr() + kv_slot7 = cute.recast_ptr(s_ring.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr() + main_b = cute.recast_ptr(sMain.iterator, dtype=cutlass.Float8E4M3FN).raw_ptr() + sHistR = cute.make_tensor( + cute.recast_ptr(sAttB.iterator, dtype=Int32), cute.make_layout(L.NB_SEL) + ) + sCkR = cute.make_tensor(sAttO.iterator, cute.make_layout(L.QUADC)) + oend = cutlass.min(mSched[0, 0], batch_size) + if refused != Int32(0): + oend = Int32(0) + rb = cta + while rb < batch_size: + ic = rtid + while ic < Int32(K_TOP): + mTopk[rb, ic] = Int32(-1) + ic = ic + Int32(NT) + ic = rtid + while ic < Int32(640): + mGidx[rb, ic] = Int32(-1) + ic = ic + Int32(NT) + if cutlass.const_expr(self.attn): + ob = mOut.iterator.toint() + Int64(rb) * Int64(HEADS * LATENT * 2) + iw = rtid + while iw < Int32(HEADS * LATENT // 2): + cutlass.inttoptr(ob + Int64(iw) * Int64(4), mem_space=1, dtype=Int32).store( + Int32(2143322048) + ) + iw = iw + Int32(NT) + L.bar(ROW_BAR, NT) + if rtid == Int32(0): + L.publish_row(mRowStat.iterator.toint(), rb) + rb = rb + Int32(self.num_sms) + if cta == Int32(0): + if rtid == Int32(0): + mStatus[0] = refused + if cta < oend: + oq = cta + while oq < oend: + opos = Int32(mKvLens[oq]) - Int32(1) + oreq = Int32(mReq[oq]) + og0, og1, og2, og3, og4 = _write_row_outputs_regs( + oq, + Int32(0), + sHand, + Int32(0), + Int32(1), + mTopk, + mGidx, + mBtSwa, + mBtC, + opos, + oreq, + mbs, + mbc, + rtid, + ) + L.bar(ROW_BAR, NT) + if rtid == Int32(0): + L.publish_row(mRowStat.iterator.toint(), oq) + if cutlass.const_expr(self.attn): + if rtid == Int32(0): + _wait(sRowBar.iterator.raw_ptr() + Int32(5), Int32(0)) + sRS[2] = sHI[9] + sRS[3] = deep_ok(sHI.iterator) + L.bar(ROW_BAR, NT) + tmem_att = sRS[2] + odeep = Int32(0) + if cutlass.const_expr(not self.no_deep): + if sRS[3] != Int32(0): + odeep = Int32(1) + if cutlass.const_expr(self.att_skip & 32 == 0): + aph = att_row( + rtid, + oq, + og0, + og1, + og2, + og3, + og4, + tmem_att, + odeep, + q_slot0, + kv_slot0, + deep_base, + deep_q, + abar, + abar + Int32(4), + abar + Int32(12), + aph, + tma_q, + tma_swa, + tma_cmp, + sink_base + oq * Int32(HEADS), + out_addr, + scale_log2, + sMsk, + sHI.iterator, + ROW_BAR, + self.att_skip, + not self.no_deep, + self.stamps, + mStamps, + cta * Int32(256) + Int32(128), + kv_slot7, + Int32(0), + abar + Int32(13), + self.ahint, + ) + oq = oq + Int32(self.num_sms) + L.bar(ROW_BAR, NT) + if rtid == Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch(sHI.iterator + Int32(4), Int32(1), sem="release", scope="cta") + adone = Int32(0) + st_m = Float32(NEG_FLT_MAX) + st_l = Float32(0.0) + st_q = Int32(0) + st_p = Int32(0) + st_d = Int32(0) + dq_n = Int32(0) + while live != Int32(0): + if rtid == Int32(0): + prod = cute.arch.load(sHI.iterator, Int32, sem="acquire", scope="cta") + fin = cute.arch.load(sHI.iterator + Int32(2), Int32, sem="acquire", scope="cta") + ea = Int32(0) + if cutlass.const_expr(self.etile): + ea = cute.arch.load(sHI.iterator + Int32(1), Int32, sem="acquire", scope="cta") + dgo = Int32(0) + if cutlass.const_expr(self.defer): + if dq_n > Int32(0): + dgo = deep_ok(sHI.iterator) + if cute.arch.load( + sHI.iterator + Int32(5), Int32, sem="acquire", scope="cta" + ) >= Int32(DEFER_LONG): + dgo = Int32(1) + while ( + (prod <= nh) + & (fin == Int32(0)) + & ((ea == Int32(0)) | (adone != Int32(0))) + & (dgo == Int32(0)) + ): + L.nanosleep(Int32(128)) + prod = cute.arch.load(sHI.iterator, Int32, sem="acquire", scope="cta") + fin = cute.arch.load(sHI.iterator + Int32(2), Int32, sem="acquire", scope="cta") + if cutlass.const_expr(self.etile): + ea = cute.arch.load( + sHI.iterator + Int32(1), Int32, sem="acquire", scope="cta" + ) + if cutlass.const_expr(self.defer): + if dq_n > Int32(0): + dgo = deep_ok(sHI.iterator) + if cute.arch.load( + sHI.iterator + Int32(5), Int32, sem="acquire", scope="cta" + ) >= Int32(DEFER_LONG): + dgo = Int32(1) + if prod <= nh: + cute.arch.fence_acq_rel_cta() + prod = cute.arch.load(sHI.iterator, Int32, sem="acquire", scope="cta") + cute.arch.fence_acq_rel_cta() + wk = Int32(0) + if prod > nh: + # The leader consults pref before the row-wide work barrier. + _wait(sRowBar.iterator.raw_ptr() + (nh & Int32(1)), (nh >> Int32(1)) & Int32(1)) + wk = Int32(1) + if cutlass.const_expr(self.defer): + if dq_n > Int32(0): + if sHQ[(nh & Int32(1)) * Int32(8) + Int32(6)] != Int32(0): + wk = Int32(3) + elif dq_n > Int32(0): + wk = Int32(3) + elif (ea != Int32(0)) & (adone == Int32(0)): + wk = Int32(2) + sRS[0] = wk + L.bar(ROW_BAR, NT) + work = sRS[0] + # Every reader captures work before the leader may publish again. + L.bar(ROW_BAR, NT) + if work == Int32(1): + _wait(sRowBar.iterator.raw_ptr() + (nh & Int32(1)), (nh >> Int32(1)) & Int32(1)) + if work == Int32(0): + live = Int32(0) + elif cutlass.const_expr(self.row_noop): + L.bar(ROW_BAR, NT) + prims.mbarrier_arrive(sRowBar.iterator.raw_ptr() + Int32(2) + (nh & Int32(1))) + nh = nh + Int32(1) + else: + hs = (nh & Int32(1)) * Int32(8) + q = Int32(0) + n = Int32(0) + P = Int32(1) + p = Int32(0) + cbuf = Int32(0) + bsel = Int32(0) + pref = Int32(0) + # The selector may rewrite these slots while deferred or early + # attention runs. Only a published segment consumes its metadata. + if work == Int32(1): + q = sHQ[hs + Int32(0)] + n = sHQ[hs + Int32(1)] + P = sHQ[hs + Int32(2)] + p = sHQ[hs + Int32(3)] + cbuf = sHQ[hs + Int32(4)] + bsel = sHQ[hs + Int32(5)] + pref = sHQ[hs + Int32(6)] + done_row = Int32(0) + gv0 = Int32(-1) + gv1 = Int32(-1) + gv2 = Int32(-1) + gv3 = Int32(-1) + gv4 = Int32(-1) + j0 = Int32(0) + j1 = Int32(NTILES) + keep = Int32(0) + dly_t = Int32(-1) + if cutlass.const_expr(self.rdelay > 0): + if work == Int32(1): + if nh + Int32(2) < nseg_r: + dly_t = sHQ[hs + Int32(7)] + if work == Int32(2): + q = sHQ[14] + pref = Int32(1) + gv0 = sGv[rtid] + done_row = Int32(1) + j1 = Int32(1) + elif work == Int32(3): + dq_n = dq_n - Int32(1) + q = sDQ[dq_n] + gv0 = Int32(mGidx[q, rtid]) + gv1 = Int32(mGidx[q, rtid + Int32(128)]) + gv2 = Int32(mGidx[q, rtid + Int32(256)]) + gv3 = Int32(mGidx[q, rtid + Int32(384)]) + gv4 = Int32(mGidx[q, rtid + Int32(512)]) + pref = Int32(0) + done_row = Int32(1) + elif pref != Int32(0): + gv0 = sGv[rtid] + gv1 = sGv[rtid + Int32(128)] + gv2 = sGv[rtid + Int32(256)] + gv3 = sGv[rtid + Int32(384)] + gv4 = sGv[rtid + Int32(512)] + done_row = Int32(1) + if adone != Int32(0): + j0 = Int32(1) + else: + if cutlass.const_expr(self.ring2): + if P == Int32(1): + keep = Int32(1) + sMb = cute.make_tensor( + sMain.iterator + bsel * Int32(MAIN_CAP), cute.make_layout(MAIN_CAP) + ) + done_row, gv0, gv1, gv2, gv3, gv4 = _finalize_seg( + rtid, + ROW_BAR, + cta, + start_q, + q, + n, + P, + p, + sMb, + cbuf, + sHI.iterator + Int32(12) + bsel, + sHand, + sAttB, + sAttO, + sHistR, + sCkR, + sRres, + sRred, + sRwc, + cute.make_tensor(sRS.iterator + Int32(1), cute.make_layout(1)), + mKvLens, + mReq, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRowStat, + mSched, + ws_seg_base, + ws_ctr_base, + mbs, + mbc, + self.num_sms, + self.skew_ns, + skew_seed, + nh * Int32(16) + Int32(3), + self.stamps, + mStamps, + cta * Int32(256) + Int32(148), + dly_t, + self.rdelay, + keep, + self.rsort, + sRowBar.iterator.raw_ptr() + Int32(2) + bsel, + sel_fast=self.sel_fast, + ) + if work == Int32(1): + if nh + Int32(2) == nseg_r: + # The selector takes sHand/sAttB/sAttO only for its last + # segment, after all 128 row threads finish the prior one + # (not awaited with sel_hand2). + prims.mbarrier_arrive(sRowBar.iterator.raw_ptr() + Int32(4)) + if cutlass.const_expr(self.attn): + if done_row != Int32(0): + if rtid == Int32(0): + _wait(sRowBar.iterator.raw_ptr() + Int32(5), Int32(0)) + sRS[2] = sHI[9] + sRS[3] = deep_ok(sHI.iterator) + if cutlass.const_expr(self.defer): + sRS[5] = cute.arch.load( + sHI.iterator, Int32, sem="acquire", scope="cta" + ) + sRS[6] = cute.arch.load( + sHI.iterator + Int32(5), Int32, sem="acquire", scope="cta" + ) + if cutlass.const_expr(self.skew_ns > 0): + L.skew_sleep( + skew_seed + rtid, nh * Int32(16) + Int32(9), Int32(self.skew_ns) + ) + L.bar(ROW_BAR, NT) + tmem_att = sRS[2] + dfr = Int32(0) + if cutlass.const_expr(self.defer): + if ( + (work == Int32(1)) + & (pref == Int32(0)) + & (sRS[3] == Int32(0)) + & (dq_n < Int32(self.dq_cap)) + ): + if sRS[5] > nh + Int32(1): + dfr = Int32(1) + elif sRS[6] < Int32(DEFER_LONG): + dfr = Int32(1) + if dfr != Int32(0): + if rtid == Int32(0): + sDQ[dq_n] = q + dq_n = dq_n + Int32(1) + else: + deep0 = Int32(0) + if cutlass.const_expr(not self.no_deep): + if sRS[3] != Int32(0): + deep0 = Int32(1) + ext_on = Int32(0) + if cutlass.const_expr(self.gath): + if pref != Int32(0): + ext_on = Int32(1) + deep0 = Int32(1) + if cutlass.const_expr(self.stamps): + if rtid == Int32(0): + if work == Int32(2): + mStamps[cta * 256 + 160] = cutlass.Int64( + cute.arch.globaltimer() + ) + elif (nh < Int32(8)) & (work == Int32(1)): + mStamps[cta * 256 + 24 + nh] = cutlass.Int64( + cute.arch.globaltimer() + ) + kv_b = None + two_a = None + if cutlass.const_expr(self.ring2): + kv_b = main_b + bsel * Int32(MAIN_CAP * 8) + two_a = keep + cute.arch.fence_view_async_shared() + if cutlass.const_expr(self.att_skip & 32 == 0): + if cutlass.const_expr(self.etile): + i_m = Float32(NEG_FLT_MAX) + i_l = Float32(0.0) + i_q = Int32(0) + i_p = Int32(0) + i_d = deep0 + if j0 != Int32(0): + i_m = st_m + i_l = st_l + i_q = st_q + i_p = st_p + i_d = st_d + aph, st_m, st_l, st_q, st_p, st_d = att_row( + rtid, + q, + gv0, + gv1, + gv2, + gv3, + gv4, + tmem_att, + deep0, + q_slot0, + kv_slot0, + deep_base, + deep_q, + abar, + abar + Int32(4), + abar + Int32(12), + aph, + tma_q, + tma_swa, + tma_cmp, + sink_base + q * Int32(HEADS), + out_addr, + scale_log2, + sMsk, + sHI.iterator, + ROW_BAR, + self.att_skip, + not self.no_deep, + self.stamps, + mStamps, + cta * Int32(256) + Int32(128), + kv_slot7, + ext_on, + abar + Int32(13), + self.ahint, + True, + j0, + j1, + (i_m, i_l, i_q, i_p, i_d), + self.apace, + kv_b, + two_a, + ) + else: + pl = None + if cutlass.const_expr(self.pace_adapt): + pl = nh + Int32(1) + if work == Int32(3): + pl = nh + aph = att_row( + rtid, + q, + gv0, + gv1, + gv2, + gv3, + gv4, + tmem_att, + deep0, + q_slot0, + kv_slot0, + deep_base, + deep_q, + abar, + abar + Int32(4), + abar + Int32(12), + aph, + tma_q, + tma_swa, + tma_cmp, + sink_base + q * Int32(HEADS), + out_addr, + scale_log2, + sMsk, + sHI.iterator, + ROW_BAR, + self.att_skip, + not self.no_deep, + self.stamps, + mStamps, + cta * Int32(256) + Int32(128), + kv_slot7, + ext_on, + abar + Int32(13), + self.ahint, + False, + None, + None, + None, + self.apace, + kv_b, + two_a, + pl, + ) + if cutlass.const_expr(self.stamps): + if work == Int32(1): + if nh < Int32(8): + mStamps[cta * 256 + 120 + nh] = cutlass.Int64( + cute.arch.globaltimer() + ) + else: + mStamps[cta * 256 + 161] = cutlass.Int64(cute.arch.globaltimer()) + if cutlass.const_expr(self.ring2): + if keep != Int32(0): + if rtid == Int32(0): + cute.arch.fence_view_async_shared() + prims.mbarrier_arrive(sRowBar.iterator.raw_ptr() + Int32(2) + bsel) + if work == Int32(2): + adone = Int32(1) + elif work == Int32(3): + if dq_n == Int32(0): + if rtid == Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch( + sHI.iterator + Int32(15), nh, sem="release", scope="cta" + ) + else: + if dq_n == Int32(0): + if rtid == Int32(0): + cute.arch.fence_acq_rel_cta() + cute.arch.atomic_exch( + sHI.iterator + Int32(15), nh + Int32(1), sem="release", scope="cta" + ) + nh = nh + Int32(1) + if cutlass.const_expr(self.stamps): + if rtid == Int32(0): + mStamps[cta * 256 + 20] = cutlass.Int64(cute.arch.globaltimer()) + mStamps[cta * 256 + 14] = L.clk64() + + +_COMPILED = {} + + +def compile_indexer(mk: IndexerKernel): + key = tuple( + ((k, v) for k, v in sorted(vars(mk).items()) if isinstance(v, (int, float, bool, str))) + ) + if key in _COMPILED: + return _COMPILED[key] + H, D = (mk.num_heads, mk.head_dim) + fp4 = mk.fp4 + block_bytes = mk.phys_block_kv * ((D // 2 if fp4 else D) + 4) + rt = cute.runtime + sb = cute.sym_int() + kv_fake = rt.make_fake_tensor( + cutlass.Uint8, (cute.sym_int(), block_bytes), stride=(cute.sym_int64(), 1) + ) + q_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (H, D // 2 if fp4 else D, cute.sym_int()), stride_order=(1, 0, 2) + ) + w_fake = rt.make_fake_compact_tensor(cutlass.Float32, (H, cute.sym_int()), stride_order=(0, 1)) + lg_fake = rt.make_fake_tensor( + cutlass.Float32, (cute.sym_int(), cute.sym_int()), stride=(cute.sym_int64(), 1) + ) + bt_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, cute.sym_int()), stride_order=(1, 0)) + cl_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb,), stride_order=(0,)) + sm_fake = rt.make_fake_compact_tensor(cutlass.Int32, (cute.sym_int(), 2), stride_order=(1, 0)) + kvl_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb,), stride_order=(0,)) + req_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb,), stride_order=(0,)) + bts_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, cute.sym_int()), stride_order=(1, 0)) + btc_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, cute.sym_int()), stride_order=(1, 0)) + tk_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, K_TOP), stride_order=(1, 0)) + gi_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, 640), stride_order=(1, 0)) + wss_fake = rt.make_fake_compact_tensor(cutlass.Int64, (cute.sym_int(),), stride_order=(0,)) + wsc_fake = rt.make_fake_compact_tensor(cutlass.Int64, (cute.sym_int(),), stride_order=(0,)) + rs_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, 16), stride_order=(1, 0)) + st_fake = rt.make_fake_compact_tensor(cutlass.Int64, (cute.sym_int(),), stride_order=(0,)) + qa_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + sp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + cp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + sk_fake = rt.make_fake_compact_tensor( + cutlass.Float32, (cute.sym_int(), 64), stride_order=(1, 0), assumed_align=16 + ) + ou_fake = rt.make_fake_compact_tensor( + cutlass.BFloat16, (cute.sym_int(), 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + stw_fake = rt.make_fake_compact_tensor(cutlass.Int32, (4,), stride_order=(0,)) + stream = rt.make_fake_stream(use_tvm_ffi_env_stream=True) + compiled = cute.compile( + mk, + kv_fake, + q_fake, + w_fake, + lg_fake, + bt_fake, + cl_fake, + sm_fake, + kvl_fake, + req_fake, + bts_fake, + btc_fake, + tk_fake, + gi_fake, + wss_fake, + wsc_fake, + rs_fake, + st_fake, + qa_fake, + sp_fake, + cp_fake, + sk_fake, + ou_fake, + stw_fake, + cutlass.Float32(1.0), + cutlass.Int32(1), + cutlass.Int32(1), + stream, + *( + (rt.make_fake_compact_tensor(cutlass.Int32, (H, cute.sym_int()), stride_order=(0, 1)),) + if fp4 + else () + ), + options="--enable-tvm-ffi --generate-line-info", + ) + _COMPILED[key] = compiled + return compiled diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_lib.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_lib.py new file mode 100644 index 000000000000..4fcbc9fdd117 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_lib.py @@ -0,0 +1,2231 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""specDSA large-batch kernels, device helpers: PTX helpers, the ready queue and the selection routines shared by +the two kernels, and the L2 cache-policy constants. + +The constants that follow from the model (top-K) are defined from the ``DS_V4_FLASH`` spec of ``config.py``. +""" + +import cutlass +import cutlass.cute as cute +import cutlass.cute.math as cmath +from cutlass import Float32, Int32, Int64, Uint32, Uint64 +from cutlass._mlir.dialects import arith as mlir_arith +from cutlass._mlir.dialects import llvm +from cutlass._mlir.dialects import math as mlir_math +from cutlass.cutlass_dsl import T, dsl_user_op + +from .config import DS_V4_FLASH as SPEC + +# ==================================================================================================================== +# PTX helpers, the ready queue and the selection routines shared by the two kernels. +# ==================================================================================================================== + +K_TOP = SPEC.topk +NBS = 256 +QUADC = 288 +NB_SEL = 1024 +SENT_LO = -3e38 +SENT_HI = 3e38 +NEG_INF = float("-inf") +RES_B, RES_M, RES_ABOVE, RES_TOT, RES_B2, RES_B3 = (0, 1, 2, 3, 4, 5) +GEN_SHIFT = 16 +GEN_ONE = 1 << GEN_SHIFT +GRAIN = 32 +SWA = 128 +TPB_SWA = 128 +TPB_C = 32 +V_OK = 1 +V_FB_RADIX = 2 +V_FB_RECOMP = 3 +PATH_SHORT, PATH_T1, PATH_T12, PATH_FB_RADIX, PATH_FB_RECOMP, PATH_FLOOR = (1, 2, 3, 4, 5, 6) + + +def _asm(res_t, args, s, cons, loc, ip, side=True): + return llvm.inline_asm( + res_t, + args, + s, + cons, + has_side_effects=side, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +def _v(x, loc, ip): + return x.ir_value(loc=loc, ip=ip) + + +@dsl_user_op +def gtimer(*, loc=None, ip=None): + return Int64(_asm(T.i64(), [], "mov.u64 $0, %globaltimer;", "=l", loc, ip)) + + +@dsl_user_op +def clk64(*, loc=None, ip=None): + return Int64(_asm(T.i64(), [], "mov.u64 $0, %clock64;", "=l", loc, ip)) + + +@dsl_user_op +def nanosleep(ns, *, loc=None, ip=None): + _asm(None, [_v(ns, loc, ip)], "nanosleep.u32 $0;", "r", loc, ip) + + +@dsl_user_op +def prefetch_l2(addr, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip)], "prefetch.global.L2 [$0];", "l", loc, ip) + + +@dsl_user_op +def fence_acq_rel_gpu(*, loc=None, ip=None): + _asm(None, [], "fence.acq_rel.gpu;", "", loc, ip) + + +@dsl_user_op +def atom_add_u64(addr, val, *, loc=None, ip=None): + return Uint64( + _asm( + T.i64(), + [_v(addr, loc, ip), _v(val, loc, ip)], + "atom.relaxed.gpu.global.add.u64 $0, [$1], $2;", + "=l,l,l", + loc, + ip, + ) + ) + + +@dsl_user_op +def red_add_u64(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.relaxed.gpu.global.add.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def red_add_u32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.relaxed.gpu.global.add.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def ld_relaxed_u64(addr, *, loc=None, ip=None): + return Uint64( + _asm(T.i64(), [_v(addr, loc, ip)], "ld.relaxed.gpu.global.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def ld_acquire_u64(addr, *, loc=None, ip=None): + return Uint64( + _asm(T.i64(), [_v(addr, loc, ip)], "ld.acquire.gpu.global.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def st_release_u64(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "st.release.gpu.global.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def atom_add_i32(addr, val, *, loc=None, ip=None): + return Int32( + _asm( + T.i32(), + [_v(addr, loc, ip), _v(val, loc, ip)], + "atom.relaxed.gpu.global.add.u32 $0, [$1], $2;", + "=r,l,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def ld_acquire_i32(addr, *, loc=None, ip=None): + return Int32( + _asm(T.i32(), [_v(addr, loc, ip)], "ld.acquire.gpu.global.u32 $0, [$1];", "=r,l", loc, ip) + ) + + +@dsl_user_op +def st_release_i32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "st.release.gpu.global.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def st_relaxed_i32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "st.relaxed.gpu.global.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +# Ready queue shared by the indexer (producer) and the attention kernel (consumer), int32 words: +# [0] publish count, [1] claim count, [2] exited attention CTAs, [AQ_ENTRY + k] = k-th completed row or -1. +AQ_PUB = 0 +AQ_CLAIM = 1 +AQ_DONE = 2 +AQ_ENTRY = 4 + + +@cute.jit +def publish_row(aq_base, q): + # One thread, after a CTA barrier that orders the row's topk/gidx stores: release the row to attention. + fence_acq_rel_gpu() + slot = atom_add_i32(aq_base + Int64(AQ_PUB * 4), Int32(1)) + st_release_i32(aq_base + Int64(AQ_ENTRY * 4) + Int64(slot) * Int64(4), q) + + +@dsl_user_op +def ld_cg_u32(addr, *, loc=None, ip=None): + return Uint32(_asm(T.i32(), [_v(addr, loc, ip)], "ld.global.cg.u32 $0, [$1];", "=r,l", loc, ip)) + + +@dsl_user_op +def ld_cg_i32(addr, *, loc=None, ip=None): + return Int32(_asm(T.i32(), [_v(addr, loc, ip)], "ld.global.cg.u32 $0, [$1];", "=r,l", loc, ip)) + + +@dsl_user_op +def ld_cg_u64(addr, *, loc=None, ip=None): + return Uint64(_asm(T.i64(), [_v(addr, loc, ip)], "ld.global.cg.u64 $0, [$1];", "=l,l", loc, ip)) + + +@dsl_user_op +def ld_cg_f32(addr, *, loc=None, ip=None): + return Float32( + _asm(T.f32(), [_v(addr, loc, ip)], "ld.global.cg.f32 $0, [$1];", "=f,l", loc, ip) + ) + + +@dsl_user_op +def st_g_u64(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.u64 [$0], $1;", "l,l", loc, ip) + + +@dsl_user_op +def st_g_u32(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.u32 [$0], $1;", "l,r", loc, ip) + + +@dsl_user_op +def st_g_f32(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.f32 [$0], $1;", "l,f", loc, ip) + + +@dsl_user_op +def ld_nc_f32x4(addr, *, loc=None, ip=None): + st = llvm.StructType.get_literal([T.f32(), T.f32(), T.f32(), T.f32()]) + r = _asm( + st, + [_v(addr, loc, ip)], + "ld.global.nc.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,l", + loc, + ip, + side=False, + ) + return tuple((Float32(llvm.extractvalue(T.f32(), r, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def ld_nc_f32(addr, *, loc=None, ip=None): + return Float32( + _asm( + T.f32(), [_v(addr, loc, ip)], "ld.global.nc.f32 $0, [$1];", "=f,l", loc, ip, side=False + ) + ) + + +@dsl_user_op +def ld_cg_f32x4(addr, *, loc=None, ip=None): + st = llvm.StructType.get_literal([T.f32(), T.f32(), T.f32(), T.f32()]) + r = _asm( + st, + [_v(addr, loc, ip)], + "ld.global.cg.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,l", + loc, + ip, + ) + return tuple((Float32(llvm.extractvalue(T.f32(), r, [i], loc=loc, ip=ip)) for i in range(4))) + + +def bar(bar_id, nthr): + cute.arch.barrier(barrier_id=bar_id, number_of_threads=nthr) + + +def u32_of_f32(v): + return Uint32(llvm.bitcast(Uint32.mlir_type, v.ir_value())) + + +@dsl_user_op +def ld_shared_b32(smem_ptr, *, loc=None, ip=None): + addr = smem_ptr.toint(loc=loc, ip=ip) + return Int32( + llvm.inline_asm( + Int32.mlir_type, + [addr.ir_value(loc=loc, ip=ip)], + "ld.shared.b32 $0, [$1];", + "=r,r", + has_side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def st_shared_b32(smem_ptr, val, *, loc=None, ip=None): + addr = smem_ptr.toint(loc=loc, ip=ip) + llvm.inline_asm( + None, + [addr.ir_value(loc=loc, ip=ip), Int32(val).ir_value(loc=loc, ip=ip)], + "st.shared.b32 [$0], $1;", + "r,r", + has_side_effects=True, + loc=loc, + ip=ip, + ) + + +@cute.jit +def sf_atom_transpose(smem_ptr): + """One warp reshuffles 128 int32 (a 128-token scale atom of four UE8M0 each) to the byte layout UTCCP expects.""" + lane_idx = cute.arch.lane_idx() + values = cute.make_rmem_tensor((4,), cutlass.Int32) + for i in cutlass.range_constexpr(4): + values[i] = ld_shared_b32(smem_ptr + (i ^ (lane_idx >> 3)) * 32 + lane_idx) + cute.arch.sync_warp(-1) + for i in cutlass.range_constexpr(4): + st_shared_b32(smem_ptr + lane_idx * 4 + (i ^ (lane_idx >> 3)), values[i]) + + +def f32_of_u32(u): + return Float32(llvm.bitcast(Float32.mlir_type, u.ir_value())) + + +def fkey_bits(u): + neg = Uint32(0) - (u >> Uint32(31)) + return u ^ (neg | Uint32(2147483648)) + + +def fkey(x): + return fkey_bits(u32_of_f32(x)) + + +def invkey_bits(K): + s = K >> Uint32(31) + m = s - Uint32(1) | Uint32(2147483648) + return K ^ m + + +def invkey(K): + return f32_of_u32(invkey_bits(K)) + + +def warp_min_u32(v): + return cute.arch.warp_redux_sync(v, "min") + + +def warp_max_u32(v): + return cute.arch.warp_redux_sync(v, "max") + + +def f2u_rz(v): + return Uint32(v) + + +def f2s_rz(v): + return Int32(v) + + +@dsl_user_op +def _fmaf(a, b, c, *, loc=None, ip=None): + return Float32( + mlir_math.fma( + a.ir_value(loc=loc, ip=ip), + b.ir_value(loc=loc, ip=ip), + c.ir_value(loc=loc, ip=ip), + fastmath=mlir_arith.FastMathFlags.none, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _shfl_up_add(val, lane, offset: cutlass.Constexpr): + other = cute.arch.shuffle_sync_up(val, offset, mask_and_clamp=0) + if lane >= Int32(offset): + val = val + other + return val + + +@cute.jit +def warp_incl_scan_add(val, lane): + for o in [1, 2, 4, 8, 16]: + val = _shfl_up_add(val, lane, o) + return val + + +def smem_atom_i32_128(): + return cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Int32, num_bits_per_copy=128) + + +def _smem_v4_tensor(base_addr, byte_off): + p = cute.make_ptr(Int32, base_addr + byte_off, cute.AddressSpace.smem, assumed_align=16) + return cute.make_tensor(p, cute.make_layout((4,))) + + +def lds128_i32(copy_atom, base_addr, byte_off, frag): + cute.copy(copy_atom, _smem_v4_tensor(base_addr, byte_off), frag) + + +def sts128_i32(copy_atom, frag, base_addr, byte_off): + cute.copy(copy_atom, frag, _smem_v4_tensor(base_addr, byte_off)) + + +@cute.jit +def scan_cross0( + s_hist, + target, + tidx, + s_res, + target2, + target3, + s_addv, + nb: cutlass.Constexpr, + zero: cutlass.Constexpr, + two: cutlass.Constexpr = False, + three: cutlass.Constexpr = False, + addf: cutlass.Constexpr = False, +): + BPT = nb // 32 + NV = BPT // 4 + HOLD = NV <= 2 + if tidx < Int32(32): + lane = tidx + atom = smem_atom_i32_128() + hbase = s_hist.iterator.toint() + frags = [cute.make_rmem_tensor((4,), Int32) for _ in range(NV)] + sm = Int32(0) + for q in cutlass.range_constexpr(NV): + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, hbase, boff, frags[q]) + sm = sm + frags[q][0] + frags[q][1] + frags[q][2] + frags[q][3] + w = warp_incl_scan_add(sm, lane) + tot = cute.arch.shuffle_sync(w, Int32(31)) + after = tot - w + if lane == Int32(0): + s_res[RES_TOT] = tot + base = lane * Int32(BPT) + for q in cutlass.range_constexpr(NV - 1, -1, -1): + if cutlass.const_expr(HOLD): + vv = frags[q] + else: + vv = cute.make_rmem_tensor((4,), Int32) + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, hbase, boff, vv) + o4 = cute.make_rmem_tensor((4,), Int32) + for j in cutlass.range_constexpr(3, -1, -1): + cq = vv[j] + if cutlass.const_expr(zero): + o4[j] = Int32(0) + else: + o4[j] = after + gb = base + Int32(4 * q + j) + cross = Int32(0) + if after < target: + if after + cq >= target: + cross = Int32(1) + if gb == Int32(0): + cross = Int32(1) + if cross != Int32(0): + s_res[RES_B] = gb + s_res[RES_ABOVE] = after + s_res[RES_M] = cq + if cutlass.const_expr(two): + cross2 = Int32(0) + if after < target2: + if after + cq >= target2: + cross2 = Int32(1) + if gb == Int32(0): + cross2 = Int32(1) + if cross2 != Int32(0): + s_res[RES_B2] = gb + if cutlass.const_expr(three): + cross3 = Int32(0) + if after < target3: + if after + cq >= target3: + cross3 = Int32(1) + if gb == Int32(0): + cross3 = Int32(1) + if cross3 != Int32(0): + s_res[RES_B3] = gb + after = after + cq + if cutlass.const_expr(addf): + av = cute.make_rmem_tensor((4,), Int32) + aoff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, s_addv.iterator.toint(), aoff, av) + for j in cutlass.range_constexpr(4): + o4[j] = o4[j] + av[j] + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + sts128_i32(atom, o4, hbase, boff) + + +@cute.jit +def hi_bit_or_zero(msk): + r = Int32(0) + if msk != Int32(0): + r = Int32(31) - Int32(cute.arch.clz(msk)) + return r + + +@cute.jit +def _shfl_down_add(val, lane, offset: cutlass.Constexpr): + other = cute.arch.shuffle_sync_down(val, offset, mask_and_clamp=31) + if lane + Int32(offset) < Int32(32): + val = val + other + return val + + +@cute.jit +def warp_suffix_scan_add(val, lane): + for o in [1, 2, 4, 8, 16]: + val = _shfl_down_add(val, lane, o) + return val + + +@cute.jit +def find_cross(s_hist, target, tidx, s_res, nb: cutlass.Constexpr): + BPL = nb // 32 + if tidx < Int32(32): + lane = tidx + part = Int32(0) + for j in cutlass.range_constexpr(BPL): + idx = lane * Int32(BPL) + (Int32(j) + lane & Int32(BPL - 1)) + part = part + s_hist[idx] + v = warp_suffix_scan_add(part, lane) + if lane == Int32(0): + s_res[RES_TOT] = v + msk = Int32(cute.arch.vote_ballot_sync(v >= target)) + Lb = hi_bit_or_zero(msk) + aboveL = cute.arch.shuffle_sync(v - part, Lb) + h = Int32(0) + if lane < Int32(BPL): + h = s_hist[Lb * Int32(BPL) + lane] + w = warp_suffix_scan_add(h, lane) + msk2 = Int32(cute.arch.vote_ballot_sync(aboveL + w >= target)) + J = hi_bit_or_zero(msk2) + if lane == J: + s_res[RES_B] = Lb * Int32(BPL) + J + s_res[RES_M] = h + s_res[RES_ABOVE] = aboveL + (w - h) + + +def pack_entry(xbits_u32, idx_i32): + return Uint64(Uint32(idx_i32)) << Uint64(32) | Uint64(xbits_u32) + + +def entry_bits(e): + return Uint32(e & Uint64(4294967295)) + + +def entry_idx(e): + return Int32(Uint32(e >> Uint64(32))) + + +def entry_key(e): + kb = fkey_bits(entry_bits(e)) + return Uint64(kb) << Uint64(32) | Uint64(Uint32(4294967295) - Uint32(e >> Uint64(32))) + + +def key_to_entry(k): + idx = Uint32(4294967295) - Uint32(k & Uint64(4294967295)) + bits = invkey_bits(Uint32(k >> Uint64(32))) + return Uint64(idx) << Uint64(32) | Uint64(bits) + + +@cute.jit +def ld_entry(lst, i, src_gmem: cutlass.Constexpr): + r = Uint64(0) + if cutlass.const_expr(src_gmem): + r = ld_cg_u64(lst.iterator.toint() + Int64(i) * Int64(8)) + else: + r = Uint64(lst[i]) + return r + + +@cute.jit +def gvr_ladder( + n, k, aim_base, sfac, amin, sd_en, r_const: cutlass.Constexpr, scap: cutlass.Constexpr +): + SMP = Int32(0) + SS2 = Int32(1) + TGT = Int32(0) + TGT2 = Int32(0) + if n <= k: + TGT = Int32(1073741823) + TGT2 = Int32(1073741823) + else: + x6 = Int32(6) * n + ri = Int32(cmath.sqrt(Float32(x6))) + if ri * ri > x6: + ri = ri - Int32(1) + if (ri + Int32(1)) * (ri + Int32(1)) <= x6: + ri = ri + Int32(1) + r6 = ri + if x6 - ri * ri > ri: + r6 = ri + Int32(1) + aim = aim_base + if r6 > aim: + aim = r6 + if cutlass.const_expr(r_const > 1): + if aim < amin: + aim = amin + scap_c = Int32(scap) + if aim > scap_c >> Int32(1): + aim = scap_c >> Int32(1) + if aim < k: + aim = k + n4w = n >> Int32(2) + gate = Int32(0) + if n > scap_c: + gate = Int32(1) + if sd_en != Int32(0): + if n <= scap_c: + if n > k << Int32(1): + gate = Int32(1) + if n4w < Int32(4): + gate = Int32(0) + if gate != Int32(0): + sel = Int32(Float32(sfac * n) * cute.arch.rcp_approx(Float32(aim))) + if sel < Int32(256): + sel = Int32(256) + nh = n >> Int32(1) + if sel > nh: + sel = nh + pairs = sel >> Int32(3) + if pairs < Int32(1): + pairs = Int32(1) + half = n4w >> Int32(1) + if half < Int32(1): + half = Int32(1) + if pairs > half: + pairs = half + SS2 = Int32(Float32(half) * cute.arch.rcp_approx(Float32(pairs))) + if SS2 < Int32(1): + SS2 = Int32(1) + SMP = Int32(Float32(half) * cute.arch.rcp_approx(Float32(SS2))) + if SMP * SS2 > half: + SMP = SMP - Int32(1) + if SMP < Int32(1): + SMP = Int32(1) + rn_ = cute.arch.rcp_approx(Float32(n)) + smp8f = Float32(SMP) * Float32(8.0) + TGT = Int32(Float32(aim) * smp8f * rn_) + if TGT < Int32(1): + TGT = Int32(1) + TGT2 = Int32(Float32(k) * smp8f * rn_) + if TGT2 < Int32(1): + TGT2 = Int32(1) + return (SMP, SS2, TGT, TGT2) + + +@cute.jit +def gvr_sample_thresholds( + s_smp, + SMP, + TGT, + TGT2, + s_hist, + s_res, + s_wred, + tid, + split: cutlass.Constexpr, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + if tid == Int32(0): + s_res[RES_B2] = Int32(-1) + s_res[RES_B3] = Int32(-1) + smn = Float32(float("inf")) + smx = Float32(float("-inf")) + j = tid + while j < SMP: + for t in cutlass.range_constexpr(8): + v = Float32(s_smp[j * Int32(8) + Int32(t)]) + smn = cute.arch.fmin(smn, v) + smx = cute.arch.fmax(smx, v) + j = j + Int32(nthr) + a0 = warp_min_u32(fkey(smn)) + c0m = warp_max_u32(fkey(smx)) + if lane == Int32(0): + s_wred[wid] = a0 + s_wred[Int32(NW) + wid] = c0m + bar(bar_id, nthr) + av = Uint32(4294967295) + cv = Uint32(0) + if lane < Int32(NW): + av = Uint32(s_wred[lane]) + cv = Uint32(s_wred[Int32(NW) + lane]) + SMIN = invkey(warp_min_u32(av)) + SMAX = invkey(warp_max_u32(cv)) + GMIN = Float32(SENT_LO) + T = Float32(NEG_INF) + HIC = Float32(NEG_INF) + T3 = Float32(NEG_INF) + Tk = Float32(NEG_INF) + w = Float32(0.0) + sok = Int32(0) + if SMP > Int32(0): + if SMAX > SMIN: + sok = Int32(1) + if sok != Int32(0): + w = (SMAX - SMIN) * Float32(1.0 / 256.0) + sc_s = cute.arch.rcp_approx(w) + j2 = tid + while j2 < SMP: + for t in cutlass.range_constexpr(8): + v2 = Float32(s_smp[j2 * Int32(8) + Int32(t)]) + bq = f2s_rz((v2 - SMIN) * sc_s) + if bq > Int32(NBS - 1): + bq = Int32(NBS - 1) + cute.arch.atomic_add(s_hist.iterator + bq, Int32(1), sem="relaxed", scope="cta") + j2 = j2 + Int32(nthr) + bar(bar_id, nthr) + scan_cross0( + s_hist, + TGT, + tid, + s_res, + TGT2, + TGT * Int32(2), + s_hist, + nb=NBS, + zero=True, + two=True, + three=True, + ) + bar(bar_id, nthr) + tot0 = s_res[RES_TOT] + b1v = s_res[RES_B] + b2v = s_res[RES_B2] + b3v = s_res[RES_B3] + if sok != Int32(0): + if tot0 >= TGT: + T = _fmaf(Float32(b1v), w, SMIN) + Trung = T + tinf = Int32(1) + if T > Float32(NEG_INF): + tinf = Int32(0) + if tinf != Int32(0): + T = GMIN + if sok != Int32(0): + if tot0 >= TGT: + if b2v >= Int32(0): + Tk = _fmaf(Float32(b2v), w, SMIN) + anch = T + if cutlass.const_expr(not split): + anch = cute.arch.fmin(T, Trung) + d_ = cute.arch.fmax(Tk - anch, Float32(0.0)) + HIC = cute.arch.fmax(_fmaf(Float32(4.0), d_, T), _fmaf(Float32(8.0), w, T)) + if sok != Int32(0): + if tot0 >= TGT * Int32(2): + if b3v >= Int32(0): + if T > GMIN: + t3c = _fmaf(Float32(b3v), w, SMIN) + if t3c < T: + T3 = t3c + bar(bar_id, nthr) + return (T, HIC, T3, Tk, SMIN, SMAX, w, sok, tot0, b1v, b2v, b3v) + + +@cute.jit +def tier_stage_warp( + xs, pos0, nlim, T, T3, s_st1, s_st2, s_cnt, cap1, cap2, lane, tier2: cutlass.Constexpr +): + lm = Int32(cute.arch.lanemask_lt()) + t2on = Int32(0) + if cutlass.const_expr(tier2): + if T3 > Float32(NEG_INF): + t2on = Int32(1) + off1 = Int32(0) + off2 = Int32(0) + m1s = [Int32(0)] * 4 + m2s = [Int32(0)] * 4 + vmax = Float32(NEG_INF) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + x = xs[q] + ok = p < nlim + a1 = Int32(0) + a2 = Int32(0) + if ok: + vmax = cute.arch.fmax(vmax, x) + if x >= T: + a1 = Int32(1) + elif t2on != Int32(0): + if x >= T3: + a2 = Int32(1) + m1s[q] = Int32(cute.arch.vote_ballot_sync(a1 != Int32(0))) + m2s[q] = Int32(cute.arch.vote_ballot_sync(a2 != Int32(0))) + tot1 = Int32(0) + tot2 = Int32(0) + for q in cutlass.range_constexpr(4): + tot1 = tot1 + Int32(cute.arch.popc(m1s[q])) + tot2 = tot2 + Int32(cute.arch.popc(m2s[q])) + b1 = Int32(0) + b2 = Int32(0) + if lane == Int32(0): + if tot1 > Int32(0): + b1 = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(0), tot1, sem="relaxed", scope="cta") + ) + if tot2 > Int32(0): + b2 = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(1), tot2, sem="relaxed", scope="cta") + ) + b1 = cute.arch.shuffle_sync(b1, Int32(0)) + b2 = cute.arch.shuffle_sync(b2, Int32(0)) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + if m1s[q] >> lane & Int32(1) != Int32(0): + slot = b1 + off1 + Int32(cute.arch.popc(m1s[q] & lm)) + if slot < cap1: + s_st1[slot] = pack_entry(u32_of_f32(xs[q]), p) + if m2s[q] >> lane & Int32(1) != Int32(0): + slot2 = b2 + off2 + Int32(cute.arch.popc(m2s[q] & lm)) + if slot2 < cap2: + s_st2[slot2] = pack_entry(u32_of_f32(xs[q]), p) + off1 = off1 + Int32(cute.arch.popc(m1s[q])) + off2 = off2 + Int32(cute.arch.popc(m2s[q])) + return vmax + + +@cute.jit +def grain_max_8lanes(vmax_lane): + v = vmax_lane + for o in [1, 2, 4]: + v = cute.arch.fmax(v, cute.arch.shuffle_sync_bfly(v, o)) + return v + + +@cute.jit +def floor_admit_warp(xs, pos0, nlim, thr_run, s_buf, s_cnt, cap, lane): + lm = Int32(cute.arch.lanemask_lt()) + ms = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + a = Int32(0) + if p < nlim: + if xs[q] >= thr_run: + a = Int32(1) + ms[q] = Int32(cute.arch.vote_ballot_sync(a != Int32(0))) + tot = Int32(0) + for q in cutlass.range_constexpr(4): + tot = tot + Int32(cute.arch.popc(ms[q])) + b = Int32(0) + if lane == Int32(0): + if tot > Int32(0): + b = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(0), tot, sem="relaxed", scope="cta") + ) + b = cute.arch.shuffle_sync(b, Int32(0)) + off = Int32(0) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + if ms[q] >> lane & Int32(1) != Int32(0): + slot = b + off + Int32(cute.arch.popc(ms[q] & lm)) + if slot < cap: + s_buf[slot] = pack_entry(u32_of_f32(xs[q]), p) + off = off + Int32(cute.arch.popc(ms[q])) + return tot + + +@cute.jit +def gc_arrive(addr): + fence_acq_rel_gpu() + return atom_add_u64(addr, Uint64(1)) + + +@cute.jit +def gc_pad(addr, P): + red_add_u64(addr, Uint64(GEN_ONE) - Uint64(P)) + + +@cute.jit +def gc_wait(addr, target, skew_ns): + v = ld_relaxed_u64(addr) + while v < target: + nanosleep(Int32(64)) + v = ld_relaxed_u64(addr) + fence_acq_rel_gpu() + return v + + +@cute.jit +def verdict_publish(addr, gen, status): + st_release_u64(addr, gen + Uint64(1) << Uint64(8) | Uint64(status)) + + +@cute.jit +def verdict_wait(addr, gen): + want = gen + Uint64(1) + v = ld_acquire_u64(addr) + while v >> Uint64(8) != want: + nanosleep(Int32(128)) + v = ld_acquire_u64(addr) + return Int32(Uint32(v & Uint64(255))) + + +@cute.jit +def skew_sleep(seed, salt, skew_ns): + if skew_ns > Int32(0): + h = Uint32(seed) * Uint32(2654435761) + Uint32(salt) * Uint32(2246822519) + h = h ^ h >> Uint32(15) + h = h * Uint32(739982445) + h = h ^ h >> Uint32(13) + ns = Int32(h % Uint32(skew_ns)) + nanosleep(ns) + + +@cute.jit +def _vbin(e, lo, sc, nb: cutlass.Constexpr): + x = f32_of_u32(entry_bits(e)) + b = f2u_rz((x - lo) * sc) + if b > Uint32(nb - 1): + b = Uint32(nb - 1) + return Int32(b) + + +@cute.jit +def _block_min_max_u32( + a_min, a_max, s_red, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + wmn = warp_min_u32(a_min) + wmx = warp_max_u32(a_max) + if lane == Int32(0): + s_red[wid] = wmn + s_red[Int32(NW) + wid] = wmx + bar(bar_id, nthr) + av = Uint32(4294967295) + cv = Uint32(0) + if lane < Int32(NW): + av = Uint32(s_red[lane]) + cv = Uint32(s_red[Int32(NW) + lane]) + rmn = warp_min_u32(av) + rmx = warp_max_u32(cv) + bar(bar_id, nthr) + return (rmn, rmx) + + +@cute.jit +def _warp_prefix(cnt_w, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + if lane == Int32(0): + s_wc[wid] = cnt_w + bar(bar_id, nthr) + ex = Int32(0) + tot = Int32(0) + for w_ in cutlass.range_constexpr(NW): + c = Int32(s_wc[w_]) + if Int32(w_) < wid: + ex = ex + c + tot = tot + c + bar(bar_id, nthr) + return (ex, tot) + + +@cute.jit +def select_topk_list( + lst, + C, + K, + out_e, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + src_gmem: cutlass.Constexpr, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + want_kth: cutlass.Constexpr = False, + prof=None, + rng_lo=None, + rng_hi=None, + hist_ready: cutlass.Constexpr = False, + fast_loops: cutlass.Constexpr = False, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + nout = C + if nout > K: + nout = K + kth = Uint64(18446744073709551615) + mret = Int32(0) + info = Int32(0) + if C <= K: + i = tid + while i < C: + out_e[i] = ld_entry(lst, i, src_gmem) + i = i + Int32(nthr) + bar(bar_id, nthr) + else: + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[0] = clk64() + lo = Float32(0.0) + hi = Float32(0.0) + if cutlass.const_expr(rng_lo is None): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + kmn = Uint32(4294967295) + kmx = Uint32(0) + i4 = (tid >> Int32(5)) * Int32(128) + lane + while i4 < C: + if cutlass.const_expr(fast_loops): + kbs = [] + for q in cutlass.range_constexpr(4): + icl = cutlass.min(i4 + Int32(32 * q), C - Int32(1)) + kbs.append(fkey_bits(entry_bits(ld_entry(lst, icl, src_gmem)))) + for q in cutlass.range_constexpr(4): + kmn = Uint32(cutlass.select_(kbs[q] < kmn, kbs[q], kmn)) + kmx = Uint32(cutlass.select_(kbs[q] > kmx, kbs[q], kmx)) + else: + for q in cutlass.range_constexpr(4): + iq = i4 + Int32(32 * q) + icl = iq + if icl > C - Int32(1): + icl = C - Int32(1) + kbq = fkey_bits(entry_bits(ld_entry(lst, icl, src_gmem))) + if kbq < kmn: + kmn = kbq + if kbq > kmx: + kmx = kbq + i4 = i4 + Int32(nthr * 4) + gmn, gmx = _block_min_max_u32(kmn, kmx, s_red, tid, nthr, bar_id) + lo = invkey(gmn) + hi = invkey(gmx) + else: + lo = rng_lo + hi = rng_hi + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[1] = clk64() + wv = (hi - lo) * Float32(1.0 / NB_SEL) + sc = Float32(0.0) + if wv > Float32(0.0): + if wv < Float32(3e38): + sc = cute.arch.rcp_approx(wv) + if cutlass.const_expr(not hist_ready): + if cutlass.const_expr(rng_lo is not None): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + i4 = (tid >> Int32(5)) * Int32(128) + lane + while i4 < C: + bq_ = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bq_[q] = _vbin(ld_entry(lst, icl, src_gmem), lo, sc, NB_SEL) + for q in cutlass.range_constexpr(4): + if i4 + Int32(32 * q) < C: + cute.arch.atomic_add( + s_hist.iterator + bq_[q], Int32(1), sem="relaxed", scope="cta" + ) + i4 = i4 + Int32(nthr * 4) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[2] = clk64() + find_cross(s_hist, K, tid, s_res, NB_SEL) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[3] = clk64() + B = s_res[RES_B] + above = s_res[RES_ABOVE] + m = s_res[RES_M] + need = K - above + mret = m + whole = Int32(0) + if need >= m: + whole = Int32(1) + keepc = Int32(0) + if whole == Int32(0): + if m <= Int32(QUADC): + keepc = Int32(1) + Bw = B + if whole != Int32(0): + Bw = B - Int32(1) + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + chunk = (C + Int32(nthr * 4) - Int32(1)) // Int32(nthr * 4) * Int32(128) + c0 = wid * chunk + c1 = c0 + chunk + if c1 > C: + c1 = C + cw = Int32(0) + cc = Int32(0) + i4 = c0 + lane + while i4 < c1: + if cutlass.const_expr(fast_loops): + bbs = [] + for q in cutlass.range_constexpr(4): + icl = cutlass.min(i4 + Int32(32 * q), C - Int32(1)) + bbs.append(_vbin(ld_entry(lst, icl, src_gmem), lo, sc, NB_SEL)) + for q in cutlass.range_constexpr(4): + vq = i4 + Int32(32 * q) < c1 + cw = cw + cutlass.select_(vq & (bbs[q] > Bw), Int32(1), Int32(0)) + cc = cc + cutlass.select_( + vq & (bbs[q] == B) & (bbs[q] <= Bw), Int32(1), Int32(0) + ) + else: + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bb = _vbin(ld_entry(lst, icl, src_gmem), lo, sc, NB_SEL) + if i4 + Int32(32 * q) < c1: + if bb > Bw: + cw = cw + Int32(1) + elif bb == B: + cc = cc + Int32(1) + i4 = i4 + Int32(128) + wcw = Int32(cute.arch.warp_redux_sync(cw, "add")) + wcc = Int32(cute.arch.warp_redux_sync(cc, "add")) + if lane == Int32(0): + s_wc[wid] = wcw + s_wc[Int32(NW) + wid] = wcc + bar(bar_id, nthr) + pw = Int32(0) + pc = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + pw = pw + Int32(s_wc[w_]) + pc = pc + Int32(s_wc[NW + w_]) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[4] = clk64() + base0 = c0 + while base0 < c1: + ed = [] + for q in cutlass.range_constexpr(4): + icl = base0 + Int32(32 * q) + lane + if icl > C - Int32(1): + icl = C - Int32(1) + ed.append(ld_entry(lst, icl, src_gmem)) + fws = [] + fcs = [] + if cutlass.const_expr(fast_loops): + for q in cutlass.range_constexpr(4): + vq = base0 + Int32(32 * q) + lane < c1 + bdf_ = _vbin(ed[q], lo, sc, NB_SEL) + fws.append(cutlass.select_(vq & (bdf_ > Bw), Int32(1), Int32(0))) + fcs.append(cutlass.select_(vq & (bdf_ == B) & (bdf_ <= Bw), Int32(1), Int32(0))) + for q in cutlass.range_constexpr(4): + fw = Int32(0) + fc = Int32(0) + if cutlass.const_expr(fast_loops): + fw = fws[q] + fc = fcs[q] + else: + if base0 + Int32(32 * q) + lane < c1: + bd_ = _vbin(ed[q], lo, sc, NB_SEL) + if bd_ > Bw: + fw = Int32(1) + elif bd_ == B: + fc = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fw != Int32(0))) + mc = Int32(cute.arch.vote_ballot_sync(fc != Int32(0))) + if fw != Int32(0): + out_e[pw + Int32(cute.arch.popc(mw & lm))] = ed[q] + if fc != Int32(0): + if keepc != Int32(0): + s_ck[pc + Int32(cute.arch.popc(mc & lm))] = entry_key(ed[q]) + pw = pw + Int32(cute.arch.popc(mw)) + pc = pc + Int32(cute.arch.popc(mc)) + base0 = base0 + Int32(128) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[5] = clk64() + if whole == Int32(0): + if m <= Int32(32): + info = Int32(1) + if wid == Int32(0): + kq = Uint64(0) + if lane < m: + kq = Uint64(s_ck[lane]) + khi = Uint32(kq >> Uint64(32)) + klo = Uint32(kq & Uint64(4294967295)) + r_ = Int32(0) + for j in cutlass.range_constexpr(32): + ohi = cute.arch.shuffle_sync(khi, Int32(j)) + olo = cute.arch.shuffle_sync(klo, Int32(j)) + if Int32(j) < m: + if ohi > khi: + r_ = r_ + Int32(1) + elif ohi == khi: + if olo > klo: + r_ = r_ + Int32(1) + if lane < m: + if r_ < need: + out_e[above + r_] = key_to_entry(kq) + bar(bar_id, nthr) + elif m <= Int32(QUADC): + info = Int32(1) + i = tid + while i < m: + ki = Uint64(s_ck[i]) + r_ = Int32(0) + jq = Int32(0) + while jq < m: + if Uint64(s_ck[jq]) > ki: + r_ = r_ + Int32(1) + jq = jq + Int32(1) + if r_ < need: + out_e[above + r_] = key_to_entry(ki) + i = i + Int32(nthr) + bar(bar_id, nthr) + else: + info = Int32(2) + pref = Uint64(0) + plen = Int32(0) + needr = need + done = Int32(0) + while done == Int32(0): + shift = Int32(56) - plen + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + i = tid + while i < C: + e2_ = ld_entry(lst, i, src_gmem) + if _vbin(e2_, lo, sc, NB_SEL) == B: + k2 = entry_key(e2_) + okp = Int32(1) + if plen > Int32(0): + if k2 >> Uint64(Int32(64) - plen) != pref: + okp = Int32(0) + if okp != Int32(0): + dg = Int32(Uint32(k2 >> Uint64(shift) & Uint64(255))) + cute.arch.atomic_add( + s_hist.iterator + dg, Int32(1), sem="relaxed", scope="cta" + ) + i = i + Int32(nthr) + bar(bar_id, nthr) + scan_cross0(s_hist, needr, tid, s_res, needr, needr, s_hist, nb=NBS, zero=True) + bar(bar_id, nthr) + dB = s_res[RES_B] + dab = s_res[RES_ABOVE] + dm = s_res[RES_M] + bar(bar_id, nthr) + pref = pref << Uint64(8) | Uint64(dB) + plen = plen + Int32(8) + needr = needr - dab + if needr >= dm: + done = Int32(1) + if plen >= Int32(64): + done = Int32(1) + thr = pref << Uint64(Int32(64) - plen) + if plen >= Int32(64): + thr = pref + nw2 = Int32(0) + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + if ii < c1: + e3_ = ld_entry(lst, ii, src_gmem) + if _vbin(e3_, lo, sc, NB_SEL) == B: + if entry_key(e3_) >= thr: + f2_ = Int32(1) + nw2 = nw2 + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(f2_ != Int32(0)))) + r0 = r0 + Int32(32) + ex2, tot2 = _warp_prefix(nw2, s_wc, tid, nthr, bar_id) + p2 = above + ex2 + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + e4 = Uint64(0) + if ii < c1: + e4 = ld_entry(lst, ii, src_gmem) + if _vbin(e4, lo, sc, NB_SEL) == B: + if entry_key(e4) >= thr: + f2_ = Int32(1) + m2 = Int32(cute.arch.vote_ballot_sync(f2_ != Int32(0))) + if f2_ != Int32(0): + out_e[p2 + Int32(cute.arch.popc(m2 & lm))] = e4 + p2 = p2 + Int32(cute.arch.popc(m2)) + r0 = r0 + Int32(32) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[6] = clk64() + if cutlass.const_expr(want_kth): + kmn64 = Uint64(18446744073709551615) + i = tid + while i < nout: + kk = entry_key(Uint64(out_e[i])) + if kk < kmn64: + kmn64 = kk + i = i + Int32(nthr) + hi32 = Uint32(kmn64 >> Uint64(32)) + lo32 = Uint32(kmn64 & Uint64(4294967295)) + wmh = warp_min_u32(hi32) + cand = Uint32(4294967295) + if hi32 == wmh: + cand = lo32 + wml = warp_min_u32(cand) + if lane == Int32(0): + s_red[wid] = wmh + s_red[Int32(NW) + wid] = wml + bar(bar_id, nthr) + bh = Uint32(4294967295) + bl = Uint32(4294967295) + for w_ in cutlass.range_constexpr(NW): + h_ = Uint32(s_red[w_]) + l_ = Uint32(s_red[Int32(NW) + Int32(w_)]) + if h_ < bh: + bh = h_ + bl = l_ + elif h_ == bh: + if l_ < bl: + bl = l_ + kth = Uint64(bh) << Uint64(32) | Uint64(bl) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[7] = clk64() + return (nout, kth, mret, info) + + +@cute.jit +def l2g_swa(i, pos, req, bt_swa, max_blocks_swa, swa_off_tokens): + st = pos - Int32(SWA - 1) + if st < Int32(0): + st = Int32(0) + loc = st + i + blk = loc // Int32(TPB_SWA) + bc = blk + if bc > max_blocks_swa - Int32(1): + bc = max_blocks_swa - Int32(1) + page = Int32(bt_swa[req, bc]) + g = Int32(-1) + if loc <= pos: + if blk < max_blocks_swa: + g = swa_off_tokens + page * Int32(TPB_SWA) + (loc - blk * Int32(TPB_SWA)) + return g + + +@cute.jit +def l2g_swa_local(loc, req, bt_swa, max_blocks_swa, swa_off_tokens): + blk = loc // Int32(TPB_SWA) + bc = blk + if bc > max_blocks_swa - Int32(1): + bc = max_blocks_swa - Int32(1) + if bc < Int32(0): + bc = Int32(0) + page = Int32(bt_swa[req, bc]) + g = Int32(-1) + if loc >= Int32(0): + if blk < max_blocks_swa: + g = swa_off_tokens + page * Int32(TPB_SWA) + (loc - blk * Int32(TPB_SWA)) + return g + + +@cute.jit +def l2g_compressed(c, req, bt_c, max_blocks_c, c_off_tokens): + blk = c // Int32(TPB_C) + bc = blk + if bc > max_blocks_c - Int32(1): + bc = max_blocks_c - Int32(1) + if bc < Int32(0): + bc = Int32(0) + page = Int32(bt_c[req, bc]) + g = Int32(-1) + if c >= Int32(0): + if blk < max_blocks_c: + g = c_off_tokens + page * Int32(TPB_C) + (c - blk * Int32(TPB_C)) + return g + + +@cute.jit +def block_excl_scan(v, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + inc = warp_incl_scan_add(v, lane) + if lane == Int32(31): + s_wc[wid] = inc + bar(bar_id, nthr) + base = Int32(0) + tot = Int32(0) + for w_ in cutlass.range_constexpr(NW): + c = Int32(s_wc[w_]) + if Int32(w_) < wid: + base = base + c + tot = tot + c + bar(bar_id, nthr) + return (base + inc - v, tot) + + +@cute.jit +def sample_window_range(t0, t1, SMP, SS2): + st = Int32(8) * SS2 + j0 = (t0 + st - Int32(1)) // st + j1 = (t1 + st - Int32(1)) // st + if j1 > SMP: + j1 = SMP + if j0 > j1: + j0 = j1 + return (j0, j1) + + +@cute.jit +def flatten_regions( + dst, dst_gmem: cutlass.Constexpr, reg_base, cap, s_pc, s_po, P, tid, nthr: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + p = wid + while p < P: + cnt = Int32(s_pc[p]) + off = Int32(s_po[p]) + src = reg_base + Int64(p) * Int64(cap) * Int64(8) + i = lane + while i < cnt: + e = ld_cg_u64(src + Int64(i) * Int64(8)) + if cutlass.const_expr(dst_gmem): + st_g_u64(dst.iterator.toint() + Int64(off + i) * Int64(8), e) + else: + dst[off + i] = e + i = i + Int32(32) + p = p + Int32(NW) + + +@cute.jit +def parts_table_warp0(desc_base, P, cap1, cap2, s_pt, s_tot, tid): + if tid < Int32(32): + lane = tid + ppl = P + Int32(31) >> Int32(5) + p0 = lane * ppl + a1 = [Int32(0)] * 8 + a2 = [Int32(0)] * 8 + for q in cutlass.range_constexpr(8): + pq = p0 + Int32(q) + pc = pq + if pc > P - Int32(1): + pc = P - Int32(1) + v1 = ld_cg_i32(desc_base + Int64(pc) * Int64(16)) + v2 = ld_cg_i32(desc_base + Int64(pc) * Int64(16) + Int64(4)) + ok = Int32(0) + if Int32(q) < ppl: + if pq < P: + ok = Int32(1) + a1[q] = v1 * ok + a2[q] = v2 * ok + s1 = Int32(0) + s2 = Int32(0) + n1 = Int32(0) + n2 = Int32(0) + o1 = Int32(0) + o2 = Int32(0) + for q in cutlass.range_constexpr(8): + c1_ = a1[q] + if c1_ > cap1: + c1_ = cap1 + o1 = o1 + Int32(1) + c2_ = a2[q] + if c2_ > cap2: + c2_ = cap2 + o2 = o2 + Int32(1) + s1 = s1 + c1_ + s2 = s2 + c2_ + n1 = n1 + a1[q] + n2 = n2 + a2[q] + i1 = warp_incl_scan_add(s1, lane) + i2 = warp_incl_scan_add(s2, lane) + t1s = cute.arch.shuffle_sync(i1, Int32(31)) + t2s = cute.arch.shuffle_sync(i2, Int32(31)) + b1 = i1 - s1 + b2 = i2 - s2 + t1s + for q in cutlass.range_constexpr(8): + pq = p0 + Int32(q) + c1_ = a1[q] + if c1_ > cap1: + c1_ = cap1 + c2_ = a2[q] + if c2_ > cap2: + c2_ = cap2 + if Int32(q) < ppl: + if pq < P: + s_pt[pq] = b1 + s_pt[P + pq] = b2 + b1 = b1 + c1_ + b2 = b2 + c2_ + tn1 = Int32(cute.arch.warp_redux_sync(n1, "add")) + tn2 = Int32(cute.arch.warp_redux_sync(n2, "add")) + to1 = Int32(cute.arch.warp_redux_sync(o1, "add")) + to2 = Int32(cute.arch.warp_redux_sync(o2, "add")) + if lane == Int32(0): + s_pt[Int32(2) * P] = t1s + t2s + s_tot[0] = t1s + s_tot[1] = t2s + s_tot[2] = tn1 + s_tot[3] = tn2 + s_tot[4] = to1 + s_tot[5] = to2 + + +@cute.jit +def build_owner_map( + s_own, s_pt, np_, C, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + i = tid + while i < C: + s_own[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + q = tid + while q < np_: + a = Int32(s_pt[q]) + if Int32(s_pt[q + Int32(1)]) > a: + s_own[a] = q + q = q + Int32(nthr) + bar(bar_id, nthr) + E = (C + Int32(nthr) - Int32(1)) // Int32(nthr) + b0 = tid * E + b1 = b0 + E + if b1 > C: + b1 = C + mx = Int32(0) + i = b0 + while i < b1: + v = Int32(s_own[i]) + if v > mx: + mx = v + i = i + Int32(1) + inc = mx + for o in [1, 2, 4, 8, 16]: + other = cute.arch.shuffle_sync_up(inc, o, mask_and_clamp=0) + if lane >= Int32(o): + if other > inc: + inc = other + if lane == Int32(31): + s_wc[wid] = inc + ex = cute.arch.shuffle_sync_up(inc, 1, mask_and_clamp=0) + if lane == Int32(0): + ex = Int32(0) + bar(bar_id, nthr) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + wv = Int32(s_wc[w_]) + if wv > ex: + ex = wv + run = ex + i = b0 + while i < b1: + v = Int32(s_own[i]) + if v > run: + run = v + s_own[i] = run + i = i + Int32(1) + bar(bar_id, nthr) + + +@cute.jit +def gather_parts( + dst, + dst_gmem: cutlass.Constexpr, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + with_hist, + tid, + nthr: cutlass.Constexpr, + s_own=None, +): + UNR = 8 + base = Int32(0) + while base < C: + es = [] + fs = [] + for u in cutlass.range_constexpr(UNR): + f = base + Int32(u * nthr) + tid + fl = f + if fl > C - Int32(1): + fl = C - Int32(1) + p_ = Int32(0) + if cutlass.const_expr(s_own is not None): + p_ = Int32(s_own[fl]) + else: + lo_ = Int32(0) + hi_ = np_ + for it in cutlass.range_constexpr(9): + mid = lo_ + hi_ >> Int32(1) + if Int32(s_pt[mid]) <= fl: + lo_ = mid + else: + hi_ = mid + p_ = lo_ + off = fl - Int32(s_pt[p_]) + src = reg1_base + (Int64(p_) * Int64(cap1) + Int64(off)) * Int64(8) + if p_ >= P: + src = reg2_base + (Int64(p_ - P) * Int64(cap2) + Int64(off)) * Int64(8) + es.append(ld_cg_u64(src)) + fs.append(f) + for u in cutlass.range_constexpr(UNR): + if fs[u] < C: + if cutlass.const_expr(dst_gmem): + st_g_u64(dst.iterator.toint() + Int64(fs[u]) * Int64(8), es[u]) + else: + dst[fs[u]] = es[u] + if with_hist != Int32(0): + b = _vbin(es[u], lo, sc, NB_SEL) + cute.arch.atomic_add(s_hist.iterator + b, Int32(1), sem="relaxed", scope="cta") + base = base + Int32(UNR * nthr) + + +@cute.jit +def finalize_tiers( + n, + P, + T, + T3, + HIC, + desc_base, + reg1_base, + reg2_base, + cap1, + cap2, + flat, + s_list, + sel_cap: cutlass.Constexpr, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + s_pt, + s_tot, + s_own, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + prof=None, +): + K = Int32(K_TOP) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[8] = gtimer() + parts_table_warp0(desc_base, P, cap1, cap2, s_pt, s_tot, tid) + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[9] = gtimer() + tot1s = Int32(s_tot[0]) + tot2s = Int32(s_tot[1]) + tot1 = Int32(s_tot[2]) + tot2 = Int32(s_tot[3]) + ovf1 = Int32(s_tot[4]) + ovf2 = Int32(s_tot[5]) + use = Int32(0) + if tot1 >= K: + if ovf1 == Int32(0): + use = Int32(1) + if use == Int32(0): + if T3 > Float32(NEG_INF): + if tot1 + tot2 >= K: + if ovf1 + ovf2 == Int32(0): + use = Int32(2) + C = Int32(0) + m = Int32(0) + nout = Int32(0) + info = Int32(0) + if use != Int32(0): + C = tot1s + np_ = P + lo = T + if use == Int32(2): + C = tot1s + tot2s + np_ = Int32(2) * P + lo = T3 + kth = Uint64(0) + rng = Int32(0) + if HIC > lo: + if HIC < Float32(3e38): + rng = Int32(1) + wv = (HIC - lo) * Float32(1.0 / NB_SEL) + sc = Float32(0.0) + if rng != Int32(0): + sc = cute.arch.rcp_approx(wv) + if C <= Int32(sel_cap): + build_owner_map(s_own, s_pt, np_, C, s_wc, tid, nthr, bar_id) + gather_parts( + s_list, + False, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + rng, + tid, + nthr, + s_own, + ) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[10] = gtimer() + if rng != Int32(0): + nout, kth, m, info = select_topk_list( + s_list, + C, + K, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + False, + nthr, + bar_id, + False, + None, + lo, + HIC, + True, + ) + else: + nout, kth, m, info = select_topk_list( + s_list, C, K, s_out, s_hist, s_ck, s_res, s_red, s_wc, tid, False, nthr, bar_id + ) + else: + gather_parts( + flat, + True, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + Int32(0), + tid, + nthr, + ) + fence_acq_rel_gpu() + bar(bar_id, nthr) + nout, kth, m, info = select_topk_list( + flat, C, K, s_out, s_hist, s_ck, s_res, s_red, s_wc, tid, True, nthr, bar_id + ) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[11] = gtimer() + return (use, C, m, tot1, tot2, nout, info) + + +@cute.jit +def write_row_outputs( + row, + n, + s_out, + nout, + short, + topk_out, + gidx, + bt_swa, + bt_c, + pos, + req, + mbs, + mbc, + swa_off, + c_off, + tid, + nthr: cutlass.Constexpr, +): + NQ = (640 + nthr - 1) // nthr + gv = [] + cols = [] + for q in cutlass.range_constexpr(NQ): + col = tid + Int32(q * nthr) + g = Int32(-1) + if col < Int32(SWA): + g = l2g_swa(col, pos, req, bt_swa, mbs, swa_off) + elif col < Int32(SWA + K_TOP): + i = col - Int32(SWA) + idx = Int32(-1) + if short != Int32(0): + if i < n: + idx = i + elif i < nout: + idx = entry_idx(Uint64(s_out[i])) + topk_out[row, i] = idx + g = l2g_compressed(idx, req, bt_c, mbc, c_off) + gv.append(g) + cols.append(col) + for q in cutlass.range_constexpr(NQ): + if cols[q] < Int32(SWA + K_TOP): + gidx[row, cols[q]] = gv[q] + + +@cute.jit +def grain_threshold( + gmax_addr, + ng, + s_list, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + i = tid + while i < ng: + gm = ld_cg_f32(gmax_addr + Int64(i) * Int64(4)) + s_list[i] = pack_entry(u32_of_f32(gm), i) + i = i + Int32(nthr) + bar(bar_id, nthr) + nout, kth, m, info = select_topk_list( + s_list, + ng, + Int32(K_TOP), + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + False, + nthr, + bar_id, + True, + ) + return invkey(Uint32(kth >> Uint64(32))) + + +@cute.jit +def recompute_grains( + n, + t0, + t1, + Tstar, + x_row, + gmax_addr, + fbr_addr, + s_cnt, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + if tid == Int32(0): + s_cnt[0] = Int32(0) + bar(bar_id, nthr) + g = (t0 >> Int32(5)) + wid + g1 = t1 + Int32(31) >> Int32(5) + while g < g1: + gm = ld_cg_f32(gmax_addr + Int64(g) * Int64(4)) + if gm >= Tstar: + p = g * Int32(32) + lane + a = Int32(0) + x = Float32(NEG_INF) + if p < t1: + if p < n: + x = ld_nc_f32(x_row + Int64(p) * Int64(4)) + if x >= Tstar: + a = Int32(1) + msk = Int32(cute.arch.vote_ballot_sync(a != Int32(0))) + tot = Int32(cute.arch.popc(msk)) + b = Int32(0) + if lane == Int32(0): + if tot > Int32(0): + b = Int32( + cute.arch.atomic_add( + s_cnt.iterator + Int32(0), tot, sem="relaxed", scope="cta" + ) + ) + b = cute.arch.shuffle_sync(b, Int32(0)) + if a != Int32(0): + slot = b + Int32(cute.arch.popc(msk & lm)) + st_g_u64(fbr_addr + Int64(slot) * Int64(8), pack_entry(u32_of_f32(x), p)) + g = g + Int32(NW) + bar(bar_id, nthr) + c = Int32(s_cnt[0]) + bar(bar_id, nthr) + return c + + +@cute.jit +def radix_round_local( + s_chunk, + cnt, + prefix, + plen, + shift, + mask, + s_rh, + nbins: cutlass.Constexpr, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + i = tid + while i < Int32(nbins): + s_rh[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + i = tid + while i < cnt: + kb = fkey(Float32(s_chunk[i])) + okp = Int32(1) + if plen > Int32(0): + if kb >> Uint32(Int32(32) - plen) != prefix: + okp = Int32(0) + if okp != Int32(0): + d = Int32(kb >> Uint32(shift) & Uint32(mask)) + cute.arch.atomic_add(s_rh.iterator + d, Int32(1), sem="relaxed", scope="cta") + i = i + Int32(nthr) + bar(bar_id, nthr) + + +@cute.jit +def radix_participant( + row, + part, + P, + n, + t0, + t1, + s_chunk, + ctr_fb, + fbh_row, + fbt_row, + s_rh, + s_res, + s_wc, + s_scal, + topk_out, + gidx, + bt_c, + req, + mbc, + c_off, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + cnt = t1 - t0 + if t1 > n: + cnt = n - t0 + need = Int32(K_TOP) + prefix = Uint32(0) + plen = Int32(0) + gF = Uint64(0) + for r in cutlass.range_constexpr(3): + bits = 11 if r < 2 else 10 + shift = 21 if r == 0 else 10 if r == 1 else 0 + nb_ = 1 << bits + radix_round_local( + s_chunk, cnt, prefix, plen, Int32(shift), Int32(nb_ - 1), s_rh, 2048, tid, nthr, bar_id + ) + i = tid + while i < Int32(nb_): + c = Int32(s_rh[i]) + if c != Int32(0): + red_add_u32(fbh_row + Int64(r * 2048 + i) * Int64(4), c) + i = i + Int32(nthr) + bar(bar_id, nthr) + if tid == Int32(0): + old = gc_arrive(ctr_fb) + if cutlass.const_expr(r == 0): + gF = old >> Uint64(GEN_SHIFT) + s_scal[6] = Int32(Uint32(gF & Uint64(4294967295))) + s_scal[7] = Int32(Uint32(gF >> Uint64(32))) + gF2 = Uint64(Uint32(s_scal[7])) << Uint64(32) | Uint64(Uint32(s_scal[6])) + gc_wait(ctr_fb, (gF2 << Uint64(GEN_SHIFT)) + Uint64(r + 1) * Uint64(P), Int32(0)) + bar(bar_id, nthr) + i = tid + while i < Int32(nb_): + s_rh[i] = ld_cg_i32(fbh_row + Int64(r * 2048 + i) * Int64(4)) + i = i + Int32(nthr) + if cutlass.const_expr(nb_ < 2048): + i = tid + Int32(nb_) + while i < Int32(2048): + s_rh[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + scan_cross0(s_rh, need, tid, s_res, need, need, s_rh, nb=2048, zero=True) + bar(bar_id, nthr) + dB = s_res[RES_B] + dab = s_res[RES_ABOVE] + bar(bar_id, nthr) + prefix = prefix << Uint32(bits) | Uint32(dB) + plen = plen + Int32(bits) + need = need - dab + kth = prefix + my_ab = Int32(0) + my_eq = Int32(0) + i = tid + while i < cnt: + kb = fkey(Float32(s_chunk[i])) + if kb > kth: + my_ab = my_ab + Int32(1) + elif kb == kth: + my_eq = my_eq + Int32(1) + i = i + Int32(nthr) + e_, tab = block_excl_scan(my_ab, s_wc, tid, nthr, bar_id) + e2_, teq = block_excl_scan(my_eq, s_wc, tid, nthr, bar_id) + if tid == Int32(0): + st_g_u64( + fbt_row + Int64(part) * Int64(8), + Uint64(Uint32(teq)) << Uint64(32) | Uint64(Uint32(tab)), + ) + gF3 = Uint64(Uint32(s_scal[7])) << Uint64(32) | Uint64(Uint32(s_scal[6])) + old = gc_arrive(ctr_fb) + if Int32(Uint32(old & Uint64(65535))) == Int32(4) * P - Int32(1): + gc_pad(ctr_fb, Int32(4) * P) + gc_wait(ctr_fb, (gF3 << Uint64(GEN_SHIFT)) + Uint64(4) * Uint64(P), Int32(0)) + bar(bar_id, nthr) + ab_t = Int32(0) + eq_t = Int32(0) + if tid < P: + w2 = ld_cg_u64(fbt_row + Int64(tid) * Int64(8)) + ab_t = Int32(Uint32(w2 & Uint64(4294967295))) + eq_t = Int32(Uint32(w2 >> Uint64(32))) + tie_ex, tie_tot_ = block_excl_scan(eq_t, s_wc, tid, nthr, bar_id) + q_t = need - tie_ex + if q_t < Int32(0): + q_t = Int32(0) + if q_t > eq_t: + q_t = eq_t + win_ex, win_tot_ = block_excl_scan(ab_t + q_t, s_wc, tid, nthr, bar_id) + if tid == part: + s_scal[0] = win_ex + s_scal[1] = q_t + bar(bar_id, nthr) + slot0 = Int32(s_scal[0]) + myq = Int32(s_scal[1]) + NW = nthr // 32 + chunk = (cnt + Int32(nthr) - Int32(1)) // Int32(nthr) * Int32(32) + c0 = wid * chunk + c1 = c0 + chunk + if c1 > cnt: + c1 = cnt + nwin = Int32(0) + ntie = Int32(0) + r0 = c0 + while r0 < c1: + ii = r0 + lane + fa = Int32(0) + fe = Int32(0) + if ii < c1: + kb = fkey(Float32(s_chunk[ii])) + if kb > kth: + fa = Int32(1) + elif kb == kth: + fe = Int32(1) + nwin = nwin + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(fa != Int32(0)))) + ntie = ntie + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(fe != Int32(0)))) + r0 = r0 + Int32(32) + if lane == Int32(0): + s_wc[wid] = ntie + bar(bar_id, nthr) + tex = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + tex = tex + Int32(s_wc[w_]) + bar(bar_id, nthr) + tq = myq - tex + if tq < Int32(0): + tq = Int32(0) + if tq > ntie: + tq = ntie + if lane == Int32(0): + s_wc[wid] = nwin + tq + bar(bar_id, nthr) + wex = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + wex = wex + Int32(s_wc[w_]) + bar(bar_id, nthr) + pw = slot0 + wex + tr = tex + r0 = c0 + while r0 < c1: + ii = r0 + lane + fa = Int32(0) + fe = Int32(0) + if ii < c1: + kb = fkey(Float32(s_chunk[ii])) + if kb > kth: + fa = Int32(1) + elif kb == kth: + fe = Int32(1) + me = Int32(cute.arch.vote_ballot_sync(fe != Int32(0))) + trank = tr + Int32(cute.arch.popc(me & lm)) + if fe != Int32(0): + if trank < myq: + fa = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fa != Int32(0))) + if fa != Int32(0): + slot = pw + Int32(cute.arch.popc(mw & lm)) + idx = t0 + ii + topk_out[row, slot] = idx + gidx[row, Int32(SWA) + slot] = l2g_compressed(idx, req, bt_c, mbc, c_off) + pw = pw + Int32(cute.arch.popc(mw)) + tr = tr + Int32(cute.arch.popc(me)) + r0 = r0 + Int32(32) + per = (Int32(3 * 2048) + P - Int32(1)) // P + z0 = part * per + z1 = z0 + per + if z1 > Int32(3 * 2048): + z1 = Int32(3 * 2048) + i = z0 + tid + while i < z1: + st_g_u32(fbh_row + Int64(i) * Int64(4), Int32(0)) + i = i + Int32(nthr) + bar(bar_id, nthr) + return (kth, need) + + +# ==================================================================================================================== +# L2 cache-policy constants for the indexer-K stream. +# ==================================================================================================================== + +POL_NONE, POL_EVICT_FIRST, POL_UNCHANGED, POL_FIRST_HALF, POL_NORMAL = (0, 1, 2, 3, 4) +POL_NAMES = { + POL_NONE: "none", + POL_EVICT_FIRST: "ef", + POL_UNCHANGED: "eu", + POL_FIRST_HALF: "ef50", + POL_NORMAL: "en", +} +_POL_ASM = { + POL_EVICT_FIRST: "createpolicy.fractional.L2::evict_first.b64 $0, 1.0;", + POL_UNCHANGED: "createpolicy.fractional.L2::evict_unchanged.b64 $0, 1.0;", + POL_FIRST_HALF: "createpolicy.fractional.L2::evict_first.L2::evict_unchanged.b64 $0, 0.5;", + POL_NORMAL: "createpolicy.fractional.L2::evict_normal.b64 $0, 1.0;", +} + + +@dsl_user_op +def make_l2_policy(policy: int, *, loc=None, ip=None) -> cutlass.Int64: + if policy not in _POL_ASM: + raise ValueError(f"no createpolicy for knob {policy}") + return cutlass.Int64( + llvm.inline_asm( + cutlass.Int64.mlir_type, + [], + _POL_ASM[policy], + "=l", + has_side_effects=True, + loc=loc, + ip=ip, + ) + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_op.py new file mode 100644 index 000000000000..218be37b15cc --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/large_batch_op.py @@ -0,0 +1,684 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA large-batch kernels, host side: DeepSeek-V4-Flash decode for many rows on B200 (SM100, 148 SMs). + +Two launches per call, back to back on the current stream. The first streams each row's indexer K cache (FP8 or MXFP4) +once, computes the indexer logits and selects the exact top-512 compressed positions in the stream (a floor learned +from the candidates already admitted in the row segment, the exact top-512 of the ones kept, exact fallbacks when too +many are kept), maps them to compressed-KV rows and publishes finished rows to a ready queue. The second, started with +programmatic dependent launch, runs the sparse MLA attention over the selected rows plus the 128-row sliding window and +the attention sink, claiming rows from the queue as they complete. + +``prepare`` builds the per-step state (the CTA schedule from the compressed lengths, the expanded sinks); +``run`` launches both kernels and writes ``topk`` (int32 compressed positions) and ``out`` (bf16). The kernels are +compiled on first use per device, outside CUDA-graph capture, or ahead of it by ``precompile``. + +Contract: +- A state belongs to one batch size and one caller. Its workspace (ready queue, selection scratch) is reset by the + kernels at the end of every launch, so launches that share a state, and ``prepare`` calls that refresh it, must be + stream-ordered. +- ``topk`` and ``out`` must not alias any input. ``out`` should be 32-byte aligned (every torch allocation is): the + attention epilogue of an FP4 spec writes 32-byte stores into it, and an ``out`` that is only 16-byte aligned runs the + narrower epilogue, a little slower. +- The indexer launch is persistent and needs all 148 SMs; it fails at launch on a partitioned device (MPS limits, + green contexts). +- Block tables must be contiguous int32 and hold valid page ids for every page a row touches: ``ceil(n / 32)`` + entries for the indexer and the compressed-KV tables, ``ceil(kv_len / 128)`` for the window table. +- The kernels do not trap. A schedule that does not match ``ctx_lens`` (a stale ``prepare``) makes the launch refuse + every row: ``topk`` is -1, ``out`` is zero and ``error_bits`` is non-zero. +""" + +from __future__ import annotations + +import threading +from dataclasses import dataclass + +import numpy as np +import torch + +from .config import ( + DS_V4_FLASH, + DS_V4_FLASH_FP4, + NUM_SMS, + SpecDsaConfig, + check_device, + supported_spec, +) + +__all__ = [ + "ERR_SCHEDULE", + "SpecDsaLargeBatchState", + "error_bits", + "is_supported", + "precompile", + "prepare", + "run", +] + +# Bit of ``error_bits`` (the kernel status word): the schedule does not match ctx_lens, i.e. prepare() was not +# refreshed for these lengths. +ERR_SCHEDULE = 1 + +# Schedule granule: a row costs ceil(n / SCHED_UNIT) units, at least SCHED_MIN_UNITS; the CTAs split the total evenly. +SCHED_UNIT = 256 +SCHED_MIN_UNITS = 128 +# Below SCHED_ALIGN_BATCH rows the schedule aligns the rows to the CTAs instead (see ``_schedule``), when that costs +# the busiest CTA at most SCHED_ALIGN_SLACK_PCT percent more stream work. It gains nothing measurable above that and +# costs about 60 us of host time per call. +SCHED_ALIGN_BATCH = 80 +SCHED_ALIGN_SLACK_PCT = 3 +# A CTA that streams pieces of several rows pays a fresh start of the selection (floor learning, four compactions) for +# every row it touches, on top of its stream time: about 6 us (BS 32) to 15 us (BS 256) per extra row segment, i.e. +# 14 to 41 schedule units. ``_balance_cuts`` moves the cuts so that stream units plus this cost are even over the CTAs. +# Per spec: (batch size, cost of a row segment in units) points, linear in between; no entry = the even split. +_SEG_UNITS: dict = { + DS_V4_FLASH_FP4.kernel_key: ((1, 14), (64, 14), (100, 24), (128, 38), (256, 28), (1024, 28)) +} +SELECT_BINS = 512 +SEGMENT_WORDS = 520 # int64 words per CTA and slot of the selection scratch +# int32 words per row of the ready queue; word AQ_ENTRY + k holds the k-th finished row. +READY_QUEUE_WORDS = 16 + +_KERNEL_CONFIG = dict( + phys_block_kv=DS_V4_FLASH.index_page_tokens, + desc=True, + sel_fin=True, + gath=True, + rot=True, + ahint=1, + late_release=False, + apace=10, + sel_idle_ns=128, + rsort=True, + policy=1, + cbins=SELECT_BINS, + trig0=768, + trig=1536, + attn=False, + kv_stages=4, + q_stages=2, +) + +# The knobs of the indexer kernel per spec (kernel_key). An FP4 K tile is half the bytes of an FP8 one: twice the +# stages keep the same bytes in flight. merge1: the last piece of a split row merges its row's +# pieces in one selection (two sources gathered at a time), not in one two-way selection per +# piece; fast_verdict: the schedule verdict at kernel entry issues its loads before its first branch; +# trig0: the first compaction of a segment waits for 1536 candidates; sel_fast / cmp_fast: the exact selection of the +# finalization and the in-stream compaction issue the independent work of an iteration together; sel_hand2: the selector +# warps finalize the last segment of a CTA into their own result list instead of waiting for the row warps to finish the +# earlier segment (the wait made the call 5 - 12 us slower at 40 - 92 rows). lim_loop / lim_loop2: the tile loops of the +# math warps / of the K-loading and UMMA warps end on one compare with a limit computed once per segment instead of +# the three-term condition; nolock: the two UMMA warps meet at the named barrier at a row change only, not after every +# tile; floor_mask: a math warp re-reads its candidate floor when (tile & floor_mask) == 0. All four are off here (the +# base table is the behaviour below the first variant) and on in the variants. +_KNOBS = { + DS_V4_FLASH.kernel_key: _KERNEL_CONFIG, + DS_V4_FLASH_FP4.kernel_key: dict( + _KERNEL_CONFIG, + kv_stages=8, + merge1=2, + fast_verdict=True, + trig0=1536, + sel_fast=True, + cmp_fast=True, + sel_hand2=True, + lim_loop=False, + lim_loop2=False, + nolock=False, + floor_mask=6, + ), +} + +# Batch-size ranges that run the indexer kernel with other knobs: (first batch size, overrides), the last range whose +# first batch size is not above the batch size wins. A range is a second compile of the same kernel class. The first +# range starts at the first large-batch size, so the base knobs above only serve launches forced below it. The four +# selector warps poll the candidate rings every sel_idle_ns: the polls compete with the TMA / MMA barriers of the SM and +# with the power budget (a 1.5 us sleep is 1 - 2 % faster at 100 - 150 rows and 4 - 7 % from 192 rows on), and six K +# stages (12 tiles in flight instead of 16) share the HBM more evenly between the SMs (the slowest SMs set the end of +# the call): with the loop-control and lockstep knobs that is 0.9 - 2 % faster than the base knobs at 27 - 56 rows +# (eight stages with those knobs are 3 - 4 % slower at 47 - 64 rows). At 512 rows and more the SM clock sits at about +# 1.4 GHz (power cap) and the stream is bound by the ~290 SM cycles a math warp spends per 128-position tile +# (hand-offs, the 64-head epilogue, floor read, compare, loop control), more than the HBM time of a tile (184 ns): the +# loop-control, lockstep and floor-read knobs take instructions off that chain (a 4 times rarer floor read from 192 +# rows: every 16th tile instead of every 4th), and from 768 rows the selector warps sleep 3 us between polls and the K +# stages are eight again (in the nsys protocol six stages are better at 384 - 767 rows, eight at 768 and more). +_VARIANTS = { + DS_V4_FLASH_FP4.kernel_key: ( + ( + DS_V4_FLASH_FP4.megakernel_max_batch + 1, + dict(sel_idle_ns=1536, kv_stages=6, lim_loop=True, lim_loop2=True, nolock=True), + ), + ( + 192, + dict( + sel_idle_ns=1536, + kv_stages=6, + lim_loop=True, + lim_loop2=True, + nolock=True, + floor_mask=30, + ), + ), + ( + 768, + dict(sel_idle_ns=3072, lim_loop=True, lim_loop2=True, nolock=True, floor_mask=30), + ), + ), +} + +# Knobs of the attention kernel per spec (kernel_key); no entry = the shipped kernel. exit_early: the "last CTA to leave +# resets the ready queue" accounting runs right after the CTA's final claim, off the critical path of the last row. +# wide_store: the output epilogue writes 32-byte stores, half the store instructions of 16-byte ones (the epilogue is +# ~3 us of the ~13 us row latency that ends every call); it needs a 32-byte aligned ``out``, so a second compile without +# it serves an ``out`` that is only 16-byte aligned. +_TAIL_KNOBS: dict = {DS_V4_FLASH_FP4.kernel_key: dict(exit_early=True, wide_store=True)} + +_lock = threading.Lock() +_engines: dict[tuple, dict] = {} + + +def _kernel_modules() -> tuple: + from . import large_batch, large_batch_lib + + return large_batch, large_batch_lib + + +def is_supported( + device: torch.device | None = None, config: SpecDsaConfig | None = None +) -> tuple[bool, str]: + """Whether the large-batch kernels serve ``config`` (default: DS-V4-Flash) on ``device``. + + That takes a supported spec with large-batch kernels, CuTe DSL installed and SM100 with all 148 SMs (one CTA per + SM). + """ + try: + if not supported_spec(config).large_batch: + return False, "the spec has no large-batch kernels" + except NotImplementedError as e: + return False, str(e) + return check_device(device) + + +def _check_batch_size(batch_size: int, config: SpecDsaConfig) -> None: + if not 1 <= batch_size <= config.max_batch: + raise ValueError(f"batch size {batch_size} not in [1, {config.max_batch}]") + + +def _device_index(device: torch.device) -> int: + device = torch.device(device) + return device.index if device.index is not None else torch.cuda.current_device() + + +def _engine(device: torch.device, config: SpecDsaConfig | None = None) -> dict: + config = supported_spec(config) + if not config.large_batch: + raise ValueError(f"{config.name} has no large-batch kernels") + key = (_device_index(device), config.kernel_key) + with _lock: + if key not in _engines: + lb, _ = _kernel_modules() + knobs = _KNOBS[config.kernel_key] + tail_knobs = _TAIL_KNOBS.get(config.kernel_key, {}) + _engines[key] = { + "indexer": lb.IndexerKernel(num_sms=NUM_SMS, config=config, **knobs), + "indexer_fn": None, + # [first batch size, kernel, compiled function] + "variants": [ + [ + first, + lb.IndexerKernel(num_sms=NUM_SMS, config=config, **{**knobs, **over}), + None, + ] + for first, over in _VARIANTS.get(config.kernel_key, ()) + ], + "tail": lb.AttentionTail(config=config, **tail_knobs), + "tail_fn": None, + # the tail for an ``out`` that is not 32-byte aligned (only with wide_store) + "tail_narrow": ( + lb.AttentionTail(config=config, **{**tail_knobs, "wide_store": False}) + if tail_knobs.get("wide_store") + else None + ), + "tail_narrow_fn": None, + } + return _engines[key] + + +def _not_compiled(e: dict) -> bool: + return ( + e["indexer_fn"] is None + or e["tail_fn"] is None + or (e.get("tail_narrow") is not None and e.get("tail_narrow_fn") is None) + or any(v[2] is None for v in e.get("variants", ())) + ) + + +def precompile(device: torch.device, config: SpecDsaConfig | None = None) -> None: + """Compile both kernels for ``device`` (the indexer kernel takes about a minute per knob range). + + The compiled kernels serve every batch size (a knob range of the indexer kernel is a compile of its own). Must run + outside CUDA-graph capture; ``run`` compiles on first use otherwise. + """ + lb, _ = _kernel_modules() + e = _engine(device, config) + with _lock: + if _not_compiled(e): + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "spec_dsa (large batch): compile the kernels (precompile) before " + "CUDA-graph capture" + ) + if e["indexer_fn"] is None: + e["indexer_fn"] = lb.compile_indexer(e["indexer"]) + for v in e.get("variants", ()): + if v[2] is None: + v[2] = lb.compile_indexer(v[1]) + if e["tail_fn"] is None: + e["tail_fn"] = lb.compile_tail(e["tail"]) + if e.get("tail_narrow") is not None and e.get("tail_narrow_fn") is None: + e["tail_narrow_fn"] = lb.compile_tail(e["tail_narrow"]) + + +@dataclass +class SpecDsaLargeBatchState: + """Per-step metadata and workspace of one caller; see ``prepare``. + + ``sched`` is the CTA schedule (row and unit offset where each CTA starts, one extra entry for the end), + ``sinks`` the per-row copy of the attention sink. ``ready_queue`` carries finished rows from the indexer to the + attention kernel. ``selection_ws`` and ``counters`` are per-row selection scratch; ``gidx`` holds the 640 KV row + indices of each row (128 window rows, then the selection). ``status`` is the kernel status word (``error_bits``). + ``lg``, ``req`` and ``stamps`` are kernel arguments that carry no state. ``config`` is the spec the state was built + for. + """ + + batch_size: int + sched: torch.Tensor + sinks: torch.Tensor + req: torch.Tensor + gidx: torch.Tensor + selection_ws: torch.Tensor + counters: torch.Tensor + ready_queue: torch.Tensor + stamps: torch.Tensor + lg: torch.Tensor + status: torch.Tensor + config: SpecDsaConfig + + +def _seg_units(config: SpecDsaConfig, batch_size: int) -> int: + """Cost of one row segment of a CTA in schedule units for ``batch_size`` rows (0 = not modelled).""" + points = _SEG_UNITS.get(config.kernel_key) + if not points: + return 0 + xs, ys = zip(*points) + return int(round(float(np.interp(batch_size, xs, ys)))) + + +def _balance_cuts(prefix: np.ndarray, num_ctas: int, seg_units: int) -> np.ndarray: + """CTA cuts (positions in the concatenated unit space, ``num_ctas + 1`` of them) that make the stream units of a CTA + plus ``seg_units`` per row it touches even over the CTAs. + + A CTA that covers ``[a, b)`` touches the row boundaries strictly inside plus one row, so its cost is + ``G(b) - G(a) + seg_units`` with ``G(x) = x + seg_units * #{row starts below x}``: an even split of ``G`` is the + balanced one. A cut that falls into the jump of ``G`` at a row start is placed on that row start. + """ + total = int(prefix[-1]) + inner = prefix[1:-1] # starts of rows 1..B-1 + s = np.arange(num_ctas + 1, dtype=np.float64) + y = s * ((total + seg_units * inner.size) / num_ctas) + if inner.size == 0: + x = y + else: + g_left = inner + seg_units * np.arange(inner.size) # G just below the start of row j + 1 + m = np.searchsorted(g_left + seg_units, y, side="left") # starts passed completely + x = y - seg_units * m + mc = np.minimum(m, inner.size - 1) + x = np.where((m < inner.size) & (y > g_left[mc]), inner[mc], x) + cuts = np.rint(x).astype(np.int64) + cuts[0], cuts[-1] = 0, total + return np.maximum.accumulate(cuts) + + +def _schedule(ctx_lens: list[int], num_ctas: int, seg_units: int = 0) -> np.ndarray: + """CTA schedule: CTA ``s`` starts at unit ``s * quota + min(s, rem)`` of the rows' concatenated unit ranges. + + Row ``r`` spans ``max(ceil(n_r / SCHED_UNIT), SCHED_MIN_UNITS)`` units; entry ``s`` is ``(row, unit offset in + the row)`` of that start (offset 0 for rows with fewer than ``SCHED_MIN_UNITS`` real units, which are never + split) and entry ``num_ctas`` is ``(batch_size, 0)``. With ``seg_units`` > 0 the cuts are moved by + ``_balance_cuts`` so that a CTA that touches more rows gets fewer units. + + With fewer than ``SCHED_ALIGN_BATCH`` rows the even split cuts rows at arbitrary units, and every extra piece of + a row is one more candidate list for the last finisher of the row to merge. ``_aligned_schedule`` then cuts the + rows into fewer pieces, one per CTA, and is used when it has fewer pieces and costs the busiest CTA at most + ``SCHED_ALIGN_SLACK_PCT`` percent more stream work. + """ + n = np.asarray(ctx_lens, dtype=np.int64) + batch = n.size + units = -(-n // SCHED_UNIT) + cost = np.maximum(units, SCHED_MIN_UNITS) + prefix = np.concatenate([[0], np.cumsum(cost)]) + quota, rem = divmod(int(prefix[-1]), num_ctas) + s = np.arange(num_ctas + 1, dtype=np.int64) + start = s * quota + np.minimum(s, rem) + if seg_units > 0: + start = _balance_cuts(prefix, num_ctas, seg_units) + row = np.searchsorted(prefix[1:], start, side="right") + inside = row < batch + row_c = np.minimum(row, batch - 1) + offset = np.where(inside & (units[row_c] >= SCHED_MIN_UNITS), start - prefix[row_c], 0) + sched = np.stack([np.where(inside, row, batch), offset], axis=1).astype(np.int32) + if batch >= SCHED_ALIGN_BATCH or batch > num_ctas: + return sched + aligned = _aligned_schedule(units, num_ctas) + pieces = int((aligned[:, 0] < batch).sum()) + # selection pieces of the even split: the rows it touches plus the rows it cuts in the middle + first_row, first_off = sched[:-1, 0], sched[:-1, 1] + next_row, next_off = sched[1:, 0], sched[1:, 1] + moved = (next_row != first_row) | (next_off != first_off) + even_pieces = int(((next_row - first_row) + (next_off > 0))[moved].sum()) + busiest_aligned = _busiest_cta_units(units, aligned, seg_units) + busiest_even = _busiest_cta_units(units, sched, seg_units) + if pieces < even_pieces and busiest_aligned * 100 <= busiest_even * ( + 100 + SCHED_ALIGN_SLACK_PCT + ): + return aligned + return sched + + +def _busiest_cta_units(units: np.ndarray, sched: np.ndarray, seg_units: int = 0) -> int: + """Stream units (``SCHED_UNIT`` positions of the rows, without the minimum cost) of the busiest CTA of ``sched``, + plus ``seg_units`` for every row segment of the CTA.""" + work = np.concatenate([[0], np.cumsum(units)]) + pos = work[sched[:, 0]] + sched[:, 1] + cost = np.diff(pos) + if seg_units > 0: + rows = (np.diff(sched[:, 0]) + (sched[1:, 1] > 0)).clip(min=0) + cost = cost + seg_units * np.where(cost > 0, rows, 0) + return int(cost.max()) + + +def _aligned_schedule(units: np.ndarray, num_ctas: int) -> np.ndarray: + """Cut every row of at least ``SCHED_MIN_UNITS`` units into the fewest equal pieces that fit one per CTA. + + A smallest piece size is searched such that the pieces of all rows (a shorter row stays in one piece) number at + most ``num_ctas``; a row of ``u`` units is cut into ``ceil(u / size)`` pieces that differ by at most one unit. + Returns the entries of ``_schedule`` for one piece per CTA, the unused CTAs and the end entry being + ``(batch_size, 0)``. + """ + batch = units.size + small = units < SCHED_MIN_UNITS + long_rows = units[~small] + lo = max(1, int(units[small].max()) if small.any() else 1) + hi = int(units.max()) + while lo < hi: + mid = (lo + hi) // 2 + if batch - long_rows.size + int(((long_rows + (mid - 1)) // mid).sum()) <= num_ctas: + hi = mid + else: + lo = mid + 1 + count = np.where(small, 1, (units + (lo - 1)) // lo) + row = np.repeat(np.arange(batch), count) + nth = np.arange(row.size) - (np.cumsum(count) - count)[row] # index of the piece inside its row + base, extra = np.divmod(units, count) + entries = np.full((num_ctas + 1, 2), 0, dtype=np.int32) + entries[:, 0] = batch + entries[: row.size, 0] = row + entries[: row.size, 1] = nth * base[row] + np.minimum(nth, extra[row]) + return entries + + +def _host_ints(t: torch.Tensor, count: int, name: str) -> list[int]: + v = t.reshape(-1) + if v.numel() < count: + raise ValueError(f"{name} has {v.numel()} entries, need {count}") + return [int(x) for x in v[:count].tolist()] + + +def prepare( + ctx_lens: torch.Tensor, + sinks: torch.Tensor, + state: SpecDsaLargeBatchState | None = None, + *, + config: SpecDsaConfig | None = None, +) -> SpecDsaLargeBatchState: + """Build (or refresh in place) the per-step state for ``B = ctx_lens.numel()`` rows. + + Args: + ctx_lens: int32 [B], compressed (indexer) length of each row, in [512, 2**18] for DS-V4-Flash. + sinks: float32 [64] on the target device, per-head attention sink. + state: a state of the same batch size to refresh; keeps its workspace and its spec. + config: the spec (default: DS-V4-Flash, the only one the kernels serve). + + The lengths are read on the host: pass a host (CPU) tensor to avoid a device-to-host copy; a device tensor works + but synchronizes. + """ + if state is not None: + if config is not None and config.kernel_key != state.config.kernel_key: + raise ValueError(f"state is for {state.config.name!r}, got {config.name!r}") + config = state.config + config = supported_spec(config) + batch_size = int(ctx_lens.numel()) + _check_batch_size(batch_size, config) + device = sinks.device + if device.type != "cuda": + raise ValueError("sinks must be a CUDA tensor") + if sinks.numel() != config.attn_heads: + raise ValueError(f"sinks must have {config.attn_heads} entries, got {tuple(sinks.shape)}") + ctx_host = _host_ints(ctx_lens, batch_size, "ctx_lens") + if any(not config.min_index_len <= n <= config.max_index_len for n in ctx_host): + raise ValueError( + f"compressed lengths must lie in [{config.min_index_len}, {config.max_index_len}]" + ) + if state is not None and state.batch_size != batch_size: + raise ValueError(f"state is for {state.batch_size} rows, got {batch_size}") + _, lib = _kernel_modules() + if state is None: + ready_queue = torch.zeros((batch_size, READY_QUEUE_WORDS), dtype=torch.int32, device=device) + ready_queue.view(-1)[lib.AQ_ENTRY : lib.AQ_ENTRY + batch_size] = -1 + state = SpecDsaLargeBatchState( + batch_size=batch_size, + sched=torch.empty((NUM_SMS + 1, 2), dtype=torch.int32, device=device), + sinks=torch.empty((batch_size, config.attn_heads), dtype=torch.float32, device=device), + req=torch.arange(batch_size, dtype=torch.int32, device=device), + gidx=torch.full( + (batch_size, config.selected_rows), -9, dtype=torch.int32, device=device + ), + selection_ws=torch.zeros(3 * NUM_SMS * SEGMENT_WORDS, dtype=torch.int64, device=device), + counters=torch.zeros(batch_size * 16, dtype=torch.int64, device=device), + ready_queue=ready_queue, + stamps=torch.zeros(NUM_SMS * 256, dtype=torch.int64, device=device), + lg=torch.empty((1, 256), dtype=torch.float32, device=device), + status=torch.full((4,), -7, dtype=torch.int32, device=device), + config=config, + ) + state.sched.copy_( + torch.from_numpy(_schedule(ctx_host, NUM_SMS, _seg_units(config, batch_size))), + non_blocking=True, + ) + state.sinks.copy_(sinks.reshape(1, config.attn_heads).expand(batch_size, config.attn_heads)) + return state + + +def error_bits(state: SpecDsaLargeBatchState) -> torch.Tensor: + """Status word of the last launch of ``state`` (``ERR_*`` bits): an int32 [1] device view, no sync. + + Zero means the last launch ran normally; a fresh state reads -7 until its first launch. + """ + return state.status[:1] + + +def _check_numel(name: str, t: torch.Tensor, numel: int, dtype: torch.dtype | None = None) -> None: + if t.numel() != numel or (dtype is not None and t.dtype != dtype) or not t.is_contiguous(): + raise ValueError( + f"{name} must be contiguous with {numel} elements" + + (f" of {dtype}" if dtype is not None else "") + + f", got {t.dtype} {tuple(t.shape)}" + ) + + +def _check_rows(name: str, t: torch.Tensor, row_bytes: int) -> None: + if t.element_size() != 1 or t.dim() < 2 or t.shape[-1] != row_bytes or not t.is_contiguous(): + raise ValueError( + f"{name} must be a contiguous 1-byte tensor with {row_bytes}-byte rows, " + f"got {t.dtype} {tuple(t.shape)}" + ) + + +def _check_block_table(name: str, t: torch.Tensor, batch_size: int) -> None: + if t.dtype != torch.int32 or t.dim() != 2 or t.shape[0] < batch_size or not t.is_contiguous(): + raise ValueError( + f"{name} must be a contiguous int32 [B, pages] tensor with B >= {batch_size}, " + f"got {t.dtype} {tuple(t.shape)}" + ) + + +def run( + state: SpecDsaLargeBatchState, + q_idx: torch.Tensor, + w_idx: torch.Tensor, + k_cache: torch.Tensor, + idx_block_table: torch.Tensor, + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + topk: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + q_scale: torch.Tensor | None = None, +) -> None: + """Launch the two kernels on the current stream. + + Args: + state: from ``prepare`` for these lengths. + q_idx: float8_e4m3fn [B, 64, 128] (or [B, 1, 64, 128]), indexer queries; for an FP4 spec packed E2M1, 1 byte + per two values ([B, 64, 64]). + w_idx: float32 [B, 64], indexer head weights. + k_cache: uint8 [pages, ...] with ``config.index_page_bytes`` bytes per page: 4224 for FP8 (32 x 128 FP8 values, + then 32 float32 scales), 2176 for FP4 (32 x 64 bytes of E2M1 pairs, then 32 int32 of four UE8M0 scales, one + per 32 values). + idx_block_table: int32 [B, pages], indexer K pages of each row. + ctx_lens: int32 [B] on the device, the same lengths as given to ``prepare``. + kv_lens: int32 [B] on the device, uncompressed length of each row (>= 128); the window is its last 128 + positions. + q_att: float8_e4m3fn [B, 64, 512], attention queries. + swa_pool: float8_e4m3fn [..., 512], sliding-window KV rows (128 rows per page); bt_swa: int32 [B, pages]. + c_pool: float8_e4m3fn [..., 512], compressed KV rows (32 rows per page); bt_c: int32 [B, pages]. + topk: int32 [B, 512] output, the selected compressed positions (in no particular order). + out: bfloat16 [B, 64 * 512] output (32-byte aligned for the fastest epilogue; 16 bytes is enough). + softmax_scale: attention softmax scale (default: ``1 / sqrt(kv_dim)`` of the spec). + q_scale: int32 [B, 64] (or [B, 1, 64]), the four UE8M0 query scales of each head in one int32 (FP4 specs only). + + The shapes are those of the DS-V4-Flash spec; ``state.config`` gives the sizes the checks use. + """ + config = state.config + b = state.batch_size + fp4 = config.index_k_dtype == "fp4" + if softmax_scale is None: + softmax_scale = config.default_softmax_scale + q_values = config.index_head_dim // 2 if fp4 else config.index_head_dim + _check_numel("q_idx", q_idx, b * config.index_heads * q_values) + if fp4: + if q_scale is None: + raise ValueError("an FP4 spec needs q_scale (the UE8M0 scales of the FP4 queries)") + _check_numel("q_scale", q_scale, b * config.index_heads, torch.int32) + elif q_scale is not None: + raise ValueError("q_scale belongs to FP4 specs") + if q_idx.element_size() != 1: + raise ValueError(f"q_idx must be FP8 (1 byte per value), got {q_idx.dtype}") + _check_numel("w_idx", w_idx, b * config.index_heads, torch.float32) + _check_numel("q_att", q_att, b * config.attn_heads * config.kv_dim) + if q_att.element_size() != 1: + raise ValueError(f"q_att must be FP8 (1 byte per value), got {q_att.dtype}") + _check_numel("ctx_lens", ctx_lens, b, torch.int32) + _check_numel("kv_lens", kv_lens, b, torch.int32) + _check_numel("topk", topk, b * config.topk, torch.int32) + _check_numel("out", out, b * config.attn_heads * config.kv_dim, torch.bfloat16) + _check_rows("swa_pool", swa_pool, config.kv_dim) + _check_rows("c_pool", c_pool, config.kv_dim) + for name, table in (("idx_block_table", idx_block_table), ("bt_swa", bt_swa), ("bt_c", bt_c)): + _check_block_table(name, table, b) + pages = int(k_cache.shape[0]) + if k_cache.element_size() != 1 or k_cache.numel() != pages * config.index_page_bytes: + raise ValueError( + f"k_cache must hold {config.index_page_bytes} bytes per page, got {tuple(k_cache.shape)}" + ) + e = _engine(q_idx.device, config) + if _not_compiled(e): + precompile(q_idx.device, config) + indexer_fn = e["indexer_fn"] + for first, _, fn in e.get("variants", ()): + if b >= first: + indexer_fn = fn + q_att8 = q_att.view(torch.uint8).view(b, config.attn_heads, config.kv_dim) + swa8 = swa_pool.view(torch.uint8).view(-1, config.kv_dim) + c8 = c_pool.view(torch.uint8).view(-1, config.kv_dim) + out3 = out.view(b, config.attn_heads, config.kv_dim) + indexer_fn( + k_cache.view(pages, -1), + q_idx.reshape(-1) + .as_strided( + (config.index_heads, q_values, b), + (q_values, 1, config.index_heads * q_values), + ) + .view(torch.uint8), + w_idx.reshape(-1).as_strided((config.index_heads, b), (1, config.index_heads)), + state.lg, + idx_block_table[:b], + ctx_lens, + state.sched, + kv_lens, + state.req, + bt_swa[:b], + bt_c[:b], + topk, + state.gidx, + state.selection_ws, + state.counters, + state.ready_queue, + state.stamps, + q_att8, + swa8, + c8, + state.sinks, + out3, + state.status, + softmax_scale, + pages, + b, + *( + (q_scale.reshape(-1).as_strided((config.index_heads, b), (1, config.index_heads)),) + if fp4 + else () + ), + ) + tail_fn = e["tail_fn"] + if e.get("tail_narrow") is not None and out.data_ptr() % 32: + tail_fn = e["tail_narrow_fn"] + tail_fn( + q_att8, + swa8, + c8, + state.gidx, + state.sinks, + out3, + state.ready_queue, + softmax_scale, + NUM_SMS, + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel.py new file mode 100644 index 000000000000..6fc43d174581 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel.py @@ -0,0 +1,10071 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""specDSA megakernel (CuTe DSL, SM100): the cooperative launch, the indexer-K stream, the sampled threshold, +candidate publication and the teams' exact top-512 selection, with the row split descriptors, the selection entry points +and the host entry points ``SpecDsaMegakernel`` and ``compile_mk`` used by ``megakernel_op.py``. + +The kernel is specialized for the ``DS_V4_FLASH`` spec of ``config.py``: its structural constants are defined from +it and ``SpecDsaMegakernel`` rejects a config with another ``kernel_key``. +""" + +from __future__ import annotations + +import dataclasses +import math + +import cuda.bindings.driver as cuda_driver +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cudax +import cutlass.pipeline as pipeline +import cutlass.utils.blackwell_helpers as sm100_utils +import cutlass.utils.blockscaled_layout as blockscaled_utils +import torch +from cutlass import Float4E2M1FN, Float8E8M0FNU, Float32, Int32, Int64, Uint32, Uint64 +from cutlass.cute.nvgpu import cpasync, tcgen05 +from cutlass.cute.nvgpu.tcgen05 import find_tmem_tensor_col_offset +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.experimental import primitives as prims +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait + +from . import megakernel_attention as A +from . import megakernel_lib as L +from .config import DS_V4_FLASH as SPEC +from .config import DS_V4_FLASH_FP4 as SPEC_FP4 +from .config import NUM_SMS, SpecDsaConfig, require_built_for + +# ==================================================================================================================== +# Per-row split descriptors (which stream CTA streams which 256-position splits and pages of a row), built on the +# device by ``build_desc_device``. +# ==================================================================================================================== + +K_TOP = SPEC.topk +SPLIT_TOK = 256 +TILE = 128 +MAXS = 8 +N_MAX = SPEC.max_index_len +PLAN = dict(aim_base=1024, sfac=16, amin=1792, sd_en=0, r_const=64, scap=8192) +DESC_WORDS = 32 +MAGIC = 20912 + + +@cute.jit +def _or_reduce(v): + return Int32(cute.arch.warp_redux_sync(v, "or")) + + +@cute.jit +def _desc_body( + mCtx: cute.Tensor, + mBt: cute.Tensor, + mDesc: cute.Tensor, + ns_ctas: cutlass.Constexpr[int], + rot: cutlass.Constexpr[int], + zlast: cutlass.Constexpr[bool], + zc: cutlass.Constexpr[int], + ladder_words: cutlass.Constexpr[bool], +): + c, _, _ = cute.arch.block_idx() + lane, _, _ = cute.arch.thread_idx() + out = Int32(0) + if c < Int32(ns_ctas): + n = mCtx[0] + bt_cols = cute.size(mBt, mode=[1]) + n_ok = n + if n < Int32(0) or n > Int32(N_MAX): + n_ok = Int32(0) + nsplit = (n_ok + Int32(SPLIT_TOK - 1)) // Int32(SPLIT_TOK) + # this row's range is the one of virtual CTA (c + rot) mod ns_ctas + cv = (c + Int32(rot)) % Int32(ns_ctas) + s0 = cv * nsplit // Int32(ns_ctas) + s1 = (cv + Int32(1)) * nsplit // Int32(ns_ctas) + if cutlass.const_expr(zc >= 0): + # ranges over ns_ctas - 1 CTAs; CTA zc gets an empty range + cz_ = c + if c > Int32(zc): + cz_ = c - Int32(1) + if cutlass.const_expr(rot % (ns_ctas - 1) != 0): + # rows rotate which CTA holds which range (knob drot): the CTAs that hold the dense end of the + # sequence differ from row to row + cz_ = (cz_ + Int32(rot)) % Int32(ns_ctas - 1) + s0 = cz_ * nsplit // Int32(ns_ctas - 1) + s1 = (cz_ + Int32(1)) * nsplit // Int32(ns_ctas - 1) + if c == Int32(zc): + s0 = nsplit + s1 = nsplit + if cutlass.const_expr(zlast): + # ranges over ns_ctas - 1 CTAs; CTA ns_ctas - 1 (the early T server) gets an empty range + cl_ = c + if cutlass.const_expr(rot % (ns_ctas - 1) != 0): + cl_ = (c + Int32(rot)) % Int32(ns_ctas - 1) + s0 = cl_ * nsplit // Int32(ns_ctas - 1) + s1 = (cl_ + Int32(1)) * nsplit // Int32(ns_ctas - 1) + if c == Int32(ns_ctas - 1): + s0 = nsplit + s1 = nsplit + ns = s1 - s0 + ntile = (n_ok + Int32(TILE - 1)) // Int32(TILE) + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n_ok, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + t = lane + gt = Int32(2) * s0 + t + inchunk = t < Int32(2) * ns + valid = inchunk and gt < ntile + j0 = (Int32(TILE) * gt + wst - Int32(1)) // wst + win = valid and j0 < SMP and (j0 * wst < Int32(TILE) * (gt + Int32(1))) + lm = Int32(cute.arch.lanemask_lt()) + bw = Int32(cute.arch.vote_ballot_sync(win)) + bv = Int32(cute.arch.vote_ballot_sync(valid and (not win))) + bi = Int32(cute.arch.vote_ballot_sync(inchunk and (not valid))) + nW = Int32(cute.arch.popc(bw)) + m = Int32(cute.arch.popc(bv)) + nv_ = Int32(cute.arch.popc(bw | bv)) + pos = Int32(0) + if win: + pos = Int32(cute.arch.popc(bw & lm)) + elif valid: + r = m - Int32(1) - Int32(cute.arch.popc(bv & lm)) + k = r % Int32(4) + base = Int32(0) + for kk in cutlass.range_constexpr(3): + ck = (m - Int32(kk) + Int32(3)) // Int32(4) + if Int32(kk) < k: + base = base + ck + pos = nW + base + r // Int32(4) + else: + pos = nW + m + Int32(cute.arch.popc(bi & lm)) + g = pos % Int32(2) + ti = pos // Int32(2) + o0 = Int32(0) + o1 = Int32(0) + if inchunk: + if g == Int32(0): + o0 = t << Int32(4) * ti + else: + o1 = t << Int32(4) * ti + ord0 = _or_reduce(o0) + ord1 = _or_reduce(o1) + wl = lane - Int32(8) + task = wl // Int32(8) + grp = wl % Int32(8) // Int32(4) + kp = wl % Int32(4) + tsel = Int32(0) + if grp == Int32(0): + tsel = ord0 >> Int32(4) * task & Int32(15) + else: + tsel = ord1 >> Int32(4) * task & Int32(15) + gts = Int32(2) * s0 + tsel + pg = Int32(4) * gts + kp + page = Int32(0) + if lane >= Int32(8): + if task < ns: + if gts < ntile: + if pg < bt_cols: + page = mBt[0, pg] + if lane == Int32(0): + out = s0 + elif lane == Int32(1): + out = ns + elif lane == Int32(2): + out = n + elif lane == Int32(3): + out = ord0 + elif lane == Int32(4): + out = ord1 + elif lane == Int32(5): + out = nW + elif lane == Int32(6): + if cutlass.const_expr(ladder_words): + out = SMP + else: + out = nv_ + elif lane == Int32(7): + if cutlass.const_expr(ladder_words): + out = SS2 + else: + out = Int32(MAGIC) | Int32(ns_ctas << 16) + else: + out = page + mDesc[c * Int32(DESC_WORDS) + lane] = out + + +# The descriptor kernel of the FP8 spec and the one of the FP4 spec (``ladder_words``: words 6 / 7 hold SMP / SS2 of the +# sampling ladder) are two kernels over one body, so that the FP8 kernel keeps its signature and the code it generated +# before the FP4 spec existed. +@cute.kernel +def _desc_kernel( + mCtx: cute.Tensor, + mBt: cute.Tensor, + mDesc: cute.Tensor, + ns_ctas: cutlass.Constexpr[int], + rot: cutlass.Constexpr[int] = 0, + zlast: cutlass.Constexpr[bool] = False, + zc: cutlass.Constexpr[int] = -1, +): + _desc_body(mCtx, mBt, mDesc, ns_ctas, rot, zlast, zc, False) + + +@cute.kernel +def _desc_kernel_fp4( + mCtx: cute.Tensor, + mBt: cute.Tensor, + mDesc: cute.Tensor, + ns_ctas: cutlass.Constexpr[int], + rot: cutlass.Constexpr[int] = 0, + zlast: cutlass.Constexpr[bool] = False, + zc: cutlass.Constexpr[int] = -1, +): + _desc_body(mCtx, mBt, mDesc, ns_ctas, rot, zlast, zc, True) + + +@cute.jit +def _launch_desc( + ctx: cute.Tensor, + bt: cute.Tensor, + desc: cute.Tensor, + num_sms: cutlass.Constexpr[int], + ns_ctas: cutlass.Constexpr[int], + rot: cutlass.Constexpr[int], + zlast: cutlass.Constexpr[bool], + zc: cutlass.Constexpr[int], + stream: cuda_driver.CUstream, +): + _desc_kernel(ctx, bt, desc, ns_ctas, rot, zlast, zc).launch( + grid=(num_sms, 1, 1), block=[32, 1, 1], stream=stream + ) + + +@cute.jit +def _launch_desc_fp4( + ctx: cute.Tensor, + bt: cute.Tensor, + desc: cute.Tensor, + num_sms: cutlass.Constexpr[int], + ns_ctas: cutlass.Constexpr[int], + rot: cutlass.Constexpr[int], + zlast: cutlass.Constexpr[bool], + zc: cutlass.Constexpr[int], + stream: cuda_driver.CUstream, +): + _desc_kernel_fp4(ctx, bt, desc, ns_ctas, rot, zlast, zc).launch( + grid=(num_sms, 1, 1), block=[32, 1, 1], stream=stream + ) + + +_COMPILED_DESC = {} + + +def compile_desc( + num_sms: int, + ns_ctas: int, + rot: int = 0, + zlast: bool = False, + zc: int = -1, + ladder_words: bool = False, +): + # the FP8 call (ladder_words False) has the signature, the cache key and the symbol it had before the FP4 spec + key = (num_sms, ns_ctas, rot, zlast, zc) + ((True,) if ladder_words else ()) + if key not in _COMPILED_DESC: + rt = cute.runtime + s = cute.sym_int + fk = [ + rt.make_fake_compact_tensor(cutlass.Int32, (1,), stride_order=(0,)), + rt.make_fake_compact_tensor(cutlass.Int32, (1, s()), stride_order=(1, 0)), + rt.make_fake_compact_tensor(cutlass.Int32, (s(),), stride_order=(0,)), + ] + _COMPILED_DESC[key] = cute.compile( + _launch_desc_fp4 if ladder_words else _launch_desc, + *fk, + num_sms, + ns_ctas, + rot, + zlast, + zc, + rt.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + return _COMPILED_DESC[key] + + +def build_desc_device( + ctx_lens: torch.Tensor, + bt_row: torch.Tensor, + desc: torch.Tensor, + num_sms: int, + ns_ctas: int, + rot: int = 0, + zlast: bool = False, + zc: int = -1, + ladder_words: bool = False, +): + """Write one row's split descriptor into ``desc`` on the device from its compressed length and indexer + block-table row; ``ladder_words``: words 6 / 7 hold SMP / SS2 of the sampling ladder (FP4 megakernel). + """ + assert desc.numel() >= num_sms * DESC_WORDS and desc.dtype == torch.int32 + compile_desc(num_sms, ns_ctas, rot % ns_ctas, bool(zlast), int(zc), bool(ladder_words))( + ctx_lens[0:1], bt_row, desc + ) + + +def build_desc_host( + n: int, bt_row: torch.Tensor, ns_ctas: int, num_sms: int, smp: int, ss2: int +) -> torch.Tensor: + n_ok = n if 0 <= n <= N_MAX else 0 + nsplit = (n_ok + SPLIT_TOK - 1) // SPLIT_TOK + ntile = (n_ok + TILE - 1) // TILE + wst = 8 * ss2 + bt = bt_row.reshape(-1).cpu().tolist() + d = torch.zeros((num_sms, DESC_WORDS), dtype=torch.int64) + for c in range(ns_ctas): + s0 = c * nsplit // ns_ctas + ns = (c + 1) * nsplit // ns_ctas - s0 + tiles = list(range(2 * ns)) + valid = [2 * s0 + t < ntile for t in tiles] + win = [] + for t in tiles: + gt = 2 * s0 + t + j0 = (TILE * gt + wst - 1) // wst + win.append(valid[t] and j0 < smp and (j0 * wst < TILE * (gt + 1))) + W = [t for t in tiles if win[t]] + R = [t for t in tiles if valid[t] and (not win[t])][::-1] + R = [x for k in range(4) for x in R[k::4]] + Inv = [t for t in tiles if not valid[t]] + order = W + R + Inv + o = [0, 0] + for p, t in enumerate(order): + o[p % 2] |= t << 4 * (p // 2) + d[c, 0:8] = torch.tensor( + [s0, ns, n, o[0], o[1], len(W), len(W) + len(R), MAGIC | ns_ctas << 16] + ) + for task in range(3): + for g in range(2): + p = 2 * task + g + if task < ns and p < len(order): + t = order[p] + gt = 2 * s0 + t + for k in range(4): + pg = 4 * gt + k + d[c, 8 + 8 * task + 4 * g + k] = ( + bt[pg] if gt < ntile and pg < len(bt) else 0 + ) + d = d.to(torch.int64) + d = torch.where(d >= 2**31, d - 2**32, d) + return d.to(torch.int32).view(-1) + + +# ==================================================================================================================== +# Selection constants and the bin scale of the threshold band. +# ==================================================================================================================== + +NB_SEL = L.NB_SEL +QUADC = L.QUADC +NBS = L.NBS + + +@cute.jit +def bin_scale(lo: Float32, hi: Float32): + wv = (hi - lo) * Float32(1.0 / NB_SEL) + sc = Float32(0.0) + if wv > Float32(0.0): + if wv < Float32(3e38): + sc = cute.arch.rcp_approx(wv) + return sc + + +@cute.jit +def _pst(prof, slot, tid): + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + cutlass.inttoptr( + prof + cutlass.Int64(slot) * cutlass.Int64(8), mem_space=1, dtype=cutlass.Int64 + ).store(cutlass.Int64(L.gtimer())) + + +@cute.jit +def select_slots( + lst, + C, + K, + out_s, + s_hist, + s_ck, + s_cs, + s_res, + s_red, + s_wc, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + rng_lo, + rng_hi, + hist_ready, + prof=None, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + nout = C + if nout > K: + nout = K + mret = Int32(0) + info = Int32(0) + Bret = Int32(-1) + if C <= K: + i = tid + while i < C: + out_s[i] = i + i = i + Int32(nthr) + if tid < Int32(NB_SEL): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + L.bar(bar_id, nthr) + else: + lo = rng_lo + hi = rng_hi + sc = bin_scale(lo, hi) + if hist_ready == Int32(0): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + L.bar(bar_id, nthr) + i4 = (tid >> Int32(5)) * Int32(128) + lane + while i4 < C: + bq_ = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bq_[q] = L._vbin(Uint64(lst[icl]), lo, sc, NB_SEL) + for q in cutlass.range_constexpr(4): + if i4 + Int32(32 * q) < C: + cute.arch.red( + s_hist.iterator + bq_[q], + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + i4 = i4 + Int32(nthr * 4) + L.bar(bar_id, nthr) + _pst(prof, 58, tid) + L.find_cross(s_hist, K, tid, s_res, NB_SEL) + L.bar(bar_id, nthr) + _pst(prof, 59, tid) + Bb = s_res[L.RES_B] + above = s_res[L.RES_ABOVE] + m = s_res[L.RES_M] + Bret = Bb + need = K - above + mret = m + whole = Int32(0) + if need >= m: + whole = Int32(1) + keepc = Int32(0) + if whole == Int32(0): + if m <= Int32(QUADC): + keepc = Int32(1) + Bw = Bb + if whole != Int32(0): + Bw = Bb - Int32(1) + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + chunk = (C + Int32(nthr * 4) - Int32(1)) // Int32(nthr * 4) * Int32(128) + c0 = wid * chunk + c1 = c0 + chunk + if c1 > C: + c1 = C + cw = Int32(0) + cc = Int32(0) + i4 = c0 + lane + while i4 < c1: + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bb = L._vbin(Uint64(lst[icl]), lo, sc, NB_SEL) + if i4 + Int32(32 * q) < c1: + if bb > Bw: + cw = cw + Int32(1) + elif bb == Bb: + cc = cc + Int32(1) + i4 = i4 + Int32(128) + wcw = Int32(cute.arch.warp_redux_sync(cw, "add")) + wcc = Int32(cute.arch.warp_redux_sync(cc, "add")) + if lane == Int32(0): + s_wc[wid] = wcw + s_wc[Int32(NW) + wid] = wcc + L.bar(bar_id, nthr) + _pst(prof, 60, tid) + pw = Int32(0) + pc = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + pw = pw + Int32(s_wc[w_]) + pc = pc + Int32(s_wc[NW + w_]) + base0 = c0 + while base0 < c1: + ed = [] + for q in cutlass.range_constexpr(4): + icl = base0 + Int32(32 * q) + lane + if icl > C - Int32(1): + icl = C - Int32(1) + ed.append(Uint64(lst[icl])) + for q in cutlass.range_constexpr(4): + sl = base0 + Int32(32 * q) + lane + fw = Int32(0) + fc = Int32(0) + if sl < c1: + bd_ = L._vbin(ed[q], lo, sc, NB_SEL) + if bd_ > Bw: + fw = Int32(1) + elif bd_ == Bb: + fc = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fw != Int32(0))) + mc = Int32(cute.arch.vote_ballot_sync(fc != Int32(0))) + if fw != Int32(0): + out_s[pw + Int32(cute.arch.popc(mw & lm))] = sl + if fc != Int32(0): + if keepc != Int32(0): + pcs = pc + Int32(cute.arch.popc(mc & lm)) + s_ck[pcs] = L.entry_key(ed[q]) + s_cs[pcs] = sl + pw = pw + Int32(cute.arch.popc(mw)) + pc = pc + Int32(cute.arch.popc(mc)) + base0 = base0 + Int32(128) + L.bar(bar_id, nthr) + _pst(prof, 61, tid) + if whole == Int32(0): + if m <= Int32(32): + info = Int32(1) + if wid == Int32(0): + kq = Uint64(0) + sq = Int32(0) + if lane < m: + kq = Uint64(s_ck[lane]) + sq = s_cs[lane] + khi = Uint32(kq >> Uint64(32)) + klo = Uint32(kq & Uint64(4294967295)) + r_ = Int32(0) + for j in cutlass.range_constexpr(32): + ohi = cute.arch.shuffle_sync(khi, Int32(j)) + olo = cute.arch.shuffle_sync(klo, Int32(j)) + if Int32(j) < m: + if ohi > khi: + r_ = r_ + Int32(1) + elif ohi == khi: + if olo > klo: + r_ = r_ + Int32(1) + if lane < m: + if r_ < need: + out_s[above + r_] = sq + L.bar(bar_id, nthr) + elif m <= Int32(QUADC): + info = Int32(1) + i = tid + while i < m: + ki = Uint64(s_ck[i]) + r_ = Int32(0) + jq = Int32(0) + while jq < m: + if Uint64(s_ck[jq]) > ki: + r_ = r_ + Int32(1) + jq = jq + Int32(1) + if r_ < need: + out_s[above + r_] = s_cs[i] + i = i + Int32(nthr) + L.bar(bar_id, nthr) + else: + info = Int32(2) + pref = Uint64(0) + plen = Int32(0) + needr = need + done = Int32(0) + while done == Int32(0): + shift = Int32(56) - plen + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + L.bar(bar_id, nthr) + i = tid + while i < C: + e2_ = Uint64(lst[i]) + if L._vbin(e2_, lo, sc, NB_SEL) == Bb: + k2 = L.entry_key(e2_) + okp = Int32(1) + if plen > Int32(0): + if k2 >> Uint64(Int32(64) - plen) != pref: + okp = Int32(0) + if okp != Int32(0): + dg = Int32(Uint32(k2 >> Uint64(shift) & Uint64(255))) + cute.arch.red( + s_hist.iterator + dg, + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + i = i + Int32(nthr) + L.bar(bar_id, nthr) + L.scan_cross0( + s_hist, needr, tid, s_res, needr, needr, s_hist, nb=NBS, zero=True + ) + L.bar(bar_id, nthr) + dB = s_res[L.RES_B] + dab = s_res[L.RES_ABOVE] + dm = s_res[L.RES_M] + L.bar(bar_id, nthr) + pref = pref << Uint64(8) | Uint64(dB) + plen = plen + Int32(8) + needr = needr - dab + if needr >= dm: + done = Int32(1) + if plen >= Int32(64): + done = Int32(1) + thr = pref << Uint64(Int32(64) - plen) + if plen >= Int32(64): + thr = pref + nw2 = Int32(0) + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + if ii < c1: + e3_ = Uint64(lst[ii]) + if L._vbin(e3_, lo, sc, NB_SEL) == Bb: + if L.entry_key(e3_) >= thr: + f2_ = Int32(1) + nw2 = nw2 + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(f2_ != Int32(0)))) + r0 = r0 + Int32(32) + ex2, tot2 = L._warp_prefix(nw2, s_wc, tid, nthr, bar_id) + p2 = above + ex2 + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + if ii < c1: + e4 = Uint64(lst[ii]) + if L._vbin(e4, lo, sc, NB_SEL) == Bb: + if L.entry_key(e4) >= thr: + f2_ = Int32(1) + m2 = Int32(cute.arch.vote_ballot_sync(f2_ != Int32(0))) + if f2_ != Int32(0): + out_s[p2 + Int32(cute.arch.popc(m2 & lm))] = ii + p2 = p2 + Int32(cute.arch.popc(m2)) + r0 = r0 + Int32(32) + L.bar(bar_id, nthr) + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + L.bar(bar_id, nthr) + _pst(prof, 62, tid) + return (nout, mret, info, Bret) + + +# ==================================================================================================================== +# Fused DeepSeek-V4-Flash decode kernel (CuTe DSL, SM100): the cooperative launch, the indexer-K stream, the +# sampled threshold, candidate publication and the teams' exact top-512 selection, plus the host entry points +# ``SpecDsaMegakernel`` and ``compile_mk`` used by ``megakernel_op.py``. +# ==================================================================================================================== + +_RND_RN = "rn" +NEG_INF = -math.inf +NTEAM = 8 +CAPR = 2048 +CAPL = 5632 +BOARD_CAP = 4096 +RMAX = 10 +NSLOTS = 11 +NTILES = 5 +NB_INITIAL = 512 +BUCKET_CAP = 512 +assert NB_INITIAL * 8 == NB_SEL * 4 and CAPL < 65536 +NB_DRS = 1024 +DRS_DIG = 10 +K50_BITS = 50 +GPOS_MASK = (1 << 18) - 1 +NGH = 8 +NCSLOT = 3 +SPIN_MS = 200 +P_T1 = 1 +P_T12 = 2 +P_DRS = 3 +P_ABORT = 9 +K_DONE = 1 +K_PUB = 2 +K_HIST = 3 +ST_GO = 0 +ST_SKIP = 9 +E_STALE = 1 +E_TIMEOUT = 2 +E_NLIMIT = 4 +E_MISMATCH = 8 +E_ABORTED = 16 +W_ENTRY = 0 +W_DONE = 1 +W_DONE2 = 2 +W_TSRV = 5 +W_TLINE = 8 +W_DIR = 16 +W_DP = 17 +W_INFO = 24 +W_INFO2 = 25 +W_INFO3 = 26 +W_ERR = 32 +W_ERRB = 33 +W_ABORT = 34 +W_FOL = 36 +W_RC = 48 +W_TLINE_DRY = 44 # free words: the followers' dry T stores (fwarm) +assert W_FOL + NTEAM <= W_TLINE_DRY and W_TLINE_DRY + 4 <= W_RC +W_CNT = 64 +WS_WORDS = 1024 +NSTAMP = 128 +( + ST_ENTRY, + ST_FIRST_TMA, + ST_FIRST_EPI, + ST_BOARD, + ST_STREAM_END, + ST_T_SEEN, + ST_CAND_PUB, + ST_VERDICT, + ST_EXIT, +) = range(9) +( + ST_M_SWA, + ST_M_BOARD, + ST_M_T, + ST_M_FIN, + ST_M_COPY, + ST_M_SEL, + ST_M_OUT, + ST_M_EXIT, + ST_M_WARMA, + ST_M_WARMB, +) = range(10, 20) +ST_M_PV0 = 20 +ST_A_LOAD, ST_B_CNT, ST_B_COPY2, ST_B_SELX, ST_S_SCAN, ST_S_WR = (52, 53, 54, 55, 56, 57) +S_OFF_KV0 = 0 +S_OFF_KV1 = 49152 +S_OFF_Q = 98304 +S_OFF_W = 106496 +S_OFF_SC0 = 106752 +S_OFF_SC1 = 108288 +S_OFF_LOG = 109824 +S_OFF_BTC = S_OFF_LOG + MAXS * SPLIT_TOK * 4 +S_OFF_BAR = S_OFF_BTC + MAXS * 8 * 4 +S_OFF_MISC = S_OFF_BAR + 256 +SUBCAP = 512 +S_OFF_SUB = S_OFF_MISC + 512 +S_BYTES = S_OFF_SUB + 8 * SUBCAP * 8 +S_BAR_T = 25 +# per-row logits buffers (up to 8 rows) and per-row directive state (8 x int32 [tot, ntok, t_lo, seq, done], +# then 8 x int64 gen) past the stream layout +S_OFF_LOGR = (S_BYTES + 1023) // 1024 * 1024 +S_OFF_ROWST = S_OFF_LOGR + 8 * MAXS * SPLIT_TOK * 4 +K_NONE = 15 +# service-warpgroup scratch: K_HIST histogram, per-row C-pool block-table slice, per-row [T, bin scale], +# per-row handoff mbarriers, per-row entry words, service s_wc / s_dir +S_OFF_SVH = S_OFF_ROWST + 512 +S_OFF_SVB = S_OFF_SVH + NB_DRS * 4 +S_OFF_SVT = S_OFF_SVB + 8 * MAXS * 8 * 4 +S_OFF_SVM = S_OFF_SVT + 64 +S_OFF_SVG = S_OFF_SVM + 64 +S_OFF_SVW = S_OFF_SVG + 8 * 3 * 8 + 8 * 8 +S_OFF_SVTB = S_OFF_SVW + 64 +S_OFF_LSTM = S_OFF_LOGR + 6 * MAXS * SPLIT_TOK * 4 +S_SVC_END = S_OFF_SVTB + 64 +# stream T-server scratch in the logit slots of rows 4-5 (unused for nrows <= 4) +S_TSRV_FA = S_OFF_LOGR + 4 * MAXS * SPLIT_TOK * 4 +# nrows > 4: T-server scratch in row 7's logit slot; nrows > 6: the last row's list in the idle K ring 1 +S_TSRV_FA8 = S_OFF_LOGR + 7 * MAXS * SPLIT_TOK * 4 +S_OFF_LSTM8 = S_OFF_KV1 +T_OFF_Q = 0 +T_OFF_KV = 32768 +T_OFF_LIST = T_OFF_KV + 8 * 16384 +T_OFF_SCR = T_OFF_LIST + CAPL * 8 +T_OFF_HIST = T_OFF_SCR +T_OFF_OUTS = T_OFF_HIST + 4096 +T_OFF_CK = T_OFF_OUTS + 2048 +T_OFF_CS = T_OFF_CK + 2304 +T_OFF_COFF = T_OFF_CS + 1152 +T_OFF_CU1 = T_OFF_COFF + 640 +T_OFF_CU2 = T_OFF_CU1 + 640 +T_OFF_RES = T_OFF_CU2 + 640 +T_OFF_RED = T_OFF_RES + 64 +T_OFF_WC = T_OFF_RED + 256 +T_OFF_STAT = T_OFF_WC + 256 +T_OFF_FIN = T_OFF_STAT + 1024 +T_OFF_IDX = T_OFF_FIN + 1024 +T_OFF_BAR = T_OFF_IDX + 2560 +T_OFF_MISC = T_OFF_BAR + 512 +T_OFF_FA = T_OFF_MISC + 256 +T_OFF_CROW = T_OFF_FA + 1024 + 64 + 256 + 512 +# entry words of up to MAXP passes (8 x int32 each) outside misc +MAXP = 16 +# passes of the 33..48-row configuration: their entry words reach past T_BYTES, inside the grown arena +MAXP48 = 24 +T_OFF_PW = T_OFF_CROW + 288 * 4 +T_BYTES = T_OFF_PW + MAXP * 8 * 4 +# bucket s_map and the pre-select index buffer inside the list area, beyond the partner's merge push +SMAP2_OFF = T_OFF_LIST + 20480 +SIDX2_OFF = T_OFF_LIST + 22528 +assert SIDX2_OFF + 640 * 4 <= T_OFF_SCR +assert T_OFF_LIST + (NSLOTS - 8) * 16384 <= T_OFF_STAT +assert T_BYTES <= 232448, T_BYTES +T_OFF_F_RAW = T_OFF_KV + 4 * 16384 +T_OFF_F_HIST = T_OFF_FA +T_OFF_F_RES = T_OFF_F_HIST + 1024 +T_OFF_F_RED = T_OFF_F_RES + 64 +T_OFF_F_MB = T_OFF_F_RED + 256 +T_OFF_BTC = T_OFF_KV + 6 * 16384 +T_OFF_NKEY = T_OFF_KV +assert CAPL * 8 <= 3 * 16384 +BTC_CAP = 8192 +assert T_OFF_F_RAW + BOARD_CAP * 8 <= T_OFF_BTC and T_OFF_BTC + BTC_CAP * 4 <= T_OFF_KV + 8 * 16384 +ARENA = max(T_BYTES, S_BYTES) +assert S_OFF_ROWST + 8 * 8 * 4 + 8 * 8 <= ARENA +assert S_SVC_END <= ARENA, (S_SVC_END, ARENA) +B_QF = 0 +B_KVF = 1 +B_KVE = B_KVF + NSLOTS +B_SF = B_KVE + NSLOTS +B_SE = B_SF + 4 +B_PF = B_SE + 4 +B_OF = B_PF + 4 +B_OC = B_OF + 1 +B_FIN = B_OC + 1 +B_SWA = B_FIN + 1 +B_SEL = B_SWA + 1 +B_T = B_SEL + 1 +B_PVL = B_T + 1 +B_BTC = B_PVL + 1 +B_LST = B_BTC + 1 +B_EAR = B_LST + 1 +B_RX = B_EAR + 1 +B_PR = B_EAR + 2 +B_DRY = B_EAR + 3 +assert B_EAR < 64 +DUMMY_GPOS = 2147483647 +BAR_CTL = 6 +BAR_EPI = 7 +BAR_SMX = 8 +# pass transition of the 12 non-control warps / softmax -> control WG handshake +BAR_PASS = 13 +BAR_HAND = 14 + + +@dsl_user_op +def prefetch_l2_bulk(addr, nbytes, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr, loc, ip), L._v(nbytes, loc, ip)], + "cp.async.bulk.prefetch.L2.global [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def st_rlx_u64(addr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "st.relaxed.gpu.global.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def ld_relaxed_v2u64(addr, *, loc=None, ip=None): + from cutlass._mlir.dialects import llvm as _llvm + from cutlass.cutlass_dsl import T as _T + + st = _llvm.StructType.get_literal([_T.i64(), _T.i64()]) + r = L._asm( + st, + [L._v(addr, loc, ip)], + "ld.relaxed.gpu.global.v2.u64 {$0, $1}, [$2];", + "=l,=l,l", + loc, + ip, + ) + return ( + Uint64(_llvm.extractvalue(_T.i64(), r, [0], loc=loc, ip=ip)), + Uint64(_llvm.extractvalue(_T.i64(), r, [1], loc=loc, ip=ip)), + ) + + +@dsl_user_op +def ld_relaxed_v2u64_p(addr, pred, *, loc=None, ip=None): + # predicated ld.relaxed.gpu.v2.u64 without a branch (zeros where pred == 0) + from cutlass._mlir.dialects import llvm as _llvm + from cutlass.cutlass_dsl import T as _T + + st = _llvm.StructType.get_literal([_T.i64(), _T.i64()]) + r = L._asm( + st, + [L._v(addr, loc, ip), L._v(pred, loc, ip)], + "{\n\t.reg .pred p;\n\tsetp.ne.u32 p, $3, 0;\n\tmov.u64 $0, 0;\n\tmov.u64 $1, 0;\n" + "\t@p ld.relaxed.gpu.global.v2.u64 {$0, $1}, [$2];\n}", + "=l,=l,l,r", + loc, + ip, + ) + return ( + Uint64(_llvm.extractvalue(_T.i64(), r, [0], loc=loc, ip=ip)), + Uint64(_llvm.extractvalue(_T.i64(), r, [1], loc=loc, ip=ip)), + ) + + +@dsl_user_op +def red_shared_add_u32(saddr, val, *, loc=None, ip=None): + # fire-and-forget shared-memory add (32-bit shared address) + L._asm( + None, + [L._v(saddr, loc, ip), L._v(val, loc, ip)], + "red.shared.add.u32 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def red_add_u32(addr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "red.relaxed.gpu.global.add.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def atom_add_u32(addr, val, *, loc=None, ip=None): + from cutlass.cutlass_dsl import T as _T + + return Uint32( + L._asm( + _T.i32(), + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "atom.relaxed.gpu.global.add.u32 $0, [$1], $2;", + "=r,l,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def atom_add_u32_p(addr, val, pred, dflt, *, loc=None, ip=None): + # Predicated returning atom.add without a branch, so the atom.adds of a batch issue back to + # back; returns dflt where pred == 0. + from cutlass.cutlass_dsl import T as _T + + return Uint32( + L._asm( + _T.i32(), + [L._v(addr, loc, ip), L._v(val, loc, ip), L._v(pred, loc, ip), L._v(dflt, loc, ip)], + "{\n\t.reg .pred p;\n\tsetp.ne.u32 p, $3, 0;\n\tmov.u32 $0, $4;\n\t@p atom.relaxed.gpu.global.add.u32 $0, " + "[$1], $2;\n}", + "=r,l,r,r,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def atom_exch_u64(addr, val, *, loc=None, ip=None): + # atomic swap of a 64-bit global word (relaxed, gpu scope); returns the old value + from cutlass.cutlass_dsl import T as _T + + return Uint64( + L._asm( + _T.i64(), + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "atom.relaxed.gpu.global.exch.b64 $0, [$1], $2;", + "=l,l,l", + loc, + ip, + ) + ) + + +@dsl_user_op +def ldg_cg_u64(addr, *, loc=None, ip=None): + # weak 64-bit global load cached in L2 only (loads of a thread overlap, unlike ld.relaxed.gpu) + from cutlass.cutlass_dsl import T as _T + + return Uint64( + L._asm(_T.i64(), [L._v(addr, loc, ip)], "ld.global.cg.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def prefetch_l1(addr, *, loc=None, ip=None): + # bring one global line into this SM's L1 + L._asm(None, [L._v(addr, loc, ip)], "prefetch.global.L1 [$0];", "l", loc, ip) + + +@dsl_user_op +def ldg_ca_u64(addr, *, loc=None, ip=None): + # weak 64-bit global load, L1-allocating + from cutlass.cutlass_dsl import T as _T + + return Uint64( + L._asm(_T.i64(), [L._v(addr, loc, ip)], "ld.global.ca.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def red_max_u64(addr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "red.relaxed.gpu.global.max.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def red_or_u64(addr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr, loc, ip), L._v(val, loc, ip)], + "red.relaxed.gpu.global.or.b64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def st_shared_v2u64(addr32, a, b, *, loc=None, ip=None): + L._asm( + None, + [L._v(addr32, loc, ip), L._v(a, loc, ip), L._v(b, loc, ip)], + "st.shared.v2.u64 [$0], {$1, $2};", + "r,l,l", + loc, + ip, + ) + + +@dsl_user_op +def cp_async8(saddr, gaddr, *, loc=None, ip=None): + L._asm( + None, + [L._v(saddr, loc, ip), L._v(gaddr, loc, ip)], + "cp.async.ca.shared.global [$0], [$1], 8;", + "r,l", + loc, + ip, + ) + + +@dsl_user_op +def lds_volatile_u32(saddr, *, loc=None, ip=None): + return Int32( + L._asm( + L.T.i32(), [L._v(saddr, loc, ip)], "ld.volatile.shared.u32 $0, [$1];", "=r,r", loc, ip + ) + ) + + +@dsl_user_op +def fence_acq_rel_cta(*, loc=None, ip=None): + L._asm(None, [], "fence.acq_rel.cta;", "", loc, ip) + + +@dsl_user_op +def sts_volatile_u32(saddr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(saddr, loc, ip), L._v(val, loc, ip)], + "st.volatile.shared.u32 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def match_any_b32(v, *, loc=None, ip=None): + from cutlass.cutlass_dsl import T as _T + + return Int32( + L._asm( + _T.i32(), [L._v(v, loc, ip)], "match.any.sync.b32 $0, $1, 0xffffffff;", "=r,r", loc, ip + ) + ) + + +@dsl_user_op +def clz_u64(x, *, loc=None, ip=None): + from cutlass.cutlass_dsl import T as _T + + return Int32(L._asm(_T.i32(), [L._v(x, loc, ip)], "clz.b64 $0, $1;", "=r,l", loc, ip)) + + +@dsl_user_op +def lds_v4f32(saddr32, *, loc=None, ip=None): + # ld.shared.v4.f32 (16-byte aligned shared address) + from cutlass._mlir.dialects import llvm as _llvm + from cutlass.cutlass_dsl import T as _T + + st = _llvm.StructType.get_literal([_T.f32(), _T.f32(), _T.f32(), _T.f32()]) + r = L._asm( + st, + [L._v(saddr32, loc, ip)], + "ld.shared.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,r", + loc, + ip, + ) + return tuple(Float32(_llvm.extractvalue(_T.f32(), r, [i], loc=loc, ip=ip)) for i in range(4)) + + +def _row2(t, r): + # (1, C) view of row r of a 2-D tensor (row stride = stride[0]) + s0_ = t.layout.stride[0] + return cute.make_tensor( + t.iterator + r * s0_, cute.make_layout((1, t.shape[1]), stride=(s0_, t.layout.stride[1])) + ) + + +def _row1(t, r): + return cute.make_tensor(t.iterator + r, cute.make_layout((1,))) + + +def _flat(t, r, size: int): + return cute.make_tensor(t.iterator + r * size, cute.make_layout((size,))) + + +def _ptr(arena, off, dtype): + return cutlass.Pointer(cute.recast_ptr(arena + off, dtype=dtype), dtype=dtype) + + +def _sm_tensor(arena, off, dtype, n, stride=1): + return cute.make_tensor( + cute.recast_ptr(arena + off, dtype=dtype), cute.make_layout(n, stride=stride) + ) + + +@cute.jit +def packed_hist_total(lo, hi): + return Int32( + (lo & Uint32(65535)) + (lo >> Uint32(16)) + (hi & Uint32(65535)) + (hi >> Uint32(16)) + ) + + +@cute.jit +def find_cross_warp_counts(s_hist, target, tidx, s_res, s_wc, nb: cutlass.Constexpr): + # Each 16-bit field counts one warp's candidates. No field can carry: + # every prefix contains at most CAPL < 65536 entries. Native u32 shared + # reductions build the low/high pairs; packed scans preserve all 4 counts. + BPL = nb // 32 + if tidx < Int32(32): + lane = tidx + part0 = Uint32(0) + part1 = Uint32(0) + for j in cutlass.range_constexpr(BPL): + idx = lane * Int32(BPL) + ((Int32(j) + lane) & Int32(BPL - 1)) + h = Uint64(s_hist[idx]) + part0 = part0 + Uint32(h) + part1 = part1 + Uint32(h >> Uint64(32)) + v0 = L.warp_suffix_scan_add(part0, lane) + v1 = L.warp_suffix_scan_add(part1, lane) + total = packed_hist_total(v0, v1) + if lane == Int32(0): + s_res[L.RES_TOT] = total + msk = Int32(cute.arch.vote_ballot_sync(total >= target)) + Lb = L.hi_bit_or_zero(msk) + above0 = cute.arch.shuffle_sync(v0 - part0, Lb) + above1 = cute.arch.shuffle_sync(v1 - part1, Lb) + h = Uint64(0) + if lane < Int32(BPL): + h = Uint64(s_hist[Lb * Int32(BPL) + lane]) + h0 = Uint32(h) + h1 = Uint32(h >> Uint64(32)) + w0 = L.warp_suffix_scan_add(h0, lane) + w1 = L.warp_suffix_scan_add(h1, lane) + msk2 = Int32( + cute.arch.vote_ballot_sync(packed_hist_total(above0 + w0, above1 + w1) >= target) + ) + J = L.hi_bit_or_zero(msk2) + if lane == J: + winner0 = above0 + w0 - h0 + winner1 = above1 + w1 - h1 + above = packed_hist_total(winner0, winner1) + m = packed_hist_total(h0, h1) + s_res[L.RES_B] = Lb * Int32(BPL) + J + s_res[L.RES_M] = m + s_res[L.RES_ABOVE] = above + if target - above >= m: + winner0 = winner0 + h0 + winner1 = winner1 + h1 + h0 = Uint32(0) + h1 = Uint32(0) + # Emit prefix offsets directly. The whole candidate counting pass + # and its cross-warp barriers are unnecessary after this scan. + pw1 = Int32(winner0 & Uint32(65535)) + pw2 = pw1 + Int32(winner0 >> Uint32(16)) + px1 = Int32(h0 & Uint32(65535)) + px2 = px1 + Int32(h0 >> Uint32(16)) + s_wc[0] = Int32(0) + s_wc[1] = pw1 + s_wc[2] = pw2 + s_wc[3] = pw2 + Int32(winner1 & Uint32(65535)) + s_wc[4] = Int32(0) + s_wc[5] = px1 + s_wc[6] = px2 + s_wc[7] = px2 + Int32(h1 & Uint32(65535)) + + +class SpecDsaMegakernel: + """Kernel configuration and device code: the constructor arguments are the compile-time knobs (``op.py`` holds + the per-batch-size sets); ``row_sizes()`` gives the per-row workspace sizes. + """ + + def __init__( + self, + num_sms: int = NUM_SMS, + policy: int = L.POL_EVICT_FIRST, + debug: bool = False, + stamps: bool = False, + math_regs: int = 232, + kv_stages: int = 2, + phys_block_kv: int = SPEC.index_page_tokens, + prewarm: bool = True, + skew: int = 0, + coop: bool = True, + qk_ahead: bool = False, + gjoin: bool = True, + wdelay: int = 400, + mma_block: bool = True, + mma_idle_ns: int = 0, + ctl_regs: bool = True, + spin_ms: int = SPIN_MS, + acqpoll: bool = False, + relst: bool = False, + wacq: int = 0, + folpre: bool = True, + heal: bool = True, + nofence: bool = False, + lean: bool = False, + bulk: bool = True, + fblka: bool = False, + gen2: bool = True, + hook: bool = True, + late_done: int = 0, + pref: bool = True, + pchk: int = 16, + full_attention_tiles: bool = False, + swag: bool = False, + nohoist: bool = False, + rs24: bool = False, + rs24_t4split: bool = False, + rs24_dry: bool = True, + rs24_f32: bool = False, + rs24_exitbar: bool = False, + rs24_asym: bool = False, + rs24_lsu: int = 0, + nrows: int = 1, + nteams: int = 0, + ppref: bool = True, + presel: bool = False, + pdec: bool = False, + warm1: bool = False, + pollns: int = 0, + acqx: bool = False, + swpre: bool = True, + bpf: bool = False, + entcg: bool = False, + tsz01: bool = False, + tsz2: bool = False, + tsz: bool = False, + drot: int = 0, + awarm3: bool = False, + awarm2a: bool = False, + btcl: bool = False, + pdwait: int = 0, + awarm2: bool = False, + t1a: bool = False, + awarm: bool = False, + pdirect: bool = False, + tsrv1: bool = False, + tl1r: bool = False, + tszall: bool = False, + qdb: bool = False, + dpf: bool = False, + early: bool = False, + tearly: bool = False, + b1l: bool = False, + b1l_u: int = 2, + b1l_e: bool = True, + b1l_pub: bool = False, + b1l_upub: int = 2, + ring: bool = False, + ring_w12: bool = False, + team4: bool = False, + tcta: int = 0, + lpoll: bool = False, + lfence: bool = False, + lbin: bool = False, + tpoll1: bool = False, + cls4: bool = False, + fwarm: bool = False, + config: SpecDsaConfig | None = None, + ): + self.fp4 = config is not None and config.index_k_dtype == "fp4" + require_built_for(config, SPEC_FP4 if self.fp4 else SPEC) + assert coop, ( + "the protocol spins across CTAs: all 148 CTAs must be co-resident (cooperative launch)" + ) + assert bulk, "warp-compacted acquire requires even-padded stream packets" + assert kv_stages in ((2, 3, 4, 5, 6) if self.fp4 else (2, 3)), kv_stages + assert wdelay >= 0 and mma_idle_ns >= 0 and (skew >= 0) + assert not (qk_ahead and gjoin), "qk_ahead belongs to the gjoin=False MMA role" + assert 1 <= spin_ms <= 10000, spin_ms + assert ladder_max_smp() * 8 <= min(BOARD_CAP, RMAX * 128 * 2), "board capacity" + self.full_attention_tiles = bool(full_attention_tiles) + self.swag = bool(swag) + # tcta: dedicated T-server CTAs (the last tcta CTAs of the grid, even) compute the threshold line of every row + # (rows t, t + tcta, ...) instead of the stream CTAs with an empty split range, whose math warps block in the T + # wait and then run a few us behind the other stream CTAs for the rest of the launch (needs the shared-team T + # server layout: tsz01 / tsz2 / tsz / tszall) + self.tcta = int(tcta) + # The threshold chain (FP4 sets of 1 to 4 rows, ``megakernel_op._FP4_SMALL``; the published threshold line is + # unchanged, bit for bit): lpoll: the T lead re-loads only the board pairs not yet valid; lfence: it starts + # polling at once and its release fence (histogram clear) runs while the first poll loads are in flight; + # lbin: the rank bins come from a 256-bin histogram instead of the bitwise key search; tpoll1: the stream CTAs + # read the threshold line in one round trip; cls4: the buffered tiles are classified with the loads of four + # tiles first; fwarm: the followers' dry pass of the threshold code does not wait for the board and covers the + # T stores + self.lpoll = bool(lpoll) + self.lfence = bool(lfence) + assert self.lpoll or not self.lfence, "lfence moves a fence into the lpoll loop" + self.lbin = bool(lbin) + self.tpoll1 = bool(tpoll1) + self.cls4 = bool(cls4) + self.fwarm = bool(fwarm) + self.nohoist = bool(nohoist) + self.rs24 = bool(rs24) + self.rs24_t4split = bool(rs24_t4split) + self.rs24_dry = bool(rs24_dry) + self.rs24_f32 = bool(rs24_f32) + self.rs24_exitbar = bool(rs24_exitbar) + self.rs24_asym = bool(rs24_asym) + self.rs24_lsu = int(rs24_lsu) + assert self.rs24_lsu == 0 or ( + self.rs24 and self.rs24_lsu % 4 == 0 and 4 <= self.rs24_lsu <= 32 + ), "rs24_lsu: multiple of 4 in [4, 32], needs rs24" + assert not (self.rs24_asym and self.rs24_f32), "rs24_asym pushes bf16" + self.nrows = int(nrows) + # team4: teams of 4 CTAs (two row groups x two V column halves of 256, one KV gather per tile) instead of 8; one + # team per row for 3 to 4 rows (a single pass), a paired BF16 merge + self.team4 = bool(team4) + self.team_ctas = 4 if self.team4 else NTEAM + assert not self.team4 or ( + 3 <= self.nrows <= 32 + and self.rs24 + and (not self.rs24_dry) + and (not self.rs24_f32) + and (not self.rs24_asym) + ), "team4 uses paired BF16 merge for B3..24" + assert not self.team4 or T_OFF_LIST + A.rs24_rx_bytes(False, True) <= SMAP2_OFF + assert 1 <= self.nrows <= (48 if ring else 8) and (self.nrows == 1 or self.rs24), ( + "multi-row needs rs24 (nrows > 8 needs ring)" + ) + assert not self.rs24 or ( + gjoin and (num_sms - self.team_ctas * (int(nteams) if nteams else self.nrows)) % 2 == 0 + ), "rs24 pairs team CTAs 2k, 2k+1 of the gjoin layout" + self.num_sms = num_sms + # teams of 8 CTAs; nteams < nrows shares them (team t serves rows t, t + nteams, ...) + self.nteams = min(int(nteams), self.nrows) if nteams else self.nrows + assert 1 <= self.nteams <= self.nrows + self.ns = num_sms - self.team_ctas * self.nteams - self.tcta + assert self.tcta in (0, 2) and self.ns % 2 == 0 + assert not self.tcta or ( + self.nteams < self.nrows and tsz01 and tsz2 and tsz and tszall and self.rs24 + ), "tcta needs shared teams with the stream T-server layout (tsz01 tsz2 tsz tszall)" + self.npmax = (self.nrows + self.nteams - 1) // self.nteams + assert self.npmax <= (MAXP if self.nrows <= 32 else MAXP48) # pass entry words in T_OFF_PW + assert self.ns * CAPR >= NB_INITIAL * BUCKET_CAP + assert self.ns * MAXS * SPLIT_TOK >= N_MAX and self.ns <= 160 + self.policy = policy + self.debug = bool(debug) + self.stamps = bool(stamps) + self.prewarm = bool(prewarm) + self.skew = int(skew) + self.coop = bool(coop) + self.qk_ahead = bool(qk_ahead) + self.wdelay = int(wdelay) + self.mma_block = bool(mma_block) + self.mma_idle_ns = int(mma_idle_ns) + self.ctl_regs = bool(ctl_regs) + self.gjoin = bool(gjoin) + self.spin_ns = int(spin_ms) * 1000000 + self.acqpoll = bool(acqpoll) + self.relst = bool(relst) + self.ppref = bool(ppref) + self.presel = bool(presel) + self.pdec = bool(pdec) + self.warm1 = bool(warm1) + self.pollns = int(pollns) + self.acqx = bool(acqx) + self.swpre = bool(swpre) + self.bpf = bool(bpf) + self.entcg = bool(entcg) + self.tsz01 = bool(tsz01) + # nrows > 4: CTA ns - 1 (empty in the last row) serves the last row; tsz01 scratch in row 7's slot + assert not self.tsz01 or self.nrows <= 4 or (bool(tsz2) or bool(tsz)) + self.tsz2 = bool(tsz2) + self.tsz = bool(tsz) + self.drot = int(drot) + self.awarm3 = bool(awarm3) + self.awarm2a = bool(awarm2a) + self.btcl = bool(btcl) + self.pdwait = int(pdwait) + self.awarm2 = bool(awarm2) + self.t1a = bool(t1a) + self.awarm = bool(awarm) + self.pdirect = bool(pdirect) + assert not self.pdirect or (self.presel and self.pdec) + self.tsrv1 = bool(tsrv1) + self.tl1r = bool(tl1r) + # only with shared teams (nteams < nrows), like tsz01 / tsz2 (BS1 / BS2 of the same solution: off) + self.tszall = bool(tszall) and self.nteams < self.nrows + assert not self.tszall or (self.tsz01 and self.tsz2), "tszall extends tsz01 + tsz2" + assert self.swpre or self.pdec + assert not (self.npmax > 2 and self.presel and self.swpre), ( + "misc[60] is cleared only at pass 0" + ) + assert not self.pdec or self.presel + assert wacq in (0, 1, 2) + self.wacq = int(wacq) + self.folpre = bool(folpre) + self.heal = bool(heal) + self.nofence = bool(nofence) + self.lean = bool(lean) + self.bulk = bool(bulk) + self.fblka = bool(fblka) + self.gen2 = bool(gen2) + self.hook = bool(hook) + self.pref = bool(pref) + assert pchk in (1, 2, 4, 8, 16, 32) + self.pchk = int(pchk) + assert late_done in (0, 1, 2, 3, 4) + self.late_done = int(late_done) + assert not (late_done and (not hook)) + assert self.heal or self.hook, ( + "without the exit hook only the directive-tag witness advances the generation" + ) + self.math_regs = math_regs + assert math_regs * 256 + 24 * 256 <= 65536 or ( + nrows > 1 and math_regs * 256 + 80 * 128 <= 65536 + ) + self.block_kv = TILE + self.phys_block_kv = phys_block_kv + self.num_blocks_per_mma = TILE // phys_block_kv + self.num_heads = 64 + self.head_dim = 128 + self.N = 64 + self.num_kv_stages = kv_stages + self.num_umma_stages = 1 + # Q / W double-buffered in the multi-row stream (knob qdb) + self.qdb = bool(qdb) and self.nrows > 1 + # next row's descriptor / ctx loaded one row ahead in the stream roles (knob dpf) + self.dpf = bool(dpf) and self.nrows > 1 + # ring's common-path K_DONE check on the T poller (warp 12), not the publishers (knob ring_w12) + self.ring_w12 = bool(ring_w12) + # words of the saved row state (tot, ntok, t_lo, seq, done) per row: 8 (32 B); 5 from 33 rows on + self.rst_w = 8 + # 9..48 rows (2 teams x up to 24 passes): 8-slot logits ring with a K_DONE guard (knob ring) + self.ring = bool(ring) and self.nrows > 8 + self.arena_bytes = ARENA + if self.ring: + assert ( + (self.nteams == 2 or (self.team4 and self.nteams == 4)) + and self.npmax <= (MAXP if self.nrows <= 32 else MAXP48) + and not self.qdb + and self.tsz01 + and self.tsz2 + and self.tsz + and self.tszall + ), ( + "ring: 2 or 4 shared teams, stream T servers for every row (tsz01 / tsz2 / tsz / tszall), no " + "qdb" + ) + if self.nrows <= 16: + # 16-entry service state, slot-free mbarriers and the T-server scratch in the single-row LOG / BTC + # region + self.s_tsrv_fa = S_OFF_LOG # fa .. fa + 1856 B, misc at fa + 2048 .. fa + 2304 + self.s_svb = S_OFF_LOG + 2304 # 16 x MAXS x 8 int32 (C-pool block-table slices) + self.s_rowst = ( + self.s_svb + 16 * MAXS * 8 * 4 + ) # 16 x 8 int32 [tot, ntok, t_lo, seq, done], gens at +512 + self.s_rgen_off = 512 + self.s_svg = self.s_rowst + 640 # 16 x 3 entry words, 16 gens at +384 + self.s_svgs_off = 16 * 3 * 8 + self.s_svt = self.s_svg + 512 # 16 x [T, bin scale] + self.s_svm = self.s_svt + 128 # 16 mbarriers: row handed to the publishers / drain + self.s_svtb = self.s_svm + 128 # 16 mbarriers: row T armed + self.s_slf = self.s_svtb + 128 # 8 mbarriers: logits slot free again + self.nslot = 16 + assert ( + self.s_slf + 8 * 8 <= S_OFF_BAR + and self.s_svm % 8 == 0 + and self.s_rowst % 8 == 0 + and self.s_svg % 8 == 0 + ) + assert S_SVC_END <= ARENA + elif self.nrows <= 32: + # 17..32 rows (2 teams x 16 passes): 32-entry service state past the stream layout, the C-pool + # block-table slices in the single-row LOG region; the arena grows to hold it + ext = S_SVC_END + self.s_tsrv_fa = ext # fa .. fa + 1856 B, misc at fa + 2048 .. fa + 2304 + self.s_rowst = ( + ext + 2304 + ) # 32 x 8 int32 [tot, ntok, t_lo, seq, done], gens at +1024 + self.s_rgen_off = 1024 + self.s_svg = self.s_rowst + 1280 # 32 x 3 entry words, 32 gens at +768 + self.s_svgs_off = 32 * 3 * 8 + self.s_svt = self.s_svg + 1024 # 32 x [T, bin scale] + self.s_svm = self.s_svt + 256 # 32 mbarriers: row handed to the publishers / drain + self.s_svtb = self.s_svm + 256 # 32 mbarriers: row T armed + self.s_slf = self.s_svtb + 256 # 8 mbarriers: logits slot free again + self.s_svb = S_OFF_LOG # 32 x MAXS x 8 int32 (C-pool block-table slices) + self.nslot = 32 + self.arena_bytes = (self.s_slf + 64 + 4 * 32 + 1023) // 1024 * 1024 + assert self.s_svb + 32 * MAXS * 8 * 4 <= S_OFF_BAR + assert ( + self.arena_bytes <= 232448 - 1024 + and self.s_svm % 8 == 0 + and self.s_rowst % 8 == 0 + ) + else: + # 33..48 rows (2 teams x up to 24 passes): nrows-entry state past the stream layout with one + # generation word per row (math warps), 5 state words per row and a 32-entry ring of block-table + # slices in the single-row LOG region; slice entry r & 31 is rewritten for row r >= 32 after the + # publishers of row r - 32 are done with it (mbarrier SFB[r - 32]) + n_ = self.nrows + ext = S_SVC_END + # fa .. fa + 1856 B, misc at fa + 2048 .. fa + 2304 + self.s_tsrv_fa = ext + # n x 5 int32 [tot, ntok, t_lo, seq, done], then n generations + self.s_rowst = ext + 2304 + self.rst_w = 5 + self.s_rgen_off = (n_ * 5 * 4 + 7) // 8 * 8 + # n generations (math warps), then n (poller) + self.s_svg = self.s_rowst + self.s_rgen_off + n_ * 8 + self.s_svgs_off = n_ * 8 + # n x [T, bin scale] + self.s_svt = self.s_svg + n_ * 16 + # n mbarriers: row handed to the publishers / drain, then n: row T armed + self.s_svm = self.s_svt + n_ * 8 + self.s_svtb = self.s_svm + n_ * 8 + # n - 32 mbarriers: slice entry free again, then 8: logits slot free again + self.s_sfb = self.s_svtb + n_ * 8 + self.s_slf = self.s_sfb + 16 * 8 + # 32 x MAXS x 8 int32 (C-pool block-table slices, ring) + self.s_svb = S_OFF_LOG + self.nslot = n_ + self.arena_bytes = (self.s_slf + 64 + 4 * n_ + 1023) // 1024 * 1024 + assert self.s_svb + 32 * MAXS * 8 * 4 <= S_OFF_BAR and n_ - 32 <= 16 + assert ( + self.arena_bytes <= 232448 - 1024 + and self.s_svm % 8 == 0 + and self.s_svtb % 8 == 0 + and self.s_sfb % 8 == 0 + and self.s_rowst % 8 == 0 + and self.s_svg % 8 == 0 + and self.s_rgen_off % 8 == 0 + ) + assert T_OFF_PW + self.npmax * 32 <= self.arena_bytes + else: + self.s_tsrv_fa = ( + (S_TSRV_FA if self.nrows <= 4 else S_TSRV_FA8) if self.tsz01 else S_OFF_KV0 + ) + self.s_svb = S_OFF_SVB + self.s_rowst = S_OFF_ROWST + self.s_rgen_off = 256 + self.s_svg = S_OFF_SVG + self.s_svgs_off = 8 * 3 * 8 + self.s_svt = S_OFF_SVT + self.s_svm = S_OFF_SVM + self.s_svtb = S_OFF_SVTB + self.s_slf = 0 + self.nslot = 8 + self.ring_w12 = self.ring_w12 and self.ring + # ring_w12: warp 12's per-row verdicts (8 int32: 1 = K_DONE seen and slot freed, 2 = publishers serve the row) + self.s_vrd = self.s_slf + 64 + assert not self.ring_w12 or self.s_vrd + 32 <= ( + S_OFF_BAR if self.nrows <= 16 else self.arena_bytes + ) + assert self.nrows <= 32 or self.s_vrd + 4 * self.nslot <= self.arena_bytes + # stream CTAs: row descriptor load first, TMA descriptor prefetch at entry (knob early) + self.early = bool(early) + # _team_cta: row and window lengths loaded before the barrier setup (knob tearly) + self.tearly = bool(tearly) + # candidate publish in batches of b1l_u per lane, their histogram atom.adds back to back and + # the first batch before the count barrier (b1l_e); at 1 row and on the last row (knob b1l) + self.b1l = bool(b1l) + self.b1l_u = int(b1l_u) + self.b1l_e = bool(b1l_e) + # the same in the publisher warps of the earlier rows, b1l_upub per lane (knob b1l_pub) + self.b1l_pub = bool(b1l_pub) + self.b1l_upub = int(b1l_upub) + assert 1 <= self.b1l_u <= 4 and 1 <= self.b1l_upub <= 4, "b1l_u / b1l_upub in 1..4" + self.num_q_stages = 2 if self.qdb else 1 + if self.qdb: + # Q 2 x 8 KB, W 2 x 256 B, then the scales, over the single-row logits / block-table buffers (unused for + # nrows > 1); the last scale buffer ends at S_OFF_BAR + self.s_off_q, self.s_off_w, self.s_off_sc0, self.s_off_sc1 = ( + 98304, + 114688, + 115200, + 116736, + ) + assert ( + self.s_off_sc1 + TILE * 3 * 4 <= S_OFF_BAR + and self.s_off_q + 2 * 8192 <= self.s_off_w + ) + else: + self.s_off_q, self.s_off_w, self.s_off_sc0, self.s_off_sc1 = ( + S_OFF_Q, + S_OFF_W, + S_OFF_SC0, + S_OFF_SC1, + ) + self.acc_dtype = cutlass.Float32 + self.epi_dtype = cutlass.Float32 + self.output_dtype = cutlass.Float32 + self.epi_bytes = 4 + w_stage_bytes = self.N * self.epi_bytes + self.w_stage_stride = (w_stage_bytes + 127) // 128 * 128 // self.epi_bytes + self.cta_group = tcgen05.CtaGroup.ONE + self.cluster_shape_mn = (1, 1) + self.mma_tiler_mn = (TILE, self.N) + self.num_w_in_reg = 64 + assert kv_stages * TILE * (64 if self.fp4 else 128) <= 49152 + if self.fp4: + # MXFP4 block-scaled MMA: E2M1 data, a UE8M0 scale per 32 elements (SF), two instructions of K 64 per tile + self.num_groups = 2 + self.sf_dtype = Float8E8M0FNU + self.sf_vec_size = 32 + self.umma_inst_k = 64 + # the query scales sit after the (4 KB) FP4 Q stages in the Q region + self.s_off_sfq = self.s_off_q + self.num_q_stages * 4096 + assert self.s_off_sfq + self.num_q_stages * 512 <= self.s_off_w + + def _epi_value(self, tTR_rAcc, w_cache, sW, NUM_W_IN_REG, scale_val): + s0x = cutlass.Float32(0.0) + s0y = cutlass.Float32(0.0) + s1x = cutlass.Float32(0.0) + s1y = cutlass.Float32(0.0) + acc_vec = tTR_rAcc.load() + for h in range(0, self.num_heads, 4): + x0 = acc_vec[h] + x1 = acc_vec[h + 1] + x2 = acc_vec[h + 2] + x3 = acc_vec[h + 3] + # Direct ReLU preserves the full FP32 range of weighted logits. + # Doubling the activation can overflow before the final halving; + # halving scale_val can also discard a subnormal input scale. + a0 = cute.arch.fmax(x0, Float32(0.0), nan=True) + a1 = cute.arch.fmax(x1, Float32(0.0), nan=True) + a2 = cute.arch.fmax(x2, Float32(0.0), nan=True) + a3 = cute.arch.fmax(x3, Float32(0.0), nan=True) + w0 = w_cache[h] + w1 = w_cache[h + 1] + w2 = w_cache[h + 2] + w3 = w_cache[h + 3] + s0x, s0y = cute.arch.fma_packed_f32x2((a0, a1), (w0, w1), (s0x, s0y), rnd=_RND_RN) + s1x, s1y = cute.arch.fma_packed_f32x2((a2, a3), (w2, w3), (s1x, s1y), rnd=_RND_RN) + result_t = s0x + s0y + s1x + s1y + if cutlass.const_expr(self.fp4): + return self.output_dtype(result_t) + return self.output_dtype(result_t * scale_val) + + def _setup_mma(self, a_dtype, b_dtype, a_major, b_major): + if self.fp4: + return self._setup_mma_fp4(a_dtype, b_dtype, a_major, b_major) + self.a_dtype = a_dtype + self.b_dtype = b_dtype + tiled_mma = sm100_utils.make_trivial_tiled_mma( + a_dtype, b_dtype, a_major, b_major, self.acc_dtype, self.cta_group, self.mma_tiler_mn + ) + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + full_k = mma_inst_shape_k * (self.head_dim // mma_inst_shape_k) + self.mma_tiler = (self.mma_tiler_mn[0], self.mma_tiler_mn[1], full_k) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), (tiled_mma.thr_id.shape,) + ) + self.epi_tile = self.cta_tile_shape_mnk[:2] + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, self.mma_tiler, a_dtype, self.num_kv_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, self.mma_tiler, b_dtype, self.num_q_stages + ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + self.num_tmem_alloc_cols = cutlass.utils.get_num_tmem_alloc_cols(tCtAcc_fake) + self.num_tmem_alloc_cols_total = self.num_tmem_alloc_cols * 2 * self.num_umma_stages + return tiled_mma + + def _setup_mma_fp4(self, a_dtype, b_dtype, a_major, b_major): + """The block-scaled MXF4 MMA (K 64 per instruction, two per head dim) and its scale-factor layouts.""" + self.a_dtype = a_dtype + self.b_dtype = b_dtype + tiled_mma = sm100_utils.make_blockscaled_trivial_tiled_mma( + a_dtype, + b_dtype, + a_major, + b_major, + self.sf_dtype, + self.sf_vec_size, + self.cta_group, + self.mma_tiler_mn, + ) + mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2]) + full_k = mma_inst_shape_k * (self.head_dim // mma_inst_shape_k) + self.mma_tiler = (self.mma_tiler_mn[0], self.mma_tiler_mn[1], full_k) + self.cta_tile_shape_mnk = ( + self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape), + self.mma_tiler[1], + self.mma_tiler[2], + ) + self.cluster_layout_vmnk = cute.tiled_divide( + cute.make_layout((*self.cluster_shape_mn, 1)), (tiled_mma.thr_id.shape,) + ) + self.epi_tile = self.cta_tile_shape_mnk[:2] + self.a_smem_layout_staged = sm100_utils.make_smem_layout_a( + tiled_mma, self.mma_tiler, a_dtype, self.num_kv_stages + ) + self.b_smem_layout_staged = sm100_utils.make_smem_layout_b( + tiled_mma, self.mma_tiler, b_dtype, self.num_q_stages + ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape) + self.num_tmem_alloc_cols = find_tmem_tensor_col_offset(tCtAcc_fake) + sfa_smem = blockscaled_utils.make_smem_layout_sfa( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + sfb_smem = blockscaled_utils.make_smem_layout_sfb( + tiled_mma, self.mma_tiler, self.sf_vec_size, 1 + ) + tmem_sfa = blockscaled_utils.make_tmem_layout_sfa( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfa_smem, (None, None, None, 0)), + ) + tmem_sfb = blockscaled_utils.make_tmem_layout_sfb( + tiled_mma, + self.mma_tiler, + self.sf_vec_size, + cute.slice_(sfb_smem, (None, None, None, 0)), + ) + self.tmem_sfa_layout = cute.append(tmem_sfa, cute.make_layout(1, stride=0)) + self.tmem_sfb_layout = cute.append(tmem_sfb, cute.make_layout(1, stride=0)) + sf_k_modes = cute.size(tmem_sfa, mode=[2]) + sf_tile_k = self.head_dim // self.umma_inst_k + assert sf_k_modes % sf_tile_k == 0 + self.sf_k_step = sf_k_modes // sf_tile_k + self.N_padded = ((self.N + 127) // 128) * 128 + self.num_sfa_tmem_cols = (self.cta_tile_shape_mnk[0] // 32) * sf_tile_k + self.num_sfb_tmem_cols = (self.N_padded // 32) * sf_tile_k + # TMEM: accumulators, SFA per group, SFB per (group, Q stage) + self.sf_tmem_base = self.num_tmem_alloc_cols * 2 * self.num_umma_stages + self.sfb_tmem_base = self.sf_tmem_base + self.num_sfa_tmem_cols * 2 + raw_cols = self.sfb_tmem_base + self.num_sfb_tmem_cols * 2 * self.num_q_stages + self.num_tmem_alloc_cols_total = max(1 << math.ceil(math.log2(raw_cols)), 32) + assert self.num_tmem_alloc_cols_total <= 512, "FP4 TMEM columns exceed the 512 of SM100" + self.sfa_chunk_smem_layout = sfa_smem + self.sfb_chunk_smem_layout = sfb_smem + self.copy_atom_s2t = cute.make_copy_atom( + tcgen05.Cp4x32x128bOp(self.cta_group), self.sf_dtype + ) + return tiled_mma + + def _fp4_views(self, kv_fused, b, num_phys_blocks): + """FP4 views of a K page pool [pages, 32 * 68 bytes] and of the queries. + + A page: the E2M1 data of 32 positions, then 32 int32 of four UE8M0 scales each. + """ + phys_block_kv = self.phys_block_kv + kv_fp4 = cute.recast_tensor(kv_fused, Float4E2M1FN) + b = cute.recast_tensor(b, Float4E2M1FN) + block_stride_bytes = kv_fused.layout.stride[0] + a = cute.make_tensor( + kv_fp4.iterator, + cute.make_layout( + (phys_block_kv, self.head_dim, num_phys_blocks), + stride=(self.head_dim, 1, block_stride_bytes * 2), + ), + ) + sf_bytes = cute.make_tensor( + kv_fused.iterator + phys_block_kv * (self.head_dim // 2), + cute.make_layout((phys_block_kv * 4, num_phys_blocks), stride=(1, block_stride_bytes)), + ) + return a, b, cute.recast_tensor(sf_bytes, cutlass.Int32) + + def _fp4_sf_q_atom(self, sf_q, tma_load_op): + """TMA atom of the query scales [64, rows] int32 (the SMEM stage is padded to the 128-token UTCCP atom).""" + stage_stride = (self.N_padded * 4 + 127) // 128 * 128 // 4 + self.sf_q_smem_layout_staged = cute.make_layout( + (self.N_padded, self.num_q_stages), stride=(1, stage_stride) + ) + self.sf_q_tma_smem_layout_staged = cute.make_layout( + (self.N, self.num_q_stages), stride=(1, stage_stride) + ) + return cpasync.make_tiled_tma_atom( + tma_load_op, + sf_q, + cute.select(self.sf_q_tma_smem_layout_staged, mode=[0]), + (self.N,), + ) + + @cute.jit + def __call__( + self, + kv_fused: cute.Tensor, + b: cute.Tensor, + weights: cute.Tensor, + block_table: cute.Tensor, + ctx: cute.Tensor, + desc: cute.Tensor, + q_att: cute.Tensor, + swa_pool: cute.Tensor, + c_pool: cute.Tensor, + swa_local: cute.Tensor, + bt_swa: cute.Tensor, + bt_c: cute.Tensor, + sinks: cute.Tensor, + swa_lens: cute.Tensor, + topk_out: cute.Tensor, + gidx: cute.Tensor, + out: cute.Tensor, + ws64: cute.Tensor, + hist: cute.Tensor, + board: cute.Tensor, + region: cute.Tensor, + dbg_logits: cute.Tensor, + stamps: cute.Tensor, + ctl: cute.Tensor, + num_phys_blocks: cutlass.Int32, + softmax_scale: Float32, + stream: cuda_driver.CUstream, + sf_q: cute.Tensor = None, + ): + phys_block_kv = self.phys_block_kv + scale_offset_elems = phys_block_kv * self.head_dim + if cutlass.const_expr(self.fp4): + a, b, scales = self._fp4_views(kv_fused, b, num_phys_blocks) + else: + kv_fp8 = cute.recast_tensor(kv_fused, cutlass.Float8E4M3FN) + b = cute.recast_tensor(b, cutlass.Float8E4M3FN) + kv_block_stride = kv_fused.layout.stride[0] + a = cute.make_tensor( + kv_fp8.iterator, + cute.make_layout( + (phys_block_kv, self.head_dim, num_phys_blocks), + stride=(self.head_dim, 1, kv_block_stride), + ), + ) + scale_fp8 = cute.make_tensor( + kv_fp8.iterator + scale_offset_elems, + cute.make_layout((phys_block_kv * 4, num_phys_blocks), stride=(1, kv_block_stride)), + ) + scales = cute.recast_tensor(scale_fp8, cutlass.Float32) + a_major = cutlass.utils.LayoutEnum.from_tensor(a).mma_major_mode() + b_major = cutlass.utils.LayoutEnum.ROW_MAJOR.mma_major_mode() + tiled_mma = self._setup_mma(a.element_type, b.element_type, a_major, b_major) + atom_thr_size = cute.size(tiled_mma.thr_id.shape) + tma_load_op = cpasync.CopyBulkTensorTileG2SOp() + a_tma_view = sm100_utils.make_smem_layout( + cute.nvgpu.OperandMajorMode.K, + (self.block_kv, self.head_dim), + a.element_type, + self.num_kv_stages, + ) + a_tma_view = cute.tiled_divide(a_tma_view, (self.phys_block_kv, self.head_dim)) + a_tma_view = cute.select(a_tma_view, mode=[0, 1, 3]) + self.a_tma_view_layout = a_tma_view + tma_atom_a, tma_tensor_a = cpasync.make_tiled_tma_atom( + tma_load_op, a, a_tma_view[0], (self.phys_block_kv, self.head_dim) + ) + b_op = sm100_utils.cluster_shape_to_tma_atom_B(self.cluster_shape_mn, tiled_mma.thr_id) + b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0)) + tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B( + b_op, b, b_smem_layout, self.mma_tiler, tiled_mma, self.cluster_layout_vmnk.shape + ) + self.w_smem_layout_staged = cute.make_layout( + (self.N, self.num_q_stages), stride=(1, self.w_stage_stride) + ) + tma_atom_w, tma_tensor_w = cpasync.make_tiled_tma_atom( + tma_load_op, + weights, + cute.select(self.w_smem_layout_staged, mode=[0]), + self.w_smem_layout_staged.shape[:1], + ) + self.s_smem_layout_staged = cute.make_layout((self.block_kv, self.num_kv_stages)) + tma_atom_s, tma_tensor_s = cpasync.make_tiled_tma_atom( + tma_load_op, scales, cute.make_layout((phys_block_kv,)), (phys_block_kv,) + ) + b_copy_size = cute.size_in_bytes(b.element_type, b_smem_layout) + self.num_kv_scale_tma_bytes = self.num_blocks_per_mma * ( + phys_block_kv * self.head_dim // (2 if self.fp4 else 1) + phys_block_kv * 4 + ) + self.num_q_tma_bytes = b_copy_size * atom_thr_size + self.N * self.epi_bytes + tma_atom_sf_q = None + tma_tensor_sf_q = None + sf_q_smem_layout_staged = None + sf_q_tma_smem_layout_staged = None + tmem_sfa_layout = None + tmem_sfb_layout = None + sfa_chunk_smem_layout = None + sfb_chunk_smem_layout = None + copy_atom_s2t = None + if cutlass.const_expr(self.fp4): + tma_atom_sf_q, tma_tensor_sf_q = self._fp4_sf_q_atom(sf_q, tma_load_op) + self.num_q_tma_bytes = self.num_q_tma_bytes + self.N * 4 + sf_q_smem_layout_staged = self.sf_q_smem_layout_staged + sf_q_tma_smem_layout_staged = self.sf_q_tma_smem_layout_staged + tmem_sfa_layout = self.tmem_sfa_layout + tmem_sfb_layout = self.tmem_sfb_layout + sfa_chunk_smem_layout = self.sfa_chunk_smem_layout + sfb_chunk_smem_layout = self.sfb_chunk_smem_layout + copy_atom_s2t = self.copy_atom_s2t + tma_q = cudax.create_tensor_map_tiled( + global_address=q_att.iterator.toint(), + dtype=A.E4M3, + global_dims=[A.LATENT, A.HEADS, q_att.shape[0]], + global_strides=[A.LATENT // 16, A.HEADS * A.LATENT // 16], + box_dims=[A.SLICE, A.HEADS, 1], + swizzle=cudax.TensorMapSwizzle.s128b, + ) + tma_swa = cudax.create_tensor_map_tiled( + global_address=swa_pool.iterator.toint(), + dtype=A.E4M3, + global_dims=[A.LATENT, swa_pool.shape[0]], + global_strides=[A.LATENT // 16], + box_dims=[A.SLICE, 1], + swizzle=cudax.TensorMapSwizzle.s128b, + ) + tma_cmp = cudax.create_tensor_map_tiled( + global_address=c_pool.iterator.toint(), + dtype=A.E4M3, + global_dims=[A.LATENT, c_pool.shape[0]], + global_strides=[A.LATENT // 16], + box_dims=[A.SLICE, 1], + swizzle=cudax.TensorMapSwizzle.s128b, + ) + self.kernel( + tiled_mma, + tma_atom_a, + tma_tensor_a, + tma_atom_b, + tma_tensor_b, + tma_atom_w, + tma_tensor_w, + tma_atom_s, + tma_tensor_s, + tma_q, + tma_swa, + tma_cmp, + out, + block_table, + ctx, + desc, + swa_local, + bt_swa, + bt_c, + sinks, + swa_lens, + topk_out, + gidx, + ws64, + hist, + board, + region, + dbg_logits, + stamps, + ctl, + c_pool, + softmax_scale, + self.cluster_layout_vmnk, + self.a_smem_layout_staged, + self.b_smem_layout_staged, + self.w_smem_layout_staged, + self.s_smem_layout_staged, + self.a_tma_view_layout, + self.epi_tile, + tma_atom_sf_q, + tma_tensor_sf_q, + sf_q_smem_layout_staged, + sf_q_tma_smem_layout_staged, + tmem_sfa_layout, + tmem_sfb_layout, + sfa_chunk_smem_layout, + sfb_chunk_smem_layout, + copy_atom_s2t, + ).launch( + grid=(self.num_sms, 1, 1), + block=[512, 1, 1], + cluster=(2 if self.rs24 else 1, 1, 1), + stream=stream, + min_blocks_per_mp=1, + cooperative=self.coop, + ) + + @cute.kernel + def kernel( + self, + tiled_mma: cute.TiledMma, + tma_atom_a: cute.CopyAtom, + mA_mkl: cute.Tensor, + tma_atom_b: cute.CopyAtom, + mB_nkl: cute.Tensor, + tma_atom_w: cute.CopyAtom, + mW_tma: cute.Tensor, + tma_atom_s: cute.CopyAtom, + mS_tma: cute.Tensor, + tma_q: cutlass.GridConstant[cudax.TensorMap], + tma_swa: cutlass.GridConstant[cudax.TensorMap], + tma_cmp: cutlass.GridConstant[cudax.TensorMap], + mOut: cute.Tensor, + mBlockTable: cute.Tensor, + mCtx: cute.Tensor, + mDesc: cute.Tensor, + mSwaLocal: cute.Tensor, + mBtSwa: cute.Tensor, + mBtC: cute.Tensor, + mSinks: cute.Tensor, + mSwaLens: cute.Tensor, + mTopk: cute.Tensor, + mGidx: cute.Tensor, + mWs: cute.Tensor, + mHist: cute.Tensor, + mBoard: cute.Tensor, + mRegion: cute.Tensor, + mDbg: cute.Tensor, + mStamps: cute.Tensor, + mCtl: cute.Tensor, + mCPool: cute.Tensor, + softmax_scale: Float32, + cluster_layout_vmnk: cute.Layout, + a_smem_layout_staged: cute.ComposedLayout, + b_smem_layout_staged: cute.ComposedLayout, + w_smem_layout_staged: cute.Layout, + s_smem_layout_staged: cute.Layout, + a_tma_view_layout: cute.ComposedLayout, + epi_tile: cute.Tile, + tma_atom_sf_q: cute.CopyAtom = None, + mSF_Q_tma: cute.Tensor = None, + sf_q_smem_layout_staged: cute.Layout = None, + sf_q_tma_smem_layout_staged: cute.Layout = None, + tmem_sfa_layout: cute.Layout = None, + tmem_sfb_layout: cute.Layout = None, + sfa_chunk_smem_layout: cute.Layout = None, + sfb_chunk_smem_layout: cute.Layout = None, + copy_atom_s2t: cute.CopyAtom = None, + ): + bidx, _, _ = cute.arch.block_idx() + tidx, _, _ = cute.arch.thread_idx() + smem = cutlass.utils.SmemAllocator() + arena = smem.allocate(self.arena_bytes, byte_alignment=1024) + ws = mWs.iterator.toint() + if cutlass.const_expr(self.stamps): + if tidx == 0: + (mStamps.iterator + bidx * NSTAMP + ST_ENTRY).store(Int64(L.gtimer())) + if bidx < self.ns: + self._stream_cta( + arena, + bidx, + tidx, + ws, + mCtl, + tiled_mma, + tma_atom_a, + mA_mkl, + tma_atom_b, + mB_nkl, + tma_atom_w, + mW_tma, + tma_atom_s, + mS_tma, + mBlockTable, + mCtx, + mDesc, + mBtC, + mHist, + mBoard, + mRegion, + mDbg, + mStamps, + mCPool, + cluster_layout_vmnk, + a_smem_layout_staged, + b_smem_layout_staged, + w_smem_layout_staged, + s_smem_layout_staged, + a_tma_view_layout, + epi_tile, + tma_atom_sf_q, + mSF_Q_tma, + sf_q_smem_layout_staged, + sf_q_tma_smem_layout_staged, + tmem_sfa_layout, + tmem_sfb_layout, + sfa_chunk_smem_layout, + sfb_chunk_smem_layout, + copy_atom_s2t, + ) + else: + if cutlass.const_expr(self.nrows == 1): + self._team_cta( + arena, + bidx, + tidx, + ws, + tma_q, + tma_swa, + tma_cmp, + mOut, + mCtx, + mSwaLocal, + mBtSwa, + mBtC, + mSinks, + mSwaLens, + mTopk, + mGidx, + mHist, + mBoard, + mRegion, + mStamps, + mCtl, + softmax_scale, + mDesc, + mCPool, + ) + elif cutlass.const_expr(self.nteams < self.nrows): + # shared teams: team t = CTAs ns + 8t .. ns + 8t + 7 serves rows t, t + nteams, ... + tm_ = (bidx - Int32(self.ns)) // Int32(self.team_ctas) + cta_t = Int32(self.ns) + (bidx - Int32(self.ns)) % Int32(self.team_ctas) + self._team_cta_mr( + arena, + cta_t, + tidx, + ws, + tma_q, + tma_swa, + tma_cmp, + mOut, + mCtx, + mSwaLocal, + mBtSwa, + mBtC, + mSinks, + mSwaLens, + mTopk, + mGidx, + mHist, + mBoard, + mRegion, + cute.make_tensor( + mStamps.iterator + (bidx - cta_t) * Int32(NSTAMP), mStamps.layout + ), + mCtl, + softmax_scale, + mDesc, + mCPool, + tm_, + ) + else: + # team r = CTAs ns + 8r .. ns + 8r + 7, unchanged team code on row views + rs_ = self.row_sizes() + tr_ = (bidx - Int32(self.ns)) // Int32(self.team_ctas) + cta_t = Int32(self.ns) + (bidx - Int32(self.ns)) % Int32(self.team_ctas) + self._team_cta( + arena, + cta_t, + tidx, + ws + Int64(tr_) * Int64(rs_["ws"] * 8), + tma_q, + tma_swa, + tma_cmp, + _row2(mOut, tr_), + _row1(mCtx, tr_), + _row2(mSwaLocal, tr_), + _row2(mBtSwa, tr_), + _row2(mBtC, tr_), + mSinks, + _row1(mSwaLens, tr_), + _row2(mTopk, tr_), + _row2(mGidx, tr_), + _flat(mHist, tr_, rs_["hist"]), + _flat(mBoard, tr_, rs_["board"]), + _flat(mRegion, tr_, rs_["region"]), + cute.make_tensor( + mStamps.iterator + (bidx - cta_t) * Int32(NSTAMP), mStamps.layout + ), + _flat(mCtl, tr_, rs_["ctl"]), + softmax_scale, + _flat(mDesc, tr_, rs_["desc"]), + mCPool, + tr_, + ) + + def _svbi(self, r): + # entry of row r in the block-table slice ring (32 entries, reused by row r + 32) + if self.nrows > 32: + return r & Int32(31) + return r + + def _entry_words(self, svg, r): + # the three entry words of row r as _gen_from takes them; from 33 rows on the stored word is the + # generation itself (_gen_from(gen, 0, 0) == gen) + if self.nrows > 32: + return Uint64(svg[r]), Uint64(0), Uint64(0) + return ( + Uint64(svg[r * Int32(3)]), + Uint64(svg[r * Int32(3) + Int32(1)]), + Uint64(svg[r * Int32(3) + Int32(2)]), + ) + + def _lslot(self, r): + # logits slot of row r (ring: r & 7) + if self.ring: + return r & Int32(7) + return r + + def _mstr(self, mStamps, r): + # per-row stream stamps: slot base + 16 r of block 0 (PR); ring: row r's own block 8 + r + if self.ring: + return cute.make_tensor( + mStamps.iterator + (Int32(8) + r) * Int32(self.num_sms * NSTAMP), mStamps.layout + ) + return cute.make_tensor(mStamps.iterator + r * Int32(16), mStamps.layout) + + def _mstt(self, mStamps, r): + # stream T-server stamps: blocks 1 / 2 / 3 (PR); ring: block 24 + r + if self.ring: + return cute.make_tensor( + mStamps.iterator + (Int32(24) + r) * Int32(self.num_sms * NSTAMP), mStamps.layout + ) + return cute.make_tensor( + mStamps.iterator + + cutlass.select_( + r == Int32(self.nrows - 1), + Int32(3), + cutlass.select_(r == Int32(1), Int32(1), Int32(2)), + ) + * Int32(self.num_sms * NSTAMP), + mStamps.layout, + ) + + def row_sizes(self): + # per-row element counts of the flat buffers (ws64, hist, board, region, ctl, desc) + return dict( + ws=WS_WORDS, + hist=NGH * NB_DRS, + board=BOARD_CAP, + region=self.ns * CAPR * 2, + ctl=16, + desc=self.num_sms * DESC_WORDS, + ) + + @staticmethod + def _w(ws, i): + return ws + Int64(i) * Int64(8) + + @cute.jit + def _skew(self, gen, cta, salt): + if cutlass.const_expr(self.skew > 0): + L.skew_sleep( + Int32(Uint32(gen & Uint64(4294967295))), + cta * Int32(64) + Int32(salt), + Int32(self.skew), + ) + + @cute.jit + def _stamp(self, mStamps, cta, slot): + if cutlass.const_expr(self.stamps): + (mStamps.iterator + cta * NSTAMP + slot).store(Int64(L.gtimer())) + + @cute.jit + def _stream_cta( + self, + arena, + cta, + tidx, + ws, + mCtl, + tiled_mma, + tma_atom_a, + mA_mkl, + tma_atom_b, + mB_nkl, + tma_atom_w, + mW_tma, + tma_atom_s, + mS_tma, + mBlockTable, + mCtx, + mDesc, + mBtC, + mHist, + mBoard, + mRegion, + mDbg, + mStamps, + mCPool, + cluster_layout_vmnk, + a_smem_layout_staged, + b_smem_layout_staged, + w_smem_layout_staged, + s_smem_layout_staged, + a_tma_view_layout, + epi_tile, + tma_atom_sf_q=None, + mSF_Q_tma=None, + sf_q_smem_layout_staged=None, + sf_q_tma_smem_layout_staged=None, + tmem_sfa_layout=None, + tmem_sfb_layout=None, + sfa_chunk_smem_layout=None, + sfb_chunk_smem_layout=None, + copy_atom_s2t=None, + ): + warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + lane = tidx % 32 + NUM_BLOCKS_PER_MMA = self.num_blocks_per_mma + gw1 = Uint64(0) + gw2 = Uint64(0) + gw3 = Uint64(0) + if tidx == 0: + gw1, gw2, gw3 = self._entry_loads(ws) + desc_lane = mDesc[cta * 32 + lane] + if cutlass.const_expr(self.early): + # The descriptor load above stays the first global load and the TMA warps prefetch their + # descriptors now, so both round trips overlap the barrier init and bar.sync 0. + if warp_idx == 8 or warp_idx == 9: + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_s) + if warp_idx == 8: + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_w) + if cutlass.const_expr(self.nrows > 1 or not self.early): + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n_desc = cute.arch.shuffle_sync(desc_lane, 2) + ord0 = cute.arch.shuffle_sync(desc_lane, 3) + ord1 = cute.arch.shuffle_sync(desc_lane, 4) + nwin = cute.arch.shuffle_sync(desc_lane, 5) + n = n_desc + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + t_lo = s0 * Int32(SPLIT_TOK) + nwin0 = (nwin + Int32(1)) // Int32(2) + nwin1 = nwin // Int32(2) + storage_bar = cute.recast_ptr(arena + S_OFF_BAR, dtype=Int64) + misc_i32 = cute.recast_ptr(arena + S_OFF_MISC, dtype=Int32) + kv_mbar_0 = storage_bar + kv_mbar_1 = storage_bar + 2 * self.num_kv_stages + q_mbar = storage_bar + 4 * self.num_kv_stages + umma_mbar_0 = q_mbar + 2 * self.num_q_stages + umma_mbar_1 = umma_mbar_0 + 2 + tmem_hold = misc_i32 + _s_tl = cute.make_tensor(misc_i32 + 4, cute.make_layout(8)) + s_scan = cute.make_tensor(misc_i32 + 16, cute.make_layout(32)) + s_tv = cute.make_tensor(misc_i32 + 48, cute.make_layout(4)) + s_wc = cute.make_tensor(misc_i32 + 52, cute.make_layout(8)) + sSub = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_SUB, dtype=Int64), cute.make_layout(8 * SUBCAP) + ) + tbar = storage_bar + S_BAR_T + q_free = storage_bar + (S_BAR_T + 1) + if tidx == 0: + prims.mbarrier_init(tbar, 1) + if cutlass.const_expr(self.early and self.nrows == 1): + # A zero that the descriptor shuffles read back (volatile) after bar.sync 0. + sts_volatile_u32( + Int32(cute.recast_ptr(arena + S_OFF_MISC + 60 * 4, dtype=Int32).toint()), + Int32(0), + ) + if cutlass.const_expr(self.nrows > 1): + # the Q / W stage is free again once both MMA groups' last MMAs of a row completed (tcgen05.commit) + # and the math warps read the row's weights + prims.mbarrier_init(q_free, 3) + if cutlass.const_expr(self.qdb): + prims.mbarrier_init(q_free + 1, 3) + for rb_ in cutlass.range_constexpr(self.nslot): + prims.mbarrier_init(cute.recast_ptr(arena + self.s_svm, dtype=Int64) + rb_, 1) + # row T armed by the T poller + prims.mbarrier_init(cute.recast_ptr(arena + self.s_svtb, dtype=Int64) + rb_, 1) + if cutlass.const_expr(self.ring): + for rb_ in cutlass.range_constexpr(8): + # logits slot rb_ free again (its row reached K_DONE): one publisher arrival + prims.mbarrier_init( + cute.recast_ptr(arena + self.s_slf, dtype=Int64) + rb_, 1 + ) + if cutlass.const_expr(self.nrows > 32): + for rb_ in cutlass.range_constexpr(self.nrows - 32): + # block-table slice entry rb_ free again (the publishers are done with row rb_): one arrival + prims.mbarrier_init( + cute.recast_ptr(arena + self.s_sfb, dtype=Int64) + rb_, 1 + ) + prims.fence_mbarrier_init() + sLog = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_LOG, dtype=Float32), cute.make_layout(MAXS * SPLIT_TOK) + ) + sBtc = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_BTC, dtype=Int32), cute.make_layout(MAXS * 8) + ) + prod_group = pipeline.CooperativeGroup(pipeline.Agent.Thread) + kv_cons_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 4) + q_cons_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 8) + q_pipeline = pipeline.PipelineTmaAsync.create( + barrier_storage=q_mbar, + num_stages=self.num_q_stages, + producer_group=prod_group, + consumer_group=q_cons_group, + tx_count=self.num_q_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + if cutlass.const_expr(self.fp4): + # the tensor core consumes the K tile and its scale factors: the UMMA warp releases the stage + # (tcgen05.commit) + kv_pipeline_0 = pipeline.PipelineTmaUmma.create( + barrier_storage=kv_mbar_0, + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 1), + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + kv_pipeline_1 = pipeline.PipelineTmaUmma.create( + barrier_storage=kv_mbar_1, + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 1), + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + else: + kv_pipeline_0 = pipeline.PipelineTmaAsync.create( + barrier_storage=kv_mbar_0, + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + kv_pipeline_1 = pipeline.PipelineTmaAsync.create( + barrier_storage=kv_mbar_1, + num_stages=self.num_kv_stages, + producer_group=prod_group, + consumer_group=kv_cons_group, + tx_count=self.num_kv_scale_tma_bytes, + cta_layout_vmnk=cluster_layout_vmnk, + tidx=tidx, + defer_sync=True, + ) + if cutlass.const_expr(self.rs24): + lane0_ = tidx % Int32(32) == Int32(0) + q_pipeline = dataclasses.replace(q_pipeline, is_signaling_thread=lane0_) + if cutlass.const_expr(not self.fp4): + kv_pipeline_0 = dataclasses.replace(kv_pipeline_0, is_signaling_thread=lane0_) + kv_pipeline_1 = dataclasses.replace(kv_pipeline_1, is_signaling_thread=lane0_) + umma_pipeline_0 = pipeline.PipelineUmmaAsync.create( + barrier_storage=umma_mbar_0, + num_stages=1, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 128), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + umma_pipeline_1 = pipeline.PipelineUmmaAsync.create( + barrier_storage=umma_mbar_1, + num_stages=1, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 128), + cta_layout_vmnk=cluster_layout_vmnk, + defer_sync=True, + ) + q_prod_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_q_stages + ) + q_cons_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_q_stages + ) + kv_prod_state_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_kv_stages + ) + kv_prod_state_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.num_kv_stages + ) + kv_cons_state_umma_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_umma_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_math_0 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + kv_cons_state_math_1 = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.num_kv_stages + ) + umma_prod_state_0 = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, 1) + umma_prod_state_1 = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, 1) + umma_cons_state_0 = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, 1) + umma_cons_state_1 = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, 1) + if cutlass.const_expr(self.fp4): + sfb_sync_barrier = pipeline.NamedBarrier(barrier_id=10, num_threads=64) + tmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=320) + tmem = cutlass.utils.TmemAllocator( + tmem_hold, + barrier_for_retrieve=tmem_alloc_barrier, + allocator_warp_id=0, + is_two_cta=False, + ) + gen_slot = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_MISC + 256, dtype=Int64), cute.make_layout(4) + ) + pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True) + sKV_0 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_KV0, a_smem_layout_staged.inner, dtype=self.a_dtype), + a_smem_layout_staged.outer, + ) + sKV_1 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_KV1, a_smem_layout_staged.inner, dtype=self.a_dtype), + a_smem_layout_staged.outer, + ) + sQ = cute.make_tensor( + cute.recast_ptr(arena + self.s_off_q, b_smem_layout_staged.inner, dtype=self.b_dtype), + b_smem_layout_staged.outer, + ) + sW = cute.make_tensor( + cute.recast_ptr(arena + self.s_off_w, dtype=self.epi_dtype), w_smem_layout_staged + ) + scale_dtype = cutlass.Int32 if self.fp4 else cutlass.Float32 + sScales_0 = cute.make_tensor( + cute.recast_ptr(arena + self.s_off_sc0, dtype=scale_dtype), s_smem_layout_staged + ) + sScales_1 = cute.make_tensor( + cute.recast_ptr(arena + self.s_off_sc1, dtype=scale_dtype), s_smem_layout_staged + ) + if cutlass.const_expr(self.fp4): + sSF_Q = cute.make_tensor( + cute.recast_ptr(arena + self.s_off_sfq, dtype=cutlass.Int32), + sf_q_smem_layout_staged, + ) + thr_mma = tiled_mma.get_slice(0) + sKV_0_for_tma = cute.make_tensor(sKV_0.iterator, a_tma_view_layout.outer) + sKV_1_for_tma = cute.make_tensor(sKV_1.iterator, a_tma_view_layout.outer) + gA = cute.local_tile(mA_mkl, (self.phys_block_kv, self.head_dim), coord=(None, None, None)) + tAsA_0, tAgA_0 = cpasync.tma_partition( + tma_atom_a, 0, cute.make_layout(1), sKV_0_for_tma, cute.group_modes(gA, 0, 2) + ) + tAsA_1, tAgA_1 = cpasync.tma_partition( + tma_atom_a, 0, cute.make_layout(1), sKV_1_for_tma, cute.group_modes(gA, 0, 2) + ) + gB_nkl = cute.local_tile( + mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None) + ) + tCgB = thr_mma.partition_B(gB_nkl) + b_cta_layout = cute.make_layout(cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape) + tBsB, tBgB = cpasync.tma_partition( + tma_atom_b, 0, b_cta_layout, cute.group_modes(sQ, 0, 3), cute.group_modes(tCgB, 0, 3) + ) + tBgB = tBgB[None, 0, None, None] + tWsW, tWgW = cpasync.tma_partition( + tma_atom_w, + 0, + cute.make_layout((1,)), + cute.group_modes(sW, 0, 1), + cute.group_modes(mW_tma, 0, 1), + ) + s_tma_view_layout = cute.make_layout( + (self.phys_block_kv, self.num_blocks_per_mma, self.num_kv_stages), + stride=(1, self.phys_block_kv, self.block_kv), + ) + sScales_0_for_tma = cute.make_tensor(sScales_0.iterator, s_tma_view_layout) + sScales_1_for_tma = cute.make_tensor(sScales_1.iterator, s_tma_view_layout) + gS = cute.local_tile(mS_tma, (self.phys_block_kv,), coord=(None, None)) + tSsS_0, tSgS_0 = cpasync.tma_partition( + tma_atom_s, 0, cute.make_layout(1), sScales_0_for_tma, gS + ) + tSsS_1, tSgS_1 = cpasync.tma_partition( + tma_atom_s, 0, cute.make_layout(1), sScales_1_for_tma, gS + ) + if cutlass.const_expr(self.fp4): + sSF_Q_for_tma = cute.make_tensor(sSF_Q.iterator, sf_q_tma_smem_layout_staged) + tSF_Q_sSF_Q, tSF_Q_gSF_Q = cpasync.tma_partition( + tma_atom_sf_q, + 0, + cute.make_layout((1,)), + cute.group_modes(sSF_Q_for_tma, 0, 1), + cute.group_modes(mSF_Q_tma, 0, 1), + ) + tCrA_0 = tiled_mma.make_fragment_A(sKV_0) + tCrA_1 = tiled_mma.make_fragment_A(sKV_1) + tCrB = tiled_mma.make_fragment_B(sQ) + acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2]) + acc_shape_staged = cute.append(acc_shape, 1) + tCtAcc_fake_staged = tiled_mma.make_fragment_C(acc_shape_staged) + cols_per_group = self.num_tmem_alloc_cols * 1 * (32 // self.acc_dtype.width) + c_layout = cutlass.utils.LayoutEnum.ROW_MAJOR + epi_sub_mn = (epi_tile[0], self.num_heads) + copy_atom_t2r = sm100_utils.get_tmem_load_op( + self.cta_tile_shape_mnk, c_layout, self.acc_dtype, self.acc_dtype, epi_sub_mn, False + ) + pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn) + if cutlass.const_expr(self.nrows == 1): + if cutlass.const_expr(self.early): + # At 1 row the descriptor fields are read after bar.sync 0 and only the math warps + # (the users of SMP / SS2) run the ladder. Adding the volatile zero keeps the + # shuffles below the barrier. + desc_lane = desc_lane + lds_volatile_u32( + Int32(cute.recast_ptr(arena + S_OFF_MISC + 60 * 4, dtype=Int32).toint()) + ) + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n_desc = cute.arch.shuffle_sync(desc_lane, 2) + ord0 = cute.arch.shuffle_sync(desc_lane, 3) + ord1 = cute.arch.shuffle_sync(desc_lane, 4) + nwin = cute.arch.shuffle_sync(desc_lane, 5) + n = n_desc + SMP = Int32(0) + SS2 = Int32(1) + TGT = Int32(0) + TGT2 = Int32(0) + wst = Int32(8) + t_lo = s0 * Int32(SPLIT_TOK) + nwin0 = (nwin + Int32(1)) // Int32(2) + nwin1 = nwin // Int32(2) + if warp_idx == 8 or warp_idx == 9: + cute.arch.warpgroup_reg_dealloc(24) + grp = warp_idx - 8 + if cutlass.const_expr(not self.early): + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_s) + pol = None + if cutlass.const_expr(self.policy != L.POL_NONE): + pol = L.make_l2_policy(self.policy) + bt_cols = cute.size(mBlockTable, mode=[1]) + bta = mBlockTable[0, cutlass.min(Int32(8) * s0 + lane, bt_cols - 1)] + btb = mBlockTable[0, cutlass.min(Int32(8) * s0 + Int32(32) + lane, bt_cols - 1)] + ntile_row = (n + Int32(TILE - 1)) // Int32(TILE) + t_ref = Int64(0) + if cutlass.const_expr(self.wdelay > 0): + t_ref = Int64(L.gtimer()) + if grp == 0: + if cutlass.const_expr(not self.early): + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_w) + q_pipeline.producer_acquire(q_prod_state) + q_bar = q_pipeline.producer_get_barrier(q_prod_state) + cute.copy( + tma_atom_b, + tBgB[None, 0, 0], + tBsB[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + cute.copy( + tma_atom_w, tWgW[None, 0], tWsW[None, q_prod_state.index], tma_bar_ptr=q_bar + ) + if cutlass.const_expr(self.fp4): + cute.copy( + tma_atom_sf_q, + tSF_Q_gSF_Q[None, 0], + tSF_Q_sSF_Q[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + q_prod_state.advance() + for i in cutlass.range(ns, unroll=1): + if cutlass.const_expr(self.wdelay > 0): + if i == nwin0: + tnow = Int64(L.gtimer()) + while tnow - t_ref < Int64(self.wdelay): + tnow = Int64(L.gtimer()) + tl = ord0 >> Int32(4) * i & Int32(15) + tile = Int32(2) * s0 + tl + tile_ok = tile < ntile_row + phys = [Int32(0)] * NUM_BLOCKS_PER_MMA + if i < 3: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + phys[k] = cute.arch.shuffle_sync( + desc_lane, Int32(8 + 4 * 0 + k) + Int32(8) * i + ) + else: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + rel = Int32(4) * tl + Int32(k) + pa = cute.arch.shuffle_sync(bta, rel & Int32(31)) + pb = cute.arch.shuffle_sync(btb, rel & Int32(31)) + pv = cutlass.select_(rel >= Int32(32), pb, pa) + phys[k] = cutlass.select_(tile_ok, pv, Int32(0)) + kv_pipeline_0.producer_acquire(kv_prod_state_0) + if cutlass.const_expr(self.stamps): + if i == 0: + if lane == 0: + (mStamps.iterator + cta * NSTAMP + ST_FIRST_TMA).store( + Int64(L.gtimer()) + ) + bar = kv_pipeline_0.producer_get_barrier(kv_prod_state_0) + stage = kv_prod_state_0.index + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_0[None, 0, 0, phys[k]], + tAsA_0[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_0[None, 0, phys[k]], + tSsS_0[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_0.advance() + else: + for i in cutlass.range(ns, unroll=1): + if cutlass.const_expr(self.wdelay > 0): + if i == nwin1: + tnow = Int64(L.gtimer()) + while tnow - t_ref < Int64(self.wdelay): + tnow = Int64(L.gtimer()) + tl = ord1 >> Int32(4) * i & Int32(15) + tile = Int32(2) * s0 + tl + tile_ok = tile < ntile_row + phys = [Int32(0)] * NUM_BLOCKS_PER_MMA + if i < 3: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + phys[k] = cute.arch.shuffle_sync( + desc_lane, Int32(8 + 4 * 1 + k) + Int32(8) * i + ) + else: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + rel = Int32(4) * tl + Int32(k) + pa = cute.arch.shuffle_sync(bta, rel & Int32(31)) + pb = cute.arch.shuffle_sync(btb, rel & Int32(31)) + pv = cutlass.select_(rel >= Int32(32), pb, pa) + phys[k] = cutlass.select_(tile_ok, pv, Int32(0)) + kv_pipeline_1.producer_acquire(kv_prod_state_1) + bar = kv_pipeline_1.producer_get_barrier(kv_prod_state_1) + stage = kv_prod_state_1.index + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_1[None, 0, 0, phys[k]], + tAsA_1[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_1[None, 0, phys[k]], + tSsS_1[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_1.advance() + elif warp_idx == 10 or warp_idx == 11: + cute.arch.warpgroup_reg_dealloc(24) + grp = warp_idx - 10 + L.bar(1, 320) + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base_0 = cute.make_tensor(tmem_ptr, tCtAcc_fake_staged.layout) + tCtAcc_base_1 = cute.make_tensor( + tmem_ptr + cols_per_group, tCtAcc_fake_staged.layout + ) + num_k_blocks = cute.size(tCrA_0.shape[2]) + q_pipeline.consumer_wait(q_cons_state) + q_stage = q_cons_state.index + if cutlass.const_expr(self.fp4): + if grp == 0: + for atom_idx in cutlass.range_constexpr(self.N_padded // 128): + L.sf_atom_transpose( + sSF_Q.iterator + q_stage * sSF_Q.layout.stride[1] + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sfb_sync_barrier.arrive_and_wait() + if grp == 0: + if cutlass.const_expr(self.fp4): + tCtSFA = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + self.sf_tmem_base + 0 * self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfa_layout, + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + + self.sfb_tmem_base + + (0 * self.num_q_stages + q_stage) * self.num_sfb_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + sSF_Q_ue8m0 = cute.recast_tensor(sSF_Q, Float8E8M0FNU) + sSF_Q_chunk = cute.make_tensor( + sSF_Q_ue8m0.iterator + q_stage * sSF_Q_ue8m0.layout.stride[1], + sfb_chunk_smem_layout, + ) + tCsSFB_compact = cute.filter_zeros(sSF_Q_chunk) + tCtSFB_compact = cute.filter_zeros(tCtSFB) + tiled_copy_s2t_sfb = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSFB_compact) + thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0) + tCsSFB_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact) + tCsSFB_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfb, tCsSFB_s2t_ + ) + tCtSFB_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact) + cute.copy(tiled_copy_s2t_sfb, tCsSFB_s2t, tCtSFB_s2t) + cute.arch.fence_view_async_tmem_store() + for i in cutlass.range(ns, unroll=1): + kv_pipeline_0.consumer_wait(kv_cons_state_umma_0) + umma_pipeline_0.producer_acquire(umma_prod_state_0) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage = kv_cons_state_umma_0.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_0.iterator + + kv_stage * sScales_0.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_ue8m0 = cute.recast_tensor(sScales_0, Float8E8M0FNU) + sSF_KV_chunk = cute.make_tensor( + sSF_KV_ue8m0.iterator + kv_stage * sSF_KV_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact = cute.filter_zeros(sSF_KV_chunk) + tCtSFA_compact = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact + ) + thr_copy_s2t_sfa = tiled_copy_s2t_sfa.get_slice(0) + tCsSFA_s2t_ = thr_copy_s2t_sfa.partition_S(tCsSFA_compact) + tCsSFA_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa, tCsSFA_s2t_ + ) + tCtSFA_s2t = thr_copy_s2t_sfa.partition_D(tCtSFA_compact) + cute.copy(tiled_copy_s2t_sfa, tCsSFA_s2t, tCtSFA_s2t) + tCtAcc_0 = tCtAcc_base_0[None, None, None, umma_prod_state_0.index] + for k_block in cutlass.range_constexpr(num_k_blocks): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_0, + tCrA_0[None, None, k_block, kv_stage], + tCrB[None, None, k_block, q_stage], + tCtAcc_0, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_0.consumer_release(kv_cons_state_umma_0) + kv_cons_state_umma_0.advance() + umma_pipeline_0.producer_commit(umma_prod_state_0) + umma_prod_state_0.advance() + else: + if cutlass.const_expr(self.fp4): + tCtSFA = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + self.sf_tmem_base + 1 * self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfa_layout, + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + + self.sfb_tmem_base + + (1 * self.num_q_stages + q_stage) * self.num_sfb_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + sSF_Q_ue8m0 = cute.recast_tensor(sSF_Q, Float8E8M0FNU) + sSF_Q_chunk = cute.make_tensor( + sSF_Q_ue8m0.iterator + q_stage * sSF_Q_ue8m0.layout.stride[1], + sfb_chunk_smem_layout, + ) + tCsSFB_compact = cute.filter_zeros(sSF_Q_chunk) + tCtSFB_compact = cute.filter_zeros(tCtSFB) + tiled_copy_s2t_sfb = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSFB_compact) + thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0) + tCsSFB_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact) + tCsSFB_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfb, tCsSFB_s2t_ + ) + tCtSFB_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact) + cute.copy(tiled_copy_s2t_sfb, tCsSFB_s2t, tCtSFB_s2t) + cute.arch.fence_view_async_tmem_store() + for i in cutlass.range(ns, unroll=1): + kv_pipeline_1.consumer_wait(kv_cons_state_umma_1) + umma_pipeline_1.producer_acquire(umma_prod_state_1) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage_1 = kv_cons_state_umma_1.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_1.iterator + + kv_stage_1 * sScales_1.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_ue8m0 = cute.recast_tensor(sScales_1, Float8E8M0FNU) + sSF_KV_chunk = cute.make_tensor( + sSF_KV_ue8m0.iterator + kv_stage_1 * sSF_KV_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact = cute.filter_zeros(sSF_KV_chunk) + tCtSFA_compact = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact + ) + thr_copy_s2t_sfa = tiled_copy_s2t_sfa.get_slice(0) + tCsSFA_s2t_ = thr_copy_s2t_sfa.partition_S(tCsSFA_compact) + tCsSFA_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa, tCsSFA_s2t_ + ) + tCtSFA_s2t = thr_copy_s2t_sfa.partition_D(tCtSFA_compact) + cute.copy(tiled_copy_s2t_sfa, tCsSFA_s2t, tCtSFA_s2t) + tCtAcc_1 = tCtAcc_base_1[None, None, None, umma_prod_state_1.index] + for k_block in cutlass.range_constexpr(num_k_blocks): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_1, + tCrA_1[None, None, k_block, kv_stage_1], + tCrB[None, None, k_block, q_stage], + tCtAcc_1, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_1.consumer_release(kv_cons_state_umma_1) + kv_cons_state_umma_1.advance() + umma_pipeline_1.producer_commit(umma_prod_state_1) + umma_prod_state_1.advance() + elif warp_idx < 8: + cute.arch.warpgroup_reg_alloc(self.math_regs) + wg = warp_idx // 4 + tmem.allocate(self.num_tmem_alloc_cols_total) + L.bar(1, 320) + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base_0 = cute.make_tensor(tmem_ptr, tCtAcc_fake_staged.layout) + tCtAcc_base_1 = cute.make_tensor( + tmem_ptr + cols_per_group, tCtAcc_fake_staged.layout + ) + if cutlass.const_expr(self.early): + # The board-sample ladder, in the math warps only. + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + local_tidx = tidx % 128 + cC = cute.make_identity_tensor(epi_sub_mn) + if tidx == 0: + gen_slot[0] = Int64(gw1) + gen_slot[1] = Int64(gw2) + gen_slot[2] = Int64(gw3) + q_pipeline.consumer_wait(q_cons_state) + q_stage_local = q_cons_state.index + w_cache = cute.make_rmem_tensor((self.num_w_in_reg,), self.epi_dtype) + for w_j in cutlass.range_constexpr(self.num_w_in_reg): + w_cache[w_j] = sW[w_j, q_stage_local] + if cutlass.const_expr(self.fp4): + # jw = pos // wst as umulhi(pos, magic): exact for pos < 2^18, 8 <= wst < 2^14 + # (the ladder's wst <= 920) + wmag = Uint64(Uint32(4294967295) // Uint32(wst) + Uint32(1)) + L.bar(6, 288) + gen = self._gen_from(Uint64(gen_slot[0]), Uint64(gen_slot[1]), Uint64(gen_slot[2])) + if tidx == 0: + if n_desc != mCtx[0]: + self._flag(ws, gen, Int32(E_STALE)) + if n_desc < Int32(0) or n_desc > Int32(N_MAX): + self._flag(ws, gen, Int32(E_NLIMIT)) + bboard = mBoard.iterator.toint() + btag = Uint64(self._tag32(gen)) << Uint64(32) + ci = Int32(0) + cnt1 = Int32(0) + tk = Int32(0) + Tv = Float32(float("inf")) + wsub = warp_idx * Int32(SUBCAP) + if wg == 0: + tAcc_0_ref = tCtAcc_base_0[None, None, None, 0][(None, None), 0, 0] + tAcc_0_ref_epi = cute.flat_divide(tAcc_0_ref, epi_sub_mn) + tiled_copy_ref_0 = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_0_ref_epi[None, None, 0, 0] + ) + thr_copy_ref_0 = tiled_copy_ref_0.get_slice(local_tidx) + tTR_cC = thr_copy_ref_0.partition_D(cC) + m_coord = tTR_cC[0][0] + tTR_rAcc = cute.make_fragment_like(tTR_cC, self.acc_dtype) + for i in cutlass.range(ns + Int32(1), unroll=1): + if i < ns: + tl = ord0 >> Int32(4) * i & Int32(15) + pos = (Int32(2) * s0 + tl) * Int32(TILE) + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready = kv_pipeline_0.consumer_try_wait(kv_cons_state_math_0) + umma_ready = umma_pipeline_0.consumer_try_wait(umma_cons_state_0) + if cutlass.const_expr(not self.fp4): + kv_pipeline_0.consumer_wait(kv_cons_state_math_0, kv_ready) + scale_val = sScales_0[m_coord, kv_cons_state_math_0.index] + else: + scale_val = Float32(1.0) + umma_pipeline_0.consumer_wait(umma_cons_state_0, umma_ready) + tCtAcc_c0 = tCtAcc_base_0[None, None, None, umma_cons_state_0.index] + tAcc_c0 = tCtAcc_c0[(None, None), 0, 0] + tTR_0 = thr_copy_ref_0.partition_S( + cute.flat_divide(tAcc_c0, epi_sub_mn) + ) + if cutlass.const_expr(not self.fp4): + # The scale load from this K stage must complete before the + # release lets the TMA refill the stage. + L.fence_proxy_async_smem() + kv_pipeline_0.consumer_release(kv_cons_state_math_0) + kv_cons_state_math_0.advance() + cute.copy(tiled_copy_ref_0, tTR_0[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + umma_pipeline_0.consumer_release(umma_cons_state_0) + umma_cons_state_0.advance() + val = self._epi_value( + tTR_rAcc, w_cache, sW, self.num_w_in_reg, scale_val + ) + sLog[tl * Int32(TILE) + m_coord] = val + if cutlass.const_expr(self.debug): + if pos < n: + mDbg[pos] = val + if cutlass.const_expr(self.fp4): + jw = Int32((Uint64(pos) * wmag) >> Uint64(32)) + else: + jw = pos // wst + if pos - jw * wst < Int32(8): + if jw < SMP: + st_rlx_u64( + bboard + Int64(jw * Int32(8) + (pos - jw * wst)) * Int64(8), + btag | Uint64(L.u32_of_f32(val)), + ) + if cutlass.const_expr(self.stamps): + if i == 0: + if local_tidx == 0: + (mStamps.iterator + cta * NSTAMP + ST_FIRST_EPI).store( + Int64(L.gtimer()) + ) + if cutlass.const_expr(self.stamps): + if i + Int32(1) == nwin0: + if local_tidx == 0: + (mStamps.iterator + cta * NSTAMP + ST_BOARD).store( + Int64(L.gtimer()) + ) + tk, Tv = self._t_known(tk, Tv, i, ns, tbar, s_tv) + if tk != Int32(0): + ci, cnt1 = self._classify_tasks( + ci, + cutlass.min(i, ns - Int32(1)), + ord0, + t_lo, + n, + m_coord, + sLog, + sSub, + wsub, + cnt1, + Tv, + ) + else: + tAcc_1_ref = tCtAcc_base_1[None, None, None, 0][(None, None), 0, 0] + tAcc_1_ref_epi = cute.flat_divide(tAcc_1_ref, epi_sub_mn) + tiled_copy_ref_1 = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_1_ref_epi[None, None, 0, 0] + ) + thr_copy_ref_1 = tiled_copy_ref_1.get_slice(local_tidx) + tTR_cC = thr_copy_ref_1.partition_D(cC) + m_coord = tTR_cC[0][0] + tTR_rAcc = cute.make_fragment_like(tTR_cC, self.acc_dtype) + for i in cutlass.range(ns + Int32(1), unroll=1): + if i < ns: + tl = ord1 >> Int32(4) * i & Int32(15) + pos = (Int32(2) * s0 + tl) * Int32(TILE) + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready = kv_pipeline_1.consumer_try_wait(kv_cons_state_math_1) + umma_ready = umma_pipeline_1.consumer_try_wait(umma_cons_state_1) + if cutlass.const_expr(not self.fp4): + kv_pipeline_1.consumer_wait(kv_cons_state_math_1, kv_ready) + scale_val = sScales_1[m_coord, kv_cons_state_math_1.index] + else: + scale_val = Float32(1.0) + umma_pipeline_1.consumer_wait(umma_cons_state_1, umma_ready) + tCtAcc_c1 = tCtAcc_base_1[None, None, None, umma_cons_state_1.index] + tAcc_c1 = tCtAcc_c1[(None, None), 0, 0] + tTR_1 = thr_copy_ref_1.partition_S( + cute.flat_divide(tAcc_c1, epi_sub_mn) + ) + if cutlass.const_expr(not self.fp4): + # The scale load from this K stage must complete before the + # release lets the TMA refill the stage. + L.fence_proxy_async_smem() + kv_pipeline_1.consumer_release(kv_cons_state_math_1) + kv_cons_state_math_1.advance() + cute.copy(tiled_copy_ref_1, tTR_1[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + umma_pipeline_1.consumer_release(umma_cons_state_1) + umma_cons_state_1.advance() + val = self._epi_value( + tTR_rAcc, w_cache, sW, self.num_w_in_reg, scale_val + ) + sLog[tl * Int32(TILE) + m_coord] = val + if cutlass.const_expr(self.debug): + if pos < n: + mDbg[pos] = val + if cutlass.const_expr(self.fp4): + jw = Int32((Uint64(pos) * wmag) >> Uint64(32)) + else: + jw = pos // wst + if pos - jw * wst < Int32(8): + if jw < SMP: + st_rlx_u64( + bboard + Int64(jw * Int32(8) + (pos - jw * wst)) * Int64(8), + btag | Uint64(L.u32_of_f32(val)), + ) + tk, Tv = self._t_known(tk, Tv, i, ns, tbar, s_tv) + if tk != Int32(0): + ci, cnt1 = self._classify_tasks( + ci, + cutlass.min(i, ns - Int32(1)), + ord1, + t_lo, + n, + m_coord, + sLog, + sSub, + wsub, + cnt1, + Tv, + ) + b1e_ = None + if cutlass.const_expr(self.b1l and self.b1l_e): + # Bins and histogram atom.adds of each warp's first U x 32 candidates now (T is + # known), so their round trip overlaps the stream-end barrier, the TMEM free and + # the prefix. + cute.arch.sync_warp() + b1e_ = self._b1l_issue( + sSub, + wsub, + cnt1, + tidx % Int32(32), + Tv, + L.f32_of_u32(Uint32(s_tv[1])), + mHist.iterator.toint(), + self.b1l_u, + SUBCAP, + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + L.bar(3, 256) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(self.stamps): + if tidx == 0: + (mStamps.iterator + cta * NSTAMP + ST_STREAM_END).store(Int64(L.gtimer())) + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + self._stream_publish( + cta, + tidx, + ws, + gen, + ns, + n, + t_lo, + cnt1, + wsub, + sSub, + sBtc, + s_wc, + s_scan, + sLog, + mRegion, + mHist, + mStamps, + mCPool, + arena, + mCtl, + Tv, + s_tv, + b1e_=b1e_, + ) + else: + cute.arch.warpgroup_reg_dealloc(24) + if warp_idx == 12: + btc_cols = cute.size(mBtC, mode=[1]) + for e in cutlass.range_constexpr(2): + j = lane + Int32(32 * e) + if j < Int32(8) * ns: + sBtc[j] = mBtC[0, cutlass.min(Int32(8) * s0 + j, btc_cols - 1)] + L.bar_arrive(5, 384) + if warp_idx == 12: + L.bar(6, 288) + genh = self._gen_from( + Uint64(gen_slot[0]), Uint64(gen_slot[1]), Uint64(gen_slot[2]) + ) + if lane == 0: + tv, sv = self._poll_tline1(ws, genh) + s_tv[0] = Int32(tv) + s_tv[1] = Int32(sv) + prims.mbarrier_arrive(tbar) + self._stamp(mStamps, cta, ST_T_SEEN) + else: + if warp_idx == 8 or warp_idx == 9: + cute.arch.warpgroup_reg_dealloc(24) + grp = warp_idx - 8 + if cutlass.const_expr(not self.early): + cpasync.prefetch_descriptor(tma_atom_a) + cpasync.prefetch_descriptor(tma_atom_s) + pol = None + if cutlass.const_expr(self.policy != L.POL_NONE): + pol = L.make_l2_policy(self.policy) + bt_cols = cute.size(mBlockTable, mode=[1]) + if cutlass.const_expr(not self.early): + cpasync.prefetch_descriptor(tma_atom_b) + cpasync.prefetch_descriptor(tma_atom_w) + if cutlass.const_expr(self.dpf): + if cutlass.const_expr(self.early): + # Row 0's descriptor is the entry load. + dnx_ = desc_lane + else: + dnx_ = mDesc[cta * Int32(32) + lane] + else: + dnx_ = Int32(0) + for r_ in cutlass.range(self.nrows, unroll=1): + mStR_ = self._mstr(mStamps, r_) + if cutlass.const_expr(self.dpf): + desc_lane = dnx_ + dnx_ = mDesc[ + ( + cutlass.min(r_ + Int32(1), Int32(self.nrows - 1)) + * Int32(self.num_sms) + + cta + ) + * Int32(32) + + lane + ] + else: + if cutlass.const_expr(self.early): + # Row 0 keeps the entry load (issued before bar.sync 0). + if r_ > Int32(0): + desc_lane = mDesc[ + (r_ * Int32(self.num_sms) + cta) * Int32(32) + lane + ] + else: + desc_lane = mDesc[(r_ * Int32(self.num_sms) + cta) * Int32(32) + lane] + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n_desc = cute.arch.shuffle_sync(desc_lane, 2) + ord0 = cute.arch.shuffle_sync(desc_lane, 3) + ord1 = cute.arch.shuffle_sync(desc_lane, 4) + nwin = cute.arch.shuffle_sync(desc_lane, 5) + n = n_desc + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + t_lo = s0 * Int32(SPLIT_TOK) + nwin0 = (nwin + Int32(1)) // Int32(2) + nwin1 = nwin // Int32(2) + bt_r_ = _row2(mBlockTable, r_) + bta = bt_r_[0, cutlass.min(Int32(8) * s0 + lane, bt_cols - 1)] + btb = bt_r_[0, cutlass.min(Int32(8) * s0 + Int32(32) + lane, bt_cols - 1)] + ntile_row = (n + Int32(TILE - 1)) // Int32(TILE) + t_ref = Int64(0) + if cutlass.const_expr(self.wdelay > 0): + t_ref = Int64(L.gtimer()) + if grp == 0: + if cutlass.const_expr(self.qdb): + if r_ >= Int32(2): + # Q / W double-buffered: only the row two back (same stage) must be done + while not prims.mbarrier_try_wait_parity( + q_free + (r_ & Int32(1)), + ((r_ >> Int32(1)) - Int32(1)) & Int32(1), + ): + pass + if r_ > Int32(0): + if lane == 0: + self._stamp(mStR_, cta, 11) + else: + if r_ > Int32(0): + # the previous row's MMAs completed and its weights were read + while not prims.mbarrier_try_wait_parity( + q_free, (r_ - Int32(1)) & Int32(1) + ): + pass + if lane == 0: + self._stamp(mStR_, cta, 11) + q_bar = q_pipeline.producer_get_barrier(q_prod_state) + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(q_bar, self.num_q_tma_bytes) + cute.copy( + tma_atom_b, + tBgB[None, 0, r_], + tBsB[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + cute.copy( + tma_atom_w, + tWgW[None, r_], + tWsW[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + if cutlass.const_expr(self.fp4): + cute.copy( + tma_atom_sf_q, + tSF_Q_gSF_Q[None, r_], + tSF_Q_sSF_Q[None, q_prod_state.index], + tma_bar_ptr=q_bar, + ) + q_prod_state.advance() + for i in cutlass.range(ns, unroll=1): + if cutlass.const_expr(self.wdelay > 0): + if i == nwin0: + tnow = Int64(L.gtimer()) + while tnow - t_ref < Int64(self.wdelay): + tnow = Int64(L.gtimer()) + tl = ord0 >> Int32(4) * i & Int32(15) + tile = Int32(2) * s0 + tl + tile_ok = tile < ntile_row + phys = [Int32(0)] * NUM_BLOCKS_PER_MMA + if i < 3: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + phys[k] = cute.arch.shuffle_sync( + desc_lane, Int32(8 + 4 * 0 + k) + Int32(8) * i + ) + else: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + rel = Int32(4) * tl + Int32(k) + pa = cute.arch.shuffle_sync(bta, rel & Int32(31)) + pb = cute.arch.shuffle_sync(btb, rel & Int32(31)) + pv = cutlass.select_(rel >= Int32(32), pb, pa) + phys[k] = cutlass.select_(tile_ok, pv, Int32(0)) + kv_pipeline_0.producer_acquire(kv_prod_state_0) + if cutlass.const_expr(self.stamps): + if i == 0: + if lane == 0: + (mStR_.iterator + cta * NSTAMP + ST_FIRST_TMA).store( + Int64(L.gtimer()) + ) + bar = kv_pipeline_0.producer_get_barrier(kv_prod_state_0) + stage = kv_prod_state_0.index + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_0[None, 0, 0, phys[k]], + tAsA_0[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_0[None, 0, phys[k]], + tSsS_0[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_0.advance() + else: + for i in cutlass.range(ns, unroll=1): + if cutlass.const_expr(self.wdelay > 0): + if i == nwin1: + tnow = Int64(L.gtimer()) + while tnow - t_ref < Int64(self.wdelay): + tnow = Int64(L.gtimer()) + tl = ord1 >> Int32(4) * i & Int32(15) + tile = Int32(2) * s0 + tl + tile_ok = tile < ntile_row + phys = [Int32(0)] * NUM_BLOCKS_PER_MMA + if i < 3: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + phys[k] = cute.arch.shuffle_sync( + desc_lane, Int32(8 + 4 * 1 + k) + Int32(8) * i + ) + else: + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + rel = Int32(4) * tl + Int32(k) + pa = cute.arch.shuffle_sync(bta, rel & Int32(31)) + pb = cute.arch.shuffle_sync(btb, rel & Int32(31)) + pv = cutlass.select_(rel >= Int32(32), pb, pa) + phys[k] = cutlass.select_(tile_ok, pv, Int32(0)) + kv_pipeline_1.producer_acquire(kv_prod_state_1) + bar = kv_pipeline_1.producer_get_barrier(kv_prod_state_1) + stage = kv_prod_state_1.index + for k in cutlass.range_constexpr(NUM_BLOCKS_PER_MMA): + cute.copy( + tma_atom_a, + tAgA_1[None, 0, 0, phys[k]], + tAsA_1[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + cute.copy( + tma_atom_s, + tSgS_1[None, 0, phys[k]], + tSsS_1[None, k, stage], + tma_bar_ptr=bar, + cache_policy=pol, + ) + kv_prod_state_1.advance() + elif warp_idx == 10 or warp_idx == 11: + cute.arch.warpgroup_reg_dealloc(24) + grp = warp_idx - 10 + L.bar(1, 320) + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base_0 = cute.make_tensor(tmem_ptr, tCtAcc_fake_staged.layout) + tCtAcc_base_1 = cute.make_tensor( + tmem_ptr + cols_per_group, tCtAcc_fake_staged.layout + ) + num_k_blocks = cute.size(tCrA_0.shape[2]) + if cutlass.const_expr(self.dpf): + dnx_ = mDesc[cta * Int32(32) + lane] + else: + dnx_ = Int32(0) + for r_ in cutlass.range(self.nrows, unroll=1): + mStR_ = self._mstr(mStamps, r_) + if cutlass.const_expr(self.dpf): + desc_lane = dnx_ + dnx_ = mDesc[ + ( + cutlass.min(r_ + Int32(1), Int32(self.nrows - 1)) + * Int32(self.num_sms) + + cta + ) + * Int32(32) + + lane + ] + else: + desc_lane = mDesc[(r_ * Int32(self.num_sms) + cta) * Int32(32) + lane] + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n_desc = cute.arch.shuffle_sync(desc_lane, 2) + ord0 = cute.arch.shuffle_sync(desc_lane, 3) + ord1 = cute.arch.shuffle_sync(desc_lane, 4) + nwin = cute.arch.shuffle_sync(desc_lane, 5) + n = n_desc + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + t_lo = s0 * Int32(SPLIT_TOK) + nwin0 = (nwin + Int32(1)) // Int32(2) + nwin1 = nwin // Int32(2) + q_pipeline.consumer_wait(q_cons_state) + q_stage = q_cons_state.index + if cutlass.const_expr(self.fp4): + if grp == 0: + for atom_idx in cutlass.range_constexpr(self.N_padded // 128): + L.sf_atom_transpose( + sSF_Q.iterator + + q_stage * sSF_Q.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sfb_sync_barrier.arrive_and_wait() + if grp == 0: + if lane == 0: + self._stamp(mStR_, cta, 10) + if cutlass.const_expr(self.fp4): + tCtSFA = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + self.sf_tmem_base + 0 * self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfa_layout, + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + + self.sfb_tmem_base + + (0 * self.num_q_stages + q_stage) * self.num_sfb_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + sSF_Q_ue8m0 = cute.recast_tensor(sSF_Q, Float8E8M0FNU) + sSF_Q_chunk = cute.make_tensor( + sSF_Q_ue8m0.iterator + q_stage * sSF_Q_ue8m0.layout.stride[1], + sfb_chunk_smem_layout, + ) + tCsSFB_compact = cute.filter_zeros(sSF_Q_chunk) + tCtSFB_compact = cute.filter_zeros(tCtSFB) + tiled_copy_s2t_sfb = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFB_compact + ) + thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0) + tCsSFB_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact) + tCsSFB_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfb, tCsSFB_s2t_ + ) + tCtSFB_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact) + cute.copy(tiled_copy_s2t_sfb, tCsSFB_s2t, tCtSFB_s2t) + cute.arch.fence_view_async_tmem_store() + for i in cutlass.range(ns, unroll=1): + kv_pipeline_0.consumer_wait(kv_cons_state_umma_0) + umma_pipeline_0.producer_acquire(umma_prod_state_0) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage = kv_cons_state_umma_0.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_0.iterator + + kv_stage * sScales_0.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_ue8m0 = cute.recast_tensor(sScales_0, Float8E8M0FNU) + sSF_KV_chunk = cute.make_tensor( + sSF_KV_ue8m0.iterator + + kv_stage * sSF_KV_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact = cute.filter_zeros(sSF_KV_chunk) + tCtSFA_compact = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact + ) + thr_copy_s2t_sfa = tiled_copy_s2t_sfa.get_slice(0) + tCsSFA_s2t_ = thr_copy_s2t_sfa.partition_S(tCsSFA_compact) + tCsSFA_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa, tCsSFA_s2t_ + ) + tCtSFA_s2t = thr_copy_s2t_sfa.partition_D(tCtSFA_compact) + cute.copy(tiled_copy_s2t_sfa, tCsSFA_s2t, tCtSFA_s2t) + tCtAcc_0 = tCtAcc_base_0[None, None, None, umma_prod_state_0.index] + for k_block in cutlass.range_constexpr(num_k_blocks): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_0, + tCrA_0[None, None, k_block, kv_stage], + tCrB[None, None, k_block, q_stage], + tCtAcc_0, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_0.consumer_release(kv_cons_state_umma_0) + kv_cons_state_umma_0.advance() + umma_pipeline_0.producer_commit(umma_prod_state_0) + umma_prod_state_0.advance() + else: + if cutlass.const_expr(self.fp4): + tCtSFA = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + self.sf_tmem_base + 1 * self.num_sfa_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfa_layout, + ) + tCtSFB = cute.make_tensor( + cute.recast_ptr( + tmem_ptr + + self.sfb_tmem_base + + (1 * self.num_q_stages + q_stage) * self.num_sfb_tmem_cols, + dtype=self.sf_dtype, + ), + tmem_sfb_layout, + ) + sSF_Q_ue8m0 = cute.recast_tensor(sSF_Q, Float8E8M0FNU) + sSF_Q_chunk = cute.make_tensor( + sSF_Q_ue8m0.iterator + q_stage * sSF_Q_ue8m0.layout.stride[1], + sfb_chunk_smem_layout, + ) + tCsSFB_compact = cute.filter_zeros(sSF_Q_chunk) + tCtSFB_compact = cute.filter_zeros(tCtSFB) + tiled_copy_s2t_sfb = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFB_compact + ) + thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0) + tCsSFB_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact) + tCsSFB_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfb, tCsSFB_s2t_ + ) + tCtSFB_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact) + cute.copy(tiled_copy_s2t_sfb, tCsSFB_s2t, tCtSFB_s2t) + cute.arch.fence_view_async_tmem_store() + for i in cutlass.range(ns, unroll=1): + kv_pipeline_1.consumer_wait(kv_cons_state_umma_1) + umma_pipeline_1.producer_acquire(umma_prod_state_1) + tiled_mma.set(tcgen05.Field.ACCUMULATE, False) + kv_stage_1 = kv_cons_state_umma_1.index + if cutlass.const_expr(self.fp4): + for atom_idx in cutlass.range_constexpr(self.block_kv // 128): + L.sf_atom_transpose( + sScales_1.iterator + + kv_stage_1 * sScales_1.layout.stride[1] + + atom_idx * 128 + ) + cute.arch.fence_view_async_shared() + sSF_KV_ue8m0 = cute.recast_tensor(sScales_1, Float8E8M0FNU) + sSF_KV_chunk = cute.make_tensor( + sSF_KV_ue8m0.iterator + + kv_stage_1 * sSF_KV_ue8m0.layout.stride[1], + sfa_chunk_smem_layout, + ) + tCsSFA_compact = cute.filter_zeros(sSF_KV_chunk) + tCtSFA_compact = cute.filter_zeros(tCtSFA) + tiled_copy_s2t_sfa = tcgen05.make_s2t_copy( + copy_atom_s2t, tCtSFA_compact + ) + thr_copy_s2t_sfa = tiled_copy_s2t_sfa.get_slice(0) + tCsSFA_s2t_ = thr_copy_s2t_sfa.partition_S(tCsSFA_compact) + tCsSFA_s2t = tcgen05.get_s2t_smem_desc_tensor( + tiled_copy_s2t_sfa, tCsSFA_s2t_ + ) + tCtSFA_s2t = thr_copy_s2t_sfa.partition_D(tCtSFA_compact) + cute.copy(tiled_copy_s2t_sfa, tCsSFA_s2t, tCtSFA_s2t) + tCtAcc_1 = tCtAcc_base_1[None, None, None, umma_prod_state_1.index] + for k_block in cutlass.range_constexpr(num_k_blocks): + if cutlass.const_expr(self.fp4): + tCtSFA_k = cute.slice_( + tCtSFA, (None, None, k_block * self.sf_k_step, None) + ) + tCtSFB_k = cute.slice_( + tCtSFB, (None, None, k_block * self.sf_k_step, None) + ) + tiled_mma.set(tcgen05.Field.SFA, tCtSFA_k.iterator) + tiled_mma.set(tcgen05.Field.SFB, tCtSFB_k.iterator) + cute.gemm( + tiled_mma, + tCtAcc_1, + tCrA_1[None, None, k_block, kv_stage_1], + tCrB[None, None, k_block, q_stage], + tCtAcc_1, + ) + tiled_mma.set(tcgen05.Field.ACCUMULATE, True) + if cutlass.const_expr(self.fp4): + kv_pipeline_1.consumer_release(kv_cons_state_umma_1) + kv_cons_state_umma_1.advance() + umma_pipeline_1.producer_commit(umma_prod_state_1) + umma_prod_state_1.advance() + # this group's MMAs of the row (and their Q reads) complete -> one q_free arrival + if prims.elect_sync(): + prims.tcgen05_commit( + (q_free + q_stage) if self.qdb else q_free, group=prims.CTAGroup.CTA_1 + ) + q_cons_state.advance() + elif warp_idx < 8: + cute.arch.warpgroup_reg_alloc(self.math_regs) + wg = warp_idx // 4 + tmem.allocate(self.num_tmem_alloc_cols_total) + L.bar(1, 320) + tmem_ptr = tmem.retrieve_ptr(self.acc_dtype) + tCtAcc_base_0 = cute.make_tensor(tmem_ptr, tCtAcc_fake_staged.layout) + tCtAcc_base_1 = cute.make_tensor( + tmem_ptr + cols_per_group, tCtAcc_fake_staged.layout + ) + local_tidx = tidx % 128 + cC = cute.make_identity_tensor(epi_sub_mn) + rs_ = self.row_sizes() + svg_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svg, dtype=Int64), + cute.make_layout((3 if self.nrows <= 32 else 1) * self.nslot), + ) + svm_ = cute.recast_ptr(arena + self.s_svm, dtype=Int64) + rgen_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst + self.s_rgen_off, dtype=Int64), + cute.make_layout(self.nslot), + ) + if tidx == 0: + # every row's entry words at kernel start (the team writes a row's ws only after that row + # streamed) + for rr_ in cutlass.range_constexpr(self.nrows): + ge1_, ge2_, ge3_ = self._entry_loads(ws + Int64(rr_ * rs_["ws"] * 8)) + if cutlass.const_expr(self.nrows > 32): + svg_[rr_] = Int64(self._gen_from(ge1_, ge2_, ge3_)) + else: + svg_[rr_ * 3] = Int64(ge1_) + svg_[rr_ * 3 + 1] = Int64(ge2_) + svg_[rr_ * 3 + 2] = Int64(ge3_) + # the math warps scan + publish the last row after their stream; warm that code now (memory idle, + # first tile ~2 us away): same call site shape, scratch addresses in the debug buffer, T = -inf + tbbm_ = cute.recast_ptr(arena + self.s_svtb, dtype=Int64) + s_tvm_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svt, dtype=Int32), + cute.make_layout(2 * self.nslot), + ) + sListM_ = cute.make_tensor( + cute.recast_ptr( + arena + (S_OFF_LSTM if self.nrows <= 6 else S_OFF_LSTM8), dtype=Int64 + ), + cute.make_layout(MAXS * SPLIT_TOK), + ) + cbasem_ = mCPool.iterator.toint() + _dbgm = mDbg.iterator.toint() + _sLog0 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_LOGR, dtype=Float32), + cute.make_layout(MAXS * SPLIT_TOK), + ) + _sBtc0 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_SVB, dtype=Int32), cute.make_layout(MAXS * 8) + ) + # (no warm-up pass: the last row's scan + publish code is fetched once, after the stream) + if cutlass.const_expr(self.dpf): + dnx_ = mDesc[cta * Int32(32) + lane] + cnx_ = mCtx[0] + else: + dnx_ = Int32(0) + cnx_ = Int32(0) + for r_ in cutlass.range(self.nrows, unroll=1): + mStR_ = self._mstr(mStamps, r_) + sLogR_ = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_LOGR, dtype=Float32) + + self._lslot(r_) * Int32(MAXS * SPLIT_TOK), + cute.make_layout(MAXS * SPLIT_TOK), + ) + if cutlass.const_expr(self.dpf): + desc_lane = dnx_ + dnx_ = mDesc[ + ( + cutlass.min(r_ + Int32(1), Int32(self.nrows - 1)) + * Int32(self.num_sms) + + cta + ) + * Int32(32) + + lane + ] + ctxr_ = cnx_ + cnx_ = mCtx[cutlass.min(r_ + Int32(1), Int32(self.nrows - 1))] + else: + desc_lane = mDesc[(r_ * Int32(self.num_sms) + cta) * Int32(32) + lane] + ctxr_ = mCtx[r_] + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n_desc = cute.arch.shuffle_sync(desc_lane, 2) + ord0 = cute.arch.shuffle_sync(desc_lane, 3) + ord1 = cute.arch.shuffle_sync(desc_lane, 4) + nwin = cute.arch.shuffle_sync(desc_lane, 5) + n = n_desc + if cutlass.const_expr(self.fp4): + # the descriptor kernel computed the ladder: words 6 / 7 hold SMP / SS2 + SMP = cute.arch.shuffle_sync(desc_lane, 6) + SS2 = cute.arch.shuffle_sync(desc_lane, 7) + else: + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + wst = Int32(8) * SS2 + t_lo = s0 * Int32(SPLIT_TOK) + nwin0 = (nwin + Int32(1)) // Int32(2) + nwin1 = nwin // Int32(2) + if cutlass.const_expr(self.fp4): + # jw = pos // wst as umulhi(pos, magic): exact for pos < 2^18, 8 <= wst < 2^14 + # (the ladder's wst <= 920) + wmag = Uint64(Uint32(4294967295) // Uint32(wst) + Uint32(1)) + ws_r_ = ws + Int64(r_) * Int64(rs_["ws"] * 8) + q_pipeline.consumer_wait(q_cons_state) + q_stage_local = q_cons_state.index + w_cache = cute.make_rmem_tensor((self.num_w_in_reg,), self.epi_dtype) + for w_j in cutlass.range_constexpr(self.num_w_in_reg): + w_cache[w_j] = sW[w_j, q_stage_local] + q_cons_state.advance() + # All 256 threads fence: each warp's weight loads must complete before tid 0's + # q_free arrival lets the TMA refill this Q / W stage with the next row. + L.fence_proxy_async_smem() + L.bar(3, 256) + if tidx == 0: + prims.mbarrier_arrive((q_free + q_stage_local) if self.qdb else q_free) + if tidx == 0: + self._stamp(mStR_, cta, 7) + if cutlass.const_expr(self.ring): + if r_ >= Int32(8): + # logits slot r & 7 is written only after its previous row r - 8 reached K_DONE + # (publisher arrival on SLF[r & 7]; the k-th reuse of a slot waits phase (k - 1) & 1) + while not prims.mbarrier_try_wait_parity( + cute.recast_ptr(arena + self.s_slf, dtype=Int64) + (r_ & Int32(7)), + ((r_ >> Int32(3)) - Int32(1)) & Int32(1), + ): + pass + if tidx == 0: + self._stamp(mStR_, cta, 14) + if cutlass.const_expr(self.nrows > 32): + gen = Uint64(svg_[r_]) + else: + gen = self._gen_from( + Uint64(svg_[r_ * Int32(3)]), + Uint64(svg_[r_ * Int32(3) + Int32(1)]), + Uint64(svg_[r_ * Int32(3) + Int32(2)]), + ) + if tidx == 0: + rgen_[r_] = Int64(gen) + if tidx == 0: + if n_desc != ctxr_: + self._flag(ws_r_, gen, Int32(E_STALE)) + if n_desc < Int32(0) or n_desc > Int32(N_MAX): + self._flag(ws_r_, gen, Int32(E_NLIMIT)) + bboard = mBoard.iterator.toint() + Int64(r_) * Int64(rs_["board"] * 8) + btag = Uint64(self._tag32(gen)) << Uint64(32) + ci = Int32(0) + cnt1 = Int32(0) + tk = Int32(0) + Tv = Float32(float("inf")) + wsub = warp_idx * Int32(SUBCAP) + if wg == 0: + tAcc_0_ref = tCtAcc_base_0[None, None, None, 0][(None, None), 0, 0] + tAcc_0_ref_epi = cute.flat_divide(tAcc_0_ref, epi_sub_mn) + tiled_copy_ref_0 = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_0_ref_epi[None, None, 0, 0] + ) + thr_copy_ref_0 = tiled_copy_ref_0.get_slice(local_tidx) + tTR_cC = thr_copy_ref_0.partition_D(cC) + m_coord = tTR_cC[0][0] + tTR_rAcc = cute.make_fragment_like(tTR_cC, self.acc_dtype) + for i in cutlass.range(ns + Int32(1), unroll=1): + if i < ns: + tl = ord0 >> Int32(4) * i & Int32(15) + pos = (Int32(2) * s0 + tl) * Int32(TILE) + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready = kv_pipeline_0.consumer_try_wait(kv_cons_state_math_0) + umma_ready = umma_pipeline_0.consumer_try_wait(umma_cons_state_0) + if cutlass.const_expr(not self.fp4): + kv_pipeline_0.consumer_wait(kv_cons_state_math_0, kv_ready) + scale_val = sScales_0[m_coord, kv_cons_state_math_0.index] + else: + scale_val = Float32(1.0) + umma_pipeline_0.consumer_wait(umma_cons_state_0, umma_ready) + tCtAcc_c0 = tCtAcc_base_0[None, None, None, umma_cons_state_0.index] + tAcc_c0 = tCtAcc_c0[(None, None), 0, 0] + tTR_0 = thr_copy_ref_0.partition_S( + cute.flat_divide(tAcc_c0, epi_sub_mn) + ) + if cutlass.const_expr(not self.fp4): + # The scale load from this K stage must complete before the + # release lets the TMA refill the stage. + L.fence_proxy_async_smem() + kv_pipeline_0.consumer_release(kv_cons_state_math_0) + kv_cons_state_math_0.advance() + cute.copy(tiled_copy_ref_0, tTR_0[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + umma_pipeline_0.consumer_release(umma_cons_state_0) + umma_cons_state_0.advance() + val = self._epi_value( + tTR_rAcc, w_cache, sW, self.num_w_in_reg, scale_val + ) + sLogR_[tl * Int32(TILE) + m_coord] = val + if cutlass.const_expr(self.debug): + if pos < n: + mDbg[pos] = val + if cutlass.const_expr(self.fp4): + jw = Int32((Uint64(pos) * wmag) >> Uint64(32)) + else: + jw = pos // wst + if pos - jw * wst < Int32(8): + if jw < SMP: + st_rlx_u64( + bboard + + Int64(jw * Int32(8) + (pos - jw * wst)) * Int64(8), + btag | Uint64(L.u32_of_f32(val)), + ) + if cutlass.const_expr(self.stamps): + if i == 0: + if local_tidx == 0: + (mStR_.iterator + cta * NSTAMP + ST_FIRST_EPI).store( + Int64(L.gtimer()) + ) + if cutlass.const_expr(self.stamps): + if i + Int32(1) == nwin0: + if local_tidx == 0: + (mStR_.iterator + cta * NSTAMP + ST_BOARD).store( + Int64(L.gtimer()) + ) + else: + tAcc_1_ref = tCtAcc_base_1[None, None, None, 0][(None, None), 0, 0] + tAcc_1_ref_epi = cute.flat_divide(tAcc_1_ref, epi_sub_mn) + tiled_copy_ref_1 = tcgen05.make_tmem_copy( + copy_atom_t2r, tAcc_1_ref_epi[None, None, 0, 0] + ) + thr_copy_ref_1 = tiled_copy_ref_1.get_slice(local_tidx) + tTR_cC = thr_copy_ref_1.partition_D(cC) + m_coord = tTR_cC[0][0] + tTR_rAcc = cute.make_fragment_like(tTR_cC, self.acc_dtype) + for i in cutlass.range(ns + Int32(1), unroll=1): + if i < ns: + tl = ord1 >> Int32(4) * i & Int32(15) + pos = (Int32(2) * s0 + tl) * Int32(TILE) + m_coord + if cutlass.const_expr(not self.fp4): + kv_ready = kv_pipeline_1.consumer_try_wait(kv_cons_state_math_1) + umma_ready = umma_pipeline_1.consumer_try_wait(umma_cons_state_1) + if cutlass.const_expr(not self.fp4): + kv_pipeline_1.consumer_wait(kv_cons_state_math_1, kv_ready) + scale_val = sScales_1[m_coord, kv_cons_state_math_1.index] + else: + scale_val = Float32(1.0) + umma_pipeline_1.consumer_wait(umma_cons_state_1, umma_ready) + tCtAcc_c1 = tCtAcc_base_1[None, None, None, umma_cons_state_1.index] + tAcc_c1 = tCtAcc_c1[(None, None), 0, 0] + tTR_1 = thr_copy_ref_1.partition_S( + cute.flat_divide(tAcc_c1, epi_sub_mn) + ) + if cutlass.const_expr(not self.fp4): + # The scale load from this K stage must complete before the + # release lets the TMA refill the stage. + L.fence_proxy_async_smem() + kv_pipeline_1.consumer_release(kv_cons_state_math_1) + kv_cons_state_math_1.advance() + cute.copy(tiled_copy_ref_1, tTR_1[None, None, None, 0, 0], tTR_rAcc) + cute.arch.fence_view_async_tmem_load() + umma_pipeline_1.consumer_release(umma_cons_state_1) + umma_cons_state_1.advance() + val = self._epi_value( + tTR_rAcc, w_cache, sW, self.num_w_in_reg, scale_val + ) + sLogR_[tl * Int32(TILE) + m_coord] = val + if cutlass.const_expr(self.debug): + if pos < n: + mDbg[pos] = val + if cutlass.const_expr(self.fp4): + jw = Int32((Uint64(pos) * wmag) >> Uint64(32)) + else: + jw = pos // wst + if pos - jw * wst < Int32(8): + if jw < SMP: + st_rlx_u64( + bboard + + Int64(jw * Int32(8) + (pos - jw * wst)) * Int64(8), + btag | Uint64(L.u32_of_f32(val)), + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + L.bar(3, 256) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(self.stamps): + if tidx == 0: + (mStR_.iterator + cta * NSTAMP + ST_STREAM_END).store(Int64(L.gtimer())) + if cutlass.const_expr(self.nteams < self.nrows and self.tcta == 0): + srv_ = Int32(0) + if r_ == Int32(self.nrows - 1): + # T server of the last row (CTA 0, warps 0-3; scratch in the idle K stage buffer) + if cutlass.const_expr(self.tsrv1 and self.nrows <= 4): + # the first stream CTA to finish this stream serves the T line instead + fadr_ = Int32( + cute.recast_ptr( + arena + S_OFF_MISC + 62 * 4, dtype=Int32 + ).toint() + ) + if tidx == Int32(0): + w_ = Int32(0) + if L.mbar_test_wait( + Int32((tbbm_ + r_).toint()), Int32(0) + ) == Int32(0): + tk_ = gen + Uint64(5) + if atom_exch_u64(self._w(ws_r_, W_TSRV), tk_) != tk_: + w_ = Int32(1) + sts_volatile_u32(fadr_, w_) + L.bar(3, 256) + srv_ = lds_volatile_u32(fadr_) + else: + # nrows > 4 with tsz2 / tsz: CTA ns - 1 (empty in the last row) serves it + if cta == Int32( + (self.ns - 1) + if (self.nrows > 4 and (self.tsz or self.tsz2)) + else 0 + ): + srv_ = Int32(1) + if cutlass.const_expr(self.tsz2): + # CTA ns - 1 (empty range in the last two rows) also serves row nrows - 2 + if r_ == Int32(self.nrows - 2): + if cta == Int32(self.ns - 1): + srv_ = Int32(1) + if cutlass.const_expr(self.tsz01): + # CTA ns - 2 (empty ranges in rows 0-1) serves rows 0 and 1 + if r_ < Int32(min(2, self.nrows - 2) if self.tsz2 else 2): + if cta == Int32(self.ns - 2): + srv_ = Int32(1) + if cutlass.const_expr(self.tszall): + # rows 2 .. nrows - 3 in pairs: CTA ns - 2 - r // 2 (empty in its pair) serves them + if r_ >= Int32(2) and r_ < Int32(self.nrows - 2): + if cta == Int32(self.ns - 2) - r_ // Int32(2): + srv_ = Int32(1) + if srv_ != Int32(0): + if tidx < Int32(128): + mStT_ = self._mstt(mStamps, r_) + sg1_, sg2_, sg3_ = self._entry_words(svg_, r_) + self._block_a_lead( + arena, + cta, + tidx, + ws_r_, + n, + _flat(mBoard, r_, rs_["board"]), + mStT_, + sg1_, + sg2_, + sg3_, + _flat(mCtl, r_, rs_["ctl"]), + Int32(0), + _flat(mHist, r_, rs_["hist"]), + fa=self.s_tsrv_fa, + mi=self.s_tsrv_fa + 2048, + ) + if r_ == Int32(self.nrows - 1): + # the last row: wait its T (armed by the T poller), scan + publish with all 256 math threads + L.spin(Int32((tbbm_ + r_).toint()), Int32(0)) + Tvl_ = L.f32_of_u32(Uint32(s_tvm_[r_ * Int32(2)])) + bsl_ = L.f32_of_u32(Uint32(s_tvm_[r_ * Int32(2) + Int32(1)])) + ntokl_ = cutlass.min(ns * Int32(SPLIT_TOK), n - t_lo) + if ntokl_ < Int32(0): + ntokl_ = Int32(0) + rgl_ = mRegion.iterator.toint() + Int64(r_) * Int64(rs_["region"] * 8) + sBtcL_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svb, dtype=Int32) + + self._svbi(r_) * Int32(MAXS * 8), + cute.make_layout(MAXS * 8), + ) + totl_ = self._svc_scanpub( + cta, + tidx, + Int32(1), + self._cnt_addr(ws_r_, Int32(0), cta), + rgl_ + Int64(cta) * Int64(2 * CAPR * 8), + mHist.iterator.toint() + Int64(r_) * Int64(rs_["hist"] * 4), + rgl_, + gen, + ntokl_, + t_lo, + sLogR_, + Tvl_, + bsl_, + sBtcL_, + cbasem_, + s_wc, + sListM_, + mStR_, + nth=256, + bid=3, + b1u=(self.b1l_u if self.b1l else 0), + b1e=self.b1l_e, + ) + if tidx == 0: + rstl_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst, dtype=Int32) + + r_ * Int32(self.rst_w), + cute.make_layout(self.rst_w), + ) + rstl_[0] = totl_ + rstl_[1] = ntokl_ + rstl_[2] = t_lo + rstl_[3] = Int32(0) + rstl_[4] = Int32(0) + L.bar(3, 256) + # hand the row to the publishers (rows < last) / signal the drain (last row) + if tidx == 0: + prims.mbarrier_arrive(svm_ + r_) + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + else: + cute.arch.warpgroup_reg_dealloc(56) + rs_ = self.row_sizes() + stid = tidx - Int32(384) + s_wc4 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_SVW, dtype=Int32), cute.make_layout(8) + ) + s_dir4 = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_SVW + 32, dtype=Int32), cute.make_layout(8) + ) + s_tvr = cute.make_tensor( + cute.recast_ptr(arena + self.s_svt, dtype=Int32), + cute.make_layout(2 * self.nslot), + ) + svm_ = cute.recast_ptr(arena + self.s_svm, dtype=Int64) + tbb_ = cute.recast_ptr(arena + self.s_svtb, dtype=Int64) + rgen_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst + self.s_rgen_off, dtype=Int64), + cute.make_layout(self.nslot), + ) + cbase = mCPool.iterator.toint() + svgs_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svg + self.s_svgs_off, dtype=Int64), + cute.make_layout(self.nslot), + ) + if warp_idx == 12: + # T poller: every row's C-pool block-table slice and T in row order; each T arms the row's + # mbarrier (publishers / math warps). Never waits for a publish. + if lane == Int32(0): + for rr_ in cutlass.range_constexpr(self.nrows): + ge1_, ge2_, ge3_ = self._entry_loads(ws + Int64(rr_ * rs_["ws"] * 8)) + svgs_[rr_] = Int64(self._gen_from(ge1_, ge2_, ge3_)) + for r_ in cutlass.range(self.nrows, unroll=1): + mStR_ = self._mstr(mStamps, r_) + desc_lane = mDesc[(r_ * Int32(self.num_sms) + cta) * Int32(32) + lane] + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + ws_r_ = ws + Int64(r_) * Int64(rs_["ws"] * 8) + sBtcR_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svb, dtype=Int32) + + self._svbi(r_) * Int32(MAXS * 8), + cute.make_layout(MAXS * 8), + ) + if cutlass.const_expr(self.ring_w12): + # (ring_w12): row r - 5's directive word, once: K_DONE -> its logits slot is free for + # row r + 3 now; otherwise the publishers serve it after publishing row r + ck_ = r_ - Int32(5) + if ck_ >= Int32(0) and ck_ + Int32(8) < Int32(self.nrows): + if lane == Int32(0): + mStC_ = self._mstr(mStamps, ck_) + self._stamp(mStC_, cta, 8) + vr_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_vrd, dtype=Int32), + cute.make_layout(self.nslot), + ) + hk_ = L.ld_relaxed_u64( + self._w(ws + Int64(ck_) * Int64(rs_["ws"] * 8), W_DIR) + ) + if hk_ >> Uint64(24) == self._tag40( + Uint64(svgs_[ck_]) + ) and Int32(Uint32(hk_ & Uint64(15))) == Int32(K_DONE): + # acquire: the team's K_DONE follows its reads of every CTA's packets of the + # row, + # which follow this CTA's scan of the slot + L.fence_acq_rel_gpu() + vr_[ck_] = Int32(1) + prims.mbarrier_arrive( + cute.recast_ptr(arena + self.s_slf, dtype=Int64) + + (ck_ & Int32(7)) + ) + self._stamp(mStC_, cta, 9) + else: + vr_[ck_] = Int32(2) + cute.arch.sync_warp() + if cutlass.const_expr(self.nrows > 32): + if r_ >= Int32(32): + # slice entry r & 31 is free once the publishers are done with row r - 32 + while not prims.mbarrier_try_wait_parity( + cute.recast_ptr(arena + self.s_sfb, dtype=Int64) + + (r_ - Int32(32)), + Int32(0), + ): + pass + btc_r_ = _row2(mBtC, r_) + btc_cols = cute.size(mBtC, mode=[1]) + for e in cutlass.range_constexpr(2): + j = lane + Int32(32 * e) + if j < Int32(8) * ns: + sBtcR_[j] = btc_r_[0, cutlass.min(Int32(8) * s0 + j, btc_cols - 1)] + cute.arch.sync_warp() + if lane == Int32(0): + tv, sv = self._poll_tline1(ws_r_, Uint64(svgs_[r_])) + s_tvr[r_ * Int32(2)] = Int32(tv) + s_tvr[r_ * Int32(2) + Int32(1)] = Int32(sv) + prims.mbarrier_arrive(tbb_ + r_) + self._stamp(mStR_, cta, ST_T_SEEN) + cute.arch.sync_warp() + else: + # publishers (warps 13-15, 96 threads, named barrier 4): warm-up pass (it_ == 0), then rows + # 0 .. nrows - 2 (the math handoff and T_r) + pid = tidx - Int32(416) + dbgb_ = mDbg.iterator.toint() + sListP_ = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_SUB, dtype=Int64), + cute.make_layout(8 * SUBCAP), + ) + for it_ in cutlass.range(1, self.nrows, unroll=1): + live = cutlass.select_(it_ > Int32(0), Int32(1), Int32(0)) + r_ = cutlass.max(it_ - Int32(1), Int32(0)) + if cutlass.const_expr(self.ring and not self.ring_w12): + # before publishing row r, serve row r - 6 to its K_DONE (blocking; on the bucket + # path its directive word already says K_DONE) and free its logits slot for row r + 2 + ck_ = r_ - Int32(6) + if ck_ >= Int32(0) and ck_ + Int32(8) < Int32(self.nrows): + mStC_ = self._mstr(mStamps, ck_) + if pid == Int32(0): + self._stamp(mStC_, cta, 8) + self._serve_row( + ck_, + cta, + pid, + ws, + arena, + s_wc4, + s_dir4, + mRegion, + mHist, + True, + nth=96, + bid=4, + hoff=S_OFF_SVH, + ebid=4, + ) + # every publisher thread's reads of the slot complete before the arrival + fence_acq_rel_cta() + L.bar(4, 96) + if pid == Int32(0): + prims.mbarrier_arrive( + cute.recast_ptr(arena + self.s_slf, dtype=Int64) + + (ck_ & Int32(7)) + ) + self._stamp(mStC_, cta, 9) + mStR_ = self._mstr(mStamps, r_) + desc_lane = mDesc[(r_ * Int32(self.num_sms) + cta) * Int32(32) + lane] + s0 = cute.arch.shuffle_sync(desc_lane, 0) + ns = cute.arch.shuffle_sync(desc_lane, 1) + n = cute.arch.shuffle_sync(desc_lane, 2) + t_lo = s0 * Int32(SPLIT_TOK) + ws_r_ = ws + Int64(r_) * Int64(rs_["ws"] * 8) + sBtcR_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_svb, dtype=Int32) + + self._svbi(r_) * Int32(MAXS * 8), + cute.make_layout(MAXS * 8), + ) + if live != Int32(0): + while not prims.mbarrier_try_wait_parity(svm_ + r_, Int32(0)): + pass + while not prims.mbarrier_try_wait_parity(tbb_ + r_, Int32(0)): + pass + if pid == Int32(0): + self._stamp(mStR_, cta, 13) + else: + if pid == Int32(0): + s_tvr[14] = Int32(-8388608) + s_tvr[15] = Int32(0) + L.bar(4, 96) + ti_ = cutlass.select_(live != Int32(0), r_ * Int32(2), Int32(14)) + Tv = L.f32_of_u32(Uint32(s_tvr[ti_])) + bscale = L.f32_of_u32(Uint32(s_tvr[ti_ + Int32(1)])) + gen = Uint64(rgen_[r_]) + sLogR_ = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_LOGR, dtype=Float32) + + self._lslot(r_) * Int32(MAXS * SPLIT_TOK), + cute.make_layout(MAXS * SPLIT_TOK), + ) + ntok_ = cutlass.min(ns * Int32(SPLIT_TOK), n - t_lo) + if ntok_ < Int32(0): + ntok_ = Int32(0) + rg_ = mRegion.iterator.toint() + Int64(r_) * Int64(rs_["region"] * 8) + cnta_ = self._cnt_addr(ws_r_, Int32(0), cta) + rbase_ = rg_ + Int64(cta) * Int64(2 * CAPR * 8) + ghist_ = mHist.iterator.toint() + Int64(r_) * Int64(rs_["hist"] * 4) + if live == Int32(0): + ntok_ = Int32(128) + cnta_ = dbgb_ + Int64(65536) + rbase_ = dbgb_ + rg_ = dbgb_ + ghist_ = dbgb_ + Int64(131072) + tot_ = self._svc_scanpub( + cta, + pid, + live, + cnta_, + rbase_, + ghist_, + rg_, + gen, + ntok_, + t_lo, + sLogR_, + Tv, + bscale, + sBtcR_, + cbase, + s_wc4, + sListP_, + mStR_, + nth=96, + bid=4, + pf=self.ppref, + b1u=(self.b1l_upub if self.b1l_pub else 0), + b1e=False, + ) + if live != Int32(0): + if pid == Int32(0): + rst_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst, dtype=Int32) + + r_ * Int32(self.rst_w), + cute.make_layout(self.rst_w), + ) + rst_[0] = tot_ + rst_[1] = ntok_ + rst_[2] = t_lo + rst_[3] = Int32(0) + rst_[4] = Int32(0) + L.bar(4, 96) + if cutlass.const_expr(self.nrows > 32): + if r_ + Int32(32) < Int32(self.nrows): + if pid == Int32(0): + # the scan and publish read slice entry r & 31 (r < nrows - 32): the poller + # may reuse it + prims.mbarrier_arrive( + cute.recast_ptr(arena + self.s_sfb, dtype=Int64) + r_ + ) + if live != Int32(0): + if pid == Int32(0): + self._stamp(mStR_, cta, 12) + if cutlass.const_expr(self.ring_w12): + # (ring_w12): row r - 5 (verdict written by warp 12 before it armed T(r), which these + # threads waited): freed by warp 12 -> done for the drain; not K_DONE yet -> serve it here + # (blocking) and free its slot + ck_ = r_ - Int32(5) + if ck_ >= Int32(0) and ck_ + Int32(8) < Int32(self.nrows): + vr_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_vrd, dtype=Int32), + cute.make_layout(self.nslot), + ) + if vr_[ck_] == Int32(1): + if pid == Int32(0): + rsc_ = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst, dtype=Int32) + + ck_ * Int32(self.rst_w), + cute.make_layout(self.rst_w), + ) + rsc_[4] = Int32(1) + else: + mStC_ = self._mstr(mStamps, ck_) + self._serve_row( + ck_, + cta, + pid, + ws, + arena, + s_wc4, + s_dir4, + mRegion, + mHist, + True, + nth=96, + bid=4, + hoff=S_OFF_SVH, + ebid=4, + ) + # every publisher thread's reads of the slot complete before the arrival + fence_acq_rel_cta() + L.bar(4, 96) + if pid == Int32(0): + prims.mbarrier_arrive( + cute.recast_ptr(arena + self.s_slf, dtype=Int64) + + (ck_ & Int32(7)) + ) + self._stamp(mStC_, cta, 9) + # final drain (all four warps, named barrier 2) once the math warps saved the last row's state + while not prims.mbarrier_try_wait_parity(svm_ + Int32(self.nrows - 1), Int32(0)): + pass + L.bar(2, 128) + if stid == Int32(0): + self._stamp(mStamps, cta, 9) + for q_ in cutlass.range(self.nrows, unroll=1): + self._serve_row( + q_, + cta, + stid, + ws, + arena, + s_wc4, + s_dir4, + mRegion, + mHist, + True, + nth=128, + bid=2, + hoff=S_OFF_SVH, + ebid=2, + ) + if stid == Int32(0): + self._stamp(mStamps, cta, ST_EXIT) + + @cute.jit + def _entry_loads(self, ws): + g1_ = L.ld_relaxed_u64(self._w(ws, W_DONE)) + g2_ = Uint64(0) + if cutlass.const_expr(self.gen2): + g2_ = L.ld_relaxed_u64(self._w(ws, W_DONE2)) + hd = Uint64(0) + if cutlass.const_expr(self.heal): + hd = L.ld_relaxed_u64(self._w(ws, W_DIR)) + return (g1_, g2_, hd) + + @cute.jit + def _gen_from(self, g1_, g2_, hd): + gen = g1_ + if g2_ > g1_: + gen = g2_ + tdir = Int64(hd >> Uint64(24)) + if tdir != Int64(0): + tcur = Int64(self._tag40(gen)) + ahead = tdir - tcur + if ahead < Int64(0): + ahead = ahead + Int64(1099511627775) + if ahead < Int64(1 << 39): + gen = gen + Uint64(ahead) + Uint64(1) + return gen + + @cute.jit + def _tag32(self, gen): + return Uint32(gen % Uint64(4294967295) + Uint64(1)) + + @cute.jit + def _tag40(self, gen): + return gen % Uint64(1099511627775) + Uint64(1) + + @cute.jit + def _flag(self, ws, gen, bits): + red_max_u64(self._w(ws, W_ERR), gen + Uint64(1) << Uint64(8) | Uint64(Uint32(bits))) + red_or_u64(self._w(ws, W_ERRB), Uint64(Uint32(bits))) + + @cute.jit + def _raise_abort(self, ws, gen, bits): + self._flag(ws, gen, bits | Int32(E_ABORTED)) + st_rlx_u64(self._w(ws, W_ABORT), gen + Uint64(1)) + + @cute.jit + def _deadline(self): + return Int64(L.gtimer()) + Int64(self.spin_ns) + + @cute.jit + def _poll_word_eq(self, ws, gen, addr, want): + t64 = gen + Uint64(1) + tdl = self._deadline() + st_ = Int32(0) + while st_ == Int32(0): + v = L.ld_relaxed_u64(addr) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if v == want: + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + ok = Int32(0) + if st_ == Int32(1): + ok = Int32(1) + return ok + + @cute.jit + def _followers_ready(self, ws, t64): + ready = Int32(1) + for fi in cutlass.range_constexpr(1, self.team_ctas): + f = L.ld_relaxed_u64(self._w(ws, W_FOL + fi)) + if f != t64: + ready = Int32(0) + return ready + + @cute.jit + def _wait_followers(self, ws, gen): + t64 = gen + Uint64(1) + tdl = self._deadline() + st_ = Int32(0) + while st_ == Int32(0): + ready = self._followers_ready(ws, t64) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if ready != Int32(0): + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + ok = Int32(0) + if st_ == Int32(1): + ok = Int32(1) + return ok + + @cute.jit + def _publish_dir(self, ws, gen, seq, kind, path, p0, p1, p2): + if kind != Int32(K_DONE): + L.st_g_u64(self._w(ws, W_DP), p0) + L.st_g_u64(self._w(ws, W_DP + 1), p1) + L.st_g_u64(self._w(ws, W_DP + 2), p2) + L.fence_acq_rel_gpu() + self._skew(gen, Int32(1000) + seq, 6) + st_rlx_u64( + self._w(ws, W_DIR), + self._tag40(gen) << Uint64(24) + | Uint64(Uint32(seq)) << Uint64(8) + | Uint64(Uint32(path)) << Uint64(4) + | Uint64(Uint32(kind)), + ) + + @cute.jit + def _poll_tline1(self, ws, gen): + tg = self._tag32(gen) + t64 = gen + Uint64(1) + tdl = self._deadline() + st_ = Int32(0) + tv = Uint32(2139095040) + it_ = Int32(0) + hv0 = Uint64(0) + mv0 = Uint64(0) + while st_ == Int32(0): + if cutlass.const_expr(self.tpoll1): + # HIC / SMAX before the acquire of T in program order: the three loads of an iteration overlap + hv0 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + mv0 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + wt = L.ld_acquire_u64(self._w(ws, W_TLINE)) + if cutlass.const_expr(self.tl1r): + # HIC / SMAX in the same round trip (relaxed, after the acquire of T in program order) + hv0 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + mv0 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + av = Uint64(0) + chk = Int32(1) + if cutlass.const_expr(self.pchk > 1): + chk = Int32(0) + if it_ & Int32(self.pchk - 1) == Int32(self.pchk - 1): + chk = Int32(1) + if chk != Int32(0): + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + it_ = it_ + Int32(1) + okt_ = Uint32(wt >> Uint64(32)) == tg + if cutlass.const_expr(self.tpoll1): + okt_ = okt_ and Uint32(hv0 >> Uint64(32)) == tg and Uint32(mv0 >> Uint64(32)) == tg + if okt_: + st_ = Int32(1) + tv = Uint32(wt & Uint64(4294967295)) + elif chk != Int32(0): + if av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + elif st_ == Int32(2): + self._flag(ws, gen, Int32(E_ABORTED)) + sv = Uint32(0) + if st_ == Int32(1): + # T is stored after a release fence that follows the per-call histogram clear, so this acquire also + # orders all producer atomics after the clear. + hv = hv0 + mv = mv0 + if cutlass.const_expr(not self.tl1r and not self.tpoll1): + hv = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + mv = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + # HIC / SMAX are tagged words of the same T line, stored just before T: wait for this launch's tags + while Uint32(hv >> Uint64(32)) != tg or Uint32(mv >> Uint64(32)) != tg: + hv = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + mv = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + tf = L.f32_of_u32(tv) + hi = L.f32_of_u32(Uint32(hv)) + mx = L.f32_of_u32(Uint32(mv)) + lo, hi = self._band_range(tf, hi, mx) + if tf > Float32(L.SENT_LO): + sv = L.u32_of_f32(bin_scale(lo, hi) * Float32(0.5)) + return (tv, sv) + + @cute.jit + def _t_known(self, tk, Tv, i, ns, tbar, s_tv, tpar=0): + if tk == Int32(0): + t_ = L.mbar_test_wait(Int32(tbar.toint()), Int32(tpar)) + if i == ns: + while t_ == Int32(0): + t_ = L.mbar_try_wait(Int32(tbar.toint()), Int32(tpar)) + if cute.arch.vote_all_sync(t_ != Int32(0)): + tk = Int32(1) + Tv = L.f32_of_u32(Uint32(s_tv[0])) + return (tk, Tv) + + @cute.jit + def _classify_tasks(self, ci, last, ordw, t_lo, n, m, sLog, sSub, wsub, cnt1, Tv): + lm = Int32(cute.arch.lanemask_lt()) + kT = L.fkey(Tv) + if cutlass.const_expr(self.cls4): + # up to 4 tiles per round, all loads first (the tile count is uniform over the group) + while ci <= last: + xs_ = [] + gs_ = [] + for u_ in cutlass.range_constexpr(4): + cu_ = ci + Int32(u_) + pu_ = (ordw >> Int32(4) * cu_ & Int32(15)) * Int32(TILE) + m + xu_ = Float32(0.0) + if cu_ <= last: + xu_ = sLog[pu_] + xs_.append(xu_) + gs_.append(t_lo + pu_) + bms_ = [] + oks_ = [] + for u_ in cutlass.range_constexpr(4): + ok_ = Int32(0) + bm_ = Int32(0) + if ci + Int32(u_) <= last: + if gs_[u_] < n: + if L.fkey(xs_[u_]) >= kT: + ok_ = Int32(1) + bm_ = Int32(cute.arch.vote_ballot_sync(ok_ != Int32(0))) + oks_.append(ok_) + bms_.append(bm_) + for u_ in cutlass.range_constexpr(4): + if oks_[u_] != Int32(0): + sSub[wsub + cnt1 + Int32(cute.arch.popc(bms_[u_] & lm))] = Int64( + Uint64(Uint32(gs_[u_])) << Uint64(32) | Uint64(L.u32_of_f32(xs_[u_])) + ) + cnt1 = cnt1 + Int32(cute.arch.popc(bms_[u_])) + ci = cutlass.min(ci + Int32(4), last + Int32(1)) + else: + while ci <= last: + tl = ordw >> Int32(4) * ci & Int32(15) + p = tl * Int32(TILE) + m + x = sLog[p] + gpos = t_lo + p + ok = Int32(0) + if gpos < n: + if L.fkey(x) >= kT: + ok = Int32(1) + bm = Int32(cute.arch.vote_ballot_sync(ok != Int32(0))) + if ok != Int32(0): + sSub[wsub + cnt1 + Int32(cute.arch.popc(bm & lm))] = Int64( + Uint64(Uint32(gpos)) << Uint64(32) | Uint64(L.u32_of_f32(x)) + ) + cnt1 = cnt1 + Int32(cute.arch.popc(bm)) + ci = ci + Int32(1) + return (ci, cnt1) + + @cute.jit + def _cnt_addr(self, ws, slot, c): + return self._w(ws, W_CNT) + Int64(slot * Int32(160) + c) * Int64(8) + + @cute.jit + def _b1l_issue( + self, + lst, + base, + cnt, + k0, + Tv, + bscale, + ghist, + U: cutlass.Constexpr[int], + cap: cutlass.Constexpr[int], + ): + # Entries k0 + 32 j (j < U) of a lane-strided per-warp candidate list: their bins and U + # predicated returning histogram atom.adds, issued back to back. Returns (entry, bin, + # ordinal) per entry; ordinal BUCKET_CAP means no bucket store (k >= cnt, or bscale <= 0). + hon = cutlass.select_(bscale > Float32(0.0), Int32(1), Int32(0)) + out = [] + for j in cutlass.range_constexpr(U): + kj = k0 + Int32(32 * j) + e_ = Uint64(lst[base + cutlass.min(kj, Int32(cap - 1))]) + bq_ = L._vbin(e_, Tv, bscale, NB_INITIAL) + pj = cutlass.select_(kj < cnt, hon, Int32(0)) + o_ = atom_add_u32_p(ghist + Int64(bq_) * Int64(4), Uint32(1), pj, Uint32(BUCKET_CAP)) + out.append(e_) + out.append(bq_) + out.append(o_) + return out + + @cute.jit + def _b1l_issue_flat( + self, + sList, + pre, + tot, + k0, + Tv, + bscale, + ghist, + U: cutlass.Constexpr[int], + nth: cutlass.Constexpr[int], + NW: cutlass.Constexpr[int], + LCAP: cutlass.Constexpr[int], + ): + # Entries k0 + nth j (j < U) of the CTA-wide flattened list (warp wk = the last warp with + # pre[wk] <= k, index k - pre[wk] of its scan list): bins and predicated atom.adds back to + # back. + hon = cutlass.select_(bscale > Float32(0.0), Int32(1), Int32(0)) + out = [] + for j in cutlass.range_constexpr(U): + kj = k0 + Int32(nth * j) + wk = Int32(0) + bk = Int32(0) + for w_ in cutlass.range_constexpr(1, NW): + wk = cutlass.select_(kj >= pre[w_], Int32(w_), wk) + bk = cutlass.select_(kj >= pre[w_], pre[w_], bk) + e_ = Uint64(sList[cutlass.min(wk * Int32(LCAP) + kj - bk, Int32(NW * LCAP - 1))]) + bq_ = L._vbin(e_, Tv, bscale, NB_INITIAL) + pj = cutlass.select_(kj < tot, hon, Int32(0)) + o_ = atom_add_u32_p(ghist + Int64(bq_) * Int64(4), Uint32(1), pj, Uint32(BUCKET_CAP)) + out.append(e_) + out.append(bq_) + out.append(o_) + return out + + @cute.jit + def _b1l_store( + self, + st_, + k0, + cnt, + rbase, + pre, + bucket_base, + U: cutlass.Constexpr[int], + step: cutlass.Constexpr[int] = 32, + ): + # Stores of one batch of _b1l_issue / _b1l_issue_flat: the packet entries (position pre + + # k), then the bucket entries (each waits for its atom.add). + for j in cutlass.range_constexpr(U): + kj = k0 + Int32(step * j) + if kj < cnt: + L.st_g_u64(rbase + Int64(pre + kj) * Int64(8), st_[3 * j]) + for j in cutlass.range_constexpr(U): + if st_[3 * j + 2] < Uint32(BUCKET_CAP): + L.st_g_u64( + self._bucket_addr(bucket_base, st_[3 * j + 1], Int32(st_[3 * j + 2])), + st_[3 * j], + ) + + @cute.jit + def _stream_publish( + self, + cta, + tidx, + ws, + gen, + ns, + n, + t_lo, + cnt1, + wsub, + sSub, + sBtc, + s_wc, + s_dir, + sLog, + mRegion, + mHist, + mStamps, + mCPool, + arena, + mCtl, + Tv, + s_tv, + serve: cutlass.Constexpr[bool] = True, + b1e_=None, + ): + lane = tidx % 32 + wid = tidx // 32 + if lane == 0: + s_wc[wid] = cnt1 + L.bar(5, 384) + pre = Int32(0) + tot = Int32(0) + for w_ in cutlass.range_constexpr(8): + v_ = s_wc[w_] + if Int32(w_) < wid: + pre = pre + v_ + tot = tot + v_ + t40 = self._tag40(gen) + rbase = mRegion.iterator.toint() + Int64(cta) * Int64(2 * CAPR * 8) + self._skew(gen, cta * Int32(8) + wid, 7) + if tidx == 0: + self._stamp(mStamps, cta, 40) + bscale = L.f32_of_u32(Uint32(s_tv[1])) + ghist = mHist.iterator.toint() + bucket_base = mRegion.iterator.toint() + if cutlass.const_expr(self.b1l): + # The early batch's stores (its atom.adds were issued before the stream-end barrier), + # then the warp's remaining candidates in batches of U. + k = lane + if cutlass.const_expr(b1e_ is not None): + self._b1l_store(b1e_, lane, cnt1, rbase, pre, bucket_base, self.b1l_u) + k = lane + Int32(32 * self.b1l_u) + while k < cnt1: + st_ = self._b1l_issue(sSub, wsub, cnt1, k, Tv, bscale, ghist, self.b1l_u, SUBCAP) + self._b1l_store(st_, k, cnt1, rbase, pre, bucket_base, self.b1l_u) + k = k + Int32(32 * self.b1l_u) + else: + k = lane + while k < cnt1: + e = Uint64(sSub[wsub + k]) + L.st_g_u64(rbase + Int64(pre + k) * Int64(8), e) + if bscale > Float32(0.0): + bq = L._vbin(e, Tv, bscale, NB_INITIAL) + ordinal = atom_add_u32(ghist + Int64(bq) * Int64(4), Uint32(1)) + if ordinal < Uint32(BUCKET_CAP): + L.st_g_u64(self._bucket_addr(bucket_base, bq, Int32(ordinal)), e) + k = k + Int32(32) + if cutlass.const_expr(self.bulk): + if tidx == 255: + if tot & Int32(1) != Int32(0): + L.st_g_u64( + rbase + Int64(tot) * Int64(8), + Uint64(DUMMY_GPOS) << Uint64(32) | Uint64(4286578688), + ) + L.fence_proxy_async_global() + L.bar(5, 256) + if tidx == 0: + self._stamp(mStamps, cta, 41) + self._skew(gen, cta, 3) + skipc = Int32(0) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(2) and cta == Int32(77): + skipc = Int32(1) + if cutlass.const_expr(self.relst): + L.st_release_u64( + self._cnt_addr(ws, Int32(0), cta), t40 << Uint64(24) | Uint64(Uint32(tot)) + ) + self._stamp(mStamps, cta, 42) + else: + if cutlass.const_expr(not self.nofence): + L.fence_acq_rel_gpu() + self._stamp(mStamps, cta, 42) + if skipc == Int32(0): + st_rlx_u64( + self._cnt_addr(ws, Int32(0), cta), t40 << Uint64(24) | Uint64(Uint32(tot)) + ) + self._stamp(mStamps, cta, ST_CAND_PUB) + cbase = mCPool.iterator.toint() + if cutlass.const_expr(self.pref): + k = lane + while k < cnt1: + gpos = Int32(Uint32(Uint64(sSub[wsub + k]) >> Uint64(32))) + kvr = sBtc[gpos - t_lo >> Int32(5)] * Int32(32) + (gpos & Int32(31)) + prefetch_l2_bulk(cbase + Int64(kvr) * Int64(512), Int32(512)) + k = k + Int32(32) + if cutlass.const_expr(serve): + ntok = cutlass.min(ns * Int32(SPLIT_TOK), n - t_lo) + if ntok < Int32(0): + ntok = Int32(0) + seq = Int32(0) + fin = Int32(0) + while fin == Int32(0): + if tidx == 0: + self._poll_dir(ws, gen, seq, s_dir) + L.bar(5, 256) + kind = s_dir[0] + dseq = s_dir[1] + if kind == Int32(K_PUB): + slot = s_dir[2] & Int32(255) + klo = Uint64(Uint32(s_dir[4])) << Uint64(32) | Uint64(Uint32(s_dir[3])) + khi = Uint64(Uint32(s_dir[6])) << Uint64(32) | Uint64(Uint32(s_dir[5])) + base = tot + if cutlass.const_expr(self.bulk): + base = tot + (tot & Int32(1)) + if slot == Int32(2): + base = Int32(CAPR) + self._stream_pub( + cta, tidx, ws, gen, slot, base, klo, khi, ntok, t_lo, sLog, s_wc, rbase + ) + elif kind == Int32(K_HIST): + plen = s_dir[2] >> Int32(8) & Int32(255) + pref = Uint64(Uint32(s_dir[4])) << Uint64(32) | Uint64(Uint32(s_dir[3])) + self._stream_hist( + cta, tidx, ws, gen, dseq, pref, plen, ntok, t_lo, sLog, mHist, arena + ) + else: + fin = Int32(1) + seq = dseq + L.bar(5, 256) + if tidx == 0: + self._stamp(mStamps, cta, ST_EXIT) + return tot + + @cute.jit + def _svc_publish( + self, + cta, + stid, + live, + cnt_addr, + rbase, + ghist, + bucket_base, + gen, + ntok, + t_lo, + sLog, + Tv, + bscale, + sBtcR, + cbase, + s_wc, + sList, + mStamps, + ): + # one row's first-round publish by the service warpgroup (128 threads, named barrier 4). One scan of the + # row's logits (positions < n via ntok): each warp compacts its candidates (logit >= T) into its own SMEM list; + # then the region packet, the DRS buckets, the even padding, the released count, the L2 prefetch of their KV + # rows. live == 0: the kernel-start warm-up pass (same code, scratch addresses, no stamps / prefetch). + lane = stid % Int32(32) + wid = stid // Int32(32) + lm = Int32(cute.arch.lanemask_lt()) + kT = L.fkey(Tv) + lw = wid * Int32(MAXS * SPLIT_TOK // 4) + cnt = Int32(0) + sb_ = Int32(sLog.iterator.toint()) + vals_ = [] + for j_ in cutlass.range_constexpr(4): + vals_.append( + lds_v4f32( + sb_ + + (wid * Int32(MAXS * SPLIT_TOK // 4) + Int32(128 * j_) + lane * Int32(4)) + * Int32(4) + ) + ) + for j_ in cutlass.range_constexpr(4): + pb = wid * Int32(MAXS * SPLIT_TOK // 4) + Int32(128 * j_) + lane * Int32(4) + oks_ = [] + anyv = Int32(0) + for e_ in cutlass.range_constexpr(4): + ok = Int32(0) + if pb + Int32(e_) < ntok: + if L.fkey(vals_[j_][e_]) >= kT: + ok = Int32(1) + oks_.append(ok) + anyv = anyv | ok + if cute.arch.vote_any_sync(anyv != Int32(0)): + for e_ in cutlass.range_constexpr(4): + bm = Int32(cute.arch.vote_ballot_sync(oks_[e_] != Int32(0))) + if oks_[e_] != Int32(0): + sList[lw + cnt + Int32(cute.arch.popc(bm & lm))] = Int64( + Uint64(Uint32(t_lo + pb + Int32(e_))) << Uint64(32) + | Uint64(L.u32_of_f32(vals_[j_][e_])) + ) + cnt = cnt + Int32(cute.arch.popc(bm)) + if lane == Int32(0): + s_wc[wid] = cnt + L.bar(4, 128) + p1 = s_wc[0] + p2 = p1 + s_wc[1] + p3 = p2 + s_wc[2] + tot = p3 + s_wc[3] + t40 = self._tag40(gen) + if live != Int32(0): + if stid == Int32(0): + self._stamp(mStamps, cta, 40) + k = stid + while k < tot: + wk = ( + cutlass.select_(k >= p1, Int32(1), Int32(0)) + + cutlass.select_(k >= p2, Int32(1), Int32(0)) + + cutlass.select_(k >= p3, Int32(1), Int32(0)) + ) + bk = cutlass.select_( + wk == Int32(1), + p1, + cutlass.select_(wk == Int32(2), p2, cutlass.select_(wk == Int32(3), p3, Int32(0))), + ) + e = Uint64(sList[wk * Int32(MAXS * SPLIT_TOK // 4) + k - bk]) + L.st_g_u64(rbase + Int64(k) * Int64(8), e) + if bscale > Float32(0.0): + bq = L._vbin(e, Tv, bscale, NB_INITIAL) + ordinal = atom_add_u32(ghist + Int64(bq) * Int64(4), Uint32(1)) + if ordinal < Uint32(BUCKET_CAP): + L.st_g_u64(self._bucket_addr(bucket_base, bq, Int32(ordinal)), e) + k = k + Int32(128) + if stid == Int32(127): + if tot & Int32(1) != Int32(0): + L.st_g_u64( + rbase + Int64(tot) * Int64(8), + Uint64(DUMMY_GPOS) << Uint64(32) | Uint64(4286578688), + ) + L.fence_proxy_async_global() + L.bar(4, 128) + if stid == Int32(0): + if live != Int32(0): + self._stamp(mStamps, cta, 41) + if cutlass.const_expr(self.relst): + L.st_release_u64(cnt_addr, t40 << Uint64(24) | Uint64(Uint32(tot))) + else: + L.fence_acq_rel_gpu() + st_rlx_u64(cnt_addr, t40 << Uint64(24) | Uint64(Uint32(tot))) + if live != Int32(0): + self._stamp(mStamps, cta, 42) + self._stamp(mStamps, cta, ST_CAND_PUB) + if cutlass.const_expr(self.pref): + if live != Int32(0): + k = stid + while k < tot: + wk = ( + cutlass.select_(k >= p1, Int32(1), Int32(0)) + + cutlass.select_(k >= p2, Int32(1), Int32(0)) + + cutlass.select_(k >= p3, Int32(1), Int32(0)) + ) + bk = cutlass.select_( + wk == Int32(1), + p1, + cutlass.select_( + wk == Int32(2), p2, cutlass.select_(wk == Int32(3), p3, Int32(0)) + ), + ) + gpos = Int32( + Uint32( + Uint64(sList[wk * Int32(MAXS * SPLIT_TOK // 4) + k - bk]) >> Uint64(32) + ) + ) + kvr = sBtcR[(gpos - t_lo) >> Int32(5)] * Int32(32) + (gpos & Int32(31)) + prefetch_l2_bulk(cbase + Int64(kvr) * Int64(512), Int32(512)) + k = k + Int32(128) + return tot + + @cute.jit + def _svc_scanpub( + self, + cta, + tid, + live, + cnt_addr, + rbase, + ghist, + bucket_base, + gen, + ntok, + t_lo, + sLog, + Tv, + bscale, + sBtcR, + cbase, + s_wc, + sList, + mStamps, + nth: cutlass.Constexpr[int], + bid: cutlass.Constexpr[int], + pf: cutlass.Constexpr[bool] = True, + b1u: cutlass.Constexpr[int] = 0, + b1e: cutlass.Constexpr[bool] = False, + ): + # one row's first-round publish by nth threads (named barrier bid): vectorized scan of the row's 2048 + # logits in 128-position chunks (round robin over the warps; positions < n via ntok), per-warp SMEM lists of the + # candidates (logit >= T), then region packet, DRS buckets, even padding, released count, L2 prefetch of their + # KV rows. live == 0: warm-up (scratch addresses, no stamps / prefetch). + NW: cutlass.Constexpr[int] = nth // 32 + CPW: cutlass.Constexpr[int] = (16 + nth // 32 - 1) // (nth // 32) + LCAP: cutlass.Constexpr[int] = CPW * 128 + lane = tid % Int32(32) + wid = tid // Int32(32) + lm = Int32(cute.arch.lanemask_lt()) + kT = L.fkey(Tv) + lw = wid * Int32(LCAP) + cnt = Int32(0) + sb_ = Int32(sLog.iterator.toint()) + vals_ = [] + for c_ in cutlass.range_constexpr(CPW): + pb = (wid + Int32(c_ * NW)) * Int32(128) + lane * Int32(4) + vals_.append(lds_v4f32(sb_ + cutlass.min(pb, Int32(MAXS * SPLIT_TOK - 4)) * Int32(4))) + for c_ in cutlass.range_constexpr(CPW): + pb = (wid + Int32(c_ * NW)) * Int32(128) + lane * Int32(4) + oks_ = [] + anyv = Int32(0) + for e_ in cutlass.range_constexpr(4): + ok = Int32(0) + if pb + Int32(e_) < ntok: + if L.fkey(vals_[c_][e_]) >= kT: + ok = Int32(1) + oks_.append(ok) + anyv = anyv | ok + if cute.arch.vote_any_sync(anyv != Int32(0)): + for e_ in cutlass.range_constexpr(4): + bm = Int32(cute.arch.vote_ballot_sync(oks_[e_] != Int32(0))) + if oks_[e_] != Int32(0): + sList[lw + cnt + Int32(cute.arch.popc(bm & lm))] = Int64( + Uint64(Uint32(t_lo + pb + Int32(e_))) << Uint64(32) + | Uint64(L.u32_of_f32(vals_[c_][e_])) + ) + cnt = cnt + Int32(cute.arch.popc(bm)) + b1st_ = None + if cutlass.const_expr(b1u > 0 and b1e): + # Bins and histogram atom.adds of this warp's first b1u x 32 candidates before the count + # barrier and the prefix, so their round trip overlaps them. + cute.arch.sync_warp() + b1st_ = self._b1l_issue(sList, lw, cnt, lane, Tv, bscale, ghist, b1u, LCAP) + if lane == Int32(0): + s_wc[wid] = cnt + L.bar(bid, nth) + pre = [Int32(0)] + for w_ in cutlass.range_constexpr(NW): + pre.append(pre[w_] + s_wc[w_]) + tot = pre[NW] + t40 = self._tag40(gen) + if live != Int32(0): + if tid == Int32(0): + self._stamp(mStamps, cta, 40) + if cutlass.const_expr(b1u > 0 and b1e): + # Each warp publishes its own scan list (lane-strided) from the warp's prefix on, which + # keeps the flattened packet order: the early batch's stores, then batches of b1u. + myp = Int32(0) + for w_ in cutlass.range_constexpr(1, NW): + myp = cutlass.select_(wid >= Int32(w_), pre[w_], myp) + self._b1l_store(b1st_, lane, cnt, rbase, myp, bucket_base, b1u) + k = lane + Int32(32 * b1u) + while k < cnt: + st_ = self._b1l_issue(sList, lw, cnt, k, Tv, bscale, ghist, b1u, LCAP) + self._b1l_store(st_, k, cnt, rbase, myp, bucket_base, b1u) + k = k + Int32(32 * b1u) + elif cutlass.const_expr(b1u > 0): + # The CTA-wide flattened order in batches of b1u. + k = tid + while k < tot: + st_ = self._b1l_issue_flat( + sList, pre, tot, k, Tv, bscale, ghist, b1u, nth, NW, LCAP + ) + self._b1l_store(st_, k, tot, rbase, Int32(0), bucket_base, b1u, nth) + k = k + Int32(nth * b1u) + else: + k = tid + while k < tot: + wk = Int32(0) + bk = Int32(0) + for w_ in cutlass.range_constexpr(1, NW): + if k >= pre[w_]: + wk = Int32(w_) + bk = pre[w_] + e = Uint64(sList[wk * Int32(LCAP) + k - bk]) + L.st_g_u64(rbase + Int64(k) * Int64(8), e) + if bscale > Float32(0.0): + bq = L._vbin(e, Tv, bscale, NB_INITIAL) + ordinal = atom_add_u32(ghist + Int64(bq) * Int64(4), Uint32(1)) + if ordinal < Uint32(BUCKET_CAP): + L.st_g_u64(self._bucket_addr(bucket_base, bq, Int32(ordinal)), e) + k = k + Int32(nth) + if tid == Int32(nth - 1): + if tot & Int32(1) != Int32(0): + L.st_g_u64( + rbase + Int64(tot) * Int64(8), + Uint64(DUMMY_GPOS) << Uint64(32) | Uint64(4286578688), + ) + L.fence_proxy_async_global() + L.bar(bid, nth) + if tid == Int32(0): + if live != Int32(0): + self._stamp(mStamps, cta, 41) + if cutlass.const_expr(self.relst): + L.st_release_u64(cnt_addr, t40 << Uint64(24) | Uint64(Uint32(tot))) + else: + L.fence_acq_rel_gpu() + st_rlx_u64(cnt_addr, t40 << Uint64(24) | Uint64(Uint32(tot))) + if live != Int32(0): + self._stamp(mStamps, cta, 42) + self._stamp(mStamps, cta, ST_CAND_PUB) + if cutlass.const_expr(self.pref and pf): + if live != Int32(0): + k = tid + while k < tot: + wk = Int32(0) + bk = Int32(0) + for w_ in cutlass.range_constexpr(1, NW): + if k >= pre[w_]: + wk = Int32(w_) + bk = pre[w_] + gpos = Int32(Uint32(Uint64(sList[wk * Int32(LCAP) + k - bk]) >> Uint64(32))) + kvr = sBtcR[(gpos - t_lo) >> Int32(5)] * Int32(32) + (gpos & Int32(31)) + prefetch_l2_bulk(cbase + Int64(kvr) * Int64(512), Int32(512)) + k = k + Int32(nth) + return tot + + @cute.jit + def _poll_dir_nb(self, ws, gen, seq, s_dir): + # one look at the row's directive word; kind K_NONE when nothing newer than seq is published + t40 = self._tag40(gen) + h = L.ld_relaxed_u64(self._w(ws, W_DIR)) + kind = Int32(K_NONE) + dseq = seq + if h >> Uint64(24) == t40 and Int32(Uint32(h >> Uint64(8) & Uint64(65535))) > seq: + kind = Int32(Uint32(h & Uint64(15))) + dseq = Int32(Uint32(h >> Uint64(8) & Uint64(65535))) + if kind != Int32(K_DONE): + L.fence_acq_rel_gpu() + p0 = L.ld_relaxed_u64(self._w(ws, W_DP)) + p1 = L.ld_relaxed_u64(self._w(ws, W_DP + 1)) + p2 = L.ld_relaxed_u64(self._w(ws, W_DP + 2)) + s_dir[2] = Int32(Uint32(p2 & Uint64(4294967295))) + s_dir[3] = Int32(Uint32(p0 & Uint64(4294967295))) + s_dir[4] = Int32(Uint32(p0 >> Uint64(32))) + s_dir[5] = Int32(Uint32(p1 & Uint64(4294967295))) + s_dir[6] = Int32(Uint32(p1 >> Uint64(32))) + s_dir[0] = kind + s_dir[1] = dseq + + @cute.jit + def _stream_serve( + self, + cta, + tidx, + ws, + gen, + seq, + tot, + ntok, + t_lo, + sLog, + s_wc, + s_dir, + mRegion, + mHist, + arena, + blocking: cutlass.Constexpr[bool], + nth: cutlass.Constexpr[int] = 256, + bid: cutlass.Constexpr[int] = 5, + hoff: cutlass.Constexpr[int] = S_OFF_KV0, + ): + # serve one row's selection directives: until K_DONE (blocking) or one non-blocking check + rbase = mRegion.iterator.toint() + Int64(cta) * Int64(2 * CAPR * 8) + fin = Int32(0) + go = Int32(1) + while go != Int32(0): + if tidx == 0: + if cutlass.const_expr(blocking): + self._poll_dir(ws, gen, seq, s_dir) + else: + self._poll_dir_nb(ws, gen, seq, s_dir) + L.bar(bid, nth) + kind = s_dir[0] + dseq = s_dir[1] + if kind == Int32(K_PUB): + slot = s_dir[2] & Int32(255) + klo = Uint64(Uint32(s_dir[4])) << Uint64(32) | Uint64(Uint32(s_dir[3])) + khi = Uint64(Uint32(s_dir[6])) << Uint64(32) | Uint64(Uint32(s_dir[5])) + base = tot + if cutlass.const_expr(self.bulk): + base = tot + (tot & Int32(1)) + if slot == Int32(2): + base = Int32(CAPR) + self._stream_pub( + cta, + tidx, + ws, + gen, + slot, + base, + klo, + khi, + ntok, + t_lo, + sLog, + s_wc, + rbase, + nth=nth, + bid=bid, + ) + elif kind == Int32(K_HIST): + plen = s_dir[2] >> Int32(8) & Int32(255) + pref = Uint64(Uint32(s_dir[4])) << Uint64(32) | Uint64(Uint32(s_dir[3])) + self._stream_hist( + cta, + tidx, + ws, + gen, + dseq, + pref, + plen, + ntok, + t_lo, + sLog, + mHist, + arena, + nth=nth, + bid=bid, + hoff=hoff, + ) + elif kind != Int32(K_NONE): + fin = Int32(1) + if kind != Int32(K_NONE): + seq = dseq + L.bar(bid, nth) + if cutlass.const_expr(not blocking): + go = Int32(0) + if fin != Int32(0): + go = Int32(0) + return (seq, fin) + + @cute.jit + def _serve_row( + self, + q, + cta, + tidx, + ws, + arena, + s_wc, + s_dir, + mRegion, + mHist, + blocking: cutlass.Constexpr[bool], + nth: cutlass.Constexpr[int] = 256, + bid: cutlass.Constexpr[int] = 5, + hoff: cutlass.Constexpr[int] = S_OFF_KV0, + ebid: cutlass.Constexpr[int] = 3, + ): + # serve row q from its saved state (all math threads; tidx 0 writes the state back) + rs_ = self.row_sizes() + rst = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst, dtype=Int32) + q * Int32(self.rst_w), + cute.make_layout(self.rst_w), + ) + rgen = cute.make_tensor( + cute.recast_ptr(arena + self.s_rowst + self.s_rgen_off, dtype=Int64), + cute.make_layout(self.nslot), + ) + if rst[4] == Int32(0): + sLogQ = cute.make_tensor( + cute.recast_ptr(arena + S_OFF_LOGR, dtype=Float32) + + self._lslot(q) * Int32(MAXS * SPLIT_TOK), + cute.make_layout(MAXS * SPLIT_TOK), + ) + seq2, fin2 = self._stream_serve( + cta, + tidx, + ws + Int64(q) * Int64(rs_["ws"] * 8), + Uint64(rgen[q]), + rst[3], + rst[0], + rst[1], + rst[2], + sLogQ, + s_wc, + s_dir, + _flat(mRegion, q, rs_["region"]), + _flat(mHist, q, rs_["hist"]), + arena, + blocking, + nth=nth, + bid=bid, + hoff=hoff, + ) + if tidx == 0: + rst[3] = seq2 + rst[4] = fin2 + L.bar(ebid, nth) + + @cute.jit + def _poll_dir(self, ws, gen, seq, s_dir): + t40 = self._tag40(gen) + t64 = gen + Uint64(1) + tdl = self._deadline() + st_ = Int32(0) + h = Uint64(0) + while st_ == Int32(0): + h = L.ld_relaxed_u64(self._w(ws, W_DIR)) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if h >> Uint64(24) == t40 and Int32(Uint32(h >> Uint64(8) & Uint64(65535))) > seq: + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + else: + L.nanosleep(Int32(64)) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + elif st_ == Int32(2): + self._flag(ws, gen, Int32(E_ABORTED)) + kind = Int32(K_DONE) + dseq = seq + Int32(1) + if st_ == Int32(1): + kind = Int32(Uint32(h & Uint64(15))) + dseq = Int32(Uint32(h >> Uint64(8) & Uint64(65535))) + if kind != Int32(K_DONE): + L.fence_acq_rel_gpu() + p0 = L.ld_relaxed_u64(self._w(ws, W_DP)) + p1 = L.ld_relaxed_u64(self._w(ws, W_DP + 1)) + p2 = L.ld_relaxed_u64(self._w(ws, W_DP + 2)) + s_dir[2] = Int32(Uint32(p2 & Uint64(4294967295))) + s_dir[3] = Int32(Uint32(p0 & Uint64(4294967295))) + s_dir[4] = Int32(Uint32(p0 >> Uint64(32))) + s_dir[5] = Int32(Uint32(p1 & Uint64(4294967295))) + s_dir[6] = Int32(Uint32(p1 >> Uint64(32))) + s_dir[0] = kind + s_dir[1] = dseq + + @cute.jit + def _k50(self, x, gpos): + return Uint64(L.fkey(x)) << Uint64(18) | Uint64(Uint32(Int32(GPOS_MASK) - gpos)) + + @cute.jit + def _stream_pub( + self, + cta, + tidx, + ws, + gen, + slot, + base, + klo, + khi, + ntok, + t_lo, + sLog, + s_wc, + rbase, + nth: cutlass.Constexpr[int] = 256, + bid: cutlass.Constexpr[int] = 5, + ): + lane = tidx % 32 + wid = tidx // 32 + lm = Int32(cute.arch.lanemask_lt()) + CW = (ntok + Int32(nth - 1)) // Int32(nth) * Int32(32) + c0 = wid * CW + c1 = cutlass.min(ntok, c0 + CW) + cnt = Int32(0) + kb = c0 + while kb < c1: + p = kb + lane + ok = Int32(0) + if p < c1: + kk = self._k50(sLog[p], t_lo + p) + if kk >= klo and kk < khi: + ok = Int32(1) + cnt = cnt + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(ok != Int32(0)))) + kb = kb + Int32(32) + if lane == 0: + s_wc[wid] = cnt + L.bar(bid, nth) + o = base + tot = Int32(0) + for w_ in cutlass.range_constexpr(nth // 32): + v_ = s_wc[w_] + if Int32(w_) < wid: + o = o + v_ + tot = tot + v_ + kb = c0 + while kb < c1: + p = kb + lane + ok = Int32(0) + e = Uint64(0) + if p < c1: + x = sLog[p] + gpos = t_lo + p + kk = self._k50(x, gpos) + if kk >= klo and kk < khi: + ok = Int32(1) + e = Uint64(Uint32(gpos)) << Uint64(32) | Uint64(L.u32_of_f32(x)) + bm = Int32(cute.arch.vote_ballot_sync(ok != Int32(0))) + if ok != Int32(0): + L.st_g_u64(rbase + Int64(o + Int32(cute.arch.popc(bm & lm))) * Int64(8), e) + o = o + Int32(cute.arch.popc(bm)) + kb = kb + Int32(32) + L.bar(bid, nth) + if tidx == 0: + L.fence_acq_rel_gpu() + st_rlx_u64( + self._cnt_addr(ws, slot, cta), self._tag40(gen) << Uint64(24) | Uint64(Uint32(tot)) + ) + + @cute.jit + def _stream_hist( + self, + cta, + tidx, + ws, + gen, + seq, + pref, + plen, + ntok, + t_lo, + sLog, + mHist, + arena, + nth: cutlass.Constexpr[int] = 256, + bid: cutlass.Constexpr[int] = 5, + hoff: cutlass.Constexpr[int] = S_OFF_KV0, + ): + sh = _sm_tensor(arena, hoff, Int32, NB_DRS) + if cutlass.const_expr(NB_DRS % nth == 0): + for z_ in cutlass.range_constexpr(NB_DRS // nth): + sh[tidx + Int32(z_ * nth)] = Int32(0) + else: + # nth = 96 (publisher warps): the last round clears the remaining bins only + for z_ in cutlass.range_constexpr((NB_DRS + nth - 1) // nth): + if tidx + Int32(z_ * nth) < Int32(NB_DRS): + sh[tidx + Int32(z_ * nth)] = Int32(0) + L.bar(bid, nth) + shp = Uint64(Int32(K50_BITS) - plen) + shd = Uint64(Int32(K50_BITS - DRS_DIG) - plen) + lmk = Int32(cute.arch.lanemask_lt()) + nit = (ntok + Int32(nth - 1)) // Int32(nth) + jj = Int32(0) + while jj < nit: + p = tidx + jj * Int32(nth) + dg = Int32(NB_DRS) + if p < ntok: + kk = self._k50(sLog[p], t_lo + p) + if kk >> shp == pref: + dg = Int32(Uint32(kk >> shd & Uint64(NB_DRS - 1))) + mm_ = match_any_b32(dg) + if dg != Int32(NB_DRS): + if mm_ & lmk == Int32(0): + cute.arch.red( + sh.iterator + dg, + Int32(cute.arch.popc(mm_)), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + jj = jj + Int32(1) + L.bar(bid, nth) + gh = mHist.iterator.toint() + Int64(seq) * Int64(NB_DRS * 4) + if cutlass.const_expr(NB_DRS % nth == 0): + for z_ in cutlass.range_constexpr(NB_DRS // nth): + b_ = tidx + Int32(z_ * nth) + v_ = sh[b_] + if v_ != Int32(0): + red_add_u32(gh + Int64(b_) * Int64(4), v_) + else: + # nth = 96: bounds-checked rounds + for z_ in cutlass.range_constexpr((NB_DRS + nth - 1) // nth): + b_ = tidx + Int32(z_ * nth) + if b_ < Int32(NB_DRS): + v_ = sh[b_] + if v_ != Int32(0): + red_add_u32(gh + Int64(b_) * Int64(4), v_) + L.bar(bid, nth) + if tidx == 0: + L.fence_acq_rel_gpu() + L.red_add_u64(self._w(ws, W_RC + seq), Uint64(1)) + + @cute.jit + def _team_cta( + self, + arena, + cta, + tidx, + ws, + tma_q, + tma_swa, + tma_cmp, + mOut, + mCtx, + mSwaLocal, + mBtSwa, + mBtC, + mSinks, + mSwaLens, + mTopk, + mGidx, + mHist, + mBoard, + mRegion, + mStamps, + mCtl, + softmax_scale, + mDesc, + mCPool=None, + qrow=0, + ): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + d = cta - Int32(self.ns) + bars = _ptr(arena, T_OFF_BAR, Int64) + s_q = _ptr(arena, T_OFF_Q, A.E4M3) + s_kv = _ptr(arena, T_OFF_KV, A.E4M3) + s_ext = _ptr(arena, T_OFF_LIST, A.E4M3) + s_stat = _ptr(arena, T_OFF_STAT, Float32) + s_fin = _ptr(arena, T_OFF_FIN, Float32) + s_idx = _ptr(arena, T_OFF_IDX, Int32) + misc = _ptr(arena, T_OFF_MISC, Int32) + if cutlass.const_expr(self.tearly): + # The row and window lengths are loaded at entry, before the barrier setup. + swa_len_e_ = mSwaLens[0] + n_e_ = mDesc[2] + gw1 = Uint64(0) + gw2 = Uint64(0) + gw3 = Uint64(0) + if tidx == Int32(0): + gw1, gw2, gw3 = self._entry_loads(ws) + (misc + 12).store(Int32(0)) + (misc + 13).store(Int32(0)) + (misc + 14).store(Int32(0)) + (misc + 15).store(Int32(0)) + (misc + 16).store(Int32(0)) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_init(bars + B_QF, 1) + for i in cutlass.range_constexpr(NSLOTS): + if cutlass.const_expr(self.rs24_lsu and 4 <= i < 8): + # g = 1: tile 4's slots also count the control WG's cp.async arrivals + prims.mbarrier_init( + bars + (B_KVF + i), + cutlass.select_( + (d & Int32(1)) != Int32(0), Int32(1 + A.LSU_ARR), Int32(1) + ), + ) + else: + prims.mbarrier_init(bars + (B_KVF + i), 1) + prims.mbarrier_init(bars + (B_KVE + i), 1) + for i in cutlass.range_constexpr(4): + prims.mbarrier_init(bars + (B_SF + i), 1) + prims.mbarrier_init(bars + (B_SE + i), 1) + prims.mbarrier_init(bars + (B_PF + i), 4) + prims.mbarrier_init(bars + B_OF, 1) + prims.mbarrier_init(bars + B_OC, 4) + prims.mbarrier_init(bars + B_FIN, 4) + prims.mbarrier_init(bars + B_SWA, 128) + prims.mbarrier_init(bars + B_SEL, 128) + prims.mbarrier_init(bars + B_T, 1) + prims.mbarrier_init(bars + B_PVL, 1) + prims.mbarrier_init(bars + B_BTC, 1) + prims.mbarrier_init(bars + B_LST, 1) + prims.mbarrier_init(bars + B_EAR, 128) + if cutlass.const_expr(self.rs24): + prims.mbarrier_init(bars + B_RX, 1) + prims.mbarrier_init(bars + B_PR, 1) + if cutlass.const_expr(self.rs24_dry): + prims.mbarrier_init(bars + B_DRY, 1) + prims.mbarrier_arrive_expect_tx( + bars + B_RX, A.rs24_rx_bytes(self.rs24_f32 or self.rs24_asym, self.team4) + ) + if cutlass.const_expr(self.rs24_dry): + prims.mbarrier_arrive_expect_tx( + bars + B_DRY, + A.rs24_rx_bytes(self.rs24_f32 or self.rs24_asym, self.team4), + ) + if warp == Int32(A.W_G0): + if prims.elect_sync(): + prims.prefetch_tensormap(tma_q.get_ptr()) + prims.prefetch_tensormap(tma_swa.get_ptr()) + prims.prefetch_tensormap(tma_cmp.get_ptr()) + prims.fence_mbarrier_init() + if warp == Int32(A.W_MMA): + prims.tcgen05_alloc(misc, A.TMEM_COLS, group=prims.CTAGroup.CTA_1) + prims.tcgen05_relinquish_alloc_permit(group=prims.CTAGroup.CTA_1) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + # phase 0 of the cluster barrier: arrive now (the mbarrier inits are fenced above); every thread waits only + # before its first remote operation (softmax WG: real merge; control WG: B_PR arrive; others: at exit) + if cutlass.const_expr(self.team4): + # team4 uses the releasing arrive + cute.arch.cluster_arrive() + else: + cute.arch.cluster_arrive_relaxed() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = misc.load() + scale_log2 = softmax_scale * Float32(A.LOG2_E) + tr = None + if cutlass.const_expr(self.stamps): + tr = mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8) + if cutlass.const_expr(self.tearly): + swa_len = swa_len_e_ + n = n_e_ + else: + swa_len = mSwaLens[0] + n = mDesc[2] + if n < Int32(0) or n > Int32(N_MAX): + n = Int32(0) + n_sel = cutlass.min(n, Int32(K_TOP)) + if warp < Int32(4): + prims.setmaxregister(A.REG_SOFTMAX, prims.SetMaxRegisterAction.INCREASE) + if cutlass.const_expr(self.fblka): + self._block_a_lead( + arena, cta, tidx, ws, n, mBoard, mStamps, gw1, gw2, gw3, mCtl, d, mHist + ) + else: + # One call site for the whole team: the followers run the leader's threshold code once, dry (one + # stale board read, no wait, no publish), at kernel start, so the leader's real pass when the board + # completes fetches its code from L2. Followers then read the leader's T line as before. + self._block_a_lead( + arena, cta, tidx, ws, n, mBoard, mStamps, gw1, gw2, gw3, mCtl, d, mHist + ) + if d != Int32(0): + self._follow_tline(arena, cta, d, tidx, ws, mStamps, gw1, gw2, gw3, mCtl) + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_SMX, 128) + if tidx == Int32(0): + prims.mbarrier_arrive(bars + B_T) + if cutlass.const_expr(self.gjoin): + if cutlass.const_expr(self.rs24): + zsm = Int32(cute.recast_ptr(arena + T_OFF_MISC + 61 * 4, dtype=Int32).toint()) + A.role_softmax_24( + tmem, + bars + B_SF, + bars + B_PF, + scale_log2, + swa_len, + n_sel, + d, + bars + B_OF, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + Int32(_ptr(arena, T_OFF_LIST, Int32).toint()), + Int32(_ptr(arena, T_OFF_STAT, Int32).toint()), + Int32((bars + B_PVL).toint()), + Int32((bars + B_RX).toint()), + Int32((bars + B_PR).toint()), + Int32((bars + B_DRY).toint()), + zsm, + tr, + full_tiles=self.full_attention_tiles, + dry_merge=self.rs24_dry, + f32x=self.rs24_f32, + asym=self.rs24_asym, + wide_v=self.team4, + ) + else: + A.role_softmax_team( + tmem, + bars + B_SF, + bars + B_PF, + s_stat, + s_fin, + bars + B_FIN, + scale_log2, + swa_len, + n_sel, + Int32(0), + Int32(NTILES), + Float32(A.NEG_FLT_MAX), + Float32(0.0), + True, + tr, + bars + B_OF, + d, + full_tiles=self.full_attention_tiles, + ) + if cutlass.const_expr(self.late_done == 2): + if d == Int32(0): + if tidx == Int32(0): + mi_ = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + if mi_[12] == Int32(P_T1) and mi_[14] != Int32(0): + gq_ = Uint64(Uint32(mi_[5])) << Uint64(32) | Uint64(Uint32(mi_[4])) + self._publish_dir( + ws, + gq_, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + else: + A.role_softmax_team( + tmem, + bars + B_SF, + bars + B_PF, + s_stat, + s_fin, + bars + B_FIN, + scale_log2, + swa_len, + n_sel, + Int32(0), + Int32(NTILES), + Float32(A.NEG_FLT_MAX), + Float32(0.0), + True, + tr, + full_tiles=self.full_attention_tiles, + ) + elif warp < Int32(8): + if cutlass.const_expr(self.ctl_regs): + prims.setmaxregister(A.REG_CTL, prims.SetMaxRegisterAction.INCREASE) + if cutlass.const_expr(self.rs24): + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + None, + None, + ) + if cutlass.const_expr(self.rs24_lsu): + if (d & Int32(1)) != Int32(0): + # tile 4's rows were published by this warpgroup before its B_SEL arrive (named barrier); issue + # before the cluster wait / B_PR arrive (the partner pushes into slot 8 only at its merge) + A.lsu_tile4( + tidx - Int32(128), + d, + self.rs24_lsu, + Int32(s_kv.toint()), + Int32(s_idx.toint()), + Int32((bars + B_KVF).toint()), + bars + B_KVE, + mCPool.iterator.toint(), + tr, + wide_v=self.team4, + ) + if cutlass.const_expr(self.stamps): + A._stamp( + mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8), + Int32(52), + tidx == Int32(128), + ) + cute.arch.cluster_wait() + if tidx == Int32(160): + # (not ctid 0: on team CTA 0 it may still be in the late-done follower wait) + L.mbar_arrive_remote( + L.mapa_u32(Int32((bars + B_PR).toint()), L.cluster_ctarank() ^ Int32(1)) + ) + elif cutlass.const_expr(self.gjoin): + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + ( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_SEL, + Int32(A.NGW) + warp - Int32(4), + d, + NTILES, + NSLOTS, + None, + Int32(2), + A.NGW + 4, + bars + B_EAR, + 2, + ), + ( + tmem, + bars + B_PF, + bars + B_OF, + bars + B_OC, + s_stat, + s_fin, + bars + B_FIN, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + scale_log2, + d, + Int32(s_kv.toint()), + NTILES, + BAR_EPI, + tr, + bars + B_PVL, + ), + ) + else: + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + ) + A.role_corr_epi_team( + tmem, + bars + B_PF, + bars + B_OF, + bars + B_OC, + s_stat, + s_fin, + bars + B_FIN, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + scale_log2, + d, + Int32(s_kv.toint()), + NTILES, + BAR_EPI, + tr, + ) + elif warp == Int32(A.W_MMA): + prims.setmaxregister(A.REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + if cutlass.const_expr(self.gjoin): + if cutlass.const_expr(self.rs24): + A.role_mma_24( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_PF, + bars + B_OF, + d, + bars + B_PVL, + tr, + pfence=self.rs24_lsu > 0, + wide_v=self.team4, + ) + else: + A.role_mma_ordered( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_SE, + bars + B_PF, + bars + B_OF, + d, + NTILES, + NSLOTS, + bars + B_PVL, + tr, + bars + B_EAR if self.mma_block else None, + self.mma_idle_ns, + ) + else: + A.role_mma_team( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_SE, + bars + B_PF, + bars + B_OC, + bars + B_OF, + d, + NTILES, + NSLOTS, + tr, + self.qk_ahead, + ) + else: + prims.setmaxregister(A.REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + if warp == Int32(A.W_G0): + A.role_q_load(tma_q, s_q, bars + B_QF, qrow) + if warp == Int32(A.W_G0 + 1): + if prims.elect_sync(): + btc_cols = cute.size(mBtC, mode=[1]) + npg = cutlass.min( + (n + Int32(31)) // Int32(32), cutlass.min(btc_cols, Int32(BTC_CAP)) + ) + nbt = npg * Int32(4) // Int32(16) * Int32(16) + if nbt > Int32(0): + L.mbar_arrive_expect_tx(Int32((bars + B_BTC).toint()), nbt) + L.bulk_g2s( + Int32(cute.recast_ptr(arena + T_OFF_BTC, dtype=Int32).toint()), + mBtC.iterator.toint(), + nbt, + Int32((bars + B_BTC).toint()), + ) + else: + prims.mbarrier_arrive(bars + B_BTC) + if warp == Int32(A.W_G0 + 2): + rgb = mRegion.iterator.toint() + for q in cutlass.range_constexpr(NB_INITIAL // 32): + bha = self._bucket_addr(rgb, cute.arch.lane_idx() + Int32(q * 32), Int32(0)) + for h_ in cutlass.range_constexpr(4): + L.prefetch_l2(bha + Int64(128 * h_)) + if cutlass.const_expr(self.swag): + if warp >= Int32(A.W_G0 + 3): + gt_ = (warp - Int32(A.W_G0 + 3)) * Int32(32) + cute.arch.lane_idx() + mbs_ = cute.size(mBtSwa, mode=[1]) + loc_ = mSwaLocal[0, gt_] + rsw_ = L.l2g_swa_local(loc_, Int32(0), mBtSwa, mbs_, Int32(0)) + (s_idx + gt_).store(rsw_) + # each writer releases its own index store to the gather warps + prims.mbarrier_arrive(bars + B_SWA) + if cutlass.const_expr(self.rs24): + A.role_gather_24( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_EAR, + bars + B_SEL, + warp - Int32(A.W_G0), + d, + NTILES, + tr, + (misc + 16) if self.rs24_t4split else None, + lsu_g=self.rs24_lsu, + wide_v=self.team4, + ) + else: + A.role_gather_team( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_SEL, + warp - Int32(A.W_G0), + d, + NTILES, + NSLOTS, + tr, + Int32(0), + A.NGW + 4 if self.gjoin else A.NGW, + bars + B_EAR if self.gjoin else None, + 2 if self.gjoin else 1, + ) + if cutlass.const_expr(self.hook): + if warp == Int32(A.W_G0 + A.NGW - 1): + if cute.arch.lane_idx() == Int32(0): + self._stamp(mStamps, cta, 106) + self._team_exit(arena, d, ws) + self._stamp(mStamps, cta, 107) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24 and self.rs24_exitbar): + if warp >= Int32(8): + cute.arch.cluster_wait() + # neither CTA of the pair exits while the other may still push into it (not needed: every remote write or + # arrive into a CTA is consumed by one of its own mbarrier waits before it finishes; a cluster wait that + # actually has to wait costs ~1 us) + cute.arch.cluster_arrive() + cute.arch.cluster_wait() + if warp == Int32(A.W_MMA): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + prims.tcgen05_dealloc( + prims.make_tmem_ptr(tmem, Float32), A.TMEM_COLS, group=prims.CTAGroup.CTA_1 + ) + if cutlass.const_expr(self.stamps): + if tidx == Int32(0): + (mStamps.iterator + cta * NSTAMP + ST_M_EXIT).store(Int64(L.gtimer())) + + def _rsel(self, vals, r): + # select vals[r] (Python list, dynamic r) + v = vals[0] + for k_ in range(1, len(vals)): + v = cutlass.select_(r == Int32(k_), vals[k_], v) + return v + + @cute.jit + def _tserver_cta(self, arena, cta, tidx, ws0, mCtxA, mHistA, mBoardA, mStampsA, mCtlA, tt): + # dedicated T-server CTA tt (of tcta): the threshold line of the rows tt, tt + tcta, ... in order, + # computed by warps 0-3 (128 threads, as the stream T server): the board of a row is awaited (spin), + # T / HIC / T3 / SMAX published after the row's histogram clear. The other warps have nothing to do. + if tidx < Int32(128): + rs_ = self.row_sizes() + nrk_ = (Int32(self.nrows) - tt + Int32(self.tcta - 1)) // Int32(self.tcta) + for k_ in cutlass.range(nrk_, unroll=1): + r_ = tt + k_ * Int32(self.tcta) + ws_r_ = ws0 + Int64(r_) * Int64(rs_["ws"] * 8) + n_ = mCtxA[r_] + if n_ < Int32(0) or n_ > Int32(N_MAX): + n_ = Int32(0) + g1_ = Uint64(0) + g2_ = Uint64(0) + g3_ = Uint64(0) + if tidx == Int32(0): + g1_, g2_, g3_ = self._entry_loads(ws_r_) + mStT_ = cute.make_tensor( + mStampsA.iterator + (Int32(24) + r_) * Int32(self.num_sms * NSTAMP), + mStampsA.layout, + ) + self._block_a_lead( + arena, + cta, + tidx, + ws_r_, + n_, + _flat(mBoardA, r_, rs_["board"]), + mStT_, + g1_, + g2_, + g3_, + _flat(mCtlA, r_, rs_["ctl"]), + Int32(0), + _flat(mHistA, r_, rs_["hist"]), + ) + + @cute.jit + def _team_cta_mr( + self, + arena, + cta, + tidx, + ws0, + tma_q, + tma_swa, + tma_cmp, + mOutA, + mCtxA, + mSwaLocalA, + mBtSwaA, + mBtCA, + mSinks, + mSwaLensA, + mTopkA, + mGidxA, + mHistA, + mBoardA, + mRegionA, + mStampsA, + mCtlA, + softmax_scale, + mDescA, + mCPool, + tm, + ): + # tcta > 0: the CTAs after the shared teams (kernel(): their tm is nteams, cta = ns + their index among the last + # team_ctas CTAs) are the dedicated T servers; their server index is (tm - nteams) * team_ctas + cta - ns + args_ = ( + arena, + cta, + tidx, + ws0, + tma_q, + tma_swa, + tma_cmp, + mOutA, + mCtxA, + mSwaLocalA, + mBtSwaA, + mBtCA, + mSinks, + mSwaLensA, + mTopkA, + mGidxA, + mHistA, + mBoardA, + mRegionA, + mStampsA, + mCtlA, + softmax_scale, + mDescA, + mCPool, + tm, + ) + if cutlass.const_expr(self.tcta > 0): + if tm >= Int32(self.nteams): + self._tserver_cta( + arena, + cta, + tidx, + ws0, + mCtxA, + mHistA, + mBoardA, + mStampsA, + mCtlA, + (tm - Int32(self.nteams)) * Int32(self.team_ctas) + cta - Int32(self.ns), + ) + else: + self._team_cta_mr_body(*args_) + else: + self._team_cta_mr_body(*args_) + + @cute.jit + def _team_cta_mr_body( + self, + arena, + cta, + tidx, + ws0, + tma_q, + tma_swa, + tma_cmp, + mOutA, + mCtxA, + mSwaLocalA, + mBtSwaA, + mBtCA, + mSinks, + mSwaLensA, + mTopkA, + mGidxA, + mHistA, + mBoardA, + mRegionA, + mStampsA, + mCtlA, + softmax_scale, + mDescA, + mCPool, + tm, + ): + # one team serving rows tm, tm + nteams, ... + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + d = cta - Int32(self.ns) + bars = _ptr(arena, T_OFF_BAR, Int64) + s_q = _ptr(arena, T_OFF_Q, A.E4M3) + s_kv = _ptr(arena, T_OFF_KV, A.E4M3) + s_ext = _ptr(arena, T_OFF_LIST, A.E4M3) + s_stat = _ptr(arena, T_OFF_STAT, Float32) + s_fin = _ptr(arena, T_OFF_FIN, Float32) + s_idx = _ptr(arena, T_OFF_IDX, Int32) + misc = _ptr(arena, T_OFF_MISC, Int32) + pw = _ptr(arena, T_OFF_PW, Int32) # pass entry words + rs_ = self.row_sizes() + npass_ = (Int32(self.nrows) - tm + Int32(self.nteams - 1)) // Int32(self.nteams) + # thread 0 loads every pass's entry words, n and swa_len at kernel start (memory idle) into + # misc[32 + 8 k ..] (only warp 0 waits for them; the setmaxnreg.dec warps carry no pending loads) + if tidx == Int32(0): + for kk_ in cutlass.range_constexpr((self.nrows + self.nteams - 1) // self.nteams): + rk_ = cutlass.min(tm + Int32(kk_ * self.nteams), Int32(self.nrows - 1)) + e1_, e2_, e3_ = self._entry_loads(ws0 + Int64(rk_) * Int64(rs_["ws"] * 8)) + for jj_, ev_ in enumerate((e1_, e2_, e3_)): + (pw + (8 * kk_ + 2 * jj_)).store(Int32(Uint32(ev_ & Uint64(4294967295)))) + (pw + (1 + 8 * kk_ + 2 * jj_)).store(Int32(Uint32(ev_ >> Uint64(32)))) + (pw + (6 + 8 * kk_)).store(_flat(mDescA, rk_, rs_["desc"])[2]) + (pw + (7 + 8 * kk_)).store(_row1(mSwaLensA, rk_)[0]) + if warp == Int32(A.W_G0): + if prims.elect_sync(): + prims.prefetch_tensormap(tma_q.get_ptr()) + prims.prefetch_tensormap(tma_swa.get_ptr()) + prims.prefetch_tensormap(tma_cmp.get_ptr()) + if warp == Int32(A.W_MMA): + prims.tcgen05_alloc(misc, A.TMEM_COLS, group=prims.CTAGroup.CTA_1) + prims.tcgen05_relinquish_alloc_permit(group=prims.CTAGroup.CTA_1) + if warp < Int32(4): + prims.setmaxregister(A.REG_SOFTMAX, prims.SetMaxRegisterAction.INCREASE) + for k_ in cutlass.range(npass_, unroll=1): + row_ = tm + k_ * Int32(self.nteams) + mStamps = cute.make_tensor( + mStampsA.iterator + k_ * Int32(self.num_sms * NSTAMP), mStampsA.layout + ) + ws = ws0 + Int64(row_) * Int64(rs_["ws"] * 8) + mOut = _row2(mOutA, row_) + _mCtx = _row1(mCtxA, row_) + mSwaLocal = _row2(mSwaLocalA, row_) + mBtSwa = _row2(mBtSwaA, row_) + mBtC = _row2(mBtCA, row_) + _mSwaLens = _row1(mSwaLensA, row_) + mTopk = _row2(mTopkA, row_) + mGidx = _row2(mGidxA, row_) + mHist = _flat(mHistA, row_, rs_["hist"]) + mBoard = _flat(mBoardA, row_, rs_["board"]) + mRegion = _flat(mRegionA, row_, rs_["region"]) + mCtl = _flat(mCtlA, row_, rs_["ctl"]) + _mDesc = _flat(mDescA, row_, rs_["desc"]) + qrow = row_ + gw1 = Uint64(0) + gw2 = Uint64(0) + gw3 = Uint64(0) + if tidx == Int32(0): + gw1 = Uint64(Uint32((pw + (Int32(0) + k_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(1) + k_ * Int32(8))).load()) + ) << Uint64(32) + gw2 = Uint64(Uint32((pw + (Int32(2) + k_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(3) + k_ * Int32(8))).load()) + ) << Uint64(32) + gw3 = Uint64(Uint32((pw + (Int32(4) + k_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(5) + k_ * Int32(8))).load()) + ) << Uint64(32) + (misc + 12).store(Int32(0)) + (misc + 13).store(Int32(0)) + (misc + 14).store(Int32(0)) + (misc + 15).store(Int32(0)) + (misc + 16).store(Int32(0)) + if cutlass.const_expr(self.pdec): + if k_ == Int32(0): + (misc + 60).store(Int32(0)) + if cutlass.const_expr(self.pdirect): + (misc + 27).store(Int32(0)) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_init(bars + B_QF, 1) + for i in cutlass.range_constexpr(NSLOTS): + if cutlass.const_expr(self.rs24_lsu and 4 <= i < 8): + # g = 1: tile 4's slots also count the control WG's cp.async arrivals + prims.mbarrier_init( + bars + (B_KVF + i), + cutlass.select_( + (d & Int32(1)) != Int32(0), Int32(1 + A.LSU_ARR), Int32(1) + ), + ) + else: + prims.mbarrier_init(bars + (B_KVF + i), 1) + prims.mbarrier_init(bars + (B_KVE + i), 1) + for i in cutlass.range_constexpr(4): + prims.mbarrier_init(bars + (B_SF + i), 1) + prims.mbarrier_init(bars + (B_SE + i), 1) + prims.mbarrier_init(bars + (B_PF + i), 4) + prims.mbarrier_init(bars + B_OF, 1) + prims.mbarrier_init(bars + B_OC, 4) + prims.mbarrier_init(bars + B_FIN, 4) + prims.mbarrier_init(bars + B_SWA, 128) + prims.mbarrier_init(bars + B_SEL, 128) + prims.mbarrier_init(bars + B_T, 1) + prims.mbarrier_init(bars + B_PVL, 1) + prims.mbarrier_init(bars + B_BTC, 1) + prims.mbarrier_init(bars + B_LST, 1) + prims.mbarrier_init(bars + B_EAR, 128) + if cutlass.const_expr(self.rs24): + prims.mbarrier_init(bars + B_RX, 1) + prims.mbarrier_init(bars + B_PR, 1) + if cutlass.const_expr(self.rs24_dry): + prims.mbarrier_init(bars + B_DRY, 1) + prims.mbarrier_arrive_expect_tx( + bars + B_RX, + A.rs24_rx_bytes(self.rs24_f32 or self.rs24_asym, self.team4), + ) + if cutlass.const_expr(self.rs24_dry): + prims.mbarrier_arrive_expect_tx( + bars + B_DRY, + A.rs24_rx_bytes(self.rs24_f32 or self.rs24_asym, self.team4), + ) + prims.fence_mbarrier_init() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ == Int32(0): + prims.barrier_cta_sync(0) + else: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.pdec): + if k_ > Int32(0): + if cutlass.const_expr(self.pdirect): + if tidx == Int32(0): + # this pass started (mbarriers re-initialized): a pre-select may join it + sts_volatile_u32( + Int32( + cute.recast_ptr( + arena + T_OFF_MISC + 27 * 4, dtype=Int32 + ).toint() + ), + Int32(1), + ) + L.bar_arrive(BAR_HAND, 256) + if cutlass.const_expr(self.rs24): + # phase 0 of the cluster barrier: arrive now (the mbarrier inits are fenced above); every thread + # waits only + # before its first remote operation (softmax WG: real merge; control WG: B_PR arrive; others: at + # exit) + if cutlass.const_expr(self.team4): + cute.arch.cluster_arrive() + else: + cute.arch.cluster_arrive_relaxed() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = misc.load() + scale_log2 = softmax_scale * Float32(A.LOG2_E) + tr = None + if cutlass.const_expr(self.stamps): + tr = mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8) + swa_len = (pw + (Int32(7) + k_ * Int32(8))).load() + n = (pw + (Int32(6) + k_ * Int32(8))).load() + if n < Int32(0) or n > Int32(N_MAX): + n = Int32(0) + n_sel = cutlass.min(n, Int32(K_TOP)) + if k_ == Int32(0): + if cutlass.const_expr(self.fblka): + self._block_a_lead( + arena, cta, tidx, ws, n, mBoard, mStamps, gw1, gw2, gw3, mCtl, d, mHist + ) + else: + # One call site for the whole team: the followers run the leader's threshold code once, dry (one + # stale board read, no wait, no publish), at kernel start, so the leader's real pass when the + # board + # completes fetches its code from L2. Followers then read the leader's T line as before. + if cutlass.const_expr(self.tsz01 and self.nteams < self.nrows): + # rows 0-1 come from the stream T server: every team CTA follows its row's T line + self._follow_tline( + arena, cta, d, tidx, ws, mStamps, gw1, gw2, gw3, mCtl + ) + elif cutlass.const_expr(self.t1a and self.nteams < self.nrows): + # team A's lead computes rows 0 and 1 here (row 1's pass runs warm code); team B + # computes nothing; every CTA then follows its row's T line (team A's lead: row 0 again) + npa_ = Int32(1) + if tm != Int32(0): + npa_ = Int32(0) + elif d == Int32(0): + npa_ = Int32(2) + for pa_ in cutlass.range(npa_, unroll=1): + rra_ = row_ + pa_ + wsa_ = ws0 + Int64(rra_) * Int64(rs_["ws"] * 8) + na_ = n + g1a_ = gw1 + g2a_ = gw2 + g3a_ = gw3 + if pa_ != Int32(0): + na_ = Int32(_flat(mDescA, rra_, rs_["desc"])[2]) + if na_ < Int32(0) or na_ > Int32(N_MAX): + na_ = Int32(0) + if tidx == Int32(0): + g1a_, g2a_, g3a_ = self._entry_loads(wsa_) + msa_ = cute.make_tensor( + mStampsA.iterator + + cutlass.select_(pa_ != Int32(0), Int32(2), k_) + * Int32(self.num_sms * NSTAMP), + mStampsA.layout, + ) + self._block_a_lead( + arena, + cta, + tidx, + wsa_, + na_, + _flat(mBoardA, rra_, rs_["board"]), + msa_, + g1a_, + g2a_, + g3a_, + _flat(mCtlA, rra_, rs_["ctl"]), + d, + _flat(mHistA, rra_, rs_["hist"]), + ) + self._follow_tline( + arena, cta, d, tidx, ws, mStamps, gw1, gw2, gw3, mCtl + ) + else: + npa_ = Int32(1) + if cutlass.const_expr(self.awarm): + if d == Int32(0): + npa_ = Int32(2) + if cutlass.const_expr(self.awarm2): + if tm != Int32(0) and d == Int32(0): + npa_ = Int32(2) + if cutlass.const_expr(self.awarm2a): + if d == Int32(0): + npa_ = Int32(2) + for pa_ in cutlass.range(npa_, unroll=1): + # the lead runs this code once dry first (as a follower: no wait, no publish) + de_ = d + if pa_ + Int32(1) < npa_: + de_ = Int32(1) + if cutlass.const_expr(self.awarm2 or self.awarm2a): + # ... and without board loads + dr_ = Int32(0) + if pa_ + Int32(1) < npa_: + dr_ = Int32(1) + self._block_a_lead( + arena, + cta, + tidx, + ws, + n, + mBoard, + mStamps, + gw1, + gw2, + gw3, + mCtl, + de_, + mHist, + dry_=dr_, + ) + else: + self._block_a_lead( + arena, + cta, + tidx, + ws, + n, + mBoard, + mStamps, + gw1, + gw2, + gw3, + mCtl, + de_, + mHist, + ) + if d != Int32(0): + self._follow_tline( + arena, cta, d, tidx, ws, mStamps, gw1, gw2, gw3, mCtl + ) + else: + # this row's T line was computed in the previous pass (misc slots + 13) + if tidx == Int32(0): + (misc + 4).store((misc + 17).load()) + (misc + 5).store((misc + 18).load()) + (misc + 8).store((misc + 21).load()) + (misc + 9).store((misc + 22).load()) + (misc + 10).store((misc + 23).load()) + (misc + 11).store((misc + 24).load()) + (misc + 13).store((misc + 26).load()) + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_SMX, 128) + if tidx == Int32(0): + prims.mbarrier_arrive(bars + B_T) + nx2_ = Int32(-1) + if cutlass.const_expr(self.tsz2): + # row nrows - 2's T line comes from the stream T server + nx2_ = Int32(self.nrows - 2) + if ( + k_ + Int32(1) < npass_ + and row_ + Int32(self.nteams) != Int32(self.nrows - 1) + and row_ + Int32(self.nteams) != nx2_ + and Int32(1 if self.tszall else 0) == Int32(0) + ): + # the next pass's T line now (its board completes while this row is selected); the lead + # also clears the next row's count histogram here, before its T word is released + kn_ = k_ + Int32(1) + rown_ = row_ + Int32(self.nteams) + wsn_ = ws0 + Int64(rown_) * Int64(rs_["ws"] * 8) + mStampsN_ = cute.make_tensor( + mStampsA.iterator + kn_ * Int32(self.num_sms * NSTAMP), mStampsA.layout + ) + mCtlN_ = _flat(mCtlA, rown_, rs_["ctl"]) + nn_ = (pw + (Int32(6) + kn_ * Int32(8))).load() + if nn_ < Int32(0) or nn_ > Int32(N_MAX): + nn_ = Int32(0) + gn1_ = Uint64(0) + gn2_ = Uint64(0) + gn3_ = Uint64(0) + if tidx == Int32(0): + gn1_ = Uint64(Uint32((pw + (Int32(0) + kn_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(1) + kn_ * Int32(8))).load()) + ) << Uint64(32) + gn2_ = Uint64(Uint32((pw + (Int32(2) + kn_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(3) + kn_ * Int32(8))).load()) + ) << Uint64(32) + gn3_ = Uint64(Uint32((pw + (Int32(4) + kn_ * Int32(8))).load())) | Uint64( + Uint32((pw + (Int32(5) + kn_ * Int32(8))).load()) + ) << Uint64(32) + (misc + 26).store(Int32(0)) + npb_ = Int32(1) + if cutlass.const_expr(self.awarm or self.awarm3): + if d == Int32(0): + npb_ = Int32(2) + for pb_ in cutlass.range(npb_, unroll=1): + # dry first on the lead (as a follower: no wait, no publish) + db_ = d + if pb_ + Int32(1) < npb_: + db_ = Int32(1) + if cutlass.const_expr(self.awarm3): + # ... and without board loads + dr_ = Int32(0) + if pb_ + Int32(1) < npb_: + dr_ = Int32(1) + self._block_a_lead( + arena, + cta, + tidx, + wsn_, + nn_, + _flat(mBoardA, rown_, rs_["board"]), + mStampsN_, + gn1_, + gn2_, + gn3_, + mCtlN_, + db_, + _flat(mHistA, rown_, rs_["hist"]), + mo=13, + dry_=dr_, + ) + else: + self._block_a_lead( + arena, + cta, + tidx, + wsn_, + nn_, + _flat(mBoardA, rown_, rs_["board"]), + mStampsN_, + gn1_, + gn2_, + gn3_, + mCtlN_, + db_, + _flat(mHistA, rown_, rs_["hist"]), + mo=13, + ) + if d != Int32(0): + self._follow_tline( + arena, cta, d, tidx, wsn_, mStampsN_, gn1_, gn2_, gn3_, mCtlN_, mo=13 + ) + if cutlass.const_expr(self.gjoin): + if cutlass.const_expr(self.rs24): + zsm = Int32( + cute.recast_ptr(arena + T_OFF_MISC + 61 * 4, dtype=Int32).toint() + ) + A.role_softmax_24( + tmem, + bars + B_SF, + bars + B_PF, + scale_log2, + swa_len, + n_sel, + d, + bars + B_OF, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + Int32(_ptr(arena, T_OFF_LIST, Int32).toint()), + Int32(_ptr(arena, T_OFF_STAT, Int32).toint()), + Int32((bars + B_PVL).toint()), + Int32((bars + B_RX).toint()), + Int32((bars + B_PR).toint()), + Int32((bars + B_DRY).toint()), + zsm, + tr, + full_tiles=self.full_attention_tiles, + dry_merge=self.rs24_dry, + f32x=self.rs24_f32, + asym=self.rs24_asym, + wide_v=self.team4, + ) + else: + A.role_softmax_team( + tmem, + bars + B_SF, + bars + B_PF, + s_stat, + s_fin, + bars + B_FIN, + scale_log2, + swa_len, + n_sel, + Int32(0), + Int32(NTILES), + Float32(A.NEG_FLT_MAX), + Float32(0.0), + True, + tr, + bars + B_OF, + d, + full_tiles=self.full_attention_tiles, + ) + if cutlass.const_expr(self.late_done == 2): + if d == Int32(0): + if tidx == Int32(0): + mi_ = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + if mi_[12] == Int32(P_T1) and mi_[14] != Int32(0): + gq_ = Uint64(Uint32(mi_[5])) << Uint64(32) | Uint64( + Uint32(mi_[4]) + ) + self._publish_dir( + ws, + gq_, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + else: + A.role_softmax_team( + tmem, + bars + B_SF, + bars + B_PF, + s_stat, + s_fin, + bars + B_FIN, + scale_log2, + swa_len, + n_sel, + Int32(0), + Int32(NTILES), + Float32(A.NEG_FLT_MAX), + Float32(0.0), + True, + tr, + full_tiles=self.full_attention_tiles, + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ + Int32(1) < npass_: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + else: + prims.barrier_cta_sync(0) + elif warp < Int32(8): + if cutlass.const_expr(self.ctl_regs): + prims.setmaxregister(A.REG_CTL, prims.SetMaxRegisterAction.INCREASE) + for k_ in cutlass.range(npass_, unroll=1): + row_ = tm + k_ * Int32(self.nteams) + mStamps = cute.make_tensor( + mStampsA.iterator + k_ * Int32(self.num_sms * NSTAMP), mStampsA.layout + ) + ws = ws0 + Int64(row_) * Int64(rs_["ws"] * 8) + mOut = _row2(mOutA, row_) + _mCtx = _row1(mCtxA, row_) + mSwaLocal = _row2(mSwaLocalA, row_) + mBtSwa = _row2(mBtSwaA, row_) + mBtC = _row2(mBtCA, row_) + _mSwaLens = _row1(mSwaLensA, row_) + mTopk = _row2(mTopkA, row_) + mGidx = _row2(mGidxA, row_) + mHist = _flat(mHistA, row_, rs_["hist"]) + mBoard = _flat(mBoardA, row_, rs_["board"]) + mRegion = _flat(mRegionA, row_, rs_["region"]) + mCtl = _flat(mCtlA, row_, rs_["ctl"]) + _mDesc = _flat(mDescA, row_, rs_["desc"]) + qrow = row_ + prims.fence_mbarrier_init() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ == Int32(0): + prims.barrier_cta_sync(0) + else: + # joins after the softmax WG's start barrier (mbarriers re-initialized) + if cutlass.const_expr(self.pdirect): + # a direct pre-select joined this pass already (misc[58] = 2) + if (misc + 58).load() != Int32(2): + L.bar(BAR_HAND, 256) + else: + L.bar(BAR_HAND, 256) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + # phase 0 of the cluster barrier: arrive now (the mbarrier inits are fenced above); every thread + # waits only + # before its first remote operation (softmax WG: real merge; control WG: B_PR arrive; others: at + # exit) + if cutlass.const_expr(self.team4): + cute.arch.cluster_arrive() + else: + cute.arch.cluster_arrive_relaxed() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = misc.load() + scale_log2 = softmax_scale * Float32(A.LOG2_E) + tr = None + if cutlass.const_expr(self.stamps): + tr = mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8) + swa_len = (pw + (Int32(7) + k_ * Int32(8))).load() + n = (pw + (Int32(6) + k_ * Int32(8))).load() + if n < Int32(0) or n > Int32(N_MAX): + n = Int32(0) + n_sel = cutlass.min(n, Int32(K_TOP)) + if cutlass.const_expr(self.rs24): + # job 0 = this pass's row (skipped when pre-selected), job 1 = the next pass's row (pre-select) + pok_ = Int32(0) + njb_ = Int32(1) + if cutlass.const_expr(self.presel): + if k_ > Int32(0): + pok_ = (misc + 58).load() + if k_ + Int32(1) < npass_: + njb_ = Int32(2) + for jb_ in cutlass.range(njb_, unroll=1): + if jb_ != Int32(0) or pok_ == Int32(0): + kj_ = k_ + jb_ + rowj_ = row_ + jb_ * Int32(self.nteams) + nj_ = (pw + (Int32(6) + kj_ * Int32(8))).load() + if nj_ < Int32(0) or nj_ > Int32(N_MAX): + nj_ = Int32(0) + gj1_ = Uint64( + Uint32((pw + (Int32(0) + kj_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(1) + kj_ * Int32(8))).load())) << Uint64( + 32 + ) + gj2_ = Uint64( + Uint32((pw + (Int32(2) + kj_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(3) + kj_ * Int32(8))).load())) << Uint64( + 32 + ) + gj3_ = Uint64( + Uint32((pw + (Int32(4) + kj_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(5) + kj_ * Int32(8))).load())) << Uint64( + 32 + ) + mStampsJ_ = cute.make_tensor( + mStampsA.iterator + kj_ * Int32(self.num_sms * NSTAMP), + mStampsA.layout, + ) + s_idxj_ = _ptr( + arena, + cutlass.select_( + jb_ == Int32(0), Int32(T_OFF_IDX), Int32(SIDX2_OFF) + ), + Int32, + ) + p0j_ = Int32(1) + if k_ == Int32(0) and jb_ == Int32(0): + p0j_ = Int32(0 if self.prewarm else 1) + if cutlass.const_expr(self.warm1): + if tm != Int32(0): + p0j_ = Int32(1) + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws0 + Int64(rowj_) * Int64(rs_["ws"] * 8), + nj_, + s_idxj_, + bars, + _row2(mSwaLocalA, rowj_), + _row2(mBtSwaA, rowj_), + _row2(mBtCA, rowj_), + _row2(mTopkA, rowj_), + _row2(mGidxA, rowj_), + _flat(mRegionA, rowj_, rs_["region"]), + _flat(mHistA, rowj_, rs_["hist"]), + mStampsJ_, + _flat(mCtlA, rowj_, rs_["ctl"]), + None, + None, + p0=p0j_, + pre_=jb_, + gwn=(gj1_, gj2_, gj3_), + ) + if jb_ == Int32(0): + if pok_ == Int32(1): + self._shipped_sel( + arena, + cta, + d, + tidx - Int32(128), + ws, + s_idx, + bars, + mStamps, + n, + mBtC, + ) + if cutlass.const_expr(self.rs24_lsu): + if (d & Int32(1)) != Int32(0): + # tile 4's rows were published by this warpgroup before its B_SEL arrive (named + # barrier); issue + # before the cluster wait / B_PR arrive (the partner pushes into slot 8 only at its + # merge) + A.lsu_tile4( + tidx - Int32(128), + d, + self.rs24_lsu, + Int32(s_kv.toint()), + Int32(s_idx.toint()), + Int32((bars + B_KVF).toint()), + bars + B_KVE, + mCPool.iterator.toint(), + tr, + wide_v=self.team4, + ) + if cutlass.const_expr(self.stamps): + A._stamp( + mStamps.iterator.toint() + + Int64(cta) * Int64(NSTAMP * 8), + Int32(52), + tidx == Int32(128), + ) + cute.arch.cluster_wait() + if tidx == Int32(160): + # (not ctid 0: on team CTA 0 it may still be in the late-done follower wait) + L.mbar_arrive_remote( + L.mapa_u32( + Int32((bars + B_PR).toint()), L.cluster_ctarank() ^ Int32(1) + ) + ) + elif cutlass.const_expr(self.gjoin): + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + ( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_SEL, + Int32(A.NGW) + warp - Int32(4), + d, + NTILES, + NSLOTS, + None, + Int32(2), + A.NGW + 4, + bars + B_EAR, + 2, + ), + ( + tmem, + bars + B_PF, + bars + B_OF, + bars + B_OC, + s_stat, + s_fin, + bars + B_FIN, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + scale_log2, + d, + Int32(s_kv.toint()), + NTILES, + BAR_EPI, + tr, + bars + B_PVL, + ), + ) + else: + self._control_s1d( + arena, + cta, + d, + tidx - Int32(128), + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + ) + A.role_corr_epi_team( + tmem, + bars + B_PF, + bars + B_OF, + bars + B_OC, + s_stat, + s_fin, + bars + B_FIN, + mSinks.iterator.raw_ptr(), + mOut.iterator.toint(), + scale_log2, + d, + Int32(s_kv.toint()), + NTILES, + BAR_EPI, + tr, + ) + # B_BTC is re-initialized next pass: its bulk copy must have landed (abort paths skip the wait) + if tidx == Int32(128): + A._wait(bars + B_BTC, Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ + Int32(1) == npass_: + prims.barrier_cta_sync(0) + else: + prims.barrier_cta_sync(0) + elif warp == Int32(A.W_MMA): + prims.setmaxregister(A.REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + for k_ in cutlass.range(npass_, unroll=1): + row_ = tm + k_ * Int32(self.nteams) + mStamps = cute.make_tensor( + mStampsA.iterator + k_ * Int32(self.num_sms * NSTAMP), mStampsA.layout + ) + ws = ws0 + Int64(row_) * Int64(rs_["ws"] * 8) + mOut = _row2(mOutA, row_) + _mCtx = _row1(mCtxA, row_) + mSwaLocal = _row2(mSwaLocalA, row_) + mBtSwa = _row2(mBtSwaA, row_) + mBtC = _row2(mBtCA, row_) + _mSwaLens = _row1(mSwaLensA, row_) + mTopk = _row2(mTopkA, row_) + mGidx = _row2(mGidxA, row_) + mHist = _flat(mHistA, row_, rs_["hist"]) + mBoard = _flat(mBoardA, row_, rs_["board"]) + mRegion = _flat(mRegionA, row_, rs_["region"]) + mCtl = _flat(mCtlA, row_, rs_["ctl"]) + _mDesc = _flat(mDescA, row_, rs_["desc"]) + qrow = row_ + prims.fence_mbarrier_init() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ == Int32(0): + prims.barrier_cta_sync(0) + else: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + # phase 0 of the cluster barrier: arrive now (the mbarrier inits are fenced above); every thread + # waits only + # before its first remote operation (softmax WG: real merge; control WG: B_PR arrive; others: at + # exit) + if cutlass.const_expr(self.team4): + cute.arch.cluster_arrive() + else: + cute.arch.cluster_arrive_relaxed() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = misc.load() + scale_log2 = softmax_scale * Float32(A.LOG2_E) + tr = None + if cutlass.const_expr(self.stamps): + tr = mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8) + swa_len = (pw + (Int32(7) + k_ * Int32(8))).load() + n = (pw + (Int32(6) + k_ * Int32(8))).load() + if n < Int32(0) or n > Int32(N_MAX): + n = Int32(0) + n_sel = cutlass.min(n, Int32(K_TOP)) + if cutlass.const_expr(self.gjoin): + if cutlass.const_expr(self.rs24): + A.role_mma_24( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_PF, + bars + B_OF, + d, + bars + B_PVL, + tr, + pfence=self.rs24_lsu > 0, + wide_v=self.team4, + ) + else: + A.role_mma_ordered( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_SE, + bars + B_PF, + bars + B_OF, + d, + NTILES, + NSLOTS, + bars + B_PVL, + tr, + bars + B_EAR if self.mma_block else None, + self.mma_idle_ns, + ) + else: + A.role_mma_team( + tmem, + s_q, + s_kv, + s_ext, + bars + B_QF, + bars + B_KVF, + bars + B_KVE, + bars + B_SF, + bars + B_SE, + bars + B_PF, + bars + B_OC, + bars + B_OF, + d, + NTILES, + NSLOTS, + tr, + self.qk_ahead, + ) + if k_ + Int32(1) < npass_: + nx2m_ = Int32(-1) + if cutlass.const_expr(self.tsz2): + nx2m_ = Int32(self.nrows - 2) + if ( + row_ + Int32(self.nteams) == Int32(self.nrows - 1) + or row_ + Int32(self.nteams) == nx2m_ + or Int32(1 if self.tszall else 0) != Int32(0) + ): + # the last row's T line (stream T server), read now by lane 0 into misc + 13 + if cute.arch.lane_idx() == Int32(0): + kn_ = k_ + Int32(1) + rown_ = row_ + Int32(self.nteams) + mStampsN_ = cute.make_tensor( + mStampsA.iterator + kn_ * Int32(self.num_sms * NSTAMP), + mStampsA.layout, + ) + gn1_ = Uint64( + Uint32((pw + (Int32(0) + kn_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(1) + kn_ * Int32(8))).load())) << Uint64( + 32 + ) + gn2_ = Uint64( + Uint32((pw + (Int32(2) + kn_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(3) + kn_ * Int32(8))).load())) << Uint64( + 32 + ) + gn3_ = Uint64( + Uint32((pw + (Int32(4) + kn_ * Int32(8))).load()) + ) | Uint64(Uint32((pw + (Int32(5) + kn_ * Int32(8))).load())) << Uint64( + 32 + ) + (misc + 26).store(Int32(0)) + self._follow_tline1( + arena, + cta, + d, + Int32(0), + ws0 + Int64(rown_) * Int64(rs_["ws"] * 8), + mStampsN_, + gn1_, + gn2_, + gn3_, + _flat(mCtlA, rown_, rs_["ctl"]), + mo=13, + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ + Int32(1) < npass_: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + if k_ + Int32(1) < npass_: + # this warp never waited on the cluster barrier in the pass: wait before the next arrive + cute.arch.cluster_wait() + else: + prims.setmaxregister(A.REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + for k_ in cutlass.range(npass_, unroll=1): + row_ = tm + k_ * Int32(self.nteams) + mStamps = cute.make_tensor( + mStampsA.iterator + k_ * Int32(self.num_sms * NSTAMP), mStampsA.layout + ) + ws = ws0 + Int64(row_) * Int64(rs_["ws"] * 8) + mOut = _row2(mOutA, row_) + _mCtx = _row1(mCtxA, row_) + mSwaLocal = _row2(mSwaLocalA, row_) + mBtSwa = _row2(mBtSwaA, row_) + mBtC = _row2(mBtCA, row_) + _mSwaLens = _row1(mSwaLensA, row_) + mTopk = _row2(mTopkA, row_) + mGidx = _row2(mGidxA, row_) + mHist = _flat(mHistA, row_, rs_["hist"]) + mBoard = _flat(mBoardA, row_, rs_["board"]) + mRegion = _flat(mRegionA, row_, rs_["region"]) + mCtl = _flat(mCtlA, row_, rs_["ctl"]) + _mDesc = _flat(mDescA, row_, rs_["desc"]) + qrow = row_ + prims.fence_mbarrier_init() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ == Int32(0): + prims.barrier_cta_sync(0) + else: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + # phase 0 of the cluster barrier: arrive now (the mbarrier inits are fenced above); every thread + # waits only + # before its first remote operation (softmax WG: real merge; control WG: B_PR arrive; others: at + # exit) + if cutlass.const_expr(self.team4): + cute.arch.cluster_arrive() + else: + cute.arch.cluster_arrive_relaxed() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = misc.load() + scale_log2 = softmax_scale * Float32(A.LOG2_E) + tr = None + if cutlass.const_expr(self.stamps): + tr = mStamps.iterator.toint() + Int64(cta) * Int64(NSTAMP * 8) + swa_len = (pw + (Int32(7) + k_ * Int32(8))).load() + n = (pw + (Int32(6) + k_ * Int32(8))).load() + if n < Int32(0) or n > Int32(N_MAX): + n = Int32(0) + n_sel = cutlass.min(n, Int32(K_TOP)) + if warp == Int32(A.W_G0): + A.role_q_load(tma_q, s_q, bars + B_QF, qrow) + if warp == Int32(A.W_G0 + 1): + if prims.elect_sync(): + btc_cols = cute.size(mBtC, mode=[1]) + npg = cutlass.min( + (n + Int32(31)) // Int32(32), cutlass.min(btc_cols, Int32(BTC_CAP)) + ) + nbt = npg * Int32(4) // Int32(16) * Int32(16) + if nbt > Int32(0): + L.mbar_arrive_expect_tx(Int32((bars + B_BTC).toint()), nbt) + L.bulk_g2s( + Int32(cute.recast_ptr(arena + T_OFF_BTC, dtype=Int32).toint()), + mBtC.iterator.toint(), + nbt, + Int32((bars + B_BTC).toint()), + ) + else: + prims.mbarrier_arrive(bars + B_BTC) + pfb_ = Int32(1) + if cutlass.const_expr(self.presel): + if k_ > Int32(0): + pfb_ = Int32(0) + if warp == Int32(A.W_G0 + 2) and pfb_ != Int32(0): + rgb = mRegion.iterator.toint() + for q in cutlass.range_constexpr(NB_INITIAL // 32): + bha = self._bucket_addr(rgb, cute.arch.lane_idx() + Int32(q * 32), Int32(0)) + for h_ in cutlass.range_constexpr(4): + L.prefetch_l2(bha + Int64(128 * h_)) + if cutlass.const_expr(self.swag): + if warp >= Int32(A.W_G0 + 3): + gt_ = (warp - Int32(A.W_G0 + 3)) * Int32(32) + cute.arch.lane_idx() + mbs_ = cute.size(mBtSwa, mode=[1]) + pks_ = Int32(0) + if cutlass.const_expr(self.presel): + if k_ > Int32(0): + if cutlass.const_expr(self.pdec): + pks_ = lds_volatile_u32( + Int32( + cute.recast_ptr( + arena + T_OFF_MISC + 60 * 4, dtype=Int32 + ).toint() + ) + ) + else: + pks_ = (misc + 58).load() + rsw_ = Int32(0) + if pks_ != Int32(0): + # SWA rows prepared by the previous pass's pre-select + if cutlass.const_expr(self.pdec): + fence_acq_rel_cta() + rsw_ = (_ptr(arena, SIDX2_OFF, Int32) + gt_).load() + else: + loc_ = mSwaLocal[0, gt_] + rsw_ = L.l2g_swa_local(loc_, Int32(0), mBtSwa, mbs_, Int32(0)) + (s_idx + gt_).store(rsw_) + # each writer releases its own index store to the gather warps + prims.mbarrier_arrive(bars + B_SWA) + if cutlass.const_expr(self.rs24): + A.role_gather_24( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_EAR, + bars + B_SEL, + warp - Int32(A.W_G0), + d, + NTILES, + tr, + (misc + 16) if self.rs24_t4split else None, + lsu_g=self.rs24_lsu, + wide_v=self.team4, + ) + else: + A.role_gather_team( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + bars + B_KVF, + bars + B_KVE, + bars + B_SWA, + bars + B_SEL, + warp - Int32(A.W_G0), + d, + NTILES, + NSLOTS, + tr, + Int32(0), + A.NGW + 4 if self.gjoin else A.NGW, + bars + B_EAR if self.gjoin else None, + 2 if self.gjoin else 1, + ) + if cutlass.const_expr(self.hook): + if warp == Int32(A.W_G0 + A.NGW - 1): + if cute.arch.lane_idx() == Int32(0): + self._stamp(mStamps, cta, 106) + self._team_exit(arena, d, ws) + self._stamp(mStamps, cta, 107) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + if cutlass.const_expr(self.pdec): + if k_ + Int32(1) < npass_: + L.bar(BAR_PASS, 384) + else: + prims.barrier_cta_sync(0) + else: + prims.barrier_cta_sync(0) + if cutlass.const_expr(self.rs24): + if k_ + Int32(1) < npass_: + # this warp never waited on the cluster barrier in the pass: wait before the next arrive + cute.arch.cluster_wait() + if warp == Int32(A.W_MMA): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + prims.tcgen05_dealloc( + prims.make_tmem_ptr(misc.load(), Float32), A.TMEM_COLS, group=prims.CTAGroup.CTA_1 + ) + if cutlass.const_expr(self.stamps): + if tidx == Int32(0): + (mStampsA.iterator + cta * NSTAMP + ST_M_EXIT).store(Int64(L.gtimer())) + + @cute.jit + def _team_exit(self, arena, d, ws): + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + gen = Uint64(Uint32(misc[5])) << Uint64(32) | Uint64(Uint32(misc[4])) + t64 = gen + Uint64(1) + ab = misc[13] + if d == Int32(0): + tdl = self._deadline() + st_ = Int32(0) + while st_ == Int32(0): + ready = self._followers_ready(ws, t64) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if ready != Int32(0): + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + elif st_ == Int32(2): + self._flag(ws, gen, Int32(E_ABORTED)) + if st_ != Int32(1): + ab = Int32(1) + if cutlass.const_expr(self.late_done == 1): + if ab == Int32(0): + if misc[12] == Int32(P_T1): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + nxt = gen + Uint64(1) + if ab != Int32(0): + nxt = gen + Uint64(2) + st_rlx_u64(self._w(ws, W_DONE), nxt) + st_rlx_u64(self._w(ws, W_DONE2), nxt) + else: + t40 = self._tag40(gen) + tdl = self._deadline() + st_ = Int32(0) + h = Uint64(0) + while st_ == Int32(0): + h = L.ld_relaxed_u64(self._w(ws, W_DIR)) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if h >> Uint64(24) == t40 and Int32(Uint32(h & Uint64(15))) == Int32(K_DONE): + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + elif st_ == Int32(2): + self._flag(ws, gen, Int32(E_ABORTED)) + if st_ == Int32(1): + if Int32(Uint32(h >> Uint64(4) & Uint64(15))) != misc[12]: + self._flag(ws, gen, Int32(E_MISMATCH)) + + @cute.jit + def _scan4(self, v0, v1, v2, v3, ctid, arena): + NT: cutlass.Constexpr[int] = 128 + s_wc = _sm_tensor(arena, T_OFF_WC, Int32, 64) + lane = ctid % Int32(32) + wid = ctid // Int32(32) + i0 = L.warp_incl_scan_add(v0, lane) + i1 = L.warp_incl_scan_add(v1, lane) + i2 = L.warp_incl_scan_add(v2, lane) + i3 = L.warp_incl_scan_add(v3, lane) + if lane == Int32(31): + s_wc[wid * Int32(4)] = i0 + s_wc[wid * Int32(4) + Int32(1)] = i1 + s_wc[wid * Int32(4) + Int32(2)] = i2 + s_wc[wid * Int32(4) + Int32(3)] = i3 + L.bar(BAR_CTL, NT) + b0 = Int32(0) + b1 = Int32(0) + b2 = Int32(0) + b3 = Int32(0) + t0 = Int32(0) + t1 = Int32(0) + t2 = Int32(0) + t3 = Int32(0) + for w_ in cutlass.range_constexpr(NT // 32): + c0 = s_wc[4 * w_] + c1 = s_wc[4 * w_ + 1] + c2 = s_wc[4 * w_ + 2] + c3 = s_wc[4 * w_ + 3] + if Int32(w_) < wid: + b0 = b0 + c0 + b1 = b1 + c1 + b2 = b2 + c2 + b3 = b3 + c3 + t0 = t0 + c0 + t1 = t1 + c1 + t2 = t2 + c2 + t3 = t3 + c3 + L.bar(BAR_CTL, NT) + return (b0 + i0 - v0, b1 + i1 - v1, b2 + i2 - v2, b3 + i3 - v3, t0, t1, t2, t3) + + @cute.jit + def _band_range(self, T, HIC, SMAX): + lo = T + hi = HIC + if not hi > lo: + hi = SMAX + if not hi > lo: + hi = lo + Float32(1.0) + return (lo, hi) + + @cute.jit + def _wg_any(self, v, ctid, s_red, bar_id: cutlass.Constexpr[int]): + lane = ctid % Int32(32) + wid = ctid // Int32(32) + w = Int32(0) + bm = Int32(cute.arch.vote_ballot_sync(v != Int32(0))) + if bm != Int32(0): + w = Int32(1) + if lane == Int32(0): + s_red[Int32(40) + wid] = Uint32(w) + L.bar(bar_id, 128) + r = Int32(s_red[40] | s_red[41] | s_red[42] | s_red[43]) + L.bar(bar_id, 128) + return r + + @cute.jit + def _warm_abort(self, real, status, ctid, bars, misc): + # the warm-up pass runs to completion: the producers' counts arrive well after T is known, so finishing + # the synthetic emission / rank / epilogue code first keeps all of it cache-resident for the real pass + return status + + @cute.jit + def _follow_tline( + self, arena, cta, d, ctid, ws, mStamps, gw1, gw2, gw3, mCtl, mo: cutlass.Constexpr[int] = 0 + ): + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + if ctid == Int32(0): + gen = self._gen_from(gw1, gw2, gw3) + misc[4 + mo] = Int32(Uint32(gen & Uint64(4294967295))) + misc[5 + mo] = Int32(Uint32(gen >> Uint64(32))) + tg = self._tag32(gen) + t64 = gen + Uint64(1) + skipf = Int32(0) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(4) and d == Int32(2): + skipf = Int32(1) + if skipf == Int32(0): + st_rlx_u64(self._w(ws, W_FOL) + Int64(d) * Int64(8), t64) + tdl = self._deadline() + st_ = Int32(0) + l0 = Uint64(0) + l1 = Uint64(0) + l2 = Uint64(0) + l3 = Uint64(0) + while st_ == Int32(0): + l0 = L.ld_relaxed_u64(self._w(ws, W_TLINE)) + l1 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + l2 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 2)) + l3 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if ( + Uint32(l0 >> Uint64(32)) == tg + and Uint32(l1 >> Uint64(32)) == tg + and (Uint32(l2 >> Uint64(32)) == tg) + and (Uint32(l3 >> Uint64(32)) == tg) + ): + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + if st_ == Int32(1): + misc[8 + mo] = Int32(Uint32(l0 & Uint64(4294967295))) + misc[9 + mo] = Int32(Uint32(l1 & Uint64(4294967295))) + misc[10 + mo] = Int32(Uint32(l2 & Uint64(4294967295))) + misc[11 + mo] = Int32(Uint32(l3 & Uint64(4294967295))) + else: + misc[8 + mo] = Int32(2139095040) + misc[9 + mo] = Int32(-8388608) + misc[10 + mo] = Int32(-8388608) + misc[11 + mo] = Int32(-8388608) + misc[13 + mo] = Int32(1) + self._stamp(mStamps, cta, ST_M_T) + L.bar(BAR_SMX, 128) + + @cute.jit + def _follow_tline1( + self, arena, cta, d, ctid, ws, mStamps, gw1, gw2, gw3, mCtl, mo: cutlass.Constexpr[int] = 0 + ): + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + if True: + gen = self._gen_from(gw1, gw2, gw3) + misc[4 + mo] = Int32(Uint32(gen & Uint64(4294967295))) + misc[5 + mo] = Int32(Uint32(gen >> Uint64(32))) + tg = self._tag32(gen) + t64 = gen + Uint64(1) + skipf = Int32(0) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(4) and d == Int32(2): + skipf = Int32(1) + if skipf == Int32(0): + st_rlx_u64(self._w(ws, W_FOL) + Int64(d) * Int64(8), t64) + tdl = self._deadline() + st_ = Int32(0) + l0 = Uint64(0) + l1 = Uint64(0) + l2 = Uint64(0) + l3 = Uint64(0) + while st_ == Int32(0): + l0 = L.ld_relaxed_u64(self._w(ws, W_TLINE)) + l1 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 1)) + l2 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 2)) + l3 = L.ld_relaxed_u64(self._w(ws, W_TLINE + 3)) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if ( + Uint32(l0 >> Uint64(32)) == tg + and Uint32(l1 >> Uint64(32)) == tg + and (Uint32(l2 >> Uint64(32)) == tg) + and (Uint32(l3 >> Uint64(32)) == tg) + ): + st_ = Int32(1) + elif av == t64: + st_ = Int32(2) + elif Int64(L.gtimer()) > tdl: + st_ = Int32(3) + if st_ == Int32(3): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + if st_ == Int32(1): + misc[8 + mo] = Int32(Uint32(l0 & Uint64(4294967295))) + misc[9 + mo] = Int32(Uint32(l1 & Uint64(4294967295))) + misc[10 + mo] = Int32(Uint32(l2 & Uint64(4294967295))) + misc[11 + mo] = Int32(Uint32(l3 & Uint64(4294967295))) + else: + misc[8 + mo] = Int32(2139095040) + misc[9 + mo] = Int32(-8388608) + misc[10 + mo] = Int32(-8388608) + misc[11 + mo] = Int32(-8388608) + misc[13 + mo] = Int32(1) + self._stamp(mStamps, cta, ST_M_T) + + @cute.jit + def _block_a_lead( + self, + arena, + cta, + ctid, + ws, + n, + mBoard, + mStamps, + gw1, + gw2, + gw3, + mCtl, + d, + mHist, + mo: cutlass.Constexpr[int] = 0, + fa: cutlass.Constexpr[int] = T_OFF_FA, + mi: cutlass.Constexpr[int] = T_OFF_MISC, + dry_=None, + ): + NT: cutlass.Constexpr[int] = 128 + SMP, SS2, TGT, TGT2 = L.gvr_ladder( + n, + Int32(K_TOP), + Int32(PLAN["aim_base"]), + Int32(PLAN["sfac"]), + Int32(PLAN["amin"]), + Int32(PLAN["sd_en"]), + PLAN["r_const"], + PLAN["scap"], + ) + s_keys = _sm_tensor(arena, fa + (T_OFF_F_HIST - T_OFF_FA), Uint32, 256) + s_mins = _sm_tensor(arena, fa + (T_OFF_F_MB - T_OFF_FA), Uint32, NT) + s_res = _sm_tensor(arena, fa + (T_OFF_F_RES - T_OFF_FA), Uint32, 16) + s_red = _sm_tensor(arena, fa + (T_OFF_F_RED - T_OFF_FA), Uint32, 64) + misc = _sm_tensor(arena, mi, Int32, 64) + lane = ctid % Int32(32) + wid = ctid // Int32(32) + bbase = mBoard.iterator.toint() + if d == Int32(0): + # DRS starts at histogram row 1, leaving row 0 for these counts. + for j in cutlass.range_constexpr(NB_INITIAL // NT): + L.st_g_u32( + mHist.iterator.toint() + Int64(ctid + Int32(j * NT)) * Int64(4), Uint32(0) + ) + if cutlass.const_expr(not self.lfence): + L.fence_acq_rel_gpu() + if cutlass.const_expr(self.lbin): + # the 256-bin histogram of the rank selection (the key scratch of the old path), ready after the barrier + s_keys[ctid] = Uint32(0) + s_keys[ctid + Int32(NT)] = Uint32(0) + if ctid == Int32(0): + self._stamp(mStamps, cta, 68) + gg_ = self._gen_from(gw1, gw2, gw3) + misc[4 + mo] = Int32(Uint32(gg_ & Uint64(4294967295))) + misc[5 + mo] = Int32(Uint32(gg_ >> Uint64(32))) + L.bar(BAR_SMX, NT) + if d == Int32(0): + if ctid == Int32(0): + # Release of the histogram clear (cumulative over the clearing threads, ordered by the barrier + # above): every later store of this thread, the T word included, is ordered after it. + if cutlass.const_expr(not self.lfence): + L.fence_acq_rel_gpu() + gen = Uint64(Uint32(misc[5 + mo])) << Uint64(32) | Uint64(Uint32(misc[4 + mo])) + tg = self._tag32(gen) + t64 = gen + Uint64(1) + if cutlass.const_expr(self.fblka): + if d != Int32(0): + if ctid == Int32(0): + st_rlx_u64(self._w(ws, W_FOL) + Int64(d) * Int64(8), t64) + self._skew(gen, cta * Int32(4) + Int32(2), ctid) + nq = SMP * Int32(4) + nmine = Int32(0) + if ctid < nq: + nmine = cutlass.min((nq - ctid + Int32(NT - 1)) // Int32(NT), Int32(RMAX)) + # Keep the tagged board's values in registers until the local top-two + # reduction. No raw-sample shared staging or histogram rescan remains. + samples = cute.make_rmem_tensor((2 * RMAX,), Float32) + okp = Int32(0) + ab = Int32(0) + if nmine == Int32(0): + okp = Int32(1) + if cutlass.const_expr(dry_ is not None): + # dry pass without board loads (warms this code in the SM's instruction cache) + if dry_ != Int32(0): + okp = Int32(1) + if cutlass.const_expr(self.fwarm): + if d != Int32(0): + okp = Int32(1) + tdl = self._deadline() + if cutlass.const_expr(self.lpoll): + # re-load only the pairs not yet seen valid (bit r of vm_ set while pair r is pending) + vm_ = Int32(0) + if nmine > Int32(0): + vm_ = (Int32(1) << nmine) - Int32(1) + first_ = Int32(1) + while okp == Int32(0): + wsr = [] + for r_ in cutlass.range_constexpr(RMAX): + q2 = ctid + cutlass.min(Int32(r_), nmine - Int32(1)) * Int32(NT) + wsr.append( + ld_relaxed_v2u64_p( + bbase + Int64(q2) * Int64(16), (vm_ >> Int32(r_)) & Int32(1) + ) + ) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if cutlass.const_expr(self.lfence): + if first_ != Int32(0): + if d == Int32(0): + if ctid == Int32(0): + # cumulative release of the histogram clear (ordered after the barrier above) while + # the first poll loads are in flight + L.fence_acq_rel_gpu() + first_ = Int32(0) + for r_ in cutlass.range_constexpr(RMAX): + if (vm_ >> Int32(r_)) & Int32(1) != Int32(0): + if ( + Uint32(wsr[r_][0] >> Uint64(32)) == tg + and Uint32(wsr[r_][1] >> Uint64(32)) == tg + ): + samples[2 * r_] = L.f32_of_u32(Uint32(wsr[r_][0])) + samples[2 * r_ + 1] = L.f32_of_u32(Uint32(wsr[r_][1])) + vm_ = vm_ ^ Int32(1 << r_) + okp = Int32(0) + if vm_ == Int32(0): + okp = Int32(1) + if d != Int32(0): + okp = Int32(1) + if okp == Int32(0): + if av == t64: + ab = Int32(1) + okp = Int32(1) + elif Int64(L.gtimer()) > tdl: + ab = Int32(2) + okp = Int32(1) + if cutlass.const_expr(self.lfence): + if first_ != Int32(0): + # no poll iteration ran (a row without samples): the release fence of the clear is still due + if d == Int32(0): + if ctid == Int32(0): + L.fence_acq_rel_gpu() + else: + while okp == Int32(0): + wsr = [] + for r_ in cutlass.range_constexpr(RMAX): + q2 = ctid + cutlass.min(Int32(r_), nmine - Int32(1)) * Int32(NT) + wsr.append(ld_relaxed_v2u64(bbase + Int64(q2) * Int64(16))) + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + okp = Int32(1) + for r_ in cutlass.range_constexpr(RMAX): + if Int32(r_) < nmine: + samples[2 * r_] = L.f32_of_u32(Uint32(wsr[r_][0])) + samples[2 * r_ + 1] = L.f32_of_u32(Uint32(wsr[r_][1])) + if ( + Uint32(wsr[r_][0] >> Uint64(32)) != tg + or Uint32(wsr[r_][1] >> Uint64(32)) != tg + ): + okp = Int32(0) + if d != Int32(0): + okp = Int32(1) + if okp == Int32(0): + if av == t64: + ab = Int32(1) + okp = Int32(1) + elif Int64(L.gtimer()) > tdl: + ab = Int32(2) + okp = Int32(1) + if ab == Int32(2): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + smn = Float32(float("inf")) + smx = Float32(float("-inf")) + smx2 = Float32(float("-inf")) + # Consume a thread's registers only after its tagged snapshot passed. + if ab == Int32(0): + for r_ in cutlass.range_constexpr(RMAX): + if Int32(r_) < nmine: + va = samples[2 * r_] + vb = samples[2 * r_ + 1] + smn = cute.arch.fmin(smn, va) + smn = cute.arch.fmin(smn, vb) + pair_hi = cute.arch.fmax(va, vb) + pair_lo = cute.arch.fmin(va, vb) + smx2 = cute.arch.fmax(smx2, cute.arch.fmin(smx, pair_hi)) + smx2 = cute.arch.fmax(smx2, pair_lo) + smx = cute.arch.fmax(smx, pair_hi) + if cutlass.const_expr(self.lbin): + # Histogram rank selection: a key's bin is monotone in the key, so the bin of the rank-r key is the + # largest bin with at least r keys at or above it (the key search finds the key, then bins it the same way). + kmx_ = Uint32(L.fkey(smx)) + kmn_ = Uint32(L.fkey(smn)) + # SMIN / SMAX exactly as the key search computes them (warp 3's fold over s_keys / s_mins[lane + 32 j]): its + # first step (j = 0, the threads of warp 0) compares against the constant init 0 / 0xFFFFFFFF as a SIGNED + # integer, so warp 0's top-1 key counts only if it is below 2^31 (a negative float) and its min key only if + # it is at least 2^31 (a non-negative float); the later steps and the warp reduction are unsigned. Kept so + # that the T line stays bit-identical (the range [SMIN, SMAX] sets the bins). + if wid == Int32(0): + kmx_ = Uint32(cutlass.select_(kmx_ < Uint32(2147483648), kmx_, Uint32(0))) + kmn_ = Uint32(cutlass.select_(kmn_ >= Uint32(2147483648), kmn_, Uint32(4294967295))) + wmx_ = Uint32(cute.arch.warp_redux_sync(kmx_, "max")) + wmn_ = Uint32(cute.arch.warp_redux_sync(kmn_, "min")) + wab = cute.arch.warp_redux_sync(Uint32(ab), "or") + if lane == Int32(0): + s_red[wid] = wmx_ + s_red[Int32(4) + wid] = wmn_ + s_red[Int32(40) + wid] = wab + L.bar(BAR_SMX, NT) + ab = Int32(s_red[40] | s_red[41] | s_red[42] | s_red[43]) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_BOARD) + self._stamp(mStamps, cta, 21) + nkeys = Int32(2) * cutlass.min(nq, Int32(NT)) + gmx_ = Uint32(s_red[0]) + gmn_ = Uint32(s_red[4]) + for w_ in cutlass.range_constexpr(1, 4): + v1_ = Uint32(s_red[w_]) + v2_ = Uint32(s_red[4 + w_]) + gmx_ = Uint32(cutlass.select_(v1_ > gmx_, v1_, gmx_)) + gmn_ = Uint32(cutlass.select_(v2_ < gmn_, v2_, gmn_)) + SMIN = L.invkey(gmn_) + SMAX = L.invkey(gmx_) + wv0_ = (SMAX - SMIN) * Float32(1.0 / 256.0) + sc0_ = cutlass.select_(wv0_ > Float32(0.0), cute.arch.rcp_approx(wv0_), Float32(0.0)) + # bin of a key: trunc(clamp((x - SMIN) * sc, 0, 255)) == clamp(trunc(.), 0, 255) of the old path + fa_ = cute.arch.fmin(cute.arch.fmax((smx - SMIN) * sc0_, Float32(0.0)), Float32(255.0)) + fb_ = cute.arch.fmin(cute.arch.fmax((smx2 - SMIN) * sc0_, Float32(0.0)), Float32(255.0)) + kaddr_ = Int32(s_keys.iterator.toint()) + red_shared_add_u32(kaddr_ + L.f2s_rz(fa_) * Int32(4), Uint32(1)) + red_shared_add_u32(kaddr_ + L.f2s_rz(fb_) * Int32(4), Uint32(1)) + L.bar(BAR_SMX, NT) + # every warp resolves the three ranks: lane i owns the bins 255 - 8 i .. 248 - 8 i (descending), warp + # inclusive scan of the 8-bin sums = cumulative count from the top + bs_ = Int32(248) - lane * Int32(8) + c_ = [] + for j_ in cutlass.range_constexpr(8): + c_.append(Int32(s_keys[bs_ + Int32(j_)])) + tot_ = ((c_[0] + c_[1]) + (c_[2] + c_[3])) + ((c_[4] + c_[5]) + (c_[6] + c_[7])) + incl_ = L.warp_incl_scan_add(tot_, lane) + excl_ = incl_ - tot_ + rbins_ = [] + rks_ = [Int32(TGT), Int32(TGT2), Int32(TGT) * Int32(2)] + for ri_ in cutlass.range_constexpr(3): + rk_ = rks_[ri_] + bm_ = Uint32(cute.arch.vote_ballot_sync(incl_ >= rk_)) + lsb_ = bm_ & (Uint32(0) - bm_) + ls_ = (Int32(31) - Int32(cute.arch.clz(lsb_))) & Int32(31) + run_ = excl_ + fnd_ = Int32(0) + bsel_ = Int32(0) + for jj_ in cutlass.range_constexpr(8): + j_ = 7 - jj_ + run_ = run_ + c_[j_] + hit_ = cutlass.select_( + run_ >= rk_, cutlass.select_(fnd_ == Int32(0), Int32(1), Int32(0)), Int32(0) + ) + bsel_ = cutlass.select_(hit_ != Int32(0), bs_ + Int32(j_), bsel_) + fnd_ = fnd_ | hit_ + rbins_.append(cute.arch.shuffle_sync(bsel_, ls_)) + rb0_ = rbins_[0] + rb1_ = rbins_[1] + rb2_ = rbins_[2] + if ctid == Int32(0): + self._stamp(mStamps, cta, 22) + self._stamp(mStamps, cta, 23) + else: + s_keys[ctid] = L.fkey(smx) + s_keys[ctid + Int32(NT)] = L.fkey(smx2) + s_mins[ctid] = L.fkey(smn) + wab = cute.arch.warp_redux_sync(Uint32(ab), "or") + if lane == Int32(0): + s_red[Int32(40) + wid] = wab + L.bar(BAR_SMX, NT) + ab = Int32(s_red[40] | s_red[41] | s_red[42] | s_red[43]) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_BOARD) + self._stamp(mStamps, cta, 21) + nkeys = Int32(2) * cutlass.min(nq, Int32(NT)) + if wid < Int32(3): + rank = Int32(TGT) + if wid == Int32(1): + rank = Int32(TGT2) + elif wid == Int32(2): + rank = Int32(TGT * Int32(2)) + selected = Uint32(L.fkey(Float32(float("-inf")))) + if ab == Int32(0) and rank > Int32(0) and rank <= nkeys: + keys = cute.make_rmem_tensor((8,), Uint32) + lo = Uint32(4294967295) + hi = Uint32(0) + for j in cutlass.range_constexpr(8): + shared_key = Uint32(s_keys[lane + Int32(j * 32)]) + keys[j] = shared_key + lo = Uint32(cutlass.min(lo, shared_key)) + hi = Uint32(cutlass.max(hi, shared_key)) + lo = Uint32(L.warp_min_u32(lo)) + hi = Uint32(L.warp_max_u32(hi)) + steps = Int32(0) + # Each pivot removes a differing key bit. Count the whole + # array at every pass, so rank remains a global rank. + while lo < hi and steps < Int32(32): + bit = Uint32(Uint32(31) - cute.arch.clz(lo ^ hi)) + pivot = Uint32((hi >> bit) << bit) + nabove = Int32(0) + above_min = Uint32(4294967295) + below_max = Uint32(0) + for j in cutlass.range_constexpr(8): + radix_key = Uint32(keys[j]) + if radix_key >= pivot: + nabove = nabove + Int32(1) + above_min = Uint32(cutlass.min(above_min, radix_key)) + else: + below_max = Uint32(cutlass.max(below_max, radix_key)) + nabove = Int32(cute.arch.warp_redux_sync(nabove, "add")) + above_min = Uint32(L.warp_min_u32(above_min)) + below_max = Uint32(L.warp_max_u32(below_max)) + if nabove >= rank: + lo = Uint32(above_min) + else: + hi = Uint32(below_max) + steps = steps + Int32(1) + selected = Uint32(lo) + if lane == Int32(0): + s_res[wid] = selected + else: + vmin = Uint32(4294967295) + vmax = Uint32(0) + for j in cutlass.range_constexpr(4): + vmin = Uint32(cutlass.min(vmin, Uint32(s_mins[lane + Int32(j * 32)]))) + vmax = Uint32(cutlass.max(vmax, Uint32(s_keys[lane + Int32(j * 32)]))) + vmin = Uint32(L.warp_min_u32(vmin)) + vmax = Uint32(L.warp_max_u32(vmax)) + if lane == Int32(0): + s_res[3] = vmin + s_res[4] = vmax + L.bar(BAR_SMX, NT) + if ctid == Int32(0): + self._stamp(mStamps, cta, 22) + self._stamp(mStamps, cta, 23) + SMIN = L.invkey(Uint32(s_res[3])) + SMAX = L.invkey(Uint32(s_res[4])) + GMIN = Float32(L.SENT_LO) + T = Float32(NEG_INF) + HIC = Float32(NEG_INF) + T3 = Float32(NEG_INF) + Tk = Float32(NEG_INF) + wv = Float32(0.0) + sc_s = Float32(0.0) + sok = Int32(0) + if SMP > Int32(0): + if SMAX > SMIN: + sok = Int32(1) + tot0 = Int32(0) + b1v = Int32(-1) + b2v = Int32(-1) + b3v = Int32(-1) + if sok != Int32(0): + wv = (SMAX - SMIN) * Float32(1.0 / 256.0) + sc_s = cute.arch.rcp_approx(wv) + tot0 = nkeys + # Monotone binning commutes with order statistics. Reconstruct + # the same 256-bin proposal; all-logit certification is unchanged. + if tot0 >= TGT: + if cutlass.const_expr(self.lbin): + b1v = rb0_ + else: + b1v = L.f2s_rz((L.invkey(Uint32(s_res[0])) - SMIN) * sc_s) + b1v = cutlass.max(Int32(0), cutlass.min(Int32(255), b1v)) + if tot0 >= TGT2: + if cutlass.const_expr(self.lbin): + b2v = rb1_ + else: + b2v = L.f2s_rz((L.invkey(Uint32(s_res[1])) - SMIN) * sc_s) + b2v = cutlass.max(Int32(0), cutlass.min(Int32(255), b2v)) + if tot0 >= TGT * Int32(2): + if cutlass.const_expr(self.lbin): + b3v = rb2_ + else: + b3v = L.f2s_rz((L.invkey(Uint32(s_res[2])) - SMIN) * sc_s) + b3v = cutlass.max(Int32(0), cutlass.min(Int32(255), b3v)) + if sok != Int32(0): + if tot0 >= TGT: + T = L._fmaf(Float32(b1v), wv, SMIN) + tinf = Int32(1) + if T > Float32(NEG_INF): + tinf = Int32(0) + if tinf != Int32(0): + T = GMIN + if sok != Int32(0): + if tot0 >= TGT: + if b2v >= Int32(0): + Tk = L._fmaf(Float32(b2v), wv, SMIN) + d_ = cute.arch.fmax(Tk - T, Float32(0.0)) + HIC = cute.arch.fmax(L._fmaf(Float32(4.0), d_, T), L._fmaf(Float32(8.0), wv, T)) + if sok != Int32(0): + if tot0 >= TGT * Int32(2): + if b3v >= Int32(0): + if T > GMIN: + t3c = L._fmaf(Float32(b3v), wv, SMIN) + if t3c < T: + T3 = t3c + if cutlass.const_expr(not self.lbin): + L.bar(BAR_SMX, NT) + if ctid == Int32(0): + if ab != Int32(0): + misc[8 + mo] = Int32(2139095040) + misc[9 + mo] = Int32(-8388608) + misc[10 + mo] = Int32(-8388608) + misc[11 + mo] = Int32(-8388608) + misc[13 + mo] = Int32(1) + else: + misc[8 + mo] = Int32(L.u32_of_f32(T)) + misc[9 + mo] = Int32(L.u32_of_f32(HIC)) + misc[10 + mo] = Int32(L.u32_of_f32(T3)) + misc[11 + mo] = Int32(L.u32_of_f32(SMAX)) + self._skew(gen, cta, 5) + skip_t = Int32(0) + if d != Int32(0): + skip_t = Int32(1) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(1): + skip_t = Int32(1) + if cutlass.const_expr(self.fwarm): + skip_t = Int32(0) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(1): + skip_t = Int32(1) + tw_ = cutlass.select_(d == Int32(0), Int32(W_TLINE), Int32(W_TLINE_DRY)) + if skip_t == Int32(0): + tgl = Uint64(tg) << Uint64(32) + st_rlx_u64(self._w(ws, tw_ + Int32(1)), tgl | Uint64(L.u32_of_f32(HIC))) + st_rlx_u64(self._w(ws, tw_ + Int32(2)), tgl | Uint64(L.u32_of_f32(T3))) + st_rlx_u64(self._w(ws, tw_ + Int32(3)), tgl | Uint64(L.u32_of_f32(SMAX))) + st_rlx_u64(self._w(ws, tw_), tgl | Uint64(L.u32_of_f32(T))) + elif skip_t == Int32(0): + tgl = Uint64(tg) << Uint64(32) + st_rlx_u64(self._w(ws, W_TLINE + 1), tgl | Uint64(L.u32_of_f32(HIC))) + st_rlx_u64(self._w(ws, W_TLINE + 2), tgl | Uint64(L.u32_of_f32(T3))) + st_rlx_u64(self._w(ws, W_TLINE + 3), tgl | Uint64(L.u32_of_f32(SMAX))) + st_rlx_u64(self._w(ws, W_TLINE), tgl | Uint64(L.u32_of_f32(T))) + self._stamp(mStamps, cta, ST_M_T) + L.bar(BAR_SMX, NT) + + @cute.jit + def _poll_counts(self, ws, gen, slot, ctid): + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + t40 = self._tag40(gen) + t64 = gen + Uint64(1) + hasa = ctid < Int32(NS) + hasb = ctid + Int32(NT) < Int32(NS) + oka = Int32(0) + okb = Int32(0) + if not hasa: + oka = Int32(1) + if not hasb: + okb = Int32(1) + na = Int32(0) + nb = Int32(0) + ab = Int32(0) + go = Int32(1) + if oka != Int32(0) and okb != Int32(0): + go = Int32(0) + tdl = self._deadline() + ca = self._cnt_addr(ws, slot, cutlass.min(ctid, Int32(NS - 1))) + cb = self._cnt_addr(ws, slot, cutlass.min(ctid + Int32(NT), Int32(NS - 1))) + it_ = Int32(0) + while go != Int32(0): + wa = Uint64(0) + wb = Uint64(0) + if cutlass.const_expr(self.acqpoll): + wa = L.ld_acquire_u64(ca) + wb = L.ld_acquire_u64(cb) + else: + wa = L.ld_relaxed_u64(ca) + wb = L.ld_relaxed_u64(cb) + av = Uint64(0) + chk = Int32(1) + if cutlass.const_expr(self.pchk > 1): + chk = Int32(0) + if it_ & Int32(self.pchk - 1) == Int32(self.pchk - 1): + chk = Int32(1) + if chk != Int32(0): + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + it_ = it_ + Int32(1) + if oka == Int32(0): + if wa >> Uint64(24) == t40: + oka = Int32(1) + na = Int32(Uint32(wa & Uint64(16777215))) + if okb == Int32(0): + if wb >> Uint64(24) == t40: + okb = Int32(1) + nb = Int32(Uint32(wb & Uint64(16777215))) + if oka != Int32(0) and okb != Int32(0): + go = Int32(0) + elif chk != Int32(0): + if av == t64: + ab = Int32(1) + go = Int32(0) + elif Int64(L.gtimer()) > tdl: + ab = Int32(2) + go = Int32(0) + if ab == Int32(2): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + if cutlass.const_expr(not self.acqpoll and (not self.nofence)): + L.fence_acq_rel_gpu() + return (na, nb, ab) + + @cute.jit + def _poll_counts_hist(self, ws, gen, ctid, hptr, s_wc): + # CTA-uniform count poll that also re-reads this thread's four histogram bins on every pass, so the + # histogram snapshot is as fresh as the last count word seen; the caller validates it against C1. + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + lane = ctid % Int32(32) + wid = ctid // Int32(32) + t40 = self._tag40(gen) + t64 = gen + Uint64(1) + oka = Int32(0) + okb = Int32(0) + if not ctid < Int32(NS): + oka = Int32(1) + if not ctid + Int32(NT) < Int32(NS): + okb = Int32(1) + na = Int32(0) + nb = Int32(0) + ab = Int32(0) + h0 = Int32(0) + h1 = Int32(0) + h2 = Int32(0) + h3 = Int32(0) + tdl = self._deadline() + ca = self._cnt_addr(ws, Int32(0), cutlass.min(ctid, Int32(NS - 1))) + cb = self._cnt_addr(ws, Int32(0), cutlass.min(ctid + Int32(NT), Int32(NS - 1))) + it_ = Int32(0) + go = Int32(1) + while go != Int32(0): + wa = Uint64(0) + wb = Uint64(0) + if cutlass.const_expr(self.acqx): + wa = L.ld_relaxed_u64(ca) + wb = L.ld_relaxed_u64(cb) + else: + hv = L.ldg_cg_v4(hptr) + h0 = hv[0] + h1 = hv[1] + h2 = hv[2] + h3 = hv[3] + wa = L.ld_acquire_u64(ca) + wb = L.ld_acquire_u64(cb) + if oka == Int32(0): + if wa >> Uint64(24) == t40: + oka = Int32(1) + na = Int32(Uint32(wa & Uint64(16777215))) + if okb == Int32(0): + if wb >> Uint64(24) == t40: + okb = Int32(1) + nb = Int32(Uint32(wb & Uint64(16777215))) + if it_ & Int32(15) == Int32(15): + if ab == Int32(0): + av = L.ld_relaxed_u64(self._w(ws, W_ABORT)) + if av == t64: + ab = Int32(1) + elif Int64(L.gtimer()) > tdl: + ab = Int32(2) + mine = (oka != Int32(0) and okb != Int32(0)) or ab != Int32(0) + wd = Int32(cute.arch.vote_ballot_sync(mine)) + if lane == Int32(0): + s_wc[Int32(40) + (it_ & Int32(1)) * Int32(4) + wid] = wd + L.bar(BAR_CTL, NT) + base = Int32(40) + (it_ & Int32(1)) * Int32(4) + alld = ( + s_wc[base] & s_wc[base + Int32(1)] & s_wc[base + Int32(2)] & s_wc[base + Int32(3)] + ) + it_ = it_ + Int32(1) + if alld == Int32(-1): + go = Int32(0) + else: + if cutlass.const_expr(self.pollns > 0): + L.nanosleep(Int32(self.pollns)) + if cutlass.const_expr(self.acqx): + # acquire for the count releases this thread observed, passed on by the barrier, then one + # histogram read that includes every published contribution + L.fence_acq_rel_gpu() + L.bar(BAR_CTL, NT) + hx = L.ldg_cg_v4(hptr) + h0 = hx[0] + h1 = hx[1] + h2 = hx[2] + h3 = hx[3] + if ab == Int32(2): + self._raise_abort(ws, gen, Int32(E_TIMEOUT)) + return (na, nb, ab, h0, h1, h2, h3) + + @cute.jit + def _k3row(self, gp, npg_s, s_btc, mBtC, mbc, real): + pg = gp >> Int32(5) + bt = Int32(0) + # Prewarm uses synthetic candidates and does not wait for the BTC TMA. + # Its rows never reach attention, so only real selection reads pages. + if real: + if pg < npg_s: + bt = s_btc[pg] + else: + bt = mBtC[0, cutlass.min(pg, mbc - Int32(1))] + return bt * Int32(32) + (gp & Int32(31)) + + @cute.jit + def _bucket_addr(self, rg, b, ordinal): + # The second half of each producer region is idle until DRS starts. + # Four 512-entry buckets fit in each such half; no extra allocation. + flat = b * Int32(BUCKET_CAP) + ordinal + off = flat // Int32(CAPR) * Int32(2 * CAPR) + Int32(CAPR) + flat % Int32(CAPR) + return rg + Int64(off) * Int64(8) + + @cute.jit + def _bucket_acquire( + self, arena, cta, d, ctid, ws, gen, Kq, mHist, mStamps, mCtl, real=True, mo_=None, rgp_=None + ): + NT: cutlass.Constexpr[int] = 128 + lane = ctid % Int32(32) + wid = ctid // Int32(32) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + s_red = _sm_tensor(arena, T_OFF_RED, Uint32, 64) + s_wc = _sm_tensor(arena, T_OFF_WC, Int32, 64) + s_hist = _sm_tensor(arena, T_OFF_HIST, Int32, NB_SEL) + s_res = _sm_tensor(arena, T_OFF_RES, Int32, 16) + s_map = _sm_tensor(arena, SMAP2_OFF, Int32, K_TOP) + if cutlass.const_expr(mo_ is None): + mo_ = Int32(0) + # warm-up pass (real == 0): the same code without the count poll; the histogram values it reads are + # discarded and it never takes the fast path, publishes or writes misc + na = Int32(0) + nb = Int32(0) + ab = Int32(0) + sh0 = Int32(0) + sh1 = Int32(0) + sh2 = Int32(0) + sh3 = Int32(0) + hptr = mHist.iterator.toint() + Int64(ctid) * Int64(16) + if real: + na, nb, ab, sh0, sh1, sh2, sh3 = self._poll_counts_hist(ws, gen, ctid, hptr, s_wc) + else: + hw_ = L.ldg_cg_v4(hptr) + sh0 = hw_[0] + sh1 = hw_[1] + sh2 = hw_[2] + sh3 = hw_[3] + wc = Int32(cute.arch.warp_redux_sync(na + nb, "add")) + wa = Uint32(cute.arch.warp_redux_sync(Uint32(ab), "or")) + if lane == Int32(0): + s_red[wid * Int32(2)] = Uint32(wc) + s_red[wid * Int32(2) + Int32(1)] = wa + # This barrier also carries every count-acquire to all histogram readers. + L.bar(BAR_CTL, NT) + C1 = Int32(s_red[0] + s_red[2] + s_red[4] + s_red[6]) + bad = Int32(s_red[1] | s_red[3] | s_red[5] | s_red[7]) + T = L.f32_of_u32(Uint32(misc[Int32(8) + mo_])) + HIC = L.f32_of_u32(Uint32(misc[Int32(9) + mo_])) + SMAX = L.f32_of_u32(Uint32(misc[Int32(11) + mo_])) + lo, hi = self._band_range(T, HIC, SMAX) + sc = bin_scale(lo, hi) * Float32(0.5) + eligible = ( + bad == Int32(0) + and misc[Int32(13) + mo_] == Int32(0) + and C1 >= Kq + and Kq > Int32(0) + and T > Float32(L.SENT_LO) + and sc > Float32(0.0) + ) + if cutlass.const_expr(self.debug): + if mCtl[0] != Int32(0): + eligible = False + fast = Int32(0) + Bb = Int32(-1) + above = Int32(0) + m = Int32(0) + elig_ = Int32(0) + if eligible: + elig_ = Int32(1) + if not real: + elig_ = Int32(1) + if elig_ != Int32(0): + if ctid == Int32(0): + s_res[L.RES_B] = Int32(-1) + s_res[L.RES_ABOVE] = Int32(0) + s_res[L.RES_M] = Int32(0) + # Adjacent bins are one aligned vector load, avoiding four + # dependent scalar CG load/consume sequences per thread. + for q in cutlass.range_constexpr(4): + s_map[ctid * Int32(4) + Int32(q)] = Int32(2147483647) + subtotal = (sh0 + sh1) + (sh2 + sh3) + inc = L.warp_incl_scan_add(subtotal, lane) + if lane == Int32(31): + s_wc[wid] = inc + L.bar(BAR_CTL, NT) + before = inc - subtotal + total = Int32(0) + for w in cutlass.range_constexpr(4): + v = s_wc[w] + if Int32(w) < wid: + before = before + v + total = total + v + if real: + if total != C1: + # stale snapshot: one re-read, ordered after every count acquire by the barrier above + L.bar(BAR_CTL, NT) + hw2 = L.ldg_cg_v4(hptr) + sh0 = hw2[0] + sh1 = hw2[1] + sh2 = hw2[2] + sh3 = hw2[3] + subtotal = (sh0 + sh1) + (sh2 + sh3) + inc = L.warp_incl_scan_add(subtotal, lane) + if lane == Int32(31): + s_wc[wid] = inc + L.bar(BAR_CTL, NT) + before = inc - subtotal + total = Int32(0) + for w in cutlass.range_constexpr(4): + v = s_wc[w] + if Int32(w) < wid: + before = before + v + total = total + v + hv = [sh0, sh1, sh2, sh3] + suffix = total - before + for q in cutlass.range_constexpr(4): + bi = ctid * Int32(4) + Int32(q) + s_hist[bi] = suffix + next_suffix = suffix - hv[q] + # Mark each nonempty bucket's output interval. Its physical + # source index is a constant delta plus the destination slot. + # The deltas decrease with slot, so one prefix-min fills gaps. + if hv[q] > Int32(0) and next_suffix < Kq: + flat = bi * Int32(BUCKET_CAP) + off = flat // Int32(CAPR) * Int32(2 * CAPR) + Int32(CAPR) + flat % Int32(CAPR) + s_map[next_suffix] = off - next_suffix + if cutlass.const_expr(self.bpf and rgp_ is not None): + # this bin feeds the top Kq rows: its entry lines into L1 now + if real: + nl_ = (cutlass.min(hv[q], Int32(BUCKET_CAP)) + Int32(15)) // Int32(16) + jl_ = Int32(0) + while jl_ < nl_: + prefetch_l1(rgp_ + Int64(off + jl_ * Int32(16)) * Int64(8)) + jl_ = jl_ + Int32(1) + if suffix >= Kq and next_suffix < Kq: + s_res[L.RES_B] = bi + s_res[L.RES_ABOVE] = next_suffix + s_res[L.RES_M] = hv[q] + suffix = next_suffix + if ctid == Int32(0): + s_hist[NB_INITIAL] = Int32(0) + L.bar(BAR_CTL, NT) + Bb = s_res[L.RES_B] + above = s_res[L.RES_ABOVE] + m = s_res[L.RES_M] + # Every bin strictly above the crossing contains at most Kq rows, + # so it fits in BUCKET_CAP. Only the crossing needs a capacity test. + if total == C1 and Bb >= Int32(0) and m <= Int32(QUADC): + if real: + fast = Int32(1) + if fast != Int32(0): + if ctid == Int32(0): + misc[Int32(12) + mo_] = Int32(P_T1) + if d == Int32(0 if self.late_done != 4 else -1): + fol_ok = self._wait_followers(ws, gen) + misc[Int32(14) + mo_] = fol_ok + if cutlass.const_expr(self.late_done == 0): + if fol_ok != Int32(0): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + self._stamp(mStamps, cta, ST_M_FIN) + return (fast, C1, Bb, above, m) + + @cute.jit + def _bucket_select( + self, + arena, + cta, + ctid, + Kw, + Bb, + above, + m, + real, + st, + bars, + n, + s_idx, + mBtC, + mbc, + mRegion, + mStamps, + pre_=None, + ): + NT: cutlass.Constexpr[int] = 128 + lane = ctid % Int32(32) + wid = ctid // Int32(32) + s_map = _sm_tensor(arena, SMAP2_OFF, Int32, K_TOP) + if cutlass.const_expr(pre_ is None): + pre_ = Int32(0) + s_wc = _sm_tensor(arena, T_OFF_WC, Int32, 64) + s_outs = _sm_tensor(arena, T_OFF_OUTS, Int32, K_TOP) + s_ck = _sm_tensor(arena, T_OFF_CK, Uint64, QUADC) + s_cs = _sm_tensor(arena, T_OFF_CS, Int32, QUADC) + s_crow = _sm_tensor(arena, T_OFF_CROW, Int32, QUADC) + s_btc = _sm_tensor(arena, T_OFF_BTC, Int32, BTC_CAP) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + rg = mRegion.iterator.toint() + st = self._warm_abort(real, st, ctid, bars, misc) + if st == Int32(ST_GO): + if cutlass.const_expr(not self.btcl): + if real and pre_ == Int32(0): + A._wait(bars + B_BTC, Int32(0)) + npg_s = ( + cutlass.min((n + Int32(31)) // Int32(32), cutlass.min(mbc, Int32(BTC_CAP))) + // Int32(4) + * Int32(4) + ) + if pre_ != Int32(0): + # pre-select: this pass's BTC copy (KV slot 6) holds another row, every page is read from global + npg_s = Int32(0) + # Expand the interval markers with one CTA prefix-min, replacing + # four serial nine-step shared-memory searches per thread. + offsets = [] + scan = Int32(2147483647) + for q in cutlass.range_constexpr(K_TOP // NT): + scan = cutlass.min(scan, s_map[ctid * Int32(4) + Int32(q)]) + offsets.append(scan) + for step in cutlass.range_constexpr(5): + other = cute.arch.shuffle_sync_up(scan, 1 << step, mask_and_clamp=0) + if lane >= Int32(1 << step): + scan = cutlass.min(scan, other) + if lane == Int32(31): + s_wc[wid] = scan + carry = cute.arch.shuffle_sync_up(scan, 1, mask_and_clamp=0) + if lane == Int32(0): + carry = Int32(2147483647) + L.bar(BAR_CTL, NT) + for w in cutlass.range_constexpr(4): + if Int32(w) < wid: + carry = cutlass.min(carry, s_wc[w]) + # Stop synthetic work promptly when the real threshold arrives. + st = self._warm_abort(real, st, ctid, bars, misc) + if st == Int32(ST_GO): + # Issue independent bucket reads before consuming any result. + # Crossing entries are included to overlap their load latency too. + entries = [Uint64(0)] * (K_TOP // NT) + cross = [Uint64(0)] * ((QUADC + NT - 1) // NT) + for q in cutlass.range_constexpr(K_TOP // NT): + po = ctid * Int32(4) + Int32(q) + if po < above: + e = Uint64(Uint32(po)) << Uint64(32) | Uint64(L.u32_of_f32(Float32(po))) + if real: + off = cutlass.min(offsets[q], carry) + po + if cutlass.const_expr(self.bpf): + e = ldg_ca_u64(rg + Int64(off) * Int64(8)) + elif cutlass.const_expr(self.entcg): + e = ldg_cg_u64(rg + Int64(off) * Int64(8)) + else: + e = L.ld_relaxed_u64(rg + Int64(off) * Int64(8)) + entries[q] = e + for q in cutlass.range_constexpr((QUADC + NT - 1) // NT): + i = ctid + Int32(q * NT) + if i < m: + e = Uint64(Uint32(above + i)) << Uint64(32) | Uint64( + L.u32_of_f32(Float32(above + i)) + ) + if real: + if cutlass.const_expr(self.bpf): + e = ldg_ca_u64(self._bucket_addr(rg, Bb, i)) + elif cutlass.const_expr(self.entcg): + e = ldg_cg_u64(self._bucket_addr(rg, Bb, i)) + else: + e = L.ld_relaxed_u64(self._bucket_addr(rg, Bb, i)) + cross[q] = e + if cutlass.const_expr(self.btcl): + # the block table is needed only from here (translation); the loads above are in flight + if real and pre_ == Int32(0): + A._wait(bars + B_BTC, Int32(0)) + for q in cutlass.range_constexpr(K_TOP // NT): + po = ctid * Int32(4) + Int32(q) + if po < above: + e = entries[q] + gp = Int32(Uint32(e >> Uint64(32))) + s_outs[po] = gp + rv_ = gp + if pre_ == Int32(0): + rv_ = self._k3row(gp, npg_s, s_btc, mBtC, mbc, real) + (s_idx + Int32(128) + po).store(rv_) + for q in cutlass.range_constexpr((QUADC + NT - 1) // NT): + i = ctid + Int32(q * NT) + if i < m: + e = cross[q] + gp = Int32(Uint32(e >> Uint64(32))) + s_ck[i] = L.entry_key(e) + s_cs[i] = gp + rc_ = gp + if pre_ == Int32(0): + rc_ = self._k3row(gp, npg_s, s_btc, mBtC, mbc, real) + s_crow[i] = rc_ + L.bar(BAR_CTL, NT) + if cutlass.const_expr(self.gjoin): + if real and above >= Int32(384) and pre_ == Int32(0): + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + misc[15] = Int32(1) + misc[16] = above + prims.mbarrier_arrive(bars + B_EAR) + if ctid == Int32(0) and real: + self._stamp(mStamps, cta, 70) + st = self._warm_abort(real, st, ctid, bars, misc) + if st == Int32(ST_GO): + need = Kw - above + if m <= Int32(32): + if ctid < Int32(32): + key = Uint64(0) + if ctid < m: + key = Uint64(s_ck[ctid]) + kh = Uint32(key >> Uint64(32)) + kl = Uint32(key) + # Retire the smaller side of the boundary partition. + # Two native unsigned minima select an exact 64-bit key: + # first its high word, then its low word among high ties. + discard = m - need <= need + flip = Uint32(0) + if not discard: + flip = Uint32(4294967295) + xh = kh ^ flip + xl = kl ^ flip + live = ctid < m + nr = cutlass.min(need, m - need) + for j in cutlass.range(nr, unroll=1): + vh = Uint32(4294967295) + if live: + vh = xh + mh = Uint32(cute.arch.warp_redux_sync(vh, "min")) + vl = Uint32(4294967295) + if live and xh == mh: + vl = xl + ml = Uint32(cute.arch.warp_redux_sync(vl, "min")) + if live and xh == mh and xl == ml: + live = False + keep = live + if not discard: + keep = ctid < m and not live + mask = Uint32(cute.arch.vote_ballot_sync(keep)) + prior = (Uint32(1) << Uint32(ctid)) - Uint32(1) + rank = Int32(cute.arch.popc(mask & prior)) + if keep: + s_outs[above + rank] = s_cs[ctid] + (s_idx + Int32(128) + above + rank).store(s_crow[ctid]) + else: + i = ctid + while i < m: + key = Uint64(s_ck[i]) + rank = Int32(0) + for j in cutlass.range(m, unroll=1): + if Uint64(s_ck[j]) > key: + rank = rank + Int32(1) + if rank < need: + s_outs[above + rank] = s_cs[i] + (s_idx + Int32(128) + above + rank).store(s_crow[i]) + i = i + Int32(NT) + L.bar(BAR_CTL, NT) + return st + + @cute.jit + def _shipped_sel(self, arena, cta, d, ctid, ws, s_idx, bars, mStamps, n, mBtC): + # this row was pre-selected in the previous pass: copy its KV rows, release the gathers, then the + # same directive tail as _control_s1d's real pass + NT: cutlass.Constexpr[int] = 128 + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + s2_ = _ptr(arena, SIDX2_OFF, Int32) + A._wait(bars + B_T, Int32(0)) + gen = Uint64(Uint32(misc[5])) << Uint64(32) | Uint64(Uint32(misc[4])) + if ctid == Int32(0): + self._stamp(mStamps, cta, 71) + # SIDX2 holds positions (-1 = padding): translate with this pass's block-table copy + A._wait(bars + B_BTC, Int32(0)) + if ctid == Int32(0): + self._stamp(mStamps, cta, 74) + mbc = cute.size(mBtC, mode=[1]) + s_btc = _sm_tensor(arena, T_OFF_BTC, Int32, BTC_CAP) + npg_s = ( + cutlass.min((n + Int32(31)) // Int32(32), cutlass.min(mbc, Int32(BTC_CAP))) + // Int32(4) + * Int32(4) + ) + for q in cutlass.range_constexpr(K_TOP // NT): + ii = Int32(128) + ctid + Int32(q * NT) + gp = (s2_ + ii).load() + rv_ = Int32(-1) + if gp >= Int32(0): + rv_ = self._k3row(gp, npg_s, s_btc, mBtC, mbc, True) + (s_idx + ii).store(rv_) + if ctid == Int32(0): + misc[12] = Int32(P_T1) + misc[15] = Int32(0) + misc[16] = misc[59] + self._stamp(mStamps, cta, ST_M_SEL) + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_CTL, NT) + prims.mbarrier_arrive(bars + B_EAR) + prims.mbarrier_arrive(bars + B_SEL) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_OUT) + if cutlass.const_expr(self.late_done == 4): + if d == Int32(0): + if self._wait_followers(ws, gen) != Int32(0): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + + @cute.jit + def _control_s1d( + self, + arena, + cta, + d, + ctid, + ws, + n, + s_idx, + bars, + mSwaLocal, + mBtSwa, + mBtC, + mTopk, + mGidx, + mRegion, + mHist, + mStamps, + mCtl, + gargs=None, + eargs=None, + p0=None, + pre_=None, + gwn=None, + ): + NT: cutlass.Constexpr[int] = 128 + is_t0 = d == Int32(0) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + s_outs = _sm_tensor(arena, T_OFF_OUTS, Int32, K_TOP) + _s_lst = _sm_tensor(arena, T_OFF_LIST, Uint64, CAPL) + s_hist = _sm_tensor(arena, T_OFF_HIST, Int32, NB_SEL) + s_map = _sm_tensor(arena, SMAP2_OFF, Int32, K_TOP) + pre_on = pre_ is not None + if cutlass.const_expr(pre_ is None): + pre_ = Int32(0) + # misc offset of this job's T line (pre-select: polled into misc + 44) + mo_ = cutlass.select_(pre_ != Int32(0), Int32(44), Int32(0)) + mbc = cute.size(mBtC, mode=[1]) + mbs = cute.size(mBtSwa, mode=[1]) + if cutlass.const_expr(not self.swag): + loc = mSwaLocal[0, ctid] + rsw = L.l2g_swa_local(loc, Int32(0), mBtSwa, mbs, Int32(0)) + (s_idx + ctid).store(rsw) + L.bar(BAR_CTL, NT) + # Every writer releases its own index stores to the gather warps. + prims.mbarrier_arrive(bars + B_SWA) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_SWA) + Kq = cutlass.min(n, Int32(K_TOP)) + P0: cutlass.Constexpr[int] = 0 if self.prewarm else 1 + gen = Uint64(0) + _path = Int32(P_T1) + C1 = Int32(0) + C = Int32(0) + rounds = Int32(0) + mret = Int32(0) + info = Int32(0) + Bb = Int32(-1) + nout = Int32(0) + zaddr = Int32(cute.recast_ptr(arena + T_OFF_MISC + 62 * 4, dtype=Int32).toint()) + if cutlass.const_expr(self.nohoist): + sts_volatile_u32(zaddr, Int32(0)) + ctid0 = ctid + for ps in cutlass.range(P0 if p0 is None else p0, 2, unroll=1): + ctid = ctid0 + if cutlass.const_expr(self.nohoist): + ctid = ctid0 + lds_volatile_u32(zaddr) + real = ps == Int32(1) + if ctid == Int32(0): + self._stamp(mStamps, cta, 92 + ps) + st = Int32(ST_GO) + lo = Float32(1.0) + hi = Float32(1.0) + Float32(0.001 * NT) + mm = Int32(0) + Kw = Int32(K_TOP) + C = Int32(K_TOP) + fast = Int32(0) + above = Int32(0) + bm = Int32(0) + if real: + if cutlass.const_expr(pre_on): + if pre_ != Int32(0): + # the next row's SWA KV rows into SIDX2[0..127] (copied by the next pass's swag warps) + if cutlass.const_expr(self.swpre): + locn_ = mSwaLocal[0, ctid] + (s_idx + ctid).store( + L.l2g_swa_local(locn_, Int32(0), mBtSwa, mbs, Int32(0)) + ) + if cutlass.const_expr(self.pdec): + # the SWA rows are final now: flag them for the next pass's swag warps + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + fence_acq_rel_cta() + sts_volatile_u32( + Int32( + cute.recast_ptr( + arena + T_OFF_MISC + 60 * 4, dtype=Int32 + ).toint() + ), + Int32(1), + ) + if ctid == Int32(0): + misc[57] = Int32(0) + misc[58] = Int32(0) + if cutlass.const_expr(self.pdirect and self.npmax > 2): + # misc[27] = "the pass this pre-select prepares has started": clear the + # previous pass's start (set before this pre-select began) + sts_volatile_u32( + Int32( + cute.recast_ptr( + arena + T_OFF_MISC + 27 * 4, dtype=Int32 + ).toint() + ), + Int32(0), + ) + self._follow_tline1( + arena, + cta, + d, + Int32(0), + ws, + mStamps, + gwn[0], + gwn[1], + gwn[2], + mCtl, + mo=44, + ) + L.bar(BAR_CTL, NT) + if pre_ == Int32(0): + A._wait(bars + B_T, Int32(0)) + gen = Uint64(Uint32(misc[Int32(5) + mo_])) << Uint64(32) | Uint64( + Uint32(misc[Int32(4) + mo_]) + ) + Kw = Kq + # The warm-up pass is split over the team: CTAs >= 2 run the bucket-acquire code, CTAs 0-1 the bucket + # emission / rank, so both are L2-resident for every team CTA when the stream ends. + fa_ = Int32(0) + c1a_ = Int32(0) + bba_ = Int32(-1) + aba_ = Int32(0) + bma_ = Int32(0) + if real or d >= Int32(2): + fa_, c1a_, bba_, aba_, bma_ = self._bucket_acquire( + arena, + cta, + d, + ctid, + ws, + gen, + Kq, + mHist, + mStamps, + mCtl, + real, + mo_=mo_, + rgp_=mRegion.iterator.toint(), + ) + if real: + fast = fa_ + C1 = c1a_ + Bb = bba_ + above = aba_ + bm = bma_ + if fast == Int32(0): + if pre_ == Int32(0): + st, _path, C, lo, hi, mm, C1, rounds = self._acquire( + arena, cta, d, ctid, ws, gen, n, Kq, bars, mRegion, mHist, mStamps, mCtl + ) + else: + _path = Int32(P_T1) + C = C1 + elif d < Int32(2): + # Warm the bucket-emission and boundary-rank code with purely + # synthetic shared state. No unpublished global packets are read. + fast = Int32(1) + Bb = Int32(0) + above = Int32(K_TOP - 1) + bm = Int32(1) + for q in cutlass.range_constexpr(NB_INITIAL // NT): + bi = ctid + Int32(q * NT) + s_hist[bi] = Int32(NB_INITIAL) - bi + flat = (Int32(NB_INITIAL - 1) - bi) * Int32(BUCKET_CAP) + off = flat // Int32(CAPR) * Int32(2 * CAPR) + Int32(CAPR) + flat % Int32(CAPR) + s_map[bi] = off - bi + if ctid == Int32(0): + s_hist[NB_INITIAL] = Int32(0) + L.bar(BAR_CTL, NT) + # this pre-select's acquire completed after the pass it prepares started: join that pass now + # (BAR_HAND) and emit physical rows into its s_idx with the normal release tail + pre_e_ = pre_ + s_idxe_ = s_idx + if cutlass.const_expr(self.pdirect and pre_on): + if real: + if pre_ != Int32(0) and fast != Int32(0): + if ctid == Int32(0): + fpa_ = Int32( + cute.recast_ptr(arena + T_OFF_MISC + 27 * 4, dtype=Int32).toint() + ) + fv_ = lds_volatile_u32(fpa_) + if cutlass.const_expr(self.pdwait > 0): + # wait a little for the pass start before taking the positions path + tw_ = Int64(L.gtimer()) + Int64(self.pdwait) + while fv_ == Int32(0) and Int64(L.gtimer()) < tw_: + fv_ = lds_volatile_u32(fpa_) + misc[28] = fv_ + L.bar(BAR_CTL, NT) + if misc[28] != Int32(0): + L.bar(BAR_HAND, 256) + pre_e_ = Int32(0) + if ctid == Int32(0): + misc[12] = Int32(P_T1) + misc[58] = Int32(2) + self._stamp(mStamps, cta, 78) + s_idxe_ = _ptr( + arena, + cutlass.select_(pre_e_ != Int32(0), Int32(SIDX2_OFF), Int32(T_OFF_IDX)), + Int32, + ) + fnar = Int32(0) + if cutlass.const_expr(self.debug): + if real: + if mCtl[0] == Int32(3): + fnar = Int32(1) + if fast != Int32(0): + st = self._bucket_select( + arena, + cta, + ctid, + Kw, + Bb, + above, + bm, + real, + st, + bars, + n, + s_idxe_, + mBtC, + mbc, + mRegion, + mStamps, + pre_=pre_e_, + ) + nout = Kw + mret = bm + info = Int32(1) + else: + if real and pre_ == Int32(0): + st, mret, info, Bb, nout = self._sel_list( + arena, + cta, + ctid, + C, + Kw, + lo, + hi, + mm, + fnar, + real, + st, + bars, + n, + s_idx, + mBtC, + mbc, + mStamps, + d, + ) + if cutlass.const_expr(self.wacq == 2): + if not real: + if st == Int32(ST_GO): + self._dry_acquire(arena, ctid, mRegion) + if real: + for u_ in cutlass.range_constexpr(K_TOP // NT): + ii = ctid + Int32(u_ * NT) + if ii >= nout: + s_outs[ii] = Int32(-1) + (s_idxe_ + Int32(128) + ii).store(Int32(-1)) + L.bar(BAR_CTL, NT) + if is_t0 and (pre_ == Int32(0) or fast != Int32(0)): + for u_ in cutlass.range_constexpr(K_TOP // NT): + ii = ctid + Int32(u_ * NT) + mTopk[0, ii] = s_outs[ii] + L.bar(BAR_CTL, NT) + if real and pre_e_ != Int32(0): + # pre-select result for the next pass (misc[58] = 1: _shipped_sel copies SIDX2) + if ctid == Int32(0): + if fast != Int32(0) and st == Int32(ST_GO): + misc[58] = Int32(1) + misc[59] = above + self._stamp(mStamps, cta, 72) + if real and pre_e_ == Int32(0): + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_SEL) + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_CTL, NT) + if cutlass.const_expr(self.gjoin): + # The flag is stable across this whole warpgroup. Do not update + # it here: all 128 writers must take the same fallback branch. + if misc[15] == Int32(0): + prims.mbarrier_arrive(bars + B_EAR) + prims.mbarrier_arrive(bars + B_SEL) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_OUT) + if cutlass.const_expr(self.late_done == 4): + if is_t0: + if misc[12] == Int32(P_T1): + if self._wait_followers(ws, gen) != Int32(0): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + if cutlass.const_expr(self.late_done == 3): + if is_t0: + if misc[12] == Int32(P_T1) and misc[14] != Int32(0): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + if cutlass.const_expr(gargs is not None): + A.role_gather_team(*gargs) + if cutlass.const_expr(eargs is not None): + # The epilogue runs at this one call site in both passes: dry at the end of the warm-up pass on team + # CTAs >= 2 (its single real execution then fetches L2-resident code), for real after the tail. + if real or d >= Int32(2): + dry_ = Int32(1) + if real: + dry_ = Int32(0) + A.role_corr_epi_team(*eargs, dry=dry_) + + @cute.jit + def _dry_acquire(self, arena, ctid, mRegion): + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + s_coff = _sm_tensor(arena, T_OFF_COFF, Int32, 160) + s_cu1 = _sm_tensor(arena, T_OFF_CU1, Int32, 160) + lbase = Int32(cute.recast_ptr(arena + T_OFF_LIST, dtype=Int32).toint()) + da = Int32(0) + db = Int32(0) + if ctid < Int32(NS): + da = Int32(1) + if ctid + Int32(NT) < Int32(NS): + db = Int32(1) + xa, xb, xc, xd, Sa, Sb, Sc, Sd = self._scan4(da, db, Int32(0), Int32(0), ctid, arena) + if ctid < Int32(NS): + s_coff[ctid] = xa + s_cu1[ctid] = da + if ctid + Int32(NT) < Int32(NS): + s_coff[ctid + Int32(NT)] = Sa + xb + s_cu1[ctid + Int32(NT)] = db + L.bar(BAR_CTL, NT) + self._copy_runs(ctid, mRegion.iterator.toint(), Int32(0), lbase, s_cu1, s_coff) + cute.arch.cp_async_commit_group() + cute.arch.cp_async_wait_group(0) + L.bar(BAR_CTL, NT) + + @cute.jit + def _copy_runs(self, ctid, rg, rb, lbase, s_cu1, s_coff): + NS = self.ns + sub = ctid % Int32(4) + cc = ctid // Int32(4) + while cc < Int32(NS): + uu = s_cu1[cc] + oo = s_coff[cc] + src = rg + Int64(cc) * Int64(2 * CAPR * 8) + Int64(rb) * Int64(8) + e = sub + while e < uu: + cp_async8(lbase + (oo + e) * Int32(8), src + Int64(e) * Int64(8)) + e = e + Int32(4) + cc = cc + Int32(32) + + @cute.jit + def _acquire(self, arena, cta, d, ctid, ws, gen, n, Kq, bars, mRegion, mHist, mStamps, mCtl): + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + is_t0 = d == Int32(0) + lane = ctid % Int32(32) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + # COFF is private to acquire until the rare path rebuilds its offsets. + s_acq = _sm_tensor(arena, T_OFF_COFF, Int32, 160) + s_cu2 = _sm_tensor(arena, T_OFF_CU2, Int32, 160) + lbase = Int32(cute.recast_ptr(arena + T_OFF_LIST, dtype=Int32).toint()) + rg = mRegion.iterator.toint() + T = L.f32_of_u32(Uint32(misc[8])) + HIC = L.f32_of_u32(Uint32(misc[9])) + T3 = L.f32_of_u32(Uint32(misc[10])) + SMAX = L.f32_of_u32(Uint32(misc[11])) + lo, hi = self._band_range(T, HIC, SMAX) + mm = Int32(0) + if not T > Float32(L.SENT_LO): + mm = Int32(1) + st = Int32(ST_GO) + path = Int32(P_T1) + rounds = Int32(0) + if ctid < Int32(3): + s_acq[ctid] = Int32(0) + # Retire every warm generic LIST access before any warp can overwrite + # LIST through the async proxy. This barrier also initializes counters. + L.fence_proxy_async_smem() + L.bar(BAR_CTL, NT) + self._skew(gen, cta * Int32(4) + Int32(3), ctid) + t64f = gen + Uint64(1) + fol_ready = Int32(0) + if cutlass.const_expr(self.folpre): + if is_t0 and ctid == Int32(0): + fol_ready = self._followers_ready(ws, t64f) + na, nb, ab = self._poll_counts(ws, gen, Int32(0), ctid) + fol_ok = fol_ready + if ctid == Int32(0): + self._stamp(mStamps, cta, 100) + abv = Int32(0) + if ab != Int32(0) or misc[13] != Int32(0): + abv = Int32(1) + pa = na + (na & Int32(1)) + pb = nb + (nb & Int32(1)) + if ctid < Int32(NS): + s_cu2[ctid] = pa + if ctid + Int32(NT) < Int32(NS): + s_cu2[ctid + Int32(NT)] = pb + # A warp may reserve and issue before the other three warps finish + # their count polls. Each lane keeps its packet offsets in registers. + ncopy = pa + pb + incl = L.warp_incl_scan_add(ncopy, lane) + wcopy = cute.arch.shuffle_sync(incl, Int32(31)) + wactual = cute.arch.warp_redux_sync(na + nb, "add") + wab = Int32(cute.arch.warp_redux_sync(Uint32(abv), "or")) + wbase = Int32(0) + if lane == Int32(0): + wbase = Int32(cute.arch.atomic_add(s_acq.iterator, wcopy, sem="relaxed", scope="cta")) + cute.arch.red( + s_acq.iterator + Int32(1), + wactual, + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + cute.arch.red( + s_acq.iterator + Int32(2), wab, op="add", dtype=Int32, sem="relaxed", scope="cta" + ) + wbase = cute.arch.shuffle_sync(wbase, Int32(0)) + own_base = wbase + incl - ncopy + if wbase + wcopy <= Int32(CAPL): + if wcopy > Int32(0): + if lane == Int32(0): + L.mbar_expect_tx(Int32((bars + B_LST).toint()), wcopy * Int32(8)) + cute.arch.sync_warp() + L.fence_proxy_async_global() + if ctid < Int32(NS) and pa > Int32(0): + L.bulk_g2s( + lbase + own_base * Int32(8), + rg + Int64(ctid) * Int64(2 * CAPR * 8), + pa * Int32(8), + Int32((bars + B_LST).toint()), + ) + if ctid + Int32(NT) < Int32(NS) and pb > Int32(0): + L.bulk_g2s( + lbase + (own_base + pa) * Int32(8), + rg + Int64(ctid + Int32(NT)) * Int64(2 * CAPR * 8), + pb * Int32(8), + Int32((bars + B_LST).toint()), + ) + # The arrival is delayed until all warps have registered their bytes. + # Overflow copies were skipped in complete warp spans and use fallback. + L.bar(BAR_CTL, NT) + C = s_acq[0] + C1 = s_acq[1] + ab = s_acq[2] + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_FIN) + prims.mbarrier_arrive(bars + B_LST) + self._stamp(mStamps, cta, 84) + rare = Int32(1) + if ab == Int32(0) and C1 >= Kq and C <= Int32(CAPL): + rare = Int32(0) + if cutlass.const_expr(self.rs24): + # rs24: the T1 list path (this bulk-copied list read by _sel_list) gave wrong attention while its top-512 + # was right; rows without a bucket selection go through the rare path (T12 / DRS, list rebuilt by cp.async) + rare = Int32(1) + if cutlass.const_expr(self.debug): + if mCtl[0] == Int32(1) or mCtl[0] == Int32(2): + rare = Int32(1) + if rare == Int32(0): + if ctid == Int32(0): + misc[12] = Int32(P_T1) + if is_t0: + skip_d = Int32(0) + if cutlass.const_expr(self.debug): + if mCtl[1] == Int32(3): + skip_d = Int32(1) + if cutlass.const_expr(self.late_done > 0): + skip_d = Int32(1) + if fol_ok == Int32(0): + fol_ok = self._wait_followers(ws, gen) + misc[14] = fol_ok + if skip_d == Int32(0): + if fol_ok == Int32(0): + fol_ok = self._wait_followers(ws, gen) + if fol_ok != Int32(0): + self._publish_dir( + ws, + gen, + Int32(1), + Int32(K_DONE), + Int32(P_T1), + Uint64(0), + Uint64(0), + Uint64(0), + ) + A._wait(bars + B_LST, Int32(0)) + if ctid == Int32(0): + self._stamp(mStamps, cta, 85) + # Make every reader finish C/C1 before the rare path reuses COFF. + L.bar(BAR_CTL, NT) + if rare != Int32(0): + if cutlass.const_expr(self.lean): + st = Int32(ST_SKIP) + C = Int32(0) + else: + st, path, C, lo, hi, mm, rounds = self._acquire_rare( + arena, + cta, + d, + ctid, + ws, + gen, + n, + Kq, + bars, + mRegion, + mHist, + mStamps, + mCtl, + ab, + C1, + T, + HIC, + T3, + SMAX, + lo, + hi, + mm, + fol_ok, + ) + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + self._stamp(mStamps, cta, ST_M_COPY) + return (st, path, C, lo, hi, mm, C1, rounds) + + @cute.jit + def _acquire_rare( + self, + arena, + cta, + d, + ctid, + ws, + gen, + n, + Kq, + bars, + mRegion, + mHist, + mStamps, + mCtl, + ab, + C1, + T, + HIC, + T3, + SMAX, + lo, + hi, + mm, + fol_ok, + ): + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + is_t0 = d == Int32(0) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + s_red = _sm_tensor(arena, T_OFF_RED, Uint32, 64) + s_coff = _sm_tensor(arena, T_OFF_COFF, Int32, 160) + s_cu1 = _sm_tensor(arena, T_OFF_CU1, Int32, 160) + s_cu2 = _sm_tensor(arena, T_OFF_CU2, Int32, 160) + lbase = Int32(cute.recast_ptr(arena + T_OFF_LIST, dtype=Int32).toint()) + rg = mRegion.iterator.toint() + st = Int32(ST_GO) + path = Int32(P_T1) + rounds = Int32(0) + seq = Int32(0) + rb = Int32(0) + C = C1 + want_t12 = Int32(0) + want_drs = Int32(0) + fm = Int32(0) + if cutlass.const_expr(self.debug): + fm = mCtl[0] + t3ok = Int32(0) + if T3 > Float32(NEG_INF): + if T3 < T: + t3ok = Int32(1) + if is_t0: + if ab == Int32(0): + abf = Int32(0) + if ctid == Int32(0): + if fol_ok == Int32(0): + if self._wait_followers(ws, gen) == Int32(0): + abf = Int32(1) + ab = self._wg_any(abf, ctid, s_red, BAR_CTL) + if ab != Int32(0): + st = Int32(ST_SKIP) + path = Int32(P_ABORT) + else: + if C1 < Kq and t3ok != Int32(0): + want_t12 = Int32(1) + else: + want_drs = Int32(1) + if fm == Int32(1): + if t3ok != Int32(0): + want_t12 = Int32(1) + want_drs = Int32(0) + else: + want_drs = Int32(1) + if fm == Int32(2): + want_t12 = Int32(0) + want_drs = Int32(1) + if want_t12 != Int32(0): + seq = seq + Int32(1) + rounds = rounds + Int32(1) + if is_t0 and ctid == Int32(0): + klo = Uint64(L.fkey(T3)) << Uint64(18) + khi = Uint64(L.fkey(T)) << Uint64(18) + self._publish_dir(ws, gen, seq, Int32(K_PUB), Int32(P_T12), klo, khi, Uint64(1)) + ma, mb2, ab2 = self._poll_counts(ws, gen, Int32(1), ctid) + ab2 = self._wg_any(ab2, ctid, s_red, BAR_CTL) + ua = Int32(0) + ub = Int32(0) + if ctid < Int32(NS): + ua = s_cu2[ctid] + ma + if ctid + Int32(NT) < Int32(NS): + ub = s_cu2[ctid + Int32(NT)] + mb2 + ya, yb, yc, yd, Ua, Ub, Uc, Ud = self._scan4(ua, ub, ma + mb2, Int32(0), ctid, arena) + Ct = C1 + Uc + if ab2 != Int32(0): + st = Int32(ST_SKIP) + path = Int32(P_ABORT) + elif Ct >= Kq and Ua + Ub <= Int32(CAPL): + path = Int32(P_T12) + C = Ua + Ub + lo, hi = self._band_range(T3, HIC, SMAX) + if ctid < Int32(NS): + s_coff[ctid] = ya + s_cu1[ctid] = ua + if ctid + Int32(NT) < Int32(NS): + s_coff[ctid + Int32(NT)] = Ua + yb + s_cu1[ctid + Int32(NT)] = ub + seq = seq + Int32(1) + if is_t0 and ctid == Int32(0): + self._publish_dir( + ws, gen, seq, Int32(K_DONE), Int32(P_T12), Uint64(0), Uint64(0), Uint64(0) + ) + else: + want_drs = Int32(1) + L.bar(BAR_CTL, NT) + if want_drs != Int32(0): + if st == Int32(ST_GO): + ab_drs = Int32(0) + if is_t0: + seq, rnd, ab_drs = self._drs_lead(arena, ctid, ws, gen, seq, Kq, mHist) + rounds = rounds + rnd + ma, mb2, ab3 = self._poll_counts(ws, gen, Int32(2), ctid) + ab3 = self._wg_any(ab3 | ab_drs, ctid, s_red, BAR_CTL) + ya, yb, yc, yd, Ua, Ub, Uc, Ud = self._scan4( + ma, mb2, Int32(0), Int32(0), ctid, arena + ) + if ab3 != Int32(0): + st = Int32(ST_SKIP) + path = Int32(P_ABORT) + else: + path = Int32(P_DRS) + C = Ua + Ub + rb = Int32(CAPR) + mm = Int32(1) + if ctid < Int32(NS): + s_coff[ctid] = ya + s_cu1[ctid] = ma + if ctid + Int32(NT) < Int32(NS): + s_coff[ctid + Int32(NT)] = Ua + yb + s_cu1[ctid + Int32(NT)] = mb2 + seq = seq + Int32(1) + if is_t0 and ctid == Int32(0): + self._publish_dir( + ws, + gen, + seq, + Int32(K_DONE), + Int32(P_DRS), + Uint64(0), + Uint64(0), + Uint64(0), + ) + L.bar(BAR_CTL, NT) + if st != Int32(ST_GO): + C = Int32(0) + if is_t0 and ctid == Int32(0): + self._publish_dir( + ws, + gen, + seq + Int32(1), + Int32(K_DONE), + Int32(P_ABORT), + Uint64(0), + Uint64(0), + Uint64(0), + ) + if ctid == Int32(0): + misc[12] = path + if st != Int32(ST_GO): + misc[13] = Int32(1) + self._flag(ws, gen, Int32(E_ABORTED)) + L.bar(BAR_CTL, NT) + if st == Int32(ST_GO): + self._copy_runs(ctid, rg, rb, lbase, s_cu1, s_coff) + cute.arch.cp_async_commit_group() + cute.arch.cp_async_wait_group(0) + return (st, path, C, lo, hi, mm, rounds) + + @cute.jit + def _drs_lead(self, arena, ctid, ws, gen, seq, Kq, mHist): + NT: cutlass.Constexpr[int] = 128 + NS = self.ns + s_hist = _sm_tensor(arena, T_OFF_HIST, Int32, NB_DRS) + s_res = _sm_tensor(arena, T_OFF_RES, Int32, 16) + pref = Uint64(0) + plen = Int32(0) + acc = Int32(0) + need = Kq + fin = Int32(0) + ab = Int32(0) + rounds = Int32(0) + while fin == Int32(0): + seq = seq + Int32(1) + rounds = rounds + Int32(1) + gh = mHist.iterator.toint() + Int64(seq) * Int64(NB_DRS * 4) + for z_ in cutlass.range_constexpr(NB_DRS // NT): + L.st_g_u32(gh + Int64(ctid + Int32(z_ * NT)) * Int64(4), Uint32(0)) + if ctid == Int32(0): + L.st_g_u64(self._w(ws, W_RC + seq), Uint64(0)) + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + self._publish_dir( + ws, + gen, + seq, + Int32(K_HIST), + Int32(P_DRS), + pref, + Uint64(0), + Uint64(Uint32(plen)) << Uint64(8), + ) + okr = self._poll_word_eq(ws, gen, self._w(ws, W_RC + seq), Uint64(NS)) + s_res[7] = okr + L.fence_acq_rel_gpu() + L.bar(BAR_CTL, NT) + if s_res[7] == Int32(0): + ab = Int32(1) + fin = Int32(1) + else: + L.fence_acq_rel_gpu() + hv = [] + for z_ in cutlass.range_constexpr(NB_DRS // NT): + hv.append(L.ld_cg_i32(gh + Int64(ctid + Int32(z_ * NT)) * Int64(4))) + for z_ in cutlass.range_constexpr(NB_DRS // NT): + s_hist[ctid + Int32(z_ * NT)] = hv[z_] + L.bar(BAR_CTL, NT) + L.find_cross(s_hist, need, ctid, s_res, NB_DRS) + L.bar(BAR_CTL, NT) + dg = s_res[L.RES_B] + ad = s_res[L.RES_ABOVE] + md = s_res[L.RES_M] + L.bar(BAR_CTL, NT) + acc = acc + ad + need = need - ad + pref = pref << Uint64(DRS_DIG) | Uint64(Uint32(dg)) + plen = plen + Int32(DRS_DIG) + if acc + md <= Int32(CAPL) or plen >= Int32(K50_BITS): + fin = Int32(1) + if ab == Int32(0): + seq = seq + Int32(1) + if ctid == Int32(0): + klo = pref << Uint64(Int32(K50_BITS) - plen) + self._publish_dir( + ws, + gen, + seq, + Int32(K_PUB), + Int32(P_DRS), + klo, + Uint64(1) << Uint64(K50_BITS), + Uint64(2), + ) + return (seq, rounds, ab) + + @cute.jit + def _wg_minmax_u64(self, kmn, kmx, s_red, ctid): + lane = ctid % Int32(32) + wid = ctid // Int32(32) + mh = Uint32(kmn >> Uint64(32)) + ml = Uint32(kmn & Uint64(4294967295)) + wmh = L.warp_min_u32(mh) + c1_ = Uint32(4294967295) + if mh == wmh: + c1_ = ml + wml = L.warp_min_u32(c1_) + xh = Uint32(kmx >> Uint64(32)) + xl = Uint32(kmx & Uint64(4294967295)) + wxh = L.warp_max_u32(xh) + c2_ = Uint32(0) + if xh == wxh: + c2_ = xl + wxl = L.warp_max_u32(c2_) + if lane == Int32(0): + s_red[Int32(16) + wid * Int32(4)] = wmh + s_red[Int32(17) + wid * Int32(4)] = wml + s_red[Int32(18) + wid * Int32(4)] = wxh + s_red[Int32(19) + wid * Int32(4)] = wxl + L.bar(BAR_CTL, 128) + gmh = Uint32(4294967295) + gml = Uint32(4294967295) + gxh = Uint32(0) + gxl = Uint32(0) + for w_ in cutlass.range_constexpr(4): + a_ = Uint32(s_red[16 + 4 * w_]) + b_ = Uint32(s_red[17 + 4 * w_]) + c_ = Uint32(s_red[18 + 4 * w_]) + e_ = Uint32(s_red[19 + 4 * w_]) + if a_ < gmh: + gmh = a_ + gml = b_ + elif a_ == gmh: + if b_ < gml: + gml = b_ + if c_ > gxh: + gxh = c_ + gxl = e_ + elif c_ == gxh: + if e_ > gxl: + gxl = e_ + L.bar(BAR_CTL, 128) + return (Uint64(gmh) << Uint64(32) | Uint64(gml), Uint64(gxh) << Uint64(32) | Uint64(gxl)) + + @cute.jit + def _sel_list( + self, + arena, + cta, + ctid, + C, + Kw, + lo, + hi, + mm, + fnar, + real, + st, + bars, + n, + s_idx, + mBtC, + mbc, + mStamps, + d, + ): + NT: cutlass.Constexpr[int] = 128 + NWC: cutlass.Constexpr[int] = NT // 32 + lane = ctid % Int32(32) + wid = ctid // Int32(32) + misc = _sm_tensor(arena, T_OFF_MISC, Int32, 64) + s_res = _sm_tensor(arena, T_OFF_RES, Int32, 16) + s_red = _sm_tensor(arena, T_OFF_RED, Uint32, 64) + s_wc = _sm_tensor(arena, T_OFF_WC, Int32, 64) + s_hist = _sm_tensor(arena, T_OFF_HIST, Int32, NB_SEL) + s_phist = _sm_tensor(arena, T_OFF_HIST, Uint64, NB_INITIAL) + s_outs = _sm_tensor(arena, T_OFF_OUTS, Int32, K_TOP) + s_ck = _sm_tensor(arena, T_OFF_CK, Uint64, QUADC) + s_cs = _sm_tensor(arena, T_OFF_CS, Int32, QUADC) + s_btc = _sm_tensor(arena, T_OFF_BTC, Int32, BTC_CAP) + s_crow = _sm_tensor(arena, T_OFF_CROW, Int32, QUADC) + s_lst = _sm_tensor(arena, T_OFF_LIST, Uint64, CAPL) + mret = Int32(0) + info = Int32(0) + Bb = Int32(-1) + Bw = Int32(-1) + nout = Int32(0) + Sw = Int32(0) + Sx = Int32(0) + pw = Int32(0) + px = Int32(0) + need = Int32(0) + sc = Float32(0.0) + CW = (C + Int32(NT - 1)) // Int32(NT) * Int32(32) + c0 = wid * CW + c1 = cutlass.min(C, c0 + CW) + if st == Int32(ST_GO): + nout = cutlass.min(Kw, C) + if mm != Int32(0): + kmn = Uint32(4294967295) + kmx = Uint32(0) + kq = ctid + while kq < C: + e_ = Uint64(s_lst[kq]) + kb_ = L.fkey_bits(Uint32(e_ & Uint64(4294967295))) + if Uint32(e_ >> Uint64(32)) != Uint32(DUMMY_GPOS): + if kb_ < kmn: + kmn = kb_ + if kb_ > kmx: + kmx = kb_ + kq = kq + Int32(NT) + gmn, gmx = L._block_min_max_u32(kmn, kmx, s_red, ctid, NT, BAR_CTL) + lo = L.invkey(gmn) + hi = L.invkey(gmx) + sc = bin_scale(lo, hi) * Float32(0.5) + for z_ in cutlass.range_constexpr(NB_INITIAL // NT): + s_phist[ctid + Int32(z_ * NT)] = Uint64(0) + L.bar(BAR_CTL, NT) + hpair = wid >> Int32(1) + hinc = Int32(1) << ((wid & Int32(1)) * Int32(16)) + i4 = c0 + lane + while i4 < c1: + bq_ = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + icl = cutlass.min(i4 + Int32(32 * q), c1 - Int32(1)) + bq_[q] = L._vbin(Uint64(s_lst[icl]), lo, sc, NB_INITIAL) + for q in cutlass.range_constexpr(4): + if i4 + Int32(32 * q) < c1: + cute.arch.red( + s_hist.iterator + bq_[q] * Int32(2) + hpair, + hinc, + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + i4 = i4 + Int32(128) + L.bar(BAR_CTL, NT) + if ctid == Int32(0) and real: + self._stamp(mStamps, cta, 87) + st = self._warm_abort(real, st, ctid, bars, misc) + if st == Int32(ST_GO): + find_cross_warp_counts(s_phist, Kw, ctid, s_res, s_wc, NB_INITIAL) + L.bar(BAR_CTL, NT) + Bb = s_res[L.RES_B] + above = s_res[L.RES_ABOVE] + mret = s_res[L.RES_M] + need = Kw - above + Bw = Bb + Sw = above + Sx = mret + if need >= mret: + Bw = Bb - Int32(1) + Sw = above + mret + Sx = Int32(0) + else: + info = Int32(1) + pw = s_wc[wid] + px = s_wc[Int32(NWC) + wid] + if ctid == Int32(0) and real: + self._stamp(mStamps, cta, 88) + st = self._warm_abort(real, st, ctid, bars, misc) + if st == Int32(ST_GO): + if real: + A._wait(bars + B_BTC, Int32(0)) + npg_s = ( + cutlass.min((n + Int32(31)) // Int32(32), cutlass.min(mbc, Int32(BTC_CAP))) + // Int32(4) + * Int32(4) + ) + lm = Int32(cute.arch.lanemask_lt()) + nkey = Int32(0) + if Sw < Kw: + if Sx > Int32(QUADC) or fnar != Int32(0): + nkey = Int32(1) + # s_nkey aliases KV ring slots 0-2: wait for their first release by this CTA's QK. With rs24, row + # group 1 (odd d: tiles 3 and 4) fills the ring only after this selection's B_EAR / B_SEL arrive, + # so its slots are still unused here and are never released before then (waiting deadlocks). + rg0_ = Int32(1) + if cutlass.const_expr(self.rs24): + rg0_ = Int32(1) - (d & Int32(1)) + if rg0_ != Int32(0): + for sl_ in cutlass.range_constexpr(3): + A._wait(bars + (B_KVE + sl_), Int32(0)) + s_nkey = _sm_tensor(arena, T_OFF_NKEY, Uint64, CAPL) + kb = c0 + while kb < c1: + sl = kb + lane + e = Uint64(s_lst[cutlass.min(sl, c1 - Int32(1))]) + fw = Int32(0) + fc = Int32(0) + gp = Int32(Uint32(e >> Uint64(32))) + if sl < c1: + bq = L._vbin(e, lo, sc, NB_INITIAL) + if bq > Bw: + fw = Int32(1) + elif bq == Bb: + fc = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fw != Int32(0))) + mc = Int32(cute.arch.vote_ballot_sync(fc != Int32(0))) + if fw != Int32(0) or fc != Int32(0): + row = self._k3row(gp, npg_s, s_btc, mBtC, mbc, real) + if fw != Int32(0): + po = pw + Int32(cute.arch.popc(mw & lm)) + if po < Kw: + s_outs[po] = gp + (s_idx + Int32(128) + po).store(row) + else: + pc_ = px + Int32(cute.arch.popc(mc & lm)) + if pc_ < Int32(QUADC): + s_ck[pc_] = L.entry_key(e) + s_cs[pc_] = gp + s_crow[pc_] = row + if nkey != Int32(0): + s_nkey[pc_] = L.entry_key(e) + pw = pw + Int32(cute.arch.popc(mw)) + px = px + Int32(cute.arch.popc(mc)) + kb = kb + Int32(32) + L.bar(BAR_CTL, NT) + if cutlass.const_expr(self.gjoin): + if real and Sw >= Int32(384) and nkey == Int32(0): + # The first three compressed tiles are exact winners. All + # ring-aliased selection state is dead on this path. + cute.arch.fence_proxy("async.shared", space="cta") + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + misc[15] = Int32(1) + prims.mbarrier_arrive(bars + B_EAR) + if ctid == Int32(0) and real: + self._stamp(mStamps, cta, 70) + if Sw < Kw: + if Sx <= Int32(32) and fnar == Int32(0): + if ctid < Int32(32): + kq_ = Uint64(0) + if ctid < Sx: + kq_ = Uint64(s_ck[ctid]) + khi = Uint32(kq_ >> Uint64(32)) + klo = Uint32(kq_ & Uint64(4294967295)) + r_ = Int32(0) + for j_ in cutlass.range(Sx, unroll=1): + ohi = cute.arch.shuffle_sync(khi, Int32(j_)) + olo = cute.arch.shuffle_sync(klo, Int32(j_)) + if Int32(j_) < Sx: + if ohi > khi: + r_ = r_ + Int32(1) + elif ohi == khi: + if olo > klo: + r_ = r_ + Int32(1) + if ctid < Sx: + if r_ < Kw - Sw: + s_outs[Sw + r_] = s_cs[ctid] + (s_idx + Int32(128) + Sw + r_).store(s_crow[ctid]) + elif Sx <= Int32(QUADC) and fnar == Int32(0): + i = ctid + while i < Sx: + ki = Uint64(s_ck[i]) + r_ = Int32(0) + jq = Int32(0) + while jq < Sx: + if Uint64(s_ck[jq]) > ki: + r_ = r_ + Int32(1) + jq = jq + Int32(1) + if r_ < Kw - Sw: + s_outs[Sw + r_] = s_cs[i] + (s_idx + Int32(128) + Sw + r_).store(s_crow[i]) + i = i + Int32(NT) + else: + info = Int32(2) + if cutlass.const_expr(not self.lean): + self._narrow( + arena, + ctid, + Sx, + Sw, + Kw - Sw, + npg_s, + mBtC, + mbc, + real, + s_idx, + mStamps, + cta, + ) + L.bar(BAR_CTL, NT) + return (st, mret, info, Bb, nout) + + @cute.jit + def _pmask(self, pref, plen): + pm = Uint64(0) + pv = Uint64(0) + if plen > Int32(0): + pm = Uint64(18446744073709551615) << Uint64(Int32(64) - plen) + pv = pref << Uint64(Int32(64) - plen) + return (pm, pv) + + @cute.jit + def _narrow(self, arena, ctid, m, Sw, need, npg_s, mBtC, mbc, real, s_idx, mStamps, cta): + NT: cutlass.Constexpr[int] = 128 + lane = ctid % Int32(32) + wid = ctid // Int32(32) + s_res = _sm_tensor(arena, T_OFF_RES, Int32, 16) + s_red = _sm_tensor(arena, T_OFF_RED, Uint32, 64) + s_wc = _sm_tensor(arena, T_OFF_WC, Int32, 64) + s_hist = _sm_tensor(arena, T_OFF_HIST, Int32, NB_SEL) + s_outs = _sm_tensor(arena, T_OFF_OUTS, Int32, K_TOP) + s_btc = _sm_tensor(arena, T_OFF_BTC, Int32, BTC_CAP) + s_key = _sm_tensor(arena, T_OFF_NKEY, Uint64, CAPL) + L.bar(BAR_CTL, NT) + if ctid == Int32(0): + self._stamp(mStamps, cta, 110) + plen = Int32(0) + pref = Uint64(0) + needr = need + done = Int32(0) + lmk = Int32(cute.arch.lanemask_lt()) + nit = (m + Int32(NT * 4 - 1)) // Int32(NT * 4) + while done == Int32(0): + pm0, pv0 = self._pmask(pref, plen) + kmn = Uint64(18446744073709551615) + kmx = Uint64(0) + jj = Int32(0) + while jj < nit: + i0 = jj * Int32(NT * 4) + ctid + kq_ = [] + for q in cutlass.range_constexpr(4): + kq_.append(Uint64(s_key[cutlass.min(i0 + Int32(NT * q), m - Int32(1))])) + for q in cutlass.range_constexpr(4): + if i0 + Int32(NT * q) < m: + if kq_[q] & pm0 == pv0: + if kq_[q] < kmn: + kmn = kq_[q] + if kq_[q] > kmx: + kmx = kq_[q] + jj = jj + Int32(1) + gmn, gmx = self._wg_minmax_u64(kmn, kmx, s_red, ctid) + if ctid == Int32(0): + self._stamp(mStamps, cta, 111) + xr = gmn ^ gmx + cpl = Int32(64) + if xr != Uint64(0): + cpl = clz_u64(xr) + if cpl > plen: + plen = cpl + pref = gmn >> Uint64(Int32(64) - plen) + if plen >= Int32(64): + done = Int32(1) + if done == Int32(0): + nbd = cutlass.min(Int32(10), Int32(64) - plen) + shift = Uint64(Int32(64) - plen - nbd) + pm1, pv1 = self._pmask(pref, plen) + dmask = Uint64((Int32(1) << nbd) - Int32(1)) + for z_ in cutlass.range_constexpr(NB_SEL // NT): + s_hist[ctid + Int32(z_ * NT)] = Int32(0) + L.bar(BAR_CTL, NT) + jj = Int32(0) + while jj < nit: + i0 = jj * Int32(NT * 4) + ctid + dgs = [] + for q in cutlass.range_constexpr(4): + kq = i0 + Int32(NT * q) + k_ = Uint64(s_key[cutlass.min(kq, m - Int32(1))]) + dg = Int32(NB_SEL) + if kq < m: + if k_ & pm1 == pv1: + dg = Int32(Uint32(k_ >> shift & dmask)) + dgs.append(dg) + for q in cutlass.range_constexpr(4): + mm_ = match_any_b32(dgs[q]) + if dgs[q] != Int32(NB_SEL): + if mm_ & lmk == Int32(0): + cute.arch.red( + s_hist.iterator + dgs[q], + Int32(cute.arch.popc(mm_)), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + jj = jj + Int32(1) + L.bar(BAR_CTL, NT) + L.find_cross(s_hist, needr, ctid, s_res, NB_SEL) + L.bar(BAR_CTL, NT) + dB = s_res[L.RES_B] + dab = s_res[L.RES_ABOVE] + dm = s_res[L.RES_M] + L.bar(BAR_CTL, NT) + pref = pref << Uint64(nbd) | Uint64(Uint32(dB)) + plen = plen + nbd + needr = needr - dab + if ctid == Int32(0): + if cutlass.const_expr(self.stamps): + rr_ = cutlass.min(plen // Int32(8), Int32(7)) + (mStamps.iterator + cta * NSTAMP + Int32(112) + rr_).store( + Int64(L.gtimer()) + ) + if needr >= dm or plen >= Int32(64): + done = Int32(1) + if ctid == Int32(0): + self._stamp(mStamps, cta, 120) + thr = pref + if plen < Int32(64): + thr = pref << Uint64(Int32(64) - plen) + lm = Int32(cute.arch.lanemask_lt()) + CW = (m + Int32(NT * 4 - 1)) // Int32(NT * 4) * Int32(128) + e0 = wid * CW + e1 = cutlass.min(m, e0 + CW) + cnt = Int32(0) + kb = e0 + while kb < e1: + fs = [] + for q in cutlass.range_constexpr(4): + sl = kb + Int32(32 * q) + lane + k_ = Uint64(s_key[cutlass.min(sl, e1 - Int32(1))]) + f2 = Int32(0) + if sl < e1: + if k_ >= thr: + f2 = Int32(1) + fs.append(f2) + for q in cutlass.range_constexpr(4): + cnt = cnt + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(fs[q] != Int32(0)))) + kb = kb + Int32(128) + ex2, tot2 = L._warp_prefix(cnt, s_wc, ctid, NT, BAR_CTL) + p2 = Sw + ex2 + kb = e0 + while kb < e1: + ks = [] + for q in cutlass.range_constexpr(4): + ks.append(Uint64(s_key[cutlass.min(kb + Int32(32 * q) + lane, e1 - Int32(1))])) + for q in cutlass.range_constexpr(4): + sl = kb + Int32(32 * q) + lane + f2 = Int32(0) + if sl < e1: + if ks[q] >= thr: + f2 = Int32(1) + m2 = Int32(cute.arch.vote_ballot_sync(f2 != Int32(0))) + if f2 != Int32(0): + so = p2 + Int32(cute.arch.popc(m2 & lm)) + gp = Int32(Uint32(4294967295) - Uint32(ks[q] & Uint64(4294967295))) + if so < Int32(K_TOP): + s_outs[so] = gp + (s_idx + Int32(128) + so).store( + self._k3row(gp, npg_s, s_btc, mBtC, mbc, real) + ) + p2 = p2 + Int32(cute.arch.popc(m2)) + kb = kb + Int32(128) + L.bar(BAR_CTL, NT) + + +_COMPILED = {} + + +def compile_mk(mk: SpecDsaMegakernel): + """Compile ``mk`` with TVM-FFI over symbolic shapes; returns the callable that ``op.run`` launches.""" + key = tuple( + sorted(((k, v) for k, v in vars(mk).items() if isinstance(v, (int, float, bool, str)))) + ) + if key in _COMPILED: + return _COMPILED[key] + rt = cute.runtime + s = cute.sym_int + fp4 = mk.fp4 + block_bytes = mk.phys_block_kv * ((mk.head_dim // 2 if fp4 else mk.head_dim) + 4) + fk = [ + rt.make_fake_tensor(cutlass.Uint8, (s(), block_bytes), stride=(cute.sym_int64(), 1)), + rt.make_fake_compact_tensor( + cutlass.Uint8, (64, 64 if fp4 else 128, mk.nrows), stride_order=(1, 0, 2) + ), + rt.make_fake_compact_tensor(cutlass.Float32, (64, mk.nrows), stride_order=(0, 1)), + rt.make_fake_compact_tensor(Int32, (mk.nrows, s()), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (mk.nrows,), stride_order=(0,)), + rt.make_fake_compact_tensor(Int32, (s(),), stride_order=(0,)), + rt.make_fake_compact_tensor( + cutlass.Uint8, (mk.nrows, 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ), + rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ), + rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ), + rt.make_fake_compact_tensor(Int32, (mk.nrows, 128), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (mk.nrows, s()), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (mk.nrows, s()), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Float32, (64,), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int32, (mk.nrows,), stride_order=(0,)), + rt.make_fake_compact_tensor(Int32, (mk.nrows, 512), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (mk.nrows, 640), stride_order=(1, 0)), + rt.make_fake_compact_tensor( + cutlass.BFloat16, (mk.nrows, 64 * 512), stride_order=(1, 0), assumed_align=128 + ), + rt.make_fake_compact_tensor(Int64, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int32, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int64, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int64, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Float32, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int64, (s(),), stride_order=(0,), assumed_align=16), + rt.make_fake_compact_tensor(Int32, (16 * mk.nrows,), stride_order=(0,)), + ] + stream = rt.make_fake_stream(use_tvm_ffi_env_stream=True) + c = cute.compile( + mk, + *fk, + Int32(1), + Float32(1.0), + stream, + *( + (rt.make_fake_compact_tensor(Int32, (64, mk.nrows), stride_order=(0, 1)),) + if fp4 + else () + ), + options="--enable-tvm-ffi --generate-line-info", + ) + _COMPILED[key] = c + return c + + +def ladder_host(n: int): + import numpy as np + + k = K_TOP + if n <= k: + return (0, 1) + x6 = 6 * n + ri = int(math.isqrt(x6)) + r6 = ri + 1 if x6 - ri * ri > ri else ri + aim = max(PLAN["aim_base"], r6) + aim = max(aim, PLAN["amin"]) + aim = min(aim, PLAN["scap"] >> 1) + aim = max(aim, k) + n4w = n >> 2 + gate = 1 if n > PLAN["scap"] else 0 + if n4w < 4: + gate = 0 + if not gate: + return (0, 1) + f32 = np.float32 + sel = int(f32(PLAN["sfac"] * n) * (f32(1.0) / f32(aim))) + sel = max(sel, 256) + sel = min(sel, n >> 1) + pairs = max(sel >> 3, 1) + half = max(n4w >> 1, 1) + pairs = min(pairs, half) + ss2 = max(int(f32(half) * (f32(1.0) / f32(pairs))), 1) + smp = int(f32(half) * (f32(1.0) / f32(ss2))) + if smp * ss2 > half: + smp -= 1 + return (max(smp, 1), ss2) + + +_SMP_MAX = None + + +def ladder_max_smp() -> int: + global _SMP_MAX + if _SMP_MAX is None: + _SMP_MAX = max((ladder_host(n)[0] for n in range(N_MAX - 4096, N_MAX + 1))) + return _SMP_MAX diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_attention.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_attention.py new file mode 100644 index 000000000000..47243a1b7536 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_attention.py @@ -0,0 +1,3581 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""specDSA megakernel, attention: the sparse MLA over the selected compressed-KV rows, the sliding-window rows and +the attention sink (TMA gathers, tcgen05 MMA, softmax and correction warps). + +The first half is the stand-alone attention engine, the second the roles that the team CTAs of the megakernel run. Where +both define a name differently the roles' name is kept and the engine's carries an ``_engine`` (``_ENGINE``) suffix. + +The constants that follow from the model (heads, KV row size, window, top-K) are defined from the ``DS_V4_FLASH`` spec +of ``config.py``. +""" + +from __future__ import annotations + +import math + +import cuda.bindings.driver as cuda_driver +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as cuda +import torch +from cutlass import Boolean, Float32, Int32, Int64, Uint32 +from cutlass._mlir.dialects import llvm as _llvm +from cutlass.cutlass_dsl import T as _T +from cutlass.cutlass_dsl import dsl_user_op +from cutlass.cutlass_dsl import dsl_user_op as _dsl_user_op +from cutlass.experimental import primitives as prims + +from . import megakernel_lib as L +from .config import DS_V4_FLASH as SPEC + +# ==================================================================================================================== +# Sparse MLA building blocks shared by the attention roles: Q / KV tensor maps, tcgen05 MMA and softmax helpers. +# ==================================================================================================================== + +HEADS = SPEC.attn_heads +LATENT = SPEC.kv_dim +WINDOW = SPEC.window +TOPK = SPEC.topk +NROWS = WINDOW + TOPK +SLICE = 128 +NSLICE = LATENT // SLICE +Q_SLICE_BYTES = HEADS * SLICE +Q_BYTES = HEADS * LATENT +LOG2_E = 1.4426950408889634 +LOG2_448 = 8.8073549 +NEG_FLT_MAX = -3.4028235e38 +PANEL1 = 16 << 16 +TMEM_COLS = 512 +TMEM_O = 256 +REG_SOFTMAX = 184 +REG_CORR = 232 +REG_OTHER = 48 +W_CORR0 = 4 +W_MMA = 8 +W_QLOAD = 9 +W_GATHER0 = 10 +NGW_ENGINE = 4 +THREADS = 512 +E4M3 = cutlass.Float8E4M3FN +BF16 = cutlass.BFloat16 + + +@cute.jit +def _wait(mbar, phase): + while not prims.mbarrier_try_wait_parity(mbar, phase): + pass + + +@cute.jit +def _tma_gather4(smem_dst, tma_desc, mbar, col, r0, r1, r2, r3) -> None: + bar = prims.cvta_to(mbar, prims.CvtaSpace.SHARED) + prims.inline_ptx_hl( + "{\n\t.reg .pred leader;\n\telect.sync _|leader, -1;\n\t@leader " + "cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes [{$r0}], [{$r1}, " + "{{$r2}, {$r3}, {$r4}, {$r5}, {$r6}}], [{$r7}];\n\t}", + read_only_args=[smem_dst, tma_desc, col, r0, r1, r2, r3, bar], + ) + + +@cute.jit +def _pack4_e4m3(v0: Float32, v1: Float32, v2: Float32, v3: Float32): + return cute.arch.inline_ptx( + "{\n .reg .b16 lo;\n .reg .b16 hi;\n cvt.rn.satfinite.e4m3x2.f32 lo, {$r1}, {$r0};\n " + "cvt.rn.satfinite.e4m3x2.f32 hi, {$r3}, {$r2};\n mov.b32 {$w0}, {lo, hi};\n}", + write_only_types=[Int32], + read_only_args=[v0, v1, v2, v3], + ) + + +@cute.jit +def _tmem_st_p_fp8(tmem_addr, regs, n: cutlass.Constexpr[int]) -> None: + body = ", ".join(("{$r%d}" % (i + 1) for i in range(n))) + cute.arch.inline_ptx( + f"tcgen05.st.sync.aligned.16x32bx2.x{n}.b32 [{{$r0}}], {n}, {{ {body} }};", + read_only_args=[tmem_addr] + [regs[i] for i in range(n)], + ) + + +@cute.jit +def _shfl_xor_f32(x: Float32, dist: cutlass.Constexpr[int]) -> Float32: + return Float32( + prims.shfl_sync( + thread_mask=4294967295, val=x, offset=dist, mask_and_clamp=31, kind=prims.Shfl.BFLY + ) + ) + + +@cute.jit +def _shfl_idx_i32(x: Int32, src) -> Int32: + return Int32( + prims.shfl_sync( + thread_mask=4294967295, val=x, offset=src, mask_and_clamp=31, kind=prims.Shfl.IDX + ) + ) + + +@dsl_user_op +def _gtimer(*, loc=None, ip=None): + return Int64( + _llvm.inline_asm( + _T.i64(), + [], + "mov.u64 $0, %globaltimer;", + "=l", + has_side_effects=True, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _stamp(tr, slot, cond) -> None: + if cond: + t = _gtimer() + cutlass.inttoptr(tr + Int64(slot) * Int64(8), mem_space=1, dtype=Int64).store(t) + + +@cute.jit +def _pack_bf16x2(v0: Float32, v1: Float32): + return cutlass.Vector.from_elements((v0, v1), Float32).to(BF16).bitcast(Int32)[0] + + +@cute.jit +def role_q_load_engine(tma_q, s_q, q_full, q_empty, row0, row_step, n_items): + for it in cutlass.range(n_items, unroll=1): + b = row0 + it * row_step + if it > Int32(0): + _wait(q_empty, it - Int32(1) & Int32(1)) + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(q_full, Q_BYTES) + for c in cutlass.range_constexpr(NSLICE): + prims.cp_async_bulk_tensor_shared_cta_global( + s_q + c * Q_SLICE_BYTES, tma_q.get_ptr(), [c * SLICE, 0, b], q_full + ) + + +@cute.jit +def role_gather( + tma_swa, + tma_cmp, + s_kv, + idx_ptr, + kv_full, + kv_empty, + gwarp, + row0, + row_step, + n_items, + lb, + tile_n: cutlass.Constexpr[int], + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + tr=None, +): + R: cutlass.Constexpr[int] = tile_n // NGW_ENGINE + per_warp: cutlass.Constexpr[int] = R // 4 + slot_bytes: cutlass.Constexpr[int] = tile_n * SLICE + lane = cute.arch.lane_idx() + total = n_items * Int32(ntiles) + nxt = Int32(0) + b0 = row0 + pos0 = lb + gwarp * Int32(R) + lane + if lane < Int32(R): + nxt = (idx_ptr + b0 * Int32(NROWS) + pos0).load() + for g in cutlass.range(total, unroll=1): + it = g // Int32(ntiles) + j = g - it * Int32(ntiles) + cur = nxt + list_start = lb + j * Int32(tile_n) + g1 = g + Int32(1) + if g1 < total: + it1 = g1 // Int32(ntiles) + j1 = g1 - it1 * Int32(ntiles) + b1 = row0 + it1 * row_step + if lane < Int32(R): + nxt = ( + idx_ptr + b1 * Int32(NROWS) + lb + j1 * Int32(tile_n) + gwarp * Int32(R) + lane + ).load() + use_swa = list_start < Int32(WINDOW) + for c in cutlass.range_constexpr(NSLICE): + k = g * Int32(NSLICE) + Int32(c) + slot = k % Int32(nslots) + ph = k // Int32(nslots) & Int32(1) + _wait(kv_empty + slot, ph ^ Int32(1)) + if gwarp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(kv_full + slot, slot_bytes) + dst0 = s_kv + slot * Int32(slot_bytes) + gwarp * Int32(R * SLICE) + for q in cutlass.range_constexpr(per_warp): + r0 = _shfl_idx_i32(cur, Int32(4 * q)) + r1 = _shfl_idx_i32(cur, Int32(4 * q + 1)) + r2 = _shfl_idx_i32(cur, Int32(4 * q + 2)) + r3 = _shfl_idx_i32(cur, Int32(4 * q + 3)) + if use_swa: + _tma_gather4( + dst0 + Int32(4 * q * SLICE), + tma_swa.get_ptr(), + kv_full + slot, + Int32(c * SLICE), + r0, + r1, + r2, + r3, + ) + else: + _tma_gather4( + dst0 + Int32(4 * q * SLICE), + tma_cmp.get_ptr(), + kv_full + slot, + Int32(c * SLICE), + r0, + r1, + r2, + r3, + ) + if cutlass.const_expr(tr is not None): + _stamp( + tr, Int32(10) + j, g < Int32(ntiles) and gwarp == Int32(0) and (lane == Int32(0)) + ) + _stamp( + tr, + Int32(100) + it * Int32(8) + j, + it < Int32(12) and gwarp == Int32(0) and (lane == Int32(0)), + ) + + +@cute.jit +def _pv_engine( + tmem, + s_kv, + g, + it, + j, + p_full, + o_corr, + o_free, + kv_empty, + s_empty, + o_full, + idesc_pv, + tile_n: cutlass.Constexpr[int], + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + v_lo=0, + nv: cutlass.Constexpr[int] = NSLICE, +): + slot_bytes: cutlass.Constexpr[int] = tile_n * SLICE + st = g & Int32(1) + _wait(p_full + st, g >> Int32(1) & Int32(1)) + if j > Int32(0): + _wait(o_corr, it * Int32(ntiles - 1) + j - Int32(1) & Int32(1)) + elif it > Int32(0): + _wait(o_free, it - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + acc = j > Int32(0) + for vv in cutlass.range_constexpr(nv): + v = Int32(v_lo) + Int32(vv) + k = g * Int32(NSLICE) + v + slot = k % Int32(nslots) + d_addr = tmem + Int32(TMEM_O) + v % Int32(2) * Int32(128) + (v >> Int32(1)) * Int32(PANEL1) + a_addr = tmem + st * Int32(tile_n) + Int32(tile_n // 4) + (v >> Int32(1)) * Int32(PANEL1) + vdesc = prims.Tcgen05SmemDesc.build( + s_kv + slot * Int32(slot_bytes), + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(tile_n // 32): + en = acc if cutlass.const_expr(kb == 0) else Boolean(True) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(kv_empty + slot, group=prims.CTAGroup.CTA_1) + if prims.elect_sync(): + prims.tcgen05_commit(s_empty + st, group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(o_full, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def role_mma( + tmem, + s_q, + s_kv, + q_full, + q_empty, + kv_full, + kv_empty, + s_full, + s_empty, + p_full, + o_corr, + o_free, + o_full, + n_items, + tile_n: cutlass.Constexpr[int], + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + tr=None, + v_lo=0, + nv: cutlass.Constexpr[int] = NSLICE, +): + slot_bytes: cutlass.Constexpr[int] = tile_n * SLICE + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=tile_n, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, a_major=0, b_major=1, n_dim=SLICE, m_dim=HEADS + ) + qdesc = prims.Tcgen05SmemDesc.build( + s_q, + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + lane = cute.arch.lane_idx() + for it in cutlass.range(n_items, unroll=1): + _wait(q_full, it & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(90), it == Int32(0) and lane == Int32(0)) + _stamp(tr, Int32(180) + it, it < Int32(12) and lane == Int32(0)) + for j in cutlass.range_constexpr(ntiles): + g = it * Int32(ntiles) + Int32(j) + st = g & Int32(1) + if g >= Int32(2): + _wait(s_empty + st, (g >> Int32(1)) - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + st * Int32(tile_n) + for c in cutlass.range_constexpr(NSLICE): + k = g * Int32(NSLICE) + Int32(c) + slot = k % Int32(nslots) + _wait(kv_full + slot, k // Int32(nslots) & Int32(1)) + kdesc = prims.Tcgen05SmemDesc.build( + s_kv + slot * Int32(slot_bytes), + leading_byte_offset=slot_bytes, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(SLICE // 32): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(c * Q_SLICE_BYTES + kb * 32), + kdesc.advance_start_address(kb * 32), + idesc_qk, + Boolean(c > 0 or kb > 0), + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(20 + j), it == Int32(0) and lane == Int32(0)) + if prims.elect_sync(): + prims.tcgen05_commit(s_full + st, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(j == ntiles - 1): + prims.tcgen05_commit(q_empty, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(j >= 1): + _pv_engine( + tmem, + s_kv, + g - Int32(1), + it, + Int32(j - 1), + p_full, + o_corr, + o_free, + kv_empty, + s_empty, + o_full, + idesc_pv, + tile_n, + ntiles, + nslots, + v_lo, + nv, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(70 + j - 1), it == Int32(0) and lane == Int32(0)) + _pv_engine( + tmem, + s_kv, + it * Int32(ntiles) + Int32(ntiles - 1), + it, + Int32(ntiles - 1), + p_full, + o_corr, + o_free, + kv_empty, + s_empty, + o_full, + idesc_pv, + tile_n, + ntiles, + nslots, + v_lo, + nv, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(70 + ntiles - 1), it == Int32(0) and lane == Int32(0)) + _stamp(tr, Int32(220) + it, it < Int32(12) and lane == Int32(0)) + + +@cute.jit +def role_softmax( + tmem, + s_full, + p_full, + s_stat, + s_fin, + fin_bar, + scale_log2: Float32, + n_items, + tile_n: cutlass.Constexpr[int], + ntiles: cutlass.Constexpr[int], + tr=None, +): + half_n: cutlass.Constexpr[int] = tile_n // 2 + npk: cutlass.Constexpr[int] = tile_n // 8 + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + head = warp * Int32(16) + (lane & Int32(15)) + lane_base = warp * Int32(32) << Int32(16) + for it in cutlass.range(n_items, unroll=1): + m_run = Float32(NEG_FLT_MAX) + l_run = Float32(0.0) + for j in cutlass.range(ntiles, unroll=1): + g = it * Int32(ntiles) + j + st = g & Int32(1) + _wait(s_full + st, g >> Int32(1) & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp( + tr, Int32(40) + j, it == Int32(0) and warp == Int32(0) and (lane == Int32(0)) + ) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + lane_base + st * Int32(tile_n) + s = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(s_addr, Float32), + num=half_n, + offset=Int64(half_n), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + for i in cutlass.range_constexpr(0, half_n, 4): + mx0 = cute.math.max(mx0, Float32(s[i]), ftz=True) + mx1 = cute.math.max(mx1, Float32(s[i + 1]), ftz=True) + mx2 = cute.math.max(mx2, Float32(s[i + 2]), ftz=True) + mx3 = cute.math.max(mx3, Float32(s[i + 3]), ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + neg_scaled = -scale_log2 * safe_max + bias = neg_scaled + Float32(LOG2_448) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for pk in cutlass.range_constexpr(npk): + x01 = cute.arch.fma_packed_f32x2( + (Float32(s[4 * pk]), Float32(s[4 * pk + 1])), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + x23 = cute.arch.fma_packed_f32x2( + (Float32(s[4 * pk + 2]), Float32(s[4 * pk + 3])), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = s_addr + Int32(tile_n // 4) + _tmem_st_p_fp8(p_addr, regs, npk) + _tmem_st_p_fp8(p_addr + Int32(PANEL1), regs, npk) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + exp_scale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if lane < Int32(16): + (s_stat + st * Int32(128) + head).store(old_max) + (s_stat + st * Int32(128) + Int32(64) + head).store(new_max) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(p_full + st) + if cutlass.const_expr(tr is not None): + _stamp( + tr, Int32(50) + j, it == Int32(0) and warp == Int32(0) and (lane == Int32(0)) + ) + l_tot = l_run + _shfl_xor_f32(l_run, 16) + fb = (it & Int32(1)) * Int32(128) + if lane < Int32(16): + (s_fin + fb + head).store(m_run) + (s_fin + fb + Int32(64) + head).store(l_tot) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(fin_bar) + + +@cute.jit +def _rescale_o(tmem, lane_base, scale: Float32): + for v in cutlass.range_constexpr(NSLICE): + o_addr = tmem + lane_base + Int32(TMEM_O + v % 2 * 128 + v // 2 * PANEL1) + for h in cutlass.range_constexpr(2): + ptr = prims.make_tmem_ptr(o_addr + Int32(32 * h), Float32) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, ptr, num=32, offset=Int64(64) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + vals = [] + for r in cutlass.range_constexpr(0, 32, 2): + pr = cute.arch.mul_packed_f32x2( + (Float32(o[r]), Float32(o[r + 1])), (scale, scale), ftz=False, rnd="rn" + ) + vals.append(pr[0]) + vals.append(pr[1]) + prims.tcgen05_st( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + cutlass.Vector.from_elements(tuple(vals), Float32), + offset=Int64(64), + ) + + +@cute.jit +def _correct_tile( + tmem, + lane_base, + head, + p_full, + o_full, + o_corr, + s_stat, + g, + it, + j, + scale_log2: Float32, + ntiles: cutlass.Constexpr[int], +): + st = g & Int32(1) + _wait(p_full + st, g >> Int32(1) & Int32(1)) + old_max = (s_stat + st * Int32(128) + head).load() + new_max = (s_stat + st * Int32(128) + Int32(64) + head).load() + _wait(o_full, g - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + scale = Float32(1.0) + if not ident: + scale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + skip = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip: + _rescale_o(tmem, lane_base, scale) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(o_corr) + + +@cute.jit +def _final_norm_engine( + final_max: Float32, reduced_sum: Float32, sink: Float32, scale_log2: Float32 +) -> Float32: + delta = sink * Float32(LOG2_E) - scale_log2 * final_max + attention_rescale = cute.math.exp2(-cute.math.max(delta, Float32(0)), approx=True) + sink_mass = cute.math.exp2(cute.math.min(delta, Float32(0)), approx=True) + sink_mass *= Float32(448.0) + return ( + Float32(1.0) + * attention_rescale + * cute.math.rcp(reduced_sum * attention_rescale + sink_mass, approx=True) + ) + + +@cute.jit +def role_correction_final( + tmem, + p_full, + o_full, + o_corr, + o_free, + s_stat, + s_fin, + fin_bar, + sink_ptr, + out_addr: Int64, + scale_log2: Float32, + row0, + row_step, + n_items, + ntiles: cutlass.Constexpr[int], + tr=None, +): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + sink = Float32((sink_ptr + head).load()) + for it in cutlass.range(n_items, unroll=1): + b = row0 + it * row_step + for j in cutlass.range_constexpr(1, ntiles): + g = it * Int32(ntiles) + Int32(j) + _correct_tile( + tmem, + lane_base, + head, + p_full, + o_full, + o_corr, + s_stat, + g, + it, + Int32(j), + scale_log2, + ntiles, + ) + if cutlass.const_expr(tr is not None): + _stamp( + tr, Int32(60 + j), it == Int32(0) and warp == Int32(0) and (lane == Int32(0)) + ) + g_last = it * Int32(ntiles) + Int32(ntiles - 1) + _wait(o_full, g_last & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(80), it == Int32(0) and warp == Int32(0) and (lane == Int32(0))) + _stamp(tr, Int32(160) + it, it < Int32(12) and warp == Int32(0) and (lane == Int32(0))) + _wait(fin_bar, it & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(240) + it, it < Int32(12) and warp == Int32(0) and (lane == Int32(0))) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + fb = (it & Int32(1)) * Int32(128) + final_max = (s_fin + fb + head).load() + reduced_sum = (s_fin + fb + Int32(64) + head).load() + norm = _final_norm_engine(final_max, reduced_sum, sink, scale_log2) + out_base = ( + out_addr + + Int64(b) * Int64(HEADS * LATENT * 2) + + Int64((head * Int32(LATENT) + half * Int32(64)) * Int32(2)) + ) + ob = [] + for v in cutlass.range_constexpr(NSLICE): + for hc in cutlass.range_constexpr(2): + o_addr = tmem + lane_base + Int32(TMEM_O + v % 2 * 128 + v // 2 * PANEL1 + 32 * hc) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for pi in cutlass.range_constexpr(16): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), + (Float32(o[2 * pi]), Float32(o[2 * pi + 1])), + ftz=False, + rnd="rn", + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(o_free) + for v in cutlass.range_constexpr(NSLICE): + for ch in cutlass.range_constexpr(8): + dst = cutlass.inttoptr( + out_base + Int64((v * SLICE + ch * 8) * 2), mem_space=1, dtype=Int32 + ) + dst.store( + cutlass.Vector.from_elements( + tuple((ob[v * 32 + ch * 4 + i] for i in range(4))), Int32 + ), + alignment=16, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(81), it == Int32(0) and warp == Int32(0) and (lane == Int32(0))) + _stamp(tr, Int32(200) + it, it < Int32(12) and warp == Int32(0) and (lane == Int32(0))) + + +@cute.jit +def _alloc_tmem(tmem_hold, warp): + if warp == Int32(W_MMA): + prims.tcgen05_alloc(tmem_hold.data_ptr(), TMEM_COLS, group=prims.CTAGroup.CTA_1) + prims.tcgen05_relinquish_alloc_permit(group=prims.CTAGroup.CTA_1) + + +@cute.kernel +def _vl_kernel( + tma_q: cutlass.GridConstant[cuda.TensorMap], + tma_swa: cutlass.GridConstant[cuda.TensorMap], + tma_cmp: cutlass.GridConstant[cuda.TensorMap], + idx: cute.Tensor, + sink: cute.Tensor, + out: cute.Tensor, + trace: cute.Tensor, + softmax_scale: Float32, + nslots: cutlass.Constexpr[int], + use_trace: cutlass.Constexpr[bool], + regs: cutlass.Constexpr[bool] = True, +): + tile_n: cutlass.Constexpr[int] = 128 + ntiles: cutlass.Constexpr[int] = NROWS // tile_n + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + cta, _, _ = cute.arch.block_idx() + grid, _, _ = cute.arch.grid_dim() + if cutlass.const_expr(use_trace): + _stamp( + trace.iterator.toint() + Int64(cta) * Int64(2048), + Int32(1), + warp == Int32(0) and cute.arch.lane_idx() == Int32(0), + ) + nrows_total = idx.shape[0] + n_items = (Int32(nrows_total) - cta + grid - Int32(1)) // grid + s_q = cutlass.Array(E4M3, Q_BYTES, space=cutlass.AddressSpace.smem, alignment=1024) + s_kv = cutlass.Array( + E4M3, nslots * tile_n * SLICE, space=cutlass.AddressSpace.smem, alignment=1024 + ) + s_stat = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + s_fin = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + q_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + q_empty = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + kv_full = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + kv_empty = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + s_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + s_empty = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + p_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + o_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_corr = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_free = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + fin_bar = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + tmem_hold = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=16) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_init(q_full.data_ptr(), 1) + prims.mbarrier_init(q_empty.data_ptr(), 1) + for i in cutlass.range_constexpr(nslots): + prims.mbarrier_init(kv_full.data_ptr() + i, 1) + prims.mbarrier_init(kv_empty.data_ptr() + i, 1) + for i in cutlass.range_constexpr(2): + prims.mbarrier_init(s_full.data_ptr() + i, 1) + prims.mbarrier_init(s_empty.data_ptr() + i, 1) + prims.mbarrier_init(p_full.data_ptr() + i, 4) + prims.mbarrier_init(o_full.data_ptr(), 1) + prims.mbarrier_init(o_corr.data_ptr(), 4) + prims.mbarrier_init(o_free.data_ptr(), 4) + prims.mbarrier_init(fin_bar.data_ptr(), 4) + prims.fence_mbarrier_init() + _alloc_tmem(tmem_hold, warp) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = tmem_hold[0] + scale_log2 = softmax_scale * Float32(LOG2_E) + tr = None + if cutlass.const_expr(use_trace): + tr = trace.iterator.toint() + Int64(cta) * Int64(2048) + _stamp(tr, Int32(0), warp == Int32(0) and cute.arch.lane_idx() == Int32(0)) + if warp < Int32(W_CORR0): + if cutlass.const_expr(regs): + prims.setmaxregister(REG_SOFTMAX, prims.SetMaxRegisterAction.INCREASE) + role_softmax( + tmem, + s_full.data_ptr(), + p_full.data_ptr(), + s_stat.data_ptr(), + s_fin.data_ptr(), + fin_bar.data_ptr(), + scale_log2, + n_items, + tile_n, + ntiles, + tr, + ) + elif warp < Int32(W_MMA): + if cutlass.const_expr(regs): + prims.setmaxregister(REG_CORR, prims.SetMaxRegisterAction.INCREASE) + role_correction_final( + tmem, + p_full.data_ptr(), + o_full.data_ptr(), + o_corr.data_ptr(), + o_free.data_ptr(), + s_stat.data_ptr(), + s_fin.data_ptr(), + fin_bar.data_ptr(), + sink.iterator.raw_ptr(), + out.iterator.toint(), + scale_log2, + cta, + grid, + n_items, + ntiles, + tr, + ) + elif warp == Int32(W_MMA): + if cutlass.const_expr(regs): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_mma( + tmem, + s_q.data_ptr(), + s_kv.data_ptr(), + q_full.data_ptr(), + q_empty.data_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + s_full.data_ptr(), + s_empty.data_ptr(), + p_full.data_ptr(), + o_corr.data_ptr(), + o_free.data_ptr(), + o_full.data_ptr(), + n_items, + tile_n, + ntiles, + nslots, + tr, + ) + elif warp == Int32(W_QLOAD): + if cutlass.const_expr(regs): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_q_load_engine( + tma_q, s_q.data_ptr(), q_full.data_ptr(), q_empty.data_ptr(), cta, grid, n_items + ) + elif warp < Int32(W_GATHER0 + NGW_ENGINE): + if cutlass.const_expr(regs): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_gather( + tma_swa, + tma_cmp, + s_kv.data_ptr(), + idx.iterator.raw_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + warp - Int32(W_GATHER0), + cta, + grid, + n_items, + Int32(0), + tile_n, + ntiles, + nslots, + tr, + ) + elif cutlass.const_expr(regs): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if warp == Int32(W_MMA): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + prims.tcgen05_dealloc( + prims.make_tmem_ptr(tmem, Float32), TMEM_COLS, group=prims.CTAGroup.CTA_1 + ) + if cutlass.const_expr(use_trace): + _stamp(tr, Int32(2), cute.arch.lane_idx() == Int32(0)) + + +def _q_map(q): + return cuda.create_tensor_map_tiled( + global_address=q.iterator.toint(), + dtype=E4M3, + global_dims=[LATENT, HEADS, q.shape[0]], + global_strides=[LATENT // 16, HEADS * LATENT // 16], + box_dims=[SLICE, HEADS, 1], + swizzle=cuda.TensorMapSwizzle.s128b, + ) + + +def _pool_map(p): + return cuda.create_tensor_map_tiled( + global_address=p.iterator.toint(), + dtype=E4M3, + global_dims=[LATENT, p.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=cuda.TensorMapSwizzle.s128b, + ) + + +@cute.jit +def _launch_vl( + q: cute.Tensor, + swa: cute.Tensor, + cmp: cute.Tensor, + idx: cute.Tensor, + sink: cute.Tensor, + out: cute.Tensor, + trace: cute.Tensor, + softmax_scale: Float32, + grid: Int32, + stream: cuda_driver.CUstream, + nslots: cutlass.Constexpr[int], + use_trace: cutlass.Constexpr[bool], +): + tma_q = _q_map(q) + tma_swa = _pool_map(swa) + tma_cmp = _pool_map(cmp) + _vl_kernel( + tma_q, tma_swa, tma_cmp, idx, sink, out, trace, softmax_scale, nslots, use_trace + ).launch(grid=(grid, 1, 1), block=(THREADS, 1, 1), stream=stream, min_blocks_per_mp=1) + + +_COMPILED: dict = {} +_NUM_SMS: dict = {} + + +def _num_sms(dev) -> int: + i = dev.index if dev.index is not None else torch.cuda.current_device() + if i not in _NUM_SMS: + _NUM_SMS[i] = torch.cuda.get_device_properties(i).multi_processor_count + return _NUM_SMS[i] + + +def _fake_inputs(): + mk = cute.runtime.make_fake_compact_tensor + b = cute.sym_int64() + rs = cute.sym_int64() + rc = cute.sym_int64() + return ( + mk(cutlass.Uint8, (b, HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(cutlass.Uint8, (rs, LATENT), stride_order=(1, 0), assumed_align=16), + mk(cutlass.Uint8, (rc, LATENT), stride_order=(1, 0), assumed_align=16), + mk(Int32, (b, NROWS), stride_order=(1, 0), assumed_align=16), + mk(Float32, (HEADS,), stride_order=(0,), assumed_align=16), + mk(BF16, (b, HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(Int64, (cute.sym_int64(),), stride_order=(0,), assumed_align=16), + ) + + +def compile_vl(nslots: int = 12, trace: bool = False): + key = ("vl", nslots, trace) + if key not in _COMPILED: + _COMPILED[key] = cute.compile( + _launch_vl, + *_fake_inputs(), + Float32(1.0), + Int32(1), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=False), + nslots, + trace, + options="--enable-tvm-ffi", + ) + return _COMPILED[key] + + +_DUMMY: dict = {} + + +def _dummy_trace(dev): + if dev not in _DUMMY: + _DUMMY[dev] = torch.zeros(16, dtype=torch.int64, device=dev) + return _DUMMY[dev] + + +def _u8(t: torch.Tensor) -> torch.Tensor: + return t.view(torch.uint8) if t.dtype != torch.uint8 else t + + +def run_vl( + q8: torch.Tensor, + swa_pool: torch.Tensor, + cmp_pool: torch.Tensor, + idx: torch.Tensor, + sink: torch.Tensor, + out: torch.Tensor, + softmax_scale: float = 1.0 / math.sqrt(512.0), + nslots: int = 12, + grid: int | None = None, + stream=None, + trace: torch.Tensor | None = None, +): + fn = compile_vl(nslots, trace is not None) + if stream is None: + stream = cuda_driver.CUstream(torch.cuda.current_stream().cuda_stream) + if grid is None: + grid = min(q8.shape[0], _num_sms(q8.device)) + tr = trace if trace is not None else _dummy_trace(q8.device) + fn( + _u8(q8), + _u8(swa_pool), + _u8(cmp_pool), + idx, + sink, + out, + tr, + Float32(softmax_scale), + Int32(grid), + stream, + ) + return out + + +@dsl_user_op +def _mapa_u32(addr_i32, rank, *, loc=None, ip=None): + return Int32( + _llvm.inline_asm( + _T.i32(), + [Int32(addr_i32).ir_value(loc=loc, ip=ip), Int32(rank).ir_value(loc=loc, ip=ip)], + "mapa.shared::cluster.u32 $0, $1, $2;", + "=r,r,r", + has_side_effects=False, + is_align_stack=False, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def _st_async_v4(raddr, rbar, a, b, c, d, *, loc=None, ip=None): + _llvm.inline_asm( + None, + [ + Int32(raddr).ir_value(loc=loc, ip=ip), + Int32(rbar).ir_value(loc=loc, ip=ip), + Int32(a).ir_value(loc=loc, ip=ip), + Int32(b).ir_value(loc=loc, ip=ip), + Int32(c).ir_value(loc=loc, ip=ip), + Int32(d).ir_value(loc=loc, ip=ip), + ], + "st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.b32 [$0], {$2, $3, $4, $5}, [$1];", + "r,r,r,r,r,r", + has_side_effects=True, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def _st_async_v2(raddr, rbar, a, b, *, loc=None, ip=None): + _llvm.inline_asm( + None, + [ + Int32(raddr).ir_value(loc=loc, ip=ip), + Int32(rbar).ir_value(loc=loc, ip=ip), + Int32(a).ir_value(loc=loc, ip=ip), + Int32(b).ir_value(loc=loc, ip=ip), + ], + "st.async.shared::cluster.mbarrier::complete_tx::bytes.v2.b32 [$0], {$2, $3}, [$1];", + "r,r,r,r", + has_side_effects=True, + asm_dialect=_llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@cute.jit +def _f2i(x: Float32) -> Int32: + return prims.mov_b32(x, target_type=Int32) + + +@cute.jit +def role_correction_export( + tmem, o_full, o_free, s_fin, fin_bar, ml_addr: Int64, o_addr: Int64, row0, row_step, n_items +): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + for it in cutlass.range(n_items, unroll=1): + b = row0 + it * row_step + _wait(o_full, it & Int32(1)) + _wait(fin_bar, it & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + fb = (it & Int32(1)) * Int32(128) + if half == Int32(0): + mrow = cutlass.inttoptr( + ml_addr + Int64(b) * Int64(512) + Int64(head * Int32(4)), mem_space=1, dtype=Float32 + ) + mrow.store((s_fin + fb + head).load()) + (mrow + Int32(64)).store((s_fin + fb + Int32(64) + head).load()) + obase = ( + o_addr + + Int64(b) * Int64(HEADS * LATENT * 4) + + Int64((head * Int32(LATENT) + half * Int32(64)) * Int32(4)) + ) + for v in cutlass.range_constexpr(NSLICE): + oa = tmem + lane_base + Int32(TMEM_O + v % 2 * 128 + v // 2 * PANEL1) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(oa, Float32), + num=64, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for ch in cutlass.range_constexpr(0, 64, 4): + dst = cutlass.inttoptr( + obase + Int64((v * SLICE + ch) * 4), mem_space=1, dtype=Float32 + ) + dst.store( + cutlass.Vector.from_elements( + tuple((Float32(o[ch + i]) for i in range(4))), Float32 + ), + alignment=16, + ) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(o_free) + + +@cute.jit +def role_vs_merge( + tmem, + o_full, + fin_bar, + s_fin, + s_ml, + s_recv, + rx_bar, + sink_ptr, + swa_ml_addr: Int64, + swa_o_addr: Int64, + out_addr: Int64, + scale_log2: Float32, + b, + r, + d, + cr: cutlass.Constexpr[int], + cd: cutlass.Constexpr[int], + has_swa: cutlass.Constexpr[bool], + tr=None, +): + nv: cutlass.Constexpr[int] = NSLICE // cd + ddims: cutlass.Constexpr[int] = LATENT // cd + hmax: cutlass.Constexpr[int] = (HEADS + cr - 1) // cr + blk: cutlass.Constexpr[int] = 2 * hmax * 16 + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + tid = warp * Int32(32) + lane + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + h_lo = (r * Int32(HEADS) + Int32(cr - 1)) // Int32(cr) + h_hi = ((r + Int32(1)) * Int32(HEADS) + Int32(cr - 1)) // Int32(cr) + nel: cutlass.Constexpr[int] = nv * 8 * 2 * hmax + nch: cutlass.Constexpr[int] = (nel + 127) // 128 + swa_pre = [] + swa_m = [] + swa_l = [] + sink_v = [] + for i in cutlass.range_constexpr(nch): + t = tid + Int32(i * 128) + e = t % Int32(2 * hmax) + hh = e % Int32(hmax) + h = h_lo + hh + v8 = cutlass.Vector.from_elements(tuple((Float32(0.0) for _ in range(8))), Float32) + ms = Float32(NEG_FLT_MAX) + ls = Float32(0.0) + if cutlass.const_expr(has_swa): + if h < h_hi and t < Int32(nel): + vc = t // Int32(2 * hmax) + gdim = ( + d * Int32(ddims) + + vc // Int32(8) * Int32(128) + + e // Int32(hmax) * Int32(64) + + vc % Int32(8) * Int32(8) + ) + sp = cutlass.inttoptr( + swa_o_addr + + Int64(b) * Int64(HEADS * LATENT * 4) + + Int64((h * Int32(LATENT) + gdim) * Int32(4)), + mem_space=1, + dtype=Float32, + ) + v8 = sp.load(count=8, alignment=16) + mp = cutlass.inttoptr( + swa_ml_addr + Int64(b) * Int64(512) + Int64(h * Int32(4)), + mem_space=1, + dtype=Float32, + ) + ms = mp.load() + ls = (mp + Int32(64)).load() + hs = h + if hs >= Int32(HEADS): + hs = Int32(HEADS - 1) + swa_pre.append(v8) + swa_m.append(ms) + swa_l.append(ls) + sink_v.append(Float32((sink_ptr + hs).load())) + _wait(o_full, 0) + _wait(fin_bar, 0) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + m_self = (s_fin + head).load() + l_self = (s_fin + Int32(64) + head).load() + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(80), tid == Int32(0)) + inv_l = Float32(1.0) / l_self + o_idx = head * Int32(cr) // Int32(HEADS) + hl = head - (o_idx * Int32(HEADS) + Int32(cr - 1)) // Int32(cr) + owner = d * Int32(cr) + o_idx + rbar = _mapa_u32(Int32(rx_bar.toint()), owner) + if half == Int32(0): + _st_async_v2( + _mapa_u32(Int32(s_ml.toint()) + (r * Int32(hmax) + hl) * Int32(8), owner), + rbar, + _f2i(m_self), + _f2i(l_self), + ) + rbase = Int32(s_recv.toint()) + r * Int32(nv * 8 * blk) + (half * Int32(hmax) + hl) * Int32(16) + for vv in cutlass.range_constexpr(nv): + v = d * Int32(nv) + Int32(vv) + oa = ( + tmem + + lane_base + + Int32(TMEM_O) + + v % Int32(2) * Int32(128) + + (v >> Int32(1)) * Int32(PANEL1) + ) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(oa, Float32), + num=64, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for c in cutlass.range_constexpr(8): + pk = [] + for pi in cutlass.range_constexpr(4): + fp = cute.arch.mul_packed_f32x2( + (inv_l, inv_l), + (Float32(o[8 * c + 2 * pi]), Float32(o[8 * c + 2 * pi + 1])), + ftz=False, + rnd="rn", + ) + pk.append(_pack_bf16x2(fp[0], fp[1])) + _st_async_v4( + _mapa_u32(rbase + Int32((vv * 8 + c) * blk), owner), + rbar, + pk[0], + pk[1], + pk[2], + pk[3], + ) + _wait(rx_bar, 0) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(84), tid == Int32(0)) + for i in cutlass.range_constexpr(nch): + t = tid + Int32(i * 128) + e = t % Int32(2 * hmax) + vc = t // Int32(2 * hmax) + hh = e % Int32(hmax) + h = h_lo + hh + if h < h_hi and t < Int32(nel): + big_m = swa_m[i] + for p in cutlass.range_constexpr(cr): + big_m = cute.math.max( + big_m, (s_ml + (Int32(p * hmax) + hh) * Int32(2)).load(), ftz=True + ) + l_tot = Float32(0.0) + acc = cutlass.Vector.from_elements(tuple((Float32(0.0) for _ in range(8))), Float32) + if cutlass.const_expr(has_swa): + w_swa = cute.math.exp2(scale_log2 * (swa_m[i] - big_m), fastmath=True) + l_tot = w_swa * swa_l[i] + acc = swa_pre[i] * w_swa + eoff = vc * Int32(blk // 2) + e * Int32(8) + for p in cutlass.range_constexpr(cr): + mpp = (s_ml + (Int32(p * hmax) + hh) * Int32(2)).load() + lpp = (s_ml + (Int32(p * hmax) + hh) * Int32(2) + Int32(1)).load() + a_p = cute.math.exp2(scale_log2 * (mpp - big_m), fastmath=True) * lpp + l_tot = l_tot + a_p + pv = (s_recv + (Int32(p * nv * 8 * blk // 2) + eoff)).load(count=8, alignment=16) + acc = acc + pv.to(Float32) * a_p + norm = _final_norm_engine(big_m, l_tot, sink_v[i], scale_log2) + gdim = ( + d * Int32(ddims) + + vc // Int32(8) * Int32(128) + + e // Int32(hmax) * Int32(64) + + vc % Int32(8) * Int32(8) + ) + dst = cutlass.inttoptr( + out_addr + + Int64(b) * Int64(HEADS * LATENT * 2) + + Int64((h * Int32(LATENT) + gdim) * Int32(2)), + mem_space=1, + dtype=BF16, + ) + dst.store((acc * norm).to(BF16), alignment=16) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(81), tid == Int32(0)) + + +@cute.kernel +def _vs_kernel( + tma_q: cutlass.GridConstant[cuda.TensorMap], + tma_swa: cutlass.GridConstant[cuda.TensorMap], + tma_cmp: cutlass.GridConstant[cuda.TensorMap], + idx: cute.Tensor, + sink: cute.Tensor, + out: cute.Tensor, + swa_ml: cute.Tensor, + swa_o: cute.Tensor, + trace: cute.Tensor, + softmax_scale: Float32, + cr: cutlass.Constexpr[int], + cd: cutlass.Constexpr[int], + has_swa: cutlass.Constexpr[bool], + use_trace: cutlass.Constexpr[bool], +): + list_lo: cutlass.Constexpr[int] = WINDOW if has_swa else 0 + tile_n: cutlass.Constexpr[int] = (NROWS - list_lo) // cr + nslots: cutlass.Constexpr[int] = NSLICE + ddims: cutlass.Constexpr[int] = LATENT // cd + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + rank, b, _ = cute.arch.block_idx() + r = rank % Int32(cr) + d = rank // Int32(cr) + lb = Int32(list_lo) + r * Int32(tile_n) + tr = None + if cutlass.const_expr(use_trace): + tr = trace.iterator.toint() + (Int64(b) * Int64(cr * cd) + Int64(rank)) * Int64(2048) + _stamp(tr, Int32(1), warp == Int32(0) and cute.arch.lane_idx() == Int32(0)) + s_q = cutlass.Array(E4M3, Q_BYTES, space=cutlass.AddressSpace.smem, alignment=1024) + s_kv = cutlass.Array( + E4M3, nslots * tile_n * SLICE, space=cutlass.AddressSpace.smem, alignment=1024 + ) + hmax: cutlass.Constexpr[int] = (HEADS + cr - 1) // cr + s_recv = cutlass.Array(BF16, cr * hmax * ddims, space=cutlass.AddressSpace.smem, alignment=128) + s_ml = cutlass.Array(Float32, cr * hmax * 2, space=cutlass.AddressSpace.smem, alignment=16) + s_stat = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + s_fin = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + q_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + q_empty = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + kv_full = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + kv_empty = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + s_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + s_empty = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + p_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + o_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_corr = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_free = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + fin_bar = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + rx_bar = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + tmem_hold = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=16) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_init(q_full.data_ptr(), 1) + prims.mbarrier_init(q_empty.data_ptr(), 1) + for i in cutlass.range_constexpr(nslots): + prims.mbarrier_init(kv_full.data_ptr() + i, 1) + prims.mbarrier_init(kv_empty.data_ptr() + i, 1) + for i in cutlass.range_constexpr(2): + prims.mbarrier_init(s_full.data_ptr() + i, 1) + prims.mbarrier_init(s_empty.data_ptr() + i, 1) + prims.mbarrier_init(p_full.data_ptr() + i, 4) + prims.mbarrier_init(o_full.data_ptr(), 1) + prims.mbarrier_init(o_corr.data_ptr(), 4) + prims.mbarrier_init(o_free.data_ptr(), 4) + prims.mbarrier_init(fin_bar.data_ptr(), 4) + prims.mbarrier_init(rx_bar.data_ptr(), 1) + n_own = ((r + Int32(1)) * Int32(HEADS) + Int32(cr - 1)) // Int32(cr) - ( + r * Int32(HEADS) + Int32(cr - 1) + ) // Int32(cr) + prims.mbarrier_arrive_expect_tx(rx_bar.data_ptr(), Int32(cr * (ddims * 2 + 8)) * n_own) + prims.fence_mbarrier_init() + _alloc_tmem(tmem_hold, warp) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cluster_arrive() + prims.barrier_cluster_wait() + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = tmem_hold[0] + scale_log2 = softmax_scale * Float32(LOG2_E) + if cutlass.const_expr(use_trace): + _stamp(tr, Int32(0), warp == Int32(0) and cute.arch.lane_idx() == Int32(0)) + if warp < Int32(W_CORR0): + prims.setmaxregister(REG_SOFTMAX, prims.SetMaxRegisterAction.INCREASE) + role_softmax( + tmem, + s_full.data_ptr(), + p_full.data_ptr(), + s_stat.data_ptr(), + s_fin.data_ptr(), + fin_bar.data_ptr(), + scale_log2, + Int32(1), + tile_n, + 1, + tr, + ) + elif warp < Int32(W_MMA): + prims.setmaxregister(REG_CORR, prims.SetMaxRegisterAction.INCREASE) + role_vs_merge( + tmem, + o_full.data_ptr(), + fin_bar.data_ptr(), + s_fin.data_ptr(), + s_ml.data_ptr(), + s_recv.data_ptr(), + rx_bar.data_ptr(), + sink.iterator.raw_ptr(), + swa_ml.iterator.toint(), + swa_o.iterator.toint(), + out.iterator.toint(), + scale_log2, + b, + r, + d, + cr, + cd, + has_swa, + tr, + ) + elif warp == Int32(W_MMA): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_mma( + tmem, + s_q.data_ptr(), + s_kv.data_ptr(), + q_full.data_ptr(), + q_empty.data_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + s_full.data_ptr(), + s_empty.data_ptr(), + p_full.data_ptr(), + o_corr.data_ptr(), + o_free.data_ptr(), + o_full.data_ptr(), + Int32(1), + tile_n, + 1, + nslots, + tr, + d * Int32(NSLICE // cd), + NSLICE // cd, + ) + elif warp == Int32(W_QLOAD): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_q_load_engine( + tma_q, s_q.data_ptr(), q_full.data_ptr(), q_empty.data_ptr(), b, Int32(0), Int32(1) + ) + elif warp < Int32(W_GATHER0 + NGW_ENGINE): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_gather( + tma_swa, + tma_cmp, + s_kv.data_ptr(), + idx.iterator.raw_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + warp - Int32(W_GATHER0), + b, + Int32(0), + Int32(1), + lb, + tile_n, + 1, + nslots, + tr, + ) + else: + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if warp == Int32(W_MMA): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + prims.tcgen05_dealloc( + prims.make_tmem_ptr(tmem, Float32), TMEM_COLS, group=prims.CTAGroup.CTA_1 + ) + prims.barrier_cluster_arrive() + prims.barrier_cluster_wait() + if cutlass.const_expr(use_trace): + _stamp(tr, Int32(2), warp == Int32(0) and cute.arch.lane_idx() == Int32(0)) + + +@cute.kernel +def _swa_kernel( + tma_q: cutlass.GridConstant[cuda.TensorMap], + tma_swa: cutlass.GridConstant[cuda.TensorMap], + idx: cute.Tensor, + swa_ml: cute.Tensor, + swa_o: cute.Tensor, + softmax_scale: Float32, +): + tile_n: cutlass.Constexpr[int] = WINDOW + nslots: cutlass.Constexpr[int] = 8 + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + cta, _, _ = cute.arch.block_idx() + grid, _, _ = cute.arch.grid_dim() + n_items = (Int32(idx.shape[0]) - cta + grid - Int32(1)) // grid + s_q = cutlass.Array(E4M3, Q_BYTES, space=cutlass.AddressSpace.smem, alignment=1024) + s_kv = cutlass.Array( + E4M3, nslots * tile_n * SLICE, space=cutlass.AddressSpace.smem, alignment=1024 + ) + s_stat = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + s_fin = cutlass.Array(Float32, 2 * 128, space=cutlass.AddressSpace.smem, alignment=16) + q_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + q_empty = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + kv_full = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + kv_empty = cutlass.Array(Int64, nslots, space=cutlass.AddressSpace.smem) + s_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + s_empty = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + p_full = cutlass.Array(Int64, 2, space=cutlass.AddressSpace.smem) + o_full = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_corr = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + o_free = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + fin_bar = cutlass.Array(Int64, 1, space=cutlass.AddressSpace.smem) + tmem_hold = cutlass.Array(Int32, 1, space=cutlass.AddressSpace.smem, alignment=16) + if warp == Int32(0): + if prims.elect_sync(): + prims.mbarrier_init(q_full.data_ptr(), 1) + prims.mbarrier_init(q_empty.data_ptr(), 1) + for i in cutlass.range_constexpr(nslots): + prims.mbarrier_init(kv_full.data_ptr() + i, 1) + prims.mbarrier_init(kv_empty.data_ptr() + i, 1) + for i in cutlass.range_constexpr(2): + prims.mbarrier_init(s_full.data_ptr() + i, 1) + prims.mbarrier_init(s_empty.data_ptr() + i, 1) + prims.mbarrier_init(p_full.data_ptr() + i, 4) + prims.mbarrier_init(o_full.data_ptr(), 1) + prims.mbarrier_init(o_corr.data_ptr(), 4) + prims.mbarrier_init(o_free.data_ptr(), 4) + prims.mbarrier_init(fin_bar.data_ptr(), 4) + prims.fence_mbarrier_init() + _alloc_tmem(tmem_hold, warp) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem = tmem_hold[0] + scale_log2 = softmax_scale * Float32(LOG2_E) + if warp < Int32(W_CORR0): + prims.setmaxregister(REG_SOFTMAX, prims.SetMaxRegisterAction.INCREASE) + role_softmax( + tmem, + s_full.data_ptr(), + p_full.data_ptr(), + s_stat.data_ptr(), + s_fin.data_ptr(), + fin_bar.data_ptr(), + scale_log2, + n_items, + tile_n, + 1, + ) + elif warp < Int32(W_MMA): + prims.setmaxregister(REG_CORR, prims.SetMaxRegisterAction.INCREASE) + role_correction_export( + tmem, + o_full.data_ptr(), + o_free.data_ptr(), + s_fin.data_ptr(), + fin_bar.data_ptr(), + swa_ml.iterator.toint(), + swa_o.iterator.toint(), + cta, + grid, + n_items, + ) + elif warp == Int32(W_MMA): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_mma( + tmem, + s_q.data_ptr(), + s_kv.data_ptr(), + q_full.data_ptr(), + q_empty.data_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + s_full.data_ptr(), + s_empty.data_ptr(), + p_full.data_ptr(), + o_corr.data_ptr(), + o_free.data_ptr(), + o_full.data_ptr(), + n_items, + tile_n, + 1, + nslots, + ) + elif warp == Int32(W_QLOAD): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_q_load_engine( + tma_q, s_q.data_ptr(), q_full.data_ptr(), q_empty.data_ptr(), cta, grid, n_items + ) + elif warp < Int32(W_GATHER0 + NGW_ENGINE): + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + role_gather( + tma_swa, + tma_swa, + s_kv.data_ptr(), + idx.iterator.raw_ptr(), + kv_full.data_ptr(), + kv_empty.data_ptr(), + warp - Int32(W_GATHER0), + cta, + grid, + n_items, + Int32(0), + tile_n, + 1, + nslots, + ) + else: + prims.setmaxregister(REG_OTHER, prims.SetMaxRegisterAction.DECREASE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + prims.barrier_cta_sync(0) + if warp == Int32(W_MMA): + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + prims.tcgen05_dealloc( + prims.make_tmem_ptr(tmem, Float32), TMEM_COLS, group=prims.CTAGroup.CTA_1 + ) + + +@cute.jit +def _launch_vs( + q: cute.Tensor, + swa: cute.Tensor, + cmp: cute.Tensor, + idx: cute.Tensor, + sink: cute.Tensor, + out: cute.Tensor, + swa_ml: cute.Tensor, + swa_o: cute.Tensor, + trace: cute.Tensor, + softmax_scale: Float32, + stream: cuda_driver.CUstream, + cr: cutlass.Constexpr[int], + cd: cutlass.Constexpr[int], + has_swa: cutlass.Constexpr[bool], + use_trace: cutlass.Constexpr[bool], +): + tma_q = _q_map(q) + tma_swa = _pool_map(swa) + tma_cmp = _pool_map(cmp) + _vs_kernel( + tma_q, + tma_swa, + tma_cmp, + idx, + sink, + out, + swa_ml, + swa_o, + trace, + softmax_scale, + cr, + cd, + has_swa, + use_trace, + ).launch( + grid=(cr * cd, q.shape[0], 1), + block=(THREADS, 1, 1), + cluster=(cr * cd, 1, 1), + stream=stream, + min_blocks_per_mp=1, + ) + + +@cute.jit +def _launch_swa( + q: cute.Tensor, + swa: cute.Tensor, + idx: cute.Tensor, + swa_ml: cute.Tensor, + swa_o: cute.Tensor, + softmax_scale: Float32, + grid: Int32, + stream: cuda_driver.CUstream, +): + tma_q = _q_map(q) + tma_swa = _pool_map(swa) + _swa_kernel(tma_q, tma_swa, idx, swa_ml, swa_o, softmax_scale).launch( + grid=(grid, 1, 1), block=(THREADS, 1, 1), stream=stream, min_blocks_per_mp=1 + ) + + +def _fake_vs(): + mk = cute.runtime.make_fake_compact_tensor + b = cute.sym_int64() + return ( + mk(cutlass.Uint8, (b, HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(cutlass.Uint8, (cute.sym_int64(), LATENT), stride_order=(1, 0), assumed_align=16), + mk(cutlass.Uint8, (cute.sym_int64(), LATENT), stride_order=(1, 0), assumed_align=16), + mk(Int32, (b, NROWS), stride_order=(1, 0), assumed_align=16), + mk(Float32, (HEADS,), stride_order=(0,), assumed_align=16), + mk(BF16, (b, HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(Float32, (cute.sym_int64(), 2, HEADS), stride_order=(2, 1, 0), assumed_align=16), + mk(Float32, (cute.sym_int64(), HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(Int64, (cute.sym_int64(),), stride_order=(0,), assumed_align=16), + ) + + +def compile_vs(cr: int, cd: int, has_swa: bool, trace: bool = False): + key = ("vs", cr, cd, has_swa, trace) + if key not in _COMPILED: + _COMPILED[key] = cute.compile( + _launch_vs, + *_fake_vs(), + Float32(1.0), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=False), + cr, + cd, + has_swa, + trace, + options="--enable-tvm-ffi", + ) + return _COMPILED[key] + + +def compile_swa(): + key = ("swa",) + if key not in _COMPILED: + mk = cute.runtime.make_fake_compact_tensor + b = cute.sym_int64() + _COMPILED[key] = cute.compile( + _launch_swa, + mk(cutlass.Uint8, (b, HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16), + mk(cutlass.Uint8, (cute.sym_int64(), LATENT), stride_order=(1, 0), assumed_align=16), + mk(Int32, (b, NROWS), stride_order=(1, 0), assumed_align=16), + mk(Float32, (cute.sym_int64(), 2, HEADS), stride_order=(2, 1, 0), assumed_align=16), + mk( + Float32, (cute.sym_int64(), HEADS, LATENT), stride_order=(2, 1, 0), assumed_align=16 + ), + Float32(1.0), + Int32(1), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=False), + options="--enable-tvm-ffi", + ) + return _COMPILED[key] + + +class SwaWorkspace: + def __init__(self, bs: int, device): + self.ml = torch.empty((bs, 2, HEADS), dtype=torch.float32, device=device) + self.o = torch.empty((bs, HEADS, LATENT), dtype=torch.float32, device=device) + + +def run_swa_partial( + q8, + swa_pool, + idx, + ws: SwaWorkspace, + softmax_scale: float = 1.0 / math.sqrt(512.0), + grid: int | None = None, + stream=None, +): + fn = compile_swa() + if stream is None: + stream = cuda_driver.CUstream(torch.cuda.current_stream().cuda_stream) + if grid is None: + grid = min(q8.shape[0], _num_sms(q8.device)) + fn(_u8(q8), _u8(swa_pool), idx, ws.ml, ws.o, Float32(softmax_scale), Int32(grid), stream) + + +def run_vs( + q8, + swa_pool, + cmp_pool, + idx, + sink, + out, + team: int = 16, + cd: int | None = None, + swa_ws: SwaWorkspace | None = None, + softmax_scale: float = 1.0 / math.sqrt(512.0), + stream=None, + trace: torch.Tensor | None = None, +): + if cd is None: + cd = {16: 4, 8: 2, 4: 1, 2: 1, 5: 1, 10: 2}.get(team, 1) + cr = team // cd + has_swa = swa_ws is not None + fn = compile_vs(cr, cd, has_swa, trace is not None) + if stream is None: + stream = cuda_driver.CUstream(torch.cuda.current_stream().cuda_stream) + dev = q8.device + if swa_ws is None: + swa_ws = _dummy_ws(dev) + tr = trace if trace is not None else _dummy_trace(dev) + fn( + _u8(q8), + _u8(swa_pool), + _u8(cmp_pool), + idx, + sink, + out, + swa_ws.ml, + swa_ws.o, + tr, + Float32(softmax_scale), + stream, + ) + return out + + +_DUMMY_WS: dict = {} + + +def _dummy_ws(dev): + if dev not in _DUMMY_WS: + _DUMMY_WS[dev] = SwaWorkspace(1, dev) + return _DUMMY_WS[dev] + + +# ==================================================================================================================== +# Warp roles of the team CTAs' sparse MLA: KV gather, MMA, softmax, correction and epilogue, and the two-row-group +# split with the DSMEM pair merge. +# ==================================================================================================================== + +TILE_N = 128 +# S buffers: lane panel 0, columns 128k (k = tile % 4); P_k: panel 1, column 128k + 32; O: panel 1, column 448 +O_COL4 = 448 +OUT_SLICE = 64 +OUT_REGS = OUT_SLICE // 2 +SLOT_BYTES = TILE_N * SLICE +SLOT_BY_POS = True +W_SM0 = 0 +W_CTL0 = 4 +W_G0 = 9 +NGW = 7 +REG_CTL = 232 +TS_Q = 24 +TS_G = 25 +TS_QK = 30 +TS_SM = 35 +TS_PV = 40 +TS_COR = 45 +TS_FIN = 50 +TS_STORED = 51 + + +@cute.jit +def _slot_ptr(s_kv, s_ext, slot): + return s_kv + slot * Int32(SLOT_BYTES) + + +@cute.jit +def role_q_load(tma_q, s_q, q_full, qrow=0): + if prims.elect_sync(): + prims.mbarrier_arrive_expect_tx(q_full, Q_BYTES) + for c in cutlass.range_constexpr(NSLICE): + prims.cp_async_bulk_tensor_shared_cta_global( + s_q + c * Q_SLICE_BYTES, tma_q.get_ptr(), [c * SLICE, 0, qrow], q_full + ) + + +@cute.jit +def role_gather_team( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + kv_full, + kv_empty, + swa_ready, + sel_ready, + gw, + v_lo, + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + tr=None, + j_begin=0, + ngw_late: cutlass.Constexpr[int] = NGW, + sel_early=None, + j_join: cutlass.Constexpr[int] = 1, +): + lane = cute.arch.lane_idx() + # Adjacent team CTAs retain the same full K/V slice for QK, then + # consume separate 64-column halves for PV and the final output. + v_slice = v_lo >> Int32(1) + for j in cutlass.range(j_begin, ntiles, unroll=1): + nw = Int32(NGW) + if j >= Int32(j_join): + nw = Int32(ngw_late) + if j == Int32(0): + _wait(swa_ready, Int32(0)) + if cutlass.const_expr(sel_early is None): + if j == Int32(1): + _wait(sel_ready, Int32(0)) + else: + if j == Int32(1): + _wait(sel_early, Int32(0)) + if j == Int32(ntiles - 1): + _wait(sel_ready, Int32(0)) + tm = tma_cmp.get_ptr().toint() + if j == Int32(0): + tm = tma_swa.get_ptr().toint() + for c in cutlass.range_constexpr(NSLICE): + sl = v_slice + Int32(1 + c) & Int32(3) + k = j * Int32(NSLICE) + sl + if cutlass.const_expr(SLOT_BY_POS): + k = j * Int32(NSLICE) + Int32(c) + slot = k % Int32(nslots) + _wait(kv_empty + slot, k // Int32(nslots) & Int32(1) ^ Int32(1)) + if gw == Int32(0): + if lane == Int32(0): + prims.mbarrier_arrive_expect_tx(kv_full + slot, SLOT_BYTES) + g = lane * nw + gw + if g < Int32(TILE_N // 4): + r4 = L.lds_v4(Int32(s_idx.toint()) + (j * Int32(TILE_N) + g * Int32(4)) * Int32(4)) + dst = Int32(_slot_ptr(s_kv, s_ext, slot).toint()) + g * Int32(4 * SLICE) + L.tma_g4( + dst, + tm, + sl * Int32(SLICE), + r4[0], + r4[1], + r4[2], + r4[3], + Int32(kv_full.toint()) + slot * Int32(8), + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_G) + j, gw == Int32(0) and lane == Int32(0)) + + +@cute.jit +def _qk( + tmem, + s_q, + s_kv, + s_ext, + j, + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots: cutlass.Constexpr[int], +): + v_slice = v_lo >> Int32(1) + st = j & Int32(3) + if j >= Int32(4): + _wait(s_empty + st, (j >> Int32(2)) - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + st * Int32(TILE_N) + # Consume in the gather order. The first three slices can issue and + # release immediately; the CTA's retained V slice is consumed last. + for step in cutlass.range_constexpr(NSLICE): + c = (v_slice + Int32(1 + step)) & Int32(3) + k = j * Int32(NSLICE) + c + if cutlass.const_expr(SLOT_BY_POS): + k = j * Int32(NSLICE) + Int32(step) + slot = k % Int32(nslots) + _wait(kv_full + slot, k // Int32(nslots) & Int32(1)) + kdesc = prims.Tcgen05SmemDesc.build( + _slot_ptr(s_kv, s_ext, slot), + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(SLICE // 32): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(c * Int32(Q_SLICE_BYTES) + Int32(kb * 32)), + kdesc.advance_start_address(kb * 32), + idesc_qk, + Boolean(step > 0 or kb > 0), + ) + if cutlass.const_expr(step < NSLICE - 1): + prims.tcgen05_commit(kv_empty + slot, group=prims.CTAGroup.CTA_1) + if prims.elect_sync(): + prims.tcgen05_commit(s_full + st, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def _pv( + tmem, + s_kv, + s_ext, + j, + p_full, + o_corr, + kv_empty, + s_empty, + o_full, + idesc_pv, + v_lo, + nslots: cutlass.Constexpr[int], + tr=None, +): + st = j & Int32(3) + _wait(p_full + st, j >> Int32(2) & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp( + tr, + Int32(56) + (j & Int32(1)) * Int32(7), + (j == Int32(1) or j == Int32(2)) and cute.arch.lane_idx() == Int32(0), + ) + if cutlass.const_expr(o_corr is not None): + if j > Int32(0): + _wait(o_corr, j - Int32(1) & Int32(1)) + if cutlass.const_expr(tr is not None): + _stamp( + tr, + Int32(57) + (j & Int32(1)) * Int32(5), + (j == Int32(1) or j == Int32(2)) and cute.arch.lane_idx() == Int32(0), + ) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + v = v_lo >> Int32(1) + slot = (j * Int32(NSLICE) + v) % Int32(nslots) + if cutlass.const_expr(SLOT_BY_POS): + slot = (j * Int32(NSLICE) + Int32(3)) % Int32(nslots) + d_addr = tmem + Int32(O_COL4) + Int32(PANEL1) + a_addr = tmem + st * Int32(TILE_N) + Int32(TILE_N // 4) + Int32(PANEL1) + # Select a half of the existing SW128 tile. The physical row pitch + # remains 128 bytes and the 1024-byte swizzle origin is unchanged. + v_ptr = _slot_ptr(s_kv, s_ext, slot) + (v_lo & Int32(1)) * Int32(OUT_SLICE) + vdesc = prims.Tcgen05SmemDesc.build( + v_ptr, + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + acc0 = Boolean(j > Int32(0)) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(TILE_N // 32): + en = acc0 if cutlass.const_expr(kb == 0) else Boolean(True) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(kv_empty + slot, group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(s_empty + st, group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(o_full, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def _landed(kv_full, j, nslots: cutlass.Constexpr[int]): + ok = Int32(1) + for c in cutlass.range_constexpr(NSLICE): + k = j * Int32(NSLICE) + Int32(c) + if L.mbar_test_wait( + Int32(kv_full.toint()) + k % Int32(nslots) * Int32(8), k // Int32(nslots) & Int32(1) + ) == Int32(0): + ok = Int32(0) + return ok + + +@cute.jit +def role_mma_team( + tmem, + s_q, + s_kv, + s_ext, + q_full, + kv_full, + kv_empty, + s_full, + s_empty, + p_full, + o_corr, + o_full, + v_lo, + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + tr=None, + qk_ahead: cutlass.Constexpr[bool] = False, + pv_last=None, +): + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=E4M3, + b_dtype=E4M3, + a_major=0, + b_major=1, + n_dim=OUT_SLICE, + m_dim=HEADS, + ) + qdesc = prims.Tcgen05SmemDesc.build( + s_q, + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + lane = cute.arch.lane_idx() + _wait(q_full, Int32(0)) + _qk( + tmem, + s_q, + s_kv, + s_ext, + Int32(0), + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_QK), lane == Int32(0)) + for j in cutlass.range(ntiles, unroll=1): + if j + Int32(1) < Int32(ntiles): + ahead = Int32(0) + if cutlass.const_expr(qk_ahead): + if j >= Int32(1): + _wait(p_full + (j & Int32(1)), j >> Int32(1) & Int32(1)) + ahead = _landed(kv_full, j + Int32(1), nslots) + if ahead != Int32(0): + _qk( + tmem, + s_q, + s_kv, + s_ext, + j + Int32(1), + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots, + ) + _pv( + tmem, + s_kv, + s_ext, + j, + p_full, + o_corr, + kv_empty, + s_empty, + o_full, + idesc_pv, + v_lo, + nslots, + tr, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV) + j, lane == Int32(0)) + if ahead == Int32(0): + _qk( + tmem, + s_q, + s_kv, + s_ext, + j + Int32(1), + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_QK + 1) + j, lane == Int32(0)) + else: + _pv( + tmem, + s_kv, + s_ext, + j, + p_full, + o_corr, + kv_empty, + s_empty, + o_full, + idesc_pv, + v_lo, + nslots, + tr, + ) + if cutlass.const_expr(pv_last is not None): + if prims.elect_sync(): + prims.tcgen05_commit(pv_last, group=prims.CTAGroup.CTA_1) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV) + j, lane == Int32(0)) + + +@cute.jit +def role_mma_ordered( + tmem, + s_q, + s_kv, + s_ext, + q_full, + kv_full, + kv_empty, + s_full, + s_empty, + p_full, + o_full, + v_lo, + ntiles: cutlass.Constexpr[int], + nslots: cutlass.Constexpr[int], + pv_last, + tr=None, + sel_ready=None, + idle_ns: cutlass.Constexpr[int] = 0, +): + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=E4M3, + b_dtype=E4M3, + a_major=0, + b_major=1, + n_dim=OUT_SLICE, + m_dim=HEADS, + ) + qdesc = prims.Tcgen05SmemDesc.build( + s_q, + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + lane = cute.arch.lane_idx() + _wait(q_full, Int32(0)) + _qk( + tmem, + s_q, + s_kv, + s_ext, + Int32(0), + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_QK), lane == Int32(0)) + _pv( + tmem, + s_kv, + s_ext, + Int32(0), + p_full, + None, + kv_empty, + s_empty, + o_full, + idesc_pv, + v_lo, + nslots, + tr, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV), lane == Int32(0)) + if cutlass.const_expr(sel_ready is not None): + _wait(sel_ready, Int32(0)) + for j in cutlass.range(1, ntiles + 1, unroll=1): + if j < Int32(ntiles): + _qk( + tmem, + s_q, + s_kv, + s_ext, + j, + kv_full, + kv_empty, + s_full, + s_empty, + qdesc, + idesc_qk, + v_lo, + nslots, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_QK) + j, lane == Int32(0)) + if j > Int32(1): + _pv( + tmem, + s_kv, + s_ext, + j - Int32(1), + p_full, + None, + kv_empty, + s_empty, + o_full, + idesc_pv, + v_lo, + nslots, + tr, + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV) + j - Int32(1), lane == Int32(0)) + if prims.elect_sync(): + prims.tcgen05_commit(pv_last, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def role_softmax_team( + tmem, + s_full, + p_full, + s_stat, + s_fin, + fin_bar, + scale_log2: Float32, + swa_len, + n_sel, + j0, + j1, + m_run, + l_run, + final: cutlass.Constexpr[bool], + tr=None, + o_full=None, + v_lo=None, + full_tiles: cutlass.Constexpr[bool] = False, +): + half_n: cutlass.Constexpr[int] = TILE_N // 2 + npk: cutlass.Constexpr[int] = TILE_N // 8 + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + head = warp * Int32(16) + (lane & Int32(15)) + lane_base = warp * Int32(32) << Int32(16) + col0 = (lane >> Int32(4)) * Int32(half_n) + for j in cutlass.range(j0, j1, unroll=1): + st = j & Int32(3) + _wait(s_full + st, j >> Int32(2) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + lane_base + st * Int32(TILE_N) + s = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(s_addr, Float32), + num=half_n, + offset=Int64(half_n), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + limit = Int32(WINDOW) + n_sel + if j == Int32(0): + limit = swa_len + nv_here = limit - (j * Int32(TILE_N) + col0) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + sv = [] + for i in cutlass.range_constexpr(half_n): + if cutlass.const_expr(full_tiles): + sv.append(Float32(s[i])) + else: + sv.append(cutlass.select_(nv_here > Int32(i), Float32(s[i]), Float32(NEG_FLT_MAX))) + for i in cutlass.range_constexpr(0, half_n, 4): + mx0 = cute.math.max(mx0, sv[i], ftz=True) + mx1 = cute.math.max(mx1, sv[i + 1], ftz=True) + mx2 = cute.math.max(mx2, sv[i + 2], ftz=True) + mx3 = cute.math.max(mx3, sv[i + 3], ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + bias = -scale_log2 * safe_max + Float32(LOG2_448) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for pk in cutlass.range_constexpr(npk): + x01 = cute.arch.fma_packed_f32x2( + (sv[4 * pk], sv[4 * pk + 1]), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + x23 = cute.arch.fma_packed_f32x2( + (sv[4 * pk + 2], sv[4 * pk + 3]), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = s_addr + Int32(TILE_N // 4) + if cutlass.const_expr(v_lo is not None): + # P lives in lane panel 1 next to O (the PV reads A from the same panel as D). + _tmem_st_p_fp8(p_addr + Int32(PANEL1), regs, npk) + else: + _tmem_st_p_fp8(p_addr, regs, npk) + _tmem_st_p_fp8(p_addr + Int32(PANEL1), regs, npk) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + exp_scale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if cutlass.const_expr(o_full is None): + if lane < Int32(16): + (s_stat + st * Int32(128) + head).store(old_max) + (s_stat + st * Int32(128) + Int32(64) + head).store(new_max) + if cutlass.const_expr(o_full is not None): + if j > Int32(0): + _wait(o_full, j - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + cscale = Float32(1.0) + if not ident: + cscale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + skip = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip: + o_addr0 = tmem + lane_base + Int32(O_COL4) + Int32(PANEL1) + ptr = prims.make_tmem_ptr(o_addr0, Float32) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + num=OUT_REGS, + offset=Int64(OUT_REGS), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + vals = [] + for rr in cutlass.range_constexpr(0, OUT_REGS, 2): + pr = cute.arch.mul_packed_f32x2( + (Float32(o[rr]), Float32(o[rr + 1])), + (cscale, cscale), + ftz=False, + rnd="rn", + ) + vals.append(pr[0]) + vals.append(pr[1]) + prims.tcgen05_st( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + cutlass.Vector.from_elements(tuple(vals), Float32), + offset=Int64(OUT_REGS), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(p_full + st) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_SM) + j, warp == Int32(0) and lane == Int32(0)) + if cutlass.const_expr(final): + l_tot = l_run + _shfl_xor_f32(l_run, 16) + if lane < Int32(16): + (s_fin + head).store(m_run) + (s_fin + Int32(64) + head).store(l_tot) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(fin_bar) + return (m_run, l_run) + + +@cute.jit +def _final_norm( + final_max: Float32, reduced_sum: Float32, sink: Float32, scale_log2: Float32 +) -> Float32: + t = cute.arch.mul_packed_f32x2( + (final_max, final_max), (scale_log2, scale_log2), ftz=False, rnd="rn" + )[0] + delta = cute.arch.fma_packed_f32x2( + (sink, sink), (Float32(LOG2_E), Float32(LOG2_E)), (-t, -t), ftz=False, rnd="rn" + )[0] + attention_rescale = cute.math.exp2(-cute.math.max(delta, Float32(0)), approx=True) + sink_mass = cute.math.exp2(cute.math.min(delta, Float32(0)), approx=True) + sink_mass *= Float32(448.0) + return ( + Float32(1.0) + * attention_rescale + * cute.math.rcp(reduced_sum * attention_rescale + sink_mass, approx=True) + ) + + +@cute.jit +def role_corr_epi_team( + tmem, + p_full, + o_full, + o_corr, + s_stat, + s_fin, + fin_bar, + sink_ptr, + out_addr: Int64, + scale_log2: Float32, + v_lo, + stage, + ntiles: cutlass.Constexpr[int], + bar_id: cutlass.Constexpr[int], + tr=None, + pv_last=None, + dry=None, +): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4) + lane = cute.arch.lane_idx() + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + sink = Float32((sink_ptr + head).load()) + o_addr0 = tmem + lane_base + Int32(O_COL4) + Int32(PANEL1) + if cutlass.const_expr(pv_last is None): + for j in cutlass.range(1, ntiles, unroll=1): + st = j & Int32(1) + _wait(p_full + st, j >> Int32(1) & Int32(1)) + old_max = (s_stat + st * Int32(128) + head).load() + new_max = (s_stat + st * Int32(128) + Int32(64) + head).load() + _wait(o_full, j - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + scale = Float32(1.0) + if not ident: + scale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + skip = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip: + for hc in cutlass.range_constexpr(OUT_REGS // 32): + ptr = prims.make_tmem_ptr(o_addr0 + Int32(32 * hc), Float32) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, ptr, num=32, offset=Int64(OUT_REGS) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + vals = [] + for rr in cutlass.range_constexpr(0, 32, 2): + pr = cute.arch.mul_packed_f32x2( + (Float32(o[rr]), Float32(o[rr + 1])), + (scale, scale), + ftz=False, + rnd="rn", + ) + vals.append(pr[0]) + vals.append(pr[1]) + prims.tcgen05_st( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + cutlass.Vector.from_elements(tuple(vals), Float32), + offset=Int64(OUT_REGS), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(o_corr) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_COR) + j, warp == Int32(0) and lane == Int32(0)) + # dry != 0: code warm-up during the warm-up pass (no waits, no output stores; values discarded) + wet = Int32(1) + if cutlass.const_expr(dry is not None): + wet = Int32(1) - dry + if wet != Int32(0): + if cutlass.const_expr(pv_last is None): + _wait(o_full, Int32(ntiles - 1 & 1)) + else: + _wait(pv_last, Int32(0)) + _wait(fin_bar, Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_FIN), warp == Int32(0) and lane == Int32(0)) + final_max = (s_fin + head).load() + reduced_sum = (s_fin + Int32(64) + head).load() + norm = _final_norm(final_max, reduced_sum, sink, scale_log2) + ob = [] + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr0, Float32), + num=OUT_REGS, + offset=Int64(OUT_REGS), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for pi in cutlass.range_constexpr(OUT_REGS // 2): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), (Float32(o[2 * pi]), Float32(o[2 * pi + 1])), ftz=False, rnd="rn" + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + # Each lane owns a contiguous 32-element output segment. Vector stores + # avoid the shared staging, CTA rendezvous, and bulk-store completion. + rowb = out_addr + Int64( + (head * Int32(LATENT) + v_lo * Int32(OUT_SLICE) + half * Int32(OUT_REGS)) * Int32(2) + ) + if wet != Int32(0): + for ch in cutlass.range_constexpr(OUT_REGS // 8): + L.st_g_v4( + rowb + Int64(ch * 16), ob[ch * 4], ob[ch * 4 + 1], ob[ch * 4 + 2], ob[ch * 4 + 3] + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_STORED), warp == Int32(0) and lane == Int32(0)) + + +# ===================================================================== 2 row groups x 4 V groups, DSMEM merge +RS24_O_COL = 384 # O accumulator: lane panel 1, columns 384-511 (N = 128); P_t at 128t + 32, t <= 2 +# team4 (wide_v): a CTA owns a 256-column V slice (vslices = 2 of the 4 KV slices of a tile) instead of 128: the PV MMA +# is N = 256 and the O accumulator sits at columns 256-511; the pair merge (_merge_22) hands the partner the 128 +# columns it owns +RS22_O_COL = 256 +RS24_DRY_MASK = 2047 # dry pass: every merge address wraps inside this CTA's 2 KB stat/fin scratch +assert 3 * TILE_N // 4 <= RS22_O_COL and RS22_O_COL + 2 * SLICE <= TMEM_COLS + + +def rs24_rx_bytes(f32x, wide_v=False): + # partner push: nchunk x [128 threads][16 B] partial O, then [128 threads][8 B] (max, sum); wide_v: twice the chunks + return (8 if f32x else 4) * (2 if wide_v else 1) * 2048 + 1024 + + +@_dsl_user_op +def _lds_vol(saddr, *, loc=None, ip=None): + return Int32( + L._asm( + L.T.i32(), [L._v(saddr, loc, ip)], "ld.volatile.shared.u32 $0, [$1];", "=r,r", loc, ip + ) + ) + + +@cute.jit +def rs24_tiles(d): + # row group g = d & 1: g == 0 -> tiles {0 (SWA), 1, 2}; g == 1 -> tiles {3, 4} + j0 = Int32(0) + cnt = Int32(3) + if (d & Int32(1)) != Int32(0): + j0 = Int32(3) + cnt = Int32(2) + return (j0, cnt) + + +LSU_ARR = ( + 128 # control WG threads arriving (noinc) on kv_full[4..7] of g = 1 CTAs when rs24_lsu > 0 +) + + +@cute.jit +def lsu_tile4( + tq, + d, + lsu_g: cutlass.Constexpr[int], + s_kv_a, + s_idx_a, + kvf_a, + kv_empty, + pool: Int64, + tr=None, + wide_v: cutlass.Constexpr[bool] = False, +): + # LSU-assisted gather (g = 1 CTAs, tile 4 = local tile 1, slots 4-7): groups [32 - lsu_g, 32) of every slot via + # cp.async (128 threads, 8 per 128 B row slice, SW128 swizzle by hand), then a noinc arrive per thread and slot + vslices: cutlass.Constexpr[int] = 2 if wide_v else 1 + k = d >> Int32(1) + t = Int32(1) + j = Int32(4) + sbase = (t & Int32(1)) * Int32(4) + epar = ((t >> Int32(1)) & Int32(1)) ^ Int32(1) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(53), tq == Int32(0)) + for step in cutlass.range(NSLICE, unroll=1): + sl = k * Int32(vslices) + Int32(vslices) + step & Int32(3) + slot = sbase + step + _wait(kv_empty + slot, epar) + for p in cutlass.range_constexpr(lsu_g // 4): + q = tq + Int32(p * LSU_ARR) + r = Int32((32 - lsu_g) * 4) + (q >> Int32(3)) + c = q & Int32(7) + row = cutlass.max(L.lds_u32(s_idx_a + (j * Int32(TILE_N) + r) * Int32(4)), Int32(0)) + src = pool + Int64(row) * Int64(LATENT) + Int64(sl * Int32(SLICE) + c * Int32(16)) + dst = ( + s_kv_a + + slot * Int32(SLOT_BYTES) + + r * Int32(SLICE) + + ((c ^ (r & Int32(7))) << Int32(4)) + ) + L.cp_async16(dst, src) + L.cp_async_mbar_arrive_noinc(kvf_a + slot * Int32(8)) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(54) + step, tq == Int32(0)) + + +@cute.jit +def role_gather_24( + tma_swa, + tma_cmp, + s_kv, + s_ext, + s_idx, + kv_full, + kv_empty, + swa_ready, + sel_early, + sel_ready, + gw, + d, + ntiles: cutlass.Constexpr[int], + tr=None, + above_ptr=None, + lsu_g: cutlass.Constexpr[int] = 0, + wide_v: cutlass.Constexpr[bool] = False, +): + # above_ptr (t4split): the last tile's rows below `above` (selection-certain) are gathered at the early release + vslices: cutlass.Constexpr[int] = 2 if wide_v else 1 + lane = cute.arch.lane_idx() + k = d >> Int32(1) + j0, cnt = rs24_tiles(d) + g = lane * Int32(NGW) + gw + for t in cutlass.range(cnt, unroll=1): + j = j0 + t + lo_g = Int32(0) + if j == Int32(0): + _wait(swa_ready, Int32(0)) + elif j == Int32(ntiles - 1): + if cutlass.const_expr(above_ptr is not None): + _wait(sel_early, Int32(0)) + lo_g = cutlass.max( + Int32(0), + cutlass.min( + Int32(TILE_N // 4), + (above_ptr.load() - j * Int32(TILE_N) + Int32(WINDOW)) // Int32(4), + ), + ) + else: + _wait(sel_ready, Int32(0)) + else: + _wait(sel_early, Int32(0)) + tm = tma_cmp.get_ptr().toint() + if j == Int32(0): + tm = tma_swa.get_ptr().toint() + g_t = Int32(TILE_N // 4) + if cutlass.const_expr(lsu_g > 0): + if j == Int32(ntiles - 1): + g_t = Int32(TILE_N // 4 - lsu_g) + hi_g = g_t + if cutlass.const_expr(above_ptr is not None): + if j == Int32(ntiles - 1): + hi_g = cutlass.min(lo_g, g_t) + sbase = (t & Int32(1)) * Int32(4) + epar = ((t >> Int32(1)) & Int32(1)) ^ Int32(1) + for step in cutlass.range_constexpr(NSLICE): + sl = k * Int32(vslices) + Int32(vslices + step) & Int32(3) + slot = sbase + Int32(step) + _wait(kv_empty + slot, epar) + if gw == Int32(0): + if lane == Int32(0): + if cutlass.const_expr(lsu_g > 0): + prims.mbarrier_arrive_expect_tx(kv_full + slot, g_t * Int32(4 * SLICE)) + else: + prims.mbarrier_arrive_expect_tx(kv_full + slot, SLOT_BYTES) + if g < hi_g: + r4 = L.lds_v4(Int32(s_idx.toint()) + (j * Int32(TILE_N) + g * Int32(4)) * Int32(4)) + dst = Int32(_slot_ptr(s_kv, s_ext, slot).toint()) + g * Int32(4 * SLICE) + L.tma_g4( + dst, + tm, + sl * Int32(SLICE), + r4[0], + r4[1], + r4[2], + r4[3], + Int32(kv_full.toint()) + slot * Int32(8), + ) + if cutlass.const_expr(above_ptr is not None): + if j == Int32(ntiles - 1): + _wait(sel_ready, Int32(0)) + for step in cutlass.range_constexpr(NSLICE): + sl = k * Int32(vslices) + Int32(vslices + step) & Int32(3) + slot = sbase + Int32(step) + if g >= hi_g and g < g_t: + r4 = L.lds_v4( + Int32(s_idx.toint()) + (j * Int32(TILE_N) + g * Int32(4)) * Int32(4) + ) + dst = Int32(_slot_ptr(s_kv, s_ext, slot).toint()) + g * Int32(4 * SLICE) + L.tma_g4( + dst, + tm, + sl * Int32(SLICE), + r4[0], + r4[1], + r4[2], + r4[3], + Int32(kv_full.toint()) + slot * Int32(8), + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_G) + j, gw == Int32(0) and lane == Int32(0)) + + +@cute.jit +def _qk_24( + tmem, + s_q, + s_kv, + s_ext, + t, + k, + kv_full, + kv_empty, + s_full, + qdesc, + idesc_qk, + pfence: cutlass.Constexpr[bool] = False, + wide_v: cutlass.Constexpr[bool] = False, +): + vslices: cutlass.Constexpr[int] = 2 if wide_v else 1 + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + t * Int32(TILE_N) + sbase = (t & Int32(1)) * Int32(4) + fpar = (t >> Int32(1)) & Int32(1) + for step in cutlass.range_constexpr(NSLICE): + c = k * Int32(vslices) + Int32(vslices + step) & Int32(3) + slot = sbase + Int32(step) + _wait(kv_full + slot, fpar) + if cutlass.const_expr(pfence): + # the slot may hold cp.async (generic proxy) bytes: order them before the tensor core's async-proxy reads + L.fence_proxy_async_smem() + kdesc = prims.Tcgen05SmemDesc.build( + _slot_ptr(s_kv, s_ext, slot), + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(SLICE // 32): + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(c * Int32(Q_SLICE_BYTES) + Int32(kb * 32)), + kdesc.advance_start_address(kb * 32), + idesc_qk, + Boolean(step > 0 or kb > 0), + ) + if cutlass.const_expr(step < NSLICE - vslices): + prims.tcgen05_commit(kv_empty + slot, group=prims.CTAGroup.CTA_1) + if prims.elect_sync(): + prims.tcgen05_commit(s_full + t, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def _pv_24( + tmem, + s_kv, + s_ext, + t, + p_full, + kv_empty, + o_full, + idesc_pv, + wide_v: cutlass.Constexpr[bool] = False, +): + vslices: cutlass.Constexpr[int] = 2 if wide_v else 1 + o_col: cutlass.Constexpr[int] = RS22_O_COL if wide_v else RS24_O_COL + _wait(p_full + t, Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + a_addr = tmem + t * Int32(TILE_N) + Int32(TILE_N // 4) + Int32(PANEL1) + if cutlass.const_expr(wide_v): + a_addr = tmem + t * Int32(TILE_N // 4) + Int32(PANEL1) + slot = (t & Int32(1)) * Int32(4) + Int32(NSLICE - vslices) + d_addr = tmem + Int32(o_col) + Int32(PANEL1) + vdesc = prims.Tcgen05SmemDesc.build( + _slot_ptr(s_kv, s_ext, slot), + leading_byte_offset=SLOT_BYTES if wide_v else 0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + acc0 = Boolean(t > Int32(0)) + if prims.elect_sync(): + for kb in cutlass.range_constexpr(TILE_N // 32): + en = acc0 if cutlass.const_expr(kb == 0) else Boolean(True) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + for v in cutlass.range_constexpr(vslices): + prims.tcgen05_commit(kv_empty + slot + Int32(v), group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(o_full, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def role_mma_24( + tmem, + s_q, + s_kv, + s_ext, + q_full, + kv_full, + kv_empty, + s_full, + p_full, + o_full, + d, + pv_last, + tr=None, + pfence: cutlass.Constexpr[bool] = False, + wide_v: cutlass.Constexpr[bool] = False, +): + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=E4M3, + b_dtype=E4M3, + a_major=0, + b_major=1, + n_dim=256 if wide_v else 128, + m_dim=HEADS, + ) + qdesc = prims.Tcgen05SmemDesc.build( + s_q, + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + lane = cute.arch.lane_idx() + k = d >> Int32(1) + j0, cnt = rs24_tiles(d) + _wait(q_full, Int32(0)) + # E1d order: QK of the next tile is issued before PV of the current one (its softmax overlaps the next QK); the SWA + # tile's PV goes right after its QK (its P is ready long before tile 1 lands) + pvn = Int32(0) + for t in cutlass.range(cnt, unroll=1): + _qk_24( + tmem, s_q, s_kv, s_ext, t, k, kv_full, kv_empty, s_full, qdesc, idesc_qk, pfence, wide_v + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_QK) + j0 + t, lane == Int32(0)) + if t == Int32(0) and j0 == Int32(0) or t > pvn: + _pv_24(tmem, s_kv, s_ext, pvn, p_full, kv_empty, o_full, idesc_pv, wide_v) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV) + j0 + pvn, lane == Int32(0)) + pvn = pvn + Int32(1) + _pv_24(tmem, s_kv, s_ext, pvn, p_full, kv_empty, o_full, idesc_pv, wide_v) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_PV) + j0 + pvn, lane == Int32(0)) + if prims.elect_sync(): + prims.tcgen05_commit(pv_last, group=prims.CTAGroup.CTA_1) + + +@cute.jit +def _merge_24( + tmem, + tq, + d, + m_me, + l_me, + sink_ptr, + out_addr: Int64, + rx_s, + stat_s, + pvl_a, + rx_a, + pr_a, + dry_a, + scale_log2: Float32, + dry, + tr=None, + f32x: cutlass.Constexpr[bool] = False, +): + # Pair merge on the softmax warpgroup (128 threads, tq = loop-variant thread index; thread (head, half) holds O + # columns 64c + 32 half + [0, 32) of block c). Push block g ^ 1 to the partner, combine block g with its push. + nchunk: cutlass.Constexpr[int] = 8 if f32x else 4 + data_b: cutlass.Constexpr[int] = nchunk * 2048 + warp = tq >> Int32(5) + lane = tq & Int32(31) + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + g = d & Int32(1) + k = d >> Int32(1) + wet = dry == Int32(0) + sink = Float32((sink_ptr + head).load()) + # dry: a parity-1 wait on the private barrier returns at once + L.wait_cl(cutlass.select_(wet, pvl_a, dry_a), cutlass.select_(wet, Int32(0), Int32(1))) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_FIN), tq == Int32(0)) + o_base = tmem + lane_base + Int32(RS24_O_COL) + Int32(PANEL1) + po = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_base + Int32(64) * (g ^ Int32(1)), Float32), + num=32, + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + if wet: + cute.arch.cluster_wait() + # the partner's selection scratch is free (its control WG arrived on our B_PR) + L.wait_cl(cutlass.select_(wet, pr_a, dry_a), cutlass.select_(wet, Int32(0), Int32(1))) + me = L.cluster_ctarank() + trank = cutlass.select_(wet, me ^ Int32(1), me) + amask = cutlass.select_(wet, Int32(-1), Int32(RS24_DRY_MASK)) + rc = L.mapa_u32(cutlass.select_(wet, rx_s, stat_s), trank) + mc = L.mapa_u32(cutlass.select_(wet, rx_a, dry_a), trank) + if cutlass.const_expr(f32x): + for i in cutlass.range_constexpr(8): + L.st_async_v4( + rc + (((Int32(i * 128) + tq) * Int32(16)) & amask), + mc, + L.u32_of_f32(Float32(po[4 * i])), + L.u32_of_f32(Float32(po[4 * i + 1])), + L.u32_of_f32(Float32(po[4 * i + 2])), + L.u32_of_f32(Float32(po[4 * i + 3])), + ) + else: + for i in cutlass.range_constexpr(4): + L.st_async_v4( + rc + (((Int32(i * 128) + tq) * Int32(16)) & amask), + mc, + _pack_bf16x2(Float32(po[8 * i]), Float32(po[8 * i + 1])), + _pack_bf16x2(Float32(po[8 * i + 2]), Float32(po[8 * i + 3])), + _pack_bf16x2(Float32(po[8 * i + 4]), Float32(po[8 * i + 5])), + _pack_bf16x2(Float32(po[8 * i + 6]), Float32(po[8 * i + 7])), + ) + L.st_async_v2( + rc + ((Int32(data_b) + tq * Int32(8)) & amask), mc, L.u32_of_f32(m_me), L.u32_of_f32(l_me) + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(121), tq == Int32(0)) + own = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_base + Int32(64) * g, Float32), + num=32, + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + # the partner's push landed (B_RX expects its bytes from kernel start); dry: our own dry stores landed + L.wait_cl(cutlass.select_(wet, rx_a, dry_a), Int32(0)) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(123), tq == Int32(0)) + lb = cutlass.select_(wet, rx_s, stat_s) + xs = [] + for i in cutlass.range_constexpr(nchunk): + xs.append(L.lds_v4(lb + (((Int32(i * 128) + tq) * Int32(16)) & amask))) + sa = lb + ((Int32(data_b) + tq * Int32(8)) & amask) + m_p = L.f32_of_u32(Uint32(L.lds_u32(sa))) + l_p = L.f32_of_u32(Uint32(L.lds_u32(sa + Int32(4)))) + m = cute.math.max(m_me, m_p, ftz=True) + w_me = cute.math.exp2(scale_log2 * (m_me - m), fastmath=True) + w_p = cute.math.exp2(scale_log2 * (m_p - m), fastmath=True) + l_sum = w_me * l_me + w_p * l_p + acc = [] + for i in cutlass.range_constexpr(32): + acc.append(w_me * Float32(own[i])) + if cutlass.const_expr(f32x): + for i in cutlass.range_constexpr(8): + for e in cutlass.range_constexpr(4): + acc[4 * i + e] = acc[4 * i + e] + w_p * L.f32_of_u32(Uint32(xs[i][e])) + else: + for i in cutlass.range_constexpr(4): + for e in cutlass.range_constexpr(4): + wd = Uint32(xs[i][e]) + acc[8 * i + 2 * e] = acc[8 * i + 2 * e] + w_p * L.f32_of_u32(wd << Uint32(16)) + acc[8 * i + 2 * e + 1] = acc[8 * i + 2 * e + 1] + w_p * L.f32_of_u32( + wd & Uint32(4294901760) + ) + norm = _final_norm(m, l_sum, sink, scale_log2) + ob = [] + for pi in cutlass.range_constexpr(16): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), (acc[2 * pi], acc[2 * pi + 1]), ftz=False, rnd="rn" + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(124), tq == Int32(0)) + # dry: the same stores with throw-away values (this CTA's own output block; the real pass overwrites it) + rowb = out_addr + Int64( + (head * Int32(LATENT) + k * Int32(128) + g * Int32(64) + half * Int32(32)) * Int32(2) + ) + for ch in cutlass.range_constexpr(4): + L.st_g_v4(rowb + Int64(ch * 16), ob[ch * 4], ob[ch * 4 + 1], ob[ch * 4 + 2], ob[ch * 4 + 3]) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_STORED), tq == Int32(0)) + + +@cute.jit +def _merge_24a( + tmem, + tq, + d, + m_me, + l_me, + sink_ptr, + out_addr: Int64, + rx_s, + stat_s, + pvl_a, + rx_a, + pr_a, + dry_a, + scale_log2: Float32, + dry, + tr=None, +): + # Asymmetric pair merge (rs24_asym): row group 0 (tiles 0-2, no boundary-rank dependency; it finishes first) pushes + # its whole 128-column partial O (bf16) + (max, sum) to row group 1, which combines and stores all 128 columns of + # the V group. No DSMEM round trip after the last PV. Thread (head, half) holds columns 64c + 32 half + [0, 32). + warp = tq >> Int32(5) + lane = tq & Int32(31) + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + g = d & Int32(1) + k = d >> Int32(1) + wet = dry == Int32(0) + L.wait_cl(cutlass.select_(wet, pvl_a, dry_a), cutlass.select_(wet, Int32(0), Int32(1))) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_FIN), tq == Int32(0)) + o_base = tmem + lane_base + Int32(RS24_O_COL) + Int32(PANEL1) + o0 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_base, Float32), + num=32, + offset=Int64(32), + ) + o1 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_base + Int32(64), Float32), + num=32, + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + amask = cutlass.select_(wet, Int32(-1), Int32(RS24_DRY_MASK)) + if g == Int32(0): + if wet: + cute.arch.cluster_wait() + L.wait_cl(cutlass.select_(wet, pr_a, dry_a), cutlass.select_(wet, Int32(0), Int32(1))) + me = L.cluster_ctarank() + trank = cutlass.select_(wet, me ^ Int32(1), me) + rc = L.mapa_u32(cutlass.select_(wet, rx_s, stat_s), trank) + mc = L.mapa_u32(cutlass.select_(wet, rx_a, dry_a), trank) + for i in cutlass.range_constexpr(4): + L.st_async_v4( + rc + (((Int32(i * 128) + tq) * Int32(16)) & amask), + mc, + _pack_bf16x2(Float32(o0[8 * i]), Float32(o0[8 * i + 1])), + _pack_bf16x2(Float32(o0[8 * i + 2]), Float32(o0[8 * i + 3])), + _pack_bf16x2(Float32(o0[8 * i + 4]), Float32(o0[8 * i + 5])), + _pack_bf16x2(Float32(o0[8 * i + 6]), Float32(o0[8 * i + 7])), + ) + for i in cutlass.range_constexpr(4): + L.st_async_v4( + rc + (((Int32((i + 4) * 128) + tq) * Int32(16)) & amask), + mc, + _pack_bf16x2(Float32(o1[8 * i]), Float32(o1[8 * i + 1])), + _pack_bf16x2(Float32(o1[8 * i + 2]), Float32(o1[8 * i + 3])), + _pack_bf16x2(Float32(o1[8 * i + 4]), Float32(o1[8 * i + 5])), + _pack_bf16x2(Float32(o1[8 * i + 6]), Float32(o1[8 * i + 7])), + ) + L.st_async_v2( + rc + ((Int32(8 * 2048) + tq * Int32(8)) & amask), + mc, + L.u32_of_f32(m_me), + L.u32_of_f32(l_me), + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(121), tq == Int32(0)) + _stamp(tr, Int32(TS_STORED), tq == Int32(0)) + else: + sink = Float32((sink_ptr + head).load()) + # the partner's push landed (B_RX expects it from kernel start); dry: a parity-1 wait returns at once + L.wait_cl(cutlass.select_(wet, rx_a, dry_a), cutlass.select_(wet, Int32(0), Int32(1))) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(123), tq == Int32(0)) + lb = cutlass.select_(wet, rx_s, stat_s) + xs = [] + for i in cutlass.range_constexpr(8): + xs.append(L.lds_v4(lb + (((Int32(i * 128) + tq) * Int32(16)) & amask))) + sa = lb + ((Int32(8 * 2048) + tq * Int32(8)) & amask) + m_p = L.f32_of_u32(Uint32(L.lds_u32(sa))) + l_p = L.f32_of_u32(Uint32(L.lds_u32(sa + Int32(4)))) + m = cute.math.max(m_me, m_p, ftz=True) + w_me = cute.math.exp2(scale_log2 * (m_me - m), fastmath=True) + w_p = cute.math.exp2(scale_log2 * (m_p - m), fastmath=True) + norm = _final_norm(m, w_me * l_me + w_p * l_p, sink, scale_log2) + wn_me = w_me * norm + wn_p = w_p * norm + for c in cutlass.range_constexpr(2): + oc = o0 if cutlass.const_expr(c == 0) else o1 + ob = [] + for i in cutlass.range_constexpr(4): + for e in cutlass.range_constexpr(4): + wd = Uint32(xs[4 * c + i][e]) + a0 = wn_me * Float32(oc[8 * i + 2 * e]) + wn_p * L.f32_of_u32(wd << Uint32(16)) + a1 = wn_me * Float32(oc[8 * i + 2 * e + 1]) + wn_p * L.f32_of_u32( + wd & Uint32(4294901760) + ) + ob.append(_pack_bf16x2(a0, a1)) + # dry: the same stores with throw-away values (this CTA's own output block; the real pass overwrites it) + rowb = out_addr + Int64( + (head * Int32(LATENT) + k * Int32(128) + Int32(64 * c) + half * Int32(32)) + * Int32(2) + ) + for ch in cutlass.range_constexpr(4): + L.st_g_v4( + rowb + Int64(ch * 16), + ob[ch * 4], + ob[ch * 4 + 1], + ob[ch * 4 + 2], + ob[ch * 4 + 3], + ) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_STORED), tq == Int32(0)) + + +@cute.jit +def _merge_22( + tmem, tq, d, m_me, l_me, sink_ptr, out_addr: Int64, rx_s, pvl_a, rx_a, pr_a, scale_log2: Float32 +): + # team4 pair merge (CTAs of the two row groups g = 0, 1 that share a V slice k): each CTA pushes the 128 columns of + # its 256-column O accumulator that the partner owns (BF16, st.async into the partner's rx buffer, completing its + # rx mbarrier) with its (max, sum), then combines its own columns with the partner's, applies the sink and the + # final normalisation, and writes its 128 columns of the output. + warp = tq >> Int32(5) + lane = tq & Int32(31) + head = warp * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = warp * Int32(32) << Int32(16) + g = d & Int32(1) + k = d >> Int32(1) + sink = Float32((sink_ptr + head).load()) + L.wait_cl(pvl_a, Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + cute.arch.cluster_wait() + L.wait_cl(pr_a, Int32(0)) + peer = L.cluster_ctarank() ^ Int32(1) + rc = L.mapa_u32(rx_s, peer) + mc = L.mapa_u32(rx_a, peer) + o_base = tmem + lane_base + Int32(RS22_O_COL + PANEL1) + for ch in cutlass.range(2, unroll=1): + src = o_base + Int32(128) * (g ^ Int32(1)) + ch * Int32(64) + po = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(src, Float32), + num=32, + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + for i in cutlass.range_constexpr(4): + dst = rc + (ch * Int32(512) + Int32(i * 128) + tq) * Int32(16) + L.st_async_v4( + dst, + mc, + _pack_bf16x2(Float32(po[8 * i]), Float32(po[8 * i + 1])), + _pack_bf16x2(Float32(po[8 * i + 2]), Float32(po[8 * i + 3])), + _pack_bf16x2(Float32(po[8 * i + 4]), Float32(po[8 * i + 5])), + _pack_bf16x2(Float32(po[8 * i + 6]), Float32(po[8 * i + 7])), + ) + L.st_async_v2(rc + Int32(16384) + tq * Int32(8), mc, L.u32_of_f32(m_me), L.u32_of_f32(l_me)) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + L.wait_cl(rx_a, Int32(0)) + sa = rx_s + Int32(16384) + tq * Int32(8) + m_p = L.f32_of_u32(Uint32(L.lds_u32(sa))) + l_p = L.f32_of_u32(Uint32(L.lds_u32(sa + Int32(4)))) + m = cute.math.max(m_me, m_p, ftz=True) + w_me = cute.math.exp2(scale_log2 * (m_me - m), fastmath=True) + w_p = cute.math.exp2(scale_log2 * (m_p - m), fastmath=True) + l_sum = w_me * l_me + w_p * l_p + norm = _final_norm(m, l_sum, sink, scale_log2) + for ch in cutlass.range(2, unroll=1): + src = o_base + g * Int32(128) + ch * Int32(64) + own = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(src, Float32), + num=32, + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + xs = [] + for i in cutlass.range_constexpr(4): + xs.append(L.lds_v4(rx_s + (ch * Int32(512) + Int32(i * 128) + tq) * Int32(16))) + acc = [] + for i in cutlass.range_constexpr(32): + acc.append(w_me * Float32(own[i])) + for i in cutlass.range_constexpr(4): + for e in cutlass.range_constexpr(4): + wd = Uint32(xs[i][e]) + acc[8 * i + 2 * e] = acc[8 * i + 2 * e] + w_p * L.f32_of_u32(wd << Uint32(16)) + acc[8 * i + 2 * e + 1] = acc[8 * i + 2 * e + 1] + w_p * L.f32_of_u32( + wd & Uint32(4294901760) + ) + ob = [] + for pi in cutlass.range_constexpr(16): + fp = cute.arch.mul_packed_f32x2( + (norm, norm), (acc[2 * pi], acc[2 * pi + 1]), ftz=False, rnd="rn" + ) + ob.append(_pack_bf16x2(fp[0], fp[1])) + rowb = out_addr + Int64( + ( + head * Int32(LATENT) + + k * Int32(256) + + g * Int32(128) + + ch * Int32(64) + + half * Int32(32) + ) + * Int32(2) + ) + for i in cutlass.range_constexpr(4): + L.st_g_v4(rowb + Int64(i * 16), ob[i * 4], ob[i * 4 + 1], ob[i * 4 + 2], ob[i * 4 + 3]) + + +@cute.jit +def role_softmax_24( + tmem, + s_full, + p_full, + scale_log2: Float32, + swa_len, + n_sel, + d, + o_full, + sink_ptr, + out_addr: Int64, + rx_s, + stat_s, + pvl_a, + rx_a, + pr_a, + dry_a, + zaddr, + tr=None, + full_tiles: cutlass.Constexpr[bool] = False, + dry_merge: cutlass.Constexpr[bool] = True, + f32x: cutlass.Constexpr[bool] = False, + asym: cutlass.Constexpr[bool] = False, + wide_v: cutlass.Constexpr[bool] = False, +): + # Softmax of this CTA's tiles, then the pair merge. With dry_merge the merge first runs dry at the same call site + # in the idle window (g == 0: after the SWA tile; g == 1: before its first tile) so the real merge runs warm. + half_n: cutlass.Constexpr[int] = TILE_N // 2 + npk: cutlass.Constexpr[int] = TILE_N // 8 + o_col: cutlass.Constexpr[int] = RS22_O_COL if wide_v else RS24_O_COL + ochunks: cutlass.Constexpr[int] = 4 if wide_v else 2 + tid0 = (cute.arch.make_warp_uniform(cute.arch.warp_idx()) % Int32(4)) * Int32( + 32 + ) + cute.arch.lane_idx() + L.sts_u32(zaddr, Int32(0)) + j0, cnt = rs24_tiles(d) + t_pre = Int32(1) - (d & Int32(1)) + ps0 = Int32(1) + if cutlass.const_expr(dry_merge): + ps0 = Int32(0) + m_run = Float32(NEG_FLT_MAX) + l_run = Float32(0.0) + for ps in cutlass.range(ps0, 2, unroll=1): + # loop-variant thread index: keeps LLVM from hoisting the per-thread math in front of this loop + tq = tid0 + _lds_vol(zaddr) + warp = tq >> Int32(5) + lane = tq & Int32(31) + lane_base = warp * Int32(32) << Int32(16) + col0 = (lane >> Int32(4)) * Int32(half_n) + tb = Int32(0) + te = cnt + if cutlass.const_expr(dry_merge): + te = t_pre + if ps == Int32(1): + tb = t_pre + te = cnt + for t in cutlass.range(tb, te, unroll=1): + j = j0 + t + _wait(s_full + t, Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + s_addr = tmem + lane_base + t * Int32(TILE_N) + s = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(s_addr, Float32), + num=half_n, + offset=Int64(half_n), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + limit = Int32(WINDOW) + n_sel + if j == Int32(0): + limit = swa_len + nv_here = limit - (j * Int32(TILE_N) + col0) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + sv = [] + for i in cutlass.range_constexpr(half_n): + if cutlass.const_expr(full_tiles): + sv.append(Float32(s[i])) + else: + sv.append( + cutlass.select_(nv_here > Int32(i), Float32(s[i]), Float32(NEG_FLT_MAX)) + ) + for i in cutlass.range_constexpr(0, half_n, 4): + mx0 = cute.math.max(mx0, sv[i], ftz=True) + mx1 = cute.math.max(mx1, sv[i + 1], ftz=True) + mx2 = cute.math.max(mx2, sv[i + 2], ftz=True) + mx3 = cute.math.max(mx3, sv[i + 3], ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + bias = -scale_log2 * safe_max + Float32(LOG2_448) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for pk in cutlass.range_constexpr(npk): + x01 = cute.arch.fma_packed_f32x2( + (sv[4 * pk], sv[4 * pk + 1]), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + x23 = cute.arch.fma_packed_f32x2( + (sv[4 * pk + 2], sv[4 * pk + 3]), + (scale_log2, scale_log2), + (bias, bias), + ftz=False, + rnd="rn", + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = s_addr + Int32(TILE_N // 4) + if cutlass.const_expr(wide_v): + p_addr = tmem + lane_base + t * Int32(TILE_N // 4) + _tmem_st_p_fp8(p_addr + Int32(PANEL1), regs, npk) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + exp_scale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if t > Int32(0): + # O holds PV of the previous tile: rescale its 128 columns once + _wait(o_full, t - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + cscale = Float32(1.0) + if not ident: + cscale = cute.math.exp2(scale_log2 * (old_max - new_max), fastmath=True) + skip = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip: + for ch in cutlass.range_constexpr(ochunks): + ptr = prims.make_tmem_ptr( + tmem + lane_base + Int32(o_col + 64 * ch) + Int32(PANEL1), Float32 + ) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, ptr, num=32, offset=Int64(32) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + vals = [] + for rr in cutlass.range_constexpr(0, 32, 2): + pr = cute.arch.mul_packed_f32x2( + (Float32(o[rr]), Float32(o[rr + 1])), + (cscale, cscale), + ftz=False, + rnd="rn", + ) + vals.append(pr[0]) + vals.append(pr[1]) + prims.tcgen05_st( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + ptr, + cutlass.Vector.from_elements(tuple(vals), Float32), + offset=Int64(32), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.sync_warp() + if prims.elect_sync(): + prims.mbarrier_arrive(p_full + t) + if cutlass.const_expr(tr is not None): + _stamp(tr, Int32(TS_SM) + j, warp == Int32(0) and lane == Int32(0)) + l_tot = l_run + _shfl_xor_f32(l_run, 16) + if cutlass.const_expr(wide_v): + _merge_22( + tmem, tq, d, m_run, l_tot, sink_ptr, out_addr, rx_s, pvl_a, rx_a, pr_a, scale_log2 + ) + elif cutlass.const_expr(asym): + _merge_24a( + tmem, + tq, + d, + m_run, + l_tot, + sink_ptr, + out_addr, + rx_s, + stat_s, + pvl_a, + rx_a, + pr_a, + dry_a, + scale_log2, + Int32(1) - ps, + tr, + ) + else: + _merge_24( + tmem, + tq, + d, + m_run, + l_tot, + sink_ptr, + out_addr, + rx_s, + stat_s, + pvl_a, + rx_a, + pr_a, + dry_a, + scale_log2, + Int32(1) - ps, + tr, + f32x, + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_lib.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_lib.py new file mode 100644 index 000000000000..0858ede0bebd --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_lib.py @@ -0,0 +1,2804 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""specDSA megakernel, device helpers: PTX wrappers, the selection primitives of the exact top-512 (sortable +float keys, histograms, crossing-bin search, warp and block reductions, memory helpers) and the L2 cache-policy +constants. + +The constants that follow from the model (top-K) are defined from the ``DS_V4_FLASH`` spec of ``config.py``. +""" + +import cutlass +import cutlass.cute as cute +import cutlass.cute.math as cmath +from cutlass import Float32, Int32, Int64, Uint32, Uint64 +from cutlass._mlir.dialects import arith as mlir_arith +from cutlass._mlir.dialects import llvm +from cutlass._mlir.dialects import math as mlir_math +from cutlass.cutlass_dsl import T, dsl_user_op + +from .config import DS_V4_FLASH as SPEC + +# ==================================================================================================================== +# Inline PTX helpers: bulk and TMA gather copies, mbarriers, cluster and DSMEM operations, timers. +# ==================================================================================================================== + + +def _v(x, loc, ip): + return x.ir_value(loc=loc, ip=ip) + + +@dsl_user_op +def gtimer(*, loc=None, ip=None): + return Int64(_asm(T.i64(), [], "mov.u64 $0, %globaltimer;", "=l", loc, ip)) + + +@dsl_user_op +def clk64(*, loc=None, ip=None): + return Int64(_asm(T.i64(), [], "mov.u64 $0, %clock64;", "=l", loc, ip)) + + +@dsl_user_op +def smid(*, loc=None, ip=None): + return Int32(_asm(T.i32(), [], "mov.u32 $0, %smid;", "=r", loc, ip)) + + +@dsl_user_op +def cluster_ctarank(*, loc=None, ip=None): + return Int32(_asm(T.i32(), [], "mov.u32 $0, %cluster_ctarank;", "=r", loc, ip)) + + +@dsl_user_op +def nanosleep(ns, *, loc=None, ip=None): + _asm(None, [_v(ns, loc, ip)], "nanosleep.u32 $0;", "r", loc, ip) + + +@dsl_user_op +def fence_acq_rel_gpu(*, loc=None, ip=None): + _asm(None, [], "fence.acq_rel.gpu;", "", loc, ip) + + +@dsl_user_op +def fence_proxy_async_smem(*, loc=None, ip=None): + _asm(None, [], "fence.proxy.async.shared::cta;", "", loc, ip) + + +@dsl_user_op +def fence_proxy_async_global(*, loc=None, ip=None): + _asm(None, [], "fence.proxy.async.global;", "", loc, ip) + + +@dsl_user_op +def fence_mbar_init_cluster(*, loc=None, ip=None): + _asm(None, [], "fence.mbarrier_init.release.cluster;", "", loc, ip) + + +@dsl_user_op +def ld_acq_gpu_u32(addr, *, loc=None, ip=None): + return Int32( + _asm(T.i32(), [_v(addr, loc, ip)], "ld.acquire.gpu.global.u32 $0, [$1];", "=r,l", loc, ip) + ) + + +@dsl_user_op +def ld_rlx_gpu_u32(addr, *, loc=None, ip=None): + return Int32( + _asm(T.i32(), [_v(addr, loc, ip)], "ld.relaxed.gpu.global.u32 $0, [$1];", "=r,l", loc, ip) + ) + + +@dsl_user_op +def st_rel_gpu_u32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "st.release.gpu.global.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def red_add_rel_gpu_u32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.release.gpu.global.add.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def st_g_v4(addr, a, b, c, d, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(a, loc, ip), _v(b, loc, ip), _v(c, loc, ip), _v(d, loc, ip)], + "st.global.v4.b32 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def st_g_cg_v4(addr, a, b, c, d, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(a, loc, ip), _v(b, loc, ip), _v(c, loc, ip), _v(d, loc, ip)], + "st.global.cg.v4.b32 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def ldg_cg_v4(gaddr, *, loc=None, ip=None): + ret = _asm( + llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), + [_v(gaddr, loc, ip)], + "ld.global.cg.v4.u32 {$0, $1, $2, $3}, [$4];", + "=r,=r,=r,=r,l", + loc, + ip, + ) + return tuple((Int32(llvm.extractvalue(T.i32(), ret, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def ldg_nc_v4(gaddr, *, loc=None, ip=None): + ret = _asm( + llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), + [_v(gaddr, loc, ip)], + "ld.global.nc.L1::no_allocate.v4.u32 {$0, $1, $2, $3}, [$4];", + "=r,=r,=r,=r,l", + loc, + ip, + ) + return tuple((Int32(llvm.extractvalue(T.i32(), ret, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def prefetch_l2_line(gaddr, *, loc=None, ip=None): + _asm(None, [_v(gaddr, loc, ip)], "prefetch.global.L2 [$0];", "l", loc, ip) + + +@dsl_user_op +def bulk_prefetch_l2(gaddr, nbytes, *, loc=None, ip=None): + _asm( + None, + [_v(gaddr, loc, ip), _v(nbytes, loc, ip)], + "cp.async.bulk.prefetch.L2.global [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def lds_u32(saddr, *, loc=None, ip=None): + return Int32(_asm(T.i32(), [_v(saddr, loc, ip)], "ld.shared.u32 $0, [$1];", "=r,r", loc, ip)) + + +@dsl_user_op +def lds_v4(saddr, *, loc=None, ip=None): + ret = _asm( + llvm.StructType.get_literal([T.i32(), T.i32(), T.i32(), T.i32()]), + [_v(saddr, loc, ip)], + "ld.shared.v4.u32 {$0, $1, $2, $3}, [$4];", + "=r,=r,=r,=r,r", + loc, + ip, + ) + return tuple((Int32(llvm.extractvalue(T.i32(), ret, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def sts_u32(saddr, val, *, loc=None, ip=None): + _asm(None, [_v(saddr, loc, ip), _v(val, loc, ip)], "st.shared.u32 [$0], $1;", "r,r", loc, ip) + + +@dsl_user_op +def sts_v4(saddr, a, b, c, d, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(a, loc, ip), _v(b, loc, ip), _v(c, loc, ip), _v(d, loc, ip)], + "st.shared.v4.b32 [$0], {$1, $2, $3, $4};", + "r,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def mapa_u32(saddr, rank, *, loc=None, ip=None): + return Int32( + _asm( + T.i32(), + [_v(saddr, loc, ip), _v(rank, loc, ip)], + "mapa.shared::cluster.u32 $0, $1, $2;", + "=r,r,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def st_async_v4(caddr, cmbar, a, b, c, d, *, loc=None, ip=None): + _asm( + None, + [ + _v(caddr, loc, ip), + _v(cmbar, loc, ip), + _v(a, loc, ip), + _v(b, loc, ip), + _v(c, loc, ip), + _v(d, loc, ip), + ], + "st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.b32 [$0], {$2, $3, $4, $5}, [$1];", + "r,r,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def st_async_v2(caddr, cmbar, a, b, *, loc=None, ip=None): + _asm( + None, + [_v(caddr, loc, ip), _v(cmbar, loc, ip), _v(a, loc, ip), _v(b, loc, ip)], + "st.async.shared::cluster.mbarrier::complete_tx::bytes.v2.b32 [$0], {$2, $3}, [$1];", + "r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_init(saddr, count, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(count, loc, ip)], + "mbarrier.init.shared::cta.b64 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_arrive(saddr, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip)], + "mbarrier.arrive.release.cta.shared::cta.b64 _, [$0];", + "r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_arrive_expect_tx(saddr, tx, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(tx, loc, ip)], + "mbarrier.arrive.expect_tx.release.cta.shared::cta.b64 _, [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_expect_tx(saddr, tx, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(tx, loc, ip)], + "mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_arrive_remote(caddr, *, loc=None, ip=None): + _asm( + None, + [_v(caddr, loc, ip)], + "mbarrier.arrive.release.cluster.shared::cluster.b64 _, [$0];", + "r", + loc, + ip, + ) + + +@dsl_user_op +def mbar_try_wait(saddr, parity, *, loc=None, ip=None): + return Int32( + _asm( + T.i32(), + [_v(saddr, loc, ip), _v(parity, loc, ip)], + "{\n\t.reg .pred p;\n\tmbarrier.try_wait.parity.shared::cta.b64 p, [$1], $2;\n\tselp.u32 $0, 1, 0, p;\n}", + "=r,r,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def mbar_try_wait_cluster(saddr, parity, *, loc=None, ip=None): + return Int32( + _asm( + T.i32(), + [_v(saddr, loc, ip), _v(parity, loc, ip)], + "{\n\t.reg .pred p;\n\tmbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [$1], $2;\n\tselp.u32 " + "$0, 1, 0, p;\n}", + "=r,r,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def mbar_test_wait(saddr, parity, *, loc=None, ip=None): + return Int32( + _asm( + T.i32(), + [_v(saddr, loc, ip), _v(parity, loc, ip)], + "{\n\t.reg .pred p;\n\tmbarrier.test_wait.parity.acquire.cluster.shared::cta.b64 p, [$1], $2;\n\tselp.u32 " + "$0, 1, 0, p;\n}", + "=r,r,r", + loc, + ip, + ) + ) + + +@cute.jit +def spin(saddr, parity): + par = Int32(parity) + ok = mbar_test_wait(Int32(saddr), par) + while ok == Int32(0): + ok = mbar_test_wait(Int32(saddr), par) + + +@cute.jit +def wait(saddr, parity): + par = Int32(parity) + ok = mbar_try_wait(Int32(saddr), par) + while ok == Int32(0): + ok = mbar_try_wait(Int32(saddr), par) + + +@cute.jit +def wait_cl(saddr, parity): + par = Int32(parity) + ok = mbar_try_wait_cluster(Int32(saddr), par) + while ok == Int32(0): + ok = mbar_try_wait_cluster(Int32(saddr), par) + + +@dsl_user_op +def cluster_arrive(*, loc=None, ip=None): + _asm(None, [], "barrier.cluster.arrive.release.aligned;", "", loc, ip) + + +@dsl_user_op +def cluster_arrive_relaxed(*, loc=None, ip=None): + _asm(None, [], "barrier.cluster.arrive.relaxed.aligned;", "", loc, ip) + + +@dsl_user_op +def cluster_wait(*, loc=None, ip=None): + _asm(None, [], "barrier.cluster.wait.acquire.aligned;", "", loc, ip) + + +@cute.jit +def cluster_sync(): + cluster_arrive() + cluster_wait() + + +@dsl_user_op +def cp_async16(saddr, gaddr, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(gaddr, loc, ip)], + "cp.async.cg.shared.global [$0], [$1], 16;", + "r,l", + loc, + ip, + ) + + +@dsl_user_op +def cp_async_mbar_arrive_noinc(saddr, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip)], + "cp.async.mbarrier.arrive.noinc.shared::cta.b64 [$0];", + "r", + loc, + ip, + ) + + +@dsl_user_op +def bulk_g2s(saddr, gaddr, nbytes, smbar, *, loc=None, ip=None): + _asm( + None, + [_v(saddr, loc, ip), _v(gaddr, loc, ip), _v(nbytes, loc, ip), _v(smbar, loc, ip)], + "cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [$0], [$1], $2, [$3];", + "r,l,r,r", + loc, + ip, + ) + + +@dsl_user_op +def bulk_g2s_mc(saddr, gaddr, nbytes, smbar, mask, *, loc=None, ip=None): + _asm( + None, + [ + _v(saddr, loc, ip), + _v(gaddr, loc, ip), + _v(nbytes, loc, ip), + _v(smbar, loc, ip), + _v(mask, loc, ip), + ], + "cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster [$0], [$1], $2, [$3], " + "$4;", + "r,l,r,r,h", + loc, + ip, + ) + + +@dsl_user_op +def bulk_s2c(caddr, saddr, nbytes, cmbar, *, loc=None, ip=None): + _asm( + None, + [_v(caddr, loc, ip), _v(saddr, loc, ip), _v(nbytes, loc, ip), _v(cmbar, loc, ip)], + "cp.async.bulk.shared::cluster.shared::cta.mbarrier::complete_tx::bytes [$0], [$1], $2, [$3];", + "r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def bulk_s2g(gaddr, saddr, nbytes, *, loc=None, ip=None): + _asm( + None, + [_v(gaddr, loc, ip), _v(saddr, loc, ip), _v(nbytes, loc, ip)], + "cp.async.bulk.global.shared::cta.bulk_group [$0], [$1], $2;", + "l,r,r", + loc, + ip, + ) + + +@dsl_user_op +def bulk_commit(*, loc=None, ip=None): + _asm(None, [], "cp.async.bulk.commit_group;", "", loc, ip) + + +@dsl_user_op +def bulk_wait0(*, loc=None, ip=None): + _asm(None, [], "cp.async.bulk.wait_group 0;", "", loc, ip) + + +@dsl_user_op +def prefetch_tensormap(tmap_gaddr, *, loc=None, ip=None): + _asm(None, [_v(tmap_gaddr, loc, ip)], "prefetch.tensormap [$0];", "l", loc, ip) + + +@dsl_user_op +def tma_g4(saddr, tmap, col, r0, r1, r2, r3, smbar, *, loc=None, ip=None): + _asm( + None, + [ + _v(saddr, loc, ip), + _v(tmap, loc, ip), + _v(col, loc, ip), + _v(r0, loc, ip), + _v(r1, loc, ip), + _v(r2, loc, ip), + _v(r3, loc, ip), + _v(smbar, loc, ip), + ], + "cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes [$0], [$1, {$2, $3, " + "$4, $5, $6}], [$7];", + "r,l,r,r,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def tma_g4_mc(saddr, tmap, col, r0, r1, r2, r3, smbar, mask, *, loc=None, ip=None): + _asm( + None, + [ + _v(saddr, loc, ip), + _v(tmap, loc, ip), + _v(col, loc, ip), + _v(r0, loc, ip), + _v(r1, loc, ip), + _v(r2, loc, ip), + _v(r3, loc, ip), + _v(smbar, loc, ip), + _v(mask, loc, ip), + ], + "cp.async.bulk.tensor.2d.shared::cluster.global.tile::gather4.mbarrier::complete_tx::bytes.multicast::cluster " + "[$0], [$1, {$2, $3, $4, $5, $6}], [$7], $8;", + "r,l,r,r,r,r,r,r,h", + loc, + ip, + ) + + +@dsl_user_op +def tma_2d(saddr, tmap, c0, c1, smbar, *, loc=None, ip=None): + _asm( + None, + [ + _v(saddr, loc, ip), + _v(tmap, loc, ip), + _v(c0, loc, ip), + _v(c1, loc, ip), + _v(smbar, loc, ip), + ], + "cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [$0], [$1, {$2, $3}], [$4];", + "r,l,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def tma_2d_mc(saddr, tmap, c0, c1, smbar, mask, *, loc=None, ip=None): + _asm( + None, + [ + _v(saddr, loc, ip), + _v(tmap, loc, ip), + _v(c0, loc, ip), + _v(c1, loc, ip), + _v(smbar, loc, ip), + _v(mask, loc, ip), + ], + "cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.multicast::cluster [$0], " + "[$1, {$2, $3}], [$4], $5;", + "r,l,r,r,r,h", + loc, + ip, + ) + + +@dsl_user_op +def tma_prefetch_g4(tmap, col, r0, r1, r2, r3, *, loc=None, ip=None): + _asm( + None, + [ + _v(tmap, loc, ip), + _v(col, loc, ip), + _v(r0, loc, ip), + _v(r1, loc, ip), + _v(r2, loc, ip), + _v(r3, loc, ip), + ], + "cp.async.bulk.prefetch.tensor.2d.L2.global.tile::gather4 [$0, {$1, $2, $3, $4, $5}];", + "l,r,r,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def tma_store_2d(tmap, c0, c1, saddr, *, loc=None, ip=None): + _asm( + None, + [ + _v(Int64(tmap), loc, ip), + _v(Int32(c0), loc, ip), + _v(Int32(c1), loc, ip), + _v(Int32(saddr), loc, ip), + ], + "cp.async.bulk.tensor.2d.global.shared::cta.tile.bulk_group [$0, {$1, $2}], [$3];", + "l,r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def ld_acq_gpu_u64(addr, *, loc=None, ip=None): + return Int64( + _asm(T.i64(), [_v(addr, loc, ip)], "ld.acquire.gpu.global.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def red_add_rel_gpu_u64(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.release.gpu.global.add.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def red_add_gpu_u32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.relaxed.gpu.global.add.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +# ==================================================================================================================== +# Selection primitives: sortable float keys, histograms, crossing-bin search, warp and block reductions and memory +# helpers for the threshold and the exact top-512. +# ==================================================================================================================== + +K_TOP = SPEC.topk +NBS = 256 +QUADC = 288 +NB_SEL = 1024 +SENT_LO = -3e38 +SENT_HI = 3e38 +NEG_INF = float("-inf") +RES_B, RES_M, RES_ABOVE, RES_TOT, RES_B2, RES_B3 = (0, 1, 2, 3, 4, 5) +GEN_SHIFT = 16 +GEN_ONE = 1 << GEN_SHIFT +GRAIN = 32 +SWA = 128 +TPB_SWA = 128 +TPB_C = 32 +V_OK = 1 +V_FB_RADIX = 2 +V_FB_RECOMP = 3 +PATH_SHORT, PATH_T1, PATH_T12, PATH_FB_RADIX, PATH_FB_RECOMP, PATH_FLOOR = (1, 2, 3, 4, 5, 6) + + +def _asm(res_t, args, s, cons, loc, ip, side=True): + return llvm.inline_asm( + res_t, + args, + s, + cons, + has_side_effects=side, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + +@dsl_user_op +def prefetch_l2(addr, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip)], "prefetch.global.L2 [$0];", "l", loc, ip) + + +@dsl_user_op +def atom_add_u64(addr, val, *, loc=None, ip=None): + return Uint64( + _asm( + T.i64(), + [_v(addr, loc, ip), _v(val, loc, ip)], + "atom.relaxed.gpu.global.add.u64 $0, [$1], $2;", + "=l,l,l", + loc, + ip, + ) + ) + + +@dsl_user_op +def red_add_u64(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.relaxed.gpu.global.add.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def red_add_u32(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "red.relaxed.gpu.global.add.u32 [$0], $1;", + "l,r", + loc, + ip, + ) + + +@dsl_user_op +def ld_relaxed_u64(addr, *, loc=None, ip=None): + return Uint64( + _asm(T.i64(), [_v(addr, loc, ip)], "ld.relaxed.gpu.global.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def ld_acquire_u64(addr, *, loc=None, ip=None): + return Uint64( + _asm(T.i64(), [_v(addr, loc, ip)], "ld.acquire.gpu.global.u64 $0, [$1];", "=l,l", loc, ip) + ) + + +@dsl_user_op +def st_release_u64(addr, val, *, loc=None, ip=None): + _asm( + None, + [_v(addr, loc, ip), _v(val, loc, ip)], + "st.release.gpu.global.u64 [$0], $1;", + "l,l", + loc, + ip, + ) + + +@dsl_user_op +def ld_cg_u32(addr, *, loc=None, ip=None): + return Uint32(_asm(T.i32(), [_v(addr, loc, ip)], "ld.global.cg.u32 $0, [$1];", "=r,l", loc, ip)) + + +@dsl_user_op +def ld_cg_i32(addr, *, loc=None, ip=None): + return Int32(_asm(T.i32(), [_v(addr, loc, ip)], "ld.global.cg.u32 $0, [$1];", "=r,l", loc, ip)) + + +@dsl_user_op +def ld_cg_u64(addr, *, loc=None, ip=None): + return Uint64(_asm(T.i64(), [_v(addr, loc, ip)], "ld.global.cg.u64 $0, [$1];", "=l,l", loc, ip)) + + +@dsl_user_op +def ld_cg_f32(addr, *, loc=None, ip=None): + return Float32( + _asm(T.f32(), [_v(addr, loc, ip)], "ld.global.cg.f32 $0, [$1];", "=f,l", loc, ip) + ) + + +@dsl_user_op +def st_g_u64(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.u64 [$0], $1;", "l,l", loc, ip) + + +@dsl_user_op +def st_g_u32(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.u32 [$0], $1;", "l,r", loc, ip) + + +@dsl_user_op +def st_g_f32(addr, val, *, loc=None, ip=None): + _asm(None, [_v(addr, loc, ip), _v(val, loc, ip)], "st.global.f32 [$0], $1;", "l,f", loc, ip) + + +@dsl_user_op +def ld_nc_f32x4(addr, *, loc=None, ip=None): + st = llvm.StructType.get_literal([T.f32(), T.f32(), T.f32(), T.f32()]) + r = _asm( + st, + [_v(addr, loc, ip)], + "ld.global.nc.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,l", + loc, + ip, + side=False, + ) + return tuple((Float32(llvm.extractvalue(T.f32(), r, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def ld_nc_f32(addr, *, loc=None, ip=None): + return Float32( + _asm( + T.f32(), [_v(addr, loc, ip)], "ld.global.nc.f32 $0, [$1];", "=f,l", loc, ip, side=False + ) + ) + + +@dsl_user_op +def ld_cg_f32x4(addr, *, loc=None, ip=None): + st = llvm.StructType.get_literal([T.f32(), T.f32(), T.f32(), T.f32()]) + r = _asm( + st, + [_v(addr, loc, ip)], + "ld.global.cg.v4.f32 {$0, $1, $2, $3}, [$4];", + "=f,=f,=f,=f,l", + loc, + ip, + ) + return tuple((Float32(llvm.extractvalue(T.f32(), r, [i], loc=loc, ip=ip)) for i in range(4))) + + +@dsl_user_op +def bar(bar_id, nthr, *, loc=None, ip=None): + # Warp-specialized participants may reach this named barrier at distinct PCs. + _asm( + None, + [_v(Int32(bar_id), loc, ip), _v(Int32(nthr), loc, ip)], + "barrier.cta.sync $0, $1;", + "r,r,~{memory}", + loc, + ip, + ) + + +@dsl_user_op +def bar_arrive(bar_id, nthr, *, loc=None, ip=None): + _asm( + None, + [_v(Int32(bar_id), loc, ip), _v(Int32(nthr), loc, ip)], + "barrier.cta.arrive $0, $1;", + "r,r,~{memory}", + loc, + ip, + ) + + +def u32_of_f32(v): + return Uint32(llvm.bitcast(Uint32.mlir_type, v.ir_value())) + + +def f32_of_u32(u): + return Float32(llvm.bitcast(Float32.mlir_type, u.ir_value())) + + +def fkey_bits(u): + neg = Uint32(0) - (u >> Uint32(31)) + return u ^ (neg | Uint32(2147483648)) + + +def fkey(x): + return fkey_bits(u32_of_f32(x)) + + +def invkey_bits(K): + s = K >> Uint32(31) + m = s - Uint32(1) | Uint32(2147483648) + return K ^ m + + +def invkey(K): + return f32_of_u32(invkey_bits(K)) + + +def warp_min_u32(v): + return cute.arch.warp_redux_sync(v, "min") + + +def warp_max_u32(v): + return cute.arch.warp_redux_sync(v, "max") + + +def f2u_rz(v): + return Uint32(v) + + +def f2s_rz(v): + return Int32(v) + + +@dsl_user_op +def _fmaf(a, b, c, *, loc=None, ip=None): + return Float32( + mlir_math.fma( + a.ir_value(loc=loc, ip=ip), + b.ir_value(loc=loc, ip=ip), + c.ir_value(loc=loc, ip=ip), + fastmath=mlir_arith.FastMathFlags.none, + loc=loc, + ip=ip, + ) + ) + + +@cute.jit +def _shfl_up_add(val, lane, offset: cutlass.Constexpr): + other = cute.arch.shuffle_sync_up(val, offset, mask_and_clamp=0) + if lane >= Int32(offset): + val = val + other + return val + + +@cute.jit +def warp_incl_scan_add(val, lane): + for o in [1, 2, 4, 8, 16]: + val = _shfl_up_add(val, lane, o) + return val + + +def smem_atom_i32_128(): + return cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Int32, num_bits_per_copy=128) + + +def _smem_v4_tensor(base_addr, byte_off): + p = cute.make_ptr(Int32, base_addr + byte_off, cute.AddressSpace.smem, assumed_align=16) + return cute.make_tensor(p, cute.make_layout((4,))) + + +def lds128_i32(copy_atom, base_addr, byte_off, frag): + cute.copy(copy_atom, _smem_v4_tensor(base_addr, byte_off), frag) + + +def sts128_i32(copy_atom, frag, base_addr, byte_off): + cute.copy(copy_atom, frag, _smem_v4_tensor(base_addr, byte_off)) + + +@cute.jit +def scan_cross0( + s_hist, + target, + tidx, + s_res, + target2, + target3, + s_addv, + nb: cutlass.Constexpr, + zero: cutlass.Constexpr, + two: cutlass.Constexpr = False, + three: cutlass.Constexpr = False, + addf: cutlass.Constexpr = False, +): + BPT = nb // 32 + NV = BPT // 4 + HOLD = NV <= 2 + if tidx < Int32(32): + lane = tidx + atom = smem_atom_i32_128() + hbase = s_hist.iterator.toint() + frags = [cute.make_rmem_tensor((4,), Int32) for _ in range(NV)] + sm = Int32(0) + for q in cutlass.range_constexpr(NV): + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, hbase, boff, frags[q]) + sm = sm + frags[q][0] + frags[q][1] + frags[q][2] + frags[q][3] + w = warp_incl_scan_add(sm, lane) + tot = cute.arch.shuffle_sync(w, Int32(31)) + after = tot - w + if lane == Int32(0): + s_res[RES_TOT] = tot + base = lane * Int32(BPT) + for q in cutlass.range_constexpr(NV - 1, -1, -1): + if cutlass.const_expr(HOLD): + vv = frags[q] + else: + vv = cute.make_rmem_tensor((4,), Int32) + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, hbase, boff, vv) + o4 = cute.make_rmem_tensor((4,), Int32) + for j in cutlass.range_constexpr(3, -1, -1): + cq = vv[j] + if cutlass.const_expr(zero): + o4[j] = Int32(0) + else: + o4[j] = after + gb = base + Int32(4 * q + j) + cross = Int32(0) + if after < target: + if after + cq >= target: + cross = Int32(1) + if gb == Int32(0): + cross = Int32(1) + if cross != Int32(0): + s_res[RES_B] = gb + s_res[RES_ABOVE] = after + s_res[RES_M] = cq + if cutlass.const_expr(two): + cross2 = Int32(0) + if after < target2: + if after + cq >= target2: + cross2 = Int32(1) + if gb == Int32(0): + cross2 = Int32(1) + if cross2 != Int32(0): + s_res[RES_B2] = gb + if cutlass.const_expr(three): + cross3 = Int32(0) + if after < target3: + if after + cq >= target3: + cross3 = Int32(1) + if gb == Int32(0): + cross3 = Int32(1) + if cross3 != Int32(0): + s_res[RES_B3] = gb + after = after + cq + if cutlass.const_expr(addf): + av = cute.make_rmem_tensor((4,), Int32) + aoff = (lane * Int32(NV) + Int32(q)) * Int32(16) + lds128_i32(atom, s_addv.iterator.toint(), aoff, av) + for j in cutlass.range_constexpr(4): + o4[j] = o4[j] + av[j] + boff = (lane * Int32(NV) + Int32(q)) * Int32(16) + sts128_i32(atom, o4, hbase, boff) + + +@cute.jit +def hi_bit_or_zero(msk): + r = Int32(0) + if msk != Int32(0): + r = Int32(31) - Int32(cute.arch.clz(msk)) + return r + + +@cute.jit +def _shfl_down_add(val, lane, offset: cutlass.Constexpr): + other = cute.arch.shuffle_sync_down(val, offset, mask_and_clamp=31) + if lane + Int32(offset) < Int32(32): + val = val + other + return val + + +@cute.jit +def warp_suffix_scan_add(val, lane): + for o in [1, 2, 4, 8, 16]: + val = _shfl_down_add(val, lane, o) + return val + + +@cute.jit +def find_cross(s_hist, target, tidx, s_res, nb: cutlass.Constexpr): + BPL = nb // 32 + if tidx < Int32(32): + lane = tidx + part = Int32(0) + for j in cutlass.range_constexpr(BPL): + idx = lane * Int32(BPL) + (Int32(j) + lane & Int32(BPL - 1)) + part = part + s_hist[idx] + v = warp_suffix_scan_add(part, lane) + if lane == Int32(0): + s_res[RES_TOT] = v + msk = Int32(cute.arch.vote_ballot_sync(v >= target)) + Lb = hi_bit_or_zero(msk) + aboveL = cute.arch.shuffle_sync(v - part, Lb) + h = Int32(0) + if lane < Int32(BPL): + h = s_hist[Lb * Int32(BPL) + lane] + w = warp_suffix_scan_add(h, lane) + msk2 = Int32(cute.arch.vote_ballot_sync(aboveL + w >= target)) + J = hi_bit_or_zero(msk2) + if lane == J: + s_res[RES_B] = Lb * Int32(BPL) + J + s_res[RES_M] = h + s_res[RES_ABOVE] = aboveL + (w - h) + + +def pack_entry(xbits_u32, idx_i32): + return Uint64(Uint32(idx_i32)) << Uint64(32) | Uint64(xbits_u32) + + +def entry_bits(e): + return Uint32(e & Uint64(4294967295)) + + +def entry_idx(e): + return Int32(Uint32(e >> Uint64(32))) + + +def entry_key(e): + kb = fkey_bits(entry_bits(e)) + return Uint64(kb) << Uint64(32) | Uint64(Uint32(4294967295) - Uint32(e >> Uint64(32))) + + +def key_to_entry(k): + idx = Uint32(4294967295) - Uint32(k & Uint64(4294967295)) + bits = invkey_bits(Uint32(k >> Uint64(32))) + return Uint64(idx) << Uint64(32) | Uint64(bits) + + +@cute.jit +def ld_entry(lst, i, src_gmem: cutlass.Constexpr): + r = Uint64(0) + if cutlass.const_expr(src_gmem): + r = ld_cg_u64(lst.iterator.toint() + Int64(i) * Int64(8)) + else: + r = Uint64(lst[i]) + return r + + +@cute.jit +def gvr_ladder( + n, k, aim_base, sfac, amin, sd_en, r_const: cutlass.Constexpr, scap: cutlass.Constexpr +): + SMP = Int32(0) + SS2 = Int32(1) + TGT = Int32(0) + TGT2 = Int32(0) + if n <= k: + TGT = Int32(1073741823) + TGT2 = Int32(1073741823) + else: + x6 = Int32(6) * n + ri = Int32(cmath.sqrt(Float32(x6))) + if ri * ri > x6: + ri = ri - Int32(1) + if (ri + Int32(1)) * (ri + Int32(1)) <= x6: + ri = ri + Int32(1) + r6 = ri + if x6 - ri * ri > ri: + r6 = ri + Int32(1) + aim = aim_base + if r6 > aim: + aim = r6 + if cutlass.const_expr(r_const > 1): + if aim < amin: + aim = amin + scap_c = Int32(scap) + if aim > scap_c >> Int32(1): + aim = scap_c >> Int32(1) + if aim < k: + aim = k + n4w = n >> Int32(2) + gate = Int32(0) + if n > scap_c: + gate = Int32(1) + if sd_en != Int32(0): + if n <= scap_c: + if n > k << Int32(1): + gate = Int32(1) + if n4w < Int32(4): + gate = Int32(0) + if gate != Int32(0): + sel = Int32(Float32(sfac * n) * cute.arch.rcp_approx(Float32(aim))) + if sel < Int32(256): + sel = Int32(256) + nh = n >> Int32(1) + if sel > nh: + sel = nh + pairs = sel >> Int32(3) + if pairs < Int32(1): + pairs = Int32(1) + half = n4w >> Int32(1) + if half < Int32(1): + half = Int32(1) + if pairs > half: + pairs = half + SS2 = Int32(Float32(half) * cute.arch.rcp_approx(Float32(pairs))) + if SS2 < Int32(1): + SS2 = Int32(1) + SMP = Int32(Float32(half) * cute.arch.rcp_approx(Float32(SS2))) + if SMP * SS2 > half: + SMP = SMP - Int32(1) + if SMP < Int32(1): + SMP = Int32(1) + rn_ = cute.arch.rcp_approx(Float32(n)) + smp8f = Float32(SMP) * Float32(8.0) + TGT = Int32(Float32(aim) * smp8f * rn_) + if TGT < Int32(1): + TGT = Int32(1) + TGT2 = Int32(Float32(k) * smp8f * rn_) + if TGT2 < Int32(1): + TGT2 = Int32(1) + return (SMP, SS2, TGT, TGT2) + + +@cute.jit +def _pst(prof, slot, tid): + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + cutlass.inttoptr(prof + Int64(slot) * Int64(8), mem_space=1, dtype=Int64).store( + Int64(gtimer()) + ) + + +@cute.jit +def gvr_sample_thresholds( + s_smp, + SMP, + TGT, + TGT2, + s_hist, + s_res, + s_wred, + tid, + split: cutlass.Constexpr, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + prof=None, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + if tid == Int32(0): + s_res[RES_B2] = Int32(-1) + s_res[RES_B3] = Int32(-1) + smn = Float32(float("inf")) + smx = Float32(float("-inf")) + j = tid + while j < SMP: + for t in cutlass.range_constexpr(8): + v = Float32(s_smp[j * Int32(8) + Int32(t)]) + smn = cute.arch.fmin(smn, v) + smx = cute.arch.fmax(smx, v) + j = j + Int32(nthr) + a0 = warp_min_u32(fkey(smn)) + c0m = warp_max_u32(fkey(smx)) + if lane == Int32(0): + s_wred[wid] = a0 + s_wred[Int32(NW) + wid] = c0m + bar(bar_id, nthr) + _pst(prof, 21, tid) + av = Uint32(4294967295) + cv = Uint32(0) + if lane < Int32(NW): + av = Uint32(s_wred[lane]) + cv = Uint32(s_wred[Int32(NW) + lane]) + SMIN = invkey(warp_min_u32(av)) + SMAX = invkey(warp_max_u32(cv)) + GMIN = Float32(SENT_LO) + T = Float32(NEG_INF) + HIC = Float32(NEG_INF) + T3 = Float32(NEG_INF) + Tk = Float32(NEG_INF) + w = Float32(0.0) + sok = Int32(0) + if SMP > Int32(0): + if SMAX > SMIN: + sok = Int32(1) + if sok != Int32(0): + w = (SMAX - SMIN) * Float32(1.0 / 256.0) + sc_s = cute.arch.rcp_approx(w) + j2 = tid + while j2 < SMP: + for t in cutlass.range_constexpr(8): + v2 = Float32(s_smp[j2 * Int32(8) + Int32(t)]) + bq = f2s_rz((v2 - SMIN) * sc_s) + if bq > Int32(NBS - 1): + bq = Int32(NBS - 1) + cute.arch.red( + s_hist.iterator + bq, + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + j2 = j2 + Int32(nthr) + bar(bar_id, nthr) + _pst(prof, 22, tid) + scan_cross0( + s_hist, + TGT, + tid, + s_res, + TGT2, + TGT * Int32(2), + s_hist, + nb=NBS, + zero=True, + two=True, + three=True, + ) + bar(bar_id, nthr) + _pst(prof, 23, tid) + tot0 = s_res[RES_TOT] + b1v = s_res[RES_B] + b2v = s_res[RES_B2] + b3v = s_res[RES_B3] + if sok != Int32(0): + if tot0 >= TGT: + T = _fmaf(Float32(b1v), w, SMIN) + Trung = T + tinf = Int32(1) + if T > Float32(NEG_INF): + tinf = Int32(0) + if tinf != Int32(0): + T = GMIN + if sok != Int32(0): + if tot0 >= TGT: + if b2v >= Int32(0): + Tk = _fmaf(Float32(b2v), w, SMIN) + anch = T + if cutlass.const_expr(not split): + anch = cute.arch.fmin(T, Trung) + d_ = cute.arch.fmax(Tk - anch, Float32(0.0)) + HIC = cute.arch.fmax(_fmaf(Float32(4.0), d_, T), _fmaf(Float32(8.0), w, T)) + if sok != Int32(0): + if tot0 >= TGT * Int32(2): + if b3v >= Int32(0): + if T > GMIN: + t3c = _fmaf(Float32(b3v), w, SMIN) + if t3c < T: + T3 = t3c + bar(bar_id, nthr) + return (T, HIC, T3, Tk, SMIN, SMAX, w, sok, tot0, b1v, b2v, b3v) + + +@cute.jit +def tier_stage_warp( + xs, pos0, nlim, T, T3, s_st1, s_st2, s_cnt, cap1, cap2, lane, tier2: cutlass.Constexpr +): + lm = Int32(cute.arch.lanemask_lt()) + t2on = Int32(0) + if cutlass.const_expr(tier2): + if T3 > Float32(NEG_INF): + t2on = Int32(1) + off1 = Int32(0) + off2 = Int32(0) + m1s = [Int32(0)] * 4 + m2s = [Int32(0)] * 4 + vmax = Float32(NEG_INF) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + x = xs[q] + ok = p < nlim + a1 = Int32(0) + a2 = Int32(0) + if ok: + vmax = cute.arch.fmax(vmax, x) + if x >= T: + a1 = Int32(1) + elif t2on != Int32(0): + if x >= T3: + a2 = Int32(1) + m1s[q] = Int32(cute.arch.vote_ballot_sync(a1 != Int32(0))) + m2s[q] = Int32(cute.arch.vote_ballot_sync(a2 != Int32(0))) + tot1 = Int32(0) + tot2 = Int32(0) + for q in cutlass.range_constexpr(4): + tot1 = tot1 + Int32(cute.arch.popc(m1s[q])) + tot2 = tot2 + Int32(cute.arch.popc(m2s[q])) + b1 = Int32(0) + b2 = Int32(0) + if lane == Int32(0): + if tot1 > Int32(0): + b1 = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(0), tot1, sem="relaxed", scope="cta") + ) + if tot2 > Int32(0): + b2 = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(1), tot2, sem="relaxed", scope="cta") + ) + b1 = cute.arch.shuffle_sync(b1, Int32(0)) + b2 = cute.arch.shuffle_sync(b2, Int32(0)) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + if m1s[q] >> lane & Int32(1) != Int32(0): + slot = b1 + off1 + Int32(cute.arch.popc(m1s[q] & lm)) + if slot < cap1: + s_st1[slot] = pack_entry(u32_of_f32(xs[q]), p) + if m2s[q] >> lane & Int32(1) != Int32(0): + slot2 = b2 + off2 + Int32(cute.arch.popc(m2s[q] & lm)) + if slot2 < cap2: + s_st2[slot2] = pack_entry(u32_of_f32(xs[q]), p) + off1 = off1 + Int32(cute.arch.popc(m1s[q])) + off2 = off2 + Int32(cute.arch.popc(m2s[q])) + return vmax + + +@cute.jit +def grain_max_8lanes(vmax_lane): + v = vmax_lane + for o in [1, 2, 4]: + v = cute.arch.fmax(v, cute.arch.shuffle_sync_bfly(v, o)) + return v + + +@cute.jit +def floor_admit_warp(xs, pos0, nlim, t_run, s_buf, s_cnt, cap, lane): + lm = Int32(cute.arch.lanemask_lt()) + ms = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + a = Int32(0) + if p < nlim: + if xs[q] >= t_run: + a = Int32(1) + ms[q] = Int32(cute.arch.vote_ballot_sync(a != Int32(0))) + tot = Int32(0) + for q in cutlass.range_constexpr(4): + tot = tot + Int32(cute.arch.popc(ms[q])) + b = Int32(0) + if lane == Int32(0): + if tot > Int32(0): + b = Int32( + cute.arch.atomic_add(s_cnt.iterator + Int32(0), tot, sem="relaxed", scope="cta") + ) + b = cute.arch.shuffle_sync(b, Int32(0)) + off = Int32(0) + for q in cutlass.range_constexpr(4): + p = pos0 + Int32(4) * lane + Int32(q) + if ms[q] >> lane & Int32(1) != Int32(0): + slot = b + off + Int32(cute.arch.popc(ms[q] & lm)) + if slot < cap: + s_buf[slot] = pack_entry(u32_of_f32(xs[q]), p) + off = off + Int32(cute.arch.popc(ms[q])) + return tot + + +@cute.jit +def gc_arrive(addr): + fence_acq_rel_gpu() + return atom_add_u64(addr, Uint64(1)) + + +@cute.jit +def gc_pad(addr, P): + red_add_u64(addr, Uint64(GEN_ONE) - Uint64(P)) + + +@cute.jit +def gc_wait(addr, target, skew_ns): + v = ld_relaxed_u64(addr) + while v < target: + nanosleep(Int32(64)) + v = ld_relaxed_u64(addr) + fence_acq_rel_gpu() + return v + + +@cute.jit +def verdict_publish(addr, gen, status): + st_release_u64(addr, gen + Uint64(1) << Uint64(8) | Uint64(status)) + + +@cute.jit +def verdict_wait(addr, gen): + want = gen + Uint64(1) + v = ld_acquire_u64(addr) + while v >> Uint64(8) != want: + nanosleep(Int32(128)) + v = ld_acquire_u64(addr) + return Int32(Uint32(v & Uint64(255))) + + +@cute.jit +def skew_sleep(seed, salt, skew_ns): + if skew_ns > Int32(0): + h = Uint32(seed) * Uint32(2654435761) + Uint32(salt) * Uint32(2246822519) + h = h ^ h >> Uint32(15) + h = h * Uint32(739982445) + h = h ^ h >> Uint32(13) + ns = Int32(h % Uint32(skew_ns)) + nanosleep(ns) + + +@cute.jit +def _vbin(e, lo, sc, nb: cutlass.Constexpr): + x = f32_of_u32(entry_bits(e)) + b = f2u_rz((x - lo) * sc) + if b > Uint32(nb - 1): + b = Uint32(nb - 1) + return Int32(b) + + +@cute.jit +def _block_min_max_u32( + a_min, a_max, s_red, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + wmn = warp_min_u32(a_min) + wmx = warp_max_u32(a_max) + if lane == Int32(0): + s_red[wid] = wmn + s_red[Int32(NW) + wid] = wmx + bar(bar_id, nthr) + av = Uint32(4294967295) + cv = Uint32(0) + if lane < Int32(NW): + av = Uint32(s_red[lane]) + cv = Uint32(s_red[Int32(NW) + lane]) + rmn = warp_min_u32(av) + rmx = warp_max_u32(cv) + bar(bar_id, nthr) + return (rmn, rmx) + + +@cute.jit +def _warp_prefix(cnt_w, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + if lane == Int32(0): + s_wc[wid] = cnt_w + bar(bar_id, nthr) + ex = Int32(0) + tot = Int32(0) + for w_ in cutlass.range_constexpr(NW): + c = Int32(s_wc[w_]) + if Int32(w_) < wid: + ex = ex + c + tot = tot + c + bar(bar_id, nthr) + return (ex, tot) + + +@cute.jit +def select_topk_list( + lst, + C, + K, + out_e, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + src_gmem: cutlass.Constexpr, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + want_kth: cutlass.Constexpr = False, + prof=None, + rng_lo=None, + rng_hi=None, + hist_ready: cutlass.Constexpr = False, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + nout = C + if nout > K: + nout = K + kth = Uint64(18446744073709551615) + mret = Int32(0) + info = Int32(0) + if C <= K: + i = tid + while i < C: + out_e[i] = ld_entry(lst, i, src_gmem) + i = i + Int32(nthr) + bar(bar_id, nthr) + else: + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[0] = clk64() + lo = Float32(0.0) + hi = Float32(0.0) + if cutlass.const_expr(rng_lo is None): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + kmn = Uint32(4294967295) + kmx = Uint32(0) + i4 = (tid >> Int32(5)) * Int32(128) + lane + while i4 < C: + for q in cutlass.range_constexpr(4): + iq = i4 + Int32(32 * q) + icl = iq + if icl > C - Int32(1): + icl = C - Int32(1) + kbq = fkey_bits(entry_bits(ld_entry(lst, icl, src_gmem))) + if kbq < kmn: + kmn = kbq + if kbq > kmx: + kmx = kbq + i4 = i4 + Int32(nthr * 4) + gmn, gmx = _block_min_max_u32(kmn, kmx, s_red, tid, nthr, bar_id) + lo = invkey(gmn) + hi = invkey(gmx) + else: + lo = rng_lo + hi = rng_hi + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[1] = clk64() + wv = (hi - lo) * Float32(1.0 / NB_SEL) + sc = Float32(0.0) + if wv > Float32(0.0): + if wv < Float32(3e38): + sc = cute.arch.rcp_approx(wv) + if cutlass.const_expr(not hist_ready): + if cutlass.const_expr(rng_lo is not None): + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + i4 = (tid >> Int32(5)) * Int32(128) + lane + while i4 < C: + bq_ = [Int32(0)] * 4 + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bq_[q] = _vbin(ld_entry(lst, icl, src_gmem), lo, sc, NB_SEL) + for q in cutlass.range_constexpr(4): + if i4 + Int32(32 * q) < C: + cute.arch.red( + s_hist.iterator + bq_[q], + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + i4 = i4 + Int32(nthr * 4) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[2] = clk64() + find_cross(s_hist, K, tid, s_res, NB_SEL) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[3] = clk64() + B = s_res[RES_B] + above = s_res[RES_ABOVE] + m = s_res[RES_M] + need = K - above + mret = m + whole = Int32(0) + if need >= m: + whole = Int32(1) + keepc = Int32(0) + if whole == Int32(0): + if m <= Int32(QUADC): + keepc = Int32(1) + Bw = B + if whole != Int32(0): + Bw = B - Int32(1) + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + chunk = (C + Int32(nthr * 4) - Int32(1)) // Int32(nthr * 4) * Int32(128) + c0 = wid * chunk + c1 = c0 + chunk + if c1 > C: + c1 = C + cw = Int32(0) + cc = Int32(0) + i4 = c0 + lane + while i4 < c1: + for q in cutlass.range_constexpr(4): + icl = i4 + Int32(32 * q) + if icl > C - Int32(1): + icl = C - Int32(1) + bb = _vbin(ld_entry(lst, icl, src_gmem), lo, sc, NB_SEL) + if i4 + Int32(32 * q) < c1: + if bb > Bw: + cw = cw + Int32(1) + elif bb == B: + cc = cc + Int32(1) + i4 = i4 + Int32(128) + wcw = Int32(cute.arch.warp_redux_sync(cw, "add")) + wcc = Int32(cute.arch.warp_redux_sync(cc, "add")) + if lane == Int32(0): + s_wc[wid] = wcw + s_wc[Int32(NW) + wid] = wcc + bar(bar_id, nthr) + pw = Int32(0) + pc = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + pw = pw + Int32(s_wc[w_]) + pc = pc + Int32(s_wc[NW + w_]) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[4] = clk64() + base0 = c0 + while base0 < c1: + ed = [] + for q in cutlass.range_constexpr(4): + icl = base0 + Int32(32 * q) + lane + if icl > C - Int32(1): + icl = C - Int32(1) + ed.append(ld_entry(lst, icl, src_gmem)) + for q in cutlass.range_constexpr(4): + fw = Int32(0) + fc = Int32(0) + if base0 + Int32(32 * q) + lane < c1: + bd_ = _vbin(ed[q], lo, sc, NB_SEL) + if bd_ > Bw: + fw = Int32(1) + elif bd_ == B: + fc = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fw != Int32(0))) + mc = Int32(cute.arch.vote_ballot_sync(fc != Int32(0))) + if fw != Int32(0): + out_e[pw + Int32(cute.arch.popc(mw & lm))] = ed[q] + if fc != Int32(0): + if keepc != Int32(0): + s_ck[pc + Int32(cute.arch.popc(mc & lm))] = entry_key(ed[q]) + pw = pw + Int32(cute.arch.popc(mw)) + pc = pc + Int32(cute.arch.popc(mc)) + base0 = base0 + Int32(128) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[5] = clk64() + if whole == Int32(0): + if m <= Int32(32): + info = Int32(1) + if wid == Int32(0): + kq = Uint64(0) + if lane < m: + kq = Uint64(s_ck[lane]) + khi = Uint32(kq >> Uint64(32)) + klo = Uint32(kq & Uint64(4294967295)) + r_ = Int32(0) + for j in cutlass.range_constexpr(32): + ohi = cute.arch.shuffle_sync(khi, Int32(j)) + olo = cute.arch.shuffle_sync(klo, Int32(j)) + if Int32(j) < m: + if ohi > khi: + r_ = r_ + Int32(1) + elif ohi == khi: + if olo > klo: + r_ = r_ + Int32(1) + if lane < m: + if r_ < need: + out_e[above + r_] = key_to_entry(kq) + bar(bar_id, nthr) + elif m <= Int32(QUADC): + info = Int32(1) + i = tid + while i < m: + ki = Uint64(s_ck[i]) + r_ = Int32(0) + jq = Int32(0) + while jq < m: + if Uint64(s_ck[jq]) > ki: + r_ = r_ + Int32(1) + jq = jq + Int32(1) + if r_ < need: + out_e[above + r_] = key_to_entry(ki) + i = i + Int32(nthr) + bar(bar_id, nthr) + else: + info = Int32(2) + pref = Uint64(0) + plen = Int32(0) + needr = need + done = Int32(0) + while done == Int32(0): + shift = Int32(56) - plen + if tid < Int32(NBS): + s_hist[tid] = Int32(0) + if cutlass.const_expr(nthr < NBS): + for z_ in cutlass.range_constexpr(1, NBS // nthr): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + i = tid + while i < C: + e2_ = ld_entry(lst, i, src_gmem) + if _vbin(e2_, lo, sc, NB_SEL) == B: + k2 = entry_key(e2_) + okp = Int32(1) + if plen > Int32(0): + if k2 >> Uint64(Int32(64) - plen) != pref: + okp = Int32(0) + if okp != Int32(0): + dg = Int32(Uint32(k2 >> Uint64(shift) & Uint64(255))) + cute.arch.red( + s_hist.iterator + dg, + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + i = i + Int32(nthr) + bar(bar_id, nthr) + scan_cross0(s_hist, needr, tid, s_res, needr, needr, s_hist, nb=NBS, zero=True) + bar(bar_id, nthr) + dB = s_res[RES_B] + dab = s_res[RES_ABOVE] + dm = s_res[RES_M] + bar(bar_id, nthr) + pref = pref << Uint64(8) | Uint64(dB) + plen = plen + Int32(8) + needr = needr - dab + if needr >= dm: + done = Int32(1) + if plen >= Int32(64): + done = Int32(1) + thr = pref << Uint64(Int32(64) - plen) + if plen >= Int32(64): + thr = pref + nw2 = Int32(0) + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + if ii < c1: + e3_ = ld_entry(lst, ii, src_gmem) + if _vbin(e3_, lo, sc, NB_SEL) == B: + if entry_key(e3_) >= thr: + f2_ = Int32(1) + nw2 = nw2 + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(f2_ != Int32(0)))) + r0 = r0 + Int32(32) + ex2, tot2 = _warp_prefix(nw2, s_wc, tid, nthr, bar_id) + p2 = above + ex2 + r0 = c0 + while r0 < c1: + ii = r0 + lane + f2_ = Int32(0) + e4 = Uint64(0) + if ii < c1: + e4 = ld_entry(lst, ii, src_gmem) + if _vbin(e4, lo, sc, NB_SEL) == B: + if entry_key(e4) >= thr: + f2_ = Int32(1) + m2 = Int32(cute.arch.vote_ballot_sync(f2_ != Int32(0))) + if f2_ != Int32(0): + out_e[p2 + Int32(cute.arch.popc(m2 & lm))] = e4 + p2 = p2 + Int32(cute.arch.popc(m2)) + r0 = r0 + Int32(32) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[6] = clk64() + if cutlass.const_expr(want_kth): + kmn64 = Uint64(18446744073709551615) + i = tid + while i < nout: + kk = entry_key(Uint64(out_e[i])) + if kk < kmn64: + kmn64 = kk + i = i + Int32(nthr) + hi32 = Uint32(kmn64 >> Uint64(32)) + lo32 = Uint32(kmn64 & Uint64(4294967295)) + wmh = warp_min_u32(hi32) + cand = Uint32(4294967295) + if hi32 == wmh: + cand = lo32 + wml = warp_min_u32(cand) + if lane == Int32(0): + s_red[wid] = wmh + s_red[Int32(NW) + wid] = wml + bar(bar_id, nthr) + bh = Uint32(4294967295) + bl = Uint32(4294967295) + for w_ in cutlass.range_constexpr(NW): + h_ = Uint32(s_red[w_]) + l_ = Uint32(s_red[Int32(NW) + Int32(w_)]) + if h_ < bh: + bh = h_ + bl = l_ + elif h_ == bh: + if l_ < bl: + bl = l_ + kth = Uint64(bh) << Uint64(32) | Uint64(bl) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[7] = clk64() + return (nout, kth, mret, info) + + +@cute.jit +def l2g_swa(i, pos, req, bt_swa, max_blocks_swa, swa_off_tokens): + st = pos - Int32(SWA - 1) + if st < Int32(0): + st = Int32(0) + loc = st + i + blk = loc // Int32(TPB_SWA) + bc = blk + if bc > max_blocks_swa - Int32(1): + bc = max_blocks_swa - Int32(1) + page = Int32(bt_swa[req, bc]) + g = Int32(-1) + if loc <= pos: + if blk < max_blocks_swa: + g = swa_off_tokens + page * Int32(TPB_SWA) + (loc - blk * Int32(TPB_SWA)) + return g + + +@cute.jit +def l2g_swa_local(loc, req, bt_swa, max_blocks_swa, swa_off_tokens): + blk = loc // Int32(TPB_SWA) + bc = blk + if bc > max_blocks_swa - Int32(1): + bc = max_blocks_swa - Int32(1) + if bc < Int32(0): + bc = Int32(0) + page = Int32(bt_swa[req, bc]) + g = Int32(-1) + if loc >= Int32(0): + if blk < max_blocks_swa: + g = swa_off_tokens + page * Int32(TPB_SWA) + (loc - blk * Int32(TPB_SWA)) + return g + + +@cute.jit +def l2g_compressed(c, req, bt_c, max_blocks_c, c_off_tokens): + blk = c // Int32(TPB_C) + bc = blk + if bc > max_blocks_c - Int32(1): + bc = max_blocks_c - Int32(1) + if bc < Int32(0): + bc = Int32(0) + page = Int32(bt_c[req, bc]) + g = Int32(-1) + if c >= Int32(0): + if blk < max_blocks_c: + g = c_off_tokens + page * Int32(TPB_C) + (c - blk * Int32(TPB_C)) + return g + + +@cute.jit +def block_excl_scan(v, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + inc = warp_incl_scan_add(v, lane) + if lane == Int32(31): + s_wc[wid] = inc + bar(bar_id, nthr) + base = Int32(0) + tot = Int32(0) + for w_ in cutlass.range_constexpr(NW): + c = Int32(s_wc[w_]) + if Int32(w_) < wid: + base = base + c + tot = tot + c + bar(bar_id, nthr) + return (base + inc - v, tot) + + +@cute.jit +def sample_window_range(t0, t1, SMP, SS2): + st = Int32(8) * SS2 + j0 = (t0 + st - Int32(1)) // st + j1 = (t1 + st - Int32(1)) // st + if j1 > SMP: + j1 = SMP + if j0 > j1: + j0 = j1 + return (j0, j1) + + +@cute.jit +def flatten_regions( + dst, dst_gmem: cutlass.Constexpr, reg_base, cap, s_pc, s_po, P, tid, nthr: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + p = wid + while p < P: + cnt = Int32(s_pc[p]) + off = Int32(s_po[p]) + src = reg_base + Int64(p) * Int64(cap) * Int64(8) + i = lane + while i < cnt: + e = ld_cg_u64(src + Int64(i) * Int64(8)) + if cutlass.const_expr(dst_gmem): + st_g_u64(dst.iterator.toint() + Int64(off + i) * Int64(8), e) + else: + dst[off + i] = e + i = i + Int32(32) + p = p + Int32(NW) + + +@cute.jit +def parts_table_warp0(desc_base, P, cap1, cap2, s_pt, s_tot, tid): + if tid < Int32(32): + lane = tid + ppl = P + Int32(31) >> Int32(5) + p0 = lane * ppl + a1 = [Int32(0)] * 8 + a2 = [Int32(0)] * 8 + for q in cutlass.range_constexpr(8): + pq = p0 + Int32(q) + pc = pq + if pc > P - Int32(1): + pc = P - Int32(1) + v1 = ld_cg_i32(desc_base + Int64(pc) * Int64(16)) + v2 = ld_cg_i32(desc_base + Int64(pc) * Int64(16) + Int64(4)) + ok = Int32(0) + if Int32(q) < ppl: + if pq < P: + ok = Int32(1) + a1[q] = v1 * ok + a2[q] = v2 * ok + s1 = Int32(0) + s2 = Int32(0) + n1 = Int32(0) + n2 = Int32(0) + o1 = Int32(0) + o2 = Int32(0) + for q in cutlass.range_constexpr(8): + c1_ = a1[q] + if c1_ > cap1: + c1_ = cap1 + o1 = o1 + Int32(1) + c2_ = a2[q] + if c2_ > cap2: + c2_ = cap2 + o2 = o2 + Int32(1) + s1 = s1 + c1_ + s2 = s2 + c2_ + n1 = n1 + a1[q] + n2 = n2 + a2[q] + i1 = warp_incl_scan_add(s1, lane) + i2 = warp_incl_scan_add(s2, lane) + t1s = cute.arch.shuffle_sync(i1, Int32(31)) + t2s = cute.arch.shuffle_sync(i2, Int32(31)) + b1 = i1 - s1 + b2 = i2 - s2 + t1s + for q in cutlass.range_constexpr(8): + pq = p0 + Int32(q) + c1_ = a1[q] + if c1_ > cap1: + c1_ = cap1 + c2_ = a2[q] + if c2_ > cap2: + c2_ = cap2 + if Int32(q) < ppl: + if pq < P: + s_pt[pq] = b1 + s_pt[P + pq] = b2 + b1 = b1 + c1_ + b2 = b2 + c2_ + tn1 = Int32(cute.arch.warp_redux_sync(n1, "add")) + tn2 = Int32(cute.arch.warp_redux_sync(n2, "add")) + to1 = Int32(cute.arch.warp_redux_sync(o1, "add")) + to2 = Int32(cute.arch.warp_redux_sync(o2, "add")) + if lane == Int32(0): + s_pt[Int32(2) * P] = t1s + t2s + s_tot[0] = t1s + s_tot[1] = t2s + s_tot[2] = tn1 + s_tot[3] = tn2 + s_tot[4] = to1 + s_tot[5] = to2 + + +@cute.jit +def build_owner_map( + s_own, s_pt, np_, C, s_wc, tid, nthr: cutlass.Constexpr, bar_id: cutlass.Constexpr +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + i = tid + while i < C: + s_own[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + q = tid + while q < np_: + a = Int32(s_pt[q]) + if Int32(s_pt[q + Int32(1)]) > a: + s_own[a] = q + q = q + Int32(nthr) + bar(bar_id, nthr) + E = (C + Int32(nthr) - Int32(1)) // Int32(nthr) + b0 = tid * E + b1 = b0 + E + if b1 > C: + b1 = C + mx = Int32(0) + i = b0 + while i < b1: + v = Int32(s_own[i]) + if v > mx: + mx = v + i = i + Int32(1) + inc = mx + for o in [1, 2, 4, 8, 16]: + other = cute.arch.shuffle_sync_up(inc, o, mask_and_clamp=0) + if lane >= Int32(o): + if other > inc: + inc = other + if lane == Int32(31): + s_wc[wid] = inc + ex = cute.arch.shuffle_sync_up(inc, 1, mask_and_clamp=0) + if lane == Int32(0): + ex = Int32(0) + bar(bar_id, nthr) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + wv = Int32(s_wc[w_]) + if wv > ex: + ex = wv + run = ex + i = b0 + while i < b1: + v = Int32(s_own[i]) + if v > run: + run = v + s_own[i] = run + i = i + Int32(1) + bar(bar_id, nthr) + + +@cute.jit +def gather_parts( + dst, + dst_gmem: cutlass.Constexpr, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + with_hist, + tid, + nthr: cutlass.Constexpr, + s_own=None, +): + UNR = 8 + base = Int32(0) + while base < C: + es = [] + fs = [] + for u in cutlass.range_constexpr(UNR): + f = base + Int32(u * nthr) + tid + fl = f + if fl > C - Int32(1): + fl = C - Int32(1) + p_ = Int32(0) + if cutlass.const_expr(s_own is not None): + p_ = Int32(s_own[fl]) + else: + lo_ = Int32(0) + hi_ = np_ + for it in cutlass.range_constexpr(9): + mid = lo_ + hi_ >> Int32(1) + if Int32(s_pt[mid]) <= fl: + lo_ = mid + else: + hi_ = mid + p_ = lo_ + off = fl - Int32(s_pt[p_]) + src = reg1_base + (Int64(p_) * Int64(cap1) + Int64(off)) * Int64(8) + if p_ >= P: + src = reg2_base + (Int64(p_ - P) * Int64(cap2) + Int64(off)) * Int64(8) + es.append(ld_cg_u64(src)) + fs.append(f) + for u in cutlass.range_constexpr(UNR): + if fs[u] < C: + if cutlass.const_expr(dst_gmem): + st_g_u64(dst.iterator.toint() + Int64(fs[u]) * Int64(8), es[u]) + else: + dst[fs[u]] = es[u] + if with_hist != Int32(0): + b = _vbin(es[u], lo, sc, NB_SEL) + cute.arch.red( + s_hist.iterator + b, + Int32(1), + op="add", + dtype=Int32, + sem="relaxed", + scope="cta", + ) + base = base + Int32(UNR * nthr) + + +@cute.jit +def finalize_tiers( + n, + P, + T, + T3, + HIC, + desc_base, + reg1_base, + reg2_base, + cap1, + cap2, + flat, + s_list, + sel_cap: cutlass.Constexpr, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + s_pt, + s_tot, + s_own, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, + prof=None, +): + K = Int32(K_TOP) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[8] = gtimer() + parts_table_warp0(desc_base, P, cap1, cap2, s_pt, s_tot, tid) + for z_ in cutlass.range_constexpr(NB_SEL // nthr if NB_SEL >= nthr else 1): + if tid + Int32(z_ * nthr) < Int32(NB_SEL): + s_hist[tid + Int32(z_ * nthr)] = Int32(0) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[9] = gtimer() + tot1s = Int32(s_tot[0]) + tot2s = Int32(s_tot[1]) + tot1 = Int32(s_tot[2]) + tot2 = Int32(s_tot[3]) + ovf1 = Int32(s_tot[4]) + ovf2 = Int32(s_tot[5]) + use = Int32(0) + if tot1 >= K: + if ovf1 == Int32(0): + use = Int32(1) + if use == Int32(0): + if T3 > Float32(NEG_INF): + if tot1 + tot2 >= K: + if ovf1 + ovf2 == Int32(0): + use = Int32(2) + C = Int32(0) + m = Int32(0) + nout = Int32(0) + info = Int32(0) + if use != Int32(0): + C = tot1s + np_ = P + lo = T + if use == Int32(2): + C = tot1s + tot2s + np_ = Int32(2) * P + lo = T3 + kth = Uint64(0) + rng = Int32(0) + if HIC > lo: + if HIC < Float32(3e38): + rng = Int32(1) + wv = (HIC - lo) * Float32(1.0 / NB_SEL) + sc = Float32(0.0) + if rng != Int32(0): + sc = cute.arch.rcp_approx(wv) + if C <= Int32(sel_cap): + build_owner_map(s_own, s_pt, np_, C, s_wc, tid, nthr, bar_id) + gather_parts( + s_list, + False, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + rng, + tid, + nthr, + s_own, + ) + bar(bar_id, nthr) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[10] = gtimer() + if rng != Int32(0): + nout, kth, m, info = select_topk_list( + s_list, + C, + K, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + False, + nthr, + bar_id, + False, + None, + lo, + HIC, + True, + ) + else: + nout, kth, m, info = select_topk_list( + s_list, C, K, s_out, s_hist, s_ck, s_res, s_red, s_wc, tid, False, nthr, bar_id + ) + else: + gather_parts( + flat, + True, + np_, + C, + s_pt, + P, + reg1_base, + reg2_base, + cap1, + cap2, + s_hist, + lo, + sc, + Int32(0), + tid, + nthr, + ) + fence_acq_rel_gpu() + bar(bar_id, nthr) + nout, kth, m, info = select_topk_list( + flat, C, K, s_out, s_hist, s_ck, s_res, s_red, s_wc, tid, True, nthr, bar_id + ) + if cutlass.const_expr(prof is not None): + if tid == Int32(0): + prof[11] = gtimer() + return (use, C, m, tot1, tot2, nout, info) + + +@cute.jit +def write_row_outputs( + row, + n, + s_out, + nout, + short, + topk_out, + gidx, + bt_swa, + bt_c, + pos, + req, + mbs, + mbc, + swa_off, + c_off, + tid, + nthr: cutlass.Constexpr, +): + NQ = (640 + nthr - 1) // nthr + gv = [] + cols = [] + for q in cutlass.range_constexpr(NQ): + col = tid + Int32(q * nthr) + g = Int32(-1) + if col < Int32(SWA): + g = l2g_swa(col, pos, req, bt_swa, mbs, swa_off) + elif col < Int32(SWA + K_TOP): + i = col - Int32(SWA) + idx = Int32(-1) + if short != Int32(0): + if i < n: + idx = i + elif i < nout: + idx = entry_idx(Uint64(s_out[i])) + topk_out[row, i] = idx + g = l2g_compressed(idx, req, bt_c, mbc, c_off) + gv.append(g) + cols.append(col) + for q in cutlass.range_constexpr(NQ): + if cols[q] < Int32(SWA + K_TOP): + gidx[row, cols[q]] = gv[q] + + +@cute.jit +def grain_threshold( + gmax_addr, + ng, + s_list, + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + i = tid + while i < ng: + gm = ld_cg_f32(gmax_addr + Int64(i) * Int64(4)) + s_list[i] = pack_entry(u32_of_f32(gm), i) + i = i + Int32(nthr) + bar(bar_id, nthr) + nout, kth, m, info = select_topk_list( + s_list, + ng, + Int32(K_TOP), + s_out, + s_hist, + s_ck, + s_res, + s_red, + s_wc, + tid, + False, + nthr, + bar_id, + True, + ) + return invkey(Uint32(kth >> Uint64(32))) + + +@cute.jit +def recompute_grains( + n, + t0, + t1, + Tstar, + x_row, + gmax_addr, + fbr_addr, + s_cnt, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + NW = nthr // 32 + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + if tid == Int32(0): + s_cnt[0] = Int32(0) + bar(bar_id, nthr) + g = (t0 >> Int32(5)) + wid + g1 = t1 + Int32(31) >> Int32(5) + while g < g1: + gm = ld_cg_f32(gmax_addr + Int64(g) * Int64(4)) + if gm >= Tstar: + p = g * Int32(32) + lane + a = Int32(0) + x = Float32(NEG_INF) + if p < t1: + if p < n: + x = ld_nc_f32(x_row + Int64(p) * Int64(4)) + if x >= Tstar: + a = Int32(1) + msk = Int32(cute.arch.vote_ballot_sync(a != Int32(0))) + tot = Int32(cute.arch.popc(msk)) + b = Int32(0) + if lane == Int32(0): + if tot > Int32(0): + b = Int32( + cute.arch.atomic_add( + s_cnt.iterator + Int32(0), tot, sem="relaxed", scope="cta" + ) + ) + b = cute.arch.shuffle_sync(b, Int32(0)) + if a != Int32(0): + slot = b + Int32(cute.arch.popc(msk & lm)) + st_g_u64(fbr_addr + Int64(slot) * Int64(8), pack_entry(u32_of_f32(x), p)) + g = g + Int32(NW) + bar(bar_id, nthr) + c = Int32(s_cnt[0]) + bar(bar_id, nthr) + return c + + +@cute.jit +def radix_round_local( + s_chunk, + cnt, + prefix, + plen, + shift, + mask, + s_rh, + nbins: cutlass.Constexpr, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + i = tid + while i < Int32(nbins): + s_rh[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + i = tid + while i < cnt: + kb = fkey(Float32(s_chunk[i])) + okp = Int32(1) + if plen > Int32(0): + if kb >> Uint32(Int32(32) - plen) != prefix: + okp = Int32(0) + if okp != Int32(0): + d = Int32(kb >> Uint32(shift) & Uint32(mask)) + cute.arch.atomic_add(s_rh.iterator + d, Int32(1), sem="relaxed", scope="cta") + i = i + Int32(nthr) + bar(bar_id, nthr) + + +@cute.jit +def radix_participant( + row, + part, + P, + n, + t0, + t1, + s_chunk, + ctr_fb, + fbh_row, + fbt_row, + s_rh, + s_res, + s_wc, + s_scal, + topk_out, + gidx, + bt_c, + req, + mbc, + c_off, + tid, + nthr: cutlass.Constexpr, + bar_id: cutlass.Constexpr, +): + lane = tid & Int32(31) + wid = tid >> Int32(5) + lm = Int32(cute.arch.lanemask_lt()) + cnt = t1 - t0 + if t1 > n: + cnt = n - t0 + need = Int32(K_TOP) + prefix = Uint32(0) + plen = Int32(0) + gF = Uint64(0) + for r in cutlass.range_constexpr(3): + bits = 11 if r < 2 else 10 + shift = 21 if r == 0 else 10 if r == 1 else 0 + nb_ = 1 << bits + radix_round_local( + s_chunk, cnt, prefix, plen, Int32(shift), Int32(nb_ - 1), s_rh, 2048, tid, nthr, bar_id + ) + i = tid + while i < Int32(nb_): + c = Int32(s_rh[i]) + if c != Int32(0): + red_add_u32(fbh_row + Int64(r * 2048 + i) * Int64(4), c) + i = i + Int32(nthr) + bar(bar_id, nthr) + if tid == Int32(0): + old = gc_arrive(ctr_fb) + if cutlass.const_expr(r == 0): + gF = old >> Uint64(GEN_SHIFT) + s_scal[6] = Int32(Uint32(gF & Uint64(4294967295))) + s_scal[7] = Int32(Uint32(gF >> Uint64(32))) + gF2 = Uint64(Uint32(s_scal[7])) << Uint64(32) | Uint64(Uint32(s_scal[6])) + gc_wait(ctr_fb, (gF2 << Uint64(GEN_SHIFT)) + Uint64(r + 1) * Uint64(P), Int32(0)) + bar(bar_id, nthr) + i = tid + while i < Int32(nb_): + s_rh[i] = ld_cg_i32(fbh_row + Int64(r * 2048 + i) * Int64(4)) + i = i + Int32(nthr) + if cutlass.const_expr(nb_ < 2048): + i = tid + Int32(nb_) + while i < Int32(2048): + s_rh[i] = Int32(0) + i = i + Int32(nthr) + bar(bar_id, nthr) + scan_cross0(s_rh, need, tid, s_res, need, need, s_rh, nb=2048, zero=True) + bar(bar_id, nthr) + dB = s_res[RES_B] + dab = s_res[RES_ABOVE] + bar(bar_id, nthr) + prefix = prefix << Uint32(bits) | Uint32(dB) + plen = plen + Int32(bits) + need = need - dab + kth = prefix + my_ab = Int32(0) + my_eq = Int32(0) + i = tid + while i < cnt: + kb = fkey(Float32(s_chunk[i])) + if kb > kth: + my_ab = my_ab + Int32(1) + elif kb == kth: + my_eq = my_eq + Int32(1) + i = i + Int32(nthr) + e_, tab = block_excl_scan(my_ab, s_wc, tid, nthr, bar_id) + e2_, teq = block_excl_scan(my_eq, s_wc, tid, nthr, bar_id) + if tid == Int32(0): + st_g_u64( + fbt_row + Int64(part) * Int64(8), + Uint64(Uint32(teq)) << Uint64(32) | Uint64(Uint32(tab)), + ) + gF3 = Uint64(Uint32(s_scal[7])) << Uint64(32) | Uint64(Uint32(s_scal[6])) + old = gc_arrive(ctr_fb) + if Int32(Uint32(old & Uint64(65535))) == Int32(4) * P - Int32(1): + gc_pad(ctr_fb, Int32(4) * P) + gc_wait(ctr_fb, (gF3 << Uint64(GEN_SHIFT)) + Uint64(4) * Uint64(P), Int32(0)) + bar(bar_id, nthr) + ab_t = Int32(0) + eq_t = Int32(0) + if tid < P: + w2 = ld_cg_u64(fbt_row + Int64(tid) * Int64(8)) + ab_t = Int32(Uint32(w2 & Uint64(4294967295))) + eq_t = Int32(Uint32(w2 >> Uint64(32))) + tie_ex, tie_tot_ = block_excl_scan(eq_t, s_wc, tid, nthr, bar_id) + q_t = need - tie_ex + if q_t < Int32(0): + q_t = Int32(0) + if q_t > eq_t: + q_t = eq_t + win_ex, win_tot_ = block_excl_scan(ab_t + q_t, s_wc, tid, nthr, bar_id) + if tid == part: + s_scal[0] = win_ex + s_scal[1] = q_t + bar(bar_id, nthr) + slot0 = Int32(s_scal[0]) + myq = Int32(s_scal[1]) + NW = nthr // 32 + chunk = (cnt + Int32(nthr) - Int32(1)) // Int32(nthr) * Int32(32) + c0 = wid * chunk + c1 = c0 + chunk + if c1 > cnt: + c1 = cnt + nwin = Int32(0) + ntie = Int32(0) + r0 = c0 + while r0 < c1: + ii = r0 + lane + fa = Int32(0) + fe = Int32(0) + if ii < c1: + kb = fkey(Float32(s_chunk[ii])) + if kb > kth: + fa = Int32(1) + elif kb == kth: + fe = Int32(1) + nwin = nwin + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(fa != Int32(0)))) + ntie = ntie + Int32(cute.arch.popc(cute.arch.vote_ballot_sync(fe != Int32(0)))) + r0 = r0 + Int32(32) + if lane == Int32(0): + s_wc[wid] = ntie + bar(bar_id, nthr) + tex = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + tex = tex + Int32(s_wc[w_]) + bar(bar_id, nthr) + tq = myq - tex + if tq < Int32(0): + tq = Int32(0) + if tq > ntie: + tq = ntie + if lane == Int32(0): + s_wc[wid] = nwin + tq + bar(bar_id, nthr) + wex = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) < wid: + wex = wex + Int32(s_wc[w_]) + bar(bar_id, nthr) + pw = slot0 + wex + tr = tex + r0 = c0 + while r0 < c1: + ii = r0 + lane + fa = Int32(0) + fe = Int32(0) + if ii < c1: + kb = fkey(Float32(s_chunk[ii])) + if kb > kth: + fa = Int32(1) + elif kb == kth: + fe = Int32(1) + me = Int32(cute.arch.vote_ballot_sync(fe != Int32(0))) + trank = tr + Int32(cute.arch.popc(me & lm)) + if fe != Int32(0): + if trank < myq: + fa = Int32(1) + mw = Int32(cute.arch.vote_ballot_sync(fa != Int32(0))) + if fa != Int32(0): + slot = pw + Int32(cute.arch.popc(mw & lm)) + idx = t0 + ii + topk_out[row, slot] = idx + gidx[row, Int32(SWA) + slot] = l2g_compressed(idx, req, bt_c, mbc, c_off) + pw = pw + Int32(cute.arch.popc(mw)) + tr = tr + Int32(cute.arch.popc(me)) + r0 = r0 + Int32(32) + per = (Int32(3 * 2048) + P - Int32(1)) // P + z0 = part * per + z1 = z0 + per + if z1 > Int32(3 * 2048): + z1 = Int32(3 * 2048) + i = z0 + tid + while i < z1: + st_g_u32(fbh_row + Int64(i) * Int64(4), Int32(0)) + i = i + Int32(nthr) + bar(bar_id, nthr) + return (kth, need) + + +# ==================================================================================================================== +# L2 cache-policy constants for the indexer-K stream. +# ==================================================================================================================== + +POL_NONE, POL_EVICT_FIRST, POL_UNCHANGED, POL_FIRST_HALF, POL_NORMAL = (0, 1, 2, 3, 4) +POL_NAMES = { + POL_NONE: "none", + POL_EVICT_FIRST: "ef", + POL_UNCHANGED: "eu", + POL_FIRST_HALF: "ef50", + POL_NORMAL: "en", +} +_POL_ASM = { + POL_EVICT_FIRST: "createpolicy.fractional.L2::evict_first.b64 $0, 1.0;", + POL_UNCHANGED: "createpolicy.fractional.L2::evict_unchanged.b64 $0, 1.0;", + POL_FIRST_HALF: "createpolicy.fractional.L2::evict_first.L2::evict_unchanged.b64 $0, 0.5;", + POL_NORMAL: "createpolicy.fractional.L2::evict_normal.b64 $0, 1.0;", +} + + +@dsl_user_op +def make_l2_policy(policy: int, *, loc=None, ip=None) -> cutlass.Int64: + if policy not in _POL_ASM: + raise ValueError(f"no createpolicy for knob {policy}") + return cutlass.Int64( + llvm.inline_asm( + cutlass.Int64.mlir_type, + [], + _POL_ASM[policy], + "=l", + has_side_effects=True, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def ld_shared_b32(smem_ptr, *, loc=None, ip=None): + addr = smem_ptr.toint(loc=loc, ip=ip) + return Int32( + llvm.inline_asm( + Int32.mlir_type, + [addr.ir_value(loc=loc, ip=ip)], + "ld.shared.b32 $0, [$1];", + "=r,r", + has_side_effects=False, + loc=loc, + ip=ip, + ) + ) + + +@dsl_user_op +def st_shared_b32(smem_ptr, val, *, loc=None, ip=None): + addr = smem_ptr.toint(loc=loc, ip=ip) + llvm.inline_asm( + None, + [addr.ir_value(loc=loc, ip=ip), Int32(val).ir_value(loc=loc, ip=ip)], + "st.shared.b32 [$0], $1;", + "r,r", + has_side_effects=True, + loc=loc, + ip=ip, + ) + + +@cute.jit +def sf_atom_transpose(smem_ptr): + """One warp reshuffles 128 int32 (a 128-token scale atom of four UE8M0 each) to the byte layout UTCCP expects.""" + lane_idx = cute.arch.lane_idx() + values = cute.make_rmem_tensor((4,), cutlass.Int32) + for i in cutlass.range_constexpr(4): + values[i] = ld_shared_b32(smem_ptr + (i ^ (lane_idx >> 3)) * 32 + lane_idx) + cute.arch.sync_warp(-1) + for i in cutlass.range_constexpr(4): + st_shared_b32(smem_ptr + lane_idx * 4 + (i ^ (lane_idx >> 3)), values[i]) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_op.py new file mode 100644 index 000000000000..28ab2c42a981 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/megakernel_op.py @@ -0,0 +1,561 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA megakernel, host side: fused DeepSeek-V4-Flash decode for 1 to ``megakernel_max_batch`` rows (47 for the FP8 +spec, 20 for the FP4 spec) on B200 (SM100, 148 SMs). + +One cooperative launch streams each row's indexer K cache (FP8 or MXFP4) once, computes the indexer logits, selects the +exact top-512 compressed positions (sampled threshold with a count certificate and exact fallbacks), maps them to +compressed-KV rows and runs the sparse MLA attention over them plus the 128-row sliding window and the attention sink. + +``prepare`` builds the per-step state (split descriptors from the indexer block table and lengths, window positions, +workspace); ``run`` launches the kernel on the current stream and writes ``topk`` (int32 compressed positions) and +``out`` (bf16). The kernel is compiled on first use per (device, batch size), outside CUDA-graph capture, or ahead of +it by ``precompile``. + +Contract: +- A state belongs to one batch size and one caller. Its workspace carries a generation counter across launches, so + launches that share a state, and ``prepare`` calls that refresh it, must be stream-ordered. +- ``topk`` and ``out`` must not alias any input. +- The launch is cooperative and needs all 148 SMs; it fails at launch on a partitioned device (MPS limits, green + contexts). +- Block tables must hold valid page ids for every page a row touches: the indexer table covers whole 128-position + tiles (``4 * ceil(n / 128)`` entries), the compressed-KV table covers ``ceil(n / 32)`` entries. +- The kernel does not trap. It records per-row errors in its workspace (see ``error_bits``); a row with an error has + undefined outputs. +- Under ``compute-sanitizer --tool synccheck`` only 1 to 4 rows complete: from 5 rows on, every pass after the first + re-initializes its mbarriers without invalidating them (the 3 to 4-row teams run a single pass). +""" + +from __future__ import annotations + +import math +import threading +from dataclasses import dataclass + +import torch + +from .config import ( + DS_V4_FLASH, + DS_V4_FLASH_FP4, + INDEX_TILE, + NUM_SMS, + SpecDsaConfig, + check_device, + supported_spec, +) + +__all__ = [ + "ERR_ABORTED", + "ERR_MISMATCH", + "ERR_NLIMIT", + "ERR_STALE", + "ERR_TIMEOUT", + "SpecDsaMegakernelState", + "error_bits", + "is_supported", + "precompile", + "prepare", + "run", + "supported_batch_sizes", +] + +# Per-row error bits recorded by the kernel (``error_bits``). +ERR_STALE = 1 # the state's lengths differ from run()'s ctx_lens: prepare() was not refreshed +ERR_TIMEOUT = 2 # a wait for another CTA timed out (10 s); the launch was aborted +ERR_NLIMIT = 4 # a compressed length outside [0, max_index_len] +ERR_MISMATCH = 8 # the stream and team CTAs disagreed on the selection path +ERR_ABORTED = 16 # this row stopped because another row or CTA aborted + +_BASE = dict( + debug=False, + stamps=False, + phys_block_kv=DS_V4_FLASH.index_page_tokens, + skew=0, + prewarm=True, + coop=True, + qk_ahead=False, + gjoin=True, + pref=True, + spin_ms=10000, + relst=True, + acqpoll=True, + late_done=4, +) +# Each batch size extends the previous set. From 5 rows on, two teams of 8 CTAs serve the rows in turn while 132 CTAs +# stream the indexer K cache; 9 to 47 rows add the ring of logits slots (ring). +_BS1 = dict(swag=True, nohoist=True, rs24=True, rs24_t4split=True, rs24_lsu=12) +_BS2 = dict(_BS1, math_regs=216, kv_stages=3, wdelay=0, early=True, tearly=True) +_BS4 = dict( + _BS2, + nteams=2, + ppref=False, + presel=True, + pdec=True, + warm1=True, + swpre=False, + pdirect=True, + tsrv1=True, + btcl=True, + tl1r=True, + tsz=True, + tsz2=True, + tsz01=True, + bpf=True, +) +# 3 and 4 rows: one team of 4 CTAs per row (two row groups x two V column halves of 256, one KV gather per tile), so +# every row has its own team and the launch is a single pass. The candidate-row L2 prefetch (pref) is off: it measured +# slower. +_BS4T = dict(_BS2, team4=True, nteams=4, rs24_dry=False, pref=False) +_BS8 = dict(_BS4, tszall=True, dpf=True, b1l=True, b1l_pub=True, b1l_upub=2) +_BS16 = dict(_BS8, ring=True, ring_w12=True) +_CONFIGS: dict[int, dict] = { + 1: _BS1, + 2: _BS2, + 3: _BS4T, + 4: _BS4T, + **{b: _BS8 for b in range(5, 9)}, + **{b: _BS16 for b in range(9, 48)}, +} + +# FP4 spec, 5 or more rows: the shared teams are four teams of 4 CTAs (team4: more rows in flight than two teams of 8), +# the candidate publisher batches 3 atomics per lane, the row's split ranges rotate over the stream CTAs (drot: the CTAs +# that hold the dense end of the sequence, and with it the heavy candidate publication, differ from row to row) and two +# dedicated CTAs compute the thresholds (tcta: no stream CTA with an empty range blocks in the threshold wait). +_FP4_SHARED = dict(team4=True, nteams=4, rs24_dry=False, b1l_upub=3, drot=37, tcta=2) +# FP4 spec, 1 to 4 rows (the stream is shorter than the FP8 one, the fixed costs of the start and of the row +# boundaries decide): the K tiles' TMA descriptors are prefetched at entry and the row lengths are loaded before the +# barrier setup (early / tearly) at one row; from two rows on the next row's descriptor is loaded one row ahead (dpf) +# and the split ranges rotate over the stream CTAs from row to row (drot), as the shared-team sets from five rows on +# already do. The threshold chain (board poll of the T lead, rank bins, T poll of the stream CTAs, classification of the +# buffered tiles) is shortened by _FP4_THRESHOLD: the rank bins come from a histogram instead of a key search and the +# stream CTAs read the threshold line in one round trip (lbin, tpoll1: the same threshold line bit for bit); at one row +# the T lead also starts polling the board without the two fences of the start (lpoll, lfence) and the classification +# loads four tiles at a time (cls4). The followers' dry pass of the threshold code (fwarm) is off: it measures 0.15 us +# slower in the nsys A / B of the unstamped kernel. +_FP4_THRESHOLD = dict(lbin=True, tpoll1=True) +# Two to three rows: the candidate publish of the last row goes out in batches (b1l: the first batch is issued before +# the stream-end barrier; three per lane at three rows, b1l_u 3) and, at two rows, the publisher warps of the first row +# batch theirs as well (b1l_pub, b1l_upub 3). +_FP4_SMALL = { + 1: dict( + early=True, + tearly=True, + lpoll=True, + lfence=True, + cls4=True, + **_FP4_THRESHOLD, + ), + 2: dict(dpf=True, drot=37, b1l=True, b1l_pub=True, b1l_upub=3, **_FP4_THRESHOLD), + 3: dict(dpf=True, drot=37, b1l=True, b1l_u=3, **_FP4_THRESHOLD), + 4: dict(dpf=True, drot=37, **_FP4_THRESHOLD), +} +# Five to eight rows: the T lead ranks the sampled logits with the 256-bin histogram (lbin, as at one to four rows; the +# published threshold line is bit for bit the same) and, at eight rows, the last row's candidate publish goes out four +# per lane (b1l_u 4). +_FP4_MID = {b: dict(_FP4_SHARED, lbin=True) for b in range(5, 9)} +_FP4_MID[8] = dict(_FP4_MID[8], b1l_u=4) +_FP4_OVERRIDES = { + **_FP4_SMALL, + **{b: _FP4_SHARED for b in range(5, 33)}, + **_FP4_MID, +} + +# The knob sets of the megakernel per spec (kernel_key) and batch size: the base knobs plus the set of the batch size +# (and, for the FP4 spec, its overrides). +_KNOBS = { + spec.kernel_key: { + b: { + **_BASE, + **knobs, + **(_FP4_OVERRIDES.get(b, {}) if spec.index_k_dtype == "fp4" else {}), + } + for b, knobs in _CONFIGS.items() + if b <= spec.megakernel_max_batch + } + for spec in (DS_V4_FLASH, DS_V4_FLASH_FP4) +} + +_lock = threading.Lock() +_engines: dict[tuple, dict] = {} + + +def _kernel_modules() -> tuple: + from . import megakernel, megakernel_lib + + return megakernel_lib, megakernel + + +def supported_batch_sizes(config: SpecDsaConfig | None = None) -> range: + """Batch sizes the megakernel serves for ``config`` (default: DS-V4-Flash): 1 up to ``megakernel_max_batch``.""" + return range(1, supported_spec(config).megakernel_max_batch + 1) + + +def is_supported( + device: torch.device | None = None, config: SpecDsaConfig | None = None +) -> tuple[bool, str]: + """Whether the megakernel serves ``config`` (default: DS-V4-Flash) on ``device``. + + That takes a supported spec with a megakernel, CuTe DSL installed and SM100 with all 148 SMs (one CTA per SM). + """ + try: + if supported_spec(config).megakernel_max_batch < 1: + return False, "the spec has no megakernel" + except NotImplementedError as e: + return False, str(e) + return check_device(device) + + +def _check_batch_size(batch_size: int, config: SpecDsaConfig) -> None: + sizes = supported_batch_sizes(config) + if batch_size not in sizes: + raise ValueError(f"batch size {batch_size} not in [{sizes.start}, {sizes.stop - 1}]") + + +def _device_index(device: torch.device) -> int: + device = torch.device(device) + return device.index if device.index is not None else torch.cuda.current_device() + + +def _engine(device: torch.device, batch_size: int, config: SpecDsaConfig | None = None) -> dict: + config = supported_spec(config) + _check_batch_size(batch_size, config) + key = (_device_index(device), batch_size, config.kernel_key) + with _lock: + if key not in _engines: + lib, mk = _kernel_modules() + kernel = mk.SpecDsaMegakernel( + num_sms=NUM_SMS, + policy=lib.POL_EVICT_FIRST if batch_size > 1 else lib.POL_NONE, + full_attention_tiles=True, + nrows=batch_size, + config=config, + **_KNOBS[config.kernel_key][batch_size], + ) + _engines[key] = {"kernel": kernel, "fn": None} + return _engines[key] + + +def _desc_params(kernel, batch_size: int, row: int) -> tuple[int, bool, int]: + """(rot, zlast, zc) of row ``row``'s split descriptor; they select the descriptor kernel variant.""" + shared = batch_size > int(kernel.nteams) and not kernel.tcta + # With shared teams one stream CTA gets an empty range in some rows and computes that row's threshold early + # (not with dedicated T-server CTAs: every stream CTA has a range in every row). + zlast = shared and ( + (kernel.tsz and row == batch_size - 1) or (kernel.tsz2 and row >= batch_size - 2) + ) + zc = -1 + if shared and kernel.tsz01 and (row < 2 or (kernel.tszall and row < batch_size - 2)): + zc = (kernel.ns - 2) if row < 2 else (kernel.ns - 2 - row // 2) + # drot: the ranges of row r rotate by (r mod 8) * drot CTAs (8 distinct descriptor-kernel variants per layout) + return ((row % 8) * int(kernel.drot)) % kernel.ns, bool(zlast), int(zc) + + +def precompile(device: torch.device, batch_size: int, config: SpecDsaConfig | None = None) -> None: + """Compile the kernels for ``batch_size`` rows on ``device`` (main kernel about 15 s, plus the descriptor kernels). + + Must run outside CUDA-graph capture. ``run`` compiles on first use otherwise. + """ + e = _engine(device, batch_size, config) + _, mk = _kernel_modules() + with _lock: + if e["fn"] is None: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "spec_dsa: compile the kernel (precompile) before CUDA-graph capture" + ) + e["fn"] = mk.compile_mk(e["kernel"]) + kernel = e["kernel"] + for r in range(batch_size): + rot, zlast, zc = _desc_params(kernel, batch_size, r) + mk.compile_desc(NUM_SMS, kernel.ns, rot, zlast, zc, kernel.fp4) + + +@dataclass +class SpecDsaMegakernelState: + """Per-step metadata and workspace of one caller; see ``prepare``. + + ``ws64`` holds ``WS_WORDS`` int64 words per row (generation counter, error words, selection directives), ``hist``, + ``board`` and ``region`` the per-row selection scratch. ``gidx``, ``dbg``, ``stamps`` and ``ctl`` are kernel + arguments used only by diagnostic builds. ``config`` is the spec the state was built for. + """ + + batch_size: int + desc: torch.Tensor + swa_local: torch.Tensor + swa_lens: torch.Tensor + gidx: torch.Tensor + ws64: torch.Tensor + hist: torch.Tensor + board: torch.Tensor + region: torch.Tensor + dbg: torch.Tensor + stamps: torch.Tensor + ctl: torch.Tensor + config: SpecDsaConfig + + +def _host_ints(t: torch.Tensor, count: int, name: str) -> list[int]: + v = t.reshape(-1) + if v.numel() < count: + raise ValueError(f"{name} has {v.numel()} entries, need {count}") + return [int(x) for x in v[:count].tolist()] + + +def prepare( + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + idx_block_table: torch.Tensor, + state: SpecDsaMegakernelState | None = None, + *, + config: SpecDsaConfig | None = None, +) -> SpecDsaMegakernelState: + """Build (or refresh in place) the per-step state for ``B = ctx_lens.numel()`` rows. + + Args: + ctx_lens: int32 [B], compressed (indexer) length of each row, in [512, 2**18] for DS-V4-Flash. + kv_lens: int32 [B], uncompressed length of each row (>= 128); the window is its last 128 positions. + idx_block_table: int32 [B, pages] on the target device, indexer K pages of each row (32 compressed positions + per page; whole 128-position tiles, so at least ``4 * ceil(n / 128)`` valid entries). + state: a state of the same batch size to refresh; keeps its workspace (and generation counter) and its spec. + config: the spec (default: DS-V4-Flash, the only one the kernels serve). + + The lengths are checked on the host: pass host (CPU) tensors to avoid a device-to-host copy; device tensors work + but synchronize. + """ + if state is not None: + if config is not None and config.kernel_key != state.config.kernel_key: + raise ValueError(f"state is for {state.config.name!r}, got {config.name!r}") + config = state.config + config = supported_spec(config) + batch_size = int(ctx_lens.numel()) + _check_batch_size(batch_size, config) + device = idx_block_table.device + if device.type != "cuda": + raise ValueError("idx_block_table must be a CUDA tensor") + ctx_host = _host_ints(ctx_lens, batch_size, "ctx_lens") + kv_host = _host_ints(kv_lens, batch_size, "kv_lens") + if any(not config.min_index_len <= n <= config.max_index_len for n in ctx_host): + raise ValueError( + f"compressed lengths must lie in [{config.min_index_len}, {config.max_index_len}], got {ctx_host}" + ) + if any(n < config.window for n in kv_host): + raise ValueError(f"uncompressed lengths must be at least {config.window}, got {kv_host}") + need_pages = config.pages_per_tile * math.ceil(max(ctx_host) / INDEX_TILE) + if idx_block_table.dim() != 2 or idx_block_table.shape[0] < batch_size: + raise ValueError(f"idx_block_table must be [B, pages] with B >= {batch_size}") + if idx_block_table.shape[1] < need_pages: + raise ValueError( + f"idx_block_table has {idx_block_table.shape[1]} pages per row, need {need_pages}" + ) + if state is not None and state.batch_size != batch_size: + raise ValueError(f"state is for {state.batch_size} rows, got {batch_size}") + _, mk = _kernel_modules() + kernel = _engine(device, batch_size, config)["kernel"] + rsz = kernel.row_sizes() + if state is None: + state = SpecDsaMegakernelState( + batch_size=batch_size, + desc=torch.zeros(batch_size * rsz["desc"], dtype=torch.int32, device=device), + swa_local=torch.empty((batch_size, config.window), dtype=torch.int32, device=device), + swa_lens=torch.full((batch_size,), config.window, dtype=torch.int32, device=device), + gidx=torch.full( + (batch_size, config.selected_rows), -7, dtype=torch.int32, device=device + ), + ws64=torch.zeros(batch_size * rsz["ws"], dtype=torch.int64, device=device), + hist=torch.zeros(batch_size * rsz["hist"], dtype=torch.int32, device=device), + board=torch.zeros(batch_size * rsz["board"], dtype=torch.int64, device=device), + region=torch.zeros(batch_size * rsz["region"], dtype=torch.int64, device=device), + dbg=torch.empty(config.max_index_len + 512, dtype=torch.float32, device=device), + stamps=torch.zeros( + NUM_SMS + * mk.NSTAMP + * ( + 56 + if batch_size > 16 + else (40 if batch_size > 8 else (4 if batch_size > 1 else 1)) + ), + dtype=torch.int64, + device=device, + ), + ctl=torch.zeros(batch_size * rsz["ctl"], dtype=torch.int32, device=device), + config=config, + ) + torch.add( + torch.tensor(kv_host, dtype=torch.int32).to(device, non_blocking=True).unsqueeze(1), + torch.arange(-config.window, 0, dtype=torch.int32, device=device), + out=state.swa_local, + ) + ctx = torch.tensor(ctx_host, dtype=torch.int32).to(device, non_blocking=True) + bt = idx_block_table[:batch_size].to(dtype=torch.int32).contiguous() + with _lock: # the descriptor kernels compile on first use + for r in range(batch_size): + rot, zlast, zc = _desc_params(kernel, batch_size, r) + mk.build_desc_device( + ctx[r : r + 1], + bt[r : r + 1], + state.desc[r * rsz["desc"] : (r + 1) * rsz["desc"]], + NUM_SMS, + kernel.ns, + rot=rot, + zlast=zlast, + zc=zc, + ladder_words=kernel.fp4, + ) + return state + + +def error_bits(state: SpecDsaMegakernelState) -> torch.Tensor: + """Per-row error bits (``ERR_*``) accumulated over the launches of ``state``: an int64 [B] device view, no sync. + + Zero means every launch so far completed normally. The bits are sticky; a fresh state starts at zero. + """ + _, mk = _kernel_modules() + return state.ws64.view(state.batch_size, mk.WS_WORDS)[:, mk.W_ERRB] + + +def _check_rows(name: str, t: torch.Tensor, row_bytes: int) -> None: + if t.element_size() != 1 or t.dim() < 2 or t.shape[-1] != row_bytes or not t.is_contiguous(): + raise ValueError( + f"{name} must be a contiguous 1-byte tensor with {row_bytes}-byte rows, " + f"got {t.dtype} {tuple(t.shape)}" + ) + + +def _check_numel(name: str, t: torch.Tensor, numel: int, dtype: torch.dtype | None = None) -> None: + if t.numel() != numel or (dtype is not None and t.dtype != dtype) or not t.is_contiguous(): + raise ValueError( + f"{name} must be contiguous with {numel} elements" + + (f" of {dtype}" if dtype is not None else "") + + f", got {t.dtype} {tuple(t.shape)}" + ) + + +def run( + state: SpecDsaMegakernelState, + q_idx: torch.Tensor, + w_idx: torch.Tensor, + k_cache: torch.Tensor, + idx_block_table: torch.Tensor, + ctx_lens: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + sinks: torch.Tensor, + topk: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + q_scale: torch.Tensor | None = None, +) -> None: + """Launch the fused kernel on the current stream. + + Args: + state: from ``prepare`` for these lengths and block tables. + q_idx: float8_e4m3fn [B, 64, 128] (or [B, 1, 64, 128]), indexer queries; for an FP4 spec packed E2M1, 1 byte + per two values ([B, 64, 64]). + w_idx: float32 [B, 64], indexer head weights. + k_cache: uint8 [pages, ...] with ``config.index_page_bytes`` bytes per page: 4224 for FP8 (32 x 128 FP8 values, + then 32 float32 scales), 2176 for FP4 (32 x 64 bytes of E2M1 pairs, then 32 int32 of four UE8M0 scales, one + per 32 values). + idx_block_table: int32 [B, pages], as given to ``prepare``. + ctx_lens: int32 [B] on the device, the same lengths as given to ``prepare``. + q_att: float8_e4m3fn [B, 64, 512], attention queries. + swa_pool: float8_e4m3fn [..., 512], sliding-window KV rows (128 rows per page); bt_swa: int32 [B, pages]. + c_pool: float8_e4m3fn [..., 512], compressed KV rows (32 rows per page); bt_c: int32 [B, pages], each row + 16-byte aligned (row stride a multiple of 4 entries). + sinks: float32 [64], per-head attention sink. + topk: int32 [B, 512] output, the selected compressed positions (in no particular order). + out: bfloat16 [B, 64 * 512] output. + softmax_scale: attention softmax scale (default: ``1 / sqrt(kv_dim)`` of the spec). + q_scale: int32 [B, 64] (or [B, 1, 64]), the four UE8M0 query scales of each head in one int32 (FP4 specs only). + + The shapes are those of the DS-V4-Flash spec; ``state.config`` gives the sizes the checks use. + """ + config = state.config + b = state.batch_size + fp4 = config.index_k_dtype == "fp4" + if softmax_scale is None: + softmax_scale = config.default_softmax_scale + q_values = config.index_head_dim // 2 if fp4 else config.index_head_dim + _check_numel("q_idx", q_idx, b * config.index_heads * q_values) + if fp4: + if q_scale is None: + raise ValueError("an FP4 spec needs q_scale (the UE8M0 scales of the FP4 queries)") + _check_numel("q_scale", q_scale, b * config.index_heads, torch.int32) + elif q_scale is not None: + raise ValueError("q_scale belongs to FP4 specs") + if q_idx.element_size() != 1: + raise ValueError(f"q_idx must be FP8 (1 byte per value), got {q_idx.dtype}") + _check_numel("w_idx", w_idx, b * config.index_heads, torch.float32) + _check_numel("q_att", q_att, b * config.attn_heads * config.kv_dim) + if q_att.element_size() != 1: + raise ValueError(f"q_att must be FP8 (1 byte per value), got {q_att.dtype}") + _check_numel("sinks", sinks, config.attn_heads) + _check_numel("topk", topk, b * config.topk, torch.int32) + _check_numel("out", out, b * config.attn_heads * config.kv_dim, torch.bfloat16) + _check_rows("swa_pool", swa_pool, config.kv_dim) + _check_rows("c_pool", c_pool, config.kv_dim) + pages = int(k_cache.shape[0]) + if k_cache.element_size() != 1 or k_cache.numel() != pages * config.index_page_bytes: + raise ValueError( + f"k_cache must hold {config.index_page_bytes} bytes per page, got {tuple(k_cache.shape)}" + ) + if bt_c.dtype != torch.int32 or bt_c.stride(-1) != 1 or bt_c.data_ptr() % 16 != 0: + raise ValueError("bt_c must be int32 with unit stride and a 16-byte aligned base") + if b > 1 and bt_c.stride(0) % 4 != 0: + raise ValueError(f"bt_c rows must be 16-byte aligned, got a row stride of {bt_c.stride(0)}") + e = _engine(q_idx.device, b, config) + if e["fn"] is None: + precompile(q_idx.device, b, config) + e["fn"]( + k_cache.view(pages, -1), + q_idx.reshape(-1) + .as_strided( + (config.index_heads, q_values, b), + (q_values, 1, config.index_heads * q_values), + ) + .view(torch.uint8), + w_idx.reshape(-1).as_strided((config.index_heads, b), (1, config.index_heads)), + idx_block_table[:b], + ctx_lens.reshape(-1)[:b], + state.desc, + q_att.view(torch.uint8).view(b, config.attn_heads, config.kv_dim), + swa_pool.view(torch.uint8).view(-1, config.kv_dim), + c_pool.view(torch.uint8).view(-1, config.kv_dim), + state.swa_local, + bt_swa[:b], + bt_c[:b], + sinks.reshape(-1).float(), + state.swa_lens, + topk, + state.gidx, + out, + state.ws64, + state.hist, + state.board, + state.region, + state.dbg, + state.stamps, + state.ctl, + pages, + softmax_scale, + *( + (q_scale.reshape(-1).as_strided((config.index_heads, b), (1, config.index_heads)),) + if fp4 + else () + ), + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/op.py new file mode 100644 index 000000000000..97a79f629395 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/op.py @@ -0,0 +1,417 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA: fused decode sparse attention of a DeepSeek DSA model on B200 (SM100), any batch size from 1 to 1,024. + +One decode step of a CSA layer: FP8 or MXFP4 paged-MQA indexer logits over the compressed indexer K cache, exact top-K +selection, mapping of the selected positions to compressed-KV rows, and the sparse MLA attention over those rows, the +sliding window and the attention sink. One call replaces the four kernels of the unfused chain. The megakernel guesses +the top-K threshold from a sample of the row's own logits (the sampling ladder of the GVR V2 top-K) and checks it with a +count certificate; a row where the guess does not hold takes an exact fallback. The large-batch kernels take no sample: +they learn a floor from the candidates already admitted in the row and select the exact top-K from the ones kept. The +tail-attention hybrid keeps the production indexer logits kernel and replaces the rest of the chain. The selection is +exact in all three. + +The kernels are specialized for a ``SpecDsaConfig`` (``config.py``). The default spec is ``DS_V4_FLASH`` (top-512 over a +64 x 128 FP8 indexer, 64 attention heads over 512-byte E4M3 KV rows, a 128-row window); ``DS_V4_FLASH_FP4`` is the same +model with the MXFP4 indexer K cache. A config without kernels is refused with ``NotImplementedError`` +(``is_supported`` and ``config.supported_spec`` tell beforehand) and its caller keeps the existing kernels. + +Three implementations sit behind one interface; ``implementation_for`` names the one a batch size uses by default: + +- ``megakernel`` (``megakernel.py`` / ``megakernel_op.py``, 1 to ``megakernel_max_batch`` rows): one cooperative launch + that streams the indexer K cache once and does the selection and the attention on dedicated CTAs while the others + keep streaming; compiled per batch size. +- ``tail_hybrid`` (``hybrid_op.py``, the batch sizes of ``tail_hybrid_range``, FP4 spec only): the indexer logits kernel + of the production MXFP4 chain, the multi-CTA exact top-512 (``topk_multicta_op.py``) and the tail attention + (``tail_op.py``), the last two by default with programmatic dependent launch up to 24 rows and a polling handshake + up to 23 rows. +- ``large_batch`` (``large_batch.py`` / ``large_batch_op.py``, more rows): a persistent indexer kernel and an attention + kernel launched behind it with programmatic dependent launch; one compile per knob range (``large_batch_op``) + serves every batch size in the range. + +| Spec | megakernel | tail hybrid | large batch | +| --- | --- | --- | --- | +| DS-V4-Flash (FP8) | 1 to 47 | none | 48 to 1,024 | +| DS-V4-Flash-FP4 | 1 to 4 | 5 to 26 | 27 to 1,024 | + +The default is the hybrid inside the spec's ``tail_hybrid_range``, else the megakernel up to ``megakernel_max_batch``, +else the large-batch kernels; for the FP4 spec these are the fastest ones in the measurements against the production +FP4 chain (1M-token captures, B200; ``README.md``). ``prepare`` and ``precompile`` take ``implementation=`` to force one +that can serve the batch size, e.g. the megakernel (which serves up to 20 FP4 rows) at 5 to 20 rows; a state remembers +its implementation. + +The hybrid is not self-contained: its logits stage is the production op +``torch.ops.trtllm.cute_dsl_fp4_paged_mqa_logits`` with the scheduler metadata of ``tensorrt_llm.deep_gemm``. Both are +resolved when first used; a missing one is a ``RuntimeError`` (``hybrid_op.is_supported``, or ``is_supported`` with a +``batch_size``, tells beforehand), with no fallback. The hybrid is tuned for rows of 1M tokens: its top-K is exact for +every length, but the faster top-K stage only for rows of 16,384 positions or more +(``topk_multicta_op.is_profitable``). For shorter rows the megakernel stays selectable at 5 to 20 rows +(``implementation="megakernel"``). + +Per step, ``prepare`` does the host work (descriptors, CTA schedule or logits scheduler metadata from the lengths, the +sinks) and ``run`` launches on the current stream; the launch can be captured in a CUDA graph and replayed while +``prepare`` refreshes the state in place. + +Contract (the numbers are those of DS-V4-Flash): +- A state belongs to one batch size, one spec, one implementation and one caller. ``prepare`` calls that refresh it and + launches that share it must be stream-ordered. The tail hybrid's logits live in the process-global buffer of the + production logits op: its launches, and that op's other users, must be stream-ordered also across states. +- ``ctx_lens`` (compressed indexer length of each row, in [512, 2**18]) and ``kv_lens`` (uncompressed length, at least + 128; the window is its last 128 positions) are read on the host by ``prepare``: pass host (CPU) tensors to avoid a + device-to-host copy; device tensors work but synchronize. ``run`` takes both on the device. The megakernel does not + read the ``kv_lens`` of ``run``, and the tail hybrid does not read its ``ctx_lens``: it uses the copy of the lengths + that ``prepare`` keeps in the state. +- ``topk`` and ``out`` must not alias any input. +- The kernels need all 148 SMs; they fail at launch on a partitioned device (MPS limits, green contexts). +- Block tables must hold valid page ids for every page a row touches: the indexer table covers whole 128-position tiles + (``4 * ceil(n / 128)`` entries per row), the compressed-KV table ``ceil(n / 32)`` entries. The tail hybrid and the + large-batch kernels take contiguous ``idx_block_table``, ``bt_swa`` and ``bt_c`` only; the megakernel also takes + strided ones. +- A launch whose state does not match ``ctx_lens`` (``prepare`` not refreshed) is refused or flagged through + ``error_bits`` and its outputs are undefined. The tail hybrid has no device flag and does not detect it: it computes + for the lengths ``prepare`` saw. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + +from . import hybrid_op, large_batch_op, megakernel_op +from .config import SpecDsaConfig, check_device, supported_spec + +__all__ = [ + "ERR_STALE", + "IMPLEMENTATIONS", + "SpecDsaState", + "error_bits", + "implementation_for", + "is_supported", + "precompile", + "prepare", + "run", +] + +# Error bit shared by the megakernel and the large-batch kernels: the state's lengths differ from the launch's +# ``ctx_lens`` (``prepare`` was not refreshed). The megakernel reports further bits per row (``megakernel_op.ERR_*``). +ERR_STALE = 1 + +_MEGAKERNEL = "megakernel" +_TAIL_HYBRID = "tail_hybrid" +_LARGE_BATCH = "large_batch" +IMPLEMENTATIONS = (_MEGAKERNEL, _TAIL_HYBRID, _LARGE_BATCH) + + +@dataclass +class SpecDsaState: + """Per-step metadata and workspace of one caller; see ``prepare``. + + ``implementation`` names the kernels the state is for (``implementation_for`` of the batch size, or the one forced + at ``prepare``), ``state`` is their state, ``sinks`` the float32 [attn_heads] attention-sink copy the megakernel + launch reads (the large-batch and tail-hybrid states hold their own copy) and ``config`` the spec the state was + built for. + """ + + batch_size: int + implementation: str + state: object + sinks: torch.Tensor | None + config: SpecDsaConfig + + +def implementation_for(batch_size: int, config: SpecDsaConfig | None = None) -> str: + """Name of the implementation that serves ``batch_size`` rows of ``config`` (default: DS-V4-Flash) by default. + + ``"tail_hybrid"`` inside ``config.tail_hybrid_range``, else ``"megakernel"`` up to ``config.megakernel_max_batch``, + else ``"large_batch"``. ``prepare`` and ``precompile`` can force another implementation that serves the batch size. + """ + config = supported_spec(config) + if not 1 <= batch_size <= config.max_batch: + raise ValueError(f"batch size {batch_size} not in [1, {config.max_batch}]") + rng = config.tail_hybrid_range + if rng is not None and rng[0] <= batch_size <= rng[1]: + return _TAIL_HYBRID + return _MEGAKERNEL if batch_size <= config.megakernel_max_batch else _LARGE_BATCH + + +def _batch_sizes(implementation: str, config: SpecDsaConfig) -> range: + """Batch sizes ``implementation`` can serve for ``config``.""" + if implementation == _MEGAKERNEL: + return megakernel_op.supported_batch_sizes(config) + if implementation == _TAIL_HYBRID: + return hybrid_op.supported_batch_sizes(config) + return range(1, config.max_batch + 1) if config.large_batch else range(0) + + +def _select(batch_size: int, config: SpecDsaConfig, implementation: str | None) -> str: + """``implementation`` if it is given and can serve ``batch_size`` rows, else the default one.""" + default = implementation_for(batch_size, config) + if implementation is None or implementation == default: + return default + if implementation not in IMPLEMENTATIONS: + raise ValueError(f"implementation must be one of {IMPLEMENTATIONS}, got {implementation!r}") + sizes = _batch_sizes(implementation, config) + if not sizes: + raise ValueError(f"{config.name} has no {implementation} implementation") + if batch_size not in sizes: + raise ValueError( + f"the {implementation} implementation of {config.name} serves {sizes.start} to {sizes.stop - 1} rows, " + f"got {batch_size}" + ) + return implementation + + +def is_supported( + device: torch.device | None = None, + config: SpecDsaConfig | None = None, + batch_size: int | None = None, +) -> tuple[bool, str]: + """Whether the kernels serve ``config`` (default: DS-V4-Flash) on ``device``, and the reason when they do not. + + That takes a spec with kernels, CuTe DSL installed and SM100 with all 148 SMs (one CTA per SM). The batch sizes of + the tail hybrid also need the production logits op (``hybrid_op.is_supported``): pass ``batch_size`` to include that + check when the hybrid is its default implementation; without it a True answer does not cover those sizes. + """ + try: + config = supported_spec(config) + except NotImplementedError as e: + return False, str(e) + ok, why = check_device(device) + if not ok or batch_size is None: + return ok, why + try: + implementation = implementation_for(batch_size, config) + except ValueError as e: + return False, str(e) + if implementation == _TAIL_HYBRID: + return hybrid_op.is_supported(device, config) + return True, "" + + +def precompile( + device: torch.device, + batch_size: int, + config: SpecDsaConfig | None = None, + *, + implementation: str | None = None, +) -> None: + """Compile what ``batch_size`` rows need on ``device`` (the megakernel per batch size, the large-batch kernels + once, the tail hybrid's top-K and tail attention per cluster size and its logits kernel). + + ``implementation`` forces one that can serve the batch size (default: ``implementation_for``). Must run outside + CUDA-graph capture; ``run`` compiles on first use otherwise. + """ + config = supported_spec(config) + implementation = _select(batch_size, config, implementation) + if implementation == _MEGAKERNEL: + megakernel_op.precompile(device, batch_size, config) + elif implementation == _TAIL_HYBRID: + hybrid_op.precompile(device, batch_size, config) + else: + large_batch_op.precompile(device, config) + + +def prepare( + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + idx_block_table: torch.Tensor, + sinks: torch.Tensor, + state: SpecDsaState | None = None, + *, + config: SpecDsaConfig | None = None, + implementation: str | None = None, +) -> SpecDsaState: + """Build (or refresh in place) the per-step state for ``B = ctx_lens.numel()`` rows. + + Args: + ctx_lens: int32 [B], compressed (indexer) length of each row, in [512, 2**18]. + kv_lens: int32 [B], uncompressed length of each row (>= 128). + idx_block_table: int32 [B, pages] on the target device, indexer K pages of each row (32 compressed positions + per page; whole 128-position tiles). + sinks: float32 [64] on the target device, per-head attention sink. + state: a state of the same batch size to refresh; keeps its workspace, its spec and its implementation. + config: the spec (default: DS-V4-Flash). A new state is built for it; a refreshed state keeps its own. + implementation: ``"megakernel"``, ``"tail_hybrid"`` or ``"large_batch"``: force that one for a new state (it has + to be able to serve the batch size, e.g. the megakernel for 5 to 20 rows of the FP4 spec). Default: the + implementation of ``implementation_for``, or, when refreshing, the one of ``state``. A request that differs + from the implementation of ``state`` is an error. + """ + if state is not None: + if config is not None and config.kernel_key != state.config.kernel_key: + raise ValueError(f"state is for {state.config.name!r}, got {config.name!r}") + config = state.config + config = supported_spec(config) + if implementation is not None and implementation not in IMPLEMENTATIONS: + raise ValueError(f"implementation must be one of {IMPLEMENTATIONS}, got {implementation!r}") + batch_size = int(ctx_lens.numel()) + if implementation is None and state is not None and state.batch_size == batch_size: + implementation = state.implementation + else: + implementation = _select(batch_size, config, implementation) + if sinks.numel() != config.attn_heads: + raise ValueError(f"sinks must have {config.attn_heads} entries, got {tuple(sinks.shape)}") + if state is not None and ( + state.batch_size != batch_size or state.implementation != implementation + ): + raise ValueError( + f"state is for {state.batch_size} rows ({state.implementation}), got {batch_size} rows ({implementation})" + ) + inner = state.state if state is not None else None + sinks_copy = None + if implementation == _MEGAKERNEL: + inner = megakernel_op.prepare(ctx_lens, kv_lens, idx_block_table, inner, config=config) + sinks_copy = ( + state.sinks + if state is not None + else torch.empty(config.attn_heads, dtype=torch.float32, device=sinks.device) + ) + sinks_copy.copy_(sinks.reshape(-1)) + elif implementation == _TAIL_HYBRID: + inner = hybrid_op.prepare(ctx_lens, kv_lens, idx_block_table, sinks, inner, config=config) + else: + if int(kv_lens.numel()) != batch_size: + raise ValueError(f"kv_lens must have {batch_size} entries, got {int(kv_lens.numel())}") + if idx_block_table.dim() != 2 or idx_block_table.shape[0] < batch_size: + raise ValueError(f"idx_block_table must be [B, pages] with B >= {batch_size}") + inner = large_batch_op.prepare(ctx_lens, sinks, inner, config=config) + if state is not None: + return state + return SpecDsaState( + batch_size=batch_size, + implementation=implementation, + state=inner, + sinks=sinks_copy, + config=config, + ) + + +def error_bits(state: SpecDsaState) -> torch.Tensor: + """Error bits of the launches of ``state``: a device view, no sync; zero means no error. + + The megakernel keeps one sticky int64 word per row (``megakernel_op.ERR_*``); the large-batch kernels keep one int32 + status word of the last launch (``ERR_STALE``; a fresh state reads -7 until its first launch); the tail hybrid has + no device flag and returns an int32 [1] zero (a stale state is not detected). + """ + if state.implementation == _MEGAKERNEL: + return megakernel_op.error_bits(state.state) + if state.implementation == _TAIL_HYBRID: + return hybrid_op.error_bits(state.state) + return large_batch_op.error_bits(state.state) + + +def run( + state: SpecDsaState, + q_idx: torch.Tensor, + w_idx: torch.Tensor, + k_cache: torch.Tensor, + idx_block_table: torch.Tensor, + ctx_lens: torch.Tensor, + kv_lens: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + topk: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + q_scale: torch.Tensor | None = None, +) -> None: + """Launch the fused kernels on the current stream. + + Args: + state: from ``prepare`` for these lengths and block tables. + q_idx: float8_e4m3fn [B, 64, 128] (or [B, 1, 64, 128]), indexer queries. + w_idx: float32 [B, 64], indexer head weights. + k_cache: uint8 [pages, ...] with 4224 bytes per page, indexer K pages (32 x 128 FP8 values, then 32 float32 + scales). + idx_block_table: int32 [B, pages], as given to ``prepare``. + ctx_lens: int32 [B] on the device, the lengths given to ``prepare`` (not read by the tail hybrid). + kv_lens: int32 [B] on the device, uncompressed lengths (the window is the last 128 positions); not read by the + megakernel. + q_att: float8_e4m3fn [B, 64, 512], attention queries. + swa_pool: float8_e4m3fn [..., 512], sliding-window KV rows (128 rows per page); bt_swa: int32 [B, pages]. + c_pool: float8_e4m3fn [..., 512], compressed KV rows (32 rows per page); bt_c: int32 [B, pages]. The megakernel + takes strided block tables (``bt_c``: each row 16-byte aligned, row stride a multiple of 4 entries), the + tail hybrid and the large-batch kernels contiguous ones. + topk: int32 [B, 512] output, the selected compressed positions (in no particular order). + out: bfloat16 [B, 64 * 512] output. + softmax_scale: attention softmax scale (default: ``1 / sqrt(kv_dim)`` of the spec of ``state``). + q_scale: int32 [B, 64], the packed UE8M0 scales of an FP4 ``q_idx`` (FP4 specs only: ``q_idx`` and ``k_cache`` + are FP4 then). + + The shapes are those of DS-V4-Flash; ``state.config`` gives the sizes the checks use. For the FP4 spec ``k_cache`` + has 2176 bytes per page (32 x 64 bytes of E2M1 pairs, then 32 int32 of four UE8M0 scales) and ``q_idx`` holds + 1 byte per two values ([B, 64, 64]). + """ + if state.implementation == _MEGAKERNEL: + megakernel_op.run( + state.state, + q_idx, + w_idx, + k_cache, + idx_block_table, + ctx_lens, + q_att, + swa_pool, + bt_swa, + c_pool, + bt_c, + state.sinks, + topk, + out, + softmax_scale, + q_scale=q_scale, + ) + elif state.implementation == _TAIL_HYBRID: + hybrid_op.run( + state.state, + q_idx, + w_idx, + k_cache, + idx_block_table, + ctx_lens, + kv_lens, + q_att, + swa_pool, + bt_swa, + c_pool, + bt_c, + topk, + out, + softmax_scale, + q_scale=q_scale, + ) + else: + large_batch_op.run( + state.state, + q_idx, + w_idx, + k_cache, + idx_block_table, + ctx_lens, + kv_lens, + q_att, + swa_pool, + bt_swa, + c_pool, + bt_c, + topk, + out, + softmax_scale, + q_scale=q_scale, + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_attention.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_attention.py new file mode 100644 index 000000000000..0a84bedcfdc7 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_attention.py @@ -0,0 +1,971 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA tail attention (K4'): the decode sparse MLA of all rows in parallel, the KV tiles of a row split over a +cluster of CTAs. + +Replaces the chain's K3 (local-to-global mapping) + K4 (sparse MLA) + K4b (reduction) behind any exact top-K kernel: +the input is the exact top-512 selection (local compressed positions, ``topk`` [B, 512] int32, as the top-K kernel +writes it) and the attention inputs of the large-batch tail; the output is ``out`` [B, 64 * 512] bf16, the same result +as ``AttentionTail`` of the large-batch kernels. + +One cluster of 5 CTAs serves a row. The row has five tiles of 128 KV rows: tile 0 = the sliding window, tiles 1-4 = the +selected rows (entries 128 (j - 1) .. 128 j - 1 of ``topk``), one tile per CTA. Every CTA runs the ``AttentionTail`` +pipeline (loader warps: local-to-global mapping + TMA gather4, MMA warp, softmax warps) on its tile with its own +running max, P quantized to E4M3 at that max, and fp32 O in TMEM. The partials are combined in the cluster: the +(max, sum) pairs go to the CTAs that own an output slice, the partial O (bf16, 128-column slice v -> CTA v % 5) goes +to the owner through distributed shared memory (``st.async`` completing the owner's mbarrier), and the owner combines +with 2^(L (m_i - m*)) weights (L = scale * log2 e), applies the sink and the normalization (the arithmetic of +``megakernel_attention._merge_*``) and stores. + +The CTAs compute and send the output slices in the order of their rank (``_pv``, ``_softmax``): CTA r starts with its +own slice and then serves the owners r + 1, r + 2, ... one after the other, so that every owner receives from one CTA +at a time (in the order 0, 1, 2, 3 all CTAs queued up at one owner after the other, and the distributed shared memory +of an SM takes ~28 bytes per clock). The slices are sent before the CTA waits for the (max, sum) pairs of its peers, +which the sends do not need. The results do not change (bit-identical). + +Only the cluster size 5 is built and validated (``SUPPORTED_CLUSTER_SIZES``): it serves up to 26 rows, the clusters of +5 CTAs that a 148-SM B200 holds at once at one CTA per SM. The tile split and the slice ownership are written for any +cluster size of 3 to 5, but the clusters of 4 and 3 CTAs (27 to 45 rows) were measured to win nothing over the +large-batch kernels and to leave only 0.5 to 0.8 % of the headroom to the accuracy bar of the real-capture gates (5 +CTAs leave about 9 %), so the constructor refuses them. + +The launch is a plain stream-ordered launch, or, with ``pdl``, a programmatic dependent launch: the kernel waits for +the grid dependency before it reads the selection (``griddepcontrol.wait``, a no-op in a plain launch), so its CTAs can +start while the top-K kernel still ranks its crossing bin (the multi-CTA top-K of ``topk_multicta`` triggers the launch +after its stream phase) and run the barrier / TMEM setup, the Q load and the sliding-window tile in the shadow of that +kernel; the CTAs of the selected tiles also bring the block-table row of their request into L2 (the loads behind the +wait read random pages of it). Behind a top-K kernel that never triggers early (the production one) the attribute only +costs 0.7 to 0.8 us at 8 to 16 rows (measured): ``pdl`` is for the multi-CTA top-K. + +With ``poll`` the kernel does not wait for the completion of the top-K grid at all: the multi-CTA top-K armed with +``arm`` marks every entry of its output -2 before the dependent launch and writes every entry exactly once with a +value >= -1, and each loader thread of a selected-tile CTA polls its own entry (an atomic read: a plain or relaxed +load may return a stale copy for microseconds on the two-partition L2) and gathers its row as soon as it is there. +A row is served when its own top-K CTAs are done instead of when the last row of the grid is. +""" + +from __future__ import annotations + +import cuda.bindings.driver as cuda +import cutlass +import cutlass.cute as cute +import cutlass.experimental.cuda as xcuda +import cutlass.pipeline as pipeline +from cutlass import Boolean, Float32, Int32, Int64, Uint32 +from cutlass.cutlass_dsl import T, dsl_user_op +from cutlass.experimental import primitives as prims + +from . import large_batch_lib as L +from . import megakernel_lib as ML +from .config import DS_V4_FLASH as SPEC +from .config import DS_V4_FLASH_FP4 as SPEC_FP4 +from .config import SpecDsaConfig, require_built_for +from .large_batch import ( + HEADS, + LATENT, + LOG2_E, + NEG_FLT_MAX, + NSLICE, + PANEL1, + Q_SLICE_BYTES, + SLICE, + SLOT_BYTES, + TILE_N, + TM_O, + TM_SB, + _final_norm, + _grow, + _pack4_e4m3, + _pack_bf16x2, + _rescale_o, + _shfl_idx_i32, + _shfl_xor_f32, + _tma_gather4, + _tmem_st_p8, + _wait, +) + +TOPK = SPEC.topk +NTILES = (SPEC.window + SPEC.topk) // TILE_N # 5 +SLICE_BYTES_O = 16384 # one 128-column slice of the 64-head O partial in bf16 +# CTAs per row that are built and validated (see the module docstring). +SUPPORTED_CLUSTER_SIZES = (5,) +E4M3 = cutlass.Float8E4M3FN + + +@dsl_user_op +def _ld_atomic_i32(addr, *, loc=None, ip=None): + """Read a 32-bit word through an atomic (``or`` with 0, GPU scope): performed at the L2, never a stale copy.""" + return Int32( + ML._asm( + T.i32(), + [ML._v(addr, loc, ip)], + "atom.relaxed.gpu.global.or.b32 $0, [$1], 0;", + "=r,l", + loc, + ip, + ) + ) + + +class TailAttention: + """The tail attention kernel; ``compile_tail_attention`` compiles it. + + Args: + g: CTAs (the cluster) per row, one of ``SUPPORTED_CLUSTER_SIZES``; another value raises ValueError. + config: a spec of the DS-V4-Flash attention (default: DS-V4-Flash), with either indexer K dtype since the + kernel does not read the indexer; a config with another attention raises NotImplementedError. + pdl: launch with the programmatic dependent launch attribute (see the module docstring). + poll: poll the top-K entries instead of waiting for the top-K grid (needs ``pdl`` and a top-K kernel that marks + its entries, ``topk_multicta_op.run(arm=True)``; see the module docstring). + + The compiled function takes, in order: ``q_att`` uint8 [B, 64, 512], ``swa_pool`` and ``c_pool`` uint8 [rows, 512], + ``topk`` int32 [B, 512], ``kv_lens`` int32 [B], ``bt_swa`` / ``bt_c`` int32 [B, pages], ``sinks`` float32 [64], + ``out`` bf16 [B, 64, 512], the softmax scale and the number of rows B. + """ + + def __init__( + self, g: int, config: SpecDsaConfig | None = None, pdl: bool = False, poll: bool = False + ): + require_built_for( + config, SPEC_FP4 if config is not None and config.index_k_dtype == "fp4" else SPEC + ) + if g not in SUPPORTED_CLUSTER_SIZES: + raise ValueError( + f"cluster size {g} not supported (built and validated for {SUPPORTED_CLUSTER_SIZES})" + ) + if poll and not pdl: + raise ValueError( + "poll needs pdl (the kernel has to start before the top-K kernel is done)" + ) + self.g = g + self.pdl = pdl + self.poll = poll + # the output slices (one per owner CTA, ranks 0-3) are computed and sent in the order of the CTA rank (``_pv``) + self.rotate = g >= NSLICE + # with the programmatic launch the CTAs wait for the top-K kernel: they prefetch the block-table row meanwhile + self.prefetch_bt = pdl + self.base, self.extra = divmod(NTILES, g) + self.nkv = self.base + (1 if self.extra else 0) # most tiles of one CTA + self.no_max = -(-NSLICE // g) # most output slices of one CTA + self.owners = min(g, NSLICE) + self.threads = 288 # warps 0-3 loader, 4-7 softmax / combine, 8 MMA issue + # mbarrier slots (8 B each; all single-arrival except B_MASK) + self.B_Q = 0 # four Q slices loader -> MMA + self.B_KV = 4 # 4 slices per local tile loader -> MMA + self.B_SFULL = self.B_KV + 4 * self.nkv # two S buffers: QK done MMA -> softmax + self.B_PV = self.B_SFULL + 2 # PV done MMA -> softmax + self.B_PRDY = self.B_PV + 1 # P stored and O rescaled softmax -> MMA + self.B_MASK = self.B_PRDY + 1 # validity mask of a tile (4 arrivals) loader -> softmax + self.B_STAT = self.B_MASK + self.nkv # (max, sum) of every CTA peers -> owner + self.B_RX = self.B_STAT + 1 # partial O slices peers -> owner + self.B_PVS = self.B_RX + ( + g - 1 + ) # PV of one output slice done (slice-wise export) MMA -> softmax + self.nbar = self.B_PVS + NSLICE + + @cute.jit + def __call__( + self, + q_att: cute.Tensor, + swa_pool: cute.Tensor, + c_pool: cute.Tensor, + topk: cute.Tensor, + kv_lens: cute.Tensor, + bt_swa: cute.Tensor, + bt_c: cute.Tensor, + sinks: cute.Tensor, + out: cute.Tensor, + softmax_scale: Float32, + nrows: Int32, + stream: cuda.CUstream, + ): + tma_q = xcuda.create_tensor_map_tiled( + global_address=q_att.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, HEADS, q_att.shape[0]], + global_strides=[LATENT // 16, HEADS * LATENT // 16], + box_dims=[SLICE, HEADS, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_swa = xcuda.create_tensor_map_tiled( + global_address=swa_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, swa_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + tma_cmp = xcuda.create_tensor_map_tiled( + global_address=c_pool.iterator.toint(), + dtype=cutlass.Float8E4M3FN, + global_dims=[LATENT, c_pool.shape[0]], + global_strides=[LATENT // 16], + box_dims=[SLICE, 1], + swizzle=xcuda.TensorMapSwizzle.s128b, + ) + self.kernel( + tma_q, + tma_swa, + tma_cmp, + topk, + kv_lens, + bt_swa, + bt_c, + sinks, + out, + softmax_scale, + ).launch( + grid=(nrows * Int32(self.g), 1, 1), + block=(self.threads, 1, 1), + cluster=(self.g, 1, 1), + stream=stream, + min_blocks_per_mp=1, + use_pdl=self.pdl, + ) + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def _loader( + self, + tid, + row, + j0, + nt, + tma_q, + tma_swa, + tma_cmp, + topk, + kv_lens, + bt_swa, + bt_c, + q_base, + kv_base, + abar, + s_msk, + ): + wl = tid >> Int32(5) + lane = tid & Int32(31) + if tid == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(abar + Int32(self.B_Q + c), Q_SLICE_BYTES) + prims.cp_async_bulk_tensor_shared_cta_global( + q_base + Int32(c * Q_SLICE_BYTES), + tma_q.get_ptr(), + [Int32(c * SLICE), Int32(0), row], + abar + Int32(self.B_Q + c), + ) + mbs = Int32(cute.size(bt_swa, mode=[1])) + mbc = Int32(cute.size(bt_c, mode=[1])) + topk_base = topk.iterator.toint() + Int64(row) * Int64(TOPK * 4) + Int64(tid * Int32(4)) + t0 = Int32(0) + if j0 == Int32(0): + # the window tile does not depend on the top-K kernel: gathered before the wait; the block-table row of + # request ``row`` is row ``row`` (the specDSA contract) + pos = Int32(kv_lens[row]) - Int32(1) + grow = L.l2g_swa(tid, pos, row, bt_swa, mbs, Int32(0)) + vm = Int32(cute.arch.vote_ballot_sync(grow >= Int32(0))) + if lane == Int32(0): + s_msk[wl] = vm + prims.mbarrier_arrive(abar + Int32(self.B_MASK)) + self._gather( + kv_base, + abar + Int32(self.B_KV), + tma_swa, + tma_cmp, + Boolean(True), + _grow(grow), + wl, + lane, + ) + t0 = Int32(1) + if cutlass.const_expr(self.prefetch_bt): + # the selected tiles (CTAs 1-4 of the cluster) read random pages of this request's block-table row (32 KB): + # each CTA brings a quarter of its 128-byte lines into L2 while the top-K kernel finishes, so that the loads + # behind the wait hit L2 + if j0 != Int32(0): + nl = (mbc * Int32(4) + Int32(127)) // Int32(128) + qn = (nl + Int32(3)) // Int32(4) + li = (j0 - Int32(1)) * qn + tid + if tid < qn: + if li < nl: + ML.prefetch_l2_line( + bt_c.iterator.toint() + + Int64(row) * Int64(mbc) * Int64(4) + + Int64(li) * Int64(128) + ) + if cutlass.const_expr(not self.poll): + cute.arch.griddepcontrol_wait() + for t in cutlass.range(t0, nt, unroll=1): + jg = j0 + t + ta = topk_base + Int64((jg - Int32(1)) * Int32(TILE_N * 4)) + if cutlass.const_expr(self.poll): + # the entry is -2 until the top-K kernel writes it (a written entry is >= -1) + c = _ld_atomic_i32(ta) + while c == Int32(-2): + c = _ld_atomic_i32(ta) + else: + c = L.ld_cg_i32(ta) + grow = L.l2g_compressed(c, row, bt_c, mbc, Int32(0)) + vm = Int32(cute.arch.vote_ballot_sync(grow >= Int32(0))) + if lane == Int32(0): + s_msk[t * Int32(4) + wl] = vm + prims.mbarrier_arrive(abar + Int32(self.B_MASK) + t) + self._gather( + kv_base + t * Int32(4 * SLOT_BYTES), + abar + Int32(self.B_KV) + t * Int32(4), + tma_swa, + tma_cmp, + Boolean(False), + _grow(grow), + wl, + lane, + ) + + @cute.jit + def _gather(self, slot_base, mbar_base, tma_swa, tma_cmp, use_swa, gidx_t, wl, lane): + # slice by slice (all rows of slice 0 first): the MMA warp starts QK on a slice as soon as it lands + if wl == Int32(0): + if prims.elect_sync(): + for c in cutlass.range_constexpr(NSLICE): + prims.mbarrier_arrive_expect_tx(mbar_base + Int32(c), SLOT_BYTES) + dst0 = slot_base + wl * Int32(32 * SLICE) + rows = [] + for q in cutlass.range_constexpr(8): + for k in cutlass.range_constexpr(4): + rows.append(_shfl_idx_i32(gidx_t, Int32(4 * q + k))) + for c in cutlass.range_constexpr(NSLICE): + for q in cutlass.range_constexpr(8): + dst = dst0 + Int32(c * SLOT_BYTES + 4 * q * SLICE) + if use_swa: + _tma_gather4( + dst, + tma_swa.get_ptr(), + mbar_base + Int32(c), + Int32(c * SLICE), + rows[4 * q], + rows[4 * q + 1], + rows[4 * q + 2], + rows[4 * q + 3], + ) + else: + _tma_gather4( + dst, + tma_cmp.get_ptr(), + mbar_base + Int32(c), + Int32(c * SLICE), + rows[4 * q], + rows[4 * q + 1], + rows[4 * q + 2], + rows[4 * q + 3], + ) + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def _pv(self, abar, tp, tmem, kv_base, idesc_pv, rk): + # O += P(tp) V(tp) once the softmax warps have stored P and rescaled O. With ``rotate`` the slices are computed + # in the order rk, rk + 1, ... (mod 4) of the CTA rank rk: the first one is the CTA's own slice, the others go + # to different owners at any time. + _wait(abar + Int32(self.B_PRDY), tp & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if cutlass.const_expr(self.rotate): + if prims.elect_sync(): + s_addr = tmem + (tp & Int32(1)) * Int32(TM_SB) + for k in cutlass.range_constexpr(NSLICE): + v = (Int32(k) + rk) & Int32(NSLICE - 1) + vdesc = prims.Tcgen05SmemDesc.build( + kv_base + (tp * Int32(4) + v) * Int32(SLOT_BYTES), + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d_addr = ( + tmem + + Int32(TM_O) + + (v & Int32(1)) * Int32(128) + + (v >> Int32(1)) * Int32(PANEL1) + ) + a_addr = s_addr + Int32(TILE_N // 4) + (v >> Int32(1)) * Int32(PANEL1) + for kb in cutlass.range_constexpr(TILE_N // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(tp > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(abar + Int32(self.B_PVS) + v, group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(abar + Int32(self.B_PV), group=prims.CTAGroup.CTA_1) + elif prims.elect_sync(): + s_addr = tmem + (tp & Int32(1)) * Int32(TM_SB) + for v in cutlass.range_constexpr(NSLICE): + vdesc = prims.Tcgen05SmemDesc.build( + kv_base + (tp * Int32(4) + Int32(v)) * Int32(SLOT_BYTES), + leading_byte_offset=0, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + d_addr = tmem + Int32(TM_O + (v & 1) * 128 + (v >> 1) * PANEL1) + a_addr = s_addr + Int32(TILE_N // 4 + (v >> 1) * PANEL1) + for kb in cutlass.range_constexpr(TILE_N // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(tp > Int32(0)) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(d_addr, Float32), + prims.make_tmem_ptr(a_addr + Int32(8 * kb), E4M3), + vdesc.advance_start_address(kb * 32 * SLICE), + idesc_pv, + en, + ) + prims.tcgen05_commit(abar + Int32(self.B_PVS + v), group=prims.CTAGroup.CTA_1) + prims.tcgen05_commit(abar + Int32(self.B_PV), group=prims.CTAGroup.CTA_1) + + @cute.jit + def _mma(self, nt, abar, q_base, kv_base, tmem, rk): + idesc_qk = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, a_dtype=E4M3, b_dtype=E4M3, n_dim=TILE_N, m_dim=HEADS + ) + idesc_pv = prims.Tcgen05InstrDesc.build( + c_dtype=Float32, + a_dtype=E4M3, + b_dtype=E4M3, + a_major=0, + b_major=1, + n_dim=SLICE, + m_dim=HEADS, + ) + for t in cutlass.range(nt, unroll=1): + g4 = t * Int32(4) + s_addr = tmem + (t & Int32(1)) * Int32(TM_SB) + if t == Int32(0): + for c in cutlass.range_constexpr(NSLICE): + _wait(abar + Int32(self.B_Q + c), Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + for c in cutlass.range_constexpr(NSLICE): + # QK on slice c as soon as its KV rows have landed + _wait(abar + Int32(self.B_KV) + g4 + Int32(c), Int32(0)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + if prims.elect_sync(): + qdesc = prims.Tcgen05SmemDesc.build( + q_base + Int32(c * Q_SLICE_BYTES), + leading_byte_offset=Q_SLICE_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + kdesc = prims.Tcgen05SmemDesc.build( + kv_base + (g4 + Int32(c)) * Int32(SLOT_BYTES), + leading_byte_offset=SLOT_BYTES, + stride_byte_offset=1024, + layout=prims.Tcgen05SmemSwizzle.SWIZZLE_128B, + ) + for kb in cutlass.range_constexpr(SLICE // 32): + en = Boolean(True) + if cutlass.const_expr(kb == 0): + en = Boolean(c > 0) + prims.tcgen05_mma( + prims.Tcgen05MMAKind.F8F6F4, + prims.CTAGroup.CTA_1, + prims.make_tmem_ptr(s_addr, Float32), + qdesc.advance_start_address(kb * 32), + kdesc.advance_start_address(kb * 32), + idesc_qk, + en, + ) + if prims.elect_sync(): + prims.tcgen05_commit( + abar + Int32(self.B_SFULL) + (t & Int32(1)), group=prims.CTAGroup.CTA_1 + ) + if t >= Int32(1): + self._pv(abar, t - Int32(1), tmem, kv_base, idesc_pv, rk) + self._pv(abar, nt - Int32(1), tmem, kv_base, idesc_pv, rk) + + # ------------------------------------------------------------------------------------------------------------ + @cute.jit + def _softmax( + self, + rtid, + r, + nt, + tmem, + abar, + s_msk, + sink_ptr, + out_addr: Int64, + row, + scale_log2: Float32, + s_stat, + s_rx, + ): + wl = rtid >> Int32(5) + lane = rtid & Int32(31) + head = wl * Int32(16) + (lane & Int32(15)) + half = lane >> Int32(4) + lane_base = wl * Int32(32) << Int32(16) + sink = Float32((sink_ptr + head).load()) + Ls = scale_log2 + G = self.g + stat_a = Int32(s_stat.iterator.toint()) + rx_a = Int32(s_rx.iterator.toint()) + bar_stat_a = Int32((abar + Int32(self.B_STAT)).toint()) + bar_rx_a = Int32((abar + Int32(self.B_RX)).toint()) + # receive accounting of an owner: (max, sum) of the G CTAs and (G - 1) partial slices per owned slice + n_own = Int32(0) + for oi in cutlass.range_constexpr(self.no_max): + if r + Int32(oi * G) < Int32(NSLICE): + n_own = n_own + Int32(1) + if rtid == Int32(0): + if r < Int32(self.owners): + prims.mbarrier_arrive_expect_tx(abar + Int32(self.B_STAT), Int32(G * 512)) + for k in cutlass.range_constexpr(G - 1): + prims.mbarrier_arrive_expect_tx( + abar + Int32(self.B_RX + k), n_own * Int32(SLICE_BYTES_O) + ) + m_run = Float32(NEG_FLT_MAX) + l_run = Float32(0.0) + for t in cutlass.range(nt, unroll=1): + sb = t & Int32(1) + _wait(abar + Int32(self.B_MASK) + t, Int32(0)) + mk = Int32(s_msk[t * Int32(4) + half * Int32(2)]) + mk2 = Int32(s_msk[t * Int32(4) + half * Int32(2) + Int32(1)]) + _wait(abar + Int32(self.B_SFULL) + sb, t >> Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tsa = tmem + sb * Int32(TM_SB) + lane_base + s0 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa, Float32), + num=32, + offset=Int64(64), + ) + s1 = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(tsa + Int32(32), Float32), + num=32, + offset=Int64(64), + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + xs = [] + for ch in cutlass.range_constexpr(2): + for i in cutlass.range_constexpr(32): + x = Float32(s0[i]) + mword = mk + if cutlass.const_expr(ch == 1): + x = Float32(s1[i]) + mword = mk2 + if mword >> Int32(i) & Int32(1) == Int32(0): + x = Float32(-float("inf")) + xs.append(x) + old_max = m_run + mx0 = old_max + mx1 = Float32(NEG_FLT_MAX) + mx2 = Float32(NEG_FLT_MAX) + mx3 = Float32(NEG_FLT_MAX) + for i in cutlass.range_constexpr(0, 64, 4): + mx0 = cute.math.max(mx0, xs[i], ftz=True) + mx1 = cute.math.max(mx1, xs[i + 1], ftz=True) + mx2 = cute.math.max(mx2, xs[i + 2], ftz=True) + mx3 = cute.math.max(mx3, xs[i + 3], ftz=True) + lmax = cute.math.max( + cute.math.max(mx0, mx1, ftz=True), cute.math.max(mx2, mx3, ftz=True), ftz=True + ) + lmax = cute.math.max(lmax, _shfl_xor_f32(lmax, 16), ftz=True) + new_max = lmax + safe_max = new_max + if safe_max == Float32(NEG_FLT_MAX): + safe_max = Float32(0.0) + neg_scaled = -Ls * safe_max + bias = neg_scaled + Float32(8.8073549) + sm0 = Float32(0.0) + sm1 = Float32(0.0) + sm2 = Float32(0.0) + sm3 = Float32(0.0) + regs = [] + for pk in cutlass.range_constexpr(16): + x01 = cute.arch.fma_packed_f32x2( + (xs[4 * pk], xs[4 * pk + 1]), (Ls, Ls), (bias, bias), ftz=False, rnd="rn" + ) + x23 = cute.arch.fma_packed_f32x2( + (xs[4 * pk + 2], xs[4 * pk + 3]), (Ls, Ls), (bias, bias), ftz=False, rnd="rn" + ) + p0 = cute.math.exp2(x01[0], fastmath=True) + p1 = cute.math.exp2(x01[1], fastmath=True) + p2 = cute.math.exp2(x23[0], fastmath=True) + p3 = cute.math.exp2(x23[1], fastmath=True) + sm0, sm1 = cute.arch.add_packed_f32x2((sm0, sm1), (p0, p1), ftz=False, rnd="rn") + sm2, sm3 = cute.arch.add_packed_f32x2((sm2, sm3), (p2, p3), ftz=False, rnd="rn") + regs.append(_pack4_e4m3(p0, p1, p2, p3)) + local_sum = sm0 + sm1 + (sm2 + sm3) + p_addr = tsa + Int32(TILE_N // 4) + _tmem_st_p8(p_addr, regs[0:8]) + _tmem_st_p8(p_addr + Int32(8), regs[8:16]) + _tmem_st_p8(p_addr + Int32(PANEL1), regs[0:8]) + _tmem_st_p8(p_addr + Int32(PANEL1 + 8), regs[8:16]) + exp_scale = cute.math.exp2(Ls * (old_max - new_max), fastmath=True) + l_run = exp_scale * l_run + local_sum + m_run = new_max + if t > Int32(0): + # O is still being accumulated by PV(t - 1): wait before rescaling it. + _wait(abar + Int32(self.B_PV), t - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + ident = old_max == new_max + scale = Float32(1.0) + if not ident: + scale = exp_scale + skip_c = prims.vote_sync(4294967295, ident, prims.VoteSync.ALL) + if not skip_c: + _rescale_o(tmem, lane_base, scale) + prims.tcgen05_wait(prims.Tcgen05Wait.STORE) + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=4, number_of_threads=128) + if rtid == Int32(0): + prims.mbarrier_arrive(abar + Int32(self.B_PRDY)) + # ------------------------------------------------------------------------------------------------------ + # combine: (max, sum) to the owners (every CTA sends to every owner, itself included) + l_tot = l_run + _shfl_xor_f32(l_run, 16) + cute.arch.cluster_wait() + if half == Int32(0): + for d in cutlass.range_constexpr(self.owners): + rc = ML.mapa_u32(stat_a + (r * Int32(64) + head) * Int32(8), Int32(d)) + mc = ML.mapa_u32(bar_stat_a, Int32(d)) + ML.st_async_v2(rc, mc, L.u32_of_f32(m_run), L.u32_of_f32(l_tot)) + # partial O slices that another CTA owns: as soon as the PV MMAs of a slice have completed, its 64 heads x 128 + # columns (bf16) go from the registers into the owner's receive buffer (``st.async``), completing the owner's + # per-source mbarrier + if cutlass.const_expr(self.rotate): + # slices in the order r, r + 1, ... (mod 4), one slice per owner (ranks 0-3, no_max == 1): the CTA's own + # slice is not sent, the others go to one owner after the other, so that every owner receives from one + # CTA at a time + for k in cutlass.range_constexpr(NSLICE): + v = (Int32(k) + r) & Int32(NSLICE - 1) + if r != v: + _wait(abar + Int32(self.B_PVS) + v, nt - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + raws = [] + for hc in cutlass.range_constexpr(2): + o_addr = ( + tmem + + lane_base + + Int32(TM_O) + + (v & Int32(1)) * Int32(128) + + (v >> Int32(1)) * Int32(PANEL1) + + Int32(32 * hc) + ) + raws.append( + prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + words = [] + for hc in cutlass.range_constexpr(2): + o = raws[hc] + for pi in cutlass.range_constexpr(16): + words.append(_pack_bf16x2(Float32(o[2 * pi]), Float32(o[2 * pi + 1]))) + sidx = r - cutlass.select_(r > v, Int32(1), Int32(0)) + off = sidx * Int32(self.no_max) * Int32(SLICE_BYTES_O) + rc0 = ML.mapa_u32(rx_a + off + rtid * Int32(16), v) + mc = ML.mapa_u32(bar_rx_a + sidx * Int32(8), v) + for q in cutlass.range_constexpr(8): + ML.st_async_v4( + rc0 + Int32(q * 2048), + mc, + words[4 * q], + words[4 * q + 1], + words[4 * q + 2], + words[4 * q + 3], + ) + for v in cutlass.range_constexpr(0 if self.rotate else NSLICE): + ov = v % G + oi = v // G + if r != Int32(ov): + _wait(abar + Int32(self.B_PVS + v), nt - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + raws = [] + for hc in cutlass.range_constexpr(2): + o_addr = ( + tmem + lane_base + Int32(TM_O + v % 2 * 128 + v // 2 * PANEL1 + 32 * hc) + ) + raws.append( + prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + ) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + words = [] + for hc in cutlass.range_constexpr(2): + o = raws[hc] + for pi in cutlass.range_constexpr(16): + words.append(_pack_bf16x2(Float32(o[2 * pi]), Float32(o[2 * pi + 1]))) + sidx = r - cutlass.select_(r > Int32(ov), Int32(1), Int32(0)) + off = (sidx * Int32(self.no_max) + Int32(oi)) * Int32(SLICE_BYTES_O) + rc0 = ML.mapa_u32(rx_a + off + rtid * Int32(16), Int32(ov)) + mc = ML.mapa_u32(bar_rx_a + sidx * Int32(8), Int32(ov)) + for q in cutlass.range_constexpr(8): + ML.st_async_v4( + rc0 + Int32(q * 2048), + mc, + words[4 * q], + words[4 * q + 1], + words[4 * q + 2], + words[4 * q + 3], + ) + # owners: weights of the G partials (the (max, sum) pairs have arrived while the slices were sent) + wn_me = Float32(0.0) + wn = [] + if r < Int32(self.owners): + ML.wait_cl(bar_stat_a, Int32(0)) + ms = [] + ls = [] + for s in cutlass.range_constexpr(G): + sa = stat_a + (Int32(s * 64) + head) * Int32(8) + ms.append(L.f32_of_u32(Uint32(ML.lds_u32(sa)))) + ls.append(L.f32_of_u32(Uint32(ML.lds_u32(sa + Int32(4))))) + m_star = ms[0] + for s in cutlass.range_constexpr(1, G): + m_star = cute.math.max(m_star, ms[s], ftz=True) + ws = [] + for s in cutlass.range_constexpr(G): + ws.append(cute.math.exp2(Ls * (ms[s] - m_star), fastmath=True)) + l_star = ws[0] * ls[0] + for s in cutlass.range_constexpr(1, G): + l_star = l_star + ws[s] * ls[s] + norm = _final_norm(m_star, l_star, sink, scale_log2) + for s in cutlass.range_constexpr(G): + wn.append(ws[s] * norm) + wn_me = wn[0] + for s in cutlass.range_constexpr(1, G): + wn_me = cutlass.select_(r == Int32(s), wn[s], wn_me) + # owners: combine + if r < Int32(self.owners): + for oi in cutlass.range_constexpr(self.no_max): + vown = r + Int32(oi * G) + if vown < Int32(NSLICE): + _wait(abar + Int32(self.B_PVS) + vown, nt - Int32(1) & Int32(1)) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + own = [] + for hc in cutlass.range_constexpr(2): + o_addr = ( + tmem + + lane_base + + Int32(TM_O) + + (vown & Int32(1)) * Int32(128) + + (vown >> Int32(1)) * Int32(PANEL1) + + Int32(32 * hc) + ) + o = prims.tcgen05_ld( + prims.Tcgen05LdStShape.SHAPE_16X32BX2, + prims.make_tmem_ptr(o_addr, Float32), + num=32, + offset=Int64(64), + ) + own.append(o) + prims.tcgen05_wait(prims.Tcgen05Wait.LOAD) + acc = [] + for hc in cutlass.range_constexpr(2): + for i in cutlass.range_constexpr(32): + acc.append(wn_me * Float32(own[hc][i])) + for s in cutlass.range_constexpr(G): + if r != Int32(s): + slot = Int32(s) - cutlass.select_(Int32(s) > r, Int32(1), Int32(0)) + ML.wait_cl(bar_rx_a + slot * Int32(8), Int32(0)) + base = rx_a + (slot * Int32(self.no_max) + Int32(oi)) * Int32( + SLICE_BYTES_O + ) + for q in cutlass.range_constexpr(8): + xq = ML.lds_v4(base + Int32(q * 2048) + rtid * Int32(16)) + for e in cutlass.range_constexpr(4): + wd = Uint32(xq[e]) + acc[8 * q + 2 * e] = acc[8 * q + 2 * e] + wn[s] * L.f32_of_u32( + wd << Uint32(16) + ) + acc[8 * q + 2 * e + 1] = acc[8 * q + 2 * e + 1] + wn[ + s + ] * L.f32_of_u32(wd & Uint32(4294901760)) + ob = [] + for pi in cutlass.range_constexpr(32): + ob.append(_pack_bf16x2(acc[2 * pi], acc[2 * pi + 1])) + rowb = ( + out_addr + + Int64(row) * Int64(HEADS * LATENT * 2) + + Int64( + (head * Int32(LATENT) + vown * Int32(SLICE) + half * Int32(64)) + * Int32(2) + ) + ) + for ch in cutlass.range_constexpr(8): + ML.st_g_v4( + rowb + Int64(ch * 16), + ob[4 * ch], + ob[4 * ch + 1], + ob[4 * ch + 2], + ob[4 * ch + 3], + ) + + # ------------------------------------------------------------------------------------------------------------ + @cute.kernel + def kernel( + self, + tma_q: cutlass.GridConstant[xcuda.TensorMap], + tma_swa: cutlass.GridConstant[xcuda.TensorMap], + tma_cmp: cutlass.GridConstant[xcuda.TensorMap], + topk: cute.Tensor, + kv_lens: cute.Tensor, + bt_swa: cute.Tensor, + bt_c: cute.Tensor, + sinks: cute.Tensor, + out: cute.Tensor, + softmax_scale: Float32, + ): + tid, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + G = self.g + row = bidx // Int32(G) + r = bidx - row * Int32(G) # rank in the cluster + smem = cutlass.utils.SmemAllocator() + sQ = smem.allocate_tensor( + cutlass.Float8E4M3FN, cute.make_layout(NSLICE * Q_SLICE_BYTES), byte_alignment=1024 + ) + sKV = smem.allocate_tensor( + cutlass.Float8E4M3FN, cute.make_layout(self.nkv * 4 * SLOT_BYTES), byte_alignment=1024 + ) + sRX = smem.allocate_tensor( + cutlass.Uint8, + cute.make_layout((G - 1) * self.no_max * 8 * 2048), + byte_alignment=1024, + ) + sBar = smem.allocate_tensor(Int64, cute.make_layout(32), byte_alignment=16) + sMask = smem.allocate_tensor(Int32, cute.make_layout(16), byte_alignment=16) + sStat = smem.allocate_tensor(Float32, cute.make_layout(G * 128), byte_alignment=16) + sTmem = smem.allocate_tensor(Int32, cute.make_layout(1), byte_alignment=16) + abar = sBar.iterator.raw_ptr() + if tid < Int32(self.nbar): + cnt = Int32(1) + if (tid >= Int32(self.B_MASK)) & (tid < Int32(self.B_MASK + self.nkv)): + cnt = Int32(4) + ML.mbar_init(Int32((abar + tid).toint()), cnt) + ML.fence_mbar_init_cluster() + cute.arch.cluster_arrive_relaxed() + tmem_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=self.threads) + tmem = cutlass.utils.TmemAllocator( + sTmem.iterator, barrier_for_retrieve=tmem_barrier, allocator_warp_id=0, is_two_cta=False + ) + tmem.allocate(512) + tmem.wait_for_alloc() + tmem_ptr = tmem.retrieve_ptr(Float32) + tmem_addr = cute.arch.load(sTmem.iterator, Int32, sem="relaxed", scope="cta") + q_base = sQ.iterator.raw_ptr() + kv_base = sKV.iterator.raw_ptr() + j0 = r * Int32(self.base) + cutlass.min(r, Int32(self.extra)) + nt = Int32(self.base) + cutlass.select_(r < Int32(self.extra), Int32(1), Int32(0)) + if tid < Int32(128): + self._loader( + tid, + row, + j0, + nt, + tma_q, + tma_swa, + tma_cmp, + topk, + kv_lens, + bt_swa, + bt_c, + q_base, + kv_base, + abar, + sMask, + ) + elif tid < Int32(256): + rtid = tid - Int32(128) + self._softmax( + rtid, + r, + nt, + tmem_addr, + abar, + sMask, + sinks.iterator.raw_ptr(), + out.iterator.toint(), + row, + softmax_scale * Float32(LOG2_E), + sStat, + sRX, + ) + else: + self._mma(nt, abar, q_base, kv_base, tmem_addr, r) + if tid < Int32(128) or tid >= Int32(256): + # the softmax warps waited for the start barrier before their first remote operation; the others do it now + # (one wait per arrive) + cute.arch.cluster_wait() + cute.arch.fence_view_async_tmem_load() + prims.tcgen05_fence(prims.Tcgen05Fence.BEFORE_THREAD_SYNC) + cute.arch.barrier(barrier_id=3, number_of_threads=self.threads) + prims.tcgen05_fence(prims.Tcgen05Fence.AFTER_THREAD_SYNC) + tmem.relinquish_alloc_permit() + tmem.free(tmem_ptr) + + +def compile_tail_attention(tail: TailAttention): + rt = cute.runtime + qa_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + sp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + cp_fake = rt.make_fake_compact_tensor( + cutlass.Uint8, (cute.sym_int64(), 512), stride_order=(1, 0), assumed_align=16 + ) + sb = cute.sym_int() + tk_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, TOPK), stride_order=(1, 0)) + kvl_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb,), stride_order=(0,)) + bts_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, cute.sym_int()), stride_order=(1, 0)) + btc_fake = rt.make_fake_compact_tensor(cutlass.Int32, (sb, cute.sym_int()), stride_order=(1, 0)) + sk_fake = rt.make_fake_compact_tensor( + cutlass.Float32, (64,), stride_order=(0,), assumed_align=16 + ) + ou_fake = rt.make_fake_compact_tensor( + cutlass.BFloat16, (sb, 64, 512), stride_order=(2, 1, 0), assumed_align=16 + ) + stream = rt.make_fake_stream(use_tvm_ffi_env_stream=True) + return cute.compile( + tail, + qa_fake, + sp_fake, + cp_fake, + tk_fake, + kvl_fake, + bts_fake, + btc_fake, + sk_fake, + ou_fake, + Float32(1.0), + Int32(1), + stream, + options="--enable-tvm-ffi --generate-line-info", + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_op.py new file mode 100644 index 000000000000..0c1fd06e5db0 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/tail_op.py @@ -0,0 +1,403 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA tail attention, host side: the multi-CTA sparse MLA (K4') that replaces the K3 (local-to-global mapping) + +K4 (sparse MLA) + K4b (reduction) kernels of the unfused decode chain behind any exact top-K kernel, and ``run_hybrid`` +(the caller's indexer logits kernel and top-K kernel, then K4'). The top-K stage of ``run_hybrid`` can be the multi-CTA +exact top-K of ``topk_multicta_op`` instead of the caller's kernel (``topk_fn=None``): it is the faster stage behind the +same logits kernel when every row has 16,384 or more positions (``topk_multicta_op.is_profitable``). + +``run_attention`` takes the exact top-512 selection (``topk`` [B, 512] int32, local compressed positions in no +particular order, -1 for an unused entry) and writes ``out`` [B, 64 * 512] bf16 like ``AttentionTail`` of the +large-batch kernels does. One cluster of 5 CTAs serves a row, up to 26 rows (the clusters of 5 that a B200 holds at +once at one CTA per SM). The launch is a plain stream-ordered launch, or, with ``pdl=True``, a programmatic dependent +launch: behind the multi-CTA top-K of ``topk_multicta_op`` (which triggers the launch after its stream phase, +``run(trigger=True)``) the CTAs of the tail attention start while that kernel ranks the crossing bin: 0.5 us less +per hybrid step on average over 9 to 24 rows (B200, nsys: 0.0 to 1.4 us at 15 of the 16 sizes, +0.15 us at one); +behind a top-K kernel that never triggers early (the production one) the attribute only costs 0.7 to 0.8 us, so +``pdl`` stays off there. ``run_hybrid`` uses it by default up to ``PDL_MAX_BATCH`` rows (``default_pdl``). + +With ``poll=True`` (the default of ``run_hybrid`` up to ``POLL_MAX_BATCH`` rows, ``default_poll``) the tail attention +does not wait for the end of the top-K grid either: the multi-CTA top-K marks the 512 entries of its output "not +written yet" at its start (``topk_multicta_op.run(trigger=True, arm=True)``) and writes each one once, and every +loader thread of a selected tile reads its entry (an atomic read) until it is written. A row is served when its own +top-K cluster is done and not when the slowest row of the batch is, and the 0.6 to 0.8 us between the last CTA of the +top-K and the release of the wait go: 0.47 us less per hybrid step on average over 5 to 24 rows (B200, nsys, 1M-token +captures: 0.0 to 1.1 us per size; at 24 rows it is flat, within +-0.3 us per pass, and off); the results are the same +bit for bit. Polling is only correct behind that top-K kernel on the same ``topk`` tensor: any other writer leaves the +kernel waiting for entries that never change (or reading stale ones). + +The kernel reads neither the indexer nor its K cache, so it is the same for the specs with an FP8 and an MXFP4 indexer +K cache: one compile per device serves both, and ``config`` (default: DS-V4-Flash) only has to be a supported spec. + +Contract: ``q_att`` float8_e4m3fn [B, 64, 512] (any shape with that many elements); ``swa_pool`` / ``c_pool`` +float8_e4m3fn [..., 512] rows (128 / 32 rows per page); ``bt_swa`` / ``bt_c`` contiguous int32 [B, pages]; ``kv_lens`` +int32 [B] on the device (the window is the last min(128, kv_len) positions); ``sinks`` float32 [64]; ``out`` bfloat16 +with B * 64 * 512 elements; all of them on one CUDA device. Row b of the batch is request b (the block tables are +indexed by the row): the specDSA operators have the same contract. ``out`` must not alias an input. +""" + +from __future__ import annotations + +import threading + +import torch + +from . import topk_multicta_op +from .config import SpecDsaConfig, check_device, supported_spec + +__all__ = [ + "PDL_MAX_BATCH", + "POLL_MAX_BATCH", + "TAIL_MAX_BATCH", + "default_pdl", + "default_poll", + "is_batch_size_supported", + "is_supported", + "precompile", + "run_attention", + "run_hybrid", + "tail_cluster_size", +] + +# Largest batch size for which ``run_hybrid`` launches the tail attention programmatically by default: its clusters +# start while the multi-CTA top-K ranks its crossing bin and hide their prologue (nsys, 1M-token captures: 0.5 to 1.8 us +# at 9 to 24 rows). At 25 and 26 rows the 26 clusters that fit one wave are all but full: the early launch costs 1.3 us +# at 25 rows and 2.9 us at 26 rows (nsys: plain 97.9 and 102.7 us, programmatic 99.2 and 105.6 us), the plain launches +# are used. +PDL_MAX_BATCH = 24 + +# Largest batch size for which ``run_hybrid`` also polls the entries of the multi-CTA top-K by default (``poll``): above +# it the clusters of the two kernels are far over one wave (120 + 120 CTAs at 24 rows on 148 SMs), the tail attention +# starts as the top-K CTAs exit and the marks of the protocol cost what the early start of the first rows wins (nsys, +# 1M-token captures, 3 to 8 passes: -1.1 to 0.0 us per size at 5 to 23 rows; flat at 24: mean -0.02 us, -0.4 to +0.3 +# per pass). +POLL_MAX_BATCH = 23 +assert POLL_MAX_BATCH <= PDL_MAX_BATCH + +# (largest batch size, CTAs per row): the co-resident clusters of a 148-SM B200 at one CTA per SM (measured) are 26 +# clusters of 5. Clusters of 4 / 3 would fit 33 / 45 rows but win nothing over the large-batch kernels there and leave +# only 0.5 to 0.8 % of the numerical headroom: not offered. +_CLUSTER_LIMITS = ((26, 5),) +TAIL_MAX_BATCH = _CLUSTER_LIMITS[-1][0] + +_lock = threading.Lock() +_compiled: dict[tuple, object] = {} + + +def default_pdl(batch_size: int) -> bool: + """Whether ``run_hybrid`` launches the tail attention programmatically by default (with the multi-CTA top-K) for + ``batch_size`` rows: up to ``PDL_MAX_BATCH``. Precompile both kernels with this value + (``precompile(..., pdl=default_pdl(b), poll=default_poll(b))``, + ``topk_multicta_op.precompile(..., trigger=default_pdl(b), arm=default_poll(b))``) before a CUDA-graph capture of + ``run_hybrid`` with the default.""" + return batch_size <= PDL_MAX_BATCH + + +def default_poll(batch_size: int) -> bool: + """Whether ``run_hybrid`` polls the entries of the multi-CTA top-K by default (``poll``, behind the armed top-K) + for ``batch_size`` rows: up to ``POLL_MAX_BATCH``. Precompile both kernels with this value + (``precompile(..., pdl=default_pdl(b), poll=default_poll(b))``, + ``topk_multicta_op.precompile(..., trigger=default_pdl(b), arm=default_poll(b))``) before a CUDA-graph capture of + ``run_hybrid`` with the default.""" + return batch_size <= POLL_MAX_BATCH + + +def tail_cluster_size(batch_size: int) -> int | None: + """CTAs per row of the tail attention for ``batch_size`` rows, None when the batch is above ``TAIL_MAX_BATCH``.""" + for max_batch, g in _CLUSTER_LIMITS: + if 1 <= batch_size <= max_batch: + return g + return None + + +def _cluster_size(batch_size: int) -> int: + g = tail_cluster_size(batch_size) + if g is None: + raise ValueError(f"batch size {batch_size} not in [1, {TAIL_MAX_BATCH}]") + return g + + +def is_batch_size_supported(batch_size: int) -> tuple[bool, str]: + """Whether the tail attention serves ``batch_size`` rows (1 to ``TAIL_MAX_BATCH``), and why not if it does not.""" + if tail_cluster_size(batch_size) is None: + return False, f"batch size {batch_size} not in [1, {TAIL_MAX_BATCH}]" + return True, "" + + +def is_supported( + device: torch.device | None = None, config: SpecDsaConfig | None = None +) -> tuple[bool, str]: + """Whether the tail attention serves ``config`` (default: DS-V4-Flash) on ``device``, and why not if it does not. + + That takes a supported spec (either indexer K dtype), CuTe DSL installed and SM100 with all 148 SMs (one CTA per + SM, clusters of 5). The batch size is checked by ``is_batch_size_supported``. + """ + try: + supported_spec(config) + except NotImplementedError as e: + return False, str(e) + return check_device(device) + + +def _device_index(device: torch.device) -> int: + device = torch.device(device) + return device.index if device.index is not None else torch.cuda.current_device() + + +def _fn(device: torch.device, g: int, pdl: bool = False, poll: bool = False): + from . import tail_attention as TA + + key = (_device_index(device), g, pdl, poll) + with _lock: + if key not in _compiled: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "spec_dsa tail attention: compile (precompile) before CUDA-graph capture" + ) + _compiled[key] = TA.compile_tail_attention(TA.TailAttention(g, pdl=pdl, poll=poll)) + return _compiled[key] + + +def precompile( + device: torch.device, + batch_size: int, + config: SpecDsaConfig | None = None, + pdl: bool = False, + poll: bool = False, +) -> None: + """Compile the tail attention kernel of ``batch_size`` rows on ``device``. + + The compiled kernel serves every batch size with the same cluster size and both indexer K dtypes; the launch + variant (``pdl``, ``poll``) is part of the compile. Must run outside CUDA-graph capture; ``run_attention`` compiles + on first use otherwise. + """ + supported_spec(config) + _fn(device, _cluster_size(batch_size), pdl, poll) + + +def _require(ok: bool, what: str, t: torch.Tensor) -> None: + if not ok: + raise ValueError(f"{what}, got {t.dtype} {tuple(t.shape)} on {t.device}") + + +def _check_arguments(config, b, topk, q_att, swa_pool, bt_swa, c_pool, bt_c, kv_lens, sinks, out): + """Raise ValueError for an argument the kernel cannot take (before any device work).""" + heads, dim = config.attn_heads, config.kv_dim + _require( + topk.dtype == torch.int32 + and tuple(topk.shape) == (b, config.topk) + and topk.is_contiguous(), + f"topk must be a contiguous int32 [B, {config.topk}] tensor", + topk, + ) + _require( + q_att.element_size() == 1 and q_att.numel() == b * heads * dim and q_att.is_contiguous(), + f"q_att must be a contiguous FP8 tensor with {b} x {heads} x {dim} elements", + q_att, + ) + for name, pool in (("swa_pool", swa_pool), ("c_pool", c_pool)): + _require( + pool.element_size() == 1 + and pool.dim() >= 2 + and pool.shape[-1] == dim + and pool.is_contiguous(), + f"{name} must be a contiguous FP8 tensor with {dim}-byte rows", + pool, + ) + for name, table in (("bt_swa", bt_swa), ("bt_c", bt_c)): + _require( + table.dtype == torch.int32 + and table.dim() == 2 + and table.shape[0] >= b + and table.is_contiguous(), + f"{name} must be a contiguous int32 [B, pages] tensor with B >= {b}", + table, + ) + _require( + kv_lens.dtype == torch.int32 and kv_lens.numel() == b and kv_lens.is_contiguous(), + f"kv_lens must be a contiguous int32 tensor with {b} elements", + kv_lens, + ) + _require( + sinks.dtype == torch.float32 and sinks.numel() == heads and sinks.is_contiguous(), + f"sinks must be a contiguous float32 tensor with {heads} elements", + sinks, + ) + _require( + out.dtype == torch.bfloat16 and out.numel() == b * heads * dim and out.is_contiguous(), + f"out must be a contiguous bfloat16 tensor with {b} x {heads} x {dim} elements", + out, + ) + if q_att.device.type != "cuda": + raise ValueError(f"the tensors must be CUDA tensors, got q_att on {q_att.device}") + named = ( + ("topk", topk), + ("swa_pool", swa_pool), + ("bt_swa", bt_swa), + ("c_pool", c_pool), + ("bt_c", bt_c), + ("kv_lens", kv_lens), + ("sinks", sinks), + ("out", out), + ) + for name, t in named: + if t.device != q_att.device: + raise ValueError( + f"{name} must be on the device of q_att ({q_att.device}), got {t.device}" + ) + + +def run_attention( + topk: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + kv_lens: torch.Tensor, + sinks: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + config: SpecDsaConfig | None = None, + pdl: bool = False, + poll: bool = False, +) -> None: + """Launch the tail attention on the current stream (see the module docstring for the contract). + + Args: + topk: int32 [B, 512], the exact top-512 selection of each row: local compressed positions in no particular + order, -1 for an unused entry. B = ``topk.shape[0]`` must be in [1, ``TAIL_MAX_BATCH``]. + q_att: float8_e4m3fn [B, 64, 512] (or [B, 64 * 512]), attention queries. + swa_pool: float8_e4m3fn [..., 512], sliding-window KV rows (128 rows per page); bt_swa: int32 [B, pages]. + c_pool: float8_e4m3fn [..., 512], compressed KV rows (32 rows per page); bt_c: int32 [B, pages]. + kv_lens: int32 [B] on the device, uncompressed length of each row; the window is its last min(128, kv_len) + positions. + sinks: float32 [64], per-head attention sink. + out: bfloat16 [B, 64 * 512] output. + softmax_scale: attention softmax scale (default: ``1 / sqrt(kv_dim)`` of the spec). + config: the spec (default: DS-V4-Flash); either indexer K dtype: the launch is the same. + pdl: launch with the programmatic dependent launch attribute: only behind a kernel that triggers the dependent + launch early (``topk_multicta_op.run(trigger=True)``), see the module docstring. + poll: poll the entries of ``topk`` instead of waiting for the top-K grid (needs ``pdl``): only behind + ``topk_multicta_op.run(trigger=True, arm=True)`` on the same ``topk`` tensor, which marks every entry -2 and + writes each one once; any other writer would leave the kernel waiting for entries that never change. + """ + config = supported_spec(config) + if poll and not pdl: + raise ValueError("poll needs pdl") + if topk.dim() != 2: + raise ValueError( + f"topk must be a contiguous int32 [B, {config.topk}] tensor, got {tuple(topk.shape)}" + ) + b = int(topk.shape[0]) + g = _cluster_size(b) + _check_arguments(config, b, topk, q_att, swa_pool, bt_swa, c_pool, bt_c, kv_lens, sinks, out) + if softmax_scale is None: + softmax_scale = config.default_softmax_scale + fn = _fn(q_att.device, g, pdl, poll) + fn( + q_att.view(torch.uint8).view(b, config.attn_heads, config.kv_dim), + swa_pool.view(torch.uint8).view(-1, config.kv_dim), + c_pool.view(torch.uint8).view(-1, config.kv_dim), + topk, + kv_lens, + bt_swa[:b], + bt_c[:b], + sinks.reshape(-1), + out.view(b, config.attn_heads, config.kv_dim), + softmax_scale, + b, + ) + + +def run_hybrid( + k1_logits_fn, + topk_fn, + topk: torch.Tensor, + q_att: torch.Tensor, + swa_pool: torch.Tensor, + bt_swa: torch.Tensor, + c_pool: torch.Tensor, + bt_c: torch.Tensor, + kv_lens: torch.Tensor, + sinks: torch.Tensor, + out: torch.Tensor, + softmax_scale: float | None = None, + *, + config: SpecDsaConfig | None = None, + ctx_lens: torch.Tensor | None = None, + pdl: bool | None = None, + poll: bool | None = None, +) -> None: + """The decode chain with K3 + K4 + K4b replaced: ``k1_logits_fn()``, the top-K stage (fills ``topk``), then K4'. + + The top-K stage is ``topk_fn(logits)``, or, when ``topk_fn`` is None, the multi-CTA exact top-K of + ``topk_multicta_op`` on the logits with ``ctx_lens`` (int32 [B] on the device: the lengths the logits kernel was + given; required then, ignored otherwise). That kernel is exact for every row length but the faster one only when + every row has ``topk_multicta_op.MIN_PROFITABLE_ROW_LEN`` positions or more (``topk_multicta_op.is_profitable``: + ask it with the host lengths of the step); keep the production top-K as ``topk_fn`` for the other batches. Compile + both kernels (``precompile`` here and ``topk_multicta_op.precompile``) before a CUDA-graph capture. + + ``pdl`` (default: on with the multi-CTA top-K up to ``PDL_MAX_BATCH`` rows, off with a ``topk_fn`` and above): the + multi-CTA top-K triggers the dependent launch after its stream phase and the tail attention is launched with the + programmatic attribute, so that its prologue overlaps the end of the top-K kernel (the results are the same). + Precompile both kernels with the same value (``topk_multicta_op.precompile(..., trigger=pdl)``, + ``precompile(..., pdl=pdl)``; ``default_pdl(batch_size)`` is the default) before a CUDA-graph capture. + ``pdl=True`` with a ``topk_fn`` raises ValueError. + + ``poll`` (default: on with the multi-CTA top-K up to ``POLL_MAX_BATCH`` rows, ``default_poll``): the multi-CTA + top-K marks the entries of ``topk`` -2 at its start (``arm``) and the tail attention does not wait for the + completion of the top-K grid but polls its entries, so that a row is served as soon as its own top-K CTAs are done + (the results are the same); precompile both kernels with the same value + (``topk_multicta_op.precompile(..., arm=poll)``, ``precompile(..., poll=poll)``) before a CUDA-graph capture. + ``poll=True`` needs ``pdl`` and the multi-CTA top-K (``topk_fn=None``). + + The arguments of the tail attention and ``config`` are those of ``run_attention``. + """ + if topk_fn is None and ctx_lens is None: + raise ValueError("run_hybrid without a topk_fn needs ctx_lens (int32 [B] on the device)") + if pdl and topk_fn is not None: + raise ValueError( + "pdl needs the multi-CTA top-K (topk_fn=None): a top-K kernel that never triggers early only loses time" + ) + if pdl is None: + pdl = topk_fn is None and default_pdl(int(topk.shape[0])) + if poll and topk_fn is not None: + raise ValueError("poll needs the multi-CTA top-K (topk_fn=None)") + if poll is None: + poll = bool(pdl) and topk_fn is None and default_poll(int(topk.shape[0])) + if poll and not pdl: + raise ValueError("poll needs pdl") + logits = k1_logits_fn() + if topk_fn is None: + topk_multicta_op.run(logits, topk, ctx_lens, config=config, trigger=pdl, arm=poll) + else: + topk_fn(logits) + run_attention( + topk, + q_att, + swa_pool, + bt_swa, + c_pool, + bt_c, + kv_lens, + sinks, + out, + softmax_scale, + config=config, + pdl=pdl, + poll=poll, + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta.py new file mode 100644 index 000000000000..798b0a6ec33e --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta.py @@ -0,0 +1,1173 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA multi-CTA exact top-512: the top-K stage of the tail-attention hybrid, one thread-block cluster per row. + +Selects the exact top-512 of every row of the fp32 logits that the indexer kernel writes (``logits`` [B, npad], row +``r`` valid up to ``ctx[r]``) and writes the positions to ``out`` [B, 512] int32: local positions of the row in no +particular order and, for a row of at most 512 positions, ``0 .. n - 1`` followed by -1 (what the production top-K +writes). The selection is exact for every input: its values are the 512 largest of the row (the multiset +``torch.topk`` returns); which of the positions that share the 512th value are taken is not specified (the fast path +takes the smaller positions, the radix fallback the ones its CTAs reach first). NaN logits are outside the contract +(the indexer kernel never writes one): they rank by their bit pattern. + +A cluster of ``g`` CTAs (grid ``g * B``, 512 threads each, no wait between clusters) serves a row, which is read once +with addresses that do not depend on the row length: + +1. Sample windows (8 floats at stride 896, rows longer than 8192 positions only) give the threshold T1, the value + whose rank in the row is expected to be 3.5 x 512, and the span [T1, sample max] that defines 1024 candidate bins. + The CTA's 512-byte chunks of the row (interleaved over the cluster) stream through a cp.async ring in shared memory + while the threshold is computed. +2. Every value >= T1 goes (position, value) to a warp-private candidate list of its CTA, and the lists are counted per + bin. +3. One all-gather of the per-CTA suffix-count tables (u16 x 1024, a bulk copy through distributed shared memory + completing an mbarrier) tells every CTA the bin B* that holds the 512th value, the number of candidates above it + and its own output offset. +4. Every CTA writes its candidates above B* straight to ``out``; the members of B* go to the lead CTA of the row, + which ranks them by (value desc, position asc) and writes the missing ones. + +Every CTA of the cluster checks the certificate of this fast path from the same all-gathered data: at least 512 +candidates, no list overflow, at most 512 members in B*. When it fails (the sample threshold was too high, massive +ties) the whole cluster runs an exact 4-level radix select over the row instead (8-bit digits, one 256-bin all-gather +per level, a write pass with a tie quota per CTA). A row of at most 8192 positions has no sample: every value is a +candidate and the same certificate decides (a row of at most 512 positions is the identity followed by -1). + +A CTA holds ~170 KB of shared memory, so the clusters of a launch have to co-reside in one wave on the 148 SMs +(clusters of 8 / 6 / 5 / 4 CTAs: 15 / 22 / 26 / 33 per B200); ``topk_multicta_op`` picks ``g`` from the batch size (1 +to 26 rows). The launch is a plain stream-ordered launch. With ``trigger`` every CTA lets the dependent grid launch +(``griddepcontrol.launch_dependents``) as soon as its stream phase is done, which is what the tail attention launched +with the programmatic attribute (``tail_op``, ``pdl``) needs to run its prologue while this kernel ranks the crossing +bin; the production kernels around it never trigger a dependent launch early. + +With ``arm`` the CTA 0 of every row marks the 512 entries of the row's output -2 at its start (a written entry is +>= -1; every path writes every entry exactly once): the tail attention launched behind it with ``poll`` +(``tail_attention``) reads its entries as soon as they exist instead of waiting for the completion of this grid. +The order that makes this safe: the CTA 0 arrives at the cluster barrier with release semantics right before its own +trigger, so its marks are in memory before the dependent grid can start, and the other CTAs store entries only after +the cluster wait that follows that arrival (no mark can land after an entry); the other CTAs arrive early and relaxed, +as without ``arm``. A short row (no stream phase) arrives with release right after the marks. +""" + +from __future__ import annotations + +import cuda.bindings.driver as cuda_driver +import cutlass +import cutlass.cute as cute +from cutlass import Float32, Int32, Int64, Uint32, Uint64 +from cutlass.cutlass_dsl import T, dsl_user_op + +from . import megakernel_lib as L +from .config import DS_V4_FLASH as SPEC + +__all__ = ["SUPPORTED_CLUSTER_SIZES", "TopkMultiCta", "compile_topk_multicta"] + +K_TOP = SPEC.topk # 512 +MAX_LEN = SPEC.max_index_len # 262144: longest row +# CTAs per row that are built and validated (see ``topk_multicta_op`` for the batch sizes they serve). +SUPPORTED_CLUSTER_SIZES = (4, 5, 6, 8) + +NT = 512 # threads per CTA +NW = NT // 32 # warps per CTA +U = 4 # 512-byte chunks per warp in one ring batch +NBUF = 3 # ring slots (batches in flight) +CH = 128 # floats per chunk (512 B, one warp-wide float4 load) +SMP_MAX = 292 # sample windows at MAX_LEN (the production top-K samples n / 896) +WST = 896 # window stride (floats): the sample windows are at j * WST whatever the row length +AIM = 1792 # expected number of candidates (>= T1) of a row, 3.5 x K_TOP +NBIN = 1024 # candidate bins +BPT = NBIN // NT # bins per thread +NSB = 2048 # sample bins (key >> 21) +LST_BYTES = 32768 # warp-private candidate lists of the CTA +LCAPW = LST_BYTES // 8 // NW # candidates one warp can hold +MCAP = 512 # crossing-bin members ranked by counting (XCAP entries are buffered) +XCAP = 1024 # crossing-bin member buffer (lead CTA) +NEG_INF = float("-inf") +SLOT = 2064 # R1 message bytes per source CTA (2048 of u16 suffix counts + 16 header) + +# shared memory layout (bytes) +OFF_BAR = 0 +OFF_MISC = 64 # 256 ints +M_BSTAR, M_SMAX, M_OVF, M_T1KEY, M_HAVE = 1, 2, 3, 8, 9 +# fallback: running counters, crossing digit, strictly-above count, per-source above counts (10..17) +M_CABOVE, M_CTIE, M_FDIG, M_FABOVE, M_FA = 4, 5, 6, 7, 10 +M_WCNT, M_WA, M_WM, M_WTOT = 32, 64, 96, 128 # per-warp counters (32 words each) +OFF_SHIST = OFF_MISC + 1024 # 2048 sample bins + 32 pad words +OFF_HIST = OFF_SHIST + (NSB + 32) * 4 +OFF_LST = OFF_HIST + NBIN * 4 # warp-private lists +OFF_RX = OFF_LST + LST_BYTES +OFF_XIN = OFF_RX + 8 * SLOT +OFF_RING = OFF_XIN + XCAP * 8 +ARENA_BYTES = OFF_RING + NBUF * U * NW * 512 + 1024 +assert ARENA_BYTES <= 227 * 1024 + + +@dsl_user_op +def lds_u64(saddr, *, loc=None, ip=None): + return Uint64( + L._asm(T.i64(), [L._v(saddr, loc, ip)], "ld.shared.u64 $0, [$1];", "=l,r", loc, ip) + ) + + +@dsl_user_op +def sts_u64(saddr, val, *, loc=None, ip=None): + L._asm( + None, [L._v(saddr, loc, ip), L._v(val, loc, ip)], "st.shared.u64 [$0], $1;", "r,l", loc, ip + ) + + +@dsl_user_op +def atom_add_sh(saddr, val, *, loc=None, ip=None): + return Int32( + L._asm( + T.i32(), + [L._v(saddr, loc, ip), L._v(val, loc, ip)], + "atom.shared.add.u32 $0, [$1], $2;", + "=r,r,r", + loc, + ip, + ) + ) + + +@dsl_user_op +def red_add_sh(saddr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(saddr, loc, ip), L._v(val, loc, ip)], + "red.shared.add.u32 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def red_max_sh(saddr, val, *, loc=None, ip=None): + L._asm( + None, + [L._v(saddr, loc, ip), L._v(val, loc, ip)], + "red.shared.max.u32 [$0], $1;", + "r,r", + loc, + ip, + ) + + +@dsl_user_op +def lds_v2(saddr, *, loc=None, ip=None): + from cutlass._mlir.dialects import llvm + + st = llvm.StructType.get_literal([T.i32(), T.i32()]) + r = L._asm(st, [L._v(saddr, loc, ip)], "ld.shared.v2.u32 {$0, $1}, [$2];", "=r,=r,r", loc, ip) + return tuple(Int32(llvm.extractvalue(T.i32(), r, [i], loc=loc, ip=ip)) for i in range(2)) + + +@dsl_user_op +def sts_v2(saddr, a, b, *, loc=None, ip=None): + L._asm( + None, + [L._v(saddr, loc, ip), L._v(a, loc, ip), L._v(b, loc, ip)], + "st.shared.v2.b32 [$0], {$1, $2};", + "r,r,r", + loc, + ip, + ) + + +@dsl_user_op +def cpa_commit(*, loc=None, ip=None): + L._asm(None, [], "cp.async.commit_group;", "", loc, ip) + + +@dsl_user_op +def cpa_wait(n, *, loc=None, ip=None): + L._asm(None, [], f"cp.async.wait_group {n};", "", loc, ip) + + +@dsl_user_op +def st_g_i32(addr, val, *, loc=None, ip=None): + L._asm( + None, [L._v(addr, loc, ip), L._v(val, loc, ip)], "st.global.u32 [$0], $1;", "l,r", loc, ip + ) + + +@cute.jit +def _umin(a, b): + r = a + if b < a: + r = b + return r + + +@cute.jit +def _issue_batch( + ring, + kbat, + slot, + rowbase, + nlim, + d, + warp, + lane, + G: cutlass.Constexpr, + U: cutlass.Constexpr, + NW: cutlass.Constexpr, +): + """cp.async the U chunks of this warp for batch ``kbat`` into ring slot ``slot`` (16 B per lane and chunk; + chunks at or beyond ``nlim`` are skipped) and commit the group.""" + for j in cutlass.range_constexpr(U): + k = kbat * Int32(U) + Int32(j) + c = d + Int32(G) * (warp + Int32(NW) * k) + if c < nlim: + L.cp_async16( + ring + + slot * Int32(U * NW * 512) + + Int32(j * NW * 512) + + warp * Int32(512) + + lane * Int32(16), + rowbase + Int64(c * Int32(CH) + lane * Int32(4)) * Int64(4), + ) + cpa_commit() + + +@cute.jit +def _kth_set_bit(mask, t): + """Index of the t-th (0-based) set bit of ``mask`` (t < popc(mask)).""" + pos = Int32(0) + m = mask + tt = t + for w in cutlass.range_constexpr(5): + wd = 16 >> w + low = m & Int32((1 << wd) - 1) + c = Int32(cute.arch.popc(low)) + if tt >= c: + tt = tt - c + m = (m >> Int32(wd)) & Int32((1 << (32 - wd)) - 1) + pos = pos + Int32(wd) + else: + m = low + return pos + + +@cute.jit +def _consume_batch( + ring, + kbat, + slot, + n_ok, + d, + warp, + lane, + t1f, + sb, + wcnt, + G: cutlass.Constexpr, + U: cutlass.Constexpr, + NW: cutlass.Constexpr, + LCAPW: cutlass.Constexpr, +): + """Values >= T1 of one batch (read from its ring slot) -> the warp's private candidate list (position, value); + returns the warp's new list length. Phase 1: per chunk one ballot of the lanes that hold a candidate among + their 4 values (no branch). Phase 2: the flagged (chunk, lane) pairs of the whole batch are numbered by the + ballots' popcounts and handed to lanes 0..31 one pair per lane (extra rounds if there are more than 32): the lane + re-reads the 4 values of its pair from the ring, tests them, a warp scan gives the slots, the lane stores. The + cost of the batch follows the number of flagged pairs, not the number of chunks that contain one.""" + bbase = ring + slot * Int32(U * NW * 512) + warp * Int32(512) + lst = sb + Int32(OFF_LST) + warp * Int32(LCAPW * 8) + mcs = cute.make_rmem_tensor((U,), Int32) + cums = cute.make_rmem_tensor((U + 1,), Int32) + cums[0] = Int32(0) + for j in cutlass.range_constexpr(U): + v = L.lds_v4(bbase + Int32(j * NW * 512) + lane * Int32(16)) + x0 = L.f32_of_u32(Uint32(v[0])) + x1 = L.f32_of_u32(Uint32(v[1])) + x2 = L.f32_of_u32(Uint32(v[2])) + x3 = L.f32_of_u32(Uint32(v[3])) + mx = cute.arch.fmax(cute.arch.fmax(x0, x1), cute.arch.fmax(x2, x3)) + pj = Int32(0) + if mx >= t1f: + pj = Int32(1) + mj = Int32(cute.arch.vote_ballot_sync(pj != Int32(0))) + mcs[j] = mj + cums[j + 1] = cums[j] + Int32(cute.arch.popc(mj)) + nitems = cums[U] + if nitems != Int32(0): + rd = Int32(0) + while rd < nitems: + r = rd + lane + act = r < nitems + # chunk of item r: the number of chunk starts (j >= 1) that are <= r + jj = Int32(0) + for j in cutlass.range_constexpr(1, U): + if cums[j] <= r: + jj = jj + Int32(1) + msk = Int32(0) + st_j = Int32(0) + for j in cutlass.range_constexpr(U): + if jj == Int32(j): + msk = mcs[j] + st_j = cums[j] + gl = Int32(0) + g0 = Int32(0) + g1 = Int32(0) + g2 = Int32(0) + g3 = Int32(0) + pb = Int32(0) + vv0 = Int32(0) + vv1 = Int32(0) + vv2 = Int32(0) + vv3 = Int32(0) + if act: + gl = _kth_set_bit(msk, r - st_j) + v = L.lds_v4(bbase + jj * Int32(NW * 512) + gl * Int32(16)) + vv0 = v[0] + vv1 = v[1] + vv2 = v[2] + vv3 = v[3] + k = kbat * Int32(U) + jj + c = d + Int32(G) * (warp + Int32(NW) * k) + pb = c * Int32(CH) + gl * Int32(4) + lim = n_ok - pb + if L.f32_of_u32(Uint32(vv0)) >= t1f: + if lim > Int32(0): + g0 = Int32(1) + if L.f32_of_u32(Uint32(vv1)) >= t1f: + if lim > Int32(1): + g1 = Int32(1) + if L.f32_of_u32(Uint32(vv2)) >= t1f: + if lim > Int32(2): + g2 = Int32(1) + if L.f32_of_u32(Uint32(vv3)) >= t1f: + if lim > Int32(3): + g3 = Int32(1) + cl = g0 + g1 + g2 + g3 + incl = L.warp_incl_scan_add(cl, lane) + tot = cute.arch.shuffle_sync(incl, Int32(31)) + slot_c = wcnt + incl - cl + if g0 != Int32(0): + if slot_c < Int32(LCAPW): + sts_u64( + lst + slot_c * Int32(8), + (Uint64(Uint32(pb)) << Uint64(32)) | Uint64(Uint32(vv0)), + ) + slot_c = slot_c + Int32(1) + if g1 != Int32(0): + if slot_c < Int32(LCAPW): + sts_u64( + lst + slot_c * Int32(8), + (Uint64(Uint32(pb + Int32(1))) << Uint64(32)) | Uint64(Uint32(vv1)), + ) + slot_c = slot_c + Int32(1) + if g2 != Int32(0): + if slot_c < Int32(LCAPW): + sts_u64( + lst + slot_c * Int32(8), + (Uint64(Uint32(pb + Int32(2))) << Uint64(32)) | Uint64(Uint32(vv2)), + ) + slot_c = slot_c + Int32(1) + if g3 != Int32(0): + if slot_c < Int32(LCAPW): + sts_u64( + lst + slot_c * Int32(8), + (Uint64(Uint32(pb + Int32(3))) << Uint64(32)) | Uint64(Uint32(vv3)), + ) + slot_c = slot_c + Int32(1) + wcnt = wcnt + tot + rd = rd + Int32(32) + return wcnt + + +@cute.jit +def _level_batch( + ring, + kbat, + slot, + n_ok, + d, + warp, + lane, + pfx, + shp, + dsh, + sb, + G: cutlass.Constexpr, + U: cutlass.Constexpr, + NW: cutlass.Constexpr, +): + """Exact radix fallback, one level: histogram (256 bins, smem) of the 8-bit digit at bit ``dsh`` of the keys of this + batch whose bits above ``dsh + 8`` equal ``pfx`` (``shp`` = number of low bits below the prefix: 32 - 8 * level).""" + bbase = ring + slot * Int32(U * NW * 512) + warp * Int32(512) + lane * Int32(16) + for j in cutlass.range_constexpr(U): + k = kbat * Int32(U) + Int32(j) + c = d + Int32(G) * (warp + Int32(NW) * k) + lim = n_ok - (c * Int32(CH) + lane * Int32(4)) + v = L.lds_v4(bbase + Int32(j * NW * 512)) + for e in cutlass.range_constexpr(4): + if Int32(e) < lim: + kx = L.fkey_bits(Uint32(v[e])) + if ((kx >> Uint32(1)) >> Uint32(shp - Int32(1))) == pfx: + red_add_sh( + sb + Int32(OFF_SHIST) + Int32((kx >> Uint32(dsh)) & Uint32(255)) * Int32(4), + Int32(1), + ) + + +@cute.jit +def _final_batch( + ring, + kbat, + slot, + n_ok, + d, + warp, + lane, + kth, + out_row, + a_base, + t_base, + t_quota, + sb, + G: cutlass.Constexpr, + U: cutlass.Constexpr, + NW: cutlass.Constexpr, +): + """Exact radix fallback, write pass: the elements whose key is above ``kth`` go to ``a_base + running count``, the + first ``t_quota`` elements equal to ``kth`` of this CTA to ``t_base + ordinal``. The running counters live in smem + (M_CABOVE / M_CTIE words); one atomic per candidate chunk step.""" + misc = sb + Int32(OFF_MISC) + lm = Int32(cute.arch.lanemask_lt()) + bbase = ring + slot * Int32(U * NW * 512) + warp * Int32(512) + lane * Int32(16) + for j in cutlass.range_constexpr(U): + k = kbat * Int32(U) + Int32(j) + c = d + Int32(G) * (warp + Int32(NW) * k) + pbase = c * Int32(CH) + lane * Int32(4) + lim = n_ok - pbase + v = L.lds_v4(bbase + Int32(j * NW * 512)) + for e in cutlass.range_constexpr(4): + pa = Int32(0) + pt = Int32(0) + if Int32(e) < lim: + kx = L.fkey_bits(Uint32(v[e])) + if kx > kth: + pa = Int32(1) + if kx == kth: + pt = Int32(1) + ma = Int32(cute.arch.vote_ballot_sync(pa != Int32(0))) + mt = Int32(cute.arch.vote_ballot_sync(pt != Int32(0))) + ba = Int32(0) + bt = Int32(0) + if lane == Int32(0): + if ma != Int32(0): + ba = atom_add_sh(misc + Int32(4 * M_CABOVE), Int32(cute.arch.popc(ma))) + if mt != Int32(0): + bt = atom_add_sh(misc + Int32(4 * M_CTIE), Int32(cute.arch.popc(mt))) + ba = cute.arch.shuffle_sync(ba, Int32(0)) + bt = cute.arch.shuffle_sync(bt, Int32(0)) + if pa != Int32(0): + st_g_i32( + out_row + Int64(a_base + ba + Int32(cute.arch.popc(ma & lm))) * Int64(4), + pbase + Int32(e), + ) + if pt != Int32(0): + ordn = bt + Int32(cute.arch.popc(mt & lm)) + if ordn < t_quota: + st_g_i32(out_row + Int64(t_base + ordn) * Int64(4), pbase + Int32(e)) + + +class TopkMultiCta: + """The multi-CTA top-512 kernel (see the module docstring); ``compile_topk_multicta`` compiles it. + + Args: + g: CTAs (the cluster) per row, one of ``SUPPORTED_CLUSTER_SIZES``; another value raises ValueError. + force_fallback: take the exact radix path on every row (a test hook: it is a different kernel, the default one + takes it only when the certificate of the fast path fails). + trigger: launch the dependent grid once the stream phase of the CTA is done (programmatic dependent launch). + A CTA that takes another path (a short row) triggers when it exits. + arm: mark the 512 output entries of every row -2 ("not written yet") at the start of the kernel, for a tail + attention that polls them (needs ``trigger``). + + The compiled function takes, in order: ``logits`` float32 [B, npad] (unit column stride, row stride a multiple of + 128, 16-byte aligned base), ``ctx`` int32 [B] (valid length of each row) and ``out`` int32 [B, 512]. + """ + + def __init__( + self, g: int, force_fallback: bool = False, trigger: bool = False, arm: bool = False + ): + if g not in SUPPORTED_CLUSTER_SIZES: + raise ValueError( + f"cluster size {g} not supported (built and validated for {SUPPORTED_CLUSTER_SIZES})" + ) + self.g = g + self.force_fallback = force_fallback + if arm and not trigger: + raise ValueError( + "arm needs trigger: the CTA 0 arrives at the cluster barrier before its trigger" + ) + self.trigger = trigger + self.arm = arm + + @cute.jit + def __call__( + self, + logits: cute.Tensor, + ctx: cute.Tensor, + out: cute.Tensor, + stream: cuda_driver.CUstream, + ): + b = logits.shape[0] + self.kernel(logits, ctx, out).launch( + grid=(b * self.g, 1, 1), + block=[NT, 1, 1], + cluster=(self.g, 1, 1), + stream=stream, + min_blocks_per_mp=1, + ) + + @cute.kernel + def kernel( + self, + logits: cute.Tensor, + ctx: cute.Tensor, + out: cute.Tensor, + ): + G = self.g + NR = (SMP_MAX + NT - 1) // NT # sample rounds per thread + bidx, _, _ = cute.arch.block_idx() + tid, _, _ = cute.arch.thread_idx() + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + lane = cute.arch.lane_idx() + row = bidx // Int32(G) + d = bidx % Int32(G) + smem = cutlass.utils.SmemAllocator() + arena = smem.allocate(ARENA_BYTES, byte_alignment=1024) + sb = Int32(arena.toint()) + b_r1 = sb + Int32(OFF_BAR) + b_r2 = sb + Int32(OFF_BAR + 8) + misc = sb + Int32(OFF_MISC) + + # mbarrier init (fence before any load of this thread is outstanding) + if warp == Int32(NW - 1): + if lane == Int32(0): + L.mbar_init(b_r1, Int32(1)) + L.mbar_init(b_r2, Int32(1)) + L.fence_mbar_init_cluster() + # zero state (the barrier that publishes it sits before the first atomics) + zi = tid + while zi < Int32((OFF_LST - OFF_MISC) // 16): + L.sts_v4(misc + zi * Int32(16), Int32(0), Int32(0), Int32(0), Int32(0)) + zi = zi + Int32(NT) + # ---- t = 0: every global load whose address does not depend on n + if cutlass.const_expr(self.arm): + # the polling tail attention behind this kernel starts after every CTA has run its stream phase: mark the + # row's entries "not written yet" (-2) now (released by the CTA 0's arrive right before its trigger, see the + # module docstring) + if d == Int32(0): + st_g_i32( + out.iterator.toint() + (Int64(row) * Int64(K_TOP) + Int64(tid)) * Int64(4), + Int32(-2), + ) + n = L.ld_cg_i32(ctx.iterator.toint() + Int64(row) * Int64(4)) + npad = Int32(logits.layout.stride[0]) + rowbase = logits.iterator.toint() + Int64(row) * Int64(logits.layout.stride[0]) * Int64(4) + ncap = npad // Int32(CH) + sv = cute.make_rmem_tensor((8 * NR,), Float32) + for e in cutlass.range_constexpr(8 * NR): + sv[e] = Float32(NEG_INF) + for r in cutlass.range_constexpr(NR): + jw0 = tid + Int32(NT * r) + if jw0 < Int32(SMP_MAX): + if jw0 * Int32(WST) + Int32(8) <= npad: + wa = rowbase + Int64(jw0 * Int32(WST)) * Int64(4) + a4 = L.ld_cg_f32x4(wa) + b4 = L.ld_cg_f32x4(wa + Int64(16)) + for e in cutlass.range_constexpr(4): + sv[8 * r + e] = a4[e] + sv[8 * r + 4 + e] = b4[e] + ring = sb + Int32(OFF_RING) + + n_ok = n + if n > Int32(MAX_LEN): + n_ok = Int32(MAX_LEN) + if n_ok > npad: # a length beyond the row buffer must not read past the row + n_ok = npad + if n_ok > Int32(K_TOP): + # sample: the windows j * WST (8 floats each) that lie inside the row, at most SMP_MAX; + # TGT = the rank in the sample that corresponds to AIM candidates of the row (aim 1792 = + # 3.5 x K). No sample for rows <= 8192 (everything is a candidate) + SMP = Int32(0) + TGT = Int32(0) + if n_ok > Int32(8192): + SMP = (n_ok - Int32(8)) // Int32(WST) + Int32(1) + if SMP > Int32(SMP_MAX): + SMP = Int32(SMP_MAX) + TGT = Int32(Float32(AIM * 8) * Float32(SMP) * cute.arch.rcp_approx(Float32(n_ok))) + if TGT < Int32(1): + TGT = Int32(1) + # ---------------- sample -> T1, span ---------------- + L.bar(1, NT) + if cutlass.const_expr(self.arm): + if d != Int32(0): + L.cluster_arrive_relaxed() + else: + L.cluster_arrive_relaxed() + smx = Uint32(0) + for r in cutlass.range_constexpr(NR): + jw = tid + Int32(NT * r) + if jw < SMP: + for e in cutlass.range_constexpr(8): + kk = L.fkey(sv[8 * r + e]) + bq = Int32(kk >> Uint32(21)) + red_add_sh( + sb + Int32(OFF_SHIST) + (bq + (bq >> Int32(6))) * Int32(4), Int32(1) + ) + if kk > smx: + smx = kk + wmx = L.warp_max_u32(smx) + if lane == Int32(0): + red_max_sh(misc + Int32(4 * M_SMAX), Int32(wmx)) + L.bar(1, NT) + # warps 1..: ring prefetch (the issue takes ~1 us of LSU time: it must not sit in front of + # the sample / threshold chain) + if warp != Int32(0): + for pb in cutlass.range_constexpr(NBUF): + _issue_batch(ring, Int32(pb), Int32(pb), rowbase, ncap, d, warp, lane, G, U, NW) + t1key = Uint32(0) + have = Int32(0) + if warp == Int32(0): + # round 0: the 32 bins at and below the highest bin of the sample (the TGT-th largest + # sample is there whenever the top of the row is positive: bins are quarter octaves of + # the float key) + smaxk0 = Uint32(L.lds_u32(misc + Int32(4 * M_SMAX))) + b0 = Int32(smaxk0 >> Uint32(21)) + found = Int32(0) + idx = b0 - lane + hh = Int32(0) + if idx >= Int32(0): + hh = L.lds_u32(sb + Int32(OFF_SHIST) + (idx + (idx >> Int32(6))) * Int32(4)) + pcum = L.warp_incl_scan_add(hh, lane) + mk = Int32(cute.arch.vote_ballot_sync(pcum >= TGT)) + if mk != Int32(0): + lbq = Int32(cute.arch.popc((mk & (Int32(0) - mk)) - Int32(1))) + t1key = Uint32(b0 - lbq) << Uint32(21) + have = Int32(1) + found = Int32(1) + if found == Int32(0): + # slow path (a signed row whose TGT-th largest sample is far below the max, e.g. + # mostly negative logits: the float key space has ~900 empty bins between the tiny + # positive and the tiny negative values, a 32-bin scan needs 30 rounds = 4.5 us): + # coarse level = 32 super-bins of 64 bins (lane l sums super-bin 31 - l), then the + # 64 bins of the hit + jc = Int32(31) - lane + cs = Int32(0) + for i_ in cutlass.range_constexpr(64): + cs = cs + L.lds_u32( + sb + Int32(OFF_SHIST) + (jc * Int32(65) + Int32(i_)) * Int32(4) + ) + pc2 = L.warp_incl_scan_add(cs, lane) + mk2 = Int32(cute.arch.vote_ballot_sync(pc2 >= TGT)) + if mk2 != Int32(0): + lb2 = Int32(cute.arch.popc((mk2 & (Int32(0) - mk2)) - Int32(1))) + jstar = Int32(31) - lb2 + cumb = cute.arch.shuffle_sync(pc2 - cs, lb2) + # lane l: bins 63 - 2l and 62 - 2l of the super-bin (padded index = bin + super-bin number) + pa = jstar * Int32(65) + Int32(63) - lane * Int32(2) + ha = L.lds_u32(sb + Int32(OFF_SHIST) + pa * Int32(4)) + hb2 = L.lds_u32(sb + Int32(OFF_SHIST) + (pa - Int32(1)) * Int32(4)) + pc3 = cumb + L.warp_incl_scan_add(ha + hb2, lane) + mk3 = Int32(cute.arch.vote_ballot_sync(pc3 >= TGT)) + lb3 = Int32(cute.arch.popc((mk3 & (Int32(0) - mk3)) - Int32(1))) + pre3 = cute.arch.shuffle_sync(pc3 - ha - hb2, lb3) + ha3 = cute.arch.shuffle_sync(ha, lb3) + tb = Int32(63) - lb3 * Int32(2) + if pre3 + ha3 < TGT: + tb = tb - Int32(1) + t1key = Uint32(jstar * Int32(64) + tb) << Uint32(21) + have = Int32(1) + if TGT <= Int32(0): + have = Int32(0) + if lane == Int32(0): + L.sts_u32(misc + Int32(4 * M_T1KEY), Int32(t1key)) + L.sts_u32(misc + Int32(4 * M_HAVE), have) + # publish T1 without waiting for the other warps' prefetch issue (arrive-only on barrier 3) + L.bar_arrive(3, NT) + for pb in cutlass.range_constexpr(NBUF): + _issue_batch(ring, Int32(pb), Int32(pb), rowbase, ncap, d, warp, lane, G, U, NW) + if warp != Int32(0): + L.bar(3, NT) + t1key = Uint32(L.lds_u32(misc + Int32(4 * M_T1KEY))) + have = L.lds_u32(misc + Int32(4 * M_HAVE)) + smaxk = Uint32(L.lds_u32(misc + Int32(4 * M_SMAX))) + t1f = Float32(-3e38) + k1 = Uint32(0) + if have != Int32(0): + t1f = L.invkey(t1key) + k1 = t1key + else: + smaxk = Uint32(4294967295) + span = Uint32(0) + if smaxk > k1: + span = smaxk - k1 + sh = Int32(0) + bl = Int32(32) - Int32(cute.arch.clz(Int32(span))) + if bl > Int32(10): + sh = bl - Int32(10) + + # ---------------- stream the CTA's chunks, collect candidates ---------------- + nchunk = (n_ok + Int32(CH - 1)) // Int32(CH) + nrem = nchunk - d + if nrem < Int32(0): + nrem = Int32(0) + kc0 = (nrem + Int32(G * NW - 1)) // Int32(G * NW) + nbat = (kc0 + Int32(U - 1)) // Int32(U) + wcnt = Int32(0) + kb = Int32(0) + while kb < nbat: + cpa_wait(NBUF - 1) + slot_b = kb % Int32(NBUF) + wcnt = _consume_batch( + ring, kb, slot_b, n_ok, d, warp, lane, t1f, sb, wcnt, G, U, NW, LCAPW + ) + _issue_batch( + ring, kb + Int32(NBUF), slot_b, rowbase, nchunk, d, warp, lane, G, U, NW + ) + kb = kb + Int32(1) + if cutlass.const_expr(self.trigger): + if cutlass.const_expr(self.arm): + # the marks are in memory (gpu scope) before any CTA of the dependent grid can start and before + # the other CTAs of the cluster, which wait for this arrival, store an entry + if d == Int32(0): + L.cluster_arrive() + cute.arch.griddepcontrol_launch_dependents() + # histogram of the warp's own candidates (32 entries per step) + lsth = sb + Int32(OFF_LST) + warp * Int32(LCAPW * 8) + cwh = _umin(wcnt, Int32(LCAPW)) + rh = Int32(0) + while rh < cwh: + ih = rh + lane + if ih < cwh: + eh = lds_u64(lsth + ih * Int32(8)) + kxh = L.fkey_bits(Uint32(eh & Uint64(4294967295))) + bqh = Int32(0) + if kxh > k1: + bqh = Int32((kxh - k1) >> Uint32(sh)) + if bqh > Int32(NBIN - 1): + bqh = Int32(NBIN - 1) + red_add_sh(sb + Int32(OFF_HIST) + bqh * Int32(4), Int32(1)) + rh = rh + Int32(32) + if lane == Int32(0): + L.sts_u32(misc + Int32(4 * M_WCNT) + warp * Int32(4), wcnt) + if wcnt > Int32(LCAPW): + red_add_sh(misc + Int32(4 * M_OVF), Int32(1)) + L.bar(1, NT) + + # ---------------- local suffix counts -> R1 all-gather -> crossing bin ---------------- + ovf_l = L.lds_u32(misc + Int32(4 * M_OVF)) + hv2 = lds_v2(sb + Int32(OFF_HIST) + tid * Int32(8)) + hb = [hv2[0], hv2[1]] + sumt = hb[0] + for j_ in cutlass.range_constexpr(1, BPT): + sumt = sumt + hb[j_] + vsuf = L.warp_suffix_scan_add(sumt, lane) + if lane == Int32(0): + L.sts_u32(misc + Int32(4 * M_WTOT) + warp * Int32(4), vsuf) + L.bar(1, NT) + hi_w = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) > warp: + hi_w = hi_w + L.lds_u32(misc + Int32(4 * (M_WTOT + w_))) + ss = [Int32(0)] * BPT + acc = (vsuf - sumt) + hi_w + for j_ in cutlass.range_constexpr(BPT - 1, -1, -1): + acc = acc + hb[j_] + ss[j_] = _umin(acc, Int32(65535)) + mybase = sb + Int32(OFF_RX) + d * Int32(SLOT) + L.sts_u32(mybase + tid * Int32(4), ss[0] | (ss[1] << Int32(16))) + if tid == Int32(0): + sts_v2(mybase + Int32(2048), ovf_l, Int32(0)) + if tid == Int32(0): + L.mbar_arrive_expect_tx(b_r1, Int32((G - 1) * SLOT)) + L.fence_proxy_async_smem() + L.cluster_wait() + L.bar(1, NT) + if warp == Int32(0): + if lane < Int32(G - 1): + pr = (d + Int32(1) + lane) % Int32(G) + L.bulk_s2c(L.mapa_u32(mybase, pr), mybase, Int32(SLOT), L.mapa_u32(b_r1, pr)) + L.wait_cl(b_r1, Int32(0)) + # decode: totals per bin of this thread's bins, crossing bin, overflow flags + tt = [Int32(0)] * BPT + for g_ in cutlass.range_constexpr(G): + xw = L.lds_u32(sb + Int32(OFF_RX) + Int32(g_ * SLOT) + tid * Int32(4)) + tt[0] = tt[0] + (xw & Int32(65535)) + tt[1] = tt[1] + ((xw >> Int32(16)) & Int32(65535)) + cand = Int32(0) + for j_ in cutlass.range_constexpr(BPT): + if tt[j_] >= Int32(K_TOP): + cand = tid * Int32(BPT) + Int32(j_ + 1) + wmc = L.warp_max_u32(Uint32(cand)) + if lane == Int32(0): + red_max_sh(misc + Int32(4 * M_BSTAR), Int32(wmc)) + ovf_any = Int32(0) + for g_ in cutlass.range_constexpr(G): + ovf_any = ovf_any | L.lds_u32(sb + Int32(OFF_RX) + Int32(g_ * SLOT + 2048)) + L.bar(1, NT) + bsp1 = L.lds_u32( + misc + Int32(4 * M_BSTAR) + ) # B* + 1, 0 = the total is below K (undershoot) + bstar = bsp1 - Int32(1) + good = Int32(0) + if bsp1 > Int32(0): + if ovf_any == Int32(0): + good = Int32(1) + above_tot = Int32(0) + m_tot = Int32(0) + off_d = Int32(0) + moff_d = Int32(0) + at_0 = Int32(0) + if good != Int32(0): + for g_ in cutlass.range_constexpr(G): + gb = sb + Int32(OFF_RX) + Int32(g_ * SLOT) + wa_ = L.lds_u32(gb + (bstar >> Int32(1)) * Int32(4)) + sat = (wa_ >> ((bstar & Int32(1)) * Int32(16))) & Int32(65535) + sab = Int32(0) + if bstar < Int32(NBIN - 1): + wb_ = L.lds_u32(gb + ((bstar + Int32(1)) >> Int32(1)) * Int32(4)) + sab = (wb_ >> (((bstar + Int32(1)) & Int32(1)) * Int32(16))) & Int32(65535) + atg = sat - sab + if Int32(g_) < d: + off_d = off_d + sab + moff_d = moff_d + atg + if g_ == 0: + at_0 = atg + above_tot = above_tot + sab + m_tot = m_tot + atg + outrow = out.iterator.toint() + Int64(row) * Int64(K_TOP) * Int64(4) + lstw = sb + Int32(OFF_LST) + warp * Int32(LCAPW * 8) + lm2 = Int32(cute.arch.lanemask_lt()) + need_fb = Int32(0) + if good == Int32(0): + need_fb = Int32(1) + if m_tot > Int32(MCAP): + need_fb = Int32(1) + if cutlass.const_expr(self.force_fallback): + need_fb = Int32(1) + if need_fb != Int32(0): + # ---- exact radix fallback over the row (rare: undershoot, list overflow, crossing bin > MCAP) ---- + fpar = Int32(1) # parity of the next phase of b_r1 (phase 0 was the R1 exchange) + pfx = Uint32(0) + need_r = Int32(K_TOP) + lvl = Int32(0) + far = cute.make_rmem_tensor((8,), Int32) + tcr = cute.make_rmem_tensor((8,), Int32) + hgr = cute.make_rmem_tensor((8,), Int32) + for z_ in cutlass.range_constexpr(8): + far[z_] = Int32(0) + tcr[z_] = Int32(0) + hgr[z_] = Int32(0) + while lvl < Int32(4): + shp = Int32(32) - lvl * Int32(8) + dsh = Int32(24) - lvl * Int32(8) + # zero the level histogram and the per-source above counters + if tid < Int32(256): + L.sts_u32(sb + Int32(OFF_SHIST) + tid * Int32(4), Int32(0)) + if tid < Int32(8): + L.sts_u32(misc + Int32(4 * M_FA) + tid * Int32(4), Int32(0)) + cpa_wait(0) + L.bar(1, NT) + for pbf in cutlass.range_constexpr(NBUF): + _issue_batch( + ring, Int32(pbf), Int32(pbf), rowbase, nchunk, d, warp, lane, G, U, NW + ) + kbf = Int32(0) + while kbf < nbat: + cpa_wait(NBUF - 1) + slotf = kbf % Int32(NBUF) + _level_batch( + ring, kbf, slotf, n_ok, d, warp, lane, pfx, shp, dsh, sb, G, U, NW + ) + _issue_batch( + ring, kbf + Int32(NBUF), slotf, rowbase, nchunk, d, warp, lane, G, U, NW + ) + kbf = kbf + Int32(1) + cpa_wait(0) + L.bar(1, NT) + # push the 256-bin histogram (u32) to the cluster (cluster barrier first: the previous + # level's slots are read) + if tid < Int32(256): + L.sts_u32( + mybase + tid * Int32(4), + L.lds_u32(sb + Int32(OFF_SHIST) + tid * Int32(4)), + ) + if tid == Int32(0): + L.mbar_arrive_expect_tx(b_r1, Int32((G - 1) * 1024)) + L.fence_proxy_async_smem() + L.cluster_arrive() + L.cluster_wait() + L.bar(1, NT) + if warp == Int32(0): + if lane < Int32(G - 1): + prf = (d + Int32(1) + lane) % Int32(G) + L.bulk_s2c( + L.mapa_u32(mybase, prf), mybase, Int32(1024), L.mapa_u32(b_r1, prf) + ) + L.wait_cl(b_r1, fpar) + # decode: totals per digit, crossing digit + tot_t = Int32(0) + for g_ in cutlass.range_constexpr(G): + xg = Int32(0) + if tid < Int32(256): + xg = L.lds_u32(sb + Int32(OFF_RX) + Int32(g_ * SLOT) + tid * Int32(4)) + hgr[g_] = xg + tot_t = tot_t + xg + vs = L.warp_suffix_scan_add(tot_t, lane) + if lane == Int32(0): + L.sts_u32(misc + Int32(4 * M_WTOT) + warp * Int32(4), vs) + L.bar(1, NT) + hiw = Int32(0) + for w_ in cutlass.range_constexpr(NW): + if Int32(w_) > warp: + hiw = hiw + L.lds_u32(misc + Int32(4 * (M_WTOT + w_))) + s_ex = (vs - tot_t) + hiw + if tid < Int32(256): + if s_ex < need_r: + if s_ex + tot_t >= need_r: + L.sts_u32(misc + Int32(4 * M_FDIG), tid) + L.sts_u32(misc + Int32(4 * M_FABOVE), s_ex) + L.bar(1, NT) + dig = L.lds_u32(misc + Int32(4 * M_FDIG)) + above_l = L.lds_u32(misc + Int32(4 * M_FABOVE)) + if tid < Int32(256): + if tid > dig: + for g_ in cutlass.range_constexpr(G): + red_add_sh(misc + Int32(4 * (M_FA + g_)), hgr[g_]) + L.bar(1, NT) + for g_ in cutlass.range_constexpr(G): + far[g_] = far[g_] + L.lds_u32(misc + Int32(4 * (M_FA + g_))) + tcr[g_] = L.lds_u32(sb + Int32(OFF_RX) + Int32(g_ * SLOT) + dig * Int32(4)) + # every thread has read this level's M_FA words and RX slots: the next level zeroes M_FA and + # rewrites the own RX slot (without this barrier a slow warp can read the zeros) + L.bar(1, NT) + need_r = need_r - above_l + pfx = (pfx << Uint32(8)) | Uint32(dig) + fpar = fpar ^ Int32(1) + lvl = lvl + Int32(1) + # kth key = pfx; need_r ties (keys equal to it) complete the selection + a_pre = Int32(0) + t_pre = Int32(0) + a_tot = Int32(0) + t_my = Int32(0) + for g_ in cutlass.range_constexpr(G): + if Int32(g_) < d: + a_pre = a_pre + far[g_] + t_pre = t_pre + tcr[g_] + if Int32(g_) == d: + t_my = tcr[g_] + a_tot = a_tot + far[g_] + quota = need_r - t_pre + if quota < Int32(0): + quota = Int32(0) + if quota > t_my: + quota = t_my + if tid < Int32(8): + L.sts_u32(misc + Int32(4 * M_CABOVE) + tid * Int32(4), Int32(0)) + cpa_wait(0) + L.bar(1, NT) + for pbf2 in cutlass.range_constexpr(NBUF): + _issue_batch( + ring, Int32(pbf2), Int32(pbf2), rowbase, nchunk, d, warp, lane, G, U, NW + ) + kbw = Int32(0) + while kbw < nbat: + cpa_wait(NBUF - 1) + slotw = kbw % Int32(NBUF) + _final_batch( + ring, + kbw, + slotw, + n_ok, + d, + warp, + lane, + pfx, + outrow, + a_pre, + a_tot + t_pre, + quota, + sb, + G, + U, + NW, + ) + _issue_batch( + ring, kbw + Int32(NBUF), slotw, rowbase, nchunk, d, warp, lane, G, U, NW + ) + kbw = kbw + Int32(1) + cpa_wait(0) + if need_fb == Int32(0): + if d == Int32(0): + if tid == Int32(0): + L.mbar_arrive_expect_tx(b_r2, (m_tot - at_0) * Int32(8)) + cw = _umin(wcnt, Int32(LCAPW)) + # pass A: per-warp counts of the entries above B* and in B* + na_w = Int32(0) + nm_w = Int32(0) + ra = Int32(0) + while ra < cw: + ia = ra + lane + pa_ = Int32(0) + pm_ = Int32(0) + if ia < cw: + ea = lds_u64(lstw + ia * Int32(8)) + ka = L.fkey_bits(Uint32(ea & Uint64(4294967295))) + qa = Int32(0) + if ka > k1: + qa = Int32((ka - k1) >> Uint32(sh)) + if qa > Int32(NBIN - 1): + qa = Int32(NBIN - 1) + if qa > bstar: + pa_ = Int32(1) + if qa == bstar: + pm_ = Int32(1) + na_w = na_w + Int32( + cute.arch.popc(Int32(cute.arch.vote_ballot_sync(pa_ != Int32(0)))) + ) + nm_w = nm_w + Int32( + cute.arch.popc(Int32(cute.arch.vote_ballot_sync(pm_ != Int32(0)))) + ) + ra = ra + Int32(32) + if lane == Int32(0): + L.sts_u32(misc + Int32(4 * M_WA) + warp * Int32(4), na_w) + L.sts_u32(misc + Int32(4 * M_WM) + warp * Int32(4), nm_w) + L.bar(1, NT) + pre_a = Int32(0) + pre_m = Int32(0) + for w2 in cutlass.range_constexpr(NW): + if Int32(w2) < warp: + pre_a = pre_a + L.lds_u32(misc + Int32(4 * (M_WA + w2))) + pre_m = pre_m + L.lds_u32(misc + Int32(4 * (M_WM + w2))) + oa = off_d + pre_a + om = moff_d + pre_m + # pass B: the writes + rb = Int32(0) + while rb < cw: + ib = rb + lane + pa2 = Int32(0) + pm2 = Int32(0) + eb = Uint64(0) + if ib < cw: + eb = lds_u64(lstw + ib * Int32(8)) + kb2 = L.fkey_bits(Uint32(eb & Uint64(4294967295))) + qb = Int32(0) + if kb2 > k1: + qb = Int32((kb2 - k1) >> Uint32(sh)) + if qb > Int32(NBIN - 1): + qb = Int32(NBIN - 1) + if qb > bstar: + pa2 = Int32(1) + if qb == bstar: + pm2 = Int32(1) + ma2 = Int32(cute.arch.vote_ballot_sync(pa2 != Int32(0))) + mm2 = Int32(cute.arch.vote_ballot_sync(pm2 != Int32(0))) + if pa2 != Int32(0): + st_g_i32( + outrow + Int64(oa + Int32(cute.arch.popc(ma2 & lm2))) * Int64(4), + Int32(Uint32(eb >> Uint64(32))), + ) + if pm2 != Int32(0): + mi = om + Int32(cute.arch.popc(mm2 & lm2)) + if d == Int32(0): + sts_u64(sb + Int32(OFF_XIN) + mi * Int32(8), eb) + else: + L.st_async_v2( + L.mapa_u32(sb + Int32(OFF_XIN) + mi * Int32(8), Int32(0)), + L.mapa_u32(b_r2, Int32(0)), + Int32(Uint32(eb & Uint64(4294967295))), + Int32(Uint32(eb >> Uint64(32))), + ) + oa = oa + Int32(cute.arch.popc(ma2)) + om = om + Int32(cute.arch.popc(mm2)) + rb = rb + Int32(32) + if d == Int32(0): + L.bar(1, NT) + L.wait_cl(b_r2, Int32(0)) + need = Int32(K_TOP) - above_tot + ok_m = Int32(0) + if m_tot <= Int32(MCAP): + ok_m = Int32(1) + if ok_m != Int32(0): + jj = tid + while jj < m_tot: + ej = lds_u64(sb + Int32(OFF_XIN) + jj * Int32(8)) + rk = Int32(0) + if need < m_tot: + kj = L.entry_key(ej) + j2 = Int32(0) + while j2 < m_tot: + if ( + L.entry_key(lds_u64(sb + Int32(OFF_XIN) + j2 * Int32(8))) + > kj + ): + rk = rk + Int32(1) + j2 = j2 + Int32(1) + else: + rk = jj + if rk < need: + st_g_i32( + outrow + Int64(above_tot + rk) * Int64(4), + Int32(Uint32(ej >> Uint64(32))), + ) + jj = jj + Int32(NT) + else: + # short row: identity and a -1 tail (written by CTA 0 of the row's cluster) + L.bar(1, NT) + if cutlass.const_expr(self.arm): + if d == Int32(0): + L.cluster_arrive() + else: + L.cluster_arrive_relaxed() + else: + L.cluster_arrive_relaxed() + if d == Int32(0): + for r2 in cutlass.range_constexpr(512 // NT if NT < 512 else 1): + jq = tid + Int32(r2 * NT) + if jq < Int32(K_TOP): + val = Int32(-1) + if jq < n_ok: + val = jq + st_g_i32( + out.iterator.toint() + + (Int64(row) * Int64(K_TOP) + Int64(jq)) * Int64(4), + val, + ) + L.cluster_wait() + + +def compile_topk_multicta(kernel: TopkMultiCta): + """Compile ``kernel`` (logits [B, npad] float32 with a dynamic row stride, ctx [B] int32, out [B, 512] int32).""" + rt = cute.runtime + sb = cute.sym_int() + logits_fake = rt.make_fake_tensor( + Float32, (sb, cute.sym_int()), stride=(cute.sym_int64(), 1), assumed_align=16 + ) + ctx_fake = rt.make_fake_compact_tensor(Int32, (sb,), stride_order=(0,)) + out_fake = rt.make_fake_compact_tensor(Int32, (sb, K_TOP), stride_order=(1, 0)) + stream = rt.make_fake_stream(use_tvm_ffi_env_stream=True) + return cute.compile( + kernel, + logits_fake, + ctx_fake, + out_fake, + stream, + options="--enable-tvm-ffi --generate-line-info", + ) diff --git a/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta_op.py b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta_op.py new file mode 100644 index 000000000000..f025cd06dd27 --- /dev/null +++ b/tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa/topk_multicta_op.py @@ -0,0 +1,266 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA multi-CTA exact top-512, host side: the top-K stage of the tail-attention hybrid (``tail_op.run_hybrid``). + +``run`` selects the exact top-512 positions of every row of the fp32 indexer logits (``logits`` [B, npad], row ``r`` +valid up to ``ctx_lens[r]``) with one cluster of CTAs per row (``topk_multicta.py``) and writes them to ``topk`` +[B, 512] int32, the input of the tail attention: local positions in no particular order, and ``0 .. n - 1`` followed +by -1 for a row of ``n <= 512`` positions, as the production top-K does. The result is exact for every input (its +values are the 512 largest of the row; which positions that share the 512th value are taken is not specified): a row +whose sampled threshold does not certify the fast path takes an in-kernel exact fallback (a radix select over the +row). A row of at most 8192 positions has no sample: every value is a candidate and the same certificate decides. + +Dispatch. Rows of 16,384 positions or more (``MIN_PROFITABLE_ROW_LEN``, 64K tokens at the compression ratio 4) take +the fast path, and the kernel is faster than the production top-K behind the same logits kernel (B200, FP4 indexer, +1M-token captures: 0.8 to 2.8 us of the 9 to 26 row hybrid, +1.3 to +3.5 % of its step; one top-K call +0.8 to +3.7 +us in 20 of 21 cases of BS 12 / 16 / 24 x 7 lengths, -0.3 us in one). Below that length the sample has few windows +(one per 896 positions) or none (rows of at most 8192 positions: every value is a candidate), and the kernel is not +reliably faster: at BS 24 it is 2 to 4 us slower for rows up to 12K positions, at BS 12 to 16 it is up to 1 us slower +for 8193 to 12K positions and 0.6 to 2.5 us faster for rows of at most 8192. A row that takes the fallback costs ~6 +us more (rare on real logits: none of 630 captured rows) and a batch is as slow as its slowest row, so +``is_profitable`` asks for every row to be long enough. The caller keeps its production top-K for the other batches +(``tail_op.run_hybrid`` takes it as ``topk_fn``). + +Contract: ``logits`` float32 [B, npad] with unit column stride, a row stride that is a multiple of 128 floats (the +logits arena of the indexer kernel has 2**18) and a 16-byte aligned base, ``ctx_lens`` at most ``npad`` (the lengths +the logits kernel was given); ``topk`` int32 [B, 512] contiguous; ``ctx_lens`` int32 [B]; all on one CUDA device. B +is 1 to 26 rows (the batch sizes of the tail attention): a cluster of 8 / 6 / 5 / 4 CTAs serves a row for 1-15 / +16 / 17-24 / 25-26 rows, and the clusters of a launch have to fit one wave of co-resident clusters on the 148 SMs. +The kernel reads the logits only, so both indexer K dtypes are served (``config``: either supported spec, default +DS-V4-Flash). ``topk`` must not alias an input. + +Launch variants (each is a compile of its own): ``trigger`` lets the tail attention launched behind it with the +programmatic attribute (``tail_op.run_attention(pdl=True)``) start while this kernel ranks the crossing bin, and +``arm`` (needs ``trigger``) also marks the 512 entries of every row -2 at the start, so that the tail attention +launched with ``poll=True`` reads each entry as soon as it is written instead of waiting for the end of this grid +(``tail_op.run_hybrid`` sets both by default up to ``tail_op.POLL_MAX_BATCH`` rows). Every entry is written exactly +once with a value >= -1 in every path (fast path, radix fallback, short rows). +""" + +from __future__ import annotations + +import threading + +import torch + +from .config import SpecDsaConfig, check_device, supported_spec + +__all__ = [ + "MAX_BATCH", + "MIN_PROFITABLE_ROW_LEN", + "cluster_size", + "is_batch_size_supported", + "is_profitable", + "is_supported", + "precompile", + "run", +] + +# (largest batch size, CTAs per row): the clusters of one launch (one CTA per SM, ~170 KB of shared memory each) have to +# co-reside in one wave. A B200 holds (measured) 15 clusters of 8 CTAs, 22 of 6, 26 of 5 and 33 of 4; these sizes put +# 120, 96, 120 and 104 CTAs at the largest batch of each. The sizes are the fastest ones behind the tail attention's +# programmatic launch (nsys, 1M-token captures: 8 CTAs beat 6 at 13 to 15 rows by 0.5 to 1.2 us). +_CLUSTER_LIMITS = ((15, 8), (16, 6), (24, 5), (26, 4)) +MAX_BATCH = _CLUSTER_LIMITS[-1][0] +# Compressed positions per row from which the kernel is faster than the production top-K (see the module docstring). +MIN_PROFITABLE_ROW_LEN = 16384 +_ROW_ALIGN = 128 # floats: the row stride of ``logits`` + +_lock = threading.Lock() +_compiled: dict[tuple, object] = {} + + +def cluster_size(batch_size: int) -> int | None: + """CTAs per row for ``batch_size`` rows, None when the batch is not in [1, ``MAX_BATCH``].""" + for max_batch, g in _CLUSTER_LIMITS: + if 1 <= batch_size <= max_batch: + return g + return None + + +def _cluster(batch_size: int) -> int: + g = cluster_size(batch_size) + if g is None: + raise ValueError(f"batch size {batch_size} not in [1, {MAX_BATCH}]") + return g + + +def is_batch_size_supported(batch_size: int) -> tuple[bool, str]: + """Whether the kernel serves ``batch_size`` rows (1 to ``MAX_BATCH``), and why not if it does not.""" + if cluster_size(batch_size) is None: + return False, f"batch size {batch_size} not in [1, {MAX_BATCH}]" + return True, "" + + +def is_supported( + device: torch.device | None = None, config: SpecDsaConfig | None = None +) -> tuple[bool, str]: + """Whether the kernel serves ``config`` (default: DS-V4-Flash) on ``device``, and why not if it does not. + + That takes a supported spec (either indexer K dtype), CuTe DSL installed and SM100 with all 148 SMs (clusters of + up to 8 CTAs at one CTA per SM). The batch size is checked by ``is_batch_size_supported``. + """ + try: + supported_spec(config) + except NotImplementedError as e: + return False, str(e) + return check_device(device) + + +def is_profitable(ctx_lens: torch.Tensor) -> bool: + """Whether the kernel is the faster top-K for rows of these lengths: every row has at least + ``MIN_PROFITABLE_ROW_LEN`` positions (see the module docstring). + + Pass the host (CPU) tensor of the step's lengths: a device tensor is read back and synchronizes. + """ + return ctx_lens.numel() > 0 and bool((ctx_lens >= MIN_PROFITABLE_ROW_LEN).all()) + + +def _device_index(device: torch.device) -> int: + device = torch.device(device) + return device.index if device.index is not None else torch.cuda.current_device() + + +def _fn( + device: torch.device, + g: int, + force_fallback: bool = False, + trigger: bool = False, + arm: bool = False, +): + """The compiled kernel of cluster size ``g`` on ``device``, compiled on first use (one compile per device, cluster + size and variant). ``force_fallback`` selects the variant that runs the exact radix select on every row: a hook + for the tests, ``run`` never uses it. ``trigger`` selects the variant that launches the dependent grid after the + stream phase, ``arm`` the variant that marks the output entries -2 at its start (see ``run``).""" + from . import topk_multicta as TM + + key = (_device_index(device), g, force_fallback, trigger, arm) + with _lock: + if key not in _compiled: + if torch.cuda.is_current_stream_capturing(): + raise RuntimeError( + "spec_dsa multi-CTA top-K: compile (precompile) before CUDA-graph capture" + ) + _compiled[key] = TM.compile_topk_multicta( + TM.TopkMultiCta(g, force_fallback, trigger, arm) + ) + return _compiled[key] + + +def precompile( + device: torch.device, + batch_size: int, + config: SpecDsaConfig | None = None, + trigger: bool = False, + arm: bool = False, +) -> None: + """Compile the kernel of ``batch_size`` rows on ``device`` (one compile per cluster size, 8, 6, 5 and 4 CTAs, and + per ``trigger`` / ``arm`` value: precompile the variant ``run`` will launch). + + Must run outside CUDA-graph capture; ``run`` compiles on first use otherwise. + """ + supported_spec(config) + if arm and not trigger: + raise ValueError("arm needs trigger: the entries are polled by a dependent grid") + _fn(device, _cluster(batch_size), False, trigger, arm) + + +def _require(ok: bool, what: str, t: torch.Tensor) -> None: + if not ok: + raise ValueError(f"{what}, got {t.dtype} {tuple(t.shape)} on {t.device}") + + +def _check_arguments(config, logits, topk, ctx_lens) -> int: + """Raise ValueError for an argument the kernel cannot take (before any device work); returns the batch size.""" + _require( + logits.dtype == torch.float32 and logits.dim() == 2 and logits.stride(1) == 1, + "logits must be a float32 [B, npad] tensor with unit column stride", + logits, + ) + b, cols = logits.shape + if not 1 <= b <= MAX_BATCH: + raise ValueError( + f"batch size {b} not in [1, {MAX_BATCH}]: the clusters of more rows no longer fit one wave, " + "use the production top-K" + ) + _require( + 1 <= cols <= config.max_index_len, + f"logits must have 1 to {config.max_index_len} columns", + logits, + ) + _require( + logits.stride(0) % _ROW_ALIGN == 0 and logits.stride(0) >= cols, + f"logits row stride must be a multiple of {_ROW_ALIGN} floats and at least the row length", + logits, + ) + _require( + topk.dtype == torch.int32 + and tuple(topk.shape) == (b, config.topk) + and topk.is_contiguous(), + f"topk must be a contiguous int32 [{b}, {config.topk}] tensor", + topk, + ) + _require( + ctx_lens.dtype == torch.int32 + and tuple(ctx_lens.shape) == (b,) + and ctx_lens.is_contiguous(), + f"ctx_lens must be a contiguous int32 [{b}] tensor", + ctx_lens, + ) + if logits.device.type != "cuda": + raise ValueError(f"the tensors must be CUDA tensors, got logits on {logits.device}") + for name, t in (("topk", topk), ("ctx_lens", ctx_lens)): + if t.device != logits.device: + raise ValueError( + f"{name} must be on the device of logits ({logits.device}), got {t.device}" + ) + return b + + +def run( + logits: torch.Tensor, + topk: torch.Tensor, + ctx_lens: torch.Tensor, + *, + config: SpecDsaConfig | None = None, + trigger: bool = False, + arm: bool = False, +) -> None: + """Launch the exact top-512 selection on the current stream (see the module docstring for the contract). + + Allocates nothing, never synchronizes with the host and can be captured in a CUDA graph once compiled + (``precompile``; outside a capture the first call compiles). + + Args: + logits: float32 [B, npad], the indexer logits; unit column stride, row stride a multiple of 128 floats, + 16-byte aligned base, B in [1, ``MAX_BATCH``]. + topk: int32 [B, 512] output: the positions of the 512 largest values of every row (see the module + docstring for the order and the ties). + ctx_lens: int32 [B] on the device, the valid length of each row in positions (at most ``npad``); a row of + at most 512 positions gets ``0 .. n - 1`` and -1 entries. + config: the spec (default: DS-V4-Flash); either indexer K dtype: the launch is the same. + trigger: let the dependent grid launch as soon as the stream phase of every CTA is done (programmatic dependent + launch): set it only when the next kernel on the stream is launched with the programmatic attribute and + waits for this grid before it reads ``topk`` (``tail_op.run_attention(pdl=True)``) or polls its entries + (``arm``); the results are the same. + arm: mark all 512 entries of every row of ``topk`` -2 at the start of the kernel (every entry is written exactly + once with a value >= -1 before the kernel is done) so that the tail attention launched with + ``run_attention(pdl=True, poll=True)`` can read the entries as they are written; needs ``trigger``. + """ + config = supported_spec(config) + b = _check_arguments(config, logits, topk, ctx_lens) + if arm and not trigger: + raise ValueError("arm needs trigger: the entries are polled by a dependent grid") + _fn(logits.device, _cluster(b), False, trigger, arm)(logits, ctx_lens, topk) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_config.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_config.py new file mode 100644 index 000000000000..8a374abbb9b3 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_config.py @@ -0,0 +1,538 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA configuration: the spec table, its validation, the support checks and the dispatch table of the op. + +Runs without a GPU: the checks refuse an unsupported spec, an unknown or incapable implementation and a missing +production logits op before any device work. Only the last test needs CuTe DSL (not a GPU) and skips without it. +""" + +import dataclasses +import importlib.util +import math +import sys +import types +from pathlib import Path + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import config as C +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import ( + hybrid_op, + large_batch_op, + megakernel_op, + op, + tail_op, + topk_multicta_op, +) + +FLASH = C.DS_V4_FLASH +FLASH_FP4 = C.DS_V4_FLASH_FP4 +# An indexer shape without kernels: top-1024 instead of top-512. +PRO = dataclasses.replace(FLASH, name="DS-V4-Pro", topk=1024) + + +def test_ds_v4_flash_values(): + """The numbers the kernels and the tests were validated with.""" + s = C.DS_V4_FLASH + assert s.name == "DS-V4-Flash" + assert (s.index_heads, s.index_head_dim, s.index_k_dtype) == (64, 128, "fp8") + assert (s.index_page_tokens, s.compress_ratio, s.topk, s.max_index_len) == (32, 4, 512, 1 << 18) + assert (s.attn_heads, s.kv_dim, s.kv_format, s.kv_page_rows) == (64, 512, "v4_e4m3_rows", 32) + assert (s.window, s.swa_page_rows, s.has_sink) == (128, 128, True) + assert (s.megakernel_max_batch, s.large_batch, s.max_batch) == (47, True, 1024) + assert s.tail_hybrid_range is None + assert s.shape_key == (64, 128, 512, 4) + assert (s.min_index_len, s.selected_rows, s.pages_per_tile) == (512, 640, 4) + assert s.index_page_bytes == 32 * (128 + 4) + assert s.default_softmax_scale == 1.0 / math.sqrt(512.0) + assert (C.NUM_SMS, C.INDEX_TILE) == (148, 128) + assert C.SUPPORTED_SPECS == {"DS-V4-Flash": s, "DS-V4-Flash-FP4": C.DS_V4_FLASH_FP4} + + +def test_ds_v4_flash_fp4_values(): + """The same model with the MXFP4 indexer K cache: only the K dtype (and the batch sizes of its kernels) differ.""" + s = C.DS_V4_FLASH_FP4 + assert s.name == "DS-V4-Flash-FP4" + assert ( + dataclasses.replace( + s, + name=FLASH.name, + index_k_dtype="fp8", + megakernel_max_batch=FLASH.megakernel_max_batch, + tail_hybrid_range=None, + ) + == FLASH + ) + assert (s.index_k_dtype, s.large_batch, s.max_batch) == ("fp4", True, 1024) + # The FP4 K stream is twice as fast per byte, the megakernel row cost is not: the large-batch kernels are faster + # from 21 rows (nsys, megakernel against large batch at 17 to 28 rows). The megakernel stays able to serve 20 rows. + assert s.megakernel_max_batch == 20 + # The tail-attention hybrid serves 5 to 26 rows: the clusters of its two kernels have to fit one wave of the SMs. + assert s.tail_hybrid_range == (5, 26) + assert s.index_page_bytes == 32 * (128 // 2 + 128 // 32) + assert s.shape_key == FLASH.shape_key and s.kernel_key != FLASH.kernel_key + + +def test_index_page_bytes(): + """The token bytes of the cache manager of the DeepSeek-V4 attention backend times the tokens of a page.""" + assert FLASH.index_page_bytes == 32 * ( + 128 + 4 + ) # E4M3 values, then one float32 scale per 128 elements + assert dataclasses.replace(FLASH, index_head_dim=256).index_page_bytes == 32 * (256 + 2 * 4) + fp4 = dataclasses.replace(FLASH, index_k_dtype="fp4") + assert fp4.index_page_bytes == 32 * ( + 128 // 2 + 128 // 32 + ) # packed E2M1 plus one UE8M0 per 32 elements + + +def test_known_shapes_match_the_adapter_table(): + path = Path(C.__file__).parents[1] / "throwaway_topk" / "adapter" / "indexer_config.py" + if not path.exists(): + pytest.skip("the top-K adapter's model table is not in this tree") + modspec = importlib.util.spec_from_file_location("indexer_config_under_test", path) + table = importlib.util.module_from_spec(modspec) + modspec.loader.exec_module(table) + for name, shape in C.KNOWN_SHAPES.items(): + assert table.MODEL_CONFIGS[name] == shape + assert FLASH.shape_key == table.MODEL_CONFIGS[FLASH.name] + + +def test_frozen_and_hashable(): + assert len({FLASH, dataclasses.replace(FLASH), PRO}) == 2 + with pytest.raises(dataclasses.FrozenInstanceError): + FLASH.topk = 1024 + + +@pytest.mark.parametrize( + "changes, match", + [ + ({"name": ""}, "name must not be empty"), + ({"topk": 0}, "topk must be a positive int"), + ({"index_heads": -1}, "index_heads must be a positive int"), + ({"topk": 512.0}, "topk must be a positive int"), + ({"index_k_dtype": "int8"}, "index_k_dtype"), + ({"kv_format": "mla"}, "kv_format"), + ({"index_head_dim": 100}, "multiple of 128"), + ({"index_k_dtype": "fp4", "index_head_dim": 100}, "multiple of 32"), + ({"topk": (1 << 18) + 32}, "exceeds max_index_len"), + ({"max_index_len": (1 << 18) + 1}, "multiple of index_page_tokens"), + ({"index_page_tokens": 256}, "divide the indexer tile"), + ({"megakernel_max_batch": -1}, "megakernel_max_batch"), + ({"megakernel_max_batch": 2048}, "exceeds max_batch"), + ({"large_batch": False}, "need the large-batch kernels"), + ({"tail_hybrid_range": (0, 8)}, "1 <= first <= last <= max_batch"), + ({"tail_hybrid_range": (9, 8)}, "1 <= first <= last <= max_batch"), + ({"tail_hybrid_range": (5, 1025)}, "1 <= first <= last <= max_batch"), + ({"tail_hybrid_range": (5,)}, "tuple .first, last. of ints"), + ({"tail_hybrid_range": [5, 8]}, "tuple .first, last. of ints"), + ({"tail_hybrid_range": (5.0, 8)}, "tuple .first, last. of ints"), + ({"tail_hybrid_range": 8}, "tuple .first, last. of ints"), + ], +) +def test_validation(changes, match): + with pytest.raises(ValueError, match=match): + dataclasses.replace(FLASH, **changes) + + +def test_kernel_key_covers_every_structural_field(monkeypatch): + """A field the kernels depend on must change ``kernel_key``; the label and the batch-size limits must not.""" + monkeypatch.setattr(C, "KV_FORMATS", ("v4_e4m3_rows", "other")) + other_value = { + "index_heads": 32, + "index_head_dim": 256, + "index_k_dtype": "fp4", + "index_page_tokens": 16, + "compress_ratio": 1, + "topk": 1024, + "max_index_len": 1 << 17, + "attn_heads": 32, + "kv_dim": 576, + "kv_format": "other", + "kv_page_rows": 64, + "window": 64, + "swa_page_rows": 64, + "has_sink": False, + } + not_structural = { + "name", + "megakernel_max_batch", + "large_batch", + "max_batch", + "tail_hybrid_range", + } + assert {f.name for f in dataclasses.fields(C.SpecDsaConfig)} == not_structural | set( + other_value + ) + for field, value in other_value.items(): + assert dataclasses.replace(FLASH, **{field: value}).kernel_key != FLASH.kernel_key, field + relabeled = dataclasses.replace(FLASH, name="alias", megakernel_max_batch=8, max_batch=256) + assert relabeled.kernel_key == FLASH.kernel_key + # the hybrid range is host-side dispatch data: no kernel_key, and so no compile or engine cache key of the + # kernels, changes with it (those are keyed by ``kernel_key``; the hybrid's kernels by cluster size and variant) + for rng in (None, (1, 1), (5, 26), (8, 12)): + assert ( + dataclasses.replace(FLASH_FP4, tail_hybrid_range=rng).kernel_key == FLASH_FP4.kernel_key + ) + assert dataclasses.replace(FLASH, tail_hybrid_range=rng).kernel_key == FLASH.kernel_key + + +def test_supported_spec(): + assert C.supported_spec() is FLASH + assert C.supported_spec(FLASH) is FLASH + # lower batch-size limits are served: more rows go to the large-batch kernels, or fewer rows are accepted + for lower in ( + dataclasses.replace(FLASH, name="small", megakernel_max_batch=8, max_batch=64), + dataclasses.replace(FLASH, megakernel_max_batch=0), + dataclasses.replace(FLASH, large_batch=False, max_batch=47), + ): + assert C.supported_spec(lower) is lower + for higher in ( + dataclasses.replace(FLASH, max_batch=2048), + dataclasses.replace(FLASH, megakernel_max_batch=64), + ): + with pytest.raises(NotImplementedError, match="batch-size limits"): + C.supported_spec(higher) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + C.supported_spec(PRO) + + +def test_supported_spec_checks_the_tail_hybrid_range(): + """A narrower range, or none, is served (the other batch sizes go to the other implementations); a range that + covers a batch size the spec's does not, or any range of a spec without one, is not.""" + for inside in (None, (5, 26), (5, 5), (8, 20), (26, 26)): + config = dataclasses.replace(FLASH_FP4, tail_hybrid_range=inside) + assert C.supported_spec(config) is config + for outside in ((4, 26), (1, 8), (5, 27), (27, 40), (1, 1024)): + with pytest.raises(NotImplementedError, match="tail-hybrid range"): + C.supported_spec(dataclasses.replace(FLASH_FP4, tail_hybrid_range=outside)) + with pytest.raises(NotImplementedError, match="tail-hybrid range"): + C.supported_spec(dataclasses.replace(FLASH, tail_hybrid_range=(5, 26))) + + +def test_resolve_spec(): + assert C.resolve_spec(64, 128, 512, 4) is FLASH + assert C.resolve_spec(64, 128, 512, 4, index_k_dtype="fp8", kv_format="v4_e4m3_rows") is FLASH + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + C.resolve_spec(64, 128, 1024, 4) + with pytest.raises(NotImplementedError, match="DS-V3.2"): + C.resolve_spec(64, 128, 2048, 1) + assert C.resolve_spec(64, 128, 512, 4, index_k_dtype="fp4") is FLASH_FP4 + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + C.resolve_spec(64, 128, 1024, 4, index_k_dtype="fp4") + with pytest.raises(NotImplementedError, match="specDSA has no kernels"): + C.resolve_spec(32, 128, 512, 4) # another model with the same top-K + + +def test_require_built_for(): + assert C.require_built_for(None, FLASH) is FLASH + alias = dataclasses.replace(FLASH, name="alias") + assert C.require_built_for(alias, FLASH) is alias + with pytest.raises(NotImplementedError, match="specialized for 'DS-V4-Flash'"): + C.require_built_for(PRO, FLASH) + + +def _default_ranges(spec): + """Batch sizes each implementation serves by default for ``spec``, as the text of the README table ("none" when + empty). Each one has to be a single range.""" + served = {name: [] for name in op.IMPLEMENTATIONS} + for batch in range(1, spec.max_batch + 1): + served[op.implementation_for(batch, spec)].append(batch) + cells = {} + for name, sizes in served.items(): + assert sizes == list(range(sizes[0], sizes[-1] + 1)) if sizes else True, (spec.name, name) + cells[name] = f"{sizes[0]} to {sizes[-1]:,} rows" if sizes else "none" + return cells + + +def test_readme_table_lists_the_batch_sizes_of_every_spec(): + """The README's spec table (megakernel, tail hybrid, large-batch ranges) is the dispatch of ``SUPPORTED_SPECS``.""" + readme = (Path(C.__file__).parent / "README.md").read_text() + for spec in C.SUPPORTED_SPECS.values(): + rows = [ln for ln in readme.splitlines() if ln.startswith(f"| {spec.name} |")] + assert len(rows) == 1, f"{spec.name}: no row in the README table" + cells = [c.strip() for c in rows[0].strip().strip("|").split("|")] + ranges = _default_ranges(spec) + assert cells[-3] == ranges["megakernel"], spec.name + assert cells[-2] == ranges["tail_hybrid"], spec.name + assert cells[-1] == ranges["large_batch"], spec.name + + +def test_op_routes_batch_sizes_by_spec(): + assert op.implementation_for(1) == "megakernel" + assert op.implementation_for(47) == "megakernel" + assert op.implementation_for(48) == "large_batch" + assert op.implementation_for(1024) == "large_batch" + for bad in (-1, 0, 1025): + with pytest.raises(ValueError, match="batch size"): + op.implementation_for(bad) + small = dataclasses.replace(FLASH, megakernel_max_batch=8) + assert (op.implementation_for(8, small), op.implementation_for(9, small)) == ( + "megakernel", + "large_batch", + ) + assert ( + op.implementation_for(1, dataclasses.replace(FLASH, megakernel_max_batch=0)) + == "large_batch" + ) + no_large = dataclasses.replace(FLASH, large_batch=False, max_batch=47) + assert op.implementation_for(47, no_large) == "megakernel" + with pytest.raises(ValueError, match="batch size 48"): + op.implementation_for(48, no_large) + assert list(megakernel_op.supported_batch_sizes()) == list(range(1, 48)) + assert list(megakernel_op.supported_batch_sizes(small)) == list(range(1, 9)) + + +def test_op_routes_fp4_batch_sizes(): + """The dispatch table of the FP4 spec: the megakernel for 1 to 4 rows, the tail hybrid for 5 to 26, the large-batch + kernels from 27 rows. The megakernel still serves up to 20 rows when asked for.""" + assert FLASH_FP4.megakernel_max_batch == 20 and FLASH_FP4.tail_hybrid_range == (5, 26) + for batch in range(1, FLASH_FP4.max_batch + 1): + expected = "megakernel" if batch <= 4 else ("tail_hybrid" if batch <= 26 else "large_batch") + assert op.implementation_for(batch, FLASH_FP4) == expected, batch + assert list(megakernel_op.supported_batch_sizes(FLASH_FP4)) == list(range(1, 21)) + assert list(hybrid_op.supported_batch_sizes(FLASH_FP4)) == list(range(5, 27)) + assert list(hybrid_op.supported_batch_sizes()) == list(range(5, 27)) + # the FP8 spec keeps its own switch and has no hybrid + assert op.implementation_for(47, FLASH) == "megakernel" + assert op.implementation_for(48, FLASH) == "large_batch" + assert "tail_hybrid" not in {op.implementation_for(b, FLASH) for b in range(1, 1025)} + assert list(hybrid_op.supported_batch_sizes(FLASH)) == [] + + +def test_op_routes_a_custom_hybrid_range(): + """The hybrid takes the batch sizes of its range out of the megakernel's and the large-batch kernels' ranges.""" + narrow = dataclasses.replace(FLASH_FP4, tail_hybrid_range=(8, 12)) + got = [op.implementation_for(b, narrow) for b in (1, 7, 8, 12, 13, 20, 21, 1024)] + assert ( + got == ["megakernel"] * 2 + ["tail_hybrid"] * 2 + ["megakernel"] * 2 + ["large_batch"] * 2 + ) + none = dataclasses.replace(FLASH_FP4, tail_hybrid_range=None) + assert [op.implementation_for(b, none) for b in (5, 20, 21)] == [ + "megakernel", + "megakernel", + "large_batch", + ] + # a range above the megakernel's last size and inside the large-batch kernels' + above = dataclasses.replace(FLASH_FP4, tail_hybrid_range=(22, 24)) + assert [op.implementation_for(b, above) for b in (20, 21, 22, 24, 25)] == [ + "megakernel", + "large_batch", + "tail_hybrid", + "tail_hybrid", + "large_batch", + ] + + +def test_tail_hybrid_range_is_inside_the_limits_of_its_kernels(): + """Both kernels of the hybrid serve every batch size of the range (their clusters fit one wave of the SMs).""" + first, last = FLASH_FP4.tail_hybrid_range + for batch in range(first, last + 1): + assert tail_op.is_batch_size_supported(batch)[0], batch + assert topk_multicta_op.is_batch_size_supported(batch)[0], batch + assert last <= min(tail_op.TAIL_MAX_BATCH, topk_multicta_op.MAX_BATCH) + + +def _prepare_args(batch): + i32 = torch.int32 + return ( + torch.full((batch,), 4096, dtype=i32), + torch.full((batch,), 16384, dtype=i32), + torch.zeros((batch, 128), dtype=i32), + torch.zeros(64), + ) + + +@pytest.mark.parametrize( + "spec, batch, implementation, match", + [ + (FLASH_FP4, 8, "megakernal", "implementation must be one of"), + ( + FLASH_FP4, + 21, + "megakernel", + "megakernel implementation of DS-V4-Flash-FP4 serves 1 to 20 rows", + ), + ( + FLASH_FP4, + 4, + "tail_hybrid", + "tail_hybrid implementation of DS-V4-Flash-FP4 serves 5 to 26 rows", + ), + ( + FLASH_FP4, + 27, + "tail_hybrid", + "tail_hybrid implementation of DS-V4-Flash-FP4 serves 5 to 26 rows", + ), + (FLASH, 8, "tail_hybrid", "DS-V4-Flash has no tail_hybrid implementation"), + (FLASH, 48, "megakernel", "megakernel implementation of DS-V4-Flash serves 1 to 47 rows"), + ( + dataclasses.replace(FLASH, megakernel_max_batch=0), + 8, + "megakernel", + "has no megakernel implementation", + ), + ( + dataclasses.replace(FLASH, large_batch=False, max_batch=47), + 8, + "large_batch", + "has no large_batch implementation", + ), + (FLASH_FP4, 1025, "large_batch", "batch size 1025"), + ], +) +def test_forced_implementation_is_refused_before_any_device_work( + spec, batch, implementation, match +): + """A forced implementation that cannot serve the batch size is a ValueError of ``prepare`` and ``precompile``, + raised before any device work (these run on the CPU).""" + with pytest.raises(ValueError, match=match): + op.prepare(*_prepare_args(batch), config=spec, implementation=implementation) + with pytest.raises(ValueError, match=match): + op.precompile(torch.device("cpu"), batch, spec, implementation=implementation) + + +def test_forced_implementation_that_can_serve_the_batch_size_is_accepted(): + """The megakernel at 5 to 20 FP4 rows and the large-batch kernels below their default range are selectable; + what a forced request resolves to is checked on the GPU (``test_cute_dsl_spec_dsa_op.py``).""" + for batch, implementation in ( + (5, "megakernel"), + (20, "megakernel"), + (5, "large_batch"), + (21, "large_batch"), + (26, "large_batch"), + (5, "tail_hybrid"), + (26, "tail_hybrid"), + ): + assert op._select(batch, FLASH_FP4, implementation) == implementation + assert op._select(5, FLASH_FP4, None) == "tail_hybrid" + assert op._select(5, FLASH_FP4, "tail_hybrid") == "tail_hybrid" + assert op._select(3, FLASH_FP4, "megakernel") == "megakernel" + + +def test_unsupported_spec_is_refused_before_any_device_work(): + for is_supported in ( + op.is_supported, + megakernel_op.is_supported, + large_batch_op.is_supported, + hybrid_op.is_supported, + ): + ok, why = is_supported(config=PRO) + assert not ok and "DS-V4-Pro" in why + ok, why = hybrid_op.is_supported(config=FLASH) + assert not ok and "no tail-hybrid range" in why + ok, why = megakernel_op.is_supported(config=dataclasses.replace(FLASH, megakernel_max_batch=0)) + assert not ok and "no megakernel" in why + ok, why = large_batch_op.is_supported( + config=dataclasses.replace(FLASH, large_batch=False, max_batch=47) + ) + assert not ok and "no large-batch" in why + i32 = torch.int32 + ctx, kv = torch.tensor([4096], dtype=i32), torch.tensor([16384], dtype=i32) + table, sinks = torch.zeros((1, 128), dtype=i32), torch.zeros(64) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + op.precompile(torch.device("cpu"), 4, PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + op.prepare(ctx, kv, table, sinks, config=PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + megakernel_op.prepare(ctx, kv, table, config=PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + large_batch_op.prepare(ctx, sinks, config=PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + hybrid_op.prepare(ctx, kv, table, sinks, config=PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + hybrid_op.precompile(torch.device("cpu"), 8, PRO) + # the hybrid refuses a batch size outside its range before any device work, whichever spec + with pytest.raises(ValueError, match="batch size 4 not in .5, 26."): + hybrid_op.prepare(*_prepare_args(4), config=FLASH_FP4) + with pytest.raises(ValueError, match="no tail-hybrid range"): + hybrid_op.prepare(*_prepare_args(8), config=FLASH) + with pytest.raises(ValueError, match="batch size 27 not in .5, 26."): + hybrid_op.precompile(torch.device("cpu"), 27, FLASH_FP4) + + +def test_missing_production_logits_op_is_a_clear_error(monkeypatch): + """The hybrid resolves the production logits op and its scheduler metadata when first used; a missing one is a + RuntimeError that names it (no fallback).""" + # the custom ops of the build do not register the op + monkeypatch.setitem( + sys.modules, "tensorrt_llm._torch.custom_ops", types.ModuleType("custom_ops_without_k1") + ) + monkeypatch.setattr(torch.ops, "trtllm", types.SimpleNamespace()) + with pytest.raises(RuntimeError, match="cute_dsl_fp4_paged_mqa_logits.*not registered"): + hybrid_op._k1_op() + # the custom ops cannot be imported at all + monkeypatch.setitem(sys.modules, "tensorrt_llm._torch.custom_ops", None) + with pytest.raises(RuntimeError, match="cute_dsl_fp4_paged_mqa_logits.*failed to import"): + hybrid_op._k1_op() + # no scheduler metadata function + monkeypatch.setitem( + sys.modules, "tensorrt_llm.deep_gemm", types.ModuleType("deep_gemm_without") + ) + with pytest.raises(RuntimeError, match="get_paged_mqa_logits_metadata"): + hybrid_op._metadata_fn() + ok, why = hybrid_op.is_supported(config=FLASH_FP4) + assert not ok and why + + +def test_op_is_supported_asks_the_hybrid_for_its_batch_sizes(monkeypatch): + """With a ``batch_size`` that defaults to the tail hybrid, ``op.is_supported`` includes the production logits op + (the device check is stubbed: the answer here is the one of the spec and the batch size).""" + monkeypatch.setattr(op, "check_device", lambda device=None: (True, "")) + monkeypatch.setattr(hybrid_op, "check_device", lambda device=None: (True, "")) + monkeypatch.setattr(hybrid_op, "_k1_op", lambda: None) + monkeypatch.setattr(hybrid_op, "_metadata_fn", lambda: None) + for batch in (None, 1, 4, 5, 26, 27, 1024): + assert op.is_supported(config=FLASH_FP4, batch_size=batch) == (True, "") + + def missing(): + raise RuntimeError("no production logits op") + + monkeypatch.setattr(hybrid_op, "_k1_op", missing) + for batch in (5, 8, 26): + assert op.is_supported(config=FLASH_FP4, batch_size=batch) == ( + False, + "no production logits op", + ) + # outside the hybrid's range, for the FP8 spec and without a batch size the hybrid is not needed + for batch in (None, 1, 4, 27, 1024): + assert op.is_supported(config=FLASH_FP4, batch_size=batch) == (True, "") + assert op.is_supported(config=FLASH, batch_size=8) == (True, "") + ok, why = op.is_supported(config=FLASH_FP4, batch_size=1025) + assert not ok and "batch size 1025" in why + ok, why = op.is_supported(config=PRO, batch_size=8) + assert not ok and "DS-V4-Pro" in why + + +def test_kernels_reject_another_spec(): + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import large_batch, megakernel + + with pytest.raises(NotImplementedError, match="specialized for"): + megakernel.SpecDsaMegakernel(config=PRO) + with pytest.raises(NotImplementedError, match="specialized for"): + large_batch.IndexerKernel(config=PRO) + with pytest.raises(NotImplementedError, match="specialized for"): + large_batch.AttentionTail(config=PRO) + # the kernel constants follow the spec + assert megakernel.K_TOP == large_batch.K_TOP == FLASH.topk + assert megakernel.N_MAX == FLASH.max_index_len + assert (large_batch.HEADS, large_batch.LATENT, large_batch.WINDOW, large_batch.NROWS) == ( + FLASH.attn_heads, + FLASH.kv_dim, + FLASH.window, + FLASH.selected_rows, + ) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_host.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_host.py new file mode 100644 index 000000000000..794eff54462a --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_host.py @@ -0,0 +1,572 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA host side without a GPU: the large-batch CTA schedule and the knob tables of the two specs. + +The CTA schedule (``large_batch_op._schedule``) cuts the rows' concatenated stream units over the 148 CTAs. The FP8 spec +must keep the even split (and the aligned split below 80 rows) exactly, since the schedule is part of what the FP8 +kernels were validated with. The FP4 spec moves the cuts with ``_balance_cuts``: a CTA that streams pieces of several +rows pays a fresh start of the selection for every row it touches, so stream units plus ``_SEG_UNITS`` per row segment +are even. + +The knob tables (``megakernel_op._KNOBS``, ``large_batch_op._KNOBS`` / ``_VARIANTS`` / ``_TAIL_KNOBS``) are what the +kernel objects are built from: the FP8 entries stay the ones of the first specDSA version (identical generated code), +the FP4 entries add the knobs of the FP4 kernels. Building a kernel object needs CuTe DSL (not a GPU) and runs every +constructor check of its knob set. + +The comparisons against ``SPEC_DSA_PR_HEAD_ROOT`` (a checkout of the specDSA version before the FP4 spec was tuned) skip +without it; the independent reference of the large-batch test and the structural checks always run. +""" + +import importlib +import importlib.util +import os +import sys +import zlib +from pathlib import Path + +import numpy as np +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import large_batch_op as op +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import megakernel_op +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import DS_V4_FLASH as FLASH +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import ( + DS_V4_FLASH_FP4 as FLASH_FP4, +) +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import NUM_SMS + +from . import test_cute_dsl_spec_dsa_large_batch as H + +UNIT, MIN_UNITS = op.SCHED_UNIT, op.SCHED_MIN_UNITS +N_MIN, N_MAX = FLASH.min_index_len, FLASH.max_index_len +# The shortest row of MIN_UNITS stream units: from here a row costs its length and can be cut; a shorter row costs +# MIN_UNITS and is never split. +LONG_MIN = (MIN_UNITS - 1) * UNIT + 1 +EDGES = [512, 513, 32512, 32513, 32767, 32768, 32769, 65535, 65536, 131071, 262143, 262144] +BATCHES = [1, 2, 3, 7, 16, 32, 47, 48, 64, 79, 80, 100, 127, 128, 148, 149, 256, 777, 1024] +# Mixtures of row lengths (every mixture exists for every batch size); the "long_*" ones have no row below LONG_MIN. +MIXES = [ + "max", + "min", + "edges", + "short", + "uniform", + "log", + "one_long", + "one_short", + "stair", + "long_uniform", + "long_edges", + "long_log", + "long_stair", + "one_long_rest_long", +] +LONG_MIXES = ["max", "long_uniform", "long_edges", "long_log", "long_stair", "one_long_rest_long"] + + +def _mix(kind, batch): + rng = np.random.RandomState(zlib.crc32(f"{kind}-{batch}".encode())) + if kind == "max": + ns = [N_MAX] * batch + elif kind == "min": + ns = [N_MIN] * batch + elif kind == "edges": + ns = [EDGES[i % len(EDGES)] for i in range(batch)] + elif kind == "short": + ns = rng.randint(N_MIN, N_MIN + 3000, batch) + elif kind == "uniform": + ns = rng.randint(N_MIN, N_MAX + 1, batch) + elif kind == "log": + ns = np.exp(rng.uniform(np.log(N_MIN), np.log(N_MAX), batch)) + elif kind == "one_long": + ns = [N_MAX] + [N_MIN] * (batch - 1) + elif kind == "one_short": + ns = [N_MIN] + [N_MAX] * (batch - 1) + elif kind == "stair": + ns = np.linspace(N_MIN, N_MAX, batch) + elif kind == "long_uniform": + ns = rng.randint(LONG_MIN, N_MAX + 1, batch) + elif kind == "long_edges": + long_edges = [n for n in EDGES if n >= LONG_MIN] + ns = [long_edges[i % len(long_edges)] for i in range(batch)] + elif kind == "long_log": + ns = np.exp(rng.uniform(np.log(LONG_MIN), np.log(N_MAX), batch)) + elif kind == "long_stair": + ns = np.linspace(LONG_MIN, N_MAX, batch) + elif kind == "one_long_rest_long": + ns = [N_MAX] + [LONG_MIN] * (batch - 1) + else: + raise ValueError(kind) + return [int(min(max(n, N_MIN), N_MAX)) for n in ns] + + +def _units(ns): + return -(-np.asarray(ns, dtype=np.int64) // UNIT) + + +def _positions(ns, sched, cost_space=False): + """Position of every schedule entry in the concatenated stream units of the rows. + + The real units of a row are ``ceil(n / UNIT)``; with ``cost_space`` a row shorter than MIN_UNITS units counts + MIN_UNITS (the cost the schedule balances). + """ + units = _units(ns) + work = np.concatenate([[0], np.cumsum(np.maximum(units, MIN_UNITS) if cost_space else units)]) + return work[sched[:, 0].astype(np.int64)] + sched[:, 1] + + +def _check_schedule(sched, ns, num_ctas=NUM_SMS): + """A valid schedule: what the kernels accept (their schedule verdict) and a partition of the stream units. + + Entry s = (row, unit offset in the row) where CTA s starts, entry ``num_ctas`` = (batch, 0). The verdict of the + kernels refuses an entry outside the batch, an offset beyond the row's units, entries that go backwards, and an end + entry other than (batch, 0). + """ + batch = len(ns) + units = _units(ns) + assert sched.shape == (num_ctas + 1, 2) and sched.dtype == np.int32 + row, off = sched[:, 0].astype(np.int64), sched[:, 1].astype(np.int64) + assert (row[0], off[0]) == (0, 0) and (row[-1], off[-1]) == (batch, 0) + assert ((row >= 0) & (row <= batch)).all() and (off >= 0).all() + inside = row < batch + assert (off[~inside] == 0).all() + u_of = units[np.minimum(row, batch - 1)] + assert (off[inside] < np.maximum(u_of[inside], 1)).all(), "offset beyond the row's units" + ahead = (row[1:] > row[:-1]) | ((row[1:] == row[:-1]) & (off[1:] >= off[:-1])) + assert ahead.all(), "entries go backwards" + assert (off[inside & (u_of < MIN_UNITS)] == 0).all(), ( + "a row of fewer than MIN_UNITS units is split" + ) + # every stream unit is read by exactly one CTA + pos = _positions(ns, sched) + assert pos[0] == 0 and pos[-1] == units.sum() and (np.diff(pos) >= 0).all() + cover = np.zeros(int(units.sum()), dtype=np.int32) + for s in range(num_ctas): + cover[pos[s] : pos[s + 1]] += 1 + assert (cover == 1).all(), "a stream unit is read by none or by two CTAs" + + +def _cta_cost(ns, sched, seg_units): + """Per CTA, the modeled cost the FP4 cuts balance: its units (a short row counts MIN_UNITS) plus ``seg_units`` per + row segment it touches; 0 for a CTA without work.""" + pos = _positions(ns, sched, cost_space=True) + units = pos[1:] - pos[:-1] + segs = (sched[1:, 0].astype(np.int64) - sched[:-1, 0]) + (sched[1:, 1] > 0) + return units + seg_units * np.where(units > 0, segs, 0) + + +# -------------------------------------------------------------------------------------------------------------------- +# the reference copy of the specDSA version before the FP4 tuning (skips without it) + + +def _load_pr_head(name): + root = os.environ.get("SPEC_DSA_PR_HEAD_ROOT") + if not root: + pytest.skip( + "SPEC_DSA_PR_HEAD_ROOT (a checkout of the specDSA version before the FP4 tuning) is not set" + ) + pkg_dir = Path(root) / "tensorrt_llm/_torch/attention/kernels/blackwell/spec_dsa" + if not (pkg_dir / "__init__.py").exists(): + pytest.skip(f"no specDSA package under {root}") + alias = "_spec_dsa_pr_head" + if alias not in sys.modules: + spec = importlib.util.spec_from_file_location( + alias, pkg_dir / "__init__.py", submodule_search_locations=[str(pkg_dir)] + ) + pkg = importlib.util.module_from_spec(spec) + sys.modules[alias] = pkg + spec.loader.exec_module(pkg) + return importlib.import_module(f"{alias}.{name}") + + +# -------------------------------------------------------------------------------------------------------------------- +# the CTA schedule + + +@pytest.mark.parametrize("batch", BATCHES) +@pytest.mark.parametrize("spec", [FLASH, FLASH_FP4], ids=["fp8", "fp4"]) +def test_schedule_is_a_valid_partition(spec, batch): + """Every batch size, every mixture: monotone entries the kernels accept, every stream unit read once.""" + seg = op._seg_units(spec, batch) + for kind in MIXES: + ns = _mix(kind, batch) + _check_schedule(op._schedule(ns, NUM_SMS, seg), ns) + + +@pytest.mark.parametrize("num_ctas", [1, 2, 3, 17, 64, NUM_SMS]) +@pytest.mark.parametrize("seg", [0, 14, 38]) +def test_schedule_for_other_cta_counts(num_ctas, seg): + for batch in (1, 2, 5, 40, 80, 200): + for kind in ("uniform", "edges", "one_long", "long_log", "stair"): + ns = _mix(kind, batch) + _check_schedule(op._schedule(ns, num_ctas, seg), ns, num_ctas) + + +@pytest.mark.parametrize("seg", [0, 1, 14, 28, 41, 500]) +@pytest.mark.parametrize("num_ctas", [1, 2, 7, NUM_SMS]) +def test_balance_cuts_are_monotone_and_cover_the_total(num_ctas, seg): + for batch in (1, 2, 9, 100, 1024): + for kind in ("uniform", "edges", "short", "one_long", "long_log"): + ns = _mix(kind, batch) + prefix = np.concatenate([[0], np.cumsum(np.maximum(_units(ns), MIN_UNITS))]) + cuts = op._balance_cuts(prefix, num_ctas, seg) + assert cuts.shape == (num_ctas + 1,) and cuts.dtype == np.int64 + assert cuts[0] == 0 and cuts[-1] == prefix[-1] + assert (np.diff(cuts) >= 0).all() and (cuts >= 0).all() and (cuts <= prefix[-1]).all() + if ( + seg == 0 + ): # without a row segment cost: every CTA gets floor or ceil of the even share + quota = int(prefix[-1]) // num_ctas + assert set(np.diff(cuts).tolist()) <= {quota, quota + 1} + + +def test_balance_cuts_small_cases(): + """Hand-computed: a cut inside the cost jump of a row start moves to that start; otherwise it shifts by the cost.""" + # two rows of 100 units, 2 CTAs, a row segment costs 50: the balanced split is one row per CTA (the even split too) + assert op._balance_cuts(np.array([0, 100, 200]), 2, 50).tolist() == [0, 100, 200] + # three rows of 100, 2 CTAs, a segment costs 10: CTA 0 = row 0 + half of row 1 (2 rows), CTA 1 = the rest (2 rows) + cuts = op._balance_cuts(np.array([0, 100, 200, 300]), 2, 10) + assert cuts.tolist() == [0, 150, 300] + # one row: no row start inside, the even split + assert op._balance_cuts(np.array([0, 1000]), 4, 40).tolist() == [0, 250, 500, 750, 1000] + + +@pytest.mark.parametrize("batch", BATCHES) +def test_fp8_schedule_matches_the_independent_reference(batch): + """The FP8 spec keeps the even split (aligned below 80 rows) exactly, with and without the spec's cost argument.""" + assert op._seg_units(FLASH, batch) == 0 + for kind in MIXES: + ns = _mix(kind, batch) + want = [list(r) for r in H._schedule_reference(ns, NUM_SMS)] + assert op._schedule(ns, NUM_SMS).tolist() == want, kind + assert op._schedule(ns, NUM_SMS, op._seg_units(FLASH, batch)).tolist() == want, kind + + +def test_fp8_schedule_is_the_pr_head_schedule(): + """The same arrays (values and dtype) as the schedule of the version before the FP4 tuning, on a grid of batch + sizes 1 to 160 and larger ones, and the aligned helper on its own.""" + pr = _load_pr_head("large_batch_op") + n_cases = 0 + for batch in list(range(1, 161)) + [200, 256, 333, 512, 777, 1024]: + for kind in MIXES: + ns = _mix(kind, batch) + want = pr._schedule(ns, NUM_SMS) + for got in ( + op._schedule(ns, NUM_SMS), + op._schedule(ns, NUM_SMS, op._seg_units(FLASH, batch)), + ): + assert got.dtype == want.dtype and np.array_equal(got, want), (batch, kind) + n_cases += 1 + if batch < op.SCHED_ALIGN_BATCH and batch <= NUM_SMS: + units = _units(ns) + assert np.array_equal( + op._aligned_schedule(units, NUM_SMS), pr._aligned_schedule(units, NUM_SMS) + ) + assert op._busiest_cta_units(units, want) == pr._busiest_cta_units(units, want) + assert n_cases > 2000 + + +@pytest.mark.parametrize("batch", BATCHES) +def test_fp4_schedule_balances_units_plus_segment_cost(batch): + """The busiest CTA (units + the segment cost of every row it touches) is at most one segment cost plus rounding + above the even share of the total (below 80 rows: and the 3 % slack of the aligned split); a row too short to be cut + (it costs 128 units) can add up to 127 units.""" + seg = op._seg_units(FLASH_FP4, batch) + assert seg > 0 + slack = 1.0 + (op.SCHED_ALIGN_SLACK_PCT / 100 if batch < op.SCHED_ALIGN_BATCH else 0.0) + for kind in MIXES: + ns = _mix(kind, batch) + sched = op._schedule(ns, NUM_SMS, seg) + cost = np.maximum(_units(ns), MIN_UNITS) + share = ( + cost.sum() + seg * (batch - 1) + ) / NUM_SMS # the even share of units + segment costs + cta = _cta_cost(ns, sched, seg) + extra = 0 if kind in LONG_MIXES else MIN_UNITS - 1 + assert cta.max() <= (share + seg + 1.5) * slack + extra, (kind, int(cta.max()), share) + + +@pytest.mark.parametrize("batch", [b for b in BATCHES if b >= op.SCHED_ALIGN_BATCH]) +def test_fp4_cuts_lower_the_busiest_cta_of_mixed_long_rows(batch): + """From 80 rows of at least 128 units: the busiest CTA of the segment-aware cuts costs at most one segment more than + the even split's (the even split has at least the even share), at least one segment less when the lengths differ + (the even split cuts at arbitrary units, and a CTA that touches many rows pays for each), and the CTAs with work are + within two segment costs of each other.""" + seg = op._seg_units(FLASH_FP4, batch) + for kind in LONG_MIXES: + ns = _mix(kind, batch) + balanced = _cta_cost(ns, op._schedule(ns, NUM_SMS, seg), seg) + even = _cta_cost(ns, op._schedule(ns, NUM_SMS, 0), seg) + assert balanced.max() <= even.max() + seg + 1, (kind, int(balanced.max()), int(even.max())) + if kind in ("long_uniform", "long_edges", "long_log", "long_stair"): + assert balanced.max() + seg <= even.max(), (kind, int(balanced.max()), int(even.max())) + if batch <= NUM_SMS: + assert balanced.max() - balanced.min() <= 2 * seg + 3, ( + kind, + balanced.min(), + balanced.max(), + ) + + +def test_segment_cost_table(): + """No cost for the FP8 spec; for FP4 the points (batch size, units) joined linearly and clamped at both ends.""" + assert op._SEG_UNITS.keys() <= {FLASH_FP4.kernel_key} + assert all(op._seg_units(FLASH, b) == 0 for b in (0, 1, 47, 48, 148, 1024, 5000)) + points = op._SEG_UNITS[FLASH_FP4.kernel_key] + assert [b for b, _ in points] == sorted({b for b, _ in points}) + for b, units in points: + assert op._seg_units(FLASH_FP4, b) == units + assert ( + op._seg_units(FLASH_FP4, 0) == points[0][1] + and op._seg_units(FLASH_FP4, 4000) == points[-1][1] + ) + for (b0, u0), (b1, u1) in zip(points[:-1], points[1:]): + for b in range(b0, b1 + 1): + want = u0 + (u1 - u0) * (b - b0) / (b1 - b0) + assert abs(op._seg_units(FLASH_FP4, b) - want) <= 0.5, b + assert min(u0, u1) <= op._seg_units(FLASH_FP4, (b0 + b1) // 2) <= max(u0, u1) + assert [op._seg_units(FLASH_FP4, b) for b in (64, 82, 100, 114, 128, 192, 256)] == [ + 14, + 19, + 24, + 31, + 38, + 33, + 28, + ] + + +# -------------------------------------------------------------------------------------------------------------------- +# the knob tables + + +def _kernel(spec, batch): + """The megakernel object of a batch size (CuTe DSL import, no GPU: building it runs the constructor checks).""" + return megakernel_op._engine(torch.device("cuda", 0), batch, spec)["kernel"] + + +def _desc_params_pr_head(kernel, batch_size, row): + """``_desc_params`` of the version before the FP4 tuning.""" + shared = batch_size > int(kernel.nteams) + zlast = shared and ( + (kernel.tsz and row == batch_size - 1) or (kernel.tsz2 and row >= batch_size - 2) + ) + zc = -1 + if shared and kernel.tsz01 and (row < 2 or (kernel.tszall and row < batch_size - 2)): + zc = (kernel.ns - 2) if row < 2 else (kernel.ns - 2 - row // 2) + return (row * int(kernel.drot)) % kernel.ns, bool(zlast), int(zc) + + +def test_megakernel_knob_tables(): + for spec in (FLASH, FLASH_FP4): + table = megakernel_op._KNOBS[spec.kernel_key] + assert ( + sorted(table) + == list(megakernel_op.supported_batch_sizes(spec)) + == list(range(1, spec.megakernel_max_batch + 1)) + ) + fp8, fp4 = megakernel_op._KNOBS[FLASH.kernel_key], megakernel_op._KNOBS[FLASH_FP4.kernel_key] + assert sorted(fp8) == list(range(1, 48)) and sorted(fp4) == list(range(1, 21)) + # the FP8 sets have none of the FP4 knobs (the generated code of the FP8 kernels is the first version's) + assert all("tcta" not in k and "drot" not in k for k in fp8.values()) + # one to four rows: the FP8 sets plus the FP4 start / row-boundary knobs of ``_FP4_SMALL``; from five rows the FP4 + # sets add the shared-team knobs + for b in range(1, 5): + small = megakernel_op._FP4_SMALL.get(b, {}) + assert {x: v for x, v in fp4[b].items() if x not in small} == { + x: v for x, v in fp8[b].items() if x not in small + }, b + assert all(fp4[b][x] == v for x, v in small.items()), b + thr = {"lbin": True, "tpoll1": True} + assert megakernel_op._FP4_SMALL == { + 1: { + "early": True, + "tearly": True, + "lpoll": True, + "lfence": True, + "cls4": True, + **thr, + }, + 2: { + "dpf": True, + "drot": 37, + "b1l": True, + "b1l_pub": True, + "b1l_upub": 3, + **thr, + }, + 3: {"dpf": True, "drot": 37, "b1l": True, "b1l_u": 3, **thr}, + 4: {"dpf": True, "drot": 37, **thr}, + } + for b in range(5, 21): + k = fp4[b] + assert (k["team4"], k["nteams"], k["tcta"], k["b1l_upub"], k["rs24_dry"]) == ( + True, + 4, + 2, + 3, + False, + ), b + assert k["drot"] > 0 and k.get("ring", False) == (b >= 9), b + # five to eight rows: the T lead's 256-bin rank search (lbin) on top of the shared-team set, and at eight rows + # the last row's candidate publish four per lane; everything else is the FP8 set of the batch size + mid = {"lbin": True} if b <= 8 else {} + if b == 8: + mid["b1l_u"] = 4 + skip = set(megakernel_op._FP4_SHARED) | set(mid) + assert {x: v for x, v in k.items() if x not in skip} == { + x: v for x, v in fp8[b].items() if x not in skip + }, b + assert all(k[x] == v for x, v in mid.items()), b + + +def _fp8_teams(b): + """Teams of the FP8 knob sets: one per row up to 4 rows, two shared teams above.""" + return b if b <= 4 else 2 + + +def test_megakernel_kernel_objects_build_for_every_batch_size(): + """Each knob set passes the constructor checks of its kernel; the FP4 sets use the FP4 front end.""" + pytest.importorskip("cutlass.cute") + for spec in (FLASH, FLASH_FP4): + for b in megakernel_op.supported_batch_sizes(spec): + k = _kernel(spec, b) + assert k.nrows == b and k.fp4 == (spec is FLASH_FP4) + assert k.ns % 2 == 0 and k.ns <= 148 + assert k.tcta == (2 if spec is FLASH_FP4 and b >= 5 else 0) + assert k.nteams == (4 if spec is FLASH_FP4 and b >= 5 else _fp8_teams(b)) + # CTAs: stream + teams + T servers = the grid + assert k.ns + k.team_ctas * k.nteams + k.tcta == 148 + + +def test_desc_params_of_the_fp8_spec_are_unchanged(): + """The rotation / early-threshold parameters of every row of every FP8 batch size are the old ones; the FP4 + spec's rows rotate over 8 distinct offsets and never use the early-threshold variants (dedicated T servers).""" + pytest.importorskip("cutlass.cute") + for b in megakernel_op.supported_batch_sizes(FLASH): + k = _kernel(FLASH, b) + for r in range(b): + assert megakernel_op._desc_params(k, b, r) == _desc_params_pr_head(k, b, r), (b, r) + for b in range(5, 21): + k = _kernel(FLASH_FP4, b) + params = [megakernel_op._desc_params(k, b, r) for r in range(b)] + assert len({p[0] for p in params}) == min(b, 8), b + assert all(p[0] == (r % 8) * int(k.drot) % k.ns for r, p in enumerate(params)) + assert all((p[1], p[2]) == (False, -1) for p in params), b + for b in range(1, 5): + k = _kernel(FLASH_FP4, b) + assert [megakernel_op._desc_params(k, b, r) for r in range(b)] == [ + _desc_params_pr_head(k, b, r) for r in range(b) + ] + + +def test_fp8_knob_tables_are_the_pr_head_tables(): + pr_mo = _load_pr_head("megakernel_op") + assert megakernel_op._KNOBS[FLASH.kernel_key] == pr_mo._KNOBS[FLASH.kernel_key] + assert megakernel_op._BASE == pr_mo._BASE and megakernel_op._CONFIGS == pr_mo._CONFIGS + pr_lb = _load_pr_head("large_batch_op") + assert op._KNOBS[FLASH.kernel_key] == pr_lb._KNOBS[FLASH.kernel_key] + assert op._KERNEL_CONFIG == pr_lb._KERNEL_CONFIG + + +def test_large_batch_knob_tables(): + """FP8: one knob set, no variants, no tail knobs. FP4: its knobs, the variants (from the first large-batch size, + 192 and 768 rows), the tail knobs.""" + assert op._KNOBS[FLASH.kernel_key] == op._KERNEL_CONFIG + assert FLASH.kernel_key not in op._VARIANTS and FLASH.kernel_key not in op._TAIL_KNOBS + assert FLASH.kernel_key not in op._SEG_UNITS + fp4 = op._KNOBS[FLASH_FP4.kernel_key] + assert fp4["kv_stages"] == 8 and fp4["merge1"] == 2 and fp4["trig0"] == 1536 + assert all(fp4[k] for k in ("fast_verdict", "sel_fast", "cmp_fast", "sel_hand2")) + # the knobs the FP8 set does not have are exactly the FP4 additions + added = {k for k in fp4 if k not in op._KERNEL_CONFIG} + assert added == { + "merge1", + "fast_verdict", + "sel_fast", + "cmp_fast", + "sel_hand2", + "lim_loop", + "lim_loop2", + "nolock", + "floor_mask", + } + # the loop-control knobs, the UMMA lockstep and the floor interval are off in the base table (the shipped + # behaviour below the first variant) and on only in the variants + assert not any(fp4[k] for k in ("lim_loop", "lim_loop2", "nolock")) and fp4["floor_mask"] == 6 + variants = op._VARIANTS[FLASH_FP4.kernel_key] + firsts = [first for first, _ in variants] + assert firsts == sorted(set(firsts)) and firsts[0] > FLASH_FP4.megakernel_max_batch + assert all(first <= FLASH_FP4.max_batch for first in firsts) + for _, over in variants: + assert set(over) <= set(fp4), "a variant overrides a knob of the kernel" + assert all(over[k] != fp4[k] for k in over), ( + "a variant that changes nothing is a second compile for nothing" + ) + assert op._TAIL_KNOBS[FLASH_FP4.kernel_key] == {"exit_early": True, "wide_store": True} + + +def _three_term_loop(start, num_kv, q_is_end, end_kv_idx): + """The tile indices of a segment under the shipped loop condition (a do-while that steps by two).""" + out, kv = [], start + while True: + out.append(kv) + kv += 2 + if not ((kv < num_kv) and (not q_is_end or kv != end_kv_idx)): + return out + + +def _limit_loop(start, num_kv, q_is_end, end_kv_idx): + """The same segment under ``lim_loop`` / ``lim_loop2``: one compare against ``_kv_limit`` computed at the start.""" + lim = (num_kv + 1) & -2 + if q_is_end: + lim = end_kv_idx + lim = max(lim, start + 2) + out, kv = [], start + while True: + out.append(kv) + kv += 2 + if not kv < lim: + return out + + +def test_kv_limit_loop_matches_the_three_term_condition(): + """kv_idx is even and steps by two, so ``kv_idx < kv_lim`` visits exactly the tiles of the three-term condition.""" + rng = np.random.default_rng(1234) + for _ in range(20000): + num_kv = int(rng.integers(1, 2049)) + q_is_end = bool(rng.integers(0, 2)) + start = 2 * int(rng.integers(0, (num_kv + 1) // 2 + 1)) if num_kv > 1 else 0 + start = min(start, num_kv - 1 if num_kv % 2 else num_kv - 2) if num_kv > 1 else 0 + if q_is_end: + end_kv_idx = 2 * int(rng.integers(start // 2 + 1, (num_kv + 1) // 2 + 1)) + else: + end_kv_idx = 0 + assert _three_term_loop(start, num_kv, q_is_end, end_kv_idx) == _limit_loop( + start, num_kv, q_is_end, end_kv_idx + ), (start, num_kv, q_is_end, end_kv_idx) + + +def test_large_batch_kernel_objects_build(): + """The indexer kernel and the attention tail of both specs, and every variant, pass their constructor checks.""" + pytest.importorskip("cutlass.cute") + lb, _ = op._kernel_modules() + for spec in (FLASH, FLASH_FP4): + knobs = op._KNOBS[spec.kernel_key] + lb.IndexerKernel(num_sms=NUM_SMS, config=spec, **knobs) + for _, over in op._VARIANTS.get(spec.kernel_key, ()): + lb.IndexerKernel(num_sms=NUM_SMS, config=spec, **{**knobs, **over}) + lb.AttentionTail(config=spec, **op._TAIL_KNOBS.get(spec.kernel_key, {})) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_large_batch.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_large_batch.py new file mode 100644 index 000000000000..819e96117ed0 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_large_batch.py @@ -0,0 +1,753 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA large-batch kernels (CuTe DSL, SM100) against an fp64 reference of the DeepSeek-V4-Flash decode chain, +for the FP8 and the MXFP4 indexer K cache (the ``idx`` fixture). + +A batch is built from a few distinct base rows (own queries, indexer K pages, compressed KV rows, length); row ``b`` +uses base ``b % len(bases)`` and its own window pages and attention query, so a 1,024-row batch needs the memory of +a handful of rows. Every row's top-512 set and attention output is checked. Bases get an opened K-th gap (so the +set is well defined), planted exact ties or all-equal logits; an attention mode in which every score is bit-equal +makes one wrong KV row visible far above the bf16 noise. +""" + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import DS_V4_FLASH as SPEC +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import ( + DS_V4_FLASH_FP4 as SPEC_FP4, +) +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import NUM_SMS +from tensorrt_llm._utils import get_sm_version + +# The shapes under test are those of the spec (``config.py``); test_cute_dsl_spec_dsa_config.py pins its values. +K_TOP, H_IDX, D_IDX = SPEC.topk, SPEC.index_heads, SPEC.index_head_dim +H_ATT, D_ATT = SPEC.attn_heads, SPEC.kv_dim +# compressed / SWA rows per page, window, compress ratio +TPB_C, TPB_SWA, WINDOW, RATIO = ( + SPEC.kv_page_rows, + SPEC.swa_page_rows, + SPEC.window, + SPEC.compress_ratio, +) +PAGE_BYTES = SPEC.index_page_bytes # 32 x 128 e4m3 values, then 32 fp32 scales +N_MAX = SPEC.max_index_len +SM_SCALE = SPEC.default_softmax_scale + +# Lengths around the schedule's granule (256 tokens, 128 units = 32,768 tokens) and the limits. +LENGTHS = [ + 262144, + 512, + 100003, + 33000, + 8197, + 262143, + 4097, + 70000, + 1000, + 131072, + 32768, + 32769, + 513, + 200000, + 24576, + 65535, +] + + +def _op(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import large_batch_op as op + + return op + + +def _supported() -> bool: + return torch.cuda.is_available() and get_sm_version() == 100 and _op().is_supported()[0] + + +pytestmark = pytest.mark.skipif( + not _supported(), reason="persistent 148-CTA kernel, qualified on B200 only" +) + + +@pytest.fixture(params=["fp8", "fp4"]) +def idx(request): + """The indexer K cache dtype under test.""" + return request.param + + +def _cdiv(a, b): + return (a + b - 1) // b + + +def _e4m3(x): + return x.clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + + +def _ue8m0(amax): + return torch.exp2(torch.ceil(torch.log2(amax.clamp_min(1e-30) / 448.0))) + + +_E2M1 = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0] + + +def _spec_of(idx): + return SPEC_FP4 if idx == "fp4" else SPEC + + +def _fp4_quantize(x): + """[M, 128] fp32 -> (E2M1 codes packed low nibble first uint8 [M, 64], UE8M0 exponents uint8 [M, 4], dequantized + fp32 [M, 128]). + + One power-of-two scale per 32 values: the smallest 2**e with amax / 2**e <= 6. + """ + m = x.shape[0] + blocks = x.reshape(m, 4, 32) + exp = torch.ceil(torch.log2(blocks.abs().amax(-1).clamp_min(1e-30) / 6.0)).clamp(-126, 127) + y = blocks / torch.exp2(exp)[..., None] + edges = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0], device=x.device) + code = torch.bucketize(y.abs(), edges).to(torch.uint8) + code = (code | (((y < 0) & (code != 0)).to(torch.uint8) << 3)).reshape(m, 128) + packed = (code[:, 0::2] | (code[:, 1::2] << 4)).contiguous() + lut = torch.tensor(_E2M1, device=x.device) + deq = (lut[code.long()].reshape(m, 4, 32) * torch.exp2(exp)[..., None]).reshape(m, 128) + return packed, (exp + 127).to(torch.uint8), deq + + +def _ref_topk(lg): + v, idx = torch.sort(lg, descending=True, stable=True) + tied = lg.numel() > K_TOP and bool(v[K_TOP - 1] == v[K_TOP]) + return idx[:K_TOP], v[:K_TOP], tied + + +@torch.no_grad() +def _ref_attention(inp, b, sel, scale): + """fp64 sparse MLA over the 128 window rows and the selected compressed rows, sink in the denominator.""" + pos = int(inp["kv_lens"][b]) - 1 + p = torch.arange(pos - WINDOW + 1, pos + 1, device=sel.device) + swa_rows = inp["bt_swa"][b, p // TPB_SWA].long() * TPB_SWA + p % TPB_SWA + c_rows = inp["bt_c"][b, sel // TPB_C].long() * TPB_C + sel % TPB_C + swa = inp["swa_pool"].view(torch.uint8).reshape(-1, D_ATT) + cpl = inp["c_pool"].view(torch.uint8).reshape(-1, D_ATT) + kv = torch.cat([swa[swa_rows], cpl[c_rows]], 0).view(torch.float8_e4m3fn).double() + q = inp["q_att"][b].view(H_ATT, D_ATT).double() + s = (q @ kv.t()) * scale + m = s.amax(-1, keepdim=True) + e = torch.exp(s - m) + den = e.sum(-1, keepdim=True) + torch.exp(inp["sinks"].double().view(-1, 1) - m) + return (e @ kv) / den + + +def _calc_diff(x, y): + x, y = x.double(), y.double() + den = (x * x + y * y).sum() + return 0.0 if float(den) == 0.0 else float(1.0 - 2.0 * (x * y).sum() / den) + + +def _open_gap(lg, sc, gap_rel, above=False): + """Scale the scores just below rank 512 by an exact power of two until the K-th gap exceeds fp32 noise. + + above: also lift the winners within the margin of the K-th value. A tie group planted at that value is not told + apart from such a winner in fp32, so the kernel may take either. + """ + if lg.numel() <= K_TOP: # every position is selected + return + for _ in range(8): + v, order = torch.sort(lg, descending=True, stable=True) + kth, nxt = float(v[K_TOP - 1]), float(v[K_TOP]) + margin = gap_rel * max(1.0, abs(kth)) + up = order[: K_TOP - 1][v[: K_TOP - 1] < kth + margin] if above else order[:0] + if kth - nxt >= margin and not up.numel(): + return + band = order[K_TOP:][v[K_TOP:] > kth - margin] + if kth > 4 * margin: + f = 0.25 + elif kth < -margin and not (above and kth > -4 * margin): + f = 4.0 + else: + raise RuntimeError("K-th logit too close to 0: pick another seed") + sc[band] *= f + lg[band] *= f + sc[up] /= f # exact; the winners move away from the K-th value + lg[up] /= f + raise RuntimeError("could not open the K-th gap") + + +@torch.no_grad() +def _make_base(n, seed, ties=0, flat=False, idx="fp8", neg=False): + """One distinct row: indexer query and weights, K pages (whole 128-row tiles) with their fp64 logits. + + ties: copies the K-th position's K row onto ``ties`` losers (an exact tie group at the K-th value, with the gap + above it opened as well). + flat: every position shares one K row (every logit equal). + neg: every head weight is negative, so every logit is <= 0 (the K-th logit and the boundary of every in-stream + compaction of the kernels lie below zero). + """ + if idx == "fp4": + return _make_base_fp4(n, seed, ties, flat, neg) + dev = torch.device("cuda") + gh = torch.Generator().manual_seed(seed) + gd = torch.Generator(device=dev).manual_seed(seed + 1) + q = _e4m3(torch.randn(H_IDX, D_IDX, generator=gd, device=dev) * 2.0) + w = (torch.randn(H_IDX, generator=gd, device=dev) * (D_IDX * H_IDX) ** -0.5).float() + if neg: + w = -(w.abs() + 0.25 * (D_IDX * H_IDX) ** -0.5) + pg = _cdiv(n, 128) * (128 // TPB_C) + npad = pg * TPB_C + kf = torch.randn(npad, D_IDX, generator=gd, device=dev) * torch.exp( + 0.5 * torch.randn(npad, 1, generator=gd, device=dev) + ) + if flat: + kf = kf[:1].repeat(npad, 1) + sc = _ue8m0(kf.abs().amax(-1)) + k8u = _e4m3(kf / sc[:, None]).view(torch.uint8) + k8 = k8u.view(torch.float8_e4m3fn) + lg = (k8[:n].double() @ q.double().t()).clamp_min(0.0) @ w.double() * sc[:n].double() + if not flat: + _open_gap(lg, sc, 1e-4, above=bool(ties)) + if ties: + order = torch.sort(lg, descending=True, stable=True).indices + src = int(order[K_TOP - 1]) + losers = order[K_TOP:] + dst = losers[torch.randperm(losers.numel(), generator=gh)[:ties].to(dev)] + k8u[dst] = k8u[src].clone() + sc[dst] = sc[src].clone() + lg[dst] = lg[src].clone() + top1 = int(torch.argmax(lg)) + if npad > n: # positions >= n get scores above every real one and must be ignored + k8u[n:] = k8u[top1].clone() + sc[n:] = sc[top1] * (256.0 if float(lg[top1]) > 0 else 1.0 / 256.0) + pages = torch.empty((pg, PAGE_BYTES), dtype=torch.uint8, device=dev) + pages[:, : TPB_C * D_IDX] = k8u.reshape(pg, TPB_C * D_IDX) + pages[:, TPB_C * D_IDX :] = sc.float().contiguous().view(torch.uint8).reshape(pg, TPB_C * 4) + ref_sel, ref_v, tied = _ref_topk(lg) + return { + "n": n, + "q_idx": q, + "w_idx": w, + "pages": pages, + "lg": lg, + "ref_sel": torch.sort(ref_sel).values, + "ref_v": ref_v, + "tied": tied, + } + + +@torch.no_grad() +def _make_base_fp4(n, seed, ties=0, flat=False, neg=False): + """_make_base for the FP4 cache: E2M1 K rows and queries with UE8M0 scales; the gap opening and the planted ties + act on the scale exponents. + """ + dev = torch.device("cuda") + gh = torch.Generator().manual_seed(seed) + gd = torch.Generator(device=dev).manual_seed(seed + 1) + q_codes, q_sf, q_deq = _fp4_quantize(torch.randn(H_IDX, D_IDX, generator=gd, device=dev) * 2.0) + w = (torch.randn(H_IDX, generator=gd, device=dev) * (D_IDX * H_IDX) ** -0.5).float() + if neg: + w = -(w.abs() + 0.25 * (D_IDX * H_IDX) ** -0.5) + pg = _cdiv(n, 128) * (128 // TPB_C) + npad = pg * TPB_C + kf = torch.randn(npad, D_IDX, generator=gd, device=dev) * torch.exp( + 0.5 * torch.randn(npad, 1, generator=gd, device=dev) + ) + if flat: + kf = kf[:1].repeat(npad, 1) + k_codes, k_sf, k_deq = _fp4_quantize(kf) + sc = torch.ones( + npad, device=dev + ) # exact power-of-two multiplier per position, folded into the exponents at the end + lg = (k_deq[:n].double() @ q_deq.double().t()).clamp_min(0.0) @ w.double() + if not flat: + _open_gap(lg, sc, 1e-4, above=bool(ties)) + if ties: + order = torch.sort(lg, descending=True, stable=True).indices + src = int(order[K_TOP - 1]) + losers = order[K_TOP:] + dst = losers[torch.randperm(losers.numel(), generator=gh)[:ties].to(dev)] + k_codes[dst] = k_codes[src].clone() + k_sf[dst] = k_sf[src].clone() + sc[dst] = sc[src].clone() + lg[dst] = lg[src].clone() + top1 = int(torch.argmax(lg)) + if npad > n: # positions >= n get scores above every real one and must be ignored + k_codes[n:] = k_codes[top1].clone() + k_sf[n:] = k_sf[top1].clone() + sc[n:] = sc[top1] * (256.0 if float(lg[top1]) > 0 else 1.0 / 256.0) + shift = torch.round(torch.log2(sc)).to(torch.int32) + k_sf = (k_sf.to(torch.int32) + shift[:, None]).clamp(1, 254).to(torch.uint8) + pages = torch.empty((pg, SPEC_FP4.index_page_bytes), dtype=torch.uint8, device=dev) + pages[:, : TPB_C * (D_IDX // 2)] = k_codes.reshape(pg, TPB_C * (D_IDX // 2)) + pages[:, TPB_C * (D_IDX // 2) :] = k_sf.reshape(pg, TPB_C * (D_IDX // 32)) + ref_sel, ref_v, tied = _ref_topk(lg) + return { + "n": n, + "q_idx": q_codes, + "q_scale": q_sf.contiguous().view(torch.int32).reshape(H_IDX), + "w_idx": w, + "pages": pages, + "lg": lg, + "ref_sel": torch.sort(ref_sel).values, + "ref_v": ref_v, + "tied": tied, + } + + +@torch.no_grad() +def _make_case(batch, specs, seed, attn="realistic", idx="fp8"): + """Inputs for ``batch`` rows; row b uses base ``b % len(specs)``. specs: dicts of n, ties, flat, neg.""" + dev = torch.device("cuda") + gh = torch.Generator().manual_seed(seed) + gd = torch.Generator(device=dev).manual_seed(seed + 7) + nb = len(specs) + bases = [ + _make_base( + s["n"], seed + 100 * j, s.get("ties", 0), s.get("flat", False), idx, s.get("neg", False) + ) + for j, s in enumerate(specs) + ] + k_off, off = [], 0 + for bs in bases: + k_off.append(off) + off += bs["pages"].shape[0] + spare_k = off + k_cache = torch.cat([bs["pages"] for bs in bases] + [bases[0]["pages"][:1]]) + idx_bt = torch.full( + (batch, _cdiv(max(b["pages"].shape[0] for b in bases), 4) * 4), spare_k, dtype=torch.int32 + ) + for b in range(batch): + j = b % nb + pg = bases[j]["pages"].shape[0] + idx_bt[b, :pg] = torch.arange(pg, dtype=torch.int32) + k_off[j] + ns = [bases[b % nb]["n"] for b in range(batch)] + kv_lens = [RATIO * n + int(torch.randint(0, RATIO, (1,), generator=gh)) for n in ns] + q_idx = torch.stack([bases[b % nb]["q_idx"] for b in range(batch)]).unsqueeze(1) + w_idx = torch.stack([bases[b % nb]["w_idx"] for b in range(batch)]) + + def rnd(*shape): + return torch.randn(*shape, generator=gd, device=dev) + + if attn == "gather_exact": + # scores depend only on dims [0, 64), shared by every KV row of a base + q_att = torch.randint(-2, 3, (batch, H_ATT, D_ATT), generator=gd, device=dev).float() * 0.25 + q_att[:, :, 64:] = 0.0 + key = torch.randint(-2, 3, (nb, 64), generator=gd, device=dev).float() * 0.25 + else: + q_att = rnd(batch, H_ATT, D_ATT) + q_att = _e4m3(q_att).reshape(batch, H_ATT * D_ATT) + + def kv_rows(j, r): + x = rnd(r, D_ATT) + if attn == "gather_exact": + x[:, :64] = key[j] + return _e4m3(x).view(torch.uint8) + + poison = torch.full((D_ATT,), 448.0, device=dev) + poison[:64] = -448.0 + poison = _e4m3(poison).view(torch.uint8) + n_swa = 2 * batch + 1 # two window pages per row, then a poison spare + swa_pool = torch.empty((n_swa, TPB_SWA, D_ATT), dtype=torch.uint8, device=dev) + swa_pool[n_swa - 1] = poison + perm_s = torch.randperm(2 * batch, generator=gh) + bt_swa = torch.full((batch, max(kv_lens) // TPB_SWA + 1), n_swa - 1, dtype=torch.int32) + for b in range(batch): + hi = (kv_lens[b] - 1) // TPB_SWA + for t, blk in enumerate((hi - 1, hi)): + pgs = int(perm_s[2 * b + t]) + if blk >= 0: + bt_swa[b, blk] = pgs + swa_pool[pgs] = kv_rows(b % nb, TPB_SWA) + pg_c = [_cdiv(bs["n"], TPB_C) for bs in bases] + c_off = [sum(pg_c[:j]) for j in range(nb)] + n_c = sum(pg_c) + 1 + c_pool = torch.empty((n_c, TPB_C, D_ATT), dtype=torch.uint8, device=dev) + c_pool[n_c - 1] = poison + for j in range(nb): + c_pool[c_off[j] : c_off[j] + pg_c[j]] = kv_rows(j, pg_c[j] * TPB_C).view( + pg_c[j], TPB_C, D_ATT + ) + bt_c = torch.full((batch, _cdiv(max(pg_c), 4) * 4), n_c - 1, dtype=torch.int32) + for b in range(batch): + j = b % nb + bt_c[b, : pg_c[j]] = torch.arange(pg_c[j], dtype=torch.int32) + c_off[j] + sinks = (torch.linspace(-6.0, 9.0, H_ATT, device=dev) + 0.1 * rnd(H_ATT)).float() + inp = { + "q_idx": q_idx, + "w_idx": w_idx.contiguous(), + "k_cache": k_cache.view(-1, TPB_C, 1, _spec_of(idx).index_page_bytes // TPB_C), + "idx_block_table": idx_bt.to(dev), + "ctx_lens": torch.tensor(ns, dtype=torch.int32, device=dev), + "kv_lens": torch.tensor(kv_lens, dtype=torch.int32, device=dev), + "q_att": q_att, + "swa_pool": swa_pool.view(torch.float8_e4m3fn), + "bt_swa": bt_swa.to(dev), + "c_pool": c_pool.view(torch.float8_e4m3fn), + "bt_c": bt_c.to(dev), + "sinks": sinks.contiguous(), + } + if idx == "fp4": + inp["q_scale"] = torch.stack([bases[b % nb]["q_scale"] for b in range(batch)]) + return inp, bases + + +def _launch(op, state, inp, topk, out, scale=SM_SCALE): + op.run( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["kv_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + topk, + out, + softmax_scale=scale, + **({"q_scale": inp["q_scale"]} if "q_scale" in inp else {}), + ) + + +def _check_selection(bases, topk): + """Every row's top-512: inside [0, n), no duplicate, the reference set (the value multiset for rows with ties).""" + nb = len(bases) + for b in range(topk.shape[0]): + base = bases[b % nb] + sel = topk[b].long() + n = base["n"] + assert bool(((sel >= 0) & (sel < n)).all()), f"row {b}: index outside [0, n)" + s = torch.sort(sel).values + assert not bool((s[1:] == s[:-1]).any()), f"row {b}: duplicate index" + if base["tied"]: + got = torch.sort(base["lg"][sel], descending=True).values + assert torch.equal(got, base["ref_v"]), f"row {b}: top-512 value multiset differs" + else: + assert torch.equal(s, base["ref_sel"]), f"row {b}: top-512 set differs" + + +def _check_rows(inp, bases, topk, out, attn, scale=SM_SCALE): + _check_selection(bases, topk) + for b in range(topk.shape[0]): + ref = _ref_attention(inp, b, topk[b].long(), scale) + o = out[b].view(H_ATT, D_ATT).double() + assert bool(torch.isfinite(o).all()), f"row {b}: non-finite output" + if attn == "gather_exact": + cd = _calc_diff(o[:, 64:], ref[:, 64:]) + assert cd < 2e-5, f"row {b}: calc_diff {cd:.3e}" + assert float((o - ref).abs().max()) <= 2.0**-6 * float(ref.abs().max()) + else: + cd = _calc_diff(o, ref) + assert cd < 1e-3, f"row {b}: calc_diff {cd:.3e}" + + +def _new_outputs(batch): + dev = torch.device("cuda") + topk = torch.full((batch, K_TOP), -5, dtype=torch.int32, device=dev) + out = torch.zeros((batch, H_ATT * D_ATT), dtype=torch.bfloat16, device=dev) + return topk, out + + +def _plain(ns): + return [{"n": n} for n in ns] + + +@pytest.mark.parametrize("batch", [1, 7, 100, 148, 149, 256, 777, 1024]) +def test_mixed_lengths(batch, idx): + op = _op() + inp, bases = _make_case(batch, _plain(LENGTHS), seed=11, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, out = _new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + + +@pytest.mark.parametrize("batch", [256, 1024]) +def test_uniform_long_rows(batch, idx): + op = _op() + inp, bases = _make_case(batch, _plain([N_MAX - 17] * 4 + [N_MAX] * 4), seed=23, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, out = _new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + + +def test_gather_exact(idx): + op = _op() + batch = 256 + inp, bases = _make_case(batch, _plain(LENGTHS), seed=31, attn="gather_exact", idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, out = _new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + _check_rows(inp, bases, topk, out, "gather_exact") + + +def test_ties_and_all_equal_rows(idx): + op = _op() + batch = 256 + specs = [ + {"n": 100000, "ties": 3}, + {"n": 262144, "ties": 6000}, + {"n": 5000, "flat": True}, + {"n": 262143, "flat": True}, + {"n": 700, "ties": 100}, + {"n": 512}, + {"n": 90000}, + {"n": 40000, "ties": 600}, + ] + inp, bases = _make_case(batch, specs, seed=41, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, out = _new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + _check_rows(inp, bases, topk, out, "realistic") + + +@pytest.mark.parametrize("batch", [32, 100, 256]) +def test_negative_logits(batch, idx): + """Rows whose logits are all <= 0: the selection must not depend on the sign of the K-th logit (a compaction whose + boundary bin lies below zero used to give a floor of 0xFFFFFFFF when the order-preserving float keys were reduced + with a signed minimum: the rest of the stream was dropped).""" + op = _op() + inp, bases = _make_case(batch, [{"n": n, "neg": True} for n in LENGTHS], seed=57, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, out = _new_outputs(batch) + # which part of the stream the signed minimum drops depends on the timing of the compactions: several launches + for launch in range(6): + topk.fill_(-5) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + if launch < 2: + _check_rows(inp, bases, topk, out, "realistic") + else: + _check_selection(bases, topk) + + +def test_state_reuse_across_steps(idx): + """One state serves several steps with different lengths; prepare refreshes the schedule in place.""" + op = _op() + batch = 256 + state = None + topk, out = _new_outputs(batch) + for step, ns in enumerate((LENGTHS, LENGTHS[5:] + LENGTHS[:5], [N_MAX] * 8)): + inp, bases = _make_case(batch, _plain(ns), seed=50 + step, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], state, config=_spec_of(idx)) + for _ in range(2): # a repeated launch on the same step + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + + +def test_stale_schedule_is_refused(idx): + op = _op() + batch = 256 + inp, bases = _make_case(batch, _plain(LENGTHS), seed=61, idx=idx) + other = torch.tensor([LENGTHS[(b + 3) % len(LENGTHS)] for b in range(batch)], dtype=torch.int32) + state = op.prepare(other, inp["sinks"], config=_spec_of(idx)) # a schedule for other lengths + topk, out = _new_outputs(batch) + out.fill_(5.0) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) & op.ERR_SCHEDULE + assert bool((topk == -1).all()) and bool((out.float() == 0).all()) + state = op.prepare( + inp["ctx_lens"].cpu(), inp["sinks"], state, config=_spec_of(idx) + ) # refreshed: the launch recovers + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + + +def test_cuda_graph_replay(idx): + """One captured launch replays over several steps; lengths change in place and prepare refreshes the schedule.""" + op = _op() + batch = 256 + steps = [ + LENGTHS[r:] + LENGTHS[:r] for r in (0, 5, 9) + ] # same pool sizes, other rows get other lengths + inp, bases = _make_case(batch, _plain(steps[0]), seed=71, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + op.precompile(torch.device("cuda"), _spec_of(idx)) + topk, out = _new_outputs(batch) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + _launch(op, state, inp, topk, out) # warm-up + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + _launch(op, state, inp, topk, out) + for step, ns in enumerate(steps): + if step: + new_inp, bases = _make_case(batch, _plain(ns), seed=71 + step, idx=idx) + for key, buf in inp.items(): + assert buf.shape == new_inp[key].shape, key + buf.copy_(new_inp[key]) + op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], state, config=_spec_of(idx)) + topk.fill_(-5) + out.zero_() + graph.replay() + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + + +def _even_schedule_reference(ctx_lens, num_ctas, unit=256, cmin=128): + """Row r costs max(ceil(n_r / unit), cmin) units; CTA s starts at unit s * (T // G) + min(s, T % G).""" + units = [-(-n // unit) for n in ctx_lens] + cost = [max(u, cmin) for u in units] + prefix, total = [], 0 + for c in cost: + total += c + prefix.append(total) + quota, rem = divmod(total, num_ctas) + rows = [] + for s in range(num_ctas + 1): + w = s * quota + min(s, rem) + r = next((i for i, e in enumerate(prefix) if e > w), len(ctx_lens)) + if r >= len(ctx_lens): + rows.append((len(ctx_lens), 0)) + continue + x = w - (prefix[r - 1] if r else 0) + rows.append((r, x if units[r] >= cmin else 0)) + return rows + + +def _schedule_reference(ctx_lens, num_ctas, unit=256, cmin=128, align_batch=80, slack_pct=3): + """The even split, or below align_batch rows the rows cut into the fewest equal pieces that fit one per CTA + (a row shorter than cmin units stays in one piece), when that has fewer pieces than the even split and costs + the busiest CTA at most slack_pct percent more stream work.""" + even = _even_schedule_reference(ctx_lens, num_ctas, unit, cmin) + batch = len(ctx_lens) + if batch >= align_batch or batch > num_ctas: + return even + units = [-(-n // unit) for n in ctx_lens] + + def pieces(size): + return [1 if u < cmin else -(-u // size) for u in units] + + size = max([u for u in units if u < cmin], default=1) + while sum(pieces(size)) > num_ctas: + size += 1 + aligned = [] + for r, count in enumerate(pieces(size)): + base, rem = divmod(units[r], count) + aligned += [(r, j * base + min(j, rem)) for j in range(count)] + n_aligned = len(aligned) + aligned += [(batch, 0)] * (num_ctas + 1 - n_aligned) + # selection pieces of the even split: the rows it touches plus the rows it cuts in the middle + n_even = sum((b[0] - a[0]) + (b[1] > 0) for a, b in zip(even[:-1], even[1:]) if a != b) + prefix = [0] + for u in units: + prefix.append(prefix[-1] + u) + + def busiest(sched): + return max(prefix[b[0]] + b[1] - prefix[a[0]] - a[1] for a, b in zip(sched[:-1], sched[1:])) + + if n_aligned < n_even and busiest(aligned) * 100 <= busiest(even) * (100 + slack_pct): + return aligned + return even + + +@pytest.mark.parametrize("batch", [1, 7, 48, 64, 79, 80, 127, 148, 256, 1024]) +def test_schedule_matches_reference(batch): + op = _op() + gen = torch.Generator().manual_seed(5 + batch) + aligned = 0 + for trial in range(6): + if trial == 0: + ns = [N_MAX] * batch + elif trial == 1: + ns = [ + SPEC.min_index_len + int(x) for x in torch.randint(0, 3000, (batch,), generator=gen) + ] + else: + ns = [ + int(x) + for x in torch.randint(SPEC.min_index_len, N_MAX + 1, (batch,), generator=gen) + ] + got = op._schedule(ns, NUM_SMS) + assert got.tolist() == [list(r) for r in _schedule_reference(ns, NUM_SMS)] + aligned += got.tolist() != [list(r) for r in _even_schedule_reference(ns, NUM_SMS)] + if batch in (48, 64): + assert aligned > 0, "the aligned schedule never applied: the test does not exercise it" + + +def test_rejects_unsupported_arguments(): + op = _op() + dev = torch.device("cuda") + sinks = torch.zeros(H_ATT, device=dev) + ok = torch.full((256,), 4096, dtype=torch.int32) + with pytest.raises(ValueError): + op.prepare(torch.full((256,), N_MAX + 1, dtype=torch.int32), sinks) + with pytest.raises(ValueError): + op.prepare(torch.full((256,), SPEC.min_index_len - 1, dtype=torch.int32), sinks) + with pytest.raises(ValueError): + op.prepare(torch.empty(0, dtype=torch.int32), sinks) + with pytest.raises(ValueError): + op.prepare(torch.full((SPEC.max_batch + 1,), 4096, dtype=torch.int32), sinks) + with pytest.raises(ValueError): + op.prepare(ok, torch.zeros(H_ATT - 1, device=dev)) + state = op.prepare(ok, sinks) + with pytest.raises(ValueError): + op.prepare(torch.full((128,), 4096, dtype=torch.int32), sinks, state) + + +@pytest.mark.parametrize("offset_elems", [0, 8, 16, 24]) +def test_out_alignment(offset_elems, idx): + """The FP4 attention tail writes its output with 32-byte stores into a 32-byte aligned ``out``; an ``out`` that is + only 16-byte aligned (offset 8 and 24 bf16 elements) runs the narrow compile and gives the same result.""" + op = _op() + batch = 48 + inp, bases = _make_case(batch, _plain(LENGTHS), seed=83, idx=idx) + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=_spec_of(idx)) + topk, _ = _new_outputs(batch) + n = batch * H_ATT * D_ATT + buf = torch.zeros(n + 64, dtype=torch.bfloat16, device=topk.device) + out = buf[offset_elems : offset_elems + n].view(batch, H_ATT * D_ATT) + assert out.data_ptr() % 16 == 0 and (out.data_ptr() % 32 == 0) == (offset_elems % 16 == 0) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + assert int(op.error_bits(state)[0]) == 0 + _check_rows(inp, bases, topk, out, "realistic") + assert bool((buf[:offset_elems] == 0).all()) and bool((buf[offset_elems + n :] == 0).all()) + + +def test_fp4_arguments_are_checked(): + """An FP4 launch needs the query scales and FP4-sized K pages; the FP8 spec takes no scales.""" + op = _op() + inp, _ = _make_case(256, _plain(LENGTHS), seed=81, idx="fp4") + state = op.prepare(inp["ctx_lens"].cpu(), inp["sinks"], config=SPEC_FP4) + topk, out = _new_outputs(256) + bad = dict(inp) + del bad["q_scale"] + with pytest.raises(ValueError, match="q_scale"): + _launch(op, state, bad, topk, out) + bad = dict(inp, k_cache=inp["k_cache"].view(-1)[: inp["k_cache"].numel() - 1]) + with pytest.raises(ValueError): + _launch(op, state, bad, topk, out) + inp8, _ = _make_case(256, _plain(LENGTHS), seed=82, idx="fp8") + state8 = op.prepare(inp8["ctx_lens"].cpu(), inp8["sinks"]) + with pytest.raises(ValueError, match="q_scale"): + _launch(op, state8, dict(inp8, q_scale=inp["q_scale"]), topk, out) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_megakernel.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_megakernel.py new file mode 100644 index 000000000000..063673182b3e --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_megakernel.py @@ -0,0 +1,717 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA megakernel (CuTe DSL, SM100) against an fp64 reference of the unfused DeepSeek-V4-Flash decode chain +(FP8 indexer K cache; the MXFP4 cache is covered by ``test_fp4_matches_reference``, with the case builder and +references of the large-batch test). + +Synthetic inputs: per-row indexer K pages and KV rows scattered over shared pools, an opened K-th gap so the top-512 +set is well defined (rows with planted exact ties or all-equal rows are checked as value multisets), and an attention +mode in which every score is bit-equal so one wrong KV row is visible far above the bf16 noise. +""" + +import zlib + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import DS_V4_FLASH as SPEC +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import ( + DS_V4_FLASH_FP4 as SPEC_FP4, +) +from tensorrt_llm._utils import get_sm_version + +# The shapes under test are those of the spec (``config.py``); test_cute_dsl_spec_dsa_config.py pins its values. +K_TOP, H_IDX, D_IDX = SPEC.topk, SPEC.index_heads, SPEC.index_head_dim +H_ATT, D_ATT = SPEC.attn_heads, SPEC.kv_dim +# compressed / SWA rows per page, window, compress ratio +TPB_C, TPB_SWA, WINDOW, RATIO = ( + SPEC.kv_page_rows, + SPEC.swa_page_rows, + SPEC.window, + SPEC.compress_ratio, +) +PAGE_BYTES = SPEC.index_page_bytes # 32 x 128 e4m3 values, then 32 fp32 scales +N_MAX = SPEC.max_index_len +SM_SCALE = SPEC.default_softmax_scale + + +def _op(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import megakernel_op + + return megakernel_op + + +def _mk(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import megakernel + + return megakernel + + +def _supported() -> bool: + return torch.cuda.is_available() and get_sm_version() == 100 and _op().is_supported()[0] + + +pytestmark = pytest.mark.skipif( + not _supported(), reason="148-CTA cooperative kernel, qualified on B200 only" +) + + +def _cdiv(a, b): + return (a + b - 1) // b + + +def _e4m3(x): + return x.clamp(-448.0, 448.0).to(torch.float8_e4m3fn) + + +def _ue8m0(amax): + return torch.exp2(torch.ceil(torch.log2(amax.clamp_min(1e-30) / 448.0))) + + +def _gather_k(k_cache, bt_row, n): + npg = _cdiv(n, TPB_C) + pg = k_cache.reshape(k_cache.shape[0], PAGE_BYTES).index_select(0, bt_row[:npg].long()) + k8 = pg[:, : TPB_C * D_IDX].contiguous().view(torch.float8_e4m3fn).view(npg * TPB_C, D_IDX)[:n] + sc = pg[:, TPB_C * D_IDX :].contiguous().view(torch.float32).reshape(npg * TPB_C)[:n] + return k8, sc + + +@torch.no_grad() +def _ref_logits(inp, b, chunk=1 << 15): + """fp64 indexer logits: scale[t] * sum_h relu(q[h] . k[t]) * w[h].""" + n = int(inp["ctx_lens"][b]) + k8, sc = _gather_k(inp["k_cache"], inp["idx_block_table"][b], n) + q, w = inp["q_idx"][b, 0].double(), inp["w_idx"][b].double() + out = torch.empty(n, dtype=torch.float64, device=q.device) + for t0 in range(0, n, chunk): + t1 = min(n, t0 + chunk) + out[t0:t1] = (k8[t0:t1].double() @ q.t()).clamp_min(0.0) @ w * sc[t0:t1].double() + return out + + +def _ref_topk(lg): + v, idx = torch.sort(lg, descending=True, stable=True) + tied = lg.numel() > K_TOP and bool(v[K_TOP - 1] == v[K_TOP]) + return idx[:K_TOP], v[:K_TOP], tied + + +@torch.no_grad() +def _ref_attention(inp, b, sel, scale): + """fp64 sparse MLA over the 128 window rows and the selected compressed rows, sink in the denominator.""" + pos = int(inp["kv_lens"][b]) - 1 + p = torch.arange(pos - WINDOW + 1, pos + 1, device=sel.device) + swa_rows = inp["bt_swa"][b, p // TPB_SWA].long() * TPB_SWA + p % TPB_SWA + c_rows = inp["bt_c"][b, sel // TPB_C].long() * TPB_C + sel % TPB_C + swa = inp["swa_pool"].view(torch.uint8).reshape(-1, D_ATT) + cpl = inp["c_pool"].view(torch.uint8).reshape(-1, D_ATT) + kv = torch.cat([swa[swa_rows], cpl[c_rows]], 0).view(torch.float8_e4m3fn).double() + q = inp["q_att"][b].view(H_ATT, D_ATT).double() + s = (q @ kv.t()) * scale + m = s.amax(-1, keepdim=True) + e = torch.exp(s - m) + den = e.sum(-1, keepdim=True) + torch.exp(inp["sinks"].double().view(-1, 1) - m) + return (e @ kv) / den + + +def _calc_diff(x, y): + x, y = x.double(), y.double() + den = (x * x + y * y).sum() + return 0.0 if float(den) == 0.0 else float(1.0 - 2.0 * (x * y).sum() / den) + + +def _open_gap(lg, sc, gap_rel): + """Scale the scores just below rank 512 by an exact power of two until the K-th gap exceeds fp32 noise.""" + if lg.numel() <= K_TOP: # every position is selected + return + for _ in range(8): + v, order = torch.sort(lg, descending=True, stable=True) + kth, nxt = float(v[K_TOP - 1]), float(v[K_TOP]) + margin = gap_rel * max(1.0, abs(kth)) + if kth - nxt >= margin: + return + band = order[K_TOP:][v[K_TOP:] > kth - margin] + if kth > 4 * margin: + f = 0.25 + elif kth < -margin: + f = 4.0 + else: + raise RuntimeError("K-th logit too close to 0: pick another seed") + sc[band] *= f + lg[band] *= f + raise RuntimeError("could not open the K-th gap") + + +@torch.no_grad() +def _make_case(ns, seed, attn, ties=None, flat=()): + """Inputs for len(ns) rows of compressed lengths ns; attn is "gather_exact" or "realistic". + + ties: {row: count} copies the K-th position's K row onto ``count`` losers (an exact tie group at the K-th value). + flat: rows whose positions all share one K row (every logit equal). + """ + ties = ties or {} + dev = torch.device("cuda") + batch = len(ns) + gh = torch.Generator().manual_seed(seed) + gd = torch.Generator(device=dev).manual_seed(seed + 1) + + def rnd(*shape): + return torch.randn(*shape, generator=gd, device=dev) + + kv_lens = [RATIO * n + int(torch.randint(0, RATIO, (1,), generator=gh)) for n in ns] + pg_idx = [_cdiv(n, 128) * (128 // TPB_C) for n in ns] # whole 128-row tiles per row + pages = sum(pg_idx) + 1 # last page: spare + perm = torch.randperm(pages - 1, generator=gh) + idx_bt = torch.full((batch, _cdiv(max(pg_idx), 4) * 4), pages - 1, dtype=torch.int32) + k_cache = torch.zeros((pages, PAGE_BYTES), dtype=torch.uint8, device=dev) + q_idx = _e4m3(rnd(batch, 1, H_IDX, D_IDX) * 2.0) + w_idx = (rnd(batch, H_IDX) * (D_IDX * H_IDX) ** -0.5).float() + off = 0 + for b, n in enumerate(ns): + npad = pg_idx[b] * TPB_C + rows = perm[off : off + pg_idx[b]].to(dev) + off += pg_idx[b] + idx_bt[b, : pg_idx[b]] = rows.to(torch.int32).cpu() + kf = rnd(npad, D_IDX) * torch.exp(0.5 * rnd(npad, 1)) + if b in flat: + kf = kf[:1].repeat(npad, 1) + sc = _ue8m0(kf.abs().amax(-1)) + k8u = _e4m3(kf / sc[:, None]).view(torch.uint8) + k8 = k8u.view(torch.float8_e4m3fn) + lg = ( + (k8[:n].double() @ q_idx[b, 0].double().t()).clamp_min(0.0) + @ w_idx[b].double() + * sc[:n].double() + ) + if b not in flat: + _open_gap(lg, sc, 1e-4) + if b in ties: # exact tie group at the K-th value + order = torch.sort(lg, descending=True, stable=True).indices + src = int(order[K_TOP - 1]) + losers = order[K_TOP:] + dst = losers[torch.randperm(losers.numel(), generator=gh)[: ties[b]].to(dev)] + k8u[dst] = k8u[src].clone() + sc[dst] = sc[src].clone() + lg[dst] = lg[src].clone() + top1 = int(torch.argmax(lg)) + if npad > n: # positions >= n get scores above every real one and must be ignored + k8u[n:] = k8u[top1].clone() + sc[n:] = sc[top1] * (256.0 if float(lg[top1]) > 0 else 1.0 / 256.0) + kp = torch.empty((pg_idx[b], PAGE_BYTES), dtype=torch.uint8, device=dev) + kp[:, : TPB_C * D_IDX] = k8u.reshape(pg_idx[b], TPB_C * D_IDX) + kp[:, TPB_C * D_IDX :] = ( + sc.float().contiguous().view(torch.uint8).reshape(pg_idx[b], TPB_C * 4) + ) + k_cache[rows] = kp + if attn == "gather_exact": + # scores depend only on dims [0, 64), shared by every KV row of a batch row + q_att = torch.randint(-2, 3, (batch, H_ATT, D_ATT), generator=gd, device=dev).float() * 0.25 + q_att[:, :, 64:] = 0.0 + key = torch.randint(-2, 3, (batch, 64), generator=gd, device=dev).float() * 0.25 + else: + q_att = rnd(batch, H_ATT, D_ATT) + q_att = _e4m3(q_att).reshape(batch, H_ATT * D_ATT) + + def kv_rows(b, r): + x = rnd(r, D_ATT) + if attn == "gather_exact": + x[:, :64] = key[b] + return _e4m3(x).view(torch.uint8) + + poison = torch.full((D_ATT,), 448.0, device=dev) + poison[:64] = -448.0 + poison = _e4m3(poison).view(torch.uint8) + n_swa = 2 * batch + 1 # two window pages per row, then a poison spare + swa_pool = torch.empty((n_swa, TPB_SWA, D_ATT), dtype=torch.uint8, device=dev) + swa_pool[n_swa - 1] = poison + perm_s = torch.randperm(2 * batch, generator=gh) + bt_swa = torch.full((batch, max(kv_lens) // TPB_SWA + 1), n_swa - 1, dtype=torch.int32) + for b in range(batch): + hi = (kv_lens[b] - 1) // TPB_SWA + for j, blk in enumerate((hi - 1, hi)): + pgs = int(perm_s[2 * b + j]) + if blk >= 0: + bt_swa[b, blk] = pgs + swa_pool[pgs] = kv_rows(b, TPB_SWA) + pg_c = [_cdiv(n, TPB_C) for n in ns] + n_c = sum(pg_c) + 1 + c_pool = torch.empty((n_c, TPB_C, D_ATT), dtype=torch.uint8, device=dev) + c_pool[n_c - 1] = poison + perm_c = torch.randperm(n_c - 1, generator=gh) + # rows 16-byte aligned: width a multiple of 4 entries + bt_c = torch.full((batch, _cdiv(max(pg_c), 4) * 4), n_c - 1, dtype=torch.int32) + off = 0 + for b in range(batch): + rows = perm_c[off : off + pg_c[b]] + off += pg_c[b] + bt_c[b, : pg_c[b]] = rows.to(torch.int32) + c_pool[rows.to(dev)] = kv_rows(b, pg_c[b] * TPB_C).view(pg_c[b], TPB_C, D_ATT) + sinks = (torch.linspace(-6.0, 9.0, H_ATT, device=dev) + 0.1 * rnd(H_ATT)).float() + return { + "q_idx": q_idx, + "w_idx": w_idx.contiguous(), + "k_cache": k_cache.view(pages, TPB_C, 1, D_IDX + 4), + "idx_block_table": idx_bt.to(dev), + "ctx_lens": torch.tensor(ns, dtype=torch.int32, device=dev), + "kv_lens": torch.tensor(kv_lens, dtype=torch.int32, device=dev), + "q_att": q_att, + "swa_pool": swa_pool.view(torch.float8_e4m3fn), + "bt_swa": bt_swa.to(dev), + "c_pool": c_pool.view(torch.float8_e4m3fn), + "bt_c": bt_c.to(dev), + "sinks": sinks.contiguous(), + } + + +def _check_row(inp, b, lg, topk_row, out_row, attn, scale): + sel = topk_row.long() + assert bool(((sel >= 0) & (sel < lg.numel())).all()), "index outside [0, n)" + s = torch.sort(sel).values + assert not bool((s[1:] == s[:-1]).any()), "duplicate index" + ref_sel, ref_v, tied = _ref_topk(lg) + if tied: + assert torch.equal(torch.sort(lg[sel], descending=True).values, ref_v), ( + "top-512 value multiset differs" + ) + else: + assert torch.equal(s, torch.sort(ref_sel).values), "top-512 set differs" + ref = _ref_attention(inp, b, sel, scale) + o = out_row.view(H_ATT, D_ATT).double() + assert bool(torch.isfinite(o).all()), "non-finite output" + if attn == "gather_exact": + cd = _calc_diff(o[:, 64:], ref[:, 64:]) + assert cd < 2e-5, f"row {b}: calc_diff {cd:.3e}" + assert float((o - ref).abs().max()) <= 2.0**-6 * float(ref.abs().max()) + else: + cd = _calc_diff(o, ref) + assert cd < 1e-3, f"row {b}: calc_diff {cd:.3e}" + + +def _run(op, state, inp, topk, out, scale): + op.run( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["sinks"], + topk, + out, + softmax_scale=scale, + ) + + +def _prepare(op, inp, state=None): + # host lengths: prepare() checks them without a device sync + return op.prepare( + inp["ctx_lens"].cpu(), inp["kv_lens"].cpu(), inp["idx_block_table"], state=state + ) + + +CASES = [ # (rows' compressed lengths, attention mode, extra case options) + pytest.param([262144], "gather_exact", {}, id="b1-max"), + pytest.param([262127], "realistic", {"scale": 0.03}, id="b1-scale"), + pytest.param([8000], "gather_exact", {"ties": {0: 9}}, id="b1-ties"), + pytest.param([32771], "gather_exact", {"ties": {0: 6000}}, id="b1-tie6000"), + pytest.param([512], "realistic", {}, id="b1-select-all"), + pytest.param([131071, 65543], "gather_exact", {"ties": {1: 7}}, id="b2-ties"), + pytest.param([65536, 32771], "realistic", {}, id="b2-mixed"), + pytest.param([32771, 32771], "gather_exact", {"flat": (1,)}, id="b2-flat"), + pytest.param([600, 5000], "realistic", {}, id="b2-short"), + pytest.param([262127] * 4, "realistic", {}, id="b4-max"), + pytest.param([131071, 98309, 50021, 32771], "gather_exact", {}, id="b4-mixed"), + pytest.param([512, 5632, 8192, 700], "gather_exact", {}, id="b4-short"), + # 3 and 4 rows run as one team of 4 CTAs per row (a single pass) + pytest.param([262127] * 3, "realistic", {}, id="b3-max"), + pytest.param( + [262127, 700, 98309, 32771], + "gather_exact", + {"ties": {1: 5, 3: 77}, "flat": (2,)}, + id="b4-short-ties-flat", + ), + pytest.param([262127] * 8, "gather_exact", {"flat": (6,)}, id="b8-flat"), + pytest.param( + [262127 - 4099 * r for r in range(8)], "realistic", {"ties": {3: 31}}, id="b8-mixed-ties" + ), + # batch sizes between the powers of two, and the ring of 9 to 47 rows + pytest.param([131071, 98309, 50021], "gather_exact", {}, id="b3-mixed"), + pytest.param([262127] * 5, "realistic", {}, id="b5-max"), + pytest.param( + [65536, 32771, 700, 262127, 8192, 5000], + "gather_exact", + {"ties": {2: 13}}, + id="b6-short-ties", + ), + pytest.param( + [262127 - 5003 * r for r in range(7)], "gather_exact", {"flat": (4,)}, id="b7-flat" + ), + pytest.param([262127 - 7001 * r for r in range(9)], "realistic", {}, id="b9-mixed"), + pytest.param([131071] * 12, "gather_exact", {"ties": {5: 17}}, id="b12-ties"), + pytest.param( + [262127 - 3001 * r for r in range(13)], "gather_exact", {"flat": (9,)}, id="b13-flat" + ), + pytest.param([262127] * 16, "realistic", {}, id="b16-max"), + pytest.param( + [262127 - 4093 * r for r in range(16)], + "gather_exact", + {"ties": {11: 29, 3: 6000}}, + id="b16-mixed-ties", + ), + pytest.param([262127 - 6007 * r for r in range(17)], "realistic", {}, id="b17-mixed"), + pytest.param( + [131071 - 3001 * r for r in range(20)], "gather_exact", {"ties": {7: 21}}, id="b20-ties" + ), + pytest.param([262127] * 24, "gather_exact", {"flat": (13, 20)}, id="b24-flat"), + pytest.param( + [262127 - 2999 * r for r in range(27)], + "realistic", + {"ties": {26: 9, 0: 6000}}, + id="b27-mixed-ties", + ), + pytest.param([262127] * 32, "realistic", {}, id="b32-max"), + pytest.param( + [262127 - 3989 * r if r % 3 else 700 + 17 * r for r in range(32)], + "gather_exact", + {"ties": {5: 3, 31: 77}, "flat": (18,)}, + id="b32-mixed-short-ties", + ), + # 33 to 47 rows: the block-table slices of rows 32 and up reuse the entries of rows 0 and up + pytest.param([262127 - 4999 * r for r in range(33)], "realistic", {}, id="b33-mixed"), + pytest.param( + [131071 - 2003 * r for r in range(37)], + "gather_exact", + {"ties": {20: 21, 36: 6000}}, + id="b37-ties", + ), + pytest.param([262127] * 41, "gather_exact", {"flat": (13, 33, 40)}, id="b41-flat"), + pytest.param( + [262127 - 3517 * r if r % 4 else 900 + 31 * r for r in range(45)], + "realistic", + {"ties": {0: 5, 32: 11, 44: 77}}, + id="b45-mixed-ties", + ), + pytest.param([262127] * 47, "realistic", {}, id="b47-max"), + pytest.param( + [262127 - 3989 * r if r % 3 else 700 + 17 * r for r in range(47)], + "gather_exact", + {"ties": {5: 3, 31: 77, 46: 6000}, "flat": (18, 40)}, + id="b47-mixed-short-ties", + ), +] + + +@pytest.mark.parametrize("ns,attn,extra", CASES) +def test_matches_reference(ns, attn, extra): + op, mk = _op(), _mk() + batch = len(ns) + extra = dict(extra) + scale = extra.pop("scale", SM_SCALE) + seed = zlib.crc32(repr((ns, attn, extra)).encode()) % 100003 + inp = _make_case(ns, seed=seed, attn=attn, **extra) + lgs = [_ref_logits(inp, b) for b in range(batch)] + state = _prepare(op, inp) + topk = torch.full((batch, K_TOP), -1, dtype=torch.int32, device="cuda") + out = torch.zeros((batch, H_ATT * D_ATT), dtype=torch.bfloat16, device="cuda") + launches = 0 + + def launch(case): + topk.fill_(-1) + out.zero_() + _run(op, state, case, topk, out, scale) + + def check(case, logits): + torch.cuda.synchronize() + for b in range(batch): + _check_row(case, b, logits[b], topk[b], out[b], attn, scale) + + for _ in range(2): # eager; the second launch runs on the next workspace generation + launch(inp) + launches += 1 + check(inp, lgs) + side = torch.cuda.Stream() + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + launch(inp) + launches += 1 + torch.cuda.current_stream().wait_stream(side) + check(inp, lgs) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + _run(op, state, inp, topk, out, scale) + for _ in range(3): + topk.fill_(-1) + out.zero_() + graph.replay() + launches += 1 + check(inp, lgs) + # Next step on the same state: new inputs of the same shapes, the state refreshed in place. Leftovers of the + # previous generation would show up as a wrong top-512 or attention. + inp2 = _make_case(ns, seed=seed + 1, attn=attn, **extra) + lgs2 = [_ref_logits(inp2, b) for b in range(batch)] + assert _prepare(op, inp2, state=state) is state + launch(inp2) + launches += 1 + check(inp2, lgs2) + assert int(op.error_bits(state).max()) == 0, "kernel error bits set" + ws = state.ws64.view(batch, mk.WS_WORDS) + assert bool((ws[:, mk.W_DONE] == launches).all()), "one workspace generation per launch" + + +def test_rejects_unsupported_shapes(): + op = _op() + dev = torch.device("cuda") + i32 = torch.int32 + many = SPEC.megakernel_max_batch + 1 + bt = torch.zeros((many, 8), dtype=i32, device=dev) + with pytest.raises(ValueError, match="batch size"): + op.prepare(torch.full((many,), 4096, dtype=i32), torch.full((many,), 16384, dtype=i32), bt) + with pytest.raises(ValueError, match="compressed lengths"): + op.prepare(torch.tensor([300], dtype=i32), torch.tensor([1200], dtype=i32), bt[:1]) + with pytest.raises(ValueError, match="compressed lengths"): + op.prepare( + torch.tensor([N_MAX + 1], dtype=i32), torch.tensor([4 * N_MAX + 4], dtype=i32), bt[:1] + ) + with pytest.raises(ValueError, match="uncompressed lengths"): + op.prepare(torch.tensor([512], dtype=i32), torch.tensor([100], dtype=i32), bt[:1]) + with pytest.raises(ValueError, match="pages per row"): + op.prepare(torch.tensor([4096], dtype=i32), torch.tensor([16384], dtype=i32), bt[:1]) + bt2 = torch.zeros((2, 128), dtype=i32, device=dev) + state = op.prepare(torch.tensor([4096], dtype=i32), torch.tensor([16384], dtype=i32), bt2[:1]) + with pytest.raises(ValueError, match="state is for"): + op.prepare( + torch.full((2,), 4096, dtype=i32), torch.full((2,), 16384, dtype=i32), bt2, state=state + ) + + +def _fp4_rows(batch, step=4093, short=(), ties=None, flat=(), base=262127): + """Specs of ``batch`` rows: lengths ``base - step * r``, the rows in ``short`` 700 + 17 r long, planted ties + {row: count}, all-equal rows ``flat``.""" + ties = ties or {} + return [ + { + "n": 700 + 17 * r if r in short else base - step * r, + "ties": ties.get(r, 0), + "flat": r in flat, + } + for r in range(batch) + ] + + +# The knob sets of the FP4 megakernel: 1 row, 2 rows, 3 to 4 rows (one team of 4 CTAs per row), 5 to 8 rows and 9 up to +# megakernel_max_batch rows (the ring of logits slots); from 5 rows four shared teams, two dedicated T-server CTAs and +# rotated split ranges. Odd and in-between sizes, the largest size, short rows (most stream CTAs have an empty split +# range) and rows of the longest length are all part of it. +FP4_N = SPEC_FP4.megakernel_max_batch +FP4_CASES = [ + pytest.param(specs, attn, id=f"b{len(specs)}-{name}") + for name, specs, attn in [ + ("max", [{"n": 262127}], "gather_exact"), + ("ties", [{"n": 8000, "ties": 9}], "gather_exact"), + ("select-all", [{"n": 512}], "realistic"), + ("ties", [{"n": 131071}, {"n": 65543, "ties": 7}], "gather_exact"), + ( + "short-ties-flat", + [{"n": 262127}, {"n": 700, "ties": 5}, {"n": 98309, "flat": True}], + "gather_exact", + ), + ( + "mixed", + [{"n": 131071}, {"n": 98309}, {"n": 50021}, {"n": 32771, "ties": 77}], + "realistic", + ), + ("mixed", _fp4_rows(5, step=7001), "realistic"), + ("max", [{"n": 262127}] * 5, "gather_exact"), + ("short-ties", _fp4_rows(6, short=(1, 4), ties={2: 13}), "gather_exact"), + ("flat", _fp4_rows(7, step=5003, flat=(4,)), "gather_exact"), + ("mixed-ties", _fp4_rows(8, step=4099, ties={3: 31}), "realistic"), + ("mixed", _fp4_rows(9, step=7001), "gather_exact"), + ("mixed-ties", _fp4_rows(10, step=5501, ties={9: 41}), "gather_exact"), + ("short-ties", _fp4_rows(11, short=(3, 9), ties={5: 17}), "realistic"), + ("flat", _fp4_rows(13, step=3001, flat=(9,)), "gather_exact"), + ("short-flat", _fp4_rows(14, short=(0, 7), flat=(11,)), "realistic"), + ("mixed", _fp4_rows(15, step=6101), "gather_exact"), + ("mixed-ties", _fp4_rows(16, ties={11: 29}), "realistic"), + ("mixed", _fp4_rows(17, step=6007), "gather_exact"), + ("short-ties", _fp4_rows(18, short=(4, 13), ties={8: 600}), "realistic"), + ( + "short-ties-flat", + _fp4_rows(19, short=(6, 12, 18), ties={0: 6000, 15: 77}, flat=(10,)), + "gather_exact", + ), + ("mixed", _fp4_rows(20, step=5003), "realistic"), + # rows of fewer than 8,192 positions: only the first stream CTAs have a split range + ("all-short", [{"n": n} for n in (512, 700, 1500, 4097, 513, 8000, 2049)], "gather_exact"), + ("all-short", [{"n": 512 + 331 * r} for r in range(12)], "realistic"), + ("max", [{"n": 262127}] * FP4_N, "realistic"), + ( + "mixed-short-ties-flat", + _fp4_rows( + FP4_N, step=3989, short=(2, 5, 8, 11, 14, 17), ties={5: 3, 7: 77}, flat=(18,) + ), + "gather_exact", + ), + ("all-short", [{"n": 512 + 97 * r} for r in range(FP4_N)], "gather_exact"), + ] + if len(specs) <= FP4_N +] + + +@pytest.mark.parametrize("specs,attn", FP4_CASES) +def test_fp4_matches_reference(specs, attn): + """MXFP4 indexer K cache: exact top-512 sets / value multisets and the attention against the fp64 references.""" + from . import test_cute_dsl_spec_dsa_large_batch as H + + op = _op() + batch = len(specs) + inp, bases = H._make_case(batch, specs, seed=300 + batch, attn=attn, idx="fp4") + state = op.prepare( + inp["ctx_lens"].cpu(), inp["kv_lens"].cpu(), inp["idx_block_table"], config=H.SPEC_FP4 + ) + topk, out = H._new_outputs(batch) + + def launch(): + topk.fill_(-1) + out.zero_() + op.run( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["sinks"], + topk, + out, + softmax_scale=SM_SCALE, + q_scale=inp["q_scale"], + ) + torch.cuda.synchronize() + + for _ in range(2): # the second launch runs on the next workspace generation + launch() + H._check_rows(inp, bases, topk, out, attn) + assert int(op.error_bits(state).max()) == 0, "kernel error bits set" + + +# The FP4 threshold knobs of ``megakernel_op._FP4_SMALL`` / ``_FP4_MID`` (lpoll, lfence, lbin, tpoll1) change how the +# threshold lead polls the sampled board, finds the three rank bins and how the stream CTAs poll the threshold line, not +# what is published: the bins come from a histogram instead of the bitwise key search and must give the same line bit +# for bit (including the [SMIN, SMAX] range of the key search, which leaves out the first warp's top-1 keys of one +# sign). +_T_KNOBS = ("lpoll", "lfence", "lbin", "tpoll1") +_PLAIN_ENGINES: dict = {} +T_LINE_CASES = [ + pytest.param([{"n": 262127}], id="b1-max"), + pytest.param([{"n": 8000, "ties": 9}], id="b1-ties"), + pytest.param([{"n": 512}], id="b1-select-all"), + pytest.param([{"n": 131071}, {"n": 65543, "ties": 7}], id="b2-ties"), + pytest.param( + [{"n": 262127}, {"n": 700, "ties": 5}, {"n": 98309, "flat": True}], id="b3-short-ties-flat" + ), + pytest.param(_fp4_rows(4, short=(1,), flat=(3,)), id="b4-short-flat"), + # five to eight rows: the T lead of the dedicated T-server CTAs (lbin from five rows on, b1l_u 3 at eight rows) + pytest.param(_fp4_rows(5, short=(2,), flat=(4,)), id="b5-short-flat"), + pytest.param(_fp4_rows(6, ties={1: 7, 4: 9}), id="b6-ties"), + pytest.param(_fp4_rows(7, short=(0, 5)), id="b7-short"), + pytest.param(_fp4_rows(8, short=(3,), flat=(6,), step=2987), id="b8-short-flat"), +] + + +@pytest.mark.parametrize("specs", T_LINE_CASES) +def test_fp4_threshold_line_does_not_depend_on_the_threshold_knobs(specs, monkeypatch): + from . import test_cute_dsl_spec_dsa_large_batch as H + + op, mk = _op(), _mk() + batch = len(specs) + inp, _ = H._make_case(batch, specs, seed=300 + batch, attn="realistic", idx="fp4") + + def run_once(): + state = op.prepare( + inp["ctx_lens"].cpu(), inp["kv_lens"].cpu(), inp["idx_block_table"], config=H.SPEC_FP4 + ) + topk, out = H._new_outputs(batch) + op.run( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["sinks"], + topk, + out, + softmax_scale=SM_SCALE, + q_scale=inp["q_scale"], + ) + torch.cuda.synchronize() + assert int(op.error_bits(state).max()) == 0, "kernel error bits set" + line = state.ws64.view(batch, mk.WS_WORDS)[:, mk.W_TLINE : mk.W_TLINE + 4] & 0xFFFFFFFF + return line.cpu(), [sorted(topk[r].tolist()) for r in range(batch)] + + knobs = op._KNOBS[H.SPEC_FP4.kernel_key] + shipped_line, shipped_sets = run_once() + monkeypatch.setitem(knobs, batch, {**knobs[batch], **dict.fromkeys(_T_KNOBS, False)}) + monkeypatch.setattr(op, "_engines", _PLAIN_ENGINES) + plain_line, plain_sets = run_once() + assert torch.equal(shipped_line, plain_line), (shipped_line, plain_line) + if not any(sp.get("ties") or sp.get("flat") for sp in specs): + # with planted ties the tied rows enter the set in arrival order: only the threshold line is compared there + assert shipped_sets == plain_sets + + +def test_fp4_requires_query_scales(): + from . import test_cute_dsl_spec_dsa_large_batch as H + + op = _op() + inp, _ = H._make_case(1, H._plain([4096]), seed=5, idx="fp4") + state = op.prepare( + inp["ctx_lens"].cpu(), inp["kv_lens"].cpu(), inp["idx_block_table"], config=H.SPEC_FP4 + ) + topk, out = H._new_outputs(1) + args = ( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["sinks"], + topk, + out, + ) + with pytest.raises(ValueError, match="q_scale"): + op.run(*args) + with pytest.raises(ValueError, match="q_scale"): + op.run(*args, q_scale=inp["q_scale"].view(-1)[:3]) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_op.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_op.py new file mode 100644 index 000000000000..dc2f17a3a558 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_op.py @@ -0,0 +1,710 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""One op for every batch size: ``spec_dsa.op`` from 1 to 1,024 rows (SM100). + +The op picks the megakernel, the tail-attention hybrid or the large-batch kernels by batch size (``implementation_for``; +the FP8 spec has no hybrid), for the FP8 and the MXFP4 indexer K cache (the ``idx`` fixture). The case builder and the +fp64 references of the large-batch test check every row's top-512 and attention here too, so the implementations are +covered through the one interface: batch sizes around the switches and between the powers of two, the CUDA-graph and +in-place refresh path, the megakernel forced at the FP4 sizes the hybrid took over, and the argument checks of the op. +The hybrid launches the production FP4 indexer logits op of the repository (and its scheduler metadata): the tests that +run it skip when that op is not registered. +""" + +import dataclasses +import re + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import hybrid_op as _hybrid +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import large_batch_op as _lbo +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op as _tail +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta_op as _topk + +from . import test_cute_dsl_spec_dsa_large_batch as H + +pytestmark = H.pytestmark +idx = H.idx +# The batch sizes at which the FP4 spec switches: the first and last size of the hybrid with the size outside them, its +# megakernel's last size, and the first size of every further compile of the large-batch indexer kernel +# (``large_batch_op._VARIANTS``) with the size before it. +FP4_LAST = H.SPEC_FP4.megakernel_max_batch +HYBRID_FIRST, HYBRID_LAST = H.SPEC_FP4.tail_hybrid_range +FP4_VARIANTS = [first for first, _ in _lbo._VARIANTS.get(H.SPEC_FP4.kernel_key, ())] or [64] +FP4_VARIANT = min(FP4_VARIANTS) +SWITCHES = { + FP4_LAST, + FP4_LAST + 1, + HYBRID_FIRST - 1, + HYBRID_FIRST, + HYBRID_LAST, + HYBRID_LAST + 1, +} | {b for first in FP4_VARIANTS for b in (first - 1, first)} +# The FP4 sizes the megakernel served by default before the hybrid took them over; it stays selectable there. +FORCED_MEGAKERNEL = [HYBRID_FIRST, 8, 9, 13, 16, 17, FP4_LAST] +# The hybrid's launch variants change with the batch size: the CTAs per row of its top-K (``topk_multicta_op``) and the +# PDL / poll limits of its tail attention. HYBRID_SIZES holds its first and last size, both sides of every limit and the +# megakernel's last size; VARIANT_SIZES one size per variant. +_LIMITS = [m for m, _ in _topk._CLUSTER_LIMITS] + [_tail.PDL_MAX_BATCH, _tail.POLL_MAX_BATCH] +HYBRID_SIZES = sorted( + {HYBRID_FIRST, HYBRID_LAST, 13, FP4_LAST} + | {b for limit in _LIMITS for b in (limit, limit + 1) if HYBRID_FIRST <= b <= HYBRID_LAST} +) +VARIANT_SIZES = sorted( + { + (_topk.cluster_size(b), _tail.default_pdl(b), _tail.default_poll(b)): b + for b in range(HYBRID_FIRST, HYBRID_LAST + 1) + }.values() +) +# Row lengths of the hybrid tests: mixed (short and long), long (every row has 16,384 positions or more: the top-K +# stage the hybrid is tuned for), short (no row has), and rows with planted ties and all-equal logits. +HYBRID_ROWS = { + "mixed": H._plain(H.LENGTHS), + "long": H._plain( + [262144, 262143, 200000, 131072, 100003, 70000, 65535, 32769, 24576, 16385, 16384, 40000] + ), + "short": H._plain([512, 513, 1000, 4097, 8192, 8193, 8197, 12000, 16383, 700]), + "ties": [ + {"n": 100000, "ties": 3}, + {"n": 262144, "ties": 6000}, + {"n": 5000, "flat": True}, + {"n": 262143, "flat": True}, + {"n": 700, "ties": 100}, + {"n": 512}, + {"n": 90000}, + {"n": 40000, "ties": 600}, + ], +} + + +def _op(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import op + + return op + + +def _skip_without_hybrid(): + ok, why = _hybrid.is_supported(config=H.SPEC_FP4) + if not ok: + pytest.skip(why) + + +def _needs_hybrid(batch, idx="fp4", implementation=None): + """Skip the test if it launches the tail hybrid and the production logits op is not available.""" + if (implementation or _op().implementation_for(batch, H._spec_of(idx))) == "tail_hybrid": + _skip_without_hybrid() + + +def _prepare(op, inp, state=None, idx="fp8", implementation=None): + # host lengths: prepare() reads them without a device sync + return op.prepare( + inp["ctx_lens"].cpu(), + inp["kv_lens"].cpu(), + inp["idx_block_table"], + inp["sinks"], + state=state, + config=H._spec_of(idx), + implementation=implementation, + ) + + +def _launch(op, state, inp, topk, out): + op.run( + state, + inp["q_idx"], + inp["w_idx"], + inp["k_cache"], + inp["idx_block_table"], + inp["ctx_lens"], + inp["kv_lens"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + topk, + out, + softmax_scale=H.SM_SCALE, + **({"q_scale": inp["q_scale"]} if "q_scale" in inp else {}), + ) + + +def _capture(fn): + """Warm up on a side stream (as the other specDSA tests do), then capture ``fn`` into a CUDA graph.""" + side = torch.cuda.Stream() + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + fn() + torch.cuda.current_stream().wait_stream(side) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + fn() + return graph + + +def _check_error_bits(op, state): + """No error bit is set. The hybrid has no device flag (``error_bits`` is a constant zero): nothing to check.""" + if state.implementation != "tail_hybrid": + assert int(op.error_bits(state).max()) == 0 + + +def test_implementation_for(idx): + op = _op() + spec = H._spec_of(idx) + assert op.implementation_for(1, spec) == "megakernel" + assert op.implementation_for(spec.max_batch, spec) == "large_batch" + if spec.tail_hybrid_range is None: + last = spec.megakernel_max_batch + assert op.implementation_for(last, spec) == "megakernel" + assert op.implementation_for(last + 1, spec) == "large_batch" + else: + first, last = spec.tail_hybrid_range + assert op.implementation_for(first - 1, spec) == "megakernel" + assert op.implementation_for(first, spec) == "tail_hybrid" + assert op.implementation_for(last, spec) == "tail_hybrid" + assert op.implementation_for(last + 1, spec) == "large_batch" + for bad in (-1, 0, spec.max_batch + 1): + with pytest.raises(ValueError, match="batch size"): + op.implementation_for(bad, spec) + + +def _check_matches_reference(batch, idx, implementation=None): + op = _op() + _needs_hybrid(batch, idx, implementation) + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=100 + batch, idx=idx) + state = _prepare(op, inp, idx=idx, implementation=implementation) + assert state.batch_size == batch + assert state.implementation == (implementation or op.implementation_for(batch, H._spec_of(idx))) + topk, out = H._new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + _check_error_bits(op, state) + H._check_rows(inp, bases, topk, out, "realistic") + + +@pytest.mark.parametrize( + "batch", + sorted({1, 2, 3, 4, 5, 8, 9, 13, 16, 17, 24, 32, 33, 40, 47, 48, 49, 64, 149, 1024} | SWITCHES), +) +def test_matches_reference(batch, idx): + _check_matches_reference(batch, idx) + + +@pytest.mark.parametrize("batch", FORCED_MEGAKERNEL) +def test_forced_megakernel_matches_reference(batch): + """The FP4 megakernel at the sizes the hybrid serves by default: ``implementation="megakernel"``.""" + _check_matches_reference(batch, "fp4", "megakernel") + + +@pytest.mark.parametrize("batch", [HYBRID_FIRST, FP4_VARIANT]) +def test_forced_large_batch_matches_reference(batch): + """The large-batch kernels below their default range: at the hybrid's first size and at the first size of their + first knob range (also the hybrid's).""" + _check_matches_reference(batch, "fp4", "large_batch") + + +def _check_refresh_in_place_and_cuda_graph(batch, idx, implementation=None): + op = _op() + _needs_hybrid(batch, idx, implementation) + ns = H.LENGTHS[:batch] if batch <= len(H.LENGTHS) else H.LENGTHS + inp, bases = H._make_case(batch, H._plain(ns), seed=7 + batch, idx=idx) + state = _prepare(op, inp, idx=idx, implementation=implementation) + topk, out = H._new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + # the same state refreshed in place for another step, then one captured launch replayed + inp2, bases2 = H._make_case(batch, H._plain(ns[::-1]), seed=70 + batch, idx=idx) + assert _prepare(op, inp2, state=state, idx=idx, implementation=implementation) is state + topk.fill_(-1) + out.zero_() + _launch(op, state, inp2, topk, out) + torch.cuda.synchronize() + H._check_rows(inp2, bases2, topk, out, "realistic") + graph = _capture(lambda: _launch(op, state, inp2, topk, out)) + for _ in range(2): + topk.fill_(-1) + out.zero_() + graph.replay() + torch.cuda.synchronize() + H._check_rows(inp2, bases2, topk, out, "realistic") + _check_error_bits(op, state) + + +@pytest.mark.parametrize("batch", sorted({4, 5, 8, 13, 24, 40, 47, 48, 60} | SWITCHES)) +def test_refresh_in_place_and_cuda_graph(batch, idx): + _check_refresh_in_place_and_cuda_graph(batch, idx) + + +@pytest.mark.parametrize("batch", [HYBRID_FIRST, 8, 13, FP4_LAST]) +def test_forced_megakernel_refresh_in_place_and_cuda_graph(batch): + _check_refresh_in_place_and_cuda_graph(batch, "fp4", "megakernel") + + +def _check_negative_logits(batch, idx, implementation=None): + """Rows whose logits are all <= 0 through the op.""" + op = _op() + _needs_hybrid(batch, idx, implementation) + ns = H.LENGTHS[:batch] if batch <= len(H.LENGTHS) else H.LENGTHS + inp, bases = H._make_case(batch, [{"n": n, "neg": True} for n in ns], seed=170 + batch, idx=idx) + state = _prepare(op, inp, idx=idx, implementation=implementation) + assert state.implementation == (implementation or op.implementation_for(batch, H._spec_of(idx))) + topk, out = H._new_outputs(batch) + for launch in range(3): + topk.fill_(-5) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + _check_error_bits(op, state) + if launch == 0: + H._check_rows(inp, bases, topk, out, "realistic") + else: + H._check_selection(bases, topk) + + +@pytest.mark.parametrize("batch", sorted({1, 3, 9, 64} | SWITCHES)) +def test_negative_logits(batch, idx): + """The megakernel sizes, the hybrid sizes and the large-batch sizes of both specs.""" + _check_negative_logits(batch, idx) + + +@pytest.mark.parametrize("batch", [9, FP4_LAST]) +def test_forced_megakernel_negative_logits(batch): + _check_negative_logits(batch, "fp4", "megakernel") + + +# -------------------------------------------------------------------------------------------------------------------- +# the tail hybrid through the op + + +@pytest.mark.parametrize("kind", list(HYBRID_ROWS)) +@pytest.mark.parametrize("batch", HYBRID_SIZES) +def test_hybrid_matches_reference(batch, kind): + """The hybrid against the fp64 reference at its first and last size and on both sides of every limit of its launch + variants (``HYBRID_SIZES``), with mixed, long, short rows and rows with planted ties and all-equal logits: every + row's exact top-512 set and attention.""" + _skip_without_hybrid() + op = _op() + inp, bases = H._make_case(batch, HYBRID_ROWS[kind], seed=3000 + batch + len(kind), idx="fp4") + state = _prepare(op, inp, idx="fp4") + assert state.implementation == "tail_hybrid" + topk, out = H._new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +@pytest.mark.parametrize("batch", [13, 24, HYBRID_LAST]) +def test_hybrid_graph_replays_over_in_place_refreshed_inputs(batch): + """One captured launch replays over several steps while the inputs change in place and ``prepare`` refreshes the + state in place: the schedule of the logits kernel follows the lengths (rows of 512 to 262,144 positions rotate over + the rows, so a stale schedule would show). The three sizes launch the hybrid with polling, with PDL only, plain.""" + _skip_without_hybrid() + op = _op() + ns = (H.LENGTHS * 2)[:batch] + steps = [ns[r:] + ns[:r] for r in (0, 5, 9)] + inp, bases = H._make_case(batch, H._plain(steps[0]), seed=2000 + batch, idx="fp4") + state = _prepare(op, inp, idx="fp4") + assert state.implementation == "tail_hybrid" + topk, out = H._new_outputs(batch) + op.precompile(torch.device("cuda"), batch, H.SPEC_FP4) + graph = _capture(lambda: _launch(op, state, inp, topk, out)) + lengths, sched = state.state.ctx_lens, state.state.sched + for step, rows in enumerate(steps): + if step: + new, bases = H._make_case(batch, H._plain(rows), seed=2000 + batch + step, idx="fp4") + for key, buf in inp.items(): + assert buf.shape == new[key].shape, key + buf.copy_(new[key]) + before = sched.clone() + assert _prepare(op, inp, state=state, idx="fp4") is state + assert state.state.ctx_lens is lengths, "prepare must refresh the lengths in place" + assert state.state.sched is sched, "prepare must refresh the schedule in place" + assert not torch.equal(sched, before), "the schedule follows the new lengths" + assert torch.equal(lengths, inp["ctx_lens"]), "the state holds the lengths of the step" + topk.fill_(-1) + out.zero_() + graph.replay() + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def _k1_runner(): + """The compile cache holder of the production FP4 logits op.""" + from tensorrt_llm._torch.custom_ops import cute_dsl_custom_ops + + runner = getattr(cute_dsl_custom_ops, "CuteDSLFP4PagedMQALogitsRunner", None) + if runner is None: + pytest.skip("the production FP4 logits runner is not in this build") + return runner + + +@pytest.mark.parametrize("batch", VARIANT_SIZES) +def test_hybrid_precompile_then_captured_op(batch, monkeypatch): + """``op.precompile`` followed by a CUDA-graph capture of ``op.run`` compiles nothing during the capture, the + production logits kernel included: there is no warm-up launch in between. One size per launch variant (CTAs per + row of the top-K, PDL, polling).""" + _skip_without_hybrid() + op = _op() + runner = _k1_runner() + # as in a fresh process: nothing compiled, the logits kernel not known to be launched + monkeypatch.setattr(runner, "kernel_cache", {}) + monkeypatch.setattr(_tail, "_compiled", {}) + monkeypatch.setattr(_topk, "_compiled", {}) + monkeypatch.setattr(_hybrid, "_k1_ready", set()) + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=2500, idx="fp4") + state = _prepare(op, inp, idx="fp4") + op.precompile(torch.device("cuda"), batch, H.SPEC_FP4) + compiled = (len(runner.kernel_cache), len(_tail._compiled), len(_topk._compiled)) + assert compiled[0] >= 1 and compiled[1:] == (1, 1), "precompile compiles all three kernels" + topk, out = H._new_outputs(batch) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + _launch(op, state, inp, topk, out) + assert (len(runner.kernel_cache), len(_tail._compiled), len(_topk._compiled)) == compiled + graph.replay() + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +@pytest.mark.filterwarnings("ignore:The CUDA Graph is empty") +def test_hybrid_capture_before_the_logits_kernel_is_compiled_is_refused(monkeypatch): + """The production logits kernel cannot be compiled inside a capture: precompile (or launch) first.""" + _skip_without_hybrid() + op = _op() + batch = 8 + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=2600, idx="fp4") + state = _prepare(op, inp, idx="fp4") + topk, out = H._new_outputs(batch) + _launch(op, state, inp, topk, out) # warm-up: compiles everything + monkeypatch.setattr(_hybrid, "_k1_ready", set()) # as in a fresh process + graph = torch.cuda.CUDAGraph() + with pytest.raises(RuntimeError, match="precompile"): + with torch.cuda.graph(graph): + _launch(op, state, inp, topk, out) + monkeypatch.undo() + topk.fill_(-1) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def test_hybrid_prepare_takes_device_lengths(): + """Like the other implementations: ``ctx_lens`` and ``kv_lens`` may be device tensors (``prepare`` reads them).""" + _skip_without_hybrid() + op = _op() + batch = 9 + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=2700, idx="fp4") + state = op.prepare( + inp["ctx_lens"], + inp["kv_lens"], + inp["idx_block_table"], + inp["sinks"], + config=H.SPEC_FP4, + ) + assert state.implementation == "tail_hybrid" + topk, out = H._new_outputs(batch) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def _guard_hybrid_lengths(monkeypatch, state): + """Make the logits op and the top-K fail, before they launch, on any lengths tensor but the state's own copy.""" + lengths = state.state.ctx_lens + k1_op, topk_run = _hybrid._k1_op, _topk.run + + def checked(ctx_lens): + assert ctx_lens.data_ptr() == lengths.data_ptr(), ( + "the launch must use the lengths of the state" + ) + + def guarded_k1_op(): + k1 = k1_op() + + def k1_checked(q, sf_q, kv, weights, ctx_lens, *args, **kwargs): + checked(ctx_lens) + return k1(q, sf_q, kv, weights, ctx_lens, *args, **kwargs) + + return k1_checked + + def topk_checked(logits, topk, ctx_lens, **kwargs): + checked(ctx_lens) + return topk_run(logits, topk, ctx_lens, **kwargs) + + monkeypatch.setattr(_hybrid, "_k1_op", guarded_k1_op) + monkeypatch.setattr(_topk, "run", topk_checked) + + +@pytest.mark.parametrize("device_lengths", ["shorter", "longer"]) +def test_hybrid_launch_uses_the_lengths_of_prepare(device_lengths, monkeypatch): + """The logits kernel and the top-K read the lengths ``prepare`` kept in the state, never the ``ctx_lens`` of the + launch (the logits kernel can hang on context lengths that differ from the ones its schedule was built from). With + device lengths 2,000 positions short or the longest possible, the launch completes and is exact for the lengths of + ``prepare``.""" + _skip_without_hybrid() + op = _op() + ns = [10492, 9000, 12000, 8200, 20000, 16500, 11111, 13000] + batch = len(ns) + inp, bases = H._make_case(batch, H._plain(ns), seed=3300, idx="fp4") + state = _prepare(op, inp, idx="fp4") + assert torch.equal(state.state.ctx_lens, inp["ctx_lens"]) + other = dict(inp) + other["ctx_lens"] = ( + inp["ctx_lens"] - 2000 + if device_lengths == "shorter" + else torch.full_like(inp["ctx_lens"], H.N_MAX) + ) + _guard_hybrid_lengths(monkeypatch, state) + topk, out = H._new_outputs(batch) + _launch(op, state, other, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def _strided(table): + """A view of ``table`` with the same values whose rows are twice as far apart.""" + wide = torch.zeros((table.shape[0], 2 * table.shape[1]), dtype=table.dtype, device=table.device) + wide[:, : table.shape[1]] = table + view = wide[:, : table.shape[1]] + assert not view.is_contiguous() + return view + + +@pytest.mark.parametrize("name", ["idx_block_table", "bt_swa", "bt_c"]) +def test_hybrid_refuses_strided_block_tables(name): + """The logits kernel and the tail attention are compiled for compact tensors: the hybrid refuses a strided block + table before it launches anything (``prepare`` the indexer table, ``run`` all three), unlike the megakernel + (``test_forced_megakernel_takes_strided_block_tables``).""" + _skip_without_hybrid() + op = _op() + batch = 9 + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=3400, idx="fp4") + state = _prepare(op, inp, idx="fp4") + strided = dict(inp) + strided[name] = _strided(inp[name]) + topk, out = H._new_outputs(batch) + if name == "idx_block_table": + with pytest.raises(ValueError, match=f"{name} must be a contiguous int32"): + _prepare(op, strided, idx="fp4") + with pytest.raises(ValueError, match=f"{name} must be a contiguous int32"): + _launch(op, state, strided, topk, out) + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def test_forced_megakernel_takes_strided_block_tables(): + """The megakernel reads strided block tables (``bt_c``: 16-byte aligned rows).""" + op = _op() + batch = 9 + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=3401, idx="fp4") + strided = dict(inp) + for name in ("idx_block_table", "bt_swa", "bt_c"): + strided[name] = _strided(inp[name]) + state = _prepare(op, strided, idx="fp4", implementation="megakernel") + topk, out = H._new_outputs(batch) + _launch(op, state, strided, topk, out) + torch.cuda.synchronize() + _check_error_bits(op, state) + H._check_rows(inp, bases, topk, out, "realistic") + + +def test_hybrid_error_bits_is_a_device_zero(): + """The hybrid has no device flag: ``error_bits`` is a persistent int32 [1] zero on the device.""" + _skip_without_hybrid() + op = _op() + inp, _ = H._make_case(6, H._plain(H.LENGTHS), seed=2800, idx="fp4") + state = _prepare(op, inp, idx="fp4") + bits = op.error_bits(state) + assert bits.dtype == torch.int32 and tuple(bits.shape) == (1,) and bits.is_cuda + assert int(bits) == 0 + assert op.error_bits(state).data_ptr() == bits.data_ptr() + + +def test_state_remembers_its_implementation_and_refuses_mismatches(): + """A state keeps the implementation it was built for: a refresh without ``implementation`` keeps it, a request for + another one or another batch size is an error.""" + _skip_without_hybrid() + op = _op() + inp, _ = H._make_case(8, H._plain(H.LENGTHS), seed=2900, idx="fp4") + hybrid = _prepare(op, inp, idx="fp4") + assert hybrid.implementation == "tail_hybrid" + assert _prepare(op, inp, state=hybrid, idx="fp4") is hybrid + assert _prepare(op, inp, state=hybrid, idx="fp4", implementation="tail_hybrid") is hybrid + with pytest.raises( + ValueError, match=re.escape("state is for 8 rows (tail_hybrid), got 8 rows (megakernel)") + ): + _prepare(op, inp, state=hybrid, idx="fp4", implementation="megakernel") + forced = _prepare(op, inp, idx="fp4", implementation="megakernel") + assert forced.implementation == "megakernel" + assert _prepare(op, inp, state=forced, idx="fp4") is forced # no keyword: the state's own + with pytest.raises( + ValueError, match=re.escape("state is for 8 rows (megakernel), got 8 rows (tail_hybrid)") + ): + _prepare(op, inp, state=forced, idx="fp4", implementation="tail_hybrid") + inp9, _ = H._make_case(9, H._plain(H.LENGTHS), seed=2901, idx="fp4") + with pytest.raises( + ValueError, match=re.escape("state is for 8 rows (tail_hybrid), got 9 rows (tail_hybrid)") + ): + _prepare(op, inp9, state=hybrid, idx="fp4") + with pytest.raises( + ValueError, match=re.escape("state is for 8 rows (megakernel), got 9 rows (tail_hybrid)") + ): + _prepare(op, inp9, state=forced, idx="fp4") + # a request that cannot serve the batch size is refused whatever the state + inp21, _ = H._make_case(21, H._plain(H.LENGTHS), seed=2902, idx="fp4") + with pytest.raises(ValueError, match="serves 1 to 20 rows"): + _prepare(op, inp21, idx="fp4", implementation="megakernel") + + +def test_hybrid_rejects_bad_arguments(): + _skip_without_hybrid() + op = _op() + batch = 6 + inp, bases = H._make_case(batch, H._plain(H.LENGTHS), seed=3100, idx="fp4") + state = _prepare(op, inp, idx="fp4") + topk, out = H._new_outputs(batch) + dev = torch.device("cuda") + + def launch(**changes): + op.run( + state, + *( + changes.get(k, inp[k]) + for k in ( + "q_idx", + "w_idx", + "k_cache", + "idx_block_table", + "ctx_lens", + "kv_lens", + "q_att", + "swa_pool", + "bt_swa", + "c_pool", + "bt_c", + ) + ), + changes.get("topk", topk), + changes.get("out", out), + softmax_scale=H.SM_SCALE, + q_scale=changes.get("q_scale", inp["q_scale"]), + ) + + with pytest.raises(ValueError, match="needs q_scale"): + launch(q_scale=None) + with pytest.raises(ValueError, match="q_scale must be contiguous"): + launch(q_scale=inp["q_scale"].float()) + with pytest.raises(ValueError, match="k_cache must hold 2176 bytes per page"): + launch(k_cache=torch.zeros((10, 2000), dtype=torch.uint8, device=dev)) + with pytest.raises(ValueError, match="ctx_lens must be contiguous"): + launch(ctx_lens=inp["ctx_lens"].long()) + with pytest.raises(ValueError, match="ctx_lens must be on the device"): + launch(ctx_lens=inp["ctx_lens"].cpu()) + with pytest.raises(ValueError, match="kv_lens must be contiguous"): + launch(kv_lens=inp["kv_lens"][:-1]) + with pytest.raises(ValueError, match="idx_block_table must be a contiguous int32"): + launch(idx_block_table=inp["idx_block_table"].long()) + with pytest.raises(ValueError, match="bt_swa must be a contiguous int32"): + launch(bt_swa=inp["bt_swa"].long()) + with pytest.raises(ValueError, match="bt_c must be a contiguous int32"): + launch(bt_c=inp["bt_c"].long()) + with pytest.raises(ValueError, match="topk must be contiguous"): + launch(topk=topk.long()) + with pytest.raises(ValueError, match="out must be a contiguous bfloat16"): + launch(out=out.float()) + with pytest.raises(ValueError, match="w_idx must be contiguous"): + launch(w_idx=inp["w_idx"].half()) + # prepare + ctx, kv, bt, sinks = ( + inp["ctx_lens"].cpu(), + inp["kv_lens"].cpu(), + inp["idx_block_table"], + inp["sinks"], + ) + short = ctx.clone() + short[0] = 300 + with pytest.raises(ValueError, match="compressed lengths"): + op.prepare(short, kv, bt, sinks, config=H.SPEC_FP4) + low = kv.clone() + low[0] = 100 + with pytest.raises(ValueError, match="uncompressed lengths"): + op.prepare(ctx, low, bt, sinks, config=H.SPEC_FP4) + with pytest.raises(ValueError, match="kv_lens must have 6 entries"): + op.prepare(ctx, kv[:-1], bt, sinks, config=H.SPEC_FP4) + with pytest.raises(ValueError, match="pages per row"): + op.prepare(ctx, kv, bt[:, :4].contiguous(), sinks, config=H.SPEC_FP4) + with pytest.raises(ValueError, match="CUDA tensor"): + op.prepare(ctx, kv, bt.cpu(), sinks, config=H.SPEC_FP4) + with pytest.raises(ValueError, match="sinks must have 64 entries"): + op.prepare(ctx, kv, bt, sinks[:8], config=H.SPEC_FP4) + # the refused launches changed nothing: the state still serves the step + _launch(op, state, inp, topk, out) + torch.cuda.synchronize() + H._check_rows(inp, bases, topk, out, "realistic") + + +def test_rejects_bad_arguments(): + op = _op() + dev = torch.device("cuda") + i32 = torch.int32 + sinks = torch.zeros(64, dtype=torch.float32, device=dev) + bt = torch.zeros((2, 128), dtype=i32, device=dev) + with pytest.raises(ValueError, match="sinks"): + op.prepare( + torch.tensor([4096], dtype=i32), + torch.tensor([16384], dtype=i32), + bt[:1], + sinks[:8], + ) + with pytest.raises(ValueError, match="compressed lengths"): + op.prepare(torch.tensor([300], dtype=i32), torch.tensor([1200], dtype=i32), bt[:1], sinks) + state = op.prepare( + torch.tensor([4096], dtype=i32), torch.tensor([16384], dtype=i32), bt[:1], sinks + ) + with pytest.raises(ValueError, match="state is for"): + op.prepare( + torch.full((2,), 4096, dtype=i32), + torch.full((2,), 16384, dtype=i32), + bt, + sinks, + state=state, + ) + # a state keeps the spec it was built for + other = dataclasses.replace(H.SPEC, name="other", topk=1024) + with pytest.raises(ValueError, match="state is for"): + op.prepare( + torch.tensor([4096], dtype=i32), + torch.tensor([16384], dtype=i32), + bt[:1], + sinks, + state=state, + config=other, + ) + assert state.config is H.SPEC + many = H.SPEC.megakernel_max_batch + 1 + bt_many = torch.zeros((many, 128), dtype=i32, device=dev) + large_state = op.prepare( + torch.full((many,), 4096, dtype=i32), torch.full((many,), 16384, dtype=i32), bt_many, sinks + ) + with pytest.raises(ValueError, match="state is for"): + op.prepare( + torch.full((1,), 4096, dtype=i32), + torch.full((1,), 16384, dtype=i32), + bt[:1], + sinks, + state=large_state, + ) diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_tail.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_tail.py new file mode 100644 index 000000000000..4d1f68579c53 --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_tail.py @@ -0,0 +1,1345 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA tail attention (``tail_op``, CuTe DSL, SM100) against an fp64 reference of the decode sparse MLA. + +The tail attention takes the exact top-512 selection of any top-K kernel (here an input, so the tests also feed +selections the real top-K never produces: -1 padded, fewer than 512 positions, a whole tile of -1, no selection) and +runs the sparse MLA over the sliding window plus the selected compressed rows with the attention sink. One cluster of +5 CTAs serves a row, up to 26 rows (the clusters of 5 that fit one wave of the 148 SMs; clusters of 4 and 3 for 27 to 45 +rows are not offered: they leave only 0.5 to 0.8 % of numerical margin and win nothing over the large-batch kernels). +The attention does not depend on the indexer K dtype: one compile serves both specs (FP8 and FP4), and both are +launched and checked. Rows with a window shorter than 128 rows (kv_len 1, 127, 128, 129, ...) and rows with fewer than +512 compressed positions are part of every mixture; the reference takes the window as the last ``min(128, kv_len)`` +positions and ignores the -1 entries. + +Three attention modes, each with the bar of its kind: + +- ``realistic``: random queries and KV rows, calc_diff < 1e-3 as in the other specDSA tests. The FP8 quantization of P + (E4M3 at the running maximum) sets the floor of this mode: 2.5e-4 on this data (the real-capture gates, whose + attention is more peaked, run at 6.0e-5). +- ``gather_exact``: every score of a row is bit-equal, so P is exact and one wrong, missing or unmasked KV row is + visible far above the bf16 noise (calc_diff < 2e-5 on the 448 columns that carry the KV rows; measured 3e-6). +- ``pow2``: with the softmax scale ln 2 every score is an integer number of bits (a query with one non-zero element, + KV rows with an element that is -2 m), so every softmax weight is an exact power of two and P is exact in E4M3 *with + different row maxima in the tiles of a row*: the combine of the cluster (the weights 2^(m_i - m*) of the partial + outputs) is checked at the tight bar too (calc_diff < 2e-5 on all columns; only the bf16 roundings remain). +""" + +import dataclasses +import inspect +import math + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import DS_V4_FLASH as SPEC +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import ( + DS_V4_FLASH_FP4 as SPEC_FP4, +) +from tensorrt_llm._utils import get_sm_version + +from . import test_cute_dsl_spec_dsa_large_batch as H + +K_TOP, H_ATT, D_ATT = SPEC.topk, SPEC.attn_heads, SPEC.kv_dim +TPB_C, TPB_SWA, WINDOW, RATIO = ( + SPEC.kv_page_rows, + SPEC.swa_page_rows, + SPEC.window, + SPEC.compress_ratio, +) +SM_SCALE = SPEC.default_softmax_scale +LN2 = math.log(2.0) +# An indexer shape without kernels: top-1024 instead of top-512. +PRO = dataclasses.replace(SPEC, name="DS-V4-Pro", topk=1024) + +# The tail attention serves 1 to 26 rows with one cluster of 5 CTAs per row; 27 rows and more are refused. +MAX_ROWS, CLUSTER = 26, 5 +BATCHES = [1, 2, 5, 8, 16, 24, 25, 26] +REFUSED = [27, 33, 34, 45, 46, 148, 1024] +ATTN_MODES = ["realistic", "gather_exact", "pow2"] +CD_REALISTIC = 1e-3 +CD_EXACT = 2e-5 + + +def _scale_of(attn): + return LN2 if attn == "pow2" else SM_SCALE + + +def _tail(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + return tail_op + + +def _supported() -> bool: + return torch.cuda.is_available() and get_sm_version() == 100 and _tail().is_supported()[0] + + +requires_b200 = pytest.mark.skipif( + not _supported(), reason="clusters of 5 CTAs on 148 SMs, qualified on B200 only" +) + + +def _spec_of(name): + return SPEC_FP4 if name == "fp4" else SPEC + + +@pytest.fixture(params=["fp4", "fp8"]) +def spec_name(request): + """The spec under test: the attention is the same, one compile serves both.""" + return request.param + + +# (kv_len, selection pattern). nc = kv_len // 4 compressed positions exist. The patterns: +# dense: every position that exists (at most 512) at random slots of the 512 entries; +# holes: dense with a quarter of the entries replaced by -1; +# short: at most 300 positions at the front, the rest -1; +# tile_gap: dense with one whole 128-entry tile of -1; +# sorted: dense in ascending order; +# one / last: a single position at slot 255 / 511; +# none: no selection, the window and the sink only. +ROW_KINDS = [ + (1048579, "dense"), # 2**18 compressed positions, the longest row + (131075, "holes"), + (262147, "tile_gap"), + ( + 129, + "dense", + ), # a window of 128 rows over two pages (positions 1 to 128), 32 compressed positions + (1, "none"), # a window of one row, no compressed position + (100003, "dense"), + (127, "dense"), # a window of 127 rows, 31 compressed positions + (65539, "short"), + (128, "holes"), # a window of exactly 128 rows (positions 0 to 127) + (8193, "sorted"), + (257, "dense"), # a window from position 129: two pages + (2, "none"), # a window of two rows + (4100, "dense"), + (256, "dense"), # a window of exactly one page (positions 128 to 255) + (2051, "one"), + (513, "dense"), # 128 compressed positions: fewer than 512 exist + (100000, "last"), + (4, "one"), # a window of 4 rows, a single compressed position + (40001, "tile_gap"), + (255, "dense"), +] + + +def _rows(batch, rot=0): + return [ROW_KINDS[(b + rot) % len(ROW_KINDS)] for b in range(batch)] + + +def _selection(pattern, nc, gen): + """int32 [512]: local compressed positions of one row in no particular order, -1 for an unused entry.""" + sel = torch.full((K_TOP,), -1, dtype=torch.int32) + take = min(nc, K_TOP) + if pattern == "none" or take == 0: + return sel + pos = torch.randperm(nc, generator=gen)[:take].to(torch.int32) + if pattern == "sorted": + sel[:take] = torch.sort(pos).values + elif pattern == "short": + m = min(take, 300) + sel[:m] = pos[:m] + elif pattern == "one": + sel[255] = pos[0] + elif pattern == "last": + sel[K_TOP - 1] = pos[0] + else: # dense, holes, tile_gap: at random slots + sel[torch.randperm(K_TOP, generator=gen)[:take]] = pos + if pattern == "holes": + sel[torch.rand(K_TOP, generator=gen) < 0.25] = -1 + elif pattern == "tile_gap": + tile = int(torch.randint(0, K_TOP // 128, (1,), generator=gen)) + sel[tile * 128 : (tile + 1) * 128] = -1 + return sel + + +@torch.no_grad() +def _make_case(rows, seed, attn="realistic"): + """Attention inputs for ``len(rows)`` rows, rows = [(kv_len, pattern), ...], and the selections [B, 512]. + + Rows with the same kv_len share their compressed KV pages (random physical page ids); every row has its own + window pages. The pages a row does not read (window rows after its last position, the spare pages) hold + poison: the largest values, so that a row that is not masked shows up in the output. + """ + dev = torch.device("cuda") + batch = len(rows) + gh = torch.Generator().manual_seed(seed) + gd = torch.Generator(device=dev).manual_seed(seed + 1) + + def rnd(*shape): + return torch.randn(*shape, generator=gd, device=dev) + + kv_lens = [kv for kv, _ in rows] + base_of = {} + for kv in kv_lens: + base_of.setdefault(kv, len(base_of)) + nb = len(base_of) + if attn == "gather_exact": + # scores depend only on dims [0, 64), shared by every KV row of a base + q_att = torch.randint(-2, 3, (batch, H_ATT, D_ATT), generator=gd, device=dev).float() * 0.25 + q_att[:, :, 64:] = 0.0 + key = torch.randint(-2, 3, (nb, 64), generator=gd, device=dev).float() * 0.25 + elif attn == "pow2": + # score = q[0] * k[0] with q[0] in {1/2, 1, 2} per head and k[0] = -2 m, m in 0..3 per KV row: with the softmax + # scale ln 2 the exponent of every weight is an integer + q_att = torch.zeros(batch, H_ATT, D_ATT, device=dev) + q_att[:, :, 0] = torch.tensor([0.5, 1.0, 2.0], device=dev).repeat(H_ATT // 3 + 1)[:H_ATT] + else: + q_att = rnd(batch, H_ATT, D_ATT) + q_att = H._e4m3(q_att).reshape(batch, H_ATT * D_ATT) + + def kv_rows(j, r, m=None): + x = rnd(r, D_ATT) + if attn == "gather_exact": + x[:, :64] = key[j] + elif attn == "pow2": + x[:, 0] = -2.0 * m + return H._e4m3(x).view(torch.uint8) + + poison = torch.full((D_ATT,), 448.0, device=dev) + poison[:64] = -448.0 + poison = H._e4m3(poison).view(torch.uint8) + # two window pages per row (the window spans at most two), then a poison spare + n_swa = 2 * batch + 1 + swa_pool = torch.empty((n_swa, TPB_SWA, D_ATT), dtype=torch.uint8, device=dev) + swa_pool[n_swa - 1] = poison + perm_s = torch.randperm(2 * batch, generator=gh) + bt_swa = torch.full((batch, max(kv_lens) // TPB_SWA + 1), n_swa - 1, dtype=torch.int32) + for b in range(batch): + hi = (kv_lens[b] - 1) // TPB_SWA + for t, blk in enumerate((hi - 1, hi)): + page = int(perm_s[2 * b + t]) + if blk >= 0: + bt_swa[b, blk] = page + # pow2: the window rows have m = 1, 2, 3, 1, ...: a window maximum below the maximum of the selected rows + m_win = 1.0 + torch.arange(TPB_SWA, device=dev) % 3 + swa_pool[page] = kv_rows(base_of[kv_lens[b]], TPB_SWA, m_win) + # compressed KV pages of every base (at least one page: the table row is never empty) + ncs = {kv: kv // RATIO for kv in base_of} + pg_c = {kv: max(1, H._cdiv(nc, TPB_C)) for kv, nc in ncs.items()} + n_c = sum(pg_c.values()) + 1 + c_pool = torch.empty((n_c, TPB_C, D_ATT), dtype=torch.uint8, device=dev) + c_pool[n_c - 1] = poison + perm_c = torch.randperm(n_c - 1, generator=gh) + bt_row, off = {}, 0 + for kv, j in base_of.items(): + pages = perm_c[off : off + pg_c[kv]] + off += pg_c[kv] + # pow2: m grows with the position, 0 in the first quarter of the row to 3 in the last: the tiles of a selection + # in ascending order have different maxima + m_pos = (torch.arange(pg_c[kv] * TPB_C, device=dev) * 4 // max(ncs[kv], 1)).clamp(max=3) + c_pool[pages.to(dev)] = kv_rows(j, pg_c[kv] * TPB_C, m_pos.float()).view( + pg_c[kv], TPB_C, D_ATT + ) + bt_row[kv] = pages.to(torch.int32) + bt_c = torch.full((batch, H._cdiv(max(pg_c.values()), 4) * 4), n_c - 1, dtype=torch.int32) + for b in range(batch): + pages = bt_row[kv_lens[b]] + bt_c[b, : pages.numel()] = pages + sel = torch.stack([_selection(p, ncs[kv], gh) for kv, p in rows]) + sinks = (torch.linspace(-6.0, 9.0, H_ATT, device=dev) + 0.1 * rnd(H_ATT)).float() + inp = { + "q_att": q_att, + "swa_pool": swa_pool.view(torch.float8_e4m3fn), + "bt_swa": bt_swa.to(dev), + "c_pool": c_pool.view(torch.float8_e4m3fn), + "bt_c": bt_c.to(dev), + "kv_lens": torch.tensor(kv_lens, dtype=torch.int32, device=dev), + "sinks": sinks.contiguous(), + "topk": sel.to(dev), + } + return inp + + +@torch.no_grad() +def _ref_attention(inp, b, scale): + """fp64 sparse MLA of row b over its window (the last min(128, kv_len) positions) and the selected rows (not -1).""" + pos = int(inp["kv_lens"][b]) - 1 + p = torch.arange(max(0, pos - WINDOW + 1), pos + 1, device=inp["topk"].device) + swa_rows = inp["bt_swa"][b, p // TPB_SWA].long() * TPB_SWA + p % TPB_SWA + sel = inp["topk"][b].long() + sel = sel[sel >= 0] + c_rows = inp["bt_c"][b, sel // TPB_C].long() * TPB_C + sel % TPB_C + swa = inp["swa_pool"].view(torch.uint8).reshape(-1, D_ATT) + cpl = inp["c_pool"].view(torch.uint8).reshape(-1, D_ATT) + kv = torch.cat([swa[swa_rows], cpl[c_rows]], 0).view(torch.float8_e4m3fn).double() + q = inp["q_att"][b].view(H_ATT, D_ATT).double() + s = (q @ kv.t()) * scale + m = s.amax(-1, keepdim=True) + e = torch.exp(s - m) + den = e.sum(-1, keepdim=True) + torch.exp(inp["sinks"].double().view(-1, 1) - m) + return (e @ kv) / den + + +def _check_rows(inp, out, attn, scale=None): + """Every row of ``out`` against the reference (the scale of the mode unless given); the largest calc_diff.""" + scale = _scale_of(attn) if scale is None else scale + cols = ( + slice(64, None) if attn == "gather_exact" else slice(None) + ) # gather_exact: dims 0-63 are the score key + worst = 0.0 + for b in range(out.shape[0]): + ref = _ref_attention(inp, b, scale) + o = out[b].view(H_ATT, D_ATT).double() + assert bool(torch.isfinite(o).all()), f"row {b}: non-finite output" + cd = H._calc_diff(o[:, cols], ref[:, cols]) + if attn == "realistic": + assert cd < CD_REALISTIC, f"row {b}: calc_diff {cd:.3e}" + else: + assert cd < CD_EXACT, f"row {b}: calc_diff {cd:.3e}" + assert float((o - ref).abs().max()) <= 2.0**-6 * float(ref.abs().max()), f"row {b}" + worst = max(worst, cd) + return worst + + +def _launch(inp, out, spec, scale=SM_SCALE): + _tail().run_attention( + inp["topk"], + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["kv_lens"], + inp["sinks"], + out, + scale, + config=spec, + ) + + +def _run_and_check(inp, out, spec, attn): + out.zero_() + _launch(inp, out, spec, _scale_of(attn)) + torch.cuda.synchronize() + return _check_rows(inp, out, attn) + + +def _new_out(batch): + return torch.zeros((batch, H_ATT * D_ATT), dtype=torch.bfloat16, device="cuda") + + +def _compiled_clusters(): + """Cluster sizes the op has compiled on the current device (one compile serves both specs).""" + dev = torch.cuda.current_device() + return {key[1] for key in _tail()._compiled if key[0] == dev} + + +# -------------------------------------------------------------------------------------------------------------------- +# host side (no GPU) + + +def test_cluster_size_table(): + tail = _tail() + assert tail.TAIL_MAX_BATCH == MAX_ROWS + assert [tail.tail_cluster_size(b) for b in range(1, MAX_ROWS + 1)] == [CLUSTER] * MAX_ROWS + for bad in (-1, 0, *REFUSED): + assert tail.tail_cluster_size(bad) is None + # a cluster of 5 CTAs per row, all rows resident in one wave of the 148 SMs + assert MAX_ROWS * CLUSTER <= 148 + + +def test_cluster_sizes_of_the_op_are_the_ones_of_the_kernel(): + """The op offers the cluster sizes the kernel is built and validated for, and the kernel refuses the others.""" + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + tail = _tail() + assert {tail.tail_cluster_size(b) for b in range(1, MAX_ROWS + 1)} == set( + TA.SUPPORTED_CLUSTER_SIZES + ) + assert TA.SUPPORTED_CLUSTER_SIZES == (CLUSTER,) + + +def test_batch_size_support(): + tail = _tail() + for b in range(1, MAX_ROWS + 1): + assert tail.is_batch_size_supported(b) == (True, "") + for bad in (-1, 0, *REFUSED): + ok, why = tail.is_batch_size_supported(bad) + assert not ok and f"batch size {bad} not in [1, {MAX_ROWS}]" in why + + +def test_is_supported_has_the_signature_of_the_other_ops(): + """is_supported(device, config) like the megakernel's and the large batch's (the batch size has its own helper).""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import ( + large_batch_op, + megakernel_op, + ) + + def params(fn): + return list(inspect.signature(fn).parameters) + + assert params(_tail().is_supported) == ["device", "config"] + assert params(_tail().is_supported) == params(megakernel_op.is_supported) + assert params(_tail().is_supported) == params(large_batch_op.is_supported) + + +def test_is_supported_host_checks(): + tail = _tail() + ok, why = tail.is_supported(config=PRO) + assert not ok and "DS-V4-Pro" in why + # a supported spec: the answer is the device check + for spec in (None, SPEC, SPEC_FP4): + ok, why = tail.is_supported(config=spec) + assert ok == (not why) + + +def test_default_config_of_every_entry_point_is_the_same(): + """precompile, run_attention and run_hybrid take ``config=None`` (the default spec): none of them has its own.""" + tail = _tail() + for fn in (tail.precompile, tail.run_attention, tail.run_hybrid): + assert inspect.signature(fn).parameters["config"].default is None, fn.__name__ + + +@requires_b200 +def test_is_supported_on_b200(): + tail = _tail() + for spec in (None, SPEC, SPEC_FP4): + assert tail.is_supported(torch.device("cuda"), spec) == (True, "") + assert tail.is_supported(config=spec) == (True, "") + + +def _host_args(batch, topk_cols=K_TOP): + """Valid CPU arguments of run_attention (the checks run before any device work).""" + i32 = torch.int32 + return dict( + topk=torch.full((batch, topk_cols), -1, dtype=i32), + q_att=torch.zeros((batch, H_ATT * D_ATT), dtype=torch.float8_e4m3fn), + swa_pool=torch.zeros((2 * batch, TPB_SWA, D_ATT), dtype=torch.float8_e4m3fn), + bt_swa=torch.zeros((batch, 4), dtype=i32), + c_pool=torch.zeros((4, TPB_C, D_ATT), dtype=torch.float8_e4m3fn), + bt_c=torch.zeros((batch, 4), dtype=i32), + kv_lens=torch.full((batch,), 1000, dtype=i32), + sinks=torch.zeros(H_ATT), + out=torch.zeros((batch, H_ATT * D_ATT), dtype=torch.bfloat16), + ) + + +def test_rejects_batches_above_26(): + tail = _tail() + for bad in (0, *REFUSED): + with pytest.raises(ValueError, match=rf"batch size {bad} not in \[1, {MAX_ROWS}\]"): + tail.run_attention(**_host_args(bad)) + for config in (SPEC, SPEC_FP4): + with pytest.raises(ValueError, match=rf"batch size {bad} not in \[1, {MAX_ROWS}\]"): + tail.precompile(torch.device("cuda"), bad, config) + + +def _transposed(t): + return t.t().contiguous().t() + + +def _rows_of_256_bytes(t): + return t[..., :256].contiguous() + + +# (argument, a variant of it, the error). topk gives the row count B: with another row count the other arguments fail. +BAD_ARGUMENTS = [ + ("topk", lambda t: t.to(torch.int64), r"topk must be a contiguous int32 \[B, 512\] tensor"), + ( + "topk", + lambda t: t[:, :-1].contiguous(), + r"topk must be a contiguous int32 \[B, 512\] tensor", + ), + ("topk", _transposed, r"topk must be a contiguous int32 \[B, 512\] tensor"), + ("topk", lambda t: t.reshape(-1), r"topk must be a contiguous int32 \[B, 512\] tensor"), + ( + "topk", + lambda t: t[:3].contiguous(), + "q_att must be a contiguous FP8 tensor with 3 x 64 x 512", + ), + ( + "q_att", + lambda t: t.to(torch.bfloat16), + "q_att must be a contiguous FP8 tensor with 4 x 64 x 512", + ), + ( + "q_att", + lambda t: t[:3].contiguous(), + "q_att must be a contiguous FP8 tensor with 4 x 64 x 512", + ), + ("q_att", _transposed, "q_att must be a contiguous FP8 tensor with 4 x 64 x 512"), + ("swa_pool", _rows_of_256_bytes, "swa_pool must be a contiguous FP8 tensor with 512-byte rows"), + ( + "swa_pool", + lambda t: t.reshape(-1), + "swa_pool must be a contiguous FP8 tensor with 512-byte rows", + ), + ( + "swa_pool", + lambda t: t.to(torch.bfloat16), + "swa_pool must be a contiguous FP8 tensor with 512-byte", + ), + ( + "swa_pool", + lambda t: t.transpose(0, 1), + "swa_pool must be a contiguous FP8 tensor with 512-byte", + ), + ("c_pool", _rows_of_256_bytes, "c_pool must be a contiguous FP8 tensor with 512-byte rows"), + ( + "c_pool", + lambda t: t.reshape(-1), + "c_pool must be a contiguous FP8 tensor with 512-byte rows", + ), + ( + "c_pool", + lambda t: t.to(torch.bfloat16), + "c_pool must be a contiguous FP8 tensor with 512-byte", + ), + ("c_pool", lambda t: t.transpose(0, 1), "c_pool must be a contiguous FP8 tensor with 512-byte"), + ("bt_swa", lambda t: t.to(torch.int64), "bt_swa must be a contiguous int32"), + ("bt_swa", lambda t: t[0], "bt_swa must be a contiguous int32"), + ("bt_swa", lambda t: t[:3].contiguous(), "bt_swa must be a contiguous int32"), + ("bt_swa", _transposed, "bt_swa must be a contiguous int32"), + ("bt_c", lambda t: t.to(torch.int16), "bt_c must be a contiguous int32"), + ("bt_c", lambda t: t[0], "bt_c must be a contiguous int32"), + ("bt_c", lambda t: t[:3].contiguous(), "bt_c must be a contiguous int32"), + ("bt_c", _transposed, "bt_c must be a contiguous int32"), + ( + "kv_lens", + lambda t: t.to(torch.int64), + "kv_lens must be a contiguous int32 tensor with 4 elements", + ), + ( + "kv_lens", + lambda t: t[:3].contiguous(), + "kv_lens must be a contiguous int32 tensor with 4 elements", + ), + ( + "kv_lens", + lambda t: torch.arange(8, dtype=t.dtype)[::2], + "kv_lens must be a contiguous int32", + ), + ( + "sinks", + lambda t: t.to(torch.float16), + "sinks must be a contiguous float32 tensor with 64 elements", + ), + ( + "sinks", + lambda t: t[:32].contiguous(), + "sinks must be a contiguous float32 tensor with 64 elements", + ), + ( + "sinks", + lambda t: torch.zeros(128)[::2], + "sinks must be a contiguous float32 tensor with 64 elements", + ), + ("out", lambda t: t.float(), "out must be a contiguous bfloat16 tensor with 4 x 64 x 512"), + ( + "out", + lambda t: t[:3].contiguous(), + "out must be a contiguous bfloat16 tensor with 4 x 64 x 512", + ), + ("out", _transposed, "out must be a contiguous bfloat16 tensor with 4 x 64 x 512"), +] + + +@pytest.mark.parametrize( + "name, variant, match", + [pytest.param(*c, id=f"{i}-{c[0]}") for i, c in enumerate(BAD_ARGUMENTS)], +) +def test_rejects_bad_arguments(name, variant, match): + args = _host_args(4) + args[name] = variant(args[name]) + with pytest.raises(ValueError, match=match): + _tail().run_attention(**args) + + +def test_rejects_tensors_that_are_not_on_a_cuda_device(): + """Valid arguments on the CPU: the kernel reads device memory.""" + with pytest.raises(ValueError, match="must be CUDA tensors, got q_att on cpu"): + _tail().run_attention(**_host_args(4)) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") +def test_rejects_tensors_on_other_devices(): + """Every tensor must be on the device of q_att: a tensor on the CPU is refused by name.""" + tail = _tail() + args = {k: v.cuda() for k, v in _host_args(4).items()} + for name in args: + if name == "q_att": + continue + bad = dict(args) + bad[name] = args[name].cpu() + with pytest.raises( + ValueError, match=rf"{name} must be on the device of q_att \(cuda:\d+\), got cpu" + ): + tail.run_attention(**bad) + bad = dict(args) + bad["q_att"] = args["q_att"].cpu() + with pytest.raises(ValueError, match="must be CUDA tensors, got q_att on cpu"): + tail.run_attention(**bad) + + +def test_unsupported_spec_is_refused_before_any_device_work(): + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + tail = _tail() + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + tail.precompile(torch.device("cpu"), 4, PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + tail.run_attention(**_host_args(4, topk_cols=PRO.topk), config=PRO) + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + # only the cluster size 5 is built and validated: 4 and 3 (27 to 45 rows) are refused, as is anything else + for g in (0, 1, 2, 3, 4, 6, 8): + with pytest.raises(ValueError, match="cluster size"): + TA.TailAttention(g, SPEC) + with pytest.raises(NotImplementedError, match="specialized for"): + TA.TailAttention(5, PRO) + for spec in (SPEC, SPEC_FP4): + assert TA.TailAttention(CLUSTER, spec).g == CLUSTER + + +def test_run_hybrid_calls_the_stages_in_order(monkeypatch): + """K1 logits, then the top-K kernel on those logits, then the tail attention with the caller's tensors.""" + tail = _tail() + calls = [] + args = _host_args(3) + logits = object() + + def k1(): + calls.append("k1") + return logits + + def topk_fn(x): + assert x is logits, "the top-K stage gets the logits the K1 stage returned" + calls.append("topk") + + def fake_attention(*a, **kw): + calls.append(("attention", a, kw)) + + monkeypatch.setattr(tail, "run_attention", fake_attention) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + tail.run_hybrid(k1, topk_fn, *(args[n] for n in names), 0.125, config=SPEC) + assert calls[:2] == ["k1", "topk"] and len(calls) == 3 + _, a, kw = calls[2] + assert len(a) == 10 and all(x is args[n] for x, n in zip(a, names)) and a[9] == 0.125 + assert kw == { + "config": SPEC, + "pdl": False, + "poll": False, + } # a caller's top-K kernel never triggers early and never arms its output: no pdl, no poll + # no config: the default of run_attention (the kernel is the same for both specs) + calls.clear() + tail.run_hybrid(k1, topk_fn, *(args[n] for n in names)) + assert calls[2][1][9] is None and calls[2][2]["config"] is None + + +# -------------------------------------------------------------------------------------------------------------------- +# kernel + + +@requires_b200 +@pytest.mark.parametrize("attn", ATTN_MODES) +@pytest.mark.parametrize("rot", [0, 7]) +@pytest.mark.parametrize("batch", BATCHES) +def test_matches_reference(batch, rot, attn): + """Batch sizes on both sides of every cluster-size boundary, rows of every kind (FP4 spec).""" + inp = _make_case(_rows(batch, rot), seed=1000 * batch + 10 * rot + len(attn), attn=attn) + _run_and_check(inp, _new_out(batch), SPEC_FP4, attn) + assert _compiled_clusters() == {CLUSTER} + + +@requires_b200 +@pytest.mark.parametrize("attn", ATTN_MODES) +@pytest.mark.parametrize("batch", [1, 8, MAX_ROWS]) +def test_fp8_spec_matches_reference(batch, attn): + """The same attention behind the FP8 spec (the compile of the FP4 spec serves it).""" + inp = _make_case(_rows(batch, 3), seed=77 * batch + len(attn), attn=attn) + _run_and_check(inp, _new_out(batch), SPEC, attn) + assert _compiled_clusters() == {CLUSTER} + + +# Windows of 1 to 5 rows, around 32 / 64 rows, around the 128-row window and around the page edge at 256 positions. +SHORT_KV_LENS = [ + 1, + 2, + 3, + 4, + 5, + 8, + 31, + 32, + 33, + 63, + 64, + 65, + 126, + 127, + 128, + 129, + 130, + 131, + 255, + 256, + 257, +] + + +@requires_b200 +@pytest.mark.parametrize("attn", ATTN_MODES) +@pytest.mark.parametrize("batch", [21, MAX_ROWS]) +def test_short_windows(batch, attn): + """Every kv_len of SHORT_KV_LENS in the batch (rows with fewer than 4 positions have no compressed position).""" + kv_lens = (SHORT_KV_LENS * 3)[:batch] + rows = [(kv, "dense" if b % 3 else "holes") for b, kv in enumerate(kv_lens)] + inp = _make_case(rows, seed=500 + batch + len(attn), attn=attn) + _run_and_check(inp, _new_out(batch), SPEC_FP4, attn) + + +@requires_b200 +@pytest.mark.parametrize("attn", ATTN_MODES) +@pytest.mark.parametrize("batch", [1, 8, MAX_ROWS]) +def test_empty_and_sparse_selections(batch, attn): + """No selection (the window and the sink), a single position, and every pattern at the longest lengths.""" + kinds = ["none", "one", "last", "short", "tile_gap", "holes", "sorted", "dense"] + rows = [(1048579 if b % 2 else 524291, kinds[b % len(kinds)]) for b in range(batch)] + inp = _make_case(rows, seed=600 + batch + len(attn), attn=attn) + out = _new_out(batch) + _run_and_check(inp, out, SPEC_FP4, attn) + inp["topk"].fill_(-1) # all rows without a selection + _run_and_check(inp, out, SPEC_FP4, attn) + + +@requires_b200 +def test_softmax_scale_and_sinks_are_read(): + """The scale is a launch argument, the sinks a tensor: both change the result as the reference says.""" + inp = _make_case(_rows(8, 2), seed=700) + out = _new_out(8) + for scale in (SM_SCALE, 0.03, 0.2): + out.zero_() + _launch(inp, out, SPEC_FP4, scale) + torch.cuda.synchronize() + _check_rows(inp, out, "realistic", scale) + inp["sinks"].add_(3.0) + _run_and_check(inp, out, SPEC_FP4, "realistic") + + +@requires_b200 +@pytest.mark.parametrize("batch", [2, 16, MAX_ROWS]) +def test_deterministic_and_batch_invariant(batch): + """Launches repeat bit for bit (a race inside the cluster would show as a differing launch); a row gives the + same bits alone as inside a batch.""" + inp = _make_case(_rows(batch, 1), seed=800 + batch) + first = _new_out(batch) + _launch(inp, first, SPEC_FP4) + for launch in range(60): + out = _new_out(batch) # zeros: a row that is not written shows as a difference + _launch(inp, out, SPEC_FP4) + assert torch.equal(out, first), f"launch {launch} differs from the first launch" + _check_rows(inp, first, "realistic") + # the first row alone (batch 1) equals that row inside the batch + row_keys = ("q_att", "bt_swa", "bt_c", "kv_lens", "topk") + one = {k: (v[:1] if k in row_keys else v) for k, v in inp.items()} + out1 = _new_out(1) + _launch(one, out1, SPEC_FP4) + torch.cuda.synchronize() + assert torch.equal(out1[0], first[0]) + + +@requires_b200 +def test_batch_sizes_up_and_down_do_not_leak(): + """The op keeps nothing but the compiled kernel: batch sizes up and down in one process give the right result each + time.""" + for batch in (MAX_ROWS, 2, 24, 1, 16): + inp = _make_case(_rows(batch, batch), seed=900 + batch, attn="pow2") + _run_and_check(inp, _new_out(batch), SPEC_FP4, "pow2") + + +def _capture(fn): + """Warm up on a side stream (as the other specDSA tests do), then capture ``fn`` into a CUDA graph.""" + side = torch.cuda.Stream() + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side): + fn() + torch.cuda.current_stream().wait_stream(side) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + fn() + return graph + + +@requires_b200 +@pytest.mark.parametrize("attn", ["realistic", "pow2"]) +@pytest.mark.parametrize("batch", [8, MAX_ROWS]) +def test_cuda_graph_replay(batch, attn, spec_name): + """One captured launch replays over several steps; the inputs change in place (selection, lengths, pages).""" + spec = _spec_of(spec_name) + rows = _rows(batch, 2) + steps = [rows[r:] + rows[:r] for r in (0, 3, 5)] # same pool sizes, other rows get other kinds + inp = _make_case(steps[0], seed=1100 + batch, attn=attn) + _tail().precompile(torch.device("cuda"), batch, spec) + out = _new_out(batch) + graph = _capture(lambda: _launch(inp, out, spec, _scale_of(attn))) + for step, rows in enumerate(steps): + if step: + new = _make_case(rows, seed=1100 + batch + step, attn=attn) + for key, buf in inp.items(): + assert buf.shape == new[key].shape, key + buf.copy_(new[key]) + out.zero_() + graph.replay() + torch.cuda.synchronize() + _check_rows(inp, out, attn) + + +@requires_b200 +@pytest.mark.parametrize("index", [None, 0], ids=["device-cuda", "device-cuda-0"]) +def test_precompile_covers_the_device_of_the_tensors(monkeypatch, index): + """precompile(device, ...) compiles what run_attention needs for tensors on that device, however the device is + spelled (``cuda`` or ``cuda:0``): the launch after it compiles nothing.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + tail = _tail() + compiles = [] + real_compile = TA.compile_tail_attention + monkeypatch.setattr( + TA, "compile_tail_attention", lambda t: (compiles.append(t.g), real_compile(t))[1] + ) + monkeypatch.setattr(tail, "_compiled", {}) # as in a fresh process + inp = _make_case(_rows(8, 4), seed=1250) + out = _new_out(8) + device = torch.device("cuda", index) if index is not None else torch.device("cuda") + tail.precompile(device, 8, SPEC_FP4) + assert compiles == [5] + _run_and_check(inp, out, SPEC_FP4, "realistic") + assert compiles == [5], ( + "the launch compiled again: precompile did not cover the tensors' device" + ) + + +@requires_b200 +def test_one_compile_serves_both_specs_and_every_batch_size(monkeypatch): + """The kernel does not depend on the indexer K dtype or on the batch size: the FP8 spec, the FP4 spec and the + default config share one compile per device.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + tail = _tail() + compiles = [] + real_compile = TA.compile_tail_attention + monkeypatch.setattr( + TA, "compile_tail_attention", lambda t: (compiles.append(t.g), real_compile(t))[1] + ) + monkeypatch.setattr(tail, "_compiled", {}) + for batch, config in ((8, SPEC_FP4), (8, SPEC), (26, None), (1, SPEC_FP4), (16, SPEC)): + inp = _make_case(_rows(batch, 2), seed=1260 + batch) + _run_and_check(inp, _new_out(batch), config, "realistic") + tail.precompile(torch.device("cuda"), 24, SPEC) + tail.precompile(torch.device("cuda"), 3) + assert compiles == [5] + assert _compiled_clusters() == {CLUSTER} + + +@requires_b200 +@pytest.mark.parametrize( + "run_config", [None, SPEC, SPEC_FP4], ids=["run-default", "run-fp8", "run-fp4"] +) +@pytest.mark.parametrize( + "pre_config", [None, SPEC, SPEC_FP4], ids=["pre-default", "pre-fp8", "pre-fp4"] +) +def test_precompile_then_captured_hybrid(monkeypatch, pre_config, run_config): + """precompile(device, batch) followed by a CUDA-graph capture of run_hybrid compiles nothing during the capture, + whichever spec each call names (``None``: the default of both): there is no warm-up launch in between.""" + tail = _tail() + batch = 8 + monkeypatch.setattr(tail, "_compiled", {}) # as in a fresh process + inp = _make_case(_rows(batch, 5), seed=1500 + batch) + sel = inp["topk"].clone() + topk = torch.full_like(sel, -1) + logits = torch.zeros(batch, 4, device="cuda") + out = _new_out(batch) + + def hybrid(): + tail.run_hybrid( + lambda: logits.add_(1.0), + lambda lg: topk.copy_(sel), + topk, + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["kv_lens"], + inp["sinks"], + out, + config=run_config, + ) + + tail.precompile(torch.device("cuda"), batch, pre_config) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + hybrid() + graph.replay() + torch.cuda.synchronize() + _check_rows({**inp, "topk": topk}, out, "realistic") + + +@requires_b200 +@pytest.mark.parametrize("name", ["q_att", "swa_pool", "c_pool", "sinks", "out"]) +def test_misaligned_tensors_are_refused(name): + """The kernel reads these through TMA and 16-byte accesses: a base address that is not a multiple of 16 bytes is a + ValueError of the compiled function, not a CUDA fault.""" + inp = _make_case(_rows(4, 0), seed=1280) + out = _new_out(4) + t = out if name == "out" else inp[name] + nbytes = t.numel() * t.element_size() + buf = torch.zeros(nbytes + 64, dtype=torch.uint8, device="cuda") + shifted = buf[t.element_size() : t.element_size() + nbytes].view(t.dtype).view(t.shape) + shifted.copy_(t) + assert shifted.data_ptr() % 16 == t.element_size() + if name == "out": + out = shifted + else: + inp[name] = shifted + with pytest.raises(ValueError, match="Misaligned"): + _launch(inp, out, SPEC_FP4) + torch.cuda.synchronize() # nothing was launched + + +@requires_b200 +def test_arguments_of_other_shapes_are_accepted(): + """The contract says q_att and out are any shape with B * 64 * 512 elements and sinks any with 64: same bits.""" + batch = 5 + inp = _make_case(_rows(batch, 1), seed=1270) + first = _new_out(batch) + _launch(inp, first, SPEC_FP4) + other = { + **inp, + "q_att": inp["q_att"].view(batch, H_ATT, D_ATT), + "sinks": inp["sinks"].view(1, H_ATT), + } + out = torch.zeros((batch, H_ATT, D_ATT), dtype=torch.bfloat16, device="cuda") + _launch(other, out, SPEC_FP4) + torch.cuda.synchronize() + assert torch.equal(out.view(batch, -1), first) + + +@pytest.mark.filterwarnings("ignore:The CUDA Graph is empty") +@requires_b200 +def test_compile_during_capture_is_refused(monkeypatch): + """A kernel that is not compiled yet cannot be compiled inside a capture: precompile first.""" + inp = _make_case(_rows(4, 0), seed=1200) + out = _new_out(4) + _launch(inp, out, SPEC_FP4) # warm-up (scratch, compile) + monkeypatch.setattr(_tail(), "_compiled", {}) # as in a fresh process + graph = torch.cuda.CUDAGraph() + with pytest.raises(RuntimeError, match="precompile"): + with torch.cuda.graph(graph): + _launch(inp, out, SPEC_FP4) + monkeypatch.undo() + _run_and_check(inp, out, SPEC_FP4, "realistic") + + +@requires_b200 +@pytest.mark.parametrize("attn", ["realistic", "pow2"]) +@pytest.mark.parametrize("batch", [5, 16, MAX_ROWS]) +def test_run_hybrid_with_stand_in_stages(batch, attn): + """run_hybrid with stand-ins for the K1 logits kernel and the top-K kernel, eagerly and inside a CUDA graph.""" + tail = _tail() + inp = _make_case(_rows(batch, 6), seed=1300 + batch, attn=attn) + sel = inp["topk"].clone() # what the stand-in top-K kernel "selects" + topk = torch.full_like(sel, -1) # the buffer the tail attention reads + logits = torch.zeros(batch, 4, device="cuda") + events = [] + + def k1(): + events.append("k1") + logits.add_(1.0) # a device op: the capture records it too + return logits + + def topk_fn(lg): + events.append("topk") + assert lg is logits + topk.copy_(sel) + + def hybrid(): + tail.run_hybrid( + k1, + topk_fn, + topk, + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["kv_lens"], + inp["sinks"], + out, + _scale_of(attn), + config=SPEC_FP4, + ) + + out = _new_out(batch) + hybrid() + torch.cuda.synchronize() + assert events == ["k1", "topk"] + _check_rows({**inp, "topk": topk}, out, attn) + tail.precompile(torch.device("cuda"), batch, SPEC_FP4) + graph = _capture(hybrid) + # the replayed graph runs the stand-in stages again: new selection, same buffers + rows = _rows(batch, 6) + inp2 = _make_case(rows[2:] + rows[:2], seed=1400 + batch, attn=attn) + for key, buf in inp.items(): + assert buf.shape == inp2[key].shape, key + buf.copy_(inp2[key]) + sel.copy_(inp2["topk"]) + topk.fill_(-1) + out.zero_() + before = float(logits[0, 0]) + graph.replay() + torch.cuda.synchronize() + assert float(logits[0, 0]) == before + 1.0, "the K1 stage is part of the graph" + _check_rows({**inp, "topk": topk}, out, attn) + + +# -------------------------------------------------------------------------------------------------------------------- +# programmatic dependent launch (``pdl``): the tail attention starts while the top-K kernel still runs + + +def test_precompile_and_run_attention_take_the_pdl_and_poll_flags(): + tail = _tail() + for fn in (tail.precompile, tail.run_attention): + for flag in ("pdl", "poll"): + p = inspect.signature(fn).parameters[flag] + assert p.default is False and p.kind is not p.POSITIONAL_ONLY + for flag in ("pdl", "poll"): + assert inspect.signature(tail.run_hybrid).parameters[flag].default is None + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + assert (TA.TailAttention(CLUSTER, SPEC).pdl, TA.TailAttention(CLUSTER, SPEC).poll) == ( + False, + False, + ) + assert TA.TailAttention(CLUSTER, SPEC, pdl=True).pdl is True + assert TA.TailAttention(CLUSTER, SPEC, pdl=True).poll is False + assert TA.TailAttention(CLUSTER, SPEC, pdl=True, poll=True).poll is True + + +def test_poll_needs_pdl(): + """Polling the entries of the selection is a variant of the programmatic launch: without it nothing launches early + and a poll loop would wait for entries that a finished kernel already wrote. Refused before any device work.""" + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + with pytest.raises(ValueError, match="poll needs pdl"): + TA.TailAttention(CLUSTER, SPEC, poll=True) + with pytest.raises(ValueError, match="poll needs pdl"): + _tail().run_attention(**_host_args(4), poll=True) + with pytest.raises(ValueError, match="poll needs pdl"): + _tail().run_attention(**_host_args(4), pdl=False, poll=True) + + +def test_run_hybrid_poll_is_refused_before_any_stage_runs(monkeypatch): + """poll needs the multi-CTA top-K (the only writer that arms the entries) and pdl; refused before the K1 stage.""" + tail = _tail() + args = _host_args(3) + called = [] + monkeypatch.setattr(tail, "run_attention", lambda *a, **k: called.append("attention")) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + for kw, match in ( + ({"poll": True, "topk_fn": lambda lg: called.append("topk")}, "poll needs the multi-CTA"), + ({"poll": True, "pdl": False}, "poll needs pdl"), + ): + topk_fn = kw.pop("topk_fn", None) + with pytest.raises(ValueError, match=match): + tail.run_hybrid( + lambda: called.append("k1"), topk_fn, *(args[n] for n in names), + ctx_lens=torch.zeros(3, dtype=torch.int32), **kw, + ) # fmt: skip + assert called == [], "refused before any stage ran" + + +def _slow_selector(): + """A stand-in top-K kernel: it lets the dependent grid launch at once, sleeps ~400 us and only then copies the + selection into ``topk`` (a CuTe kernel, compiled once).""" + import cuda.bindings.driver as cuda_driver + import cutlass + import cutlass.cute as cute + from cutlass import Int32 + + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import megakernel_lib as L + + if "fn" in _SLOW: + return _SLOW["fn"] + + @cute.kernel + def kern(src: cute.Tensor, dst: cute.Tensor): + tid, _, _ = cute.arch.thread_idx() + row, _, _ = cute.arch.block_idx() + cute.arch.griddepcontrol_launch_dependents() + for _ in cutlass.range(400, unroll=1): + L.nanosleep(Int32(1000)) + j = tid + while j < Int32(K_TOP): + dst[row, j] = src[row, j] + j = j + Int32(32) + + @cute.jit + def host(src: cute.Tensor, dst: cute.Tensor, stream: cuda_driver.CUstream): + kern(src, dst).launch(grid=(src.shape[0], 1, 1), block=(32, 1, 1), stream=stream) + + rt = cute.runtime + sb = cute.sym_int() + fn = cute.compile( + host, + rt.make_fake_compact_tensor(Int32, (sb, K_TOP), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (sb, K_TOP), stride_order=(1, 0)), + rt.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + _SLOW["fn"] = fn + return fn + + +_SLOW = {} + + +@requires_b200 +@pytest.mark.parametrize("batch", [1, 9, 16, MAX_ROWS]) +def test_pdl_tail_attention_waits_for_a_slow_top_k(batch): + """The tail attention launched with the programmatic attribute starts while the top-K stage sleeps (it triggers the + dependent launch first), so a missing griddepcontrol.wait before the first read of the selection shows as an + attention over the -1 entries of the not yet written selection.""" + inp = _make_case(_rows(batch, 5), seed=3100 + batch) + sel = inp["topk"].clone() + topk = torch.full_like(sel, -1) + inp = {**inp, "topk": topk} + slow = _slow_selector() + tail = _tail() + tail.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True) + out = _new_out(batch) + for _ in range(4): # the first launch of a kernel is slow to start: later ones race the sleeper + topk.fill_(-1) + out.zero_() + slow(sel, topk) + tail.run_attention( + topk, inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], inp["bt_c"], + inp["kv_lens"], inp["sinks"], out, SM_SCALE, config=SPEC_FP4, pdl=True, + ) # fmt: skip + torch.cuda.synchronize() + assert torch.equal(topk, sel) + _check_rows(inp, out, "realistic") + + +# The polling variant (``poll``): the entries of the selection are the synchronization, not the grid dependency. A +# stand-in producer of that protocol (``topk_multicta_op.run(trigger=True, arm=True)`` does the same): it marks every +# entry -2, lets the dependent grid launch, and writes every entry exactly once with a value >= -1. +_SENTINEL = 0x7FC07FC0 # two bf16 NaNs: the fill of ``out`` that a stored output can never equal +_ARMING = {} + + +def _arming_selector(hold): + """A stand-in top-K kernel of the polling protocol: it marks the 512 entries of its row -2, makes the marks visible + (fence) and triggers the dependent launch, sleeps ~400 us and only then copies the selection into ``dst`` entry by + entry. With ``hold`` it stays alive afterwards for up to ~20 ms, until the first word of its row of ``out`` (viewed + as int32) is no longer ``_SENTINEL``, and records in ``seen[row]`` that the tail attention stored its output while + this grid was still running (a CuTe kernel per ``hold``, compiled once).""" + import cuda.bindings.driver as cuda_driver + import cutlass + import cutlass.cute as cute + from cutlass import Int32, Int64 + + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import megakernel_lib as L + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + if hold in _ARMING: + return _ARMING[hold] + words_per_row = H_ATT * D_ATT // 2 + + @cute.kernel + def kern(src: cute.Tensor, dst: cute.Tensor, words: cute.Tensor, seen: cute.Tensor): + tid, _, _ = cute.arch.thread_idx() + row, _, _ = cute.arch.block_idx() + j = tid + while j < Int32(K_TOP): + dst[row, j] = Int32(-2) + j = j + Int32(32) + L.fence_acq_rel_gpu() + cute.arch.griddepcontrol_launch_dependents() + for _ in cutlass.range(400, unroll=1): + L.nanosleep(Int32(1000)) + j = tid + while j < Int32(K_TOP): + dst[row, j] = src[row, j] + j = j + Int32(32) + if cutlass.const_expr(hold): + if tid == Int32(0): + addr = words.iterator.toint() + Int64(row) * Int64(words_per_row) * Int64(4) + n = Int32(0) + while n < Int32(20000): + if TA._ld_atomic_i32(addr) != Int32(_SENTINEL): + seen[row] = Int32(1) + n = Int32(20000) + else: + L.nanosleep(Int32(1000)) + n = n + Int32(1) + + @cute.jit + def host( + src: cute.Tensor, + dst: cute.Tensor, + words: cute.Tensor, + seen: cute.Tensor, + stream: cuda_driver.CUstream, + ): + kern(src, dst, words, seen).launch( + grid=(src.shape[0], 1, 1), block=(32, 1, 1), stream=stream + ) + + rt = cute.runtime + sb = cute.sym_int() + fn = cute.compile( + host, + rt.make_fake_compact_tensor(Int32, (sb, K_TOP), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (sb, K_TOP), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (sb, words_per_row), stride_order=(1, 0)), + rt.make_fake_compact_tensor(Int32, (sb,), stride_order=(0,)), + rt.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + _ARMING[hold] = fn + return fn + + +def _launch_behind_arming(inp, sel, topk, out, seen, hold, pdl, poll, stale, attn="realistic"): + """One launch of the stand-in producer and the tail attention behind it (``pdl`` / ``poll`` as given). ``topk`` + holds a stale selection before the launch (the one of an earlier launch: the first 256 entries of ``sel`` dropped, + or nothing selected) that a reader of unarmed entries would take for a result.""" + topk.copy_(sel) + if stale == "dropped": + topk[:, :256] = -1 + else: + topk.fill_(-1) + out.view(torch.int32).fill_(_SENTINEL) + seen.zero_() + _arming_selector(hold)(sel, topk, out.view(torch.int32), seen) + _tail().run_attention( + topk, inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], inp["bt_c"], + inp["kv_lens"], inp["sinks"], out, _scale_of(attn), config=SPEC_FP4, pdl=pdl, poll=poll, + ) # fmt: skip + torch.cuda.synchronize() + + +@requires_b200 +@pytest.mark.parametrize("batch", [1, 9, 16, MAX_ROWS]) +def test_poll_tail_attention_waits_for_the_entries_of_a_slow_top_k(batch): + """The polling tail attention starts while the producer sleeps with every entry marked -2 and no grid dependency + to wait for: it must gather a row only from the entries that have been written (a load that reads a stale -2 or the + stale selection of the previous launch shows as a wrong attention), and the result is the plain launch's, bit for + bit.""" + inp = _make_case(_rows(batch, 5), seed=3300 + batch) + sel = inp["topk"].clone() + topk = torch.full_like(sel, -1) + inp = {**inp, "topk": topk} + plain = _new_out(batch) + _launch({**inp, "topk": sel}, plain, SPEC_FP4) + torch.cuda.synchronize() + _tail().precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True, poll=True) + out = _new_out(batch) + seen = torch.zeros(batch, dtype=torch.int32, device="cuda") + for stale in ( + "dropped", + "none", + "dropped", + "none", + ): # the first launch of a kernel is slow to start + _launch_behind_arming(inp, sel, topk, out, seen, False, True, True, stale) + assert torch.equal(topk, sel) + _check_rows(inp, out, "realistic") + assert torch.equal(out, plain) + + +@requires_b200 +@pytest.mark.parametrize("batch", [1, 9, 16, MAX_ROWS]) +def test_poll_tail_attention_finishes_while_the_top_k_grid_still_runs(batch): + """The point of ``poll``: the grid dependency is not waited for. The producer holds on after its last write until + the tail attention has stored its output (it gives up after ~20 ms), so the attention of the polling variant + finishes inside the producer's lifetime, which the variant that waits for the grid (``pdl`` alone, the control) + cannot do: its attention starts only after the producer is gone.""" + inp = _make_case(_rows(batch, 5), seed=3400 + batch) + sel = inp["topk"].clone() + topk = torch.full_like(sel, -1) + inp = {**inp, "topk": topk} + tail = _tail() + tail.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True, poll=True) + tail.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True) + out = _new_out(batch) + seen = torch.zeros(batch, dtype=torch.int32, device="cuda") + # warm-up: the first launch of each kernel loads its module, which would outlast the producer's hold + for poll in (True, False): + _launch_behind_arming(inp, sel, topk, out, seen, False, True, poll, "none") + _launch_behind_arming(inp, sel, topk, out, seen, True, True, poll, "none") + for stale in ("dropped", "none", "dropped"): + _launch_behind_arming(inp, sel, topk, out, seen, True, True, True, stale) + assert bool((seen == 1).all()), ( + "the polling attention did not finish while the producer ran" + ) + _check_rows(inp, out, "realistic") + for stale in ("dropped", "none"): + _launch_behind_arming(inp, sel, topk, out, seen, True, True, False, stale) + assert bool((seen == 0).all()), "pdl without poll started before the producer was done" + _check_rows(inp, out, "realistic") + + +@requires_b200 +@pytest.mark.parametrize("poll", [False, True]) +@pytest.mark.parametrize("attn", ATTN_MODES) +@pytest.mark.parametrize("batch", [5, MAX_ROWS]) +def test_pdl_launch_behind_a_plain_kernel_is_bit_equal(batch, attn, poll): + """The programmatic attribute behind a kernel that never triggers (here: a torch op) waits for its completion: the + same result as the plain launch, bit for bit. The polling variant finds a complete selection (no entry is -2) and + does not wait for anything more.""" + inp = _make_case(_rows(batch, 2), seed=3200 + batch, attn=attn) + plain = _new_out(batch) + _launch(inp, plain, SPEC_FP4, _scale_of(attn)) + tail = _tail() + pdl_out = _new_out(batch) + junk = torch.empty(1 << 24, device="cuda") + junk.fill_(1.0) # an unrelated kernel right before the launch + tail.run_attention( + inp["topk"], inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], inp["bt_c"], + inp["kv_lens"], inp["sinks"], pdl_out, _scale_of(attn), config=SPEC_FP4, pdl=True, poll=poll, + ) # fmt: skip + torch.cuda.synchronize() + assert torch.equal(plain, pdl_out) + _check_rows(inp, pdl_out, attn) + + +@requires_b200 +def test_pdl_is_a_separate_compile_of_the_same_cluster_size(monkeypatch): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_attention as TA + + tail = _tail() + monkeypatch.setattr(tail, "_compiled", {}) + compiles = [] + real = TA.compile_tail_attention + monkeypatch.setattr( + TA, "compile_tail_attention", lambda k: compiles.append((k.g, k.pdl, k.poll)) or real(k) + ) + dev = torch.device("cuda") + for b in (1, 13, MAX_ROWS): + tail.precompile(dev, b) + tail.precompile(dev, b, SPEC_FP4, pdl=True) + tail.precompile(dev, b, SPEC, pdl=True) + tail.precompile(dev, b, SPEC_FP4, pdl=True, poll=True) + assert sorted(compiles) == [ + (CLUSTER, False, False), + (CLUSTER, True, False), + (CLUSTER, True, True), + ] diff --git a/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_topk.py b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_topk.py new file mode 100644 index 000000000000..0a9156a4da9d --- /dev/null +++ b/tests/unittest/_torch/attention/sparse/deepseek_v4/test_cute_dsl_spec_dsa_topk.py @@ -0,0 +1,1351 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# 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. +"""specDSA multi-CTA exact top-512 (``topk_multicta_op``, CuTe DSL, SM100) against ``torch.topk``. + +The kernel selects the exact top-512 of every row of the fp32 indexer logits with one cluster of 4 to 8 CTAs per row +(8 / 6 / 5 / 4 CTAs for 1-15 / 16 / 17-24 / 25-26 rows). Its fast path guesses a threshold from sampled logits (none for +a row of at most 8192 positions: every value is a candidate) and certifies it by a count; a row where the certificate +does not hold takes an exact radix select inside the kernel. The checks of every row are the contract of the top-K +stage: all 512 positions +are in [0, n) and distinct, their values are the multiset ``torch.topk`` returns (which of several equal values at the +512th rank is taken is not specified), and a row of at most 512 positions is ``0 .. n - 1`` followed by -1. The part of +a logits row beyond its length holds garbage (1e30 by default; also +-inf and NaN), so a read past the length shows as +a selected position. + +- host side (no GPU): the cluster table, the batch limits, the signatures, ``is_profitable``, the refusal of every bad + argument, the stage order of ``tail_op.run_hybrid`` with ``topk_fn=None``; +- exactness on a B200: every cluster size at the batch-size boundaries, the row kinds (gaussian, heavy tail, quantized, + two-valued, all-equal, planted ties at the 512th value, outlier, negative-only, signed rows like the real mostly + negative layers, +-0, near-flat, a plateau at the top, ties in the tail, +-inf, all -inf, all +inf, subnormals), + row lengths from 1 to 2**18 (the short rows, the band without a sample, the edges of the sampled bands, lengths that + end inside a chunk), mixed lengths in one batch, the exact path forced on every row, views of larger and smaller + logits buffers, garbage beyond the lengths, canaries around the output; +- warp skew: the radix fallback with pseudo-random delays after every barrier and wait of the kernel source (it + guards the barrier between the levels of the fallback); +- CUDA graphs: capture after ``precompile`` (no warm-up launch), replay with the logits and the lengths refilled in + place, a capture that would compile is refused, one compile per cluster size; +- the armed variant (``trigger=True, arm=True``: it marks the 512 entries of every row -2 at its start and writes each + one once, for the polling tail attention): the exactness tests above run on it too (no -2 is left in any row of any + kind, short rows and the forced radix select included); +- the hybrid: ``tail_op.run_hybrid(topk_fn=None)`` end to end against the fp64 attention reference of the tail tests + (default launch: programmatic with polling, up to 24 rows), launched again and again on new logits without clearing + the selection (a stale selection must never be read). +""" + +import dataclasses +import inspect +import random + +import pytest +import torch + +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import DS_V4_FLASH as SPEC +from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa.config import ( + DS_V4_FLASH_FP4 as SPEC_FP4, +) +from tensorrt_llm._utils import get_sm_version + +from . import test_cute_dsl_spec_dsa_tail as T + +K_TOP = SPEC.topk +NPAD = SPEC.max_index_len # the logits arena of the indexer kernel: 2**18 columns +# An indexer shape without kernels: top-1024 instead of top-512. +PRO = dataclasses.replace(SPEC, name="DS-V4-Pro", topk=1024) + +# The batch sizes of the tail attention, and the CTAs per row of the cluster that serves each. +MAX_ROWS = 26 +CLUSTER_OF = {1: 8, 2: 8, 5: 8, 8: 8, 12: 8, 13: 8, 15: 8, 16: 6, 17: 5, 24: 5, 25: 4, 26: 4} +CLUSTER_SIZES = (8, 6, 5, 4) +BOUNDARY_BATCHES = [1, 2, 8, 12, 13, 15, 16, 17, 24, 25, 26] +REFUSED = [27, 33, 47, 74, 75, 148, 1024] +# co-resident clusters of a B200 at one CTA per SM (measured): the batch sizes of a cluster size must fit one wave +CO_RESIDENT = {8: 15, 6: 22, 5: 26, 4: 33} +# lengths: the short rows, 8192 (the largest row without a sample), the band just above it, the edges of the sampled +# bands, lengths that end inside a 128-float chunk and inside a float4, the longest row +EDGES = [ + 1, + 2, + 255, + 511, + 512, + 513, + 514, + 640, + 641, + 1023, + 4096, + 8191, + 8192, + 8193, + 8200, + 12000, + 16383, + 16384, + 20000, + 28671, + 28672, + 65536, + 100001, + 131071, + 262143, + 262144, +] + + +def _op(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta_op + + return topk_multicta_op + + +def _supported() -> bool: + return torch.cuda.is_available() and get_sm_version() == 100 and _op().is_supported()[0] + + +requires_b200 = pytest.mark.skipif( + not _supported(), reason="clusters of up to 8 CTAs on 148 SMs, qualified on B200 only" +) + + +@pytest.fixture(params=["fp4", "fp8"]) +def spec(request): + """The spec under test: the kernel reads the logits only, so both indexer K dtypes are served.""" + return SPEC_FP4 if request.param == "fp4" else SPEC + + +@pytest.fixture(params=[False, True], ids=["plain", "armed"]) +def armed(request): + """The kernel variant under test: the plain one, or the one that triggers the dependent launch and marks its output + -2 first (the producer of the polling tail attention; with no dependent grid the marks and the trigger are all it + adds, and every entry must end up written).""" + return request.param + + +# -------------------------------------------------------------------------------------------------------------------- +# rows + + +def _row(kind, n, gen): + """float32 [n]: one logits row of the given kind.""" + if n < 4 and kind in ("ties512", "gauss_tail_ties", "plateau_top"): + kind = "gauss" + if kind == "gauss": + x = torch.randn(n, generator=gen) + elif kind == "lognorm": # heavy tail + x = torch.exp(torch.randn(n, generator=gen) * 1.5) + elif kind == "quant": # coarse grid: thousands of ties at the 512th value + x = torch.round(torch.randn(n, generator=gen) * 4) / 4 + elif kind == "two": + x = (torch.rand(n, generator=gen) < 0.01).float() + elif kind == "flat": # all equal + x = torch.full((n,), 1.25) + elif kind == "ties512": # exactly 700 elements equal to a value that sits at ranks ~300 .. 1000 + x = torch.randn(n, generator=gen) + idx = torch.randperm(n, generator=gen)[:700] + thr = torch.topk(x, min(300, n - 1)).values[-1] if n > 300 else x.max() + x[idx] = thr + elif kind == "outlier": + x = torch.randn(n, generator=gen) + x[int(torch.randint(0, n, (1,), generator=gen))] = 1e6 + elif kind == "neg": # negative-only + x = -torch.exp(torch.randn(n, generator=gen)) + elif kind == "zeros": # many exact +-0.0 + x = torch.where( + torch.rand(n, generator=gen) < 0.9, + torch.zeros(n), + torch.randn(n, generator=gen) * 0.001, + ) + x = torch.where((x == 0) & (torch.rand(n, generator=gen) < 0.5), torch.full((n,), -0.0), x) + elif kind == "nearflat": + x = 3.0 + 1e-6 * torch.randn(n, generator=gen) + elif kind == "plateau_top": # a plateau of 5000 equal values at the very top + x = torch.randn(n, generator=gen) + x[torch.randperm(n, generator=gen)[: min(5000, n // 2)]] = 10.0 + elif kind == "gauss_tail_ties": + # the tail quantized to 0.02: ties spread around ranks 400 .. 700 + x = torch.randn(n, generator=gen) + t = torch.topk(x, min(900, n - 1)).values[-1] + x = torch.where(x > t, torch.round(x * 50) / 50, x) + elif kind == "inf": # a few +-inf among normal values and some ties + x = torch.randn(n, generator=gen) + idx = torch.randperm(n, generator=gen) + k = min(8, n // 4) + x[idx[:k]] = float("inf") + x[idx[k : 2 * k]] = float("-inf") + x[idx[2 * k : 2 * k + min(600, n // 3)]] = 3.0 + elif kind == "ninf": # every value -inf: all tie at the smallest key + x = torch.full((n,), float("-inf")) + elif kind == "pinf": # every value +inf + x = torch.full((n,), float("inf")) + elif kind == "denorm": # subnormals, zeros and tiny values of both signs + x = torch.randn(n, generator=gen) * 1e-40 + x = torch.where(torch.rand(n, generator=gen) < 0.3, torch.zeros(n), x) + elif kind == "signed_tail": + # like the real mostly negative layers: ~0.4 % positives, the boundary near zero + x = -torch.exp(torch.randn(n, generator=gen) * 0.6) + pos = torch.rand(n, generator=gen) < 0.004 + x = torch.where(pos, torch.exp(torch.randn(n, generator=gen) * 1.2) * 0.3, x) + else: + raise ValueError(kind) + return x.float() + + +KINDS = [ + "gauss", + "lognorm", + "quant", + "two", + "flat", + "ties512", + "outlier", + "neg", + "zeros", + "nearflat", + "plateau_top", + "gauss_tail_ties", + "inf", + "ninf", + "pinf", + "denorm", + "signed_tail", +] +# kinds without equal values at the 512th rank (a unique selection: two runs give the same set) +UNIQUE_KINDS = ["gauss", "lognorm", "neg", "signed_tail"] + + +def _logits(rows, npad=NPAD, poison=1e30): + """(logits [B, npad] on the device with ``poison`` beyond each row, ctx_lens int32 [B], the rows on the device).""" + lg = torch.full((len(rows), npad), poison, dtype=torch.float32) + for r, x in enumerate(rows): + lg[r, : x.numel()] = x + ctx = torch.tensor([x.numel() for x in rows], dtype=torch.int32) + return lg.cuda(), ctx.cuda(), [x.cuda() for x in rows] + + +def _make(kinds, lengths, seed, batch=None): + """``batch`` rows (default: the longer list), row i of kind ``kinds[i % len(kinds)]`` with + ``lengths[i % len(lengths)]`` positions.""" + gen = torch.Generator().manual_seed(seed) + b = batch or max(len(kinds), len(lengths)) + return [_row(kinds[i % len(kinds)], lengths[i % len(lengths)], gen) for i in range(b)] + + +def _check(rows, out): + """Row r of ``out`` is an exact top-512 of ``rows[r]`` (device tensors): in range, distinct, the values of + torch.topk.""" + out = out.cpu() + for r, x in enumerate(rows): + n = x.numel() + sel = out[r] + if n <= K_TOP: + want = torch.cat( + [ + torch.arange(n, dtype=torch.int32), + torch.full((K_TOP - n,), -1, dtype=torch.int32), + ] + ) + assert torch.equal(sel, want), f"row {r} (n={n}): a short row is 0 .. n - 1 and -1" + continue + assert bool(((sel >= 0) & (sel < n)).all()), f"row {r} (n={n}): position out of [0, n)" + assert torch.unique(sel).numel() == K_TOP, f"row {r} (n={n}): duplicate positions" + got = torch.sort(x[sel.to(x.device).long()], descending=True).values + assert torch.equal(got, torch.topk(x, K_TOP).values), ( + f"row {r} (n={n}): not the top-512 values" + ) + + +def _run(rows, forced=False, npad=NPAD, armed=False): + """Launch on the rows (eager) and return (out, logits, ctx, device rows); ``armed``: the variant that triggers the + dependent launch and marks the output -2 first.""" + op = _op() + lg, ctx, drows = _logits(rows, npad) + out = torch.full((len(rows), K_TOP), -9, dtype=torch.int32, device="cuda") + if forced: + op._fn(lg.device, op.cluster_size(len(rows)), True, armed, armed)(lg, ctx, out) + else: + op.run(lg, out, ctx, trigger=armed, arm=armed) + torch.cuda.synchronize() + return out, lg, ctx, drows + + +# -------------------------------------------------------------------------------------------------------------------- +# host side (no GPU) + + +def test_cluster_size_table(): + op = _op() + assert op.MAX_BATCH == MAX_ROWS + assert [op.cluster_size(b) for b in range(1, 16)] == [8] * 15 + assert [op.cluster_size(b) for b in range(16, 17)] == [6] + assert [op.cluster_size(b) for b in range(17, 25)] == [5] * 8 + assert [op.cluster_size(b) for b in range(25, 27)] == [4] * 2 + for b, g in CLUSTER_OF.items(): + assert op.cluster_size(b) == g + for bad in (-1, 0, *REFUSED): + assert op.cluster_size(bad) is None + + +def test_clusters_of_every_batch_fit_one_wave(): + """All clusters of a launch are resident at once (a second wave costs ~8 us), and the grid fits the 148 SMs.""" + op = _op() + for b in range(1, MAX_ROWS + 1): + g = op.cluster_size(b) + assert g in CO_RESIDENT + assert b <= CO_RESIDENT[g], f"{b} clusters of {g} CTAs" + assert b * g <= 148 + + +def test_max_batch_is_the_range_of_the_tail_attention(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + assert _op().MAX_BATCH == tail_op.TAIL_MAX_BATCH == MAX_ROWS + + +def test_batch_size_support(): + op = _op() + for b in range(1, MAX_ROWS + 1): + assert op.is_batch_size_supported(b) == (True, "") + for bad in (-1, 0, *REFUSED): + ok, why = op.is_batch_size_supported(bad) + assert not ok and f"batch size {bad} not in [1, {MAX_ROWS}]" in why + + +def test_is_supported_has_the_signature_of_the_other_ops(): + """is_supported(device, config) like the megakernel's, the large batch's and the tail attention's.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import ( + large_batch_op, + megakernel_op, + tail_op, + ) + + def params(fn): + return list(inspect.signature(fn).parameters) + + assert params(_op().is_supported) == ["device", "config"] + for other in (megakernel_op, large_batch_op, tail_op): + assert params(_op().is_supported) == params(other.is_supported) + + +def test_is_supported_host_checks(): + op = _op() + ok, why = op.is_supported(config=PRO) + assert not ok and "DS-V4-Pro" in why + # a supported spec: the answer is the device check + for config in (None, SPEC, SPEC_FP4): + ok, why = op.is_supported(config=config) + assert ok == (not why) + + +def test_default_config_of_every_entry_point_is_the_same(): + op = _op() + for fn in (op.precompile, op.run): + assert inspect.signature(fn).parameters["config"].default is None, fn.__name__ + + +@requires_b200 +def test_is_supported_on_b200(): + op = _op() + for config in (None, SPEC, SPEC_FP4): + assert op.is_supported(torch.device("cuda"), config) == (True, "") + assert op.is_supported(config=config) == (True, "") + + +def test_is_profitable(): + op = _op() + n0 = op.MIN_PROFITABLE_ROW_LEN + assert n0 == 16384 + i32 = torch.int32 + assert op.is_profitable(torch.full((4,), n0, dtype=i32)) + assert op.is_profitable(torch.tensor([n0, 262144, 100000], dtype=i32)) + assert not op.is_profitable( + torch.tensor([n0, n0 - 1, 262144], dtype=i32) + ) # the slowest row decides + assert not op.is_profitable(torch.tensor([512, 262144], dtype=i32)) + assert not op.is_profitable(torch.zeros(0, dtype=i32)) + + +def test_cluster_sizes_of_the_op_are_the_ones_of_the_kernel(): + """The op offers the cluster sizes the kernel is built and validated for, and the kernel refuses the others.""" + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta as TM + + op = _op() + assert {op.cluster_size(b) for b in range(1, MAX_ROWS + 1)} == set(TM.SUPPORTED_CLUSTER_SIZES) + assert set(TM.SUPPORTED_CLUSTER_SIZES) == set(CLUSTER_SIZES) + for g in (0, 1, 2, 3, 7, 9, 16): + with pytest.raises(ValueError, match="cluster size"): + TM.TopkMultiCta(g) + for g in CLUSTER_SIZES: + assert TM.TopkMultiCta(g).g == g + assert TM.TopkMultiCta(g, force_fallback=True).force_fallback + + +def _host_args(batch, cols=NPAD): + """Valid CPU arguments of run (the checks run before any device work).""" + return dict( + logits=torch.zeros((batch, cols), dtype=torch.float32), + topk=torch.full((batch, K_TOP), -1, dtype=torch.int32), + ctx_lens=torch.full((batch,), 1000, dtype=torch.int32), + ) + + +def test_rejects_batches_above_26(): + op = _op() + for bad in (0, *REFUSED): + # the batch size is the leading dimension of logits (narrow rows: a CPU tensor of 1024 x 2**18 floats is 1 GiB) + with pytest.raises(ValueError, match=rf"batch size {bad} not in \[1, {MAX_ROWS}\]"): + op.run(**_host_args(bad, cols=128)) + for config in (SPEC, SPEC_FP4): + with pytest.raises(ValueError, match=rf"batch size {bad} not in \[1, {MAX_ROWS}\]"): + op.precompile(torch.device("cuda"), bad, config) + + +def _transposed(t): + return t.t().contiguous().t() + + +# (argument, a variant of it, the error). The batch size is 4. +BAD_ARGUMENTS = [ + ("logits", lambda t: t.to(torch.float16), r"logits must be a float32 \[B, npad\] tensor"), + ("logits", lambda t: t.to(torch.bfloat16), r"logits must be a float32 \[B, npad\] tensor"), + ("logits", lambda t: t.to(torch.int32), r"logits must be a float32 \[B, npad\] tensor"), + ("logits", lambda t: t.to(torch.float64), r"logits must be a float32 \[B, npad\] tensor"), + ("logits", lambda t: t[0], r"logits must be a float32 \[B, npad\] tensor"), + ("logits", lambda t: t[None], r"logits must be a float32 \[B, npad\] tensor"), + ("logits", _transposed, r"logits must be a float32 \[B, npad\] tensor with unit column stride"), + ( + "logits", + lambda t: t[:, ::2], + r"logits must be a float32 \[B, npad\] tensor with unit column stride", + ), + ( + "logits", + lambda t: torch.zeros((4, 1025))[:, :1024], + "logits row stride must be a multiple of 128 floats", + ), + ( + "logits", + lambda t: torch.zeros((4, 1000))[:, :500], + "logits row stride must be a multiple of 128 floats", + ), + ( + "logits", + lambda t: torch.zeros((4, 2 * NPAD)), + r"logits must have 1 to 262144 columns", + ), + ("logits", lambda t: torch.zeros((4, 0)), r"logits must have 1 to 262144 columns"), + ( + "logits", + lambda t: torch.as_strided(torch.zeros(4 * 1024), (4, 1024), (512, 1)), + "at least the row length", + ), + ("topk", lambda t: t.to(torch.int64), r"topk must be a contiguous int32 \[4, 512\] tensor"), + ( + "topk", + lambda t: t[:, :-1].contiguous(), + r"topk must be a contiguous int32 \[4, 512\] tensor", + ), + ("topk", lambda t: t[:3].contiguous(), r"topk must be a contiguous int32 \[4, 512\] tensor"), + ("topk", _transposed, r"topk must be a contiguous int32 \[4, 512\] tensor"), + ("topk", lambda t: t.reshape(-1), r"topk must be a contiguous int32 \[4, 512\] tensor"), + ( + "topk", + lambda t: torch.zeros((4, 1024), dtype=torch.int32)[:, ::2], + "topk must be a contiguous", + ), + ("ctx_lens", lambda t: t.to(torch.int64), r"ctx_lens must be a contiguous int32 \[4\] tensor"), + ("ctx_lens", lambda t: t[:3].contiguous(), r"ctx_lens must be a contiguous int32 \[4\] tensor"), + ("ctx_lens", lambda t: t.reshape(2, 2), r"ctx_lens must be a contiguous int32 \[4\] tensor"), + ( + "ctx_lens", + lambda t: torch.arange(8, dtype=t.dtype)[::2], + r"ctx_lens must be a contiguous int32 \[4\] tensor", + ), + ( + "ctx_lens", + lambda t: t.to(torch.float32), + r"ctx_lens must be a contiguous int32 \[4\] tensor", + ), +] + + +@pytest.mark.parametrize( + "name, variant, match", + [pytest.param(*c, id=f"{i}-{c[0]}") for i, c in enumerate(BAD_ARGUMENTS)], +) +def test_rejects_bad_arguments(name, variant, match): + args = _host_args(4, cols=1024) + args[name] = variant(args[name]) + with pytest.raises(ValueError, match=match): + _op().run(**args) + + +def test_rejects_tensors_that_are_not_on_a_cuda_device(): + """Valid arguments on the CPU: the kernel reads device memory.""" + with pytest.raises(ValueError, match="must be CUDA tensors, got logits on cpu"): + _op().run(**_host_args(4, cols=1024)) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") +def test_rejects_tensors_on_other_devices(): + """Every tensor must be on the device of logits: a tensor on the CPU is refused by name.""" + op = _op() + args = {k: v.cuda() for k, v in _host_args(4, cols=1024).items()} + for name in ("topk", "ctx_lens"): + bad = dict(args) + bad[name] = args[name].cpu() + with pytest.raises( + ValueError, match=rf"{name} must be on the device of logits \(cuda:\d+\), got cpu" + ): + op.run(**bad) + bad = dict(args) + bad["logits"] = args["logits"].cpu() + with pytest.raises(ValueError, match="must be CUDA tensors, got logits on cpu"): + op.run(**bad) + + +def test_unsupported_spec_is_refused_before_any_device_work(): + op = _op() + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + op.precompile(torch.device("cpu"), 4, PRO) + with pytest.raises(NotImplementedError, match="DS-V4-Pro"): + op.run(**_host_args(4, cols=1024), config=PRO) + + +def _stub_hybrid_args(batch): + """CPU stand-ins for the arguments of run_hybrid (the stages are replaced in these tests).""" + return T._host_args(batch) + + +def test_default_launch_of_the_hybrid_follows_the_batch_size(): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + assert tail_op.PDL_MAX_BATCH == 24 + assert [tail_op.default_pdl(b) for b in range(1, MAX_ROWS + 1)] == [True] * 24 + [False] * 2 + # the polling protocol is on up to 23 rows (at 24 it costs what it wins), always with the programmatic launch + assert tail_op.POLL_MAX_BATCH == 23 <= tail_op.PDL_MAX_BATCH + assert [tail_op.default_poll(b) for b in range(1, MAX_ROWS + 1)] == [True] * 23 + [False] * 3 + + +@pytest.mark.parametrize("batch", [3, 23, 24, 25, 26]) +def test_run_hybrid_with_the_multicta_top_k_calls_the_stages_in_order(monkeypatch, batch): + """K1 logits, then the multi-CTA top-K on those logits and the lengths, then the tail attention with the caller's + tensors.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + op = _op() + calls = [] + args = _stub_hybrid_args(batch) + logits, ctx = object(), object() + + def k1(): + calls.append("k1") + return logits + + def fake_topk(lg, topk, ctx_lens, *, config=None, trigger=False, arm=False): + assert lg is logits and ctx_lens is ctx, ( + "the top-K stage gets the logits of the K1 stage and ctx_lens" + ) + assert topk is args["topk"] + calls.append(("multicta", config, trigger, arm)) + + def fake_attention(*a, **kw): + calls.append(("attention", a, kw)) + + monkeypatch.setattr(op, "run", fake_topk) + monkeypatch.setattr(tail_op, "run_attention", fake_attention) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + tail_op.run_hybrid(k1, None, *(args[n] for n in names), 0.125, config=SPEC, ctx_lens=ctx) + # the multi-CTA top-K triggers the dependent launch and the tail attention launches programmatically by default, up + # to PDL_MAX_BATCH rows (above it the clusters of the tail attention fill the wave: plain launches); the top-K also + # marks its output and the tail attention polls the marks up to POLL_MAX_BATCH rows + pdl = batch <= tail_op.PDL_MAX_BATCH + poll = batch <= tail_op.POLL_MAX_BATCH + assert calls[:2] == ["k1", ("multicta", SPEC, pdl, poll)] and len(calls) == 3 + _, a, kw = calls[2] + assert len(a) == 10 and all(x is args[n] for x, n in zip(a, names)) and a[9] == 0.125 + assert kw == {"config": SPEC, "pdl": pdl, "poll": poll} + + +def test_run_hybrid_without_a_top_k_function_needs_ctx_lens(monkeypatch): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + args = _stub_hybrid_args(3) + called = [] + monkeypatch.setattr(tail_op, "run_attention", lambda *a, **k: called.append("attention")) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + with pytest.raises(ValueError, match="needs ctx_lens"): + tail_op.run_hybrid(lambda: called.append("k1"), None, *(args[n] for n in names)) + assert called == [], "refused before any stage ran" + + +def test_run_hybrid_with_a_top_k_function_does_not_touch_the_multicta_kernel(monkeypatch): + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + op = _op() + args = _stub_hybrid_args(3) + calls = [] + monkeypatch.setattr(op, "run", lambda *a, **k: calls.append("multicta")) + monkeypatch.setattr(tail_op, "run_attention", lambda *a, **k: calls.append("attention")) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + tail_op.run_hybrid( + lambda: calls.append("k1"), + lambda lg: calls.append("topk"), + *(args[n] for n in names), + ctx_lens=torch.zeros(3, dtype=torch.int32), + ) + assert calls == ["k1", "topk", "attention"] + + +# -------------------------------------------------------------------------------------------------------------------- +# kernel: exactness + + +@requires_b200 +@pytest.mark.parametrize("batch", BOUNDARY_BATCHES) +def test_exact_mixed_kinds_at_the_cluster_boundaries(batch, spec, armed): + """Every cluster size (8 / 6 / 5 / 4 CTAs: 1-15 / 16 / 17-24 / 25-26 rows) on rows of every kind and long + lengths.""" + lengths = [262144, 200000, 131071, 100001, 65536, 28672, 20000, 16384] + rows = _make(KINDS, lengths, seed=100 + batch, batch=batch) + lg, ctx, drows = _logits(rows) + out = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + _op().run(lg, out, ctx, config=spec, trigger=armed, arm=armed) + torch.cuda.synchronize() + _check(drows, out) + + +@requires_b200 +@pytest.mark.parametrize("batch", [3, 16, MAX_ROWS]) +@pytest.mark.parametrize("kind", KINDS) +def test_exact_per_row_kind(kind, batch, armed): + """Rows of one kind, long and mid lengths, with 8 / 6 / 4 CTAs per row; the kinds with ties and plateaus take the + exact fallback on most rows, the others the fast path.""" + lengths = [262144, 131071, 100001, 65536, 28672, 20000, 16384, 8193] + out, _, _, drows = _run(_make([kind], lengths, seed=7, batch=batch), armed=armed) + _check(drows, out) + + +@requires_b200 +@pytest.mark.parametrize("n", EDGES) +def test_exact_at_every_edge_length(n, armed): + """Thirteen rows (6 CTAs per row) of the same length n and different kinds: the short rows (identity), the rows + without a sample (<= 8192), the first sampled lengths and the lengths that end inside a chunk.""" + kinds = ["gauss", "lognorm", "quant", "signed_tail", "neg", "ties512", "flat"] + out, _, _, drows = _run(_make(kinds, [n], seed=11 + n, batch=13), armed=armed) + _check(drows, out) + + +@requires_b200 +@pytest.mark.parametrize("batch", [5, 13, MAX_ROWS]) +def test_exact_with_a_different_length_in_every_row(batch, armed): + """Rows of one batch with lengths from 1 to 2**18 (a cluster of every kind, the slowest row decides the launch).""" + lengths = random.Random(batch).sample(EDGES, batch) + kinds = ["gauss", "signed_tail", "quant", "lognorm", "neg", "plateau_top"] + out, _, _, drows = _run(_make(kinds, lengths, seed=300 + batch, batch=batch), armed=armed) + _check(drows, out) + + +@requires_b200 +@pytest.mark.parametrize("batch", [1, 13, 16, 17, 25, 26]) +def test_exact_fallback_forced_on_every_row(batch, armed): + """The in-kernel radix select on every row, including the rows whose fast path would certify: the same exactness.""" + lengths = [262144, 131071, 65536, 20000, 16384, 8193, 8192, 4096, 600, 513, 512, 100, 1] + out, _, _, drows = _run( + _make(KINDS, lengths, seed=900 + batch, batch=batch), forced=True, armed=armed + ) + _check(drows, out) + + +@requires_b200 +def test_forced_and_default_kernels_select_the_same_set_when_it_is_unique(): + """Rows without ties at the 512th rank have one exact selection: the fast path and the radix select give it.""" + lengths = [262144, 131071, 65536, 28672, 20000, 16384, 8193, 600] + rows = _make(UNIQUE_KINDS, lengths, seed=5, batch=16) + out_default, _, _, drows = _run(rows) + out_forced, _, _, _ = _run(rows, forced=True) + _check(drows, out_default) + _check(drows, out_forced) + assert torch.equal(torch.sort(out_default, dim=1).values, torch.sort(out_forced, dim=1).values) + + +@requires_b200 +def test_planted_ties_at_the_512th_value(armed): + """700 equal values straddling the 512th rank on every row (and a quantized tail): the value multiset is exact + whichever of the tied positions are taken.""" + out, _, _, drows = _run( + _make(["ties512", "gauss_tail_ties", "quant"], [262144, 100001, 28672], seed=3, batch=18), + armed=armed, + ) + _check(drows, out) + # the part of the tied value that the selection could not leave out: every strictly larger value is selected + for r, x in enumerate(drows): + sel = out[r].long() + kth = torch.topk(x, K_TOP).values[-1] + above = torch.nonzero(x > kth).flatten() + assert bool(torch.isin(above, sel).all()), f"row {r}: a value above the 512th is missing" + + +@requires_b200 +def test_all_equal_rows_select_512_distinct_positions(): + """Every position ties: any 512 distinct positions of [0, n) are exact.""" + out, _, _, drows = _run([_row("flat", n, None) for n in (262144, 20000, 8193, 513, 1000)] * 3) + _check(drows, out) + + +@requires_b200 +@pytest.mark.parametrize("poison", [1e30, float("inf"), float("-inf"), float("nan"), -1e30]) +def test_never_reads_beyond_the_length(poison): + """Everything beyond ctx_lens is garbage (the logits arena keeps the values of earlier steps): the largest values, + infinities and NaN must not be selected or disturb a row. Lengths that end inside a 128-float chunk, a float4 and + the 8-float sample window.""" + lengths = [ + 100001, + 100003, + 100005, + 100127, + 100129, + 20001, + 16385, + 8195, + 8201, + 640, + 641, + 513, + 262143, + ] + rows = _make(["gauss", "neg", "quant"], lengths, seed=21, batch=13) + lg, ctx, drows = _logits(rows, poison=poison) + out = torch.full((13, K_TOP), -9, dtype=torch.int32, device="cuda") + _op().run(lg, out, ctx) + torch.cuda.synchronize() + _check(drows, out) + for r, x in enumerate(drows): + assert int(out[r].max()) < x.numel() + + +@requires_b200 +def test_exact_on_views_of_larger_and_smaller_buffers(): + """A [B, 100000] view of the [B, 2**18] logits arena (row stride 2**18), a [B, 16384] buffer (stride 16384) and a + [B, 20000] view of a stride-20096 buffer: the row stride, not the number of columns, is the row pitch.""" + op = _op() + gen = torch.Generator().manual_seed(2) + for cols, stride in ((100000, NPAD), (16384, 16384), (20000, 20096)): + b = 6 + rows = [ + _row(k, n, gen) + for k, n in zip(["gauss", "signed_tail", "quant"] * 2, [cols, cols - 1, cols - 641] * 2) + ] + buf = torch.full((b, stride), 1e30) + for r, x in enumerate(rows): + buf[r, : x.numel()] = x + buf = buf.cuda() + view = buf[:, :cols] + assert view.stride() == (stride, 1) + ctx = torch.tensor([x.numel() for x in rows], dtype=torch.int32, device="cuda") + out = torch.full((b, K_TOP), -9, dtype=torch.int32, device="cuda") + op.run(view, out, ctx) + torch.cuda.synchronize() + _check([x.cuda() for x in rows], out) + + +@requires_b200 +def test_writes_only_the_output_rows(): + """The 512 entries of each row are the only memory the kernel writes: canaries around the output stay.""" + op = _op() + b = 13 + rows = _make( + ["gauss", "quant", "ties512", "neg"], [262144, 28672, 100001, 600, 8193], seed=4, batch=b + ) + lg, ctx, drows = _logits(rows) + buf = torch.full((b * K_TOP + 2 * 512,), -7, dtype=torch.int32, device="cuda") + out = buf[512 : 512 + b * K_TOP].view(b, K_TOP) + out.fill_(-9) + op.run(lg, out, ctx) + torch.cuda.synchronize() + assert bool((buf[:512] == -7).all()) and bool((buf[512 + b * K_TOP :] == -7).all()) + _check(drows, out) + # the logits and the lengths are read only + lg2, ctx2, _ = _logits(rows) + assert torch.equal(lg, lg2) and torch.equal(ctx, ctx2) + + +@requires_b200 +def test_misaligned_logits_are_refused(): + """The row loads are 16-byte accesses: a base that is not a multiple of 16 bytes is a ValueError of the compiled + function, not a CUDA fault.""" + op = _op() + b = 4 + buf = torch.zeros(b * NPAD + 16, dtype=torch.float32, device="cuda") + logits = buf[1 : 1 + b * NPAD].view(b, NPAD) + assert logits.data_ptr() % 16 == 4 + out = torch.full((b, K_TOP), -9, dtype=torch.int32, device="cuda") + ctx = torch.full((b,), 1000, dtype=torch.int32, device="cuda") + with pytest.raises(ValueError, match="Misaligned"): + op.run(logits, out, ctx) + torch.cuda.synchronize() # nothing was launched + assert bool((out == -9).all()) + + +# -------------------------------------------------------------------------------------------------------------------- +# kernel: compile, CUDA graphs + + +@requires_b200 +def test_one_compile_per_cluster_size(monkeypatch): + """The compile cache is keyed by (device, cluster size): 26 batch sizes make 4 compiles, none for a second pass.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta as TM + + op = _op() + monkeypatch.setattr(op, "_compiled", {}) # as in a fresh process + compiles = [] + real = TM.compile_topk_multicta + monkeypatch.setattr( + TM, "compile_topk_multicta", lambda k: compiles.append((k.g, k.force_fallback)) or real(k) + ) + dev = torch.device("cuda") + for b in range(1, MAX_ROWS + 1): + op.precompile(dev, b) + assert sorted(g for g, _ in compiles) == sorted(CLUSTER_SIZES) and not any( + f for _, f in compiles + ) + assert {(d, g) for (d, g, f, t, a) in op._compiled} == { + (torch.cuda.current_device(), g) for g in CLUSTER_SIZES + } + for b in range(1, MAX_ROWS + 1): + op.precompile(dev, b, SPEC) + op.precompile(dev, b, SPEC_FP4) + assert len(compiles) == len(CLUSTER_SIZES) + + +def _fill_graph_buffers(lg, ctx, rows): + lg.fill_(1e30) + for r, x in enumerate(rows): + lg[r, : x.numel()] = x.cuda() + ctx.copy_(torch.tensor([x.numel() for x in rows], dtype=torch.int32)) + + +@requires_b200 +@pytest.mark.parametrize("batch", [1, 8, 13, 17, MAX_ROWS]) +def test_cuda_graph_replay_with_refilled_buffers(batch): + """precompile, capture run() (no warm-up launch), replay with the logits and the lengths refilled in place: new + data, mixed and short lengths; every replay is exact and equals the eager launch.""" + op = _op() + dev = torch.device("cuda") + lg = torch.zeros((batch, NPAD), device=dev) # the static buffers of the graph + ctx = torch.full((batch,), 1000, dtype=torch.int32, device=dev) + out = torch.full((batch, K_TOP), -9, dtype=torch.int32, device=dev) + op.precompile(dev, batch) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + op.run(lg, out, ctx) + steps = [ + (["gauss"], [262144]), + (["signed_tail", "lognorm"], [131071, 65536, 28672]), + (["gauss", "neg"], [1, 255, 512, 513, 8192, 8193, 20000, 262144]), + (["quant", "flat", "ties512"], [262144, 100001, 16384]), + (["gauss"], [600]), + ] + for i, (kinds, lengths) in enumerate(steps): + rows = _make(kinds, lengths, seed=40 + i, batch=batch) + _fill_graph_buffers(lg, ctx, rows) + out.fill_(-9) + graph.replay() + torch.cuda.synchronize() + _check([x.cuda() for x in rows], out) + # a unique selection (no ties at the 512th rank): the eager launch gives the same set + if all(k in UNIQUE_KINDS for k in kinds): + eager = torch.full_like(out, -9) + op.run(lg, eager, ctx) + torch.cuda.synchronize() + same = torch.equal(torch.sort(eager, dim=1).values, torch.sort(out, dim=1).values) + assert same, f"step {i}" + + +@requires_b200 +@pytest.mark.parametrize( + "run_config", [None, SPEC, SPEC_FP4], ids=["run-default", "run-fp8", "run-fp4"] +) +@pytest.mark.parametrize( + "pre_config", [None, SPEC, SPEC_FP4], ids=["pre-default", "pre-fp8", "pre-fp4"] +) +def test_precompile_then_captured_run(monkeypatch, pre_config, run_config): + """precompile(device, batch) followed by a CUDA-graph capture of run compiles nothing during the capture, + whichever spec each call names (``None``: the default of both): there is no warm-up launch in between.""" + op = _op() + batch = 8 + monkeypatch.setattr(op, "_compiled", {}) # as in a fresh process + lg, ctx, drows = _logits( + _make(["gauss", "signed_tail", "lognorm"], [262144, 100001, 65536], seed=60, batch=batch) + ) + out = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + op.precompile(torch.device("cuda"), batch, pre_config) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + op.run(lg, out, ctx, config=run_config) + graph.replay() + torch.cuda.synchronize() + _check(drows, out) + + +@pytest.mark.filterwarnings("ignore:The CUDA Graph is empty") +@requires_b200 +def test_compile_during_capture_is_refused(monkeypatch): + """A kernel that is not compiled yet cannot be compiled inside a capture: precompile first.""" + op = _op() + # warm-up: the CUDA context and the compile + out, lg, ctx, drows = _run(_make(["gauss"], [100001], seed=70, batch=4)) + _check(drows, out) + monkeypatch.setattr(op, "_compiled", {}) # as in a fresh process + graph = torch.cuda.CUDAGraph() + with pytest.raises(RuntimeError, match="precompile"): + with torch.cuda.graph(graph): + op.run(lg, out, ctx) + monkeypatch.undo() + out.fill_(-9) + op.run(lg, out, ctx) + torch.cuda.synchronize() + _check(drows, out) + + +# -------------------------------------------------------------------------------------------------------------------- +# warp skew: the kernel's block barriers and waits order its warps, whatever the schedule + + +# A pseudo-random warp-uniform delay (nanosleep, up to 1 us for a quarter of the (CTA, warp, site) triples) after every +# block barrier, named barrier, cluster wait, mbarrier wait and cp.async wait of the kernel source. +_SKEW_HELPERS = """ +@dsl_user_op +def nanosleep(ns, *, loc=None, ip=None): + L._asm(None, [L._v(ns, loc, ip)], "nanosleep.u32 $0;", "r", loc, ip) + + +@cute.jit +def _skew(site: cutlass.Constexpr, bidx, warp): + h = Uint32((SKEW_SEED * 2654435761 + site * 40503) & 0xFFFFFFFF) + h = h ^ (Uint32(bidx) * Uint32(2246822519)) ^ (Uint32(warp) * Uint32(3266489917)) + h = h ^ (h >> Uint32(15)) + h = h * Uint32(2246822519) + h = h ^ (h >> Uint32(13)) + d = Int32(0) + if (h & Uint32(3)) == Uint32(0): + d = Int32((h >> Uint32(8)) & Uint32(1023)) + nanosleep(d) + + +""" + + +def _skewed_module(tmp_path, seed): + """The kernel module with the delays inserted, imported as a sibling of ``topk_multicta`` (same package, so its + relative imports resolve); returns (module, number of delay sites).""" + import importlib.util + import re + import sys + + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta as TM + + text = open(TM.__file__).read() + pat = re.compile( + r"^(\s*)(L\.bar\(\d, NT\)|L\.cluster_wait\(\)|L\.wait_cl\(.*\)|cpa_wait\(.*\))\s*$" + ) + out, sites = [], 0 + for line in text.split("\n"): + out.append(line) + m = pat.match(line) + if m: + sites += 1 + out.append(f"{m.group(1)}_skew({sites}, bidx, warp)") + text = "\n".join(out) + anchor = "@cute.jit\ndef _umin(a, b):" + assert text.count(anchor) == 1 + text = text.replace(anchor, f"SKEW_SEED = {seed}\n" + _SKEW_HELPERS + anchor) + path = tmp_path / f"topk_multicta_skew{seed}.py" + path.write_text(text) + name = f"{TM.__package__}.topk_multicta_skew{seed}" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module, sites + + +@requires_b200 +@pytest.mark.parametrize("g, batch", [(8, 12), (4, 26)]) +def test_exact_fallback_under_warp_skew(tmp_path, g, batch): + """The levels of the radix fallback exchange counters through shared memory between the warps of a CTA and + through distributed shared memory between the CTAs: with random delays after every barrier and wait of the kernel + the result must stay exact. (A missing barrier between the reads at the end of a level and the zeroing at the top of + the next was invisible at the normal schedule and gave half-empty outputs here and under compute-sanitizer.)""" + module, sites = _skewed_module(tmp_path, seed=g) + assert sites >= 25, "the kernel source changed: the delay sites are not found" + kernel = module.compile_topk_multicta(module.TopkMultiCta(g, force_fallback=True)) + lengths = [262144, 131071, 65536, 20000, 16384, 8193, 4096, 600] + for seed in (1, 2): + rows = _make(KINDS, lengths, seed=700 + seed, batch=batch) + lg, ctx, drows = _logits(rows) + out = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + kernel(lg, ctx, out) + torch.cuda.synchronize() + _check(drows, out) + + +# -------------------------------------------------------------------------------------------------------------------- +# the hybrid: K1 logits -> multi-CTA top-K -> tail attention + + +def _hybrid_case(batch, rot, seed): + """Tail-attention inputs of ``batch`` rows and logits of the compressed lengths kv_len // 4 for the top-K stage.""" + rows = T._rows(batch, rot) + inp = T._make_case(rows, seed=seed) + ctx = (inp["kv_lens"] // T.RATIO).to(torch.int32) + gen = torch.Generator().manual_seed(seed + 5) + kinds = ["gauss", "signed_tail", "lognorm"] + lg, _, drows = _logits([_row(kinds[b % 3], int(n), gen) for b, n in enumerate(ctx.tolist())]) + return inp, lg, ctx, drows + + +@requires_b200 +@pytest.mark.parametrize("batch", [5, 13, 17, MAX_ROWS]) +def test_run_hybrid_with_the_multicta_top_k(batch): + """K1 stand-in -> multi-CTA top-K -> tail attention: the selection is the exact top-512 of the logits, the attention + matches the fp64 reference of that selection, and it is bit-equal to the tail attention launched on the same + selection (the top-K output feeds the attention directly).""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + inp, lg, ctx, drows = _hybrid_case(batch, 3, seed=2000 + batch) + topk = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + out = T._new_out(batch) + events = [] + + def k1(): + events.append("k1") + return lg + + tail_op.run_hybrid( + k1, + None, + topk, + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["kv_lens"], + inp["sinks"], + out, + config=SPEC_FP4, + ctx_lens=ctx, + ) + torch.cuda.synchronize() + assert events == ["k1"] + _check(drows, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic") + same = T._new_out(batch) + T._launch({**inp, "topk": topk}, same, SPEC_FP4) + torch.cuda.synchronize() + assert torch.equal(out, same) + + +@requires_b200 +def test_run_hybrid_with_the_multicta_top_k_in_a_cuda_graph(): + """Both kernels compiled before the capture, no warm-up launch; the replay runs the K1 stand-in, the top-K and the + attention on refilled buffers.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + op = _op() + batch = 16 + inp, lg, ctx, drows = _hybrid_case(batch, 3, seed=2100) + topk = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + out = T._new_out(batch) + + def hybrid(): + tail_op.run_hybrid( + lambda: lg, # the K1 stand-in: the static logits buffer + None, + topk, + inp["q_att"], + inp["swa_pool"], + inp["bt_swa"], + inp["c_pool"], + inp["bt_c"], + inp["kv_lens"], + inp["sinks"], + out, + config=SPEC_FP4, + ctx_lens=ctx, + ) + + # the default variants of run_hybrid with the multi-CTA top-K are the programmatic, polling ones + tail_op.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True, poll=True) + op.precompile(torch.device("cuda"), batch, SPEC_FP4, trigger=True, arm=True) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + hybrid() + graph.replay() + torch.cuda.synchronize() + _check(drows, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic") + # new logits and lengths in place, the same attention inputs: the replay follows them + ctx2 = ((inp["kv_lens"] // T.RATIO) // 2 + 1).to(torch.int32) + gen = torch.Generator().manual_seed(2101) + rows2 = [_row("gauss", int(n), gen) for n in ctx2.tolist()] + lg2, _, drows2 = _logits(rows2) + lg.copy_(lg2) + ctx.copy_(ctx2) + topk.fill_(-9) + out.zero_() + graph.replay() + torch.cuda.synchronize() + _check(drows2, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic") + + +# -------------------------------------------------------------------------------------------------------------------- +# programmatic dependent launch: the top-K triggers after its stream phase, the tail attention launches with it + + +def test_precompile_and_run_take_the_trigger_and_arm_flags(): + op = _op() + for fn in (op.precompile, op.run): + for flag in ("trigger", "arm"): + p = inspect.signature(fn).parameters[flag] + assert p.default is False and p.kind is not p.POSITIONAL_ONLY + + +def test_arm_needs_trigger(): + """The marks are for a dependent grid that polls them: without the trigger nothing could read them early. Refused + before any device work, in every entry point.""" + pytest.importorskip("cutlass.cute") # CuTe DSL; no GPU needed + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta as TM + + op = _op() + with pytest.raises(ValueError, match="arm needs trigger"): + op.precompile(torch.device("cpu"), 4, arm=True) + with pytest.raises(ValueError, match="arm needs trigger"): + TM.TopkMultiCta(8, arm=True) # the CTA 0 would never arrive: a deadlock, not a result + kernel = TM.TopkMultiCta(8, trigger=True, arm=True) + assert (kernel.trigger, kernel.arm) == (True, True) + assert (TM.TopkMultiCta(8).trigger, TM.TopkMultiCta(8).arm) == (False, False) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") +def test_run_arm_needs_trigger_before_any_launch(): + args = {k: v.cuda() for k, v in _host_args(4, cols=1024).items()} + with pytest.raises(ValueError, match="arm needs trigger"): + _op().run(**args, arm=True) + torch.cuda.synchronize() + assert bool((args["topk"] == -1).all()), "nothing was launched" + + +def test_run_hybrid_pdl_needs_the_multicta_top_k(monkeypatch): + """pdl=True with the caller's top-K kernel is refused before any stage runs (that kernel never triggers early).""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + args = _stub_hybrid_args(3) + called = [] + monkeypatch.setattr(tail_op, "run_attention", lambda *a, **k: called.append("attention")) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + with pytest.raises(ValueError, match="pdl needs the multi-CTA top-K"): + tail_op.run_hybrid( + lambda: called.append("k1"), lambda lg: called.append("topk"), + *(args[n] for n in names), pdl=True, + ) # fmt: skip + assert called == [], "refused before any stage ran" + + +@pytest.mark.parametrize( + "pdl, poll, expected", + [ + (None, None, (True, True)), + (True, None, (True, True)), + (False, None, (False, False)), + (True, False, (True, False)), + (True, True, (True, True)), + (None, False, (True, False)), + (None, True, (True, True)), + ], +) +def test_run_hybrid_pdl_selects_the_launch_variants_of_both_kernels( + monkeypatch, pdl, poll, expected +): + """With the multi-CTA top-K ``pdl`` (default: on) makes it trigger the dependent launch and launches the tail + attention with the programmatic attribute, and ``poll`` (default: with ``pdl``) makes the top-K mark its output and + the tail attention poll it instead of waiting for the grid; with ``pdl`` off, both are plain launches.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + op = _op() + calls = [] + args = _stub_hybrid_args(3) + monkeypatch.setattr( + op, + "run", + lambda lg, topk, ctx, *, config=None, trigger=False, arm=False: calls.append( + ("topk", trigger, arm) + ), + ) + monkeypatch.setattr( + tail_op, + "run_attention", + lambda *a, pdl=False, poll=False, **k: calls.append(("attention", pdl, poll)), + ) + names = ("topk", "q_att", "swa_pool", "bt_swa", "c_pool", "bt_c", "kv_lens", "sinks", "out") + kw = {k: v for k, v in (("pdl", pdl), ("poll", poll)) if v is not None} + tail_op.run_hybrid(lambda: object(), None, *(args[n] for n in names), ctx_lens=object(), **kw) + assert calls == [("topk", *expected), ("attention", *expected)] + + +@requires_b200 +def test_one_compile_per_cluster_size_and_trigger(monkeypatch): + """The trigger and the marks are part of the compile: the 4 cluster sizes compile once for each of the three + variants (plain, trigger, trigger + arm), none for a second pass.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import topk_multicta as TM + + op = _op() + monkeypatch.setattr(op, "_compiled", {}) + compiles = [] + real = TM.compile_topk_multicta + monkeypatch.setattr( + TM, + "compile_topk_multicta", + lambda k: compiles.append((k.g, k.trigger, k.arm)) or real(k), + ) + dev = torch.device("cuda") + for b in range(1, MAX_ROWS + 1): + op.precompile(dev, b) + op.precompile(dev, b, SPEC_FP4, trigger=True) + op.precompile(dev, b, SPEC_FP4, trigger=True, arm=True) + for b in range(1, MAX_ROWS + 1): + op.precompile(dev, b, SPEC, trigger=True) + op.precompile(dev, b, SPEC, trigger=True, arm=True) + assert sorted(compiles) == sorted( + [(g, False, False) for g in CLUSTER_SIZES] + + [(g, True, False) for g in CLUSTER_SIZES] + + [(g, True, True) for g in CLUSTER_SIZES] + ) + + +@requires_b200 +@pytest.mark.parametrize("batch", [5, 9, 13, 17, MAX_ROWS]) +def test_run_hybrid_pdl_is_bit_equal_to_the_plain_launches(batch): + """K1 stand-in -> multi-CTA top-K (triggering) -> tail attention (programmatic launch, waiting for the grid or + polling the entries) against the two plain launches of the same kernels: the same selection and the same attention + output, bit for bit (several launches in a row).""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + inp, lg, ctx, drows = _hybrid_case(batch, 3, seed=2200 + batch) + runs = {} + variants = [(False, False), (True, False), (True, True)] # (pdl, poll) + for pdl, poll in variants * 2: + topk = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + out = T._new_out(batch) + tail_op.run_hybrid( + lambda: lg, None, topk, inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], + inp["bt_c"], inp["kv_lens"], inp["sinks"], out, config=SPEC_FP4, ctx_lens=ctx, + pdl=pdl, poll=poll, + ) # fmt: skip + torch.cuda.synchronize() + _check(drows, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic") + runs.setdefault((pdl, poll), []).append((topk.sort(dim=1).values, out)) + for lst in runs.values(): + for t2, o2 in lst[1:]: + assert torch.equal(t2, lst[0][0]) and torch.equal(o2, lst[0][1]), ( + "deterministic per variant" + ) + for v in variants[1:]: + assert torch.equal(runs[v][0][0], runs[variants[0]][0][0]) + assert torch.equal(runs[v][0][1], runs[variants[0]][0][1]) + + +@requires_b200 +def test_run_hybrid_pdl_in_a_cuda_graph(): + """Both kernels compiled in their programmatic variants before the capture; the replay follows refilled buffers.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + op = _op() + batch = 16 + inp, lg, ctx, drows = _hybrid_case(batch, 3, seed=2300) + topk = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + out = T._new_out(batch) + + def hybrid(): + tail_op.run_hybrid( + lambda: lg, None, topk, inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], + inp["bt_c"], inp["kv_lens"], inp["sinks"], out, config=SPEC_FP4, ctx_lens=ctx, pdl=True, + ) # fmt: skip + + tail_op.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True, poll=True) + op.precompile(torch.device("cuda"), batch, SPEC_FP4, trigger=True, arm=True) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + hybrid() + for seed in (2301, 2302): + ctx2 = ((inp["kv_lens"] // T.RATIO) // 2 + 1).to(torch.int32) + gen = torch.Generator().manual_seed(seed) + lg2, _, drows2 = _logits([_row("gauss", int(n), gen) for n in ctx2.tolist()]) + lg.copy_(lg2) + ctx.copy_(ctx2) + topk.fill_(-9) + out.zero_() + graph.replay() + torch.cuda.synchronize() + _check(drows2, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic") + + +@requires_b200 +@pytest.mark.parametrize("mode", ["eager", "graph"]) +@pytest.mark.parametrize("batch", [5, 16, 24]) +def test_run_hybrid_poll_reads_no_stale_selection(batch, mode): + """The polling tail attention behind the armed top-K on logits that change from launch to launch (two sets with + different lengths and values, alternating), the selection and the output left as the previous launch wrote them + (never cleared): an entry read before the top-K wrote it in this launch would show as the attention over the + selection of the previous launch.""" + from tensorrt_llm._torch.attention.kernels.blackwell.spec_dsa import tail_op + + inp, lg, ctx, _ = _hybrid_case(batch, 3, seed=2400 + batch) + topk = torch.full((batch, K_TOP), -9, dtype=torch.int32, device="cuda") + out = T._new_out(batch) + + def hybrid(): # explicit: the default is the polling protocol only up to POLL_MAX_BATCH rows (24 is tested too) + tail_op.run_hybrid( + lambda: lg, None, topk, inp["q_att"], inp["swa_pool"], inp["bt_swa"], inp["c_pool"], + inp["bt_c"], inp["kv_lens"], inp["sinks"], out, config=SPEC_FP4, ctx_lens=ctx, + pdl=True, poll=True, + ) # fmt: skip + + tail_op.precompile(torch.device("cuda"), batch, SPEC_FP4, pdl=True, poll=True) + _op().precompile(torch.device("cuda"), batch, SPEC_FP4, trigger=True, arm=True) + graph = None + if mode == "graph": + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + hybrid() + ctx_a = ctx.clone() + ctx_b = ((inp["kv_lens"] // T.RATIO) // 2 + 1).to(torch.int32) + gen = torch.Generator().manual_seed(2450 + batch) + for i in range(6): + ctx_i = ctx_a if i % 2 == 0 else ctx_b + lg_i, _, drows = _logits([_row("gauss", int(n), gen) for n in ctx_i.tolist()]) + lg.copy_(lg_i) + ctx.copy_(ctx_i) + if graph is None: + hybrid() + else: + graph.replay() + torch.cuda.synchronize() + _check(drows, topk) + T._check_rows({**inp, "topk": topk}, out, "realistic")