common.py 85.4 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
"""
4
5
# MLA Common Components

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
This file implements common components for MLA implementations.

First we define:

Sq      as Q sequence length
Skv     as KV sequence length

MLA has two possible ways of computing, a data-movement friendly approach and a
compute friendly approach, we generally want to use the compute friendly
approach for "prefill" (i.e. the ratio Sq / Skv is "small", is near 1)
and the data-movement friendly approach for "decode" (i.e. the ratio
Sq / Skv is "large").

NOTE what we deem small and large is currently determined by if its labelled
prefill or decode by the scheduler, but this is something we should probably
tune.

Main reference: DeepseekV2 paper, and FlashInfer Implementation
(https://arxiv.org/abs/2405.04434 and https://github.com/flashinfer-ai/flashinfer/pull/551).

Deepseek's MLA attention works the following way:
Matthew Bonanni's avatar
Matthew Bonanni committed
27
* Use a single latent vector to represent the per-token entry of the KV cache.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
* For decode (i.e. the memory friendly approach) the attention "simulates" a
multi-head attention, while the compute is similar to multi-query attention.

Below is example of both paths assuming batchsize = 1

## More Extent Definitions:

C           Context length, `Skv - Sq`
H           hidden size
N           number of attention heads
Lq          latent dimension for Q              1536 in DSV3
Lkv         latent dimension for K/V            512 in DSV3
P           nope dimension, no rope.            128 in DSV3
R           rope dimension, goes through rope.  64 in DSV3
V           V head dim.                         128 in DSV3

## Vector/Matrix Definitions

h_t         hidden states (input to attention)  shape [Sq, H]
q_c         latent/compressed Q                 shape [Sq, Lq]
q_nope      uncompressed Q (no-rope)            shape [Sq, N, P]
q_pe        uncompressed Q (rope)               shape [Sq, N, R]
kv_c        latent/compressed KV                shape [Skv, Lkv]
k_pe        decoupled k position embeddings     shape [Skv, R]
new_kv_c    new kv_c from current iter          shape [Sq, Lkv]
new_k_pe    new k_pe from current iter          shape [Sq, R]
cache_kv_c  cached k_c from previous iters      shape [C, Lkv]
cache_k_pe  cached k_pe from previous iters     shape [C, R]
W_DQ        project h_t to q_c                  shape [H, Lq]
W_UQ        project q_c to q_nope               shape [Lq, N * P]
W_QR        project q_c to q_pe                 shape [Lq, N * R]
W_DKV       project h_t to kv_c                 shape [H, Lkv]
60
61
62
W_UK        project kv_c to k_nope              shape [Lkv, N, P]
W_KR        project h_t to k_pe                 shape [H, R]
W_UV        project kv_c to v                   shape [Lkv, N, V]
63
64
65
66
67
68
69
70
71
72
73
74
W_O         project v to h_t                    shape [N * V, H]


## Compute Friendly Approach (i.e. "_forward_prefill"):

q_c      = h_t @ W_DQ
q_nope   = (q_c @ W_UQ).view(Sq, N, P)
q_pe     = RoPE(q_c @ W_QR).view(Sq, N, R)
new_kv_c = h_t @ W_DKV
new_k_pe = RoPE(h_t @ W_KR)
kv_c     = torch.cat([new_kv_c, cache_kv_c], dim=0)
k_pe     = torch.cat([new_k_pe, cache_k_pe], dim=0)
75
76
k_nope   = (kv_c @ W_UK.view(Lkv, N * P)).view(Skv, N, P)
v        = (kv_c @ W_UV.view(Lkv, N * V)).view(Skv, N, V)
77
78
79
80
81
82
83
84

// MHA with QK headdim = P + R
//           V headdim = V
//      spda_o shape [Sq, N, V]
spda_o = scaled_dot_product_attention(
    torch.cat([q_nope, q_pe], dim=-1),
    torch.cat([k_nope, k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1),
    v
Matthew Bonanni's avatar
Matthew Bonanni committed
85
)
86
87
88
return spda_o @ W_O

NOTE: in the actual code,
89
90
    `kv_b_proj` is [W_UK; W_UV] concatenated per head
    `q_b_proj` is [W_UQ; W_QR] concatenated per head
91
92
93
94
95
96
97
    `out_proj` is W_O


## Data-Movement Friendly Approach (i.e. "_forward_decode"):

Runtime
q_c      = h_t @ W_DQ
98
99
q_nope   = (q_c @ W_UQ).view(-1, N, P)
ql_nope  = einsum("snh,lnh->snl", q, W_UK)
100
101
102
103
104
105
106
107
108
109
110
111
q_pe     = RoPE(q_c @ W_QR).view(Sq, N, R)
new_kv_c = h_t @ W_DKV
new_k_pe = RoPE(h_t @ W_KR)
kv_c     = torch.cat([new_kv_c, cache_kv_c], dim=0)
k_pe     = torch.cat([new_k_pe, cache_k_pe], dim=0)

// MQA with QK headdim = Lkv + R
//           V headdim = Lkv
//      spda_o shape [Sq, N, Lkv]
// NOTE: this is less compute-friendly since Lkv > P
//       but is more data-movement friendly since its MQA vs MHA
spda_o = scaled_dot_product_attention(
112
    torch.cat([ql_nope, q_pe], dim=-1),
113
114
115
    torch.cat([kv_c, k_pe], dim=-1),
    kv_c
)
116
117
118

o = einsum("snl,lnv->snv", spda_o.reshape(-1, N, Lkv), W_UV)
return o.view(-1, N * V) @ self.num_heads @ W_O
119
120
121
122


## Chunked Prefill

Matthew Bonanni's avatar
Matthew Bonanni committed
123
124
For chunked prefill we want to use the compute friendly algorithm. We are
assuming sufficiently large Sq / Skv ratio, in the future may want to switch to
125
126
127
128
129
the data-movement friendly approach if the chunk (i.e. `Sq`) is small.

However, the compute-friendly approach can potentially run out of memory if Skv
is large due to: `k_nope = (kv_c @ W_UK).view(Skv, N, P)`

Matthew Bonanni's avatar
Matthew Bonanni committed
130
131
To mitigate this, we chunk the computation of attention with respect to the
current context (i.e. `cache_kv_c` and `cache_k_pe`) so that we can used a
132
133
134
135
fixed workspace size.

The chunked prefill approach is as follows:

Matthew Bonanni's avatar
Matthew Bonanni committed
136
MCC        Max chunk of context to process per iter, computed dynamically,
137
138
139
140
141
142
143
           used to bound the memory usage

q_c        = h_t @ W_DQ
q_nope     = (q_c @ W_UQ).view(Sq, N, P)
q_pe       = RoPE(q_c @ W_QR).view(Sq, N, R)
new_kv_c   = h_t @ W_DKV
new_k_pe   = RoPE(h_t @ W_KR)
144
145
new_k_nope = (new_kv_c @ W_UK.view(Lkv, N * P)).view(Sq, N, P)
new_v      = (new_kv_c @ W_UV.view(Lkv, N * V)).view(Sq, N, V)
146
147
148
149
150
151
152
153
154
155
156
157

// MHA between queries and new KV
//     with QK headdim = P + R
//           V headdim = V
//    curr_o   shape [Sq, N, V]
//    curr_lse shape [N, Sq], this is just order FA returns
curr_o, curr_lse = scaled_dot_product_attention(
    torch.cat([q_nope, q_pe], dim=-1),
    torch.cat([new_k_nope, new_k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1),
    new_v,
    casual=True,
    return_softmax_lse=True
Matthew Bonanni's avatar
Matthew Bonanni committed
158
)
159
160
161
162
163

// Compute attention with the already existing context
for chunk_idx in range(cdiv(C, MCC)):
    chunk_start  = chunk_idx * MCC
    chunk_end    = min(chunk_start + MCC, C)
zhuwenwen's avatar
zhuwenwen committed
164
    Sc           = chunk_end - chunk_start
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    cache_kv_c_chunk   = cache_kv_c[chunk_start:chunk_end]
    cache_k_pe_chunk   = cache_k_pe[chunk_start:chunk_end]
    cache_k_nope_chunk = (cache_kv_c_chunk @ W_UK).view(-1, N, P)
    cache_v_chunk      = (cache_kv_c_chunk @ W_UV).view(-1, N, V)

    chunk_o, chunk_lse = scaled_dot_product_attention(
        torch.cat([q_nope, q_pe], dim=-1),
        torch.cat([cache_k_nope_chunk,
                   cache_k_pe_chunk.unsqueeze(1).expand(-1, N, -1)],
                   dim=-1),
        cache_v_chunk,
        casual=False,
        return_softmax_lse=True
    )

    curr_o, curr_lse = merge_attn_states(
        suffix_output=curr_o,
        suffix_lse=curr_lse,
        prefix_output=chunk_o,
        prefix_lse=chunk_lse,
    )

return curr_o @ W_O
"""
王敏's avatar
王敏 committed
189
import os
190
191
import functools
from abc import abstractmethod
192
from dataclasses import dataclass, field
193
from enum import Enum
194
from typing import ClassVar, Generic, TypeVar
195
196

import torch
197
from tqdm import tqdm
198
199

from vllm import _custom_ops as ops
200
from vllm import envs
201
from vllm._aiter_ops import rocm_aiter_ops
202
from vllm.config import ModelConfig, VllmConfig, get_current_vllm_config
203
from vllm.distributed.parallel_state import get_dcp_group, is_global_first_rank
204
from vllm.logger import init_logger
205
from vllm.model_executor.layers.batch_invariant import (
206
    vllm_is_batch_invariant,
207
)
208
209
210
211
212
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    LinearBase,
    UnquantizedLinearMethod,
)
Simon Mo's avatar
Simon Mo committed
213
from vllm.platforms import current_platform
214
from vllm.utils.flashinfer import has_nvidia_artifactory
215
from vllm.utils.math_utils import cdiv, round_down
216
217
218
219
from vllm.v1.attention.backend import (
    AttentionBackend,
    AttentionLayer,
    AttentionMetadata,
220
221
    AttentionMetadataBuilder,
    CommonAttentionMetadata,
222
223
224
    MLAAttentionImpl,
)
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
225
from vllm.v1.attention.backends.utils import (
226
    get_dcp_local_seq_lens,
227
228
229
230
    get_per_layer_parameters,
    infer_global_hyperparameters,
    split_decodes_and_prefills,
)
231
232
from vllm.v1.attention.ops.common import cp_lse_ag_out_rs
from vllm.v1.attention.ops.merge_attn_states import merge_attn_states
233
from vllm.v1.kv_cache_interface import AttentionSpec
234

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

class QueryLenSupport(Enum):
    """Defines the level of query length support for an attention backend's
    decode pipeline.

    - SINGLE_ONLY: Decode pipeline only supports single-token queries
                   (query_len=1)
    - UNIFORM: Decode pipeline supports uniform multi-token queries
               (all requests must have same query_len > 1)
    - VARLEN: Decode pipeline supports variable-length queries
              (mixed query lengths in same batch)
    """

    SINGLE_ONLY = "single_only"
    UNIFORM = "uniform"
    VARLEN = "varlen"


253
try:
254
255
256
    from vllm.vllm_flash_attn import (  # type: ignore[attr-defined]
        flash_attn_varlen_func,
    )
257

258
    is_vllm_fa = True
259
260
except ImportError:
    # For rocm use upstream flash attention
261
    if current_platform.is_rocm():
262
        from flash_attn import flash_attn_varlen_func  # type: ignore[no-redef]
263
    is_vllm_fa = False
264

265
266
try:
    from flashinfer import BatchPrefillWithRaggedKVCacheWrapper
267
268
    from flashinfer.prefill import cudnn_batch_prefill_with_kv_cache  # noqa: F401

269
270
    flashinfer_available = True
except ImportError:
271
    BatchPrefillWithRaggedKVCacheWrapper = object
272

273
    flashinfer_available = False
274
275


276
277
278
279
280
281
282
283
284
def dynamic_per_batched_tensor_quant(
    x: torch.Tensor, dtype: torch.dtype = torch.float8_e4m3fn
):
    DTYPE_MAX = torch.finfo(dtype).max
    min_val, max_val = x.aminmax()
    amax = torch.maximum(min_val.abs(), max_val.abs()).clamp(min=1e-10)
    scale = DTYPE_MAX / amax
    x_scl_sat = (x * scale).clamp(min=-DTYPE_MAX, max=DTYPE_MAX)
    return x_scl_sat.to(dtype).contiguous(), scale.float().reciprocal()
285
286


287
288
logger = init_logger(__name__)

289
290
CUDNN_WORKSPACE_SIZE = 12800

291
292
293
294
295
296

class MLACommonBackend(AttentionBackend):
    accept_output_buffer: bool = True

    @staticmethod
    def get_name() -> str:
297
        return "TRITON_MLA"
298
299

    @staticmethod
300
    def get_builder_cls() -> type["MLACommonMetadataBuilder"]:
301
302
303
304
305
306
307
308
        return MLACommonMetadataBuilder

    @staticmethod
    def get_kv_cache_shape(
        num_blocks: int,
        block_size: int,
        num_kv_heads: int,  # assumed to be 1 for MLA
        head_size: int,
309
        cache_dtype_str: str = "auto",
310
    ) -> tuple[int, ...]:
311
312
        return (num_blocks, block_size, head_size)

313
314
315
316
317
318
319
320
    @staticmethod
    def get_kv_cache_stride_order(
        include_num_layers_dimension: bool = False,
    ) -> tuple[int, ...]:
        # `stride_order` indicates the permutation that gets
        # us from `get_kv_cache_shape` to the actual memory layout we want.
        # (num_blocks, num_layers, block_size, head_size)
        return (1, 0, 2, 3) if include_num_layers_dimension else (0, 1, 2)
321

322
323
    @classmethod
    def get_supported_head_sizes(cls) -> list[int]:
324
325
        return [576]

326
    @classmethod
327
328
    def is_mla(cls) -> bool:
        return True
329

330
331

@dataclass
332
class MLACommonPrefillMetadata:
333
    """Prefill Specific Metadata"""
334
335
336
337
338
339
340
341
342

    @dataclass
    class ChunkedContextMetadata:
        # New for MLA (compared to FlashAttention)
        # For handling chunked prefill
        cu_seq_lens: torch.Tensor
        starts: torch.Tensor
        seq_tot: list[int]
        max_seq_lens: list[int]
343
        seq_lens: torch.Tensor
344
        workspace: torch.Tensor
345
346
        token_to_seq: torch.Tensor
        chunk_total_token: list[int]
347

348
        # for mla DCP
349
350
351
        padded_local_chunk_seq_lens: list[list[int]] | None = None
        local_context_lens_allranks: list[list[int]] | None = None
        padded_local_cu_seq_lens: torch.Tensor | None = None
352
        cu_seq_lens_lst: list[list[int]] | None = None
353
        chunk_size: int | None = None
354

355
356
357
    block_table: torch.Tensor
    query_start_loc: torch.Tensor
    max_query_len: int
358
    chunked_context: ChunkedContextMetadata | None = None
359
    query_seq_lens: torch.Tensor | None = None
360
    workspace_buffer: torch.Tensor | None = None
361
    q_data_type: torch.dtype | None = None
362

363

364
365
@dataclass
class FlashInferPrefillMetadata(MLACommonPrefillMetadata):
366
367
    prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
    prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = field(
368
369
        default_factory=list
    )
370
371


372
373
@dataclass
class CudnnPrefillMetadata(MLACommonPrefillMetadata):
374
    class ChunkedContextMetadata(MLACommonPrefillMetadata.ChunkedContextMetadata):
375
376
        seq_lens: torch.Tensor

377
    cudnn_workspace: torch.Tensor | None = None
378
379


380
381
382
383
@dataclass
class MLACommonDecodeMetadata:
    block_table: torch.Tensor
    seq_lens: torch.Tensor
384
    dcp_tot_seq_lens: torch.Tensor | None
385
386
387
388
389
390


D = TypeVar("D", bound=MLACommonDecodeMetadata)


@dataclass
391
class MLACommonMetadata(AttentionMetadata, Generic[D]):
392
393
394
395
396
    """Metadata for MLACommon.

    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """
397

398
399
400
401
402
403
404
405
    # NOTE(sang): Definition of context_len, query_len, and seq_len.
    # |---------- N-1 iteration --------|
    # |---------------- N iteration ---------------------|
    # |- tokenA -|......................|-- newTokens ---|
    # |---------- context_len ----------|
    # |-------------------- seq_len ---------------------|
    #                                   |-- query_len ---|

406
407
    num_reqs: int
    max_query_len: int
408
    max_seq_len: int
409

410
411
412
413
    num_actual_tokens: int  # Number of tokens excluding padding.
    query_start_loc: torch.Tensor
    slot_mapping: torch.Tensor

414
415
416
417
418
419
    # New for MLA (compared to FlashAttention)
    # For handling prefill decode split
    num_decodes: int
    num_decode_tokens: int
    num_prefills: int

420
    # The dimension of the attention heads
421
    head_dim: int | None = None
422

423
424
425
426
427
428
429
    decode: D | None = None
    prefill: (
        MLACommonPrefillMetadata
        | FlashInferPrefillMetadata
        | CudnnPrefillMetadata
        | None
    ) = None
430
431

    def __post_init__(self):
432
433
434
435
        if self.head_dim is not None and not MLACommonBackend.supports_head_size(
            self.head_dim
        ):
            raise ValueError(f"Head dimension {self.head_dim} is not supported by MLA.")
436
437


438
M = TypeVar("M", bound=MLACommonMetadata)
439
A = TypeVar("A", bound=AttentionMetadata)
440
441


442
def use_flashinfer_prefill() -> bool:
443
    # For blackwell default to flashinfer prefill if it's available since
444
    # it is faster than FA2.
445
446
447
    from vllm.config import get_current_vllm_config

    vllm_config = get_current_vllm_config()
448
    return (
449
        not vllm_config.attention_config.disable_flashinfer_prefill
450
        and flashinfer_available
451
452
        and not vllm_config.attention_config.use_cudnn_prefill
        and not vllm_config.attention_config.use_trtllm_ragged_deepseek_prefill
453
        and current_platform.is_device_capability_family(100)
454
    )
455
456


457
def use_cudnn_prefill() -> bool:
458
459
460
    from vllm.config import get_current_vllm_config

    vllm_config = get_current_vllm_config()
461
462
    return (
        flashinfer_available
463
        and vllm_config.attention_config.use_cudnn_prefill
464
        and current_platform.is_device_capability_family(100)
465
466
        and has_nvidia_artifactory()
    )
467
468


469
470
def use_trtllm_ragged_deepseek_prefill() -> bool:
    """Check if TRT-LLM ragged DeepSeek prefill should be used."""
471
472
473
    from vllm.config import get_current_vllm_config

    vllm_config = get_current_vllm_config()
474
475
    return (
        flashinfer_available
476
        and vllm_config.attention_config.use_trtllm_ragged_deepseek_prefill
477
        and current_platform.is_device_capability_family(100)
478
    )
479
480


481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
@dataclass
class MLADims:
    q_lora_rank: int | None
    kv_lora_rank: int
    qk_nope_head_dim: int
    qk_rope_head_dim: int
    v_head_dim: int


def get_mla_dims(model_config: ModelConfig) -> MLADims:
    hf_text_config = model_config.hf_text_config

    return MLADims(
        q_lora_rank=getattr(hf_text_config, "q_lora_rank", None),
        kv_lora_rank=hf_text_config.kv_lora_rank,
        qk_nope_head_dim=hf_text_config.qk_nope_head_dim,
        qk_rope_head_dim=hf_text_config.qk_rope_head_dim,
        v_head_dim=hf_text_config.v_head_dim,
    )


502
class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
503
504
505
506
    """
    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """
507

508
509
510
511
512
513
514
    # Defines the level of query length support for this backend.
    # - SINGLE_ONLY: Only single-token queries (no spec decode support)
    # - UNIFORM: Supports uniform multi-token queries (spec decode with uniform lengths)
    # - VARLEN: Supports variable-length queries (spec decode with mixed lengths)
    # If set to UNIFORM or VARLEN, this will increase `reorder_batch_threshold` when
    # speculative decoding is enabled.
    query_len_support: ClassVar[QueryLenSupport] = QueryLenSupport.SINGLE_ONLY
515
516
517
518

    # The threshold for reordering the batch into decode and prefill requests.
    # If > 1, the batch will be reordered such that requests with
    # query length <= threshold are classified as decode requests.
519
    # Use `query_len_support` (above) to set this automatically
520
    # when speculative decoding is enabled.
521
    reorder_batch_threshold: int = 1
522

523
    @staticmethod
524
    def determine_chunked_prefill_workspace_size(vllm_config: VllmConfig) -> int:
525
526
527
528
529
530
        scheduler_config = vllm_config.scheduler_config
        cache_config = vllm_config.cache_config
        model_config = vllm_config.model_config

        chunked_prefill_workspace_size = min(
            # Try for 8 full length request or at least 4 pages per-request
531
532
533
534
            max(
                8 * model_config.max_model_len,
                4 * scheduler_config.max_num_seqs * cache_config.block_size,
            ),
535
536
537
538
539
540
541
542
            # For long-context models try not to over-allocate limiting
            # kv-cache space, limiting it to 64k tokens,
            # which would result in the workspace being:
            #   2*(576)*(64*1024) = 144mb
            # (assuming 576 MLA head dim, and fp16)
            # which would result in up-projected context being
            #   2*(192*128)*(64*1024) = 3gb
            # (assuming 192 QK head dim, 128 heads, and fp16)
543
544
            64 * 1024,
        )
545
546
547
548

        # Enforce that we enough for at least 1 page per request
        chunked_prefill_workspace_size = max(
            chunked_prefill_workspace_size,
549
550
            scheduler_config.max_num_seqs * cache_config.block_size,
        )
551
552

        return chunked_prefill_workspace_size
553

554
555
556
557
558
559
    def __init__(
        self,
        kv_cache_spec: AttentionSpec,
        layer_names: list[str],
        vllm_config: VllmConfig,
        device: torch.device,
560
        metadata_cls: type[M] | None = None,
561
        supports_dcp_with_varlen: bool = False,
562
563
564
565
    ):
        self.metadata_cls = (
            metadata_cls if metadata_cls is not None else MLACommonMetadata
        )
566
567
568
569
        self.kv_cache_spec = kv_cache_spec
        scheduler_config = vllm_config.scheduler_config
        self.model_config = vllm_config.model_config
        parallel_config = vllm_config.parallel_config
570
        self.compilation_config = vllm_config.compilation_config
571
        self.vllm_config = vllm_config
572
573
        self.device = device

574
        self.num_heads = self.model_config.get_num_attention_heads(parallel_config)
575
        self.mla_dims = get_mla_dims(self.model_config)
576
        self.aot_schedule = current_platform.is_cuda()
577
578
579
580
581
582
583
        try:
            self.dcp_world_size = get_dcp_group().world_size
            self.dcp_rank = get_dcp_group().rank_in_group
        except AssertionError:
            # DCP might not be initialized in testing
            self.dcp_world_size = 1
            self.dcp_rank = 0
584
        self.dcp_local_block_size = parallel_config.cp_kv_cache_interleave_size
585
        self.dcp_virtual_block_size = self.dcp_local_block_size * self.dcp_world_size
586
        self.cp_kv_cache_interleave_size = parallel_config.cp_kv_cache_interleave_size
587

588
        # Don't try to access the runner on AMD
589
        if self.aot_schedule:
590
            self.page_size = self.kv_cache_spec.block_size
591

592
        self.chunked_prefill_workspace_size = (
593
            self.determine_chunked_prefill_workspace_size(vllm_config)
594
        )
595

596
597
598
599
600
        if self.dcp_world_size > 1:
            # Note(hc): The local kvcache is incomplete when DCP is triggered,
            # an additional kvcache allgather across the DCP group is therefore
            # required, so the workspace has to be enlarged by 1/DCP relative
            # to the original TP allocation.
601
            assert self.chunked_prefill_workspace_size % self.dcp_world_size == 0
602
            self.chunked_prefill_workspace = torch.empty(
603
604
605
606
607
                (
                    self.chunked_prefill_workspace_size
                    + self.chunked_prefill_workspace_size // self.dcp_world_size,
                    self.model_config.get_head_size(),
                ),
608
609
610
611
612
                dtype=self.model_config.dtype,
                device=device,
            )
        else:
            self.chunked_prefill_workspace = torch.empty(
613
614
615
616
                (
                    self.chunked_prefill_workspace_size,
                    self.model_config.get_head_size(),
                ),
617
618
619
                dtype=self.model_config.dtype,
                device=device,
            )
620
621

        self._use_cudnn_prefill = use_cudnn_prefill()
622
        self._use_fi_prefill = use_flashinfer_prefill()
623
        self._use_trtllm_ragged_prefill = use_trtllm_ragged_deepseek_prefill()
624
625
        self.prefill_metadata_cls = (
            FlashInferPrefillMetadata
626
627
628
629
630
            if self._use_fi_prefill
            else CudnnPrefillMetadata
            if self._use_cudnn_prefill
            else MLACommonPrefillMetadata
        )
631
632
633

        if self._use_fi_prefill:
            self._workspace_buffer = torch.empty(
634
                envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,
635
                dtype=torch.uint8,
636
                device=device,
637
            )
638

639
            self._fi_prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
640
            self._fi_prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = []
641
642

            self._global_hyperparameters = infer_global_hyperparameters(
643
                get_per_layer_parameters(vllm_config, layer_names, MLACommonImpl)  # type: ignore[type-abstract]
644
            )
645

646
647
        if self._use_trtllm_ragged_prefill:
            self._workspace_buffer = torch.empty(
648
649
650
                envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE,
                dtype=torch.uint8,
                device=device,
651
            )
652

653
654
655
656
        if self._use_cudnn_prefill:
            self.cudnn_workspace = torch.empty(
                CUDNN_WORKSPACE_SIZE * scheduler_config.max_num_seqs,
                dtype=torch.int8,
657
                device=device,
658
659
            )

660
        supports_spec_decode = self.query_len_support != QueryLenSupport.SINGLE_ONLY
661
        self._init_reorder_batch_threshold(
662
            self.reorder_batch_threshold, supports_spec_decode, supports_dcp_with_varlen
663
664
        )

665
666
667
668
669
670
671
        # Validate consistency between query_len_support and reorder_batch_threshold
        if self.query_len_support == QueryLenSupport.SINGLE_ONLY:
            assert self.reorder_batch_threshold == 1, (
                f"reorder_batch_threshold must be 1 when query_len_support is "
                f"SINGLE_ONLY, got {self.reorder_batch_threshold}"
            )

672
673
674
675
676
677
678
679
680
681
    def _build_fi_prefill_wrappers(self, prefill: FlashInferPrefillMetadata):
        qo_indptr = prefill.query_start_loc

        has_context = False
        if prefill.chunked_context is not None:
            chunked_context = prefill.chunked_context
            has_context = True

        if self._fi_prefill_main is None:
            self._fi_prefill_main = BatchPrefillWithRaggedKVCacheWrapper(
682
683
                self._workspace_buffer, "NHD", backend="cutlass"
            )
684
685
686
687
688
689
690
691

        if has_context:
            num_chunks = chunked_context.cu_seq_lens.shape[0]
            # Allocate more prefill chunk wrappers if needed
            if len(self._fi_prefill_chunks) < num_chunks:
                for _ in range(len(self._fi_prefill_chunks), num_chunks):
                    self._fi_prefill_chunks.append(
                        BatchPrefillWithRaggedKVCacheWrapper(
692
693
694
                            self._workspace_buffer, "NHD", backend="cutlass"
                        )
                    )
695
696
697
            assert num_chunks <= len(self._fi_prefill_chunks)

        # In MLA, the non-latent num_qo_heads == num_kv_heads
698
        num_qo_heads = self.num_heads
699
700
701
702
703
704
        num_kv_heads = num_qo_heads

        # Sanity: Verify that num_kv_heads == 1 since it is latent space
        assert self.kv_cache_spec.num_kv_heads == 1

        # Get non-latent head_dim_qk and head_dim_vo
705
        head_dim_qk = self.mla_dims.qk_nope_head_dim + self.mla_dims.qk_rope_head_dim
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
        head_dim_vo = self.mla_dims.v_head_dim

        # For main run, qo_indptr == kv_indptr
        kv_indptr = qo_indptr.clone()

        # Prepare main prefill
        self._fi_prefill_main.plan(
            qo_indptr=qo_indptr,
            kv_indptr=kv_indptr,
            num_qo_heads=num_qo_heads,
            num_kv_heads=num_kv_heads,
            head_dim_qk=head_dim_qk,
            head_dim_vo=head_dim_vo,
            causal=True,  # This is main run
            sm_scale=self._global_hyperparameters.sm_scale,
            window_left=self._global_hyperparameters.window_left,
            logits_soft_cap=self._global_hyperparameters.logits_soft_cap,
723
            q_data_type=self.model_config.dtype,
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
        )

        # Prepare context prefills
        if has_context:
            for i in range(num_chunks):
                kv_indptr_chunk = chunked_context.cu_seq_lens[i]

                self._fi_prefill_chunks[i].plan(
                    qo_indptr=qo_indptr,
                    kv_indptr=kv_indptr_chunk,
                    num_qo_heads=num_qo_heads,
                    num_kv_heads=num_kv_heads,
                    head_dim_qk=head_dim_qk,
                    head_dim_vo=head_dim_vo,
                    causal=False,  # This is context run
                    sm_scale=self._global_hyperparameters.sm_scale,
                    window_left=self._global_hyperparameters.window_left,
741
                    logits_soft_cap=self._global_hyperparameters.logits_soft_cap,
742
                    q_data_type=self.model_config.dtype,
743
744
745
746
                )

        prefill.prefill_main = self._fi_prefill_main
        prefill.prefill_chunks = self._fi_prefill_chunks
747

748
749
750
751
    def _build_decode(
        self,
        block_table_tensor: torch.Tensor,
        seq_lens_device: torch.Tensor,
752
        max_seq_len: int,
753
754
755
        query_start_loc_cpu: torch.Tensor,
        query_start_loc_device: torch.Tensor,
        num_decode_tokens: int,
756
        dcp_tot_seq_lens_device: torch.Tensor | None,
757
    ) -> MLACommonDecodeMetadata:
758
        return MLACommonDecodeMetadata(
759
            block_table=block_table_tensor,
760
            seq_lens=seq_lens_device,
761
            dcp_tot_seq_lens=dcp_tot_seq_lens_device,
762
763
        )

764
    def build_for_cudagraph_capture(
765
766
        self, common_attn_metadata: CommonAttentionMetadata
    ) -> M:
767
768
769
770
771
        """
        This method builds the metadata for full cudagraph capture.
        Currently, only decode is supported for full cudagraphs with MLA.
        """
        m = common_attn_metadata
772
773
        assert m.num_reqs <= (m.num_actual_tokens * self.reorder_batch_threshold), (
            "MLA only supports decode-only full CUDAGraph capture. "
王敏's avatar
王敏 committed
774
            "Make sure all cudagraph capture sizes <= max_num_seq."
775
        )
王敏's avatar
王敏 committed
776
777
778

        assert m.max_query_len <= self.reorder_batch_threshold  # decode only

779
780
        return self.build(0, m)

781
782
783
784
785
786
    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: CommonAttentionMetadata,
        fast_build: bool = False,
    ) -> M:
787
        num_reqs = common_attn_metadata.num_reqs
788
        num_tokens = common_attn_metadata.num_actual_tokens
789
        max_query_len = common_attn_metadata.max_query_len
790
        max_seq_len = common_attn_metadata.max_seq_len
791

Simon Mo's avatar
Simon Mo committed
792
793
794
        # Note(simon): be careful about the CPU <> GPU memory movement in this
        # function. We should avoid GPU -> CPU sync as much as possible because
        # it blocks on all previous kernels.
795
796
797
        device = self.device
        block_table_tensor = common_attn_metadata.block_table_tensor
        slot_mapping = common_attn_metadata.slot_mapping
798

799
        query_start_loc = common_attn_metadata.query_start_loc
800
        query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu
801
        seq_lens = common_attn_metadata.seq_lens
802
        dcp_local_seq_lens = common_attn_metadata.dcp_local_seq_lens
803

804
805
        num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
            split_decodes_and_prefills(
806
807
                common_attn_metadata,
                decode_threshold=self.reorder_batch_threshold,
808
                require_uniform=(self.query_len_support != QueryLenSupport.VARLEN),
809
810
            )
        )
811
812
813
814

        assert num_decodes + num_prefills == num_reqs
        assert num_decode_tokens + num_prefill_tokens == num_tokens

815
        prefill_metadata = None
816
        if num_prefills > 0:
817
818
819
            num_computed_tokens_cpu = (
                common_attn_metadata.compute_num_computed_tokens().cpu()
            )
820

821
            reqs_start = num_decodes  # prefill_start
822

823
            context_lens_cpu = num_computed_tokens_cpu[reqs_start:num_reqs]
Simon Mo's avatar
Simon Mo committed
824
825
            max_context_len_cpu = context_lens_cpu.max().item()
            num_prefills_with_context_cpu = (context_lens_cpu > 0).sum().item()
826
827
828
            prefill_query_start_loc = (
                query_start_loc[reqs_start:] - query_start_loc[reqs_start]
            )
829
830

            chunked_context_metadata = None
831
            if max_context_len_cpu > 0:
832
833
834
835
836
837
838
839
                # NOTE: it is recommend you read the `Chunked Prefill` section
                # in the comment at the top of the file before trying to
                # understand the following code

                # currently we allocate an equal amount of workspace for each
                # prefill in the batch, we could probably use a more advanced
                # algorithm here and allocate more workspace to prefills with
                # longer context lengths
840
841
842
                max_context_chunk = (
                    self.chunked_prefill_workspace_size // num_prefills_with_context_cpu
                )
843

844
845
                if self.aot_schedule:
                    # align max_context_chunk to page_size by rounding down,
846
847
848
                    # currently the `gather_and_maybe_dequant_cache` kernel
                    # cannot handle `context_chunk_starts` that are not aligned
                    # to page_size
849
                    max_context_chunk = round_down(max_context_chunk, self.page_size)
850
851

                assert max_context_chunk > 0
Simon Mo's avatar
Simon Mo committed
852
                num_chunks = cdiv(max_context_len_cpu, max_context_chunk)
853
854
855
856
857

                # if `max_context_chunk = 256`, `num_chunks = 3`, and
                #   `num_prefills_with_context = 4`, create a tensor that looks
                # like
                #  [[0, 0, 0, 0], [256, 256, 256, 256], [512, 512, 512, 512]]
Simon Mo's avatar
Simon Mo committed
858
859
                # Note(simon): this is done in CPU because of downstream's
                # of `to_list`.
860
861
862
863
                chunk_starts = (
                    torch.arange(num_chunks, dtype=torch.int32)
                    .unsqueeze(1)
                    .expand(-1, num_prefills)
864
                    * max_context_chunk
865
866
867
868
                )
                chunk_ends = torch.min(
                    context_lens_cpu.unsqueeze(0), chunk_starts + max_context_chunk
                )
869
                chunk_seq_lens = (chunk_ends - chunk_starts).clamp(min=0)
Simon Mo's avatar
Simon Mo committed
870

871
872
873
874
875
876
                cu_seq_lens_cpu = torch.zeros(
                    num_chunks, num_prefills + 1, dtype=torch.int32, pin_memory=True
                )
                torch.cumsum(
                    chunk_seq_lens, dim=1, out=cu_seq_lens_cpu[:, 1:], dtype=torch.int32
                )
877
878
879
880
881
882
883
884
885
886
887
888
889
                chunk_total_token = cu_seq_lens_cpu[:, -1]

                max_token_num_over_chunk = chunk_total_token.max().item()
                token_to_seq_tensor_cpu = torch.zeros(
                    [num_chunks, max_token_num_over_chunk], dtype=torch.int32
                )
                range_idx = torch.arange(num_prefills, dtype=torch.int32)
                for i in range(num_chunks):
                    chunk_token_to_seq_tensor = torch.repeat_interleave(
                        range_idx, chunk_seq_lens[i]
                    )
                    chunk_len = chunk_token_to_seq_tensor.shape[0]
                    token_to_seq_tensor_cpu[i, :chunk_len] = chunk_token_to_seq_tensor
890

891
                if self.dcp_world_size > 1:
892
893
894
895
896
897
898
899
                    local_context_lens_allranks = get_dcp_local_seq_lens(
                        context_lens_cpu,
                        self.dcp_world_size,
                        None,
                        self.dcp_local_block_size,
                    )
                    # Note(qcs): The max local context lengths
                    # padded to `dcp_local_block_size`.
900
                    padded_local_context_lens_cpu: torch.Tensor = (
901
902
903
904
905
906
                        cdiv(
                            context_lens_cpu,
                            self.dcp_virtual_block_size,
                        )
                        * self.dcp_local_block_size
                    )
907
908
909
910
911
912
                    # Note(hc): The above max_context_chunk already enforces
                    # block_size alignment, DCP just need the block_size can
                    # be divisible by dcp_world_size, because DCP use
                    # cp_gather_cache which not require `cp_chunk_starts`
                    # aligned to page_size.
                    assert max_context_chunk % self.dcp_world_size == 0
913
914
915
916
917
918
919
920
                    padded_local_max_context_chunk_across_ranks = (
                        cdiv(
                            max_context_chunk,
                            self.dcp_virtual_block_size,
                        )
                        * self.dcp_local_block_size
                    )
                    local_chunk_starts = (
921
922
923
                        torch.arange(num_chunks, dtype=torch.int32)
                        .unsqueeze(1)
                        .expand(-1, num_prefills)
924
                        * padded_local_max_context_chunk_across_ranks
925
                    )
926
927
928
929
                    local_chunk_ends = torch.min(
                        padded_local_context_lens_cpu.unsqueeze(0),
                        local_chunk_starts
                        + padded_local_max_context_chunk_across_ranks,
930
                    )
931
932
933
                    padded_local_chunk_seq_lens = (
                        local_chunk_ends - local_chunk_starts
                    ).clamp(min=0)
934

935
                    padded_local_cu_chunk_seq_lens_cpu = torch.zeros(
936
937
938
                        num_chunks, num_prefills + 1, dtype=torch.int32, pin_memory=True
                    )
                    torch.cumsum(
939
                        padded_local_chunk_seq_lens,
940
                        dim=1,
941
                        out=padded_local_cu_chunk_seq_lens_cpu[:, 1:],
942
943
944
945
946
947
948
949
                        dtype=torch.int32,
                    )

                chunked_context_metadata_cls = (
                    CudnnPrefillMetadata.ChunkedContextMetadata
                    if self._use_cudnn_prefill
                    else MLACommonPrefillMetadata.ChunkedContextMetadata
                )
950
                if self.dcp_world_size > 1:
951
952
                    chunked_context_metadata = chunked_context_metadata_cls(
                        cu_seq_lens=cu_seq_lens_cpu.to(device, non_blocking=True),
953
954
                        starts=local_chunk_starts.to(device, non_blocking=True),
                        seq_tot=padded_local_chunk_seq_lens.sum(dim=1).tolist(),
955
956
                        max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(),
                        seq_lens=chunk_seq_lens,
957
958
959
960
                        token_to_seq=token_to_seq_tensor_cpu.to(
                            device, non_blocking=True
                        ),
                        chunk_total_token=chunk_total_token.tolist(),
961
                        workspace=self.chunked_prefill_workspace,
962
963
964
965
966
                        padded_local_chunk_seq_lens=padded_local_chunk_seq_lens.tolist(),
                        local_context_lens_allranks=local_context_lens_allranks.tolist(),
                        padded_local_cu_seq_lens=padded_local_cu_chunk_seq_lens_cpu.to(
                            device, non_blocking=True
                        ),
967
                        cu_seq_lens_lst=cu_seq_lens_cpu.tolist(),
968
                        chunk_size=padded_local_max_context_chunk_across_ranks,
969
970
                    )
                else:
971
972
                    chunked_context_metadata = chunked_context_metadata_cls(
                        cu_seq_lens=cu_seq_lens_cpu.to(device, non_blocking=True),
973
974
975
976
                        starts=chunk_starts.to(device, non_blocking=True),
                        seq_tot=chunk_seq_lens.sum(dim=1).tolist(),
                        max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(),
                        seq_lens=chunk_seq_lens,
977
978
979
980
                        token_to_seq=token_to_seq_tensor_cpu.to(
                            device, non_blocking=True
                        ),
                        chunk_total_token=chunk_total_token,
981
982
                        workspace=self.chunked_prefill_workspace,
                    )
983

984
985
986
                if self._use_cudnn_prefill:
                    chunked_context_metadata.seq_lens = chunk_seq_lens

987
988
989
990
                assert (
                    max(chunked_context_metadata.max_seq_lens)
                    <= self.chunked_prefill_workspace_size
                )
991

992
            prefill_metadata = self.prefill_metadata_cls(
993
                block_table=block_table_tensor[reqs_start:, ...],
994
                query_start_loc=prefill_query_start_loc,
Simon Mo's avatar
Simon Mo committed
995
                max_query_len=max_query_len,
996
997
998
                chunked_context=chunked_context_metadata,
            )

999
1000
            if self._use_cudnn_prefill:
                assert isinstance(prefill_metadata, CudnnPrefillMetadata)
1001
1002
1003
                prefill_metadata.query_seq_lens = (
                    prefill_query_start_loc[1:] - prefill_query_start_loc[:-1]
                )
1004
1005
                prefill_metadata.cudnn_workspace = self.cudnn_workspace

1006
1007
1008
1009
            if self._use_trtllm_ragged_prefill:
                prefill_metadata.query_seq_lens = (
                    prefill_query_start_loc[1:] - prefill_query_start_loc[:-1]
                )
1010
                prefill_metadata.workspace_buffer = self._workspace_buffer
1011

zhuwenwen's avatar
zhuwenwen committed
1012
        decode_metadata = None
王敏's avatar
王敏 committed
1013
        if num_decodes > 0:
1014
1015
1016
1017
1018
            dcp_tot_seq_lens_device = None
            if self.dcp_world_size > 1:
                dcp_tot_seq_lens_device = seq_lens[:num_decodes]
                seq_lens = dcp_local_seq_lens

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
                # After DCP distribution, the maximum number of tokens for any rank is
                # ceil(L / (N * I)) * I, where L is max_seq_len, N is dcp_world_size,
                # and I is cp_kv_cache_interleave_size.
                # This eliminates GPU->CPU sync while minimizing workspace
                # over-allocation.
                num_partitions = self.dcp_world_size * self.cp_kv_cache_interleave_size
                max_seq_len = (
                    (max_seq_len + num_partitions - 1) // num_partitions
                ) * self.cp_kv_cache_interleave_size

王敏's avatar
王敏 committed
1029
1030
1031
            decode_metadata = self._build_decode(
                block_table_tensor=block_table_tensor[:num_decodes, ...],
                seq_lens_device=seq_lens[:num_decodes],
1032
                max_seq_len=max_seq_len,
1033
1034
                query_start_loc_cpu=query_start_loc_cpu[: num_decodes + 1],
                query_start_loc_device=query_start_loc[: num_decodes + 1],
王敏's avatar
王敏 committed
1035
                num_decode_tokens=num_decode_tokens,
1036
                dcp_tot_seq_lens_device=dcp_tot_seq_lens_device,
王敏's avatar
王敏 committed
1037
            )
1038

1039
        attn_metadata = self.metadata_cls(
1040
1041
            num_reqs=common_attn_metadata.num_reqs,
            max_query_len=common_attn_metadata.max_query_len,
1042
            max_seq_len=max_seq_len,
1043
            num_actual_tokens=num_tokens,
1044
1045
            query_start_loc=query_start_loc,
            slot_mapping=slot_mapping,
1046
            head_dim=self.model_config.get_head_size(),
1047
            # MLACommonMetadata Chunk prefill specific
1048
1049
1050
            num_decodes=num_decodes,
            num_decode_tokens=num_decode_tokens,
            num_prefills=num_prefills,
1051
1052
            prefill=prefill_metadata,
            decode=decode_metadata,
1053
1054
        )

1055
        if self._use_fi_prefill and num_prefills > 0:
1056
1057
1058
1059
1060
            assert isinstance(attn_metadata.prefill, FlashInferPrefillMetadata)
            self._build_fi_prefill_wrappers(attn_metadata.prefill)

        return attn_metadata

1061

1062
1063
1064
def reorg_kvcache(
    allgatered_kv_c_normed: torch.Tensor,
    allgatered_k_pe: torch.Tensor,
1065
1066
    padded_local_chunk_seq_lens_lst: list[int],
    local_context_lens_allranks: list[list[int]],
1067
1068
1069
1070
1071
1072
1073
    sum_seq_len: int,
    max_seq_len: int,
    chunk_size: int,
    chunk_idx: int,
    toks: int,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
1074
1075
1076
1077
1078
1079
    reorg and unpad kvcache after cp local gather to tp layout for attn kernel.
    e.g.
    allgatered_kv_c_normed = [T0_0, T0_1, T0_2, T0_3, T1_0, T1_1, ...,
                              T0_4, T0_5, pad, pad, T1_2, pad, ...]
    -> reorganized_kv_c_normed = [T0_0, T0_1, T0_2, T0_3, T0_4, T0_5,
                                  T1_0, T1_1, T1_2, ...]
1080
    Args:
1081
1082
1083
        padded_local_chunk_seq_lens_lst: local chunk context lengths
            under current CP rank.
        local_context_lens_allranks: local context lengths on each CP rank.
1084
1085
        sum_seq_len: the sum of cp_chunk_seq_lens_lst.
        max_seq_len: the max value of cp_chunk_seq_lens_lst.
1086
        chunk_size: the local padded max context chunk from
1087
1088
1089
1090
1091
1092
1093
1094
            chunked_context_metadata building.
        chunk_idx: chunk idx of chunked_prefill.
        toks: the number of tokens for local gather cache.
    """
    kv_c_segments = []
    k_pe_segments = []
    src_token_idx = 0
    max_seq_len_check = 0
1095
1096
    for padded_local_chunk_seq_len, local_context_lens in zip(
        padded_local_chunk_seq_lens_lst, local_context_lens_allranks
1097
    ):
1098
        cur_seq_len = 0
1099
        for rank, local_context_len in enumerate(local_context_lens):
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
            # Note(qcs): We split the context into multiple chunks,
            # depending on the size of the workspace.
            # local_context in dcp0:   |-----------------|
            # local_context in dcp1:   |--------------|
            # n*padded_local_chunk:    |-----|-----|-----|
            # local_chunk_len in dcp1: |-----|-----|--|
            # so we need update the last chunk length in dcp1.
            local_chunk_len = min(
                max(0, local_context_len - chunk_idx * chunk_size),
                padded_local_chunk_seq_len,
            )
            if local_chunk_len != 0:
1112
1113
1114
                kv_c_segment = allgatered_kv_c_normed[
                    rank * toks + src_token_idx : rank * toks
                    + src_token_idx
1115
                    + local_chunk_len
1116
1117
1118
1119
                ]
                k_pe_segment = allgatered_k_pe[
                    rank * toks + src_token_idx : rank * toks
                    + src_token_idx
1120
                    + local_chunk_len
1121
                ]
1122
1123
                kv_c_segments.append(kv_c_segment)
                k_pe_segments.append(k_pe_segment)
1124
                cur_seq_len += local_chunk_len
1125
        max_seq_len_check = max(max_seq_len_check, cur_seq_len)
1126
        src_token_idx += padded_local_chunk_seq_len
1127
1128
1129
1130
1131
1132
1133
1134
    reorganized_kv_c_normed = torch.cat(kv_c_segments, dim=0)
    reorganized_k_pe = torch.cat(k_pe_segments, dim=0)
    assert reorganized_kv_c_normed.shape[0] == sum_seq_len
    assert reorganized_k_pe.shape[0] == sum_seq_len
    assert max_seq_len_check == max_seq_len
    return reorganized_kv_c_normed, reorganized_k_pe


1135
1136
1137
# TODO(Lucas): rename MLACommonBaseImpl -> MLACommonImpl,
# and MLACommonImpl -> MLACommonDenseImpl or somthing like that
class MLACommonBaseImpl(MLAAttentionImpl[A], Generic[A]):
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
    """
    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """

    def __init__(
        self,
        num_heads: int,
        head_size: int,
        scale: float,
        num_kv_heads: int,
1149
1150
        alibi_slopes: list[float] | None,
        sliding_window: int | None,
1151
        kv_cache_dtype: str,
1152
        logits_soft_cap: float | None,
1153
        attn_type: str,
1154
        kv_sharing_target_layer_name: str | None,
1155
        # MLA Specific Arguments
1156
        q_lora_rank: int | None,
1157
1158
1159
1160
1161
1162
        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,
1163
        indexer=None,
1164
        q_pad_num_heads: int | None = None,
1165
    ) -> None:
1166
1167
1168
        if kv_sharing_target_layer_name is not None:
            raise NotImplementedError("KV sharing is not supported for MLA")

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
        self.num_heads = num_heads
        self.head_size = head_size
        self.scale = float(scale)
        self.num_kv_heads = num_kv_heads
        self.kv_cache_dtype = kv_cache_dtype

        self.q_lora_rank = q_lora_rank
        self.kv_lora_rank = kv_lora_rank
        self.qk_nope_head_dim = qk_nope_head_dim
        self.qk_rope_head_dim = qk_rope_head_dim
        self.qk_head_dim = qk_head_dim
        self.v_head_dim = v_head_dim
        self.kv_b_proj = kv_b_proj
1182
        self.indexer = indexer
1183
        self.q_pad_num_heads = q_pad_num_heads
1184
        self.is_aiter_triton_fp8_bmm_enabled = rocm_aiter_ops.is_fp8bmm_enabled()
zhuwenwen's avatar
zhuwenwen committed
1185
        self.use_llama_nn = os.environ.get('LLAMA_NN') == '1'
1186

1187
1188
1189
1190
1191
1192
1193
    def process_weights_after_loading(self, act_dtype: torch.dtype):
        def get_layer_weight(layer):
            WEIGHT_NAMES = ("weight", "qweight", "weight_packed")
            for attr in WEIGHT_NAMES:
                if hasattr(layer, attr):
                    return getattr(layer, attr)
            raise AttributeError(
1194
1195
                f"Layer '{layer}' has no recognized weight attribute: {WEIGHT_NAMES}."
            )
1196
1197

        def get_and_maybe_dequant_weights(layer: LinearBase):
1198
1199
1200
            if layer.quant_method is not None and not isinstance(
                layer.quant_method, UnquantizedLinearMethod
            ):
1201
                # NOTE: This should only be used offline, since it's O(N^3)
1202
1203
1204
1205
1206
1207
                eye = torch.eye(
                    layer.input_size_per_partition,
                    dtype=act_dtype,
                    device=get_layer_weight(layer).device,
                )
                dequant_weights = layer.quant_method.apply(layer, eye, bias=None)
1208
1209
1210
                del eye
                # standardize to (output, input)
                return dequant_weights.T
1211
            return layer.weight if not envs.VLLM_USE_NN else layer.weight.T
1212
1213
1214
1215

        # we currently do not have quantized bmm's which are needed for
        # `W_UV` and `W_UK_T`, we just store fp16/bf16 copies and perform
        # the bmm's in 16-bit, the extra memory overhead of this is fairly low
1216
1217
1218
1219
        if self.use_llama_nn and isinstance(self.kv_b_proj.quant_method, UnquantizedLinearMethod):
            kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj)
        else:
            kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj).T
1220
1221
        assert kv_b_proj_weight.shape == (
            self.kv_lora_rank,
1222
1223
1224
1225
1226
1227
1228
1229
            self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
        ), (
            f"{kv_b_proj_weight.shape=}, "
            f"{self.kv_lora_rank=}, "
            f"{self.num_heads=}, "
            f"{self.qk_nope_head_dim=}, "
            f"{self.v_head_dim=}"
        )
1230
1231
1232
1233
1234
1235
1236
        kv_b_proj_weight = kv_b_proj_weight.view(
            self.kv_lora_rank,
            self.num_heads,
            self.qk_nope_head_dim + self.v_head_dim,
        )

        W_UK, W_UV = kv_b_proj_weight.split(
1237
1238
            [self.qk_nope_head_dim, self.v_head_dim], dim=-1
        )
1239

1240
        if self.is_aiter_triton_fp8_bmm_enabled:
1241
1242
1243
            W_K = W_UK.transpose(0, 1)  # 16 512 128
            W_V = W_UV.permute(1, 2, 0)  # 16 128 512
            self.W_K, self.W_K_scale = dynamic_per_batched_tensor_quant(
1244
1245
                W_K, dtype=current_platform.fp8_dtype()
            )
1246
            self.W_V, self.W_V_scale = dynamic_per_batched_tensor_quant(
1247
1248
                W_V, dtype=current_platform.fp8_dtype()
            )
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263

            # The kernel operates on non-padded inputs. Hence, pre-compiling
            # triton kernel to avoid runtime compilation for unseen batch sizes
            # Pre-compile for batch sizes 1 to 1024 to cover most use-cases.
            # On DS-R1, this step adds roughly 50s to the model loading time.
            max_batch_size = 1024  # [ToDo] Find the optimal upper limit
            pre_compilation_list = list(range(1, max_batch_size + 1))
            if is_global_first_rank():
                pre_compilation_list = tqdm(
                    pre_compilation_list,
                    desc="[Aiter Triton] Pre-compiling fp8 BMM kernel",
                    total=max_batch_size,
                )

            for m in pre_compilation_list:
1264
1265
1266
1267
1268
                x = torch.empty(
                    (self.W_K.shape[0], m, self.W_K.shape[2]),
                    dtype=torch.bfloat16,
                    device=self.W_K.device,
                )
1269
                rocm_aiter_ops.triton_fp8_bmm(
1270
1271
1272
1273
1274
1275
1276
1277
                    x, self.W_K, self.W_K_scale, group_size=128, transpose_bm=True
                )

                x = torch.empty(
                    (self.W_V.shape[0], m, self.W_V.shape[2]),
                    dtype=torch.bfloat16,
                    device=self.W_V.device,
                )
1278
                rocm_aiter_ops.triton_fp8_bmm(
1279
1280
                    x, self.W_V, self.W_V_scale, group_size=128, transpose_bm=True
                )
1281
1282
1283
1284
1285
1286
1287
1288
1289
        else:
            # Convert from (L, N, V) to (N, L, V)
            self.W_UV = W_UV.transpose(0, 1)
            # Convert from (L, N, P) to (N, P, L)
            self.W_UK_T = W_UK.permute(1, 2, 0)

    def _v_up_proj(self, x: torch.Tensor, out: torch.Tensor):
        # Convert from (B, N, L) to (N, B, L)
        x = x.view(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1)
1290

1291
        if self.is_aiter_triton_fp8_bmm_enabled:
1292
            out = out.view(-1, self.num_heads, self.v_head_dim)
1293
            # Multiply + Transpose (N, B, L) x (N, L, V)->(N, B, V)->(B, N, V)
1294
            x = rocm_aiter_ops.triton_fp8_bmm(
1295
                x, self.W_V, self.W_V_scale, group_size=128, transpose_bm=True, YQ=out
1296
            )
1297
1298
1299
1300
1301
1302
1303
1304
        else:
            # Convert from (B, N * V) to (N, B, V)
            out = out.view(-1, self.num_heads, self.v_head_dim).transpose(0, 1)

            # Multiply (N, B, L) x (N, L, V) -> (N, B, V)
            torch.bmm(x, self.W_UV, out=out)  # Reuse "out" to make it "hot"

            # Convert from (N, B, V) to (B, N * V)
1305
            out_new = out.transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321

            # Adjust output buffer shape back to the original (B, N * V)
            N, B, V = out.shape
            out.resize_((B, N * V))
            out.copy_(out_new)  # Copy result


class MLACommonImpl(MLACommonBaseImpl[M], Generic[M]):
    """
    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

1322
1323
1324
1325
1326
        if use_flashinfer_prefill():
            logger.debug_once("Using FlashInfer prefill for MLA")
            self._run_prefill_context_chunk = self._run_prefill_context_chunk_fi
            self._run_prefill_new_tokens = self._run_prefill_new_tokens_fi
            self._pad_v = False
1327
1328
1329
1330
1331
1332
1333
        elif use_trtllm_ragged_deepseek_prefill():
            logger.debug_once("Using TRT-LLM ragged DeepSeek prefill for MLA")
            self._run_prefill_context_chunk = (
                self._run_prefill_context_chunk_trtllm_ragged
            )
            self._run_prefill_new_tokens = self._run_prefill_new_tokens_trtllm_ragged
            self._pad_v = False
1334
1335
        elif use_cudnn_prefill():
            logger.debug_once("Using CUDNN prefill for MLA")
1336
            self._run_prefill_context_chunk = self._run_prefill_context_chunk_cudnn
1337
1338
            self._run_prefill_new_tokens = self._run_prefill_new_tokens_cudnn
            self._pad_v = False
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
        else:  # Use FlashAttention
            logger.debug_once("Using FlashAttention prefill for MLA")
            self._run_prefill_context_chunk = self._run_prefill_context_chunk_fa
            self._run_prefill_new_tokens = self._run_prefill_new_tokens_fa

            # Handle the differences between the flash_attn_varlen from
            # flash_attn and the one from vllm_flash_attn. The former is used on
            # RoCM and the latter has an additional parameter to control
            # FA2 vs FA3
            self.flash_attn_varlen_func = flash_attn_varlen_func
            self.vllm_flash_attn_version = get_flash_attn_version()
            if self.vllm_flash_attn_version is not None:
1351
                self.flash_attn_varlen_func = functools.partial(
1352
                    flash_attn_varlen_func#, fa_version=self.vllm_flash_attn_version
1353
                )
1354
1355
1356
1357
1358

            # For MLA the v head dim is smaller than qk head dim so we pad out
            # v with 0s to match the qk head dim for attention backends that do
            # not support different headdims
            # We don't need to pad V if we are on a hopper system with FA3
1359
            device_capability = current_platform.get_device_capability()
zhuwenwen's avatar
zhuwenwen committed
1360
1361
1362
            if not current_platform.is_rocm():
                self._pad_v = self.vllm_flash_attn_version is None or not (
                    self.vllm_flash_attn_version == 3
1363
1364
                    and device_capability is not None
                    and device_capability[0] == 9
1365
                )
zhuwenwen's avatar
zhuwenwen committed
1366
1367
            else:
                self._pad_v = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count == 120
1368

1369
        self.dcp_world_size: int = -1
1370

1371
        self.chunked_prefill_workspace_size = (
1372
            MLACommonMetadataBuilder.determine_chunked_prefill_workspace_size(
1373
1374
1375
                get_current_vllm_config()
            )
        )
1376
1377
        self.cp_kv_cache_interleave_size: int = (
            get_current_vllm_config().parallel_config.cp_kv_cache_interleave_size
1378
        )
1379
1380
1381
1382

    def _flash_attn_varlen_diff_headdims(
        self, q, k, v, return_softmax_lse=False, softmax_scale=None, **kwargs
    ):
1383
1384
        maybe_padded_v = v
        if self._pad_v:
zhuwenwen's avatar
zhuwenwen committed
1385
1386
            # maybe_padded_v = torch.nn.functional.pad(
            #     v, [0, q.shape[-1] - v.shape[-1]], value=0)
1387
1388
1389
1390
1391
1392
            if not current_platform.is_rocm():
                maybe_padded_v = torch.nn.functional.pad(
                    v, [0, q.shape[-1] - v.shape[-1]], value=0
                )
            else:
                maybe_padded_v = torch.nn.functional.pad(
zhuwenwen's avatar
zhuwenwen committed
1393
                    v, [0, q.shape[-1] - v.shape[-1]- 32], value=0)
1394
                maybe_padded_v = maybe_padded_v[..., :-32].reshape(v.shape[0], v.shape[1],v.shape[2])
1395
1396
1397
1398
1399
1400
        if is_vllm_fa:
            kwargs["return_softmax_lse"] = return_softmax_lse
        else:
            # ROCm leverages the upstream flash_attn, which takes a parameter
            # called "return_attn_probs" instead of return_softmax_lse
            kwargs["return_attn_probs"] = return_softmax_lse
1401
        if vllm_is_batch_invariant():
1402
            kwargs["num_splits"] = 1
1403

1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
        attn_out = self.flash_attn_varlen_func(
            q=q,
            k=k,
            v=maybe_padded_v,
            softmax_scale=softmax_scale,
            **kwargs,
        )

        # Unpack the output if there is multiple results
        lse = None
        if isinstance(attn_out, tuple):
            attn_out, lse = attn_out[0], attn_out[1]

        # Remain consistent with old `flash_attn_varlen_func` where there
        # is only one output tensor if `return_softmax_lse` is False.
        if return_softmax_lse:
            return attn_out, lse
        return attn_out

1423
1424
1425
    def _run_prefill_new_tokens_fa(
        self, prefill: MLACommonPrefillMetadata, q, k, v, return_softmax_lse
    ):
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
        return self._flash_attn_varlen_diff_headdims(
            q=q,
            k=k,
            v=v,
            cu_seqlens_q=prefill.query_start_loc,
            cu_seqlens_k=prefill.query_start_loc,
            max_seqlen_q=prefill.max_query_len,
            max_seqlen_k=prefill.max_query_len,
            softmax_scale=self.scale,
            causal=True,
            return_softmax_lse=return_softmax_lse,
        )

1439
1440
1441
    def _run_prefill_new_tokens_fi(
        self, prefill: MLACommonPrefillMetadata, q, k, v, return_softmax_lse
    ):
1442
1443
        assert isinstance(prefill, FlashInferPrefillMetadata)
        assert prefill.prefill_main is not None
1444

1445
        ret = prefill.prefill_main.run(
1446
1447
1448
1449
1450
1451
            q=q,
            k=k,
            v=v,
            return_lse=return_softmax_lse,
        )

1452
1453
1454
1455
        if isinstance(ret, tuple):
            return ret[0], ret[1].transpose(0, 1).contiguous()
        return ret

1456
1457
1458
    def _run_prefill_new_tokens_cudnn(
        self, prefill: MLACommonPrefillMetadata, q, k, v, return_softmax_lse
    ):
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
        assert isinstance(prefill, CudnnPrefillMetadata)
        assert prefill.query_seq_lens is not None
        output, lse = cudnn_batch_prefill_with_kv_cache(
            q=q,
            k_cache=k,
            v_cache=v,
            scale=self.scale,
            workspace_buffer=prefill.cudnn_workspace,
            max_token_per_sequence=prefill.max_query_len,
            max_sequence_kv=prefill.max_query_len,
            actual_seq_lens_q=prefill.query_seq_lens.view(-1, 1, 1, 1),
            actual_seq_lens_kv=prefill.query_seq_lens.view(-1, 1, 1, 1),
            causal=True,
1472
1473
1474
1475
            # Do not support False for now
            return_lse=True,
            # Indicates actual_seq_lens are on GPU or CPU.
            is_cuda_graph_compatible=True,
1476
1477
1478
1479
1480
        )
        if return_softmax_lse:
            return output, lse
        return output

1481
1482
1483
    def _run_prefill_context_chunk_fa(
        self, prefill: MLACommonPrefillMetadata, chunk_idx: int, q, k, v
    ):
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
        assert prefill.chunked_context is not None
        return self._flash_attn_varlen_diff_headdims(
            q=q,
            k=k,
            v=v,
            cu_seqlens_q=prefill.query_start_loc,
            cu_seqlens_k=prefill.chunked_context.cu_seq_lens[chunk_idx],
            max_seqlen_q=prefill.max_query_len,
            max_seqlen_k=prefill.chunked_context.max_seq_lens[chunk_idx],
            softmax_scale=self.scale,
            causal=False,  # Context is unmasked
            return_softmax_lse=True,
        )

1498
1499
1500
    def _run_prefill_context_chunk_fi(
        self, prefill: MLACommonPrefillMetadata, chunk_idx: int, q, k, v
    ):
1501
        assert isinstance(prefill, FlashInferPrefillMetadata)
1502

1503
        attn_out, lse = prefill.prefill_chunks[chunk_idx].run(
1504
1505
1506
1507
1508
1509
            q=q,
            k=k,
            v=v,
            return_lse=True,
        )

1510
1511
        # Convert from (q_len, num_heads) to (num_heads, q_len)
        return attn_out, lse.transpose(0, 1).contiguous()
1512

1513
1514
1515
    def _run_prefill_context_chunk_cudnn(
        self, prefill: MLACommonPrefillMetadata, chunk_idx: int, q, k, v
    ):
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
        assert isinstance(prefill, CudnnPrefillMetadata)
        assert prefill.chunked_context is not None
        assert prefill.chunked_context.seq_lens[chunk_idx] is not None
        assert prefill.query_seq_lens is not None
        return cudnn_batch_prefill_with_kv_cache(
            q=q,
            k_cache=k,
            v_cache=v,
            scale=self.scale,
            workspace_buffer=prefill.cudnn_workspace,
            max_token_per_sequence=prefill.max_query_len,
            max_sequence_kv=prefill.chunked_context.max_seq_lens[chunk_idx],
            actual_seq_lens_q=prefill.query_seq_lens.view(-1, 1, 1, 1),
1529
1530
1531
            actual_seq_lens_kv=prefill.chunked_context.seq_lens[chunk_idx].view(
                -1, 1, 1, 1
            ),
1532
1533
            causal=False,
            return_lse=True,
1534
1535
            # Indicates actual_seq_lens are on GPU or CPU.
            is_cuda_graph_compatible=True,
1536
1537
        )

1538
1539
1540
1541
1542
1543
1544
    def _run_prefill_new_tokens_trtllm_ragged(
        self, prefill: MLACommonPrefillMetadata, q, k, v, return_softmax_lse
    ):
        """TRT-LLM ragged attention for new tokens (causal)."""
        from flashinfer.prefill import trtllm_ragged_attention_deepseek

        assert prefill.query_seq_lens is not None
1545
        assert prefill.workspace_buffer is not None
1546
1547
1548
1549
1550

        ret = trtllm_ragged_attention_deepseek(
            query=q,
            key=k,
            value=v,
1551
            workspace_buffer=prefill.workspace_buffer,
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
            seq_lens=prefill.query_seq_lens,
            max_q_len=prefill.max_query_len,
            max_kv_len=prefill.max_query_len,
            bmm1_scale=self.scale,
            bmm2_scale=1.0,
            o_sf_scale=1.0,
            batch_size=prefill.query_seq_lens.shape[0],
            window_left=-1,
            cum_seq_lens_q=prefill.query_start_loc,
            cum_seq_lens_kv=prefill.query_start_loc,
            enable_pdl=False,
            is_causal=True,
            return_lse=return_softmax_lse,
        )

        if isinstance(ret, tuple):
            # Convert from (q_len, num_heads) to (num_heads, q_len)
            return ret[0], ret[1].transpose(0, 1).contiguous()
        return ret

    def _run_prefill_context_chunk_trtllm_ragged(
        self, prefill: MLACommonPrefillMetadata, chunk_idx: int, q, k, v
    ):
        """TRT-LLM ragged attention for context chunks (non-causal)."""
        from flashinfer.prefill import trtllm_ragged_attention_deepseek

        assert prefill.chunked_context is not None
        assert prefill.chunked_context.seq_lens[chunk_idx] is not None
1580
        assert prefill.workspace_buffer is not None
1581
1582
1583
1584
1585
1586
1587
1588

        out = torch.zeros(
            q.shape[0],
            q.shape[1],
            v.shape[2],
            device=q.device,
            dtype=q.dtype,
        )
1589
        prefill.workspace_buffer.fill_(0)
1590
1591
1592
1593
1594

        attn_out, lse = trtllm_ragged_attention_deepseek(
            query=q,
            key=k,
            value=v,
1595
            workspace_buffer=prefill.workspace_buffer,
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
            seq_lens=prefill.chunked_context.seq_lens[chunk_idx],
            max_q_len=prefill.max_query_len,
            max_kv_len=prefill.chunked_context.max_seq_lens[chunk_idx],
            bmm1_scale=self.scale,
            bmm2_scale=1.0,
            o_sf_scale=1.0,
            batch_size=prefill.chunked_context.seq_lens[chunk_idx].shape[0],
            window_left=-1,
            cum_seq_lens_q=prefill.query_start_loc,
            cum_seq_lens_kv=prefill.chunked_context.cu_seq_lens[chunk_idx],
            enable_pdl=False,
            is_causal=False,
            return_lse=True,
            out=out,
        )

        # Convert from (q_len, num_heads) to (num_heads, q_len)
        return attn_out, lse.transpose(0, 1).contiguous()
1614

1615
    def process_weights_after_loading(self, act_dtype: torch.dtype):
1616
        def get_layer_weight(layer):
1617
1618
1619
1620
1621
            WEIGHT_NAMES = ("weight", "qweight", "weight_packed")
            for attr in WEIGHT_NAMES:
                if hasattr(layer, attr):
                    return getattr(layer, attr)
            raise AttributeError(
1622
1623
                f"Layer '{layer}' has no recognized weight attribute: {WEIGHT_NAMES}."
            )
1624
1625

        def get_and_maybe_dequant_weights(layer: LinearBase):
1626
1627
1628
            if layer.quant_method is not None and not isinstance(
                layer.quant_method, UnquantizedLinearMethod
            ):
1629
                # NOTE: This should only be used offline, since it's O(N^3)
1630
1631
1632
1633
1634
1635
                eye = torch.eye(
                    layer.input_size_per_partition,
                    dtype=act_dtype,
                    device=get_layer_weight(layer).device,
                )
                dequant_weights = layer.quant_method.apply(layer, eye, bias=None)
1636
1637
1638
                del eye
                # standardize to (output, input)
                return dequant_weights.T
1639
            return layer.weight if not envs.VLLM_USE_NN else layer.weight.T
1640

1641
        # we currently do not have quantized bmm's which are needed for
1642
        # `W_UV` and `W_UK_T`, we just store fp16/bf16 copies and perform
1643
        # the bmm's in 16-bit, the extra memory overhead of this is fairly low
zhuwenwen's avatar
zhuwenwen committed
1644
1645
1646
1647
        if self.use_llama_nn and isinstance(self.kv_b_proj.quant_method, UnquantizedLinearMethod):
            kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj)
        else:
            kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj).T
1648
1649
        assert kv_b_proj_weight.shape == (
            self.kv_lora_rank,
1650
1651
1652
1653
1654
1655
1656
1657
            self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
        ), (
            f"{kv_b_proj_weight.shape=}, "
            f"{self.kv_lora_rank=}, "
            f"{self.num_heads=}, "
            f"{self.qk_nope_head_dim=}, "
            f"{self.v_head_dim=}"
        )
1658
1659
1660
1661
1662
1663
1664
        kv_b_proj_weight = kv_b_proj_weight.view(
            self.kv_lora_rank,
            self.num_heads,
            self.qk_nope_head_dim + self.v_head_dim,
        )

        W_UK, W_UV = kv_b_proj_weight.split(
1665
1666
            [self.qk_nope_head_dim, self.v_head_dim], dim=-1
        )
1667

1668
        if self.is_aiter_triton_fp8_bmm_enabled:
1669
1670
1671
            W_K = W_UK.transpose(0, 1)  # 16 512 128
            W_V = W_UV.permute(1, 2, 0)  # 16 128 512
            self.W_K, self.W_K_scale = dynamic_per_batched_tensor_quant(
1672
1673
                W_K, dtype=current_platform.fp8_dtype()
            )
1674
            self.W_V, self.W_V_scale = dynamic_per_batched_tensor_quant(
1675
1676
                W_V, dtype=current_platform.fp8_dtype()
            )
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691

            # The kernel operates on non-padded inputs. Hence, pre-compiling
            # triton kernel to avoid runtime compilation for unseen batch sizes
            # Pre-compile for batch sizes 1 to 1024 to cover most use-cases.
            # On DS-R1, this step adds roughly 50s to the model loading time.
            max_batch_size = 1024  # [ToDo] Find the optimal upper limit
            pre_compilation_list = list(range(1, max_batch_size + 1))
            if is_global_first_rank():
                pre_compilation_list = tqdm(
                    pre_compilation_list,
                    desc="[Aiter Triton] Pre-compiling fp8 BMM kernel",
                    total=max_batch_size,
                )

            for m in pre_compilation_list:
1692
1693
1694
1695
1696
                x = torch.empty(
                    (self.W_K.shape[0], m, self.W_K.shape[2]),
                    dtype=torch.bfloat16,
                    device=self.W_K.device,
                )
1697
                rocm_aiter_ops.triton_fp8_bmm(
1698
1699
1700
1701
1702
1703
1704
1705
                    x, self.W_K, self.W_K_scale, group_size=128, transpose_bm=True
                )

                x = torch.empty(
                    (self.W_V.shape[0], m, self.W_V.shape[2]),
                    dtype=torch.bfloat16,
                    device=self.W_V.device,
                )
1706
                rocm_aiter_ops.triton_fp8_bmm(
1707
1708
                    x, self.W_V, self.W_V_scale, group_size=128, transpose_bm=True
                )
1709
1710
1711
1712
1713
        else:
            # Convert from (L, N, V) to (N, L, V)
            self.W_UV = W_UV.transpose(0, 1)
            # Convert from (L, N, P) to (N, P, L)
            self.W_UK_T = W_UK.permute(1, 2, 0)
1714

1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
    def _concat_k_nope_k_pe(
        self, k_nope: torch.Tensor, k_pe: torch.Tensor
    ) -> torch.Tensor:
        """
        Efficiently concatenate k_nope and k_pe tensors along the last dimension.

        This function avoids the performance penalty of torch.cat with expanded
        non-contiguous tensors by pre-allocating the output and using direct copies.

        Args:
            k_nope: Tensor of shape [..., nope_dim]
            k_pe: Tensor to broadcast and concatenate, typically shape [..., 1, pe_dim]
                or [..., pe_dim]

        Returns:
            Tensor of shape [..., nope_dim + pe_dim]
        """
        k = torch.empty(
            (*k_nope.shape[:-1], k_nope.shape[-1] + k_pe.shape[-1]),
            dtype=k_nope.dtype,
            device=k_nope.device,
        )
        # Direct copies with efficient broadcasting
        k[..., : k_nope.shape[-1]] = k_nope
        k[..., k_nope.shape[-1] :] = k_pe
        return k

1742
1743
1744
1745
1746
    def _compute_prefill_context(
        self,
        q: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: MLACommonMetadata,
1747
        k_scale: torch.Tensor,
1748
    ):
1749
1750
1751
        assert attn_metadata.prefill is not None
        prefill_metadata = attn_metadata.prefill
        assert prefill_metadata.chunked_context is not None
1752
1753

        output = None
1754
1755
        iters = len(prefill_metadata.chunked_context.seq_tot)
        workspace = prefill_metadata.chunked_context.workspace
1756
        for i in range(iters):
1757
            toks = prefill_metadata.chunked_context.seq_tot[i]
1758
            ops.gather_and_maybe_dequant_cache(
1759
1760
                src_cache=kv_c_and_k_pe_cache,
                dst=workspace,
1761
1762
                block_table=prefill_metadata.block_table,
                cu_seq_lens=prefill_metadata.chunked_context.cu_seq_lens[i],
1763
1764
                token_to_seq=prefill_metadata.chunked_context.token_to_seq[i],
                num_tokens=prefill_metadata.chunked_context.chunk_total_token[i],
1765
1766
                kv_cache_dtype=self.kv_cache_dtype,
                scale=k_scale,
1767
                seq_starts=prefill_metadata.chunked_context.starts[i],
1768
1769
            )

1770
1771
            kv_c_normed = workspace[:toks][..., : self.kv_lora_rank]
            k_pe = workspace[:toks][..., self.kv_lora_rank :].unsqueeze(1)
1772

1773
1774
1775
1776
            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)
1777

1778
1779
1780
1781
1782
1783
1784
1785
1786
            # if envs.VLLM_USE_OPT_CAT:
            #     if k_nope.shape[0] > 1024:
            #         from vllm.v1.attention.backends.mla.test_concat import lightop_concat_prefill_helper
            #         k = lightop_concat_prefill_helper(k_nope, k_pe.expand((*k_nope.shape[:-1], -1)),
            #                                           dim=2)
            #     else:
            #         k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)
            # else:
            #     k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)
1787
            k = self._concat_k_nope_k_pe(k_nope, k_pe)
1788

1789
1790
1791
            attn_output, attn_softmax_lse = self._run_prefill_context_chunk(
                prefill=prefill_metadata,
                chunk_idx=i,
1792
1793
                q=q,
                k=k,
1794
                v=v,
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
            )

            if output is None:
                output = attn_output
                output_lse = attn_softmax_lse
            else:
                output_tmp = torch.empty_like(output)
                output_lse_tmp = torch.empty_like(output_lse)
                merge_attn_states(
                    output=output_tmp,
                    output_lse=output_lse_tmp,
                    prefix_output=output,
                    prefix_lse=output_lse,
                    suffix_output=attn_output,
                    suffix_lse=attn_softmax_lse,
                )
                output = output_tmp
                output_lse = output_lse_tmp

        return output, output_lse

1816
1817
1818
1819
1820
1821
1822
1823
    def _context_parallel_compute_prefill_context(
        self,
        q: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: MLACommonMetadata,
        k_scale: torch.Tensor,
        dcp_world_size: int,
    ):
co63oc's avatar
co63oc committed
1824
        assert k_scale is None, "DCP not support scaled kvcache now."
1825
1826
1827
        assert attn_metadata.prefill is not None
        prefill_metadata = attn_metadata.prefill
        assert prefill_metadata.chunked_context is not None
1828
1829
1830
        assert prefill_metadata.chunked_context.padded_local_chunk_seq_lens is not None
        assert prefill_metadata.chunked_context.local_context_lens_allranks is not None
        assert prefill_metadata.chunked_context.padded_local_cu_seq_lens is not None
1831
        assert prefill_metadata.chunked_context.cu_seq_lens_lst is not None
1832
        assert prefill_metadata.chunked_context.chunk_size is not None
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843

        output = None
        iters = len(prefill_metadata.chunked_context.seq_tot)
        workspace = prefill_metadata.chunked_context.workspace

        for i in range(iters):
            toks = prefill_metadata.chunked_context.seq_tot[i]
            ops.cp_gather_cache(
                src_cache=kv_c_and_k_pe_cache,
                dst=workspace,
                block_table=prefill_metadata.block_table,
1844
1845
1846
                cu_seq_lens=prefill_metadata.chunked_context.padded_local_cu_seq_lens[
                    i
                ],
1847
1848
1849
1850
1851
1852
1853
                batch_size=attn_metadata.num_prefills,
                seq_starts=prefill_metadata.chunked_context.starts[i],
            )
            # workspace
            # |------- N tokens --------|--------- N*dcp_size tokens ----------|
            # |<- use for loca_gather ->|<--------- use for allgather -------->|
            allgather_offset = workspace.shape[0] // (dcp_world_size + 1)
1854
            assert allgather_offset * (dcp_world_size + 1) == workspace.shape[0]
1855
1856
1857
            assert toks <= allgather_offset
            local_gathered_kvcache = workspace[:toks]
            cur_allgather_workspace = workspace[
1858
1859
                allgather_offset : allgather_offset * (1 + dcp_world_size)
            ]
1860
            assert toks * dcp_world_size <= cur_allgather_workspace.shape[0]
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
            cur_allgather_kvcache = cur_allgather_workspace[: toks * dcp_world_size]
            cur_allgather_kvcache.copy_(
                get_dcp_group().all_gather(local_gathered_kvcache, dim=0)
            )
            assert (
                cur_allgather_kvcache.shape[-1]
                == self.kv_lora_rank + self.qk_rope_head_dim
            )
            allgatered_kv_c_normed, allgatered_k_pe = cur_allgather_kvcache.unsqueeze(
                1
            ).split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
1872
1873
1874
1875

            kv_c_normed, k_pe = reorg_kvcache(
                allgatered_kv_c_normed,
                allgatered_k_pe,
1876
                padded_local_chunk_seq_lens_lst=prefill_metadata.chunked_context.padded_local_chunk_seq_lens[
1877
1878
                    i
                ],
1879
                local_context_lens_allranks=prefill_metadata.chunked_context.local_context_lens_allranks,
1880
                sum_seq_len=prefill_metadata.chunked_context.cu_seq_lens_lst[i][-1],
1881
1882
1883
                max_seq_len=prefill_metadata.chunked_context.max_seq_lens[i],
                chunk_size=prefill_metadata.chunked_context.chunk_size,
                chunk_idx=i,
1884
1885
                toks=toks,
            )
1886

1887
1888
1889
1890
            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)
1891
            k = self._concat_k_nope_k_pe(k_nope, k_pe)
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919

            attn_output, attn_softmax_lse = self._run_prefill_context_chunk(
                prefill=prefill_metadata,
                chunk_idx=i,
                q=q,
                k=k,
                v=v,
            )

            if output is None:
                output = attn_output
                output_lse = attn_softmax_lse
            else:
                output_tmp = torch.empty_like(output)
                output_lse_tmp = torch.empty_like(output_lse)
                merge_attn_states(
                    output=output_tmp,
                    output_lse=output_lse_tmp,
                    prefix_output=output,
                    prefix_lse=output_lse,
                    suffix_output=attn_output,
                    suffix_lse=attn_softmax_lse,
                )
                output = output_tmp
                output_lse = output_lse_tmp

        return output, output_lse

1920
1921
1922
1923
1924
1925
1926
    def _forward_prefill(
        self,
        q: torch.Tensor,
        kv_c_normed: torch.Tensor,
        k_pe: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: MLACommonMetadata,
1927
        k_scale: torch.Tensor,
1928
1929
        output: torch.Tensor,
    ) -> None:
1930
        # TODO (zyongye): Prefill function here
1931
        assert attn_metadata.prefill is not None
1932
        assert self.dcp_world_size != -1
1933

zhuwenwen's avatar
zhuwenwen committed
1934
1935
1936
1937
        if envs.VLLM_HAS_CONTEXT_DEFAULT:
            has_context = attn_metadata.prefill.chunked_context is not None
        else:
            has_context = False
1938
1939
1940
1941
        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)
1942

1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
        # if envs.VLLM_USE_OPT_CAT:
        #     if k_nope.shape[0] > 1024:
        #         from vllm.v1.attention.backends.mla.test_concat import lightop_concat_prefill_helper
        #         k = lightop_concat_prefill_helper(k_nope, k_pe.expand((*k_nope.shape[:-1], -1)),
        #                                           dim=2)
        #     else:
        #         k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))),
        #                       dim=-1)
        # else:
        #     k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)
1953
        k = self._concat_k_nope_k_pe(k_nope, k_pe)
1954

1955
        output_prefill = self._run_prefill_new_tokens(
1956
            prefill=attn_metadata.prefill,
1957
1958
            q=q,
            k=k,
1959
            v=v,
1960
1961
1962
1963
            return_softmax_lse=has_context,
        )

        if has_context:
1964
            suffix_output, suffix_lse = output_prefill
1965
            if self.dcp_world_size > 1:
1966
                context_output, context_lse = (
1967
                    self._context_parallel_compute_prefill_context(
1968
1969
1970
1971
1972
1973
1974
                        q,
                        kv_c_and_k_pe_cache,
                        attn_metadata,
                        k_scale=None,
                        dcp_world_size=self.dcp_world_size,
                    )
                )
1975
            else:
1976
1977
1978
                context_output, context_lse = self._compute_prefill_context(
                    q, kv_c_and_k_pe_cache, attn_metadata, k_scale
                )
1979

1980
1981
1982
1983
1984
1985
            # unpad if necessary
            if self._pad_v:
                context_output = context_output[..., : v.shape[-1]]
                suffix_output = suffix_output[..., : v.shape[-1]]

            output = output.view(-1, self.num_heads, self.v_head_dim)
1986
1987
1988
1989
1990
1991
1992
            merge_attn_states(
                output=output,
                prefix_output=context_output,
                prefix_lse=context_lse,
                suffix_output=suffix_output,
                suffix_lse=suffix_lse,
            )
1993
1994
1995
        else:
            output_prefill = output_prefill[..., : v.shape[-1]].flatten(start_dim=-2)
            output.copy_(output_prefill)
1996
1997
1998
1999

    @abstractmethod
    def _forward_decode(
        self,
2000
        q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
2001
        kv_c_and_k_pe_cache: torch.Tensor,
2002
        attn_metadata: M,
2003
        layer: AttentionLayer,
2004
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
2005
2006
2007
2008
2009
        raise NotImplementedError

    def forward(
        self,
        layer: AttentionLayer,
2010
        q: torch.Tensor,
2011
2012
2013
        k_c_normed: torch.Tensor,  # key in unified attn
        k_pe: torch.Tensor,  # value in unified attn
        kv_cache: torch.Tensor,
2014
        attn_metadata: M,
2015
2016
2017
        output: torch.Tensor | None = None,
        output_scale: torch.Tensor | None = None,
        output_block_scale: torch.Tensor | None = None,
2018
2019
2020
    ) -> torch.Tensor:
        assert output is not None, "Output tensor must be provided."

2021
        if output_scale is not None or output_block_scale is not None:
2022
            raise NotImplementedError(
2023
2024
                "fused output quantization is not yet supported for MLACommonImpl"
            )
2025

2026
        if attn_metadata is None:
2027
2028
2029
2030
            # During the profile run try to simulate to worse case output size
            # for `self.kv_b_proj(kv_c_normed)` in `_compute_prefill_context`
            # since this can be large
            _ = torch.empty(
2031
2032
2033
2034
2035
                (
                    self.chunked_prefill_workspace_size,
                    self.num_heads,
                    self.qk_nope_head_dim + self.v_head_dim,
                ),
2036
2037
2038
2039
                device=k_c_normed.device,
                dtype=k_c_normed.dtype,
            )

2040
2041
2042
2043
            # The zero fill is required when used with DP + EP
            # to ensure all ranks within a DP group compute the
            # same expert outputs.
            return output.fill_(0)
2044

2045
        if self.dcp_world_size == -1:
2046
2047
            self.dcp_world_size = get_dcp_group().world_size

2048
2049
        fp8_attention = self.kv_cache_dtype.startswith("fp8")

2050
2051
2052
2053
2054
        num_actual_toks = attn_metadata.num_actual_tokens

        # Inputs and outputs may be padded for CUDA graphs
        output_padded = output
        output = output[:num_actual_toks, ...]
2055
        q = q[:num_actual_toks, ...]
2056
2057
2058
        k_c_normed = k_c_normed[:num_actual_toks, ...]
        k_pe = k_pe[:num_actual_toks, ...]

2059
2060
2061
2062
2063
        assert (
            attn_metadata.num_decodes is not None
            and attn_metadata.num_prefills is not None
            and attn_metadata.num_decode_tokens is not None
        )
2064
2065
2066
2067
2068

        has_decode = attn_metadata.num_decodes > 0
        has_prefill = attn_metadata.num_prefills > 0
        num_decode_tokens = attn_metadata.num_decode_tokens

2069
        decode_q = q[:num_decode_tokens]
2070

2071
        prefill_q = q[num_decode_tokens:]
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
        prefill_k_pe = k_pe[num_decode_tokens:]
        prefill_k_c_normed = k_c_normed[num_decode_tokens:]

        # write the latent and rope to kv cache
        if kv_cache.numel() > 0:
            ops.concat_and_cache_mla(
                k_c_normed,
                k_pe.squeeze(1),
                kv_cache,
                attn_metadata.slot_mapping.flatten(),
                kv_cache_dtype=self.kv_cache_dtype,
                scale=layer._k_scale,
            )

2086
2087
2088
        if fp8_attention:
            kv_cache = kv_cache.view(current_platform.fp8_dtype())

2089
        if has_prefill:
2090
            self._forward_prefill(
2091
2092
2093
2094
2095
2096
                prefill_q,
                prefill_k_c_normed,
                prefill_k_pe,
                kv_cache,
                attn_metadata,
                layer._k_scale,
2097
                output=output[num_decode_tokens:],
2098
            )
2099
2100

        if has_decode:
2101
            assert attn_metadata.decode is not None
2102

2103
            decode_q_nope, decode_q_pe = decode_q.split(
2104
2105
                [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
            )
2106

2107
2108
            # Convert from (B, N, P) to (N, B, P)
            decode_q_nope = decode_q_nope.transpose(0, 1)
2109

2110
2111
            if self.q_pad_num_heads is not None:
                B, N, L = decode_q_pe.shape
2112
                decode_pe_padded = decode_q_pe.new_empty((B, self.q_pad_num_heads, L))
2113
2114
2115
2116
                decode_pe_padded.resize_((B, N, L))
                decode_pe_padded.copy_(decode_q_pe)
                decode_q_pe = decode_pe_padded

2117
            if self.is_aiter_triton_fp8_bmm_enabled:
2118
                # Multiply+Transpose (N, B, P)x(N, P, L)->(N, B, L)->(B, N, L)
2119
                decode_ql_nope = rocm_aiter_ops.triton_fp8_bmm(
2120
2121
2122
2123
2124
2125
                    decode_q_nope,
                    self.W_K,
                    self.W_K_scale,
                    group_size=128,
                    transpose_bm=True,
                )
2126
            else:
2127
2128
2129
                # Pads the head_dim if necessary (for the underlying kernel)
                N, B, P = decode_q_nope.shape
                _, _, L = self.W_UK_T.shape
2130

2131
2132
                if self.q_pad_num_heads is not None:
                    decode_ql_nope = decode_q_nope.new_empty(
2133
2134
                        (self.q_pad_num_heads, B, L)
                    )
2135
2136
2137
2138
                    decode_ql_nope.resize_((N, B, L))
                else:
                    decode_ql_nope = decode_q_nope.new_empty((N, B, L))

2139
                # Multiply (N, B, P) x (N, P, L) -> (N, B, L)
2140
                torch.bmm(decode_q_nope, self.W_UK_T, out=decode_ql_nope)
2141

2142
2143
                # Convert from (N, B, L) to (B, N, L)
                decode_ql_nope = decode_ql_nope.transpose(0, 1)
2144

2145
2146
2147
            if fp8_attention:
                ql_nope_shape = decode_ql_nope.shape
                q_pe_shape = decode_q_pe.shape
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
                assert decode_ql_nope.shape[0] == decode_q_pe.shape[0]
                assert decode_ql_nope.shape[1] == decode_q_pe.shape[1]
                decode_q_shape = (
                    ql_nope_shape[0],
                    ql_nope_shape[1],
                    ql_nope_shape[2] + q_pe_shape[2],
                )
                # Using empty and copy since torch.cat introduces significant overhead.
                decode_q0 = torch.empty(
                    decode_q_shape,
                    device=decode_ql_nope.device,
                    dtype=decode_ql_nope.dtype,
2160
                )
2161
2162
                decode_q0[..., : ql_nope_shape[2]].copy_(decode_ql_nope)
                decode_q0[..., ql_nope_shape[2] :].copy_(decode_q_pe)
2163

2164
2165
2166
2167
2168
2169
2170
                decode_q, _ = ops.scaled_fp8_quant(
                    decode_q0.view(decode_q_shape[0], -1),
                    layer._q_scale,
                )
                decode_q = decode_q.view(decode_q_shape)
            else:
                decode_q = (decode_ql_nope, decode_q_pe)
2171
2172
2173
2174
2175
2176
2177
2178
            if self.dcp_world_size > 1:
                assert not fp8_attention, "DCP not support fp8 kvcache now."
                # concatenate decode_ql_nope and decode_q_pe -> (B, N, L + P)
                decode_q = torch.cat(decode_q, dim=-1)
                # decode_q do allgather in head dim.
                decode_q = get_dcp_group().all_gather(decode_q, dim=1)

            # call decode attn
2179
2180
2181
            attn_out, lse = self._forward_decode(
                decode_q, kv_cache, attn_metadata, layer
            )
2182

2183
            # correct dcp attn_out with lse.
2184
            if self.dcp_world_size > 1:
2185
2186
2187
2188
                attn_out = cp_lse_ag_out_rs(
                    attn_out,
                    lse,
                    get_dcp_group(),
2189
                    is_lse_base_on_e=not getattr(self, "_use_fi_prefill", False),
2190
                )
2191
2192

            # v_up projection
2193
            self._v_up_proj(attn_out, out=output[:num_decode_tokens])
2194
        return output_padded