| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import os |
| 5 | from typing import ClassVar |
| 6 | |
| 7 | import torch |
| 8 | |
| 9 | import vllm._custom_ops as ops |
| 10 | from vllm.config.cache import CacheDType |
| 11 | from vllm.logger import init_logger |
| 12 | from vllm.model_executor.layers.attention.mla_attention import ( |
| 13 | MLACommonBackend, |
| 14 | MLACommonImpl, |
| 15 | MLACommonMetadata, |
| 16 | MLACommonMetadataBuilder, |
| 17 | ) |
| 18 | from vllm.platforms.interface import DeviceCapability |
| 19 | from vllm.utils.platform_utils import num_compute_units |
| 20 | from vllm.utils.torch_utils import is_quantized_kv_cache |
| 21 | from vllm.v1.attention.backend import ( |
| 22 | AttentionCGSupport, |
| 23 | AttentionLayer, |
| 24 | AttentionType, |
| 25 | MultipleOf, |
| 26 | ) |
| 27 | |
| 28 | logger = init_logger(__name__) |
| 29 | |
| 30 | |
| 31 | class CutlassMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]): |
| 32 | # enable full CUDA Graph support for decode-only capture |
| 33 | _cudagraph_support: ClassVar[AttentionCGSupport] = ( |
| 34 | AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE |
| 35 | ) |
| 36 | |
| 37 | |
| 38 | class CutlassMLABackend(MLACommonBackend): |
| 39 | supported_dtypes: ClassVar[list[torch.dtype]] = [torch.float16, torch.bfloat16] |
| 40 | supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ |
| 41 | "auto", |
| 42 | "float16", |
| 43 | "bfloat16", |
| 44 | "fp8", |
| 45 | "fp8_e4m3", |
| 46 | ] |
| 47 | |
| 48 | @staticmethod |
| 49 | def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]: |
| 50 | return [128] |
| 51 | |
| 52 | @staticmethod |
| 53 | def get_name() -> str: |
| 54 | return "CUTLASS_MLA" |
| 55 | |
| 56 | @staticmethod |
| 57 | def get_impl_cls() -> type["CutlassMLAImpl"]: |
| 58 | return CutlassMLAImpl |
| 59 | |
| 60 | @staticmethod |
| 61 | def get_builder_cls() -> type["CutlassMLAMetadataBuilder"]: |
| 62 | return CutlassMLAMetadataBuilder |
| 63 | |
| 64 | @classmethod |
| 65 | def supports_compute_capability(cls, capability: DeviceCapability) -> bool: |
| 66 | return capability.major == 10 |
| 67 | |
| 68 | |
| 69 | class SM100Workspace: |
| 70 | def __init__(self, initial_workspace_size): |
| 71 | self._workspace_buf = torch.empty( |
| 72 | initial_workspace_size, device="cuda", dtype=torch.uint8 |
| 73 | ) |
| 74 | |
| 75 | self._block_size = 128 # Forced to 128 |
| 76 | |
| 77 | # Pre-compute sm_count to avoid recomputing it. Use device 0 as a proxy |
| 78 | # (assumes all devices are similar) |
| 79 | self._sm_count = num_compute_units(0) |
| 80 | |
| 81 | def get_buf(self): |
| 82 | return self._workspace_buf |
| 83 | |
| 84 | def ensure_size(self, attn_metadata: MLACommonMetadata, num_kv_splits: int): |
| 85 | batch_size = attn_metadata.num_reqs |
| 86 | max_seq_len = attn_metadata.max_query_len |
| 87 | |
| 88 | workspace_size = ops.sm100_cutlass_mla_get_workspace_size( |
| 89 | max_seq_len * self._block_size, |
| 90 | batch_size, |
| 91 | self._sm_count, |
| 92 | num_kv_splits=num_kv_splits, |
| 93 | ) |
| 94 | |
| 95 | if self._workspace_buf.shape[0] < workspace_size: |
| 96 | self._workspace_buf.resize_(workspace_size) |
| 97 | |
| 98 | |
| 99 | g_sm100_workspace = SM100Workspace(128 * 1024 * 1024) # 128MB |
| 100 | |
| 101 | MAX_HEADS = 128 |
| 102 | |
| 103 | |
| 104 | class CutlassMLAImpl(MLACommonImpl[MLACommonMetadata]): |
| 105 | can_return_lse_for_decode: bool = True |
| 106 | supports_dcp: bool = True |
| 107 | |
| 108 | def __init__( |
| 109 | self, |
| 110 | num_heads: int, |
| 111 | head_size: int, |
| 112 | scale: float, |
| 113 | num_kv_heads: int, |
| 114 | alibi_slopes: list[float] | None, |
| 115 | sliding_window: int | None, |
| 116 | kv_cache_dtype: str, |
| 117 | logits_soft_cap: float | None, |
| 118 | attn_type: str, |
| 119 | kv_sharing_target_layer_name: str | None, |
| 120 | # MLA Specific Arguments |
| 121 | **mla_args, |
| 122 | ) -> None: |
| 123 | super().__init__( |
| 124 | num_heads, |
| 125 | head_size, |
| 126 | scale, |
| 127 | num_kv_heads, |
| 128 | alibi_slopes, |
| 129 | sliding_window, |
| 130 | kv_cache_dtype, |
| 131 | logits_soft_cap, |
| 132 | attn_type, |
| 133 | kv_sharing_target_layer_name, |
| 134 | q_pad_num_heads=MAX_HEADS, |
| 135 | **mla_args, |
| 136 | ) |
| 137 | |
| 138 | unsupported_features = [alibi_slopes, sliding_window, logits_soft_cap] |
| 139 | if any(unsupported_features): |
| 140 | raise NotImplementedError( |
| 141 | "CutlassMLAImpl does not support one of the following: " |
| 142 | "alibi_slopes, sliding_window, logits_soft_cap" |
| 143 | ) |
| 144 | |
| 145 | if attn_type != AttentionType.DECODER: |
| 146 | raise NotImplementedError( |
| 147 | "Encoder self-attention and " |
| 148 | "encoder/decoder cross-attention " |
| 149 | "are not implemented for " |
| 150 | "CutlassMLAImpl" |
| 151 | ) |
| 152 | |
| 153 | # TODO: Currently, num_kv_splits is limited to 16 to avoid hanging |
| 154 | # issues. In case the code hangs, use: |
| 155 | # FORCE_NUM_KV_SPLITS=1 |
| 156 | force_num_kv_splits = os.environ.get("FORCE_NUM_KV_SPLITS", None) |
| 157 | if force_num_kv_splits: |
| 158 | logger.debug_once("Forcing num_kv_splits to %d", int(force_num_kv_splits)) |
| 159 | self._num_kv_splits = int(force_num_kv_splits) |
| 160 | else: |
| 161 | self._num_kv_splits = -1 # => Auto-detect |
| 162 | |
| 163 | # Share workspace buffer across all executions |
| 164 | self._workspace = g_sm100_workspace |
| 165 | |
| 166 | def _sm100_cutlass_mla_decode( |
| 167 | self, |
| 168 | q_nope: torch.Tensor, |
| 169 | q_pe: torch.Tensor, |
| 170 | kv_c_and_k_pe_cache: torch.Tensor, |
| 171 | seq_lens: torch.Tensor, |
| 172 | page_table: torch.Tensor, |
| 173 | workspace: torch.Tensor, |
| 174 | sm_scale: float, |
| 175 | num_kv_splits: int, |
| 176 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 177 | assert q_nope.ndim == 3, f"q_nope must be a 3D tensor, but got {q_nope.ndim}" |
| 178 | assert q_pe.ndim == 3, f"q_pe must be a 3D tensor, but got {q_pe.ndim}" |
| 179 | assert kv_c_and_k_pe_cache.ndim == 3, ( |
| 180 | "kv_c_and_k_pe_cache must be a 3D tensor, but got {}".format( |
| 181 | kv_c_and_k_pe_cache.ndim |
| 182 | ) |
| 183 | ) |
| 184 | |
| 185 | B_q, H, D_q_nope = q_nope.shape |
| 186 | B_q_2, H_2, D_q_pe = q_pe.shape |
| 187 | assert (B_q == B_q_2) and (H == H_2) |
| 188 | |
| 189 | _, PAGE_SIZE, D_ckv = kv_c_and_k_pe_cache.shape |
| 190 | |
| 191 | D_latent = 512 |
| 192 | D_rope = 64 |
| 193 | assert D_q_nope == D_latent |
| 194 | assert D_q_pe == D_rope |
| 195 | assert D_ckv == D_latent + D_rope |
| 196 | |
| 197 | MAX_HEADS = 128 |
| 198 | assert H <= MAX_HEADS, f"H must be <= {MAX_HEADS}, but got {H}" |
| 199 | |
| 200 | assert len(page_table.shape) == 2 |
| 201 | B_block_table, block_num = page_table.shape |
| 202 | assert B_block_table == B_q |
| 203 | assert block_num > 0, f"block num must be greater than 0, got {block_num}" |
| 204 | assert block_num % (128 / PAGE_SIZE) == 0 |
| 205 | |
| 206 | assert q_nope.dtype in (torch.float16, torch.bfloat16, torch.float8_e4m3fn), ( |
| 207 | f"q_nope.dtype needs to be fp16 or bf16 or e4m3 but got {q_nope.dtype}." |
| 208 | ) |
| 209 | assert q_nope.dtype == q_pe.dtype == kv_c_and_k_pe_cache.dtype |
| 210 | assert seq_lens.dtype == torch.int32, ( |
| 211 | f"seq_lens.dtype needs to be int32 but got {seq_lens.dtype}." |
| 212 | ) |
| 213 | assert page_table.dtype == torch.int32, ( |
| 214 | f"page_table.dtype needs to be int32 but got {page_table.dtype}." |
| 215 | ) |
| 216 | |
| 217 | dtype = ( |
| 218 | torch.bfloat16 |
| 219 | if is_quantized_kv_cache(self.kv_cache_dtype) |
| 220 | else q_nope.dtype |
| 221 | ) |
| 222 | out = q_nope.new_empty((B_q, MAX_HEADS, D_latent), dtype=dtype) |
| 223 | lse = ( |
| 224 | torch.empty((B_q, MAX_HEADS), dtype=torch.float32, device=q_nope.device) |
| 225 | if self.need_to_return_lse_for_decode |
| 226 | else torch.Tensor() |
| 227 | ) |
| 228 | |
| 229 | ops.sm100_cutlass_mla_decode( |
| 230 | out, |
| 231 | lse, |
| 232 | q_nope, |
| 233 | q_pe, |
| 234 | kv_c_and_k_pe_cache, |
| 235 | seq_lens, |
| 236 | page_table, |
| 237 | workspace, |
| 238 | sm_scale, |
| 239 | num_kv_splits, |
| 240 | ) |
| 241 | |
| 242 | if H < MAX_HEADS: |
| 243 | # Extract the subsets of the outputs |
| 244 | lse = lse[:, :H] if self.need_to_return_lse_for_decode else lse |
| 245 | out = out[:, :H] |
| 246 | |
| 247 | return out, lse |
| 248 | |
| 249 | def forward_mqa( |
| 250 | self, |
| 251 | q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], |
| 252 | kv_c_and_k_pe_cache: torch.Tensor, |
| 253 | attn_metadata: MLACommonMetadata, |
| 254 | layer: AttentionLayer, |
| 255 | ) -> tuple[torch.Tensor, torch.Tensor | None]: |
| 256 | assert kv_c_and_k_pe_cache.numel() > 0 |
| 257 | assert attn_metadata.decode is not None |
| 258 | |
| 259 | if layer._q_scale_float != 1.0 or layer._k_scale_float != 1.0: |
| 260 | raise NotImplementedError( |
| 261 | "CutlassMLAImpl does not support scaling for q and kv_latent yet" |
| 262 | ) |
| 263 | |
| 264 | if type(q) is tuple: |
| 265 | q_nope, q_pe = q |
| 266 | else: |
| 267 | q_nope, q_pe = torch.split( |
| 268 | q, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 |
| 269 | ) |
| 270 | |
| 271 | # Adjust workspace size (if necessary) |
| 272 | self._workspace.ensure_size(attn_metadata, self._num_kv_splits) |
| 273 | |
| 274 | # Run MLA |
| 275 | o, lse = self._sm100_cutlass_mla_decode( |
| 276 | q_nope, |
| 277 | q_pe, |
| 278 | kv_c_and_k_pe_cache, |
| 279 | attn_metadata.decode.seq_lens, |
| 280 | attn_metadata.decode.block_table, |
| 281 | self._workspace.get_buf(), |
| 282 | self.scale, |
| 283 | self._num_kv_splits, |
| 284 | ) |
| 285 | |
| 286 | return o, (lse if self.need_to_return_lse_for_decode else None) |