Skip to content

vllm.model_executor.layers.attention.sparse_mla_attention

Shared MHA implementation and metadata builder for sparse MLA backends.

Classes:

Functions:

SharedTopkIndicesBuffer

Resolves the shared top-k index buffer for sparse MLA implementations.

The indexer owns the buffer, but LLMBaseProposer.load_model repoints the draft's indexers at the target's buffer after the impls are constructed, so it must be resolved per read rather than snapshotted. Backbone skip-topk layers have no indexer and pass the buffer explicitly.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
class SharedTopkIndicesBuffer:
    """Resolves the shared top-k index buffer for sparse MLA implementations.

    The indexer owns the buffer, but `LLMBaseProposer.load_model` repoints the
    draft's indexers at the target's buffer after the impls are constructed, so
    it must be resolved per read rather than snapshotted. Backbone skip-topk
    layers have no indexer and pass the buffer explicitly.
    """

    _indexer: object | None = None
    _topk_indices_buffer: torch.Tensor | None = None

    def init_topk_indices_buffer(
        self,
        indexer: object | None,
        topk_indices_buffer: torch.Tensor | None,
    ) -> None:
        self._indexer = indexer
        self._topk_indices_buffer = topk_indices_buffer

    @property
    def topk_indices_buffer(self) -> torch.Tensor | None:
        if self._indexer is not None:
            return self._indexer.topk_indices_buffer  # type: ignore[attr-defined]
        return self._topk_indices_buffer

    @topk_indices_buffer.setter
    def topk_indices_buffer(self, buffer: torch.Tensor | None) -> None:
        # An explicit assignment supersedes the indexer.
        self._indexer = None
        self._topk_indices_buffer = buffer

SparseMLACommonImpl

Bases: MLACommonBaseImpl[T], SharedTopkIndicesBuffer, Generic[T]

Sparse MLA base with dense and masked-MHA prefill paths.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
class SparseMLACommonImpl(MLACommonBaseImpl[T], SharedTopkIndicesBuffer, Generic[T]):
    """Sparse MLA base with dense and masked-MHA prefill paths."""

    is_sparse = True
    # Reuse the index group's top-k conversion only for uniform decode batches
    # of multi-layer groups; other batches convert per layer.
    group_conversion_decode_only: ClassVar[bool] = False
    # Whether forward_mqa runs ShardQ metadata and is validated.
    supports_shardq: ClassVar[bool] = False

    def __init__(
        self,
        num_heads: int,
        head_size: int,
        scale: float,
        num_kv_heads: int,
        alibi_slopes: list[float] | None,
        sliding_window: int | None,
        kv_cache_dtype: str,
        logits_soft_cap: float | None,
        attn_type: str,
        kv_sharing_target_layer_name: str | None,
        q_lora_rank: int | None,
        kv_lora_rank: int,
        qk_nope_head_dim: int,
        qk_rope_head_dim: int,
        qk_head_dim: int,
        v_head_dim: int,
        kv_b_proj: "ColumnParallelLinear",
        indexer: object | None = None,
        topk_indices_buffer: torch.Tensor | None = None,
        index_group_builder: SparseMLAIndexGroupBuilder | None = None,
        q_pad_num_heads: int | None = None,
    ) -> None:
        super().__init__(
            num_heads,
            head_size,
            scale,
            num_kv_heads,
            kv_cache_dtype,
            kv_lora_rank,
            qk_nope_head_dim,
            qk_rope_head_dim,
            qk_head_dim,
            v_head_dim,
            kv_b_proj,
        )

        self.init_topk_indices_buffer(indexer, topk_indices_buffer)
        self.index_group: SparseMLAIndexGroup | None = None
        self.index_group_index = 0
        if index_group_builder is None and self.topk_indices_buffer is not None:
            index_group_builder = SparseMLAIndexGroupBuilder(self.topk_indices_buffer)
        if index_group_builder is not None:
            vllm_config = get_current_vllm_config()
            self.index_group, self.index_group_index = (
                index_group_builder.register_layer(
                    indexer is not None,
                    vllm_config,
                    row_width=(
                        self.get_fp8_ds_mla_row_bytes()
                        if kv_cache_dtype == "fp8_ds_mla"
                        else head_size
                    ),
                    kv_cache_dtype=kv_cache_dtype,
                )
            )

        self._use_flashinfer_concat_mla_k = (
            has_flashinfer()
            and which("ninja") is not None
            and (self.num_heads == 128)
            and (self.qk_nope_head_dim == 128)
            and (self.qk_rope_head_dim == 64)
        )
        self.masked_mha_available = _is_masked_mha_available(
            num_heads_total=num_heads * get_tensor_model_parallel_world_size(),
            kv_lora_rank=kv_lora_rank,
            qk_nope_head_dim=qk_nope_head_dim,
            qk_rope_head_dim=qk_rope_head_dim,
            v_head_dim=v_head_dim,
            kv_cache_dtype=kv_cache_dtype,
        )
        vllm_config = get_current_vllm_config()
        parallel_config = vllm_config.parallel_config
        cudagraph_mode = (
            vllm_config.compilation_config.cudagraph_mode or CUDAGraphMode.NONE
        )
        # The attention layer decides whether to use ShardQ.
        self.use_shardq = (
            self.supports_shardq
            and vllm_config.attention_config.sparse_mla_shard_q
            and vllm_config.attention_config.hisparse_config is None
            and parallel_config.tensor_parallel_size > 1
            and parallel_config.decode_context_parallel_size == 1
            and parallel_config.prefill_context_parallel_size == 1
            and cudagraph_mode.mixed_mode() != CUDAGraphMode.FULL
        )

    def record_logical_topk_ready(self) -> None:
        if self.index_group is not None:
            self.index_group.set_logical_topk_ready(self.index_group_index)

    def prepare_for_batch(self, attn_metadata: T | None) -> None:
        if self.index_group is not None:
            self.index_group.prepare_for_batch(self.index_group_index, attn_metadata)

    def _convert_logical_to_physical_topk(
        self,
        logical_topk_indices: torch.Tensor,
        attn_metadata: Any,
        *,
        block_stride_rows: int | None,
        return_valid_counts: bool,
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
        group = self.index_group
        assert group is not None
        assert self.dcp_world_size == 1
        return group.convert_logical_to_physical_topk(
            self.index_group_index,
            logical_topk_indices,
            attn_metadata,
            block_stride_rows=block_stride_rows,
            return_valid_counts=return_valid_counts,
        )

    def forward_mqa(
        self,
        q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: T,
        layer: AttentionLayer,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        assert self.topk_indices_buffer is not None
        num_tokens = q[0].shape[0] if isinstance(q, tuple) else q.shape[0]
        topk_start = attn_metadata.topk_start
        topk = self.topk_indices_buffer[topk_start : topk_start + num_tokens]
        num_decode_tokens = attn_metadata.num_decode_tokens
        block_size = attn_metadata.block_size
        index_group = self.index_group
        if not isinstance(index_group, HiSparseMLAIndexGroup):
            _, block_stride_rows = flat_kv_row_view(kv_c_and_k_pe_cache, block_size)
            if self.dcp_world_size > 1:
                physical_topk, valid_counts = triton_filter_and_convert_dcp_index(
                    attn_metadata.req_id_per_token[:num_tokens],
                    attn_metadata.block_table,
                    topk,
                    dcp_size=self.dcp_world_size,
                    dcp_rank=self.dcp_rank,
                    cp_kv_cache_interleave_size=attn_metadata.cp_kv_cache_interleave_size,
                    BLOCK_SIZE=block_size,
                    BLOCK_STRIDE_ROWS=block_stride_rows,
                    NUM_TOPK_TOKENS=topk.shape[1],
                    return_valid_counts=True,
                )
            # A mixed ShardQ step's decode tokens take the index group's
            # conversion, so its token-sharded ones convert here.
            elif topk_start or (
                self.group_conversion_decode_only
                and not (
                    index_group is not None
                    and index_group.num_layers > 1
                    and num_decode_tokens >= num_tokens
                )
            ):
                physical_topk, valid_counts = triton_convert_req_index_to_global_index(
                    attn_metadata.req_id_per_token[:num_tokens],
                    attn_metadata.block_table,
                    topk,
                    BLOCK_SIZE=block_size,
                    BLOCK_STRIDE_ROWS=block_stride_rows,
                    NUM_TOPK_TOKENS=topk.shape[1],
                    return_valid_counts=True,
                )
            else:
                physical_topk, valid_counts = self._convert_logical_to_physical_topk(
                    topk,
                    attn_metadata,
                    block_stride_rows=block_stride_rows,
                    return_valid_counts=True,
                )
            return self._forward_mqa_kernel(
                q,
                kv_c_and_k_pe_cache,
                physical_topk,
                valid_counts,
                layer=layer,
                block_size=block_size,
                is_decode=num_decode_tokens >= num_tokens,
            )

        assert self.dcp_world_size == 1
        layer_index = self.index_group_index
        hot_cache = index_group.physical_kv_cache(layer_index).view(
            kv_c_and_k_pe_cache.dtype
        )
        if (
            num_decode_tokens >= num_tokens
            or index_group.cache(layer_index).all_context_pages_resident
        ):
            physical_topk, valid_counts = index_group.convert_logical_to_physical_topk(
                layer_index,
                topk,
                attn_metadata,
                block_stride_rows=None,
                return_valid_counts=True,
            )
            return self._forward_mqa_kernel(
                q,
                hot_cache,
                physical_topk,
                valid_counts,
                layer=layer,
                block_size=block_size,
                is_decode=num_decode_tokens >= num_tokens,
            )

        decode_out = decode_lse = None
        if num_decode_tokens:
            physical_topk, valid_counts = index_group.convert_logical_to_physical_topk(
                layer_index,
                topk[:num_decode_tokens],
                attn_metadata,
                block_stride_rows=None,
                return_valid_counts=True,
            )
            q_decode = (
                (q[0][:num_decode_tokens], q[1][:num_decode_tokens])
                if isinstance(q, tuple)
                else q[:num_decode_tokens]
            )
            decode_out, decode_lse = self._forward_mqa_kernel(
                q_decode,
                hot_cache,
                physical_topk,
                valid_counts,
                layer=layer,
                block_size=block_size,
                is_decode=True,
            )

        prefill_cache, block_table, req_ids = index_group.stage_prefill_rows(
            layer_index, kv_c_and_k_pe_cache, attn_metadata
        )
        physical_topk, valid_counts = triton_convert_req_index_to_global_index(
            req_ids,
            block_table,
            topk[num_decode_tokens:],
            BLOCK_SIZE=block_size,
            NUM_TOPK_TOKENS=topk.shape[1],
            return_valid_counts=True,
        )
        q_prefill = (
            (q[0][num_decode_tokens:], q[1][num_decode_tokens:])
            if isinstance(q, tuple)
            else q[num_decode_tokens:]
        )
        prefill_out, prefill_lse = self._forward_mqa_kernel(
            q_prefill,
            prefill_cache,
            physical_topk,
            valid_counts,
            layer=layer,
            block_size=block_size,
            is_decode=False,
        )
        if decode_out is None:
            return prefill_out, prefill_lse
        out = torch.cat((decode_out, prefill_out))
        if decode_lse is None:
            return out, None
        assert prefill_lse is not None
        return out, torch.cat((decode_lse, prefill_lse))

    def _forward_mqa_kernel(
        self,
        q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
        kv_cache: torch.Tensor,
        topk_indices: torch.Tensor,
        valid_counts: torch.Tensor,
        *,
        layer: AttentionLayer,
        block_size: int,
        is_decode: bool,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        raise NotImplementedError

    @staticmethod
    def _slice_topk_per_req(
        topk_all: torch.Tensor,
        q_lens: list[int],
    ) -> list[torch.Tensor]:
        topk_per_req = []
        offset = 0
        for q_len in q_lens:
            topk_per_req.append(topk_all[offset : offset + q_len])
            offset += q_len
        return topk_per_req

    @staticmethod
    def _remap_topk_to_ranges(
        topk_per_req: list[torch.Tensor],
        range_starts: list[int] | torch.Tensor,
        range_lens: list[int],
    ) -> list[torch.Tensor]:
        remapped = []
        for topk, start, length in zip(topk_per_req, range_starts, range_lens):
            valid = (topk >= start) & (topk < start + length)
            remapped.append(torch.where(valid, topk - start, -1))
        return remapped

    def _project_kv(
        self, kv_c_normed: torch.Tensor, k_pe: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        kv_nope = self.kv_b_proj(kv_c_normed)[0].view(
            -1,
            self.num_heads,
            self.qk_nope_head_dim + self.v_head_dim,
        )
        k_nope, v = kv_nope.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
        return self._concat_k_nope_k_pe(k_nope, k_pe), v

    @staticmethod
    def _try_build_global_mask(
        topk_per_req: list[torch.Tensor],
        q_lens: list[int],
        max_query_len: int,
        max_seq_len: int,
        topk_mask_workspace: torch.Tensor,
    ) -> torch.Tensor | None:
        """Build a full-sequence top-k mask if it fits within the budget.

        When the mask fits, it is reused across the suffix and all context
        chunks, avoiding per-chunk mask rebuilds.  Returns None when the
        mask is too large, signalling the caller to fall back to per-chunk
        index remapping.
        """
        batch_size, padded_q_len, num_words_padded = _topk_mask_shape(
            len(q_lens),
            max_query_len,
            max_seq_len,
            reserve_key_starts_word=True,
        )
        needed = batch_size * padded_q_len * num_words_padded
        if needed > topk_mask_workspace.numel():
            return None

        mask = topk_mask_workspace[:needed].view(
            batch_size, padded_q_len, num_words_padded
        )
        _build_topk_mask(
            topk_per_req,
            q_lens,
            padded_q_len,
            max_seq_len,
            mask,
        )
        return mask

    def _run_masked_mha(
        self,
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        cu_seqlens_q: torch.Tensor,
        cu_seqlens_k: torch.Tensor,
        max_seqlen_q: int,
        max_seqlen_k: int,
        topk_per_req: list[torch.Tensor],
        q_lens: list[int],
        causal: bool,
        return_softmax_lse: bool = False,
        dense_mask: torch.Tensor | None = None,
        key_starts: torch.Tensor | None = None,
        topk_mask_workspace: torch.Tensor | None = None,
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
        from vllm.model_executor.layers.attention.sparse_mla_mask import (
            dense_mask_mod,
            offset_dense_mask_mod,
        )
        from vllm.vllm_flash_attn import flash_attn_varlen_func

        if dense_mask is None:
            assert topk_mask_workspace is not None
            batch_size, padded_q_len, num_words = _topk_mask_shape(
                len(q_lens), max_seqlen_q, max_seqlen_k
            )
            words_needed = batch_size * padded_q_len * num_words
            if words_needed > topk_mask_workspace.numel():
                raise ValueError(
                    f"Sparse MLA top-k mask needs {words_needed} int32 words (batch="
                    f"{len(q_lens)}, q={max_seqlen_q}, k={max_seqlen_k}) but the "
                    f"workspace holds {topk_mask_workspace.numel()}."
                )
            workspace_3d = topk_mask_workspace[:words_needed].view(
                batch_size, padded_q_len, num_words
            )
            dense_mask = _build_topk_mask(
                topk_per_req,
                q_lens,
                padded_q_len,
                max_seqlen_k,
                workspace_3d,
            )
        if key_starts is not None:
            dense_mask[:, 0, -1].copy_(key_starts)
        kwargs = {
            "q": q,
            "k": k,
            "v": v,
            "cu_seqlens_q": cu_seqlens_q,
            "cu_seqlens_k": cu_seqlens_k,
            "max_seqlen_q": max_seqlen_q,
            "max_seqlen_k": max_seqlen_k,
            "softmax_scale": self.scale,
            "return_softmax_lse": return_softmax_lse,
            "fa_version": 4,
            "mask_mod": dense_mask_mod if key_starts is None else offset_dense_mask_mod,
            "aux_tensors": [dense_mask],
            "aux_tensor_leading_dims": [2],
            "causal": causal,
        }

        return flash_attn_varlen_func(**kwargs)

    def _compute_context_mha(
        self,
        q: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        prefill_metadata: MLACommonPrefillMetadata,
        k_scale: torch.Tensor,
        q_lens: list[int],
        topk_per_req: list[torch.Tensor],
        dense_mask: torch.Tensor | None = None,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        if self.dcp_world_size > 1:
            raise NotImplementedError(
                "Masked MHA with context does not yet support decode context "
                "parallelism"
            )

        chunked_context = prefill_metadata.chunked_context
        assert chunked_context is not None
        output: torch.Tensor | None = None
        output_lse: torch.Tensor | None = None
        workspace = chunked_context.workspace

        for chunk in chunked_context.chunks:
            toks = chunk.num_context_tokens
            requests = chunk.request_slice
            ops.gather_and_maybe_dequant_cache(
                src_cache=kv_c_and_k_pe_cache,
                dst=workspace,
                block_table=prefill_metadata.block_table[requests],
                cu_seq_lens=chunk.cu_seq_lens,
                token_to_seq=chunk.token_to_seq,
                num_tokens=toks,
                kv_cache_dtype=self.kv_cache_dtype,
                scale=k_scale,
                seq_starts=chunk.starts,
            )

            chunk_kv_c = workspace[:toks, : self.kv_lora_rank]
            chunk_k_pe = workspace[:toks, self.kv_lora_rank :].unsqueeze(1)
            k, v = self._project_kv(chunk_kv_c, chunk_k_pe)
            if dense_mask is not None:
                chunk_mask: torch.Tensor | None = dense_mask[requests]
                chunk_topk = topk_per_req[requests]
                key_starts: torch.Tensor | None = chunk.starts
            else:
                chunk_mask = None
                chunk_topk = self._remap_topk_to_ranges(
                    topk_per_req[requests],
                    chunk.starts,
                    chunk.seq_lens.tolist(),
                )
                key_starts = None
            attn_out, lse = self._run_masked_mha(
                q=q[chunk.token_slice],
                k=k,
                v=v,
                cu_seqlens_q=chunk.query_start_loc,
                cu_seqlens_k=chunk.cu_seq_lens,
                max_seqlen_q=chunk.max_query_len,
                max_seqlen_k=chunk.max_seq_len,
                topk_per_req=chunk_topk,
                q_lens=q_lens[requests],
                causal=False,
                return_softmax_lse=True,
                dense_mask=chunk_mask,
                key_starts=key_starts,
                topk_mask_workspace=prefill_metadata.topk_mask_workspace,
            )

            if output is None:
                if (
                    len(chunked_context.chunks) == 1
                    and not chunked_context.empty_token_slices
                ):
                    return attn_out, lse
                output, output_lse = init_mla_context_partial(
                    chunked_context,
                    attn_out,
                    lse,
                    num_tokens=q.shape[0],
                )
            accumulate_mla_context_chunk(chunk, attn_out, lse, output, output_lse)

        assert output is not None and output_lse is not None
        return output, output_lse

    def forward_mha(  # type: ignore[override]
        self,
        q: torch.Tensor,
        kv_c_normed: torch.Tensor,
        k_pe: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: T,
        k_scale: torch.Tensor,
        output: torch.Tensor,
        output_scale: torch.Tensor | None = None,
    ) -> None:
        prefill_metadata = attn_metadata.prefill
        assert prefill_metadata is not None
        if prefill_metadata.route is SparseMLAPrefillRoute.DENSE_MHA:
            return super().forward_mha(
                q,
                kv_c_normed,
                k_pe,
                kv_c_and_k_pe_cache,
                attn_metadata,
                k_scale,
                output,
                output_scale,
            )

        assert prefill_metadata.route is SparseMLAPrefillRoute.MASKED_MHA
        assert output_scale is None
        assert self.masked_mha_available
        assert prefill_metadata.query_lens_cpu is not None
        assert self.topk_indices_buffer is not None

        q_lens = prefill_metadata.query_lens_cpu.tolist()
        num_decode_tokens = attn_metadata.num_decode_tokens
        topk_all = self.topk_indices_buffer[
            num_decode_tokens : num_decode_tokens + q.shape[0]
        ]
        topk_per_req = self._slice_topk_per_req(topk_all, q_lens)

        k, v = self._project_kv(kv_c_normed, k_pe)
        chunked_context = prefill_metadata.chunked_context
        if chunked_context is None:
            attn_out = self._run_masked_mha(
                q=q,
                k=k,
                v=v,
                cu_seqlens_q=prefill_metadata.query_start_loc,
                cu_seqlens_k=prefill_metadata.query_start_loc,
                max_seqlen_q=prefill_metadata.max_query_len,
                max_seqlen_k=prefill_metadata.max_query_len,
                topk_per_req=topk_per_req,
                q_lens=q_lens,
                causal=True,
                topk_mask_workspace=prefill_metadata.topk_mask_workspace,
            )
            assert isinstance(attn_out, torch.Tensor)
            output.copy_(attn_out[..., : self.v_head_dim].flatten(start_dim=-2))
            return

        context_lens = chunked_context.context_lens_list
        dense_mask = self._try_build_global_mask(
            topk_per_req,
            q_lens,
            prefill_metadata.max_query_len,
            attn_metadata.prefill_max_seq_len,
            prefill_metadata.topk_mask_workspace,
        )
        if dense_mask is not None:
            suffix_topk = topk_per_req
        else:
            suffix_topk = self._remap_topk_to_ranges(topk_per_req, context_lens, q_lens)
        suffix_output, suffix_lse = self._run_masked_mha(
            q=q,
            k=k,
            v=v,
            cu_seqlens_q=prefill_metadata.query_start_loc,
            cu_seqlens_k=prefill_metadata.query_start_loc,
            max_seqlen_q=prefill_metadata.max_query_len,
            max_seqlen_k=prefill_metadata.max_query_len,
            topk_per_req=suffix_topk,
            q_lens=q_lens,
            causal=True,
            return_softmax_lse=True,
            dense_mask=dense_mask,
            key_starts=(
                chunked_context.context_lens if dense_mask is not None else None
            ),
            topk_mask_workspace=prefill_metadata.topk_mask_workspace,
        )
        context_output, context_lse = self._compute_context_mha(
            q=q,
            kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
            prefill_metadata=prefill_metadata,
            k_scale=k_scale,
            q_lens=q_lens,
            topk_per_req=topk_per_req,
            dense_mask=dense_mask,
        )
        merge_attn_states(
            output=output.view(-1, self.num_heads, self.v_head_dim),
            prefix_output=context_output[..., : self.v_head_dim],
            prefix_lse=context_lse,
            suffix_output=suffix_output[..., : self.v_head_dim],
            suffix_lse=suffix_lse,
        )

_try_build_global_mask(topk_per_req, q_lens, max_query_len, max_seq_len, topk_mask_workspace) staticmethod

Build a full-sequence top-k mask if it fits within the budget.

When the mask fits, it is reused across the suffix and all context chunks, avoiding per-chunk mask rebuilds. Returns None when the mask is too large, signalling the caller to fall back to per-chunk index remapping.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
@staticmethod
def _try_build_global_mask(
    topk_per_req: list[torch.Tensor],
    q_lens: list[int],
    max_query_len: int,
    max_seq_len: int,
    topk_mask_workspace: torch.Tensor,
) -> torch.Tensor | None:
    """Build a full-sequence top-k mask if it fits within the budget.

    When the mask fits, it is reused across the suffix and all context
    chunks, avoiding per-chunk mask rebuilds.  Returns None when the
    mask is too large, signalling the caller to fall back to per-chunk
    index remapping.
    """
    batch_size, padded_q_len, num_words_padded = _topk_mask_shape(
        len(q_lens),
        max_query_len,
        max_seq_len,
        reserve_key_starts_word=True,
    )
    needed = batch_size * padded_q_len * num_words_padded
    if needed > topk_mask_workspace.numel():
        return None

    mask = topk_mask_workspace[:needed].view(
        batch_size, padded_q_len, num_words_padded
    )
    _build_topk_mask(
        topk_per_req,
        q_lens,
        padded_q_len,
        max_seq_len,
        mask,
    )
    return mask

SparseMLACommonMetadataBuilder

Bases: AttentionMetadataBuilder[T]

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
class SparseMLACommonMetadataBuilder(AttentionMetadataBuilder[T]):
    metadata_cls: type[T]
    require_uniform_decodes: ClassVar[bool] = False

    def __init__(
        self,
        kv_cache_spec: "AttentionSpec",
        layer_names: list[str],
        vllm_config: "VllmConfig",
        device: torch.device,
    ) -> None:
        super().__init__(kv_cache_spec, layer_names, vllm_config, device)
        self.vllm_config = vllm_config
        self.device = device
        self.model_config = vllm_config.model_config
        self.mla_dims = get_mla_dims(self.model_config)
        self.topk_tokens: int = vllm_config.model_config.hf_text_config.index_topk
        self.req_id_per_token_buffer = torch.empty(
            (vllm_config.scheduler_config.max_num_batched_tokens,),
            dtype=torch.int32,
            device=device,
        )
        self._context_lens_cpu = torch.empty(
            vllm_config.scheduler_config.max_num_seqs,
            dtype=torch.int32,
            device="cpu",
            pin_memory=PIN_MEMORY,
        )
        parallel_config = vllm_config.parallel_config
        self.pcp_world_size = parallel_config.prefill_context_parallel_size
        self.use_pcp = self.pcp_world_size > 1
        try:
            self.dcp_world_size = get_dcp_group().world_size
        except AssertionError:
            # DCP might not be initialized in testing
            self.dcp_world_size = 1
        self.cp_kv_cache_interleave_size = parallel_config.cp_kv_cache_interleave_size
        self.dcp_local_block_size = self.cp_kv_cache_interleave_size
        self.dcp_virtual_block_size = self.dcp_local_block_size * self.dcp_world_size

        self.chunked_prefill_workspace_size = (
            self.determine_chunked_prefill_workspace_size(vllm_config)
        )
        workspace_head_size = (
            self.mla_dims.kv_lora_rank + self.mla_dims.qk_rope_head_dim
        )
        workspace_rows = self.chunked_prefill_workspace_size
        if self.dcp_world_size > 1:
            # DCP gathers each rank's local KV shard into the workspace, so it
            # needs an extra 1/DCP rows beyond the TP allocation.
            assert self.chunked_prefill_workspace_size % self.dcp_world_size == 0
            workspace_rows += self.chunked_prefill_workspace_size // self.dcp_world_size
        self.chunked_prefill_workspace = torch.empty(
            (workspace_rows, workspace_head_size),
            dtype=self.model_config.dtype,
            device=device,
        )
        self.topk_mask_workspace: torch.Tensor | None = None
        if _is_masked_mha_available(
            self.model_config.model_arch_config.total_num_attention_heads,
            self.mla_dims.kv_lora_rank,
            self.mla_dims.qk_nope_head_dim,
            self.mla_dims.qk_rope_head_dim,
            self.mla_dims.v_head_dim,
            vllm_config.cache_config.cache_dtype,
        ):
            self.topk_mask_workspace = torch.zeros(
                GLOBAL_TOPK_MASK_MAX_BYTES // torch.int32.itemsize,
                dtype=torch.int32,
                device=device,
            )
        attention_layer = vllm_config.compilation_config.static_forward_context[
            layer_names[0]
        ]
        layer_prefill_backend = attention_layer.prefill_backend
        self._backend_name = attention_layer.get_attn_backend().get_name()
        # The workspace follows the global KV dtype; a layer group can differ
        # (e.g. an MTP draft with its own kv_cache_dtype).
        self._masked_mha_available = (
            self.topk_mask_workspace is not None
            and attention_layer.impl.masked_mha_available
        )
        self.dcp_manager: MLADCPManager | None = None
        if self.dcp_world_size > 1:
            self.dcp_manager = getattr(attention_layer, "dcp_manager", None)
            assert isinstance(self.dcp_manager, MLADCPManager)
            if layer_prefill_backend is not None:
                self.dcp_manager.init_kv_gather(
                    self.chunked_prefill_workspace,
                    self.chunked_prefill_workspace_size,
                )
        self._prefill_backend = (
            layer_prefill_backend.clone() if layer_prefill_backend is not None else None
        )
        layers = vllm_config.compilation_config.static_forward_context
        self.use_shardq = any(
            getattr(layers[name], "use_shardq", False) for name in layer_names
        )

    def _init_reorder_batch_threshold(
        self,
        reorder_batch_threshold: int | None = 1,
        supports_spec_as_decode: bool = False,
        supports_dcp_with_varlen: bool = False,
    ) -> None:
        if self.vllm_config.attention_config.hisparse_config is not None:
            reorder_batch_threshold = 1
        super()._init_reorder_batch_threshold(
            reorder_batch_threshold,
            supports_spec_as_decode,
            supports_dcp_with_varlen,
        )

    @staticmethod
    def determine_chunked_prefill_workspace_size(vllm_config: "VllmConfig") -> int:
        scheduler_config = vllm_config.scheduler_config
        cache_config = vllm_config.cache_config
        model_config = vllm_config.model_config
        topk_tokens = model_config.hf_text_config.index_topk

        workspace_size = min(
            max(
                8 * model_config.max_model_len,
                4 * scheduler_config.max_num_seqs * cache_config.block_size,
            ),
            64 * 1024,
            scheduler_config.max_num_seqs * topk_tokens,
        )
        workspace_size = max(workspace_size, cache_config.block_size)
        if vllm_config.parallel_config.decode_context_parallel_size > 1:
            return align_mla_chunked_context_workspace_size(vllm_config, workspace_size)
        return workspace_size

    def _build_req_id_per_token(
        self,
        common_attn_metadata: "CommonAttentionMetadata",
    ) -> torch.Tensor:
        return common_attn_metadata.token_to_req_indices(self.req_id_per_token_buffer)

    def _build_chunked_context_fields(
        self,
        common_attn_metadata: "CommonAttentionMetadata",
        num_decodes: int,
        num_prefills: int,
        prefill_query_lens_cpu: torch.Tensor | None,
    ) -> "MLACommonPrefillMetadata.ChunkedContextMetadata | None":
        if num_prefills == 0 or prefill_query_lens_cpu is None:
            return None

        seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound
        assert seq_lens_cpu is not None
        context_lens_cpu = self._context_lens_cpu[:num_prefills]
        torch.subtract(
            seq_lens_cpu[num_decodes : num_decodes + num_prefills],
            prefill_query_lens_cpu,
            out=context_lens_cpu,
        )
        qsl_cpu = common_attn_metadata.query_start_loc_cpu
        prefill_query_start_loc_cpu = qsl_cpu[num_decodes:] - qsl_cpu[num_decodes]

        return build_mla_chunked_context_metadata(
            context_lens_cpu=context_lens_cpu,
            prefill_query_start_loc_cpu=prefill_query_start_loc_cpu,
            chunked_prefill_workspace=self.chunked_prefill_workspace,
            chunked_prefill_workspace_size=self.chunked_prefill_workspace_size,
            block_size=self.kv_cache_spec.block_size,
            align_chunk_to_block=current_platform.is_cuda(),
            device=self.device,
            dcp_world_size=self.dcp_world_size,
            dcp_local_block_size=self.dcp_local_block_size,
            dcp_virtual_block_size=self.dcp_virtual_block_size,
            dcp_manager=self.dcp_manager,
        )

    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: "CommonAttentionMetadata",
        fast_build: bool = False,
    ) -> T:
        req_id_per_token = self._build_req_id_per_token(common_attn_metadata)

        num_decodes, num_prefills, num_decode_tokens, _ = split_decodes_and_prefills(
            common_attn_metadata,
            decode_threshold=self.reorder_batch_threshold or 1,
            treat_short_extends_as_decodes=not self.use_pcp,
            require_uniform=self.require_uniform_decodes,
        )
        (
            prefill_query_start_loc,
            prefill_max_query_len,
            prefill_query_lens_cpu,
        ) = self._build_prefill_fields(common_attn_metadata, num_decodes, num_prefills)
        decode_max_query_len = 0
        if num_decodes:
            if common_attn_metadata.max_logits_per_req is not None:
                decode_max_query_len = common_attn_metadata.max_logits_per_req
            elif num_prefills == 0:
                decode_max_query_len = common_attn_metadata.max_query_len
            else:
                decode_query_lens_cpu = torch.diff(
                    common_attn_metadata.query_start_loc_cpu[: num_decodes + 1]
                )
                decode_max_query_len = int(decode_query_lens_cpu.max().item())

        shardq_split = (
            build_shardq_split(common_attn_metadata, self.vllm_config)
            if self.use_shardq
            else None
        )
        prefill_max_seq_len = 0
        prefill: SparseMLAPrefillMetadata | None = None
        if num_prefills > 0 and self._prefill_backend is not None:
            seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound
            assert seq_lens_cpu is not None
            prefill_max_seq_len = int(
                seq_lens_cpu[num_decodes : num_decodes + num_prefills].max().item()
            )
            block_table = common_attn_metadata.block_table_tensor[num_decodes:, ...]
            chunked_context = self._build_chunked_context_fields(
                common_attn_metadata,
                num_decodes,
                num_prefills,
                prefill_query_lens_cpu,
            )
            staging_plan = None
            if self.vllm_config.attention_config.hisparse_config is not None:
                prefill_seq_lens_cpu = seq_lens_cpu[
                    num_decodes : num_decodes + num_prefills
                ]
                staging_block_capacity = int(
                    (
                        (prefill_seq_lens_cpu + self.kv_cache_spec.block_size - 1)
                        // self.kv_cache_spec.block_size
                    ).sum()
                )
                staging_plan = build_hisparse_prefill_staging_plan(
                    block_table,
                    common_attn_metadata.seq_lens[num_decodes:],
                    self.kv_cache_spec.block_size,
                    staging_block_capacity,
                )
                if chunked_context is not None:
                    block_table = staging_plan.block_table
            prefill = SparseMLAPrefillMetadata(
                block_table=block_table,
                query_start_loc=prefill_query_start_loc,
                max_query_len=prefill_max_query_len,
                query_lens_cpu=prefill_query_lens_cpu,
                chunked_context=chunked_context,
                q_data_type=self.model_config.dtype,
                output_dtype=self.model_config.dtype,
                prefill_backend=self._prefill_backend,
                topk_mask_workspace=self.topk_mask_workspace,
                host_staging_plan=staging_plan,
                route=self._prefill_route(
                    prefill_max_seq_len,
                    prefill_max_query_len,
                    prefill_query_lens_cpu,
                    chunked_context,
                    use_shardq=shardq_split is not None,
                ),
            )
            self._prefill_backend.prepare_metadata(prefill)

        metadata = self.metadata_cls(  # type: ignore[call-arg]
            num_reqs=common_attn_metadata.num_reqs,
            max_query_len=common_attn_metadata.max_query_len,
            max_seq_len=common_attn_metadata.max_seq_len,
            num_actual_tokens=common_attn_metadata.num_actual_tokens,
            query_start_loc=common_attn_metadata.query_start_loc,
            slot_mapping=common_attn_metadata.slot_mapping,
            block_table=common_attn_metadata.block_table_tensor,
            req_id_per_token=req_id_per_token,
            seq_lens=common_attn_metadata.seq_lens,
            block_size=self.kv_cache_spec.block_size,
            topk_tokens=self.topk_tokens,
            num_decodes=num_decodes,
            num_prefills=num_prefills,
            num_decode_tokens=num_decode_tokens,
            decode_max_query_len=decode_max_query_len,
            prefill_max_seq_len=prefill_max_seq_len,
            prefill=prefill,
            cp_kv_cache_interleave_size=self.cp_kv_cache_interleave_size,
        )
        if shardq_split is not None:
            metadata.shardq = build_shardq_metadata(shardq_split, metadata, self.device)
        return metadata

    def _prefill_route(
        self,
        prefill_max_seq_len: int,
        prefill_max_query_len: int,
        prefill_query_lens_cpu: torch.Tensor,
        chunked_context: "MLACommonPrefillMetadata.ChunkedContextMetadata | None",
        use_shardq: bool,
    ) -> SparseMLAPrefillRoute:
        attention_config = self.vllm_config.attention_config
        # ShardQ's top-k are compact per rank, so its prefills run in forward_mqa.
        if (
            attention_config.sparse_mla_force_mqa
            or attention_config.hisparse_config is not None
            or use_shardq
        ):
            return SparseMLAPrefillRoute.SPARSE_MQA
        if prefill_max_seq_len <= self.topk_tokens:
            # Dense MHA cannot be used under PCP+DCP.
            if self.use_pcp and self.dcp_world_size > 1:
                return SparseMLAPrefillRoute.SPARSE_MQA
            return SparseMLAPrefillRoute.DENSE_MHA
        if (
            self._masked_mha_available
            and self.dcp_world_size <= 1
            and _use_masked_mha(
                backend_name=self._backend_name,
                tensor_parallel_size=(
                    self.vllm_config.parallel_config.tensor_parallel_size
                ),
                qk_head_dim=self.mla_dims.qk_nope_head_dim
                + self.mla_dims.qk_rope_head_dim,
                v_head_dim=self.mla_dims.v_head_dim,
                query_len=prefill_max_query_len,
                seq_len=prefill_max_seq_len,
                has_context=chunked_context is not None,
            )
            and self._topk_masks_fit(
                len(prefill_query_lens_cpu), prefill_max_query_len, chunked_context
            )
        ):
            return SparseMLAPrefillRoute.MASKED_MHA
        return SparseMLAPrefillRoute.SPARSE_MQA

    def _topk_masks_fit(
        self,
        batch_size: int,
        max_query_len: int,
        chunked_context: "MLACommonPrefillMetadata.ChunkedContextMetadata | None",
    ) -> bool:
        """Whether this prefill batch's top-k masks fit the workspace."""
        assert self.topk_mask_workspace is not None
        max_context_chunk_seq_len = 0
        if chunked_context is not None:
            max_context_chunk_seq_len = max(
                chunk.max_seq_len for chunk in chunked_context.chunks
            )
        fits = _masked_mha_workspace_fits(
            batch_size=batch_size,
            max_query_len=max_query_len,
            max_context_chunk_seq_len=max_context_chunk_seq_len,
            workspace_numel=self.topk_mask_workspace.numel(),
        )
        if not fits:
            logger.warning_once(
                "Sparse MLA top-k mask workspace (%d MiB) is too small for some "
                "prefill batches; those fall back to slower sparse MQA.",
                self.topk_mask_workspace.numel()
                * torch.int32.itemsize
                // (1024 * 1024),
            )
        return fits

    @staticmethod
    def _build_prefill_fields(
        common_attn_metadata: "CommonAttentionMetadata",
        num_decodes: int,
        num_prefills: int,
    ) -> tuple[
        torch.Tensor | None,  # prefill_query_start_loc
        int,  # prefill_max_query_len
        torch.Tensor | None,  # prefill_query_lens_cpu
    ]:
        if num_prefills == 0:
            return None, 0, None

        offset = common_attn_metadata.query_start_loc[num_decodes]
        prefill_query_start_loc = (
            common_attn_metadata.query_start_loc[num_decodes:] - offset
        )

        qsl_cpu = common_attn_metadata.query_start_loc_cpu
        prefill_qsl_cpu = qsl_cpu[num_decodes:] - qsl_cpu[num_decodes]
        prefill_query_lens = prefill_qsl_cpu[1:] - prefill_qsl_cpu[:-1]
        prefill_max_query_len = int(prefill_query_lens.max().item())

        return (
            prefill_query_start_loc,
            prefill_max_query_len,
            prefill_query_lens,
        )

_topk_masks_fit(batch_size, max_query_len, chunked_context)

Whether this prefill batch's top-k masks fit the workspace.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def _topk_masks_fit(
    self,
    batch_size: int,
    max_query_len: int,
    chunked_context: "MLACommonPrefillMetadata.ChunkedContextMetadata | None",
) -> bool:
    """Whether this prefill batch's top-k masks fit the workspace."""
    assert self.topk_mask_workspace is not None
    max_context_chunk_seq_len = 0
    if chunked_context is not None:
        max_context_chunk_seq_len = max(
            chunk.max_seq_len for chunk in chunked_context.chunks
        )
    fits = _masked_mha_workspace_fits(
        batch_size=batch_size,
        max_query_len=max_query_len,
        max_context_chunk_seq_len=max_context_chunk_seq_len,
        workspace_numel=self.topk_mask_workspace.numel(),
    )
    if not fits:
        logger.warning_once(
            "Sparse MLA top-k mask workspace (%d MiB) is too small for some "
            "prefill batches; those fall back to slower sparse MQA.",
            self.topk_mask_workspace.numel()
            * torch.int32.itemsize
            // (1024 * 1024),
        )
    return fits

_build_topk_mask(topk_indices_per_req, q_lens, max_q_len, max_seq_len, out)

Build a bit-packed top-k mask while preserving padded row storage.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def _build_topk_mask(
    topk_indices_per_req: list[torch.Tensor],
    q_lens: list[int],
    max_q_len: int,
    max_seq_len: int,
    out: torch.Tensor,
) -> torch.Tensor:
    """Build a bit-packed top-k mask while preserving padded row storage."""
    batch_size = len(q_lens)
    num_words = (max_seq_len + 31) // 32
    total_rows = batch_size * max_q_len
    if total_rows == 0:
        return out[:batch_size, :max_q_len]

    total_q = sum(q_lens)
    mask_row_stride = out.stride(-2)
    block_words = triton.next_power_of_2(num_words)

    if batch_size == 1:
        topk_packed = topk_indices_per_req[0]
        num_topk = topk_packed.shape[1]
        _scatter_topk_single_req_kernel[(max_q_len,)](
            out,
            topk_packed,
            num_words=num_words,
            mask_row_stride=mask_row_stride,
            num_topk=num_topk,
            topk_stride=topk_packed.stride(0),
            total_q=total_q,
            BLOCK_TOPK=triton.next_power_of_2(num_topk),
            BLOCK_WORDS=block_words,
        )
        return out[:1, :max_q_len]

    topk_packed = torch.cat(topk_indices_per_req, dim=0)
    num_topk = topk_packed.shape[1]
    q_lens_tensor = np_to_pinned_tensor(np.asarray(q_lens, dtype=np.int32)).to(
        out.device, non_blocking=True
    )
    cu_q_lens = out.new_zeros(batch_size + 1)
    torch.cumsum(q_lens_tensor, dim=0, out=cu_q_lens[1:])
    _scatter_topk_kernel[(total_rows,)](
        out,
        topk_packed,
        cu_q_lens,
        num_words=num_words,
        mask_row_stride=mask_row_stride,
        num_topk=num_topk,
        topk_stride=topk_packed.stride(0),
        max_q_len=max_q_len,
        BLOCK_TOPK=triton.next_power_of_2(num_topk),
        BLOCK_WORDS=block_words,
    )
    return out[:batch_size, :max_q_len]

_is_masked_mha_available(num_heads_total, kv_lora_rank, qk_nope_head_dim, qk_rope_head_dim, v_head_dim, kv_cache_dtype)

Check if masked MHA can ever fire for this model configuration.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def _is_masked_mha_available(
    num_heads_total: int,
    kv_lora_rank: int,
    qk_nope_head_dim: int,
    qk_rope_head_dim: int,
    v_head_dim: int,
    kv_cache_dtype: str,
) -> bool:
    """Check if masked MHA can ever fire for this model configuration."""
    if not current_platform.is_device_capability_family(100):
        return False
    model_dims = (
        num_heads_total,
        kv_lora_rank,
        qk_nope_head_dim,
        qk_rope_head_dim,
        v_head_dim,
    )
    if model_dims not in (
        (128, 512, 128, 64, 128),
        (64, 512, 192, 64, 256),
        # GLM-5.3-Flash: NoPE, qk_head_dim 256 == the (192, 64, 256) kernel.
        (64, 512, 256, 0, 256),
    ):
        return False
    fa_version = get_flash_attn_version(
        head_size=qk_nope_head_dim + qk_rope_head_dim, head_size_v=v_head_dim
    )
    return fa_version == 4 and not is_quantized_kv_cache(kv_cache_dtype)

_masked_mha_workspace_fits(batch_size, max_query_len, max_context_chunk_seq_len, workspace_numel)

Return whether the suffix and per-context-chunk masks fit the workspace.

The global mask is excluded: it always needs more, and has its own check.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def _masked_mha_workspace_fits(
    batch_size: int,
    max_query_len: int,
    max_context_chunk_seq_len: int,
    workspace_numel: int,
) -> bool:
    """Return whether the suffix and per-context-chunk masks fit the workspace.

    The global mask is excluded: it always needs more, and has its own check.
    """
    max_key_len = max(max_query_len, max_context_chunk_seq_len)
    needed = math.prod(_topk_mask_shape(batch_size, max_query_len, max_key_len))
    return needed <= workspace_numel

_topk_mask_shape(batch_size, max_query_len, max_key_len, reserve_key_starts_word=False)

Shape of a bit-packed top-k mask, shared by every site that builds one.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def _topk_mask_shape(
    batch_size: int,
    max_query_len: int,
    max_key_len: int,
    reserve_key_starts_word: bool = False,
) -> tuple[int, int, int]:
    """Shape of a bit-packed top-k mask, shared by every site that builds one."""
    tile_m = 128 if max_query_len <= 128 else 256
    padded_q_len = triton.cdiv(max_query_len, tile_m) * tile_m
    num_words = triton.cdiv(max_key_len, 32) + int(reserve_key_starts_word)
    num_words = triton.cdiv(num_words, 4) * 4
    return batch_size, padded_q_len, num_words

build_shardq_metadata(split, metadata, device)

This step's ShardQ, with metadata narrowed to this rank's tokens.

Source code in vllm/model_executor/layers/attention/sparse_mla_attention.py
def build_shardq_metadata(
    split: ShardQSplit,
    metadata: SparseMLACommonMetadata,
    device: torch.device,
) -> ShardQMetadata:
    """This step's ShardQ, with `metadata` narrowed to this rank's tokens."""
    num_decode_tokens = split.num_decode_tokens
    shardq = ShardQMetadata(
        num_decode_tokens=num_decode_tokens,
        num_tokens_per_rank=split.num_tokens_per_rank.tolist(),
        token_ids=async_tensor_h2d(split.token_ids, device=device),
        rank_offsets=async_tensor_h2d(
            np.r_[0, np.cumsum(split.num_tokens_per_rank)], device=device
        ),
    )
    # The indexer wrote these tokens' top-k compactly after the decodes.
    shardq.attn_metadata = replace(
        metadata,
        num_decodes=0,
        num_decode_tokens=0,
        req_id_per_token=metadata.req_id_per_token[
            shardq.local_token_ids + num_decode_tokens
        ],
        topk_start=num_decode_tokens,
    )
    return shardq