common.py 62.1 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:
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
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

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)`

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:

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
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)
164
    Sc           = chunk_end - chunk_start_table
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    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
"""

import functools
from abc import abstractmethod
from dataclasses import dataclass
193
from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar
194
195
196
from itertools import chain

import numpy as np
197
198

import torch
zhuwenwen's avatar
zhuwenwen committed
199
import os
200
201

from vllm import _custom_ops as ops
202
from vllm import envs
203
204
205
from vllm.attention.backends.abstract import (AttentionBackend, AttentionLayer,
                                              AttentionMetadata,
                                              MLAAttentionImpl)
206
from vllm.attention.backends.utils import get_mla_dims
207
from vllm.attention.ops.merge_attn_states import merge_attn_states
208
from vllm.attention.utils.fa_utils import get_flash_attn_version
209
from vllm.logger import init_logger
210
from vllm.config import get_current_vllm_config
211
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
212
                                               LinearBase,
213
                                               UnquantizedLinearMethod)
Simon Mo's avatar
Simon Mo committed
214
from vllm.platforms import current_platform
215
from vllm.utils import cdiv, round_down, is_pin_memory_available
216
217
from vllm.v1.attention.backends.utils import (AttentionMetadataBuilder,
                                              CommonAttentionMetadata)
218
from vllm.v1.kv_cache_interface import AttentionSpec
王敏's avatar
王敏 committed
219
from vllm.v1.worker.block_table import BlockTable
220
from lightop import fused_rms_norm_rope_contiguous, fuse_rmsnorm_rope_quant_qkv
wujl5's avatar
wujl5 committed
221
222
from lmslim.layers.gemm.fp8_utils import per_token_quant_fp8

223

224
225
try:
    from vllm.vllm_flash_attn import flash_attn_varlen_func
226
    is_vllm_fa = True
227
228
except ImportError:
    # For rocm use upstream flash attention
229
230
    if current_platform.is_rocm():
        from flash_attn import flash_attn_varlen_func
231
    is_vllm_fa = False
232
233

if TYPE_CHECKING:
234
    from vllm.v1.core.sched.output import SchedulerOutput
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    from vllm.v1.worker.gpu_input_batch import InputBatch
    from vllm.v1.worker.gpu_model_runner import GPUModelRunner

logger = init_logger(__name__)


class MLACommonBackend(AttentionBackend):

    accept_output_buffer: bool = True

    @staticmethod
    def get_name() -> str:
        return "TRITON_MLA_VLLM_V1"

    @staticmethod
250
    def get_metadata_cls() -> type["AttentionMetadata"]:
251
252
253
        return MLACommonMetadata

    @staticmethod
254
    def get_builder_cls() -> type["MLACommonMetadataBuilder"]:
255
256
257
258
259
260
261
262
        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,
263
    ) -> tuple[int, ...]:
264
265
        return (num_blocks, block_size, head_size)

266
267
    @classmethod
    def get_supported_head_sizes(cls) -> list[int]:
268
269
        return [576]

270
271
272
273
274
275
276
277
278
279
280
    @classmethod
    def validate_head_size(cls, head_size: int) -> None:
        supported_head_sizes = cls.get_supported_head_sizes()
        if head_size not in supported_head_sizes:
            attn_type = cls.__name__.removesuffix("Backend")
            raise ValueError(
                f"Head size {head_size} is not supported by {attn_type}. "
                f"Supported head sizes are: {supported_head_sizes}. "
                "Set VLLM_ATTENTION_BACKEND=FLEX_ATTENTION to use "
                "FlexAttention backend which supports all head sizes.")

281
282

@dataclass
283
284
285
286
287
288
289
290
291
292
293
294
class MLACommonPrefillMetadata:
    """ Prefill Specific Metadata """

    @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]
        workspace: torch.Tensor
295

296
297
298
299
300
    block_table: torch.Tensor
    query_start_loc: torch.Tensor
    max_query_len: int
    chunked_context: Optional[ChunkedContextMetadata] = None

301

302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
@dataclass
class MLACommonDecodeMetadata:
    block_table: torch.Tensor
    seq_lens: torch.Tensor


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


@dataclass
class MLACommonMetadata(Generic[D]):
    """Metadata for MLACommon.

    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """
318
319
320
321
322
323
324
325
326
327
328
329
    # NOTE(sang): Definition of context_len, query_len, and seq_len.
    # |---------- N-1 iteration --------|
    # |---------------- N iteration ---------------------|
    # |- tokenA -|......................|-- newTokens ---|
    # |---------- context_len ----------|
    # |-------------------- seq_len ---------------------|
    #                                   |-- query_len ---|

    num_actual_tokens: int  # Number of tokens excluding padding.
    query_start_loc: torch.Tensor
    slot_mapping: torch.Tensor

330
331
332
333
334
335
    # New for MLA (compared to FlashAttention)
    # For handling prefill decode split
    num_decodes: int
    num_decode_tokens: int
    num_prefills: int

336
337
338
    # The dimension of the attention heads
    head_dim: Optional[int] = None

339
340
    decode: Optional[D] = None
    prefill: Optional[MLACommonPrefillMetadata] = None
341
342

    def __post_init__(self):
343
344
        if self.head_dim is not None:
            MLACommonBackend.validate_head_size(self.head_dim)
345
346


347
M = TypeVar("M", bound=MLACommonMetadata)
348
349


350
class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
351
352
353
354
355
    """
    NOTE: Please read the comment at the top of the file before trying to
    understand this class
    """

356
357
    def __init__(self,
                 runner: "GPUModelRunner",
358
359
                 kv_cache_spec: AttentionSpec,
                 block_table: BlockTable,
360
361
362
                 metadata_cls: Optional[type[M]] = None):
        self.metadata_cls = metadata_cls \
            if metadata_cls is not None else MLACommonMetadata
363
364
365
366
367
        self.runner = runner
        scheduler_config = runner.scheduler_config
        model_config = runner.model_config
        cache_config = runner.cache_config
        self.chunked_prefill_enabled = scheduler_config.chunked_prefill_enabled
368
369
370
        self.num_heads = model_config.get_num_attention_heads(
            runner.parallel_config)
        self.mla_dims = get_mla_dims(model_config)
371
        self.aot_schedule = current_platform.is_cuda()
372
        self.kv_cache_spec = kv_cache_spec
373
374
375

        # Dont try to access the runner on AMD
        if self.aot_schedule:
376
            self.page_size = self.kv_cache_spec.block_size
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

        if self.chunked_prefill_enabled:
            self.chunked_prefill_workspace_size = min(
                # Max sure there is enough for 8 full length request or at least
                # 4 pages of cache per request
                max(
                    8 * model_config.max_model_len, 4 *
                    scheduler_config.max_num_seqs * cache_config.block_size),
                # 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)
                128 * 1024)
            assert self.chunked_prefill_workspace_size >= \
                scheduler_config.max_num_seqs * cache_config.block_size
            self.chunked_prefill_workspace = torch.empty(
                (self.chunked_prefill_workspace_size,
                 model_config.get_head_size()),
                dtype=model_config.dtype,
                device=runner.device,
            )
402
        self.block_table = block_table
403

404
        self.use_spec_decode = False
405
        self.decode_token_num_threshold = 1  
406
407
        vllm_config = get_current_vllm_config()
        speculative_config = vllm_config.speculative_config
王敏's avatar
王敏 committed
408
        if speculative_config and speculative_config.num_speculative_tokens > 0:
409
410
            self.use_spec_decode = True
            self.decode_token_num_threshold = 1 + speculative_config.num_speculative_tokens
王敏's avatar
王敏 committed
411

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
        self.device = self.runner.device
        self.pin_memory = is_pin_memory_available()
        #self.num_scheduled_tokens_np = np.zeros(scheduler_config.max_num_seqs, dtype=np.int32)

        self.num_scheduled_tokens = torch.zeros(scheduler_config.max_num_seqs,
                                    dtype=torch.int32,
                                    device=self.device)
        self.num_scheduled_tokens_cpu = torch.zeros(scheduler_config.max_num_seqs,
                                        dtype=torch.int32,
                                        device="cpu",
                                        pin_memory=self.pin_memory)
        self.num_scheduled_tokens_np = self.num_scheduled_tokens_cpu.numpy()


        self.seq_lens_minus = torch.zeros(scheduler_config.max_num_seqs * self.decode_token_num_threshold,
                                    dtype=torch.int32,
                                    device=self.device)
        self.seq_lens_minus_cpu = torch.zeros(scheduler_config.max_num_seqs * self.decode_token_num_threshold,
                                        dtype=torch.int32,
                                        device="cpu",
                                        pin_memory=self.pin_memory)
        self.seq_lens_minus_np = self.seq_lens_minus_cpu.numpy()


        # support for cudagraph spec docoding
        self.spec_decode_block_table_tensor = None
        self.spec_decode_seq_lens = None

440

441
    def reorder_batch(self, input_batch: "InputBatch",
442
                      scheduler_output: "SchedulerOutput") -> bool:
443
444
445
446
447
448
449
450
451
452
        # We now want to reorder the batch so that the "decode" requests are and
        # the front and the "prefill" requests are at the using the least amount
        # swaps possible. (NOTE for now we loosely use "decode" to mean requests
        # where attention is likely memory-bound and "prefill" to mean requests
        # where attention is likely compute-bound, TODO(lucas): figure out a
        # better naming here)
        decodes = []
        prefills = []
        num_decode_tokens = 0
        num_prefill_tokens = 0
453
454
        use_spec_decode = len(
            scheduler_output.scheduled_spec_decode_tokens) > 0
455
456
457
458
459
460
461

        for i, req_id in enumerate(input_batch.req_ids):
            num_tokens = scheduler_output.num_scheduled_tokens[req_id]
            # for now treat 1 scheduled token as "decode" even if its not,
            # we should update this to something like < 8 in the future but
            # currently the TritonMLA._forward_decode only supports
            # num_tokens = 1
462
463
464
465
466
467
468
469
470
471

            # if num_tokens == 2 or num_tokens == 1:
            #     decodes.append(i)
            #     num_decode_tokens += num_tokens
            # else:
            #     prefills.append(i)
            #     num_prefill_tokens += num_tokens
            req_idx = input_batch.req_id_to_index[req_id]
            num_computed_tokens = input_batch.num_computed_tokens_cpu[req_idx]
            num_prompt_tokens = input_batch.num_prompt_tokens[req_idx]
472
            self.num_scheduled_tokens_np[i] = num_tokens
473

474
            if num_computed_tokens < num_prompt_tokens or (num_tokens > self.decode_token_num_threshold):
475
476
                prefills.append(i)
                num_prefill_tokens += num_tokens
477
478
479
            else:
                decodes.append(i)
                num_decode_tokens += num_tokens
480
481
482
483
484
485
486
487
488
489
490
491
492

        # We hope that this is fairly minimal since decodes
        # should be around for a number of iterations so hopefully they are
        # relatively stationary (and new request are generally appended to the
        # persistent batch so already should be at the back)
        # To achieve this we loop over the decodes in descending order and
        # the prefills in ascending order. We swap decodes from the  "back"
        # i.e. past where the last decode should be in the reodorered with
        # prefills from the front of the batch.
        # `decodes` and `prefills` are already in ascending order just based on
        # the above loop
        num_decodes = len(decodes)
        num_prefills = len(prefills)
493
        modified_batch = False
494
495
496
497

        for i in range(1, min(num_decodes, num_prefills) + 1):
            # If the decode is at the "back" of the batch, i, we can swap it
            # with the prefill closest to the front of the batch
498
499
            decode_idx = decodes[num_decodes - i]
            if decode_idx < num_decodes:
500
501
                break

502
503
504
            input_batch.swap_states(prefills[i - 1], decode_idx)
            modified_batch = True

505
            # num_scheduled_tokens also need to be swapped
506
507
508
509
            tmp = self.num_scheduled_tokens_np[decode_idx]
            self.num_scheduled_tokens_np[decode_idx] = self.num_scheduled_tokens_np[prefills[i - 1]]
            self.num_scheduled_tokens_np[prefills[i - 1]] = tmp

510

511
512
513
514
515
516
517
        # Save for next `build` call
        # TODO(lucas): this is a bit of a hack, we should probably have a
        # better way of doing this
        self._num_decodes = num_decodes
        self._num_prefills = num_prefills
        self._num_decode_tokens = num_decode_tokens
        self._num_prefill_tokens = num_prefill_tokens
518
        
519
        self.use_spec_decode = use_spec_decode
520

521
522
        return modified_batch

523
524
    def _build_decode(self, block_table_tensor: torch.Tensor,
                      seq_lens: torch.Tensor):
525
        return MLACommonDecodeMetadata(
526
            block_table=block_table_tensor,
527
528
529
            seq_lens=seq_lens,
        )

530
531
532
533
534
535
536
    def build_for_cudagraph_capture(
            self, common_attn_metadata: CommonAttentionMetadata) -> M:
        """
        This method builds the metadata for full cudagraph capture.
        Currently, only decode is supported for full cudagraphs with MLA.
        """
        m = common_attn_metadata
王敏's avatar
王敏 committed
537
538
539
        # assert m.num_reqs == m.num_actual_tokens, \
        #     "MLA only supports decode-only full CUDAGraph capture. " \
        #     "Make sure all cudagraph capture sizes <= max_num_seq."
540

王敏's avatar
王敏 committed
541
        #m.max_query_len = 1  # decode-only
542
543
544
545
546
547

        # Update state usually set in reorder_batch.
        self._num_decodes = m.num_reqs
        self._num_decode_tokens = m.num_actual_tokens
        self._num_prefills = 0
        self._num_prefill_tokens = 0
王敏's avatar
王敏 committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
        self.use_spec_decode = m.num_speculative_tokens > 0

        # support for cudagraph spec docoding
        if self.use_spec_decode:
            for i in range(m.num_reqs):
                self.num_scheduled_tokens_np[i] = m.num_actual_tokens // m.num_reqs

            if self.spec_decode_block_table_tensor is None:
                max_num_reqs = m.seq_lens.shape[0]
                block_table_tensor = self.block_table.get_device_tensor()
                tokens_per_seq = 1+m.num_speculative_tokens

                self.spec_decode_block_table_tensor = torch.zeros((block_table_tensor.shape[0]*tokens_per_seq,
                                                                   block_table_tensor.shape[1]),
                                     dtype=block_table_tensor.dtype,
                                     device=m.seq_lens.device)
                self.spec_decode_seq_lens = torch.zeros(max_num_reqs * tokens_per_seq,
                                     dtype=m.seq_lens.dtype,
                                     device=m.seq_lens.device)
567
568
569
        return self.build(0, m)

    def build(self, common_prefix_len: int,
570
              common_attn_metadata: CommonAttentionMetadata) -> M:
571
572
573
574
        num_reqs = common_attn_metadata.num_reqs
        num_actual_tokens = common_attn_metadata.num_actual_tokens
        max_query_len = common_attn_metadata.max_query_len

575
576
        assert self._num_decodes + self._num_prefills == num_reqs

Simon Mo's avatar
Simon Mo committed
577
578
579
        # 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.
580
        device = self.runner.device
581
582
        block_table = self.block_table
        block_table_tensor = block_table.get_device_tensor()[:num_reqs]
583
584
585
586
587
588
589
590

        slot_mapping = common_attn_metadata.slot_mapping
        if slot_mapping is None:
            block_table.slot_mapping[:num_actual_tokens].copy_(
                block_table.slot_mapping_cpu[:num_actual_tokens],
                non_blocking=True)
            block_table.slot_mapping[num_actual_tokens:].fill_(-1)
            slot_mapping = block_table.slot_mapping[:num_actual_tokens]
591

592
593
        query_start_loc = common_attn_metadata.query_start_loc
        seq_lens = common_attn_metadata.seq_lens
Simon Mo's avatar
Simon Mo committed
594

595
596
597
598
599
600
        prefill_metadata = None
        if self._num_prefills > 0:
            reqs_start = self._num_decodes  # prefill_start

            context_lens_cpu = self.runner.input_batch.\
                num_computed_tokens_cpu_tensor[reqs_start:num_reqs]
Simon Mo's avatar
Simon Mo committed
601
602
            max_context_len_cpu = context_lens_cpu.max().item()
            num_prefills_with_context_cpu = (context_lens_cpu > 0).sum().item()
603
604
            prefill_query_start_loc = query_start_loc[
                reqs_start:] - query_start_loc[reqs_start]
605
606
607

            chunked_context_metadata = None
            if self.chunked_prefill_enabled and self._num_prefills > 0 \
Simon Mo's avatar
Simon Mo committed
608
                and max_context_len_cpu > 0:
609
610
611
612
613
614
615
616
                # 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
Simon Mo's avatar
Simon Mo committed
617
618
                max_context_chunk = (self.chunked_prefill_workspace_size //
                                     num_prefills_with_context_cpu)
619

620
621
622
623
624
625
                if self.aot_schedule:
                    # align max_context_chunk to page_size by rounding down,
                    # currently the `gather_cache` kernel cannot handle
                    # `context_chunk_starts` that are not aligned to page_size
                    max_context_chunk = round_down(max_context_chunk,
                                                   self.page_size)
626
627

                assert max_context_chunk > 0
Simon Mo's avatar
Simon Mo committed
628
                num_chunks = cdiv(max_context_len_cpu, max_context_chunk)
629
630
631
632
633

                # 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
634
635
                # Note(simon): this is done in CPU because of downstream's
                # of `to_list`.
636
                chunk_starts = \
Simon Mo's avatar
Simon Mo committed
637
                    torch.arange(num_chunks, dtype=torch.int32) \
638
639
                    .unsqueeze(1).expand(-1, self._num_prefills) \
                    * max_context_chunk
Simon Mo's avatar
Simon Mo committed
640
                chunk_ends = torch.min(context_lens_cpu.unsqueeze(0),
641
642
                                       chunk_starts + max_context_chunk)
                chunk_seq_lens = (chunk_ends - chunk_starts).clamp(min=0)
Simon Mo's avatar
Simon Mo committed
643
644
645
646
647
648
649
650
651

                cu_seq_lens_cpu = torch.zeros(num_chunks,
                                              self._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)
652
653
654

                chunked_context_metadata = \
                    MLACommonPrefillMetadata.ChunkedContextMetadata(
Simon Mo's avatar
Simon Mo committed
655
656
                    cu_seq_lens=cu_seq_lens_cpu.to(device, non_blocking=True),
                    starts=chunk_starts.to(device, non_blocking=True),
657
658
659
660
661
662
663
664
665
                    seq_tot=chunk_seq_lens.sum(dim=1).tolist(),
                    max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(),
                    workspace=self.chunked_prefill_workspace,
                )

                assert max(chunked_context_metadata.max_seq_lens) <= \
                    self.chunked_prefill_workspace_size

            prefill_metadata = MLACommonPrefillMetadata(
666
                block_table=block_table_tensor[reqs_start:, ...],
667
                query_start_loc=prefill_query_start_loc,
Simon Mo's avatar
Simon Mo committed
668
                max_query_len=max_query_len,
669
670
671
672
673
                chunked_context=chunked_context_metadata,
            )

        decode_metadata = None
        if self._num_decodes > 0:
674
            if self.use_spec_decode and not common_attn_metadata.spec_layer_decoding:
675
                query_lens = self.num_scheduled_tokens_np[:self._num_decodes]
676
677
678
679
680
                self.num_scheduled_tokens[:self._num_decodes].copy_(
                    self.num_scheduled_tokens_cpu[:self._num_decodes],
                    non_blocking=True)
                repeats = self.num_scheduled_tokens[:self._num_decodes]

681
682
683
684
685
686
                cu_num_blocks = np.cumsum(query_lens)
                virtual_batches = cu_num_blocks[-1]
                block_offsets = np.repeat(cu_num_blocks - query_lens, query_lens)
                arange = np.arange(virtual_batches, dtype=np.int32) - block_offsets
                rarange = np.repeat(query_lens, query_lens) - arange - 1

687
688
689
690
691
                self.seq_lens_minus_np[:rarange.size] = rarange
                self.seq_lens_minus[:rarange.size].copy_(
                    self.seq_lens_minus_cpu[:rarange.size],
                    non_blocking=True)
                seq_lens_minus = self.seq_lens_minus[:rarange.size]
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
                
                if envs.VLLM_ZERO_OVERHEAD:
                    decode_block_table_tensor = torch.empty((self._num_decode_tokens, block_table_tensor.shape[1]), 
                                                            device=block_table_tensor.device)
                    arange_np = np.arange(self._num_decodes)
                    indices_np = np.repeat(arange_np, query_lens)
                    
                    indices = torch.from_numpy(indices_np).pin_memory().to(
                        block_table_tensor.device, non_blocking=True)
                    decode_block_table_tensor = block_table_tensor[indices].contiguous()
                    decode_seq_lens = seq_lens[indices].contiguous()
                else:
                    decode_block_table_tensor = torch.repeat_interleave(
                        block_table_tensor[:self._num_decodes, ...],
                        repeats, dim=0).contiguous()
                    decode_seq_lens = torch.repeat_interleave(seq_lens[:self._num_decodes], repeats, dim=0).contiguous()
708

709
                decode_seq_lens = decode_seq_lens - seq_lens_minus
710

王敏's avatar
王敏 committed
711
712
713
714
715
716
717
718
719
720
721
722
723
                if self.spec_decode_block_table_tensor is not None:
                    self.spec_decode_block_table_tensor[:self._num_decode_tokens].copy_(decode_block_table_tensor)
                    self.spec_decode_seq_lens[:self._num_decode_tokens].copy_(decode_seq_lens)

                    decode_metadata = self._build_decode(
                        block_table_tensor=self.spec_decode_block_table_tensor[:self._num_decode_tokens, ...],
                        seq_lens=self.spec_decode_seq_lens[:self._num_decode_tokens],
                    )
                else:
                    decode_metadata = self._build_decode(
                        block_table_tensor=decode_block_table_tensor,
                        seq_lens=decode_seq_lens,
                    )
724
            else:
725
726
727
728
729
730
731
732
733
734
735
736
737
738
                self._num_decode_tokens = self._num_decodes
                if self.use_spec_decode and self.spec_decode_block_table_tensor is not None:
                    self.spec_decode_block_table_tensor[:self._num_decode_tokens].copy_(block_table_tensor[:self._num_decode_tokens, ...])
                    self.spec_decode_seq_lens[:self._num_decode_tokens].copy_(seq_lens[:self._num_decode_tokens])

                    decode_metadata = self._build_decode(
                        block_table_tensor=self.spec_decode_block_table_tensor[:self._num_decode_tokens, ...],
                        seq_lens=self.spec_decode_seq_lens[:self._num_decode_tokens],
                    )
                else:
                    decode_metadata = self._build_decode(
                        block_table_tensor=block_table_tensor[:self._num_decode_tokens, ...],
                        seq_lens=seq_lens[:self._num_decode_tokens],
                    )
739
740

        return self.metadata_cls(
741
742
743
744
745
746
747
748
            num_actual_tokens=num_actual_tokens,
            query_start_loc=query_start_loc,
            slot_mapping=slot_mapping,
            head_dim=self.runner.model_config.get_head_size(),
            # MLACommonMetadata Chunk prefill specific
            num_decodes=self._num_decodes,
            num_decode_tokens=self._num_decode_tokens,
            num_prefills=self._num_prefills,
749
750
            prefill=prefill_metadata,
            decode=decode_metadata,
751
752
        )

753
754
    def can_run_in_cudagraph(
            self, common_attn_metadata: CommonAttentionMetadata) -> bool:
755
756
        if not self.use_spec_decode:
            return common_attn_metadata.max_query_len == 1
王敏's avatar
王敏 committed
757
        return self._num_prefills == 0
758

759

760
class MLACommonImpl(MLAAttentionImpl[M], Generic[M]):
761
762
763
764
765
766
767
768
769
770
771
    """
    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,
772
        alibi_slopes: Optional[list[float]],
773
774
        sliding_window: Optional[int],
        kv_cache_dtype: str,
775
        blocksparse_params: Optional[dict[str, Any]],
776
777
        logits_soft_cap: Optional[float],
        attn_type: str,
778
        kv_sharing_target_layer_name: Optional[str],
779
780
781
782
783
784
785
786
787
        # MLA Specific Arguments
        q_lora_rank: Optional[int],
        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,
    ) -> None:
788
789
790
        if kv_sharing_target_layer_name is not None:
            raise NotImplementedError("KV sharing is not supported for MLA")

791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
        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

        # 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
809
        self.vllm_flash_attn_version = get_flash_attn_version()
810
811
812
813
        if self.vllm_flash_attn_version is not None:
            self.flash_attn_varlen_func = \
                functools.partial(flash_attn_varlen_func,
                                  fa_version=self.vllm_flash_attn_version)
zhuwenwen's avatar
zhuwenwen committed
814
815
        
        self.use_llama_nn = os.environ.get('LLAMA_NN') == '1'
816

817
818
819
820
        # 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
zhuwenwen's avatar
zhuwenwen committed
821
822
823
824
825
826
827
        if not current_platform.is_rocm():
            self._pad_v = self.vllm_flash_attn_version is None or not (
                self.vllm_flash_attn_version == 3
                and current_platform.get_device_capability()[0] == 9)
        else:
            self._pad_v = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count == 120
            
828
829
830
831
832

    def _flash_attn_varlen_diff_headdims(self,
                                         q,
                                         k,
                                         v,
833
834
835
                                         q_descale=None,
                                         k_descale=None,
                                         v_descale=None,
836
837
838
839
840
                                         return_softmax_lse=False,
                                         softmax_scale=None,
                                         **kwargs):
        maybe_padded_v = v
        if self._pad_v:
zhuwenwen's avatar
zhuwenwen committed
841
842
            # maybe_padded_v = torch.nn.functional.pad(
            #     v, [0, q.shape[-1] - v.shape[-1]], value=0)
843
            maybe_padded_v = torch.nn.functional.pad(
zhuwenwen's avatar
zhuwenwen committed
844
845
                    v, [0, q.shape[-1] - v.shape[-1]- 32], value=0)
            maybe_padded_v = maybe_padded_v[..., :-32].reshape(v.shape[0], v.shape[1],v.shape[2])
846

847
848
849
850
851
852
853
        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

854
855
856
857
        attn_out = self.flash_attn_varlen_func(
            q=q,
            k=k,
            v=maybe_padded_v,
858
859
860
            q_descale=q_descale,
            k_descale=k_descale,
            v_descale=v_descale,
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
            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

wujl5's avatar
wujl5 committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
    def weight_quant_fp8(self, weight, dim:Optional[int]=1):
        finfo = torch.finfo(torch.float8_e4m3fn)
        fp8_min = finfo.min
        fp8_max = finfo.max
        absmax = torch.max(weight.abs(), dim=dim, keepdim=True).values
        absmax = absmax.clamp(min=1e-10)
        scale = absmax.to(torch.float32) / fp8_max
        scale = scale.clamp(min=1e-10)
        weight_fp32 = weight.float() if weight.dtype != torch.float32 else weight
        scale_fp32 = scale.float() if scale.dtype != torch.float32 else scale
        weight_q = weight_fp32 / scale_fp32
        weight_q = weight_q.clamp(fp8_min, fp8_max)
        weight_q = weight_q.to(torch.float8_e4m3fn)
        return weight_q, scale

891
    def _v_up_proj(self, x):
wujl5's avatar
wujl5 committed
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
        if self.enable_fused_DTBmm():
            x = x.view(-1, self.num_heads, self.kv_lora_rank).contiguous()
            B, N, L = x.shape
            N, V, L = self.weight_uv_bmm.shape
            if B <= 32:
                from lightop import fused_bmm as fused_DTBmm
                from lightop import get_batched_gemm_w8a8_config as DTBmm_config
                x = x.reshape(-1, self.num_heads, self.kv_lora_rank).contiguous()
                x_q, x_scale = per_token_quant_fp8(x)
                x_out = torch.empty(B, N, V, dtype=torch.bfloat16, device=x.device)
                _dtype = torch.bfloat16
                _config, _status = DTBmm_config(B, N, L)
                assert x_q.shape == (B, N, L) , f"assert error {x_q.shape}" 
                assert x_scale.shape == (B, N, 1) , f"assert error {x_scale.shape}"
                fused_DTBmm(x=x_q, w=self.weight_uv_bmm, x_scale=x_scale, w_scale=self.weight_uv_scale_bmm, 
                            bias=None, dtype=_dtype, output=x_out,
                            transpose_bm=False, transpose_bm_in=False, config=_config)
                out = x_out.reshape(-1, self.num_heads * self.v_head_dim)
                return out
            else:
                from lmslim import quant_ops
                x = x.view(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1)
                x_= x.reshape(-1,self.kv_lora_rank).contiguous()
                x_q, x_scale = per_token_quant_fp8(x_)
                x_q = x_q.reshape(self.num_heads,-1,self.kv_lora_rank).contiguous()
                x_scale = x_scale.reshape(self.num_heads,-1).contiguous()

                weight_k = self.W_UV.shape[1]
                weight_n = self.W_UV.shape[2]
                
                _, result = quant_ops.hipblaslt_w8a8_channelwise_gemm(
                            x_q, self.weight_uv_bmm , x_scale, self.weight_uv_scale_bmm, 
                            x.shape[1], weight_n, weight_k, 'NT', torch.bfloat16, None)

                return result.transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
        
        else: # default
            # Convert from (B, N, L) to (N, B, L)
            x = x.view(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1)
            # Multiply (N, B, L) x (N, L, V) -> (N, B, V)
            x = torch.bmm(x, self.W_UV)
            # Convert from (N, B, V) to (B, N * V)
            return x.transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
    
        
    def enable_fused_DTBmm(self):
        if envs.VLLM_USE_FUSED_DTBMM and \
                torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938":
            return True
        else: 
            return False
943

944
    def process_weights_after_loading(self, act_dtype: torch.dtype):
945
946

        def get_layer_weight(layer):
947
948
949
950
951
952
953
            WEIGHT_NAMES = ("weight", "qweight", "weight_packed")
            for attr in WEIGHT_NAMES:
                if hasattr(layer, attr):
                    return getattr(layer, attr)
            raise AttributeError(
                f"Layer '{layer}' has no recognized weight attribute:"
                f" {WEIGHT_NAMES}.")
954
955
956
957
958
959
960
961
962
963
964
965
966

        def get_and_maybe_dequant_weights(layer: LinearBase):
            if not isinstance(layer.quant_method, UnquantizedLinearMethod):
                # NOTE: This should only be used offline, since it's O(N^3)
                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)
                del eye
                # standardize to (output, input)
                return dequant_weights.T
967
            return layer.weight if not envs.VLLM_USE_NN else layer.weight.T
968

969
970
971
        # we currently do not have quantized bmm's which are needed for
        # `W_UV` and `W_UK_T`, we we just store fp16/bf16 copies and perform
        # the bmm's in 16-bit, the extra memory overhead of this is fairly low
zhuwenwen's avatar
zhuwenwen committed
972
973
974
975
        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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
        assert kv_b_proj_weight.shape == (
            self.kv_lora_rank,
            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=}")
        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(
            [self.qk_nope_head_dim, self.v_head_dim], dim=-1)

993
994
995
996
        # 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)
wujl5's avatar
wujl5 committed
997
998
999
1000
1001
        
        if self.enable_fused_DTBmm(): 
            weight_uv_NLV, weight_uv_scale_NL =self.weight_quant_fp8(self.W_UV, 1)
            self.weight_uv_bmm = weight_uv_NLV.transpose(1,2).contiguous()
            self.weight_uv_scale_bmm = weight_uv_scale_NL.transpose(1,2).contiguous()
1002
1003
1004
1005
1006
1007

    def _compute_prefill_context(
        self,
        q: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
        attn_metadata: MLACommonMetadata,
yangql's avatar
yangql committed
1008
        kv_scale=torch.tensor(1.0, dtype=torch.float32),     
1009
    ):
1010
1011
1012
        assert attn_metadata.prefill is not None
        prefill_metadata = attn_metadata.prefill
        assert prefill_metadata.chunked_context is not None
1013
1014

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

1018
1019
1020
1021
1022
1023
        use_flash_fp8_arch = (
            torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938" 
            and envs.VLLM_USE_FLASH_ATTN_FP8
        )
        use_fused_fp8_op = use_flash_fp8_arch and envs.VLLM_FUSE_CAT_AND_CAST_FP8

1024
        for i in range(iters):
1025
            toks = prefill_metadata.chunked_context.seq_tot[i]
1026
1027
1028
1029

            ops.gather_cache(
                src_cache=kv_c_and_k_pe_cache,
                dst=workspace,
1030
1031
                block_table=prefill_metadata.block_table,
                cu_seq_lens=prefill_metadata.chunked_context.cu_seq_lens[i],
1032
                batch_size=attn_metadata.num_prefills,
1033
                seq_starts=prefill_metadata.chunked_context.starts[i],
yangql's avatar
yangql committed
1034
1035
                kv_dtype=self.kv_cache_dtype,
                scale=kv_scale,
1036
1037
            )

1038
1039
            kv_c_normed = workspace[:toks][..., :self.kv_lora_rank]
            k_pe = workspace[:toks][..., self.kv_lora_rank:].unsqueeze(1)
1040

1041
            kv_nope = self.kv_b_proj(kv_c_normed)[0].view(
1042
1043
                -1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
            if use_fused_fp8_op:
                from lightop import op
                k_pe_expanded = k_pe.expand(k_pe.shape[0], self.num_heads, k_pe.shape[-1])
                q_attn, k_attn, v_attn = op.ds_fused_qkv_cast_fp8(
                    q, 
                    kv_nope, 
                    k_pe_expanded,  
                    self.qk_nope_head_dim, 
                    self.v_head_dim
                )
1054
            else:
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
                k_nope, v_nope = kv_nope.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)

                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_cat = lightop_concat_prefill_helper(k_nope, k_pe.expand((*k_nope.shape[:-1], -1)), dim=2)
                    else:
                        k_cat = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)
                else:
                    k_cat = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1)

                if use_flash_fp8_arch:
                    q_attn = q.to(torch.float8_e4m3fn)
                    k_attn = k_cat.to(torch.float8_e4m3fn)
                    v_attn = v_nope.to(torch.float8_e4m3fn)
                else:
                    q_attn = q
                    k_attn = k_cat
                    v_attn = v_nope

            if use_flash_fp8_arch:
                attn_output, attn_softmax_lse = self._flash_attn_varlen_diff_headdims(
                    q=q_attn,
                    k=k_attn,
                    v=v_attn,
1080
1081
1082
1083
1084
1085
                    cu_seqlens_q=prefill_metadata.query_start_loc,
                    cu_seqlens_k=prefill_metadata.chunked_context.cu_seq_lens[i],
                    max_seqlen_q=prefill_metadata.max_query_len,
                    max_seqlen_k=prefill_metadata.chunked_context.max_seq_lens[i],
                    softmax_scale=self.scale,
                    causal=False,  # Context is unmasked
1086
1087
1088
                    q_descale=None,
                    k_descale=None,
                    v_descale=None,
1089
1090
1091
                    return_softmax_lse=True,
                )
            else:
1092
1093
1094
1095
                attn_output, attn_softmax_lse = self._flash_attn_varlen_diff_headdims(
                    q=q_attn,
                    k=k_attn,
                    v=v_attn,
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
                    cu_seqlens_q=prefill_metadata.query_start_loc,
                    cu_seqlens_k=prefill_metadata.chunked_context.cu_seq_lens[i],
                    max_seqlen_q=prefill_metadata.max_query_len,
                    max_seqlen_k=prefill_metadata.chunked_context.max_seq_lens[i],
                    softmax_scale=self.scale,
                    causal=False,  # Context is unmasked
                    q_descale=None,
                    k_descale=None,
                    v_descale=None,
                    return_softmax_lse=True,
                )
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133

            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

    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,
yangql's avatar
yangql committed
1134
        kv_scale=torch.tensor(1.0, dtype=torch.float32),
1135
        kv_quant_args: Optional[list[torch.Tensor]] = None,
1136
    ) -> torch.Tensor:
1137
1138
        assert attn_metadata.prefill is not None

zhuwenwen's avatar
zhuwenwen committed
1139
1140
1141
1142
        if envs.VLLM_HAS_CONTEXT_DEFAULT:
            has_context = attn_metadata.prefill.chunked_context is not None
        else:
            has_context = False
1143
1144
1145
1146
1147
1148
        
        if kv_quant_args is not None:
            kv_nope = self.kv_b_proj.quant_method.apply(
                self.kv_b_proj, kv_c_normed, input_quant_args=kv_quant_args)
        else:
            kv_nope = self.kv_b_proj(kv_c_normed)
gaoqiong's avatar
gaoqiong committed
1149

1150
1151
1152
1153
        if isinstance(kv_nope, tuple):
            kv_nope = kv_nope[0]

        kv_nope = kv_nope.view(
1154
            -1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
        
        # kv_nope = self.kv_b_proj(kv_c_normed)[0].view(
        #     -1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
        
        use_flash_fp8_arch = (
            torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938" 
            and envs.VLLM_USE_FLASH_ATTN_FP8
        )
        use_fused_fp8_op = use_flash_fp8_arch and envs.VLLM_FUSE_CAT_AND_CAST_FP8 
        
        if use_fused_fp8_op:
            from lightop import op
            k_pe_expanded = k_pe.expand(k_pe.shape[0], self.num_heads, k_pe.shape[-1])
            q, k, v = op.ds_fused_qkv_cast_fp8(
                q, 
                kv_nope, 
                k_pe_expanded,  
                self.qk_nope_head_dim, 
                self.v_head_dim
            )
1175
        else:
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
            k_nope, v = kv_nope.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
            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)

            if use_flash_fp8_arch:
                q = q.to(torch.float8_e4m3fn)
                k = k.to(torch.float8_e4m3fn)
                v = v.to(torch.float8_e4m3fn)

        if use_flash_fp8_arch:
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
            output = self._flash_attn_varlen_diff_headdims(
                q=q,
                k=k,
                v=v,
                cu_seqlens_q=attn_metadata.prefill.query_start_loc,
                cu_seqlens_k=attn_metadata.prefill.query_start_loc,
                max_seqlen_q=attn_metadata.prefill.max_query_len,
                max_seqlen_k=attn_metadata.prefill.max_query_len,
                softmax_scale=self.scale,
                causal=True,
1202
1203
1204
                q_descale=None,
                k_descale=None,
                v_descale=None,
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
                return_softmax_lse=has_context,
            )
        else:
            output = self._flash_attn_varlen_diff_headdims(
                q=q,
                k=k,
                v=v,
                cu_seqlens_q=attn_metadata.prefill.query_start_loc,
                cu_seqlens_k=attn_metadata.prefill.query_start_loc,
                max_seqlen_q=attn_metadata.prefill.max_query_len,
                max_seqlen_k=attn_metadata.prefill.max_query_len,
                softmax_scale=self.scale,
                causal=True,
                q_descale=None,
                k_descale=None,
                v_descale=None,
                return_softmax_lse=has_context,
            )
1223
1224
1225
1226

        if has_context:
            suffix_output, suffix_lse = output
            context_output, context_lse = self._compute_prefill_context( \
yangql's avatar
yangql committed
1227
                q, kv_c_and_k_pe_cache, attn_metadata, kv_scale)
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237

            output = torch.empty_like(suffix_output)
            merge_attn_states(
                output=output,
                prefix_output=context_output,
                prefix_lse=context_lse,
                suffix_output=suffix_output,
                suffix_lse=suffix_lse,
            )

1238
1239
1240
1241
        # unpad if necessary
        if self._pad_v:
            output = output[..., :v.shape[-1]]

1242
        return output.flatten(start_dim=-2)
1243
1244
1245
1246

    @abstractmethod
    def _forward_decode(
        self,
1247
        ql_nope: torch.Tensor,
1248
1249
        q_pe: torch.Tensor,
        kv_c_and_k_pe_cache: torch.Tensor,
1250
        attn_metadata: M,
1251
1252
1253
1254
1255
1256
    ) -> torch.Tensor:
        raise NotImplementedError

    def forward(
        self,
        layer: AttentionLayer,
1257
        q: torch.Tensor,
1258
1259
1260
        k_c_normed: torch.Tensor,  # key in unified attn
        k_pe: torch.Tensor,  # value in unified attn
        kv_cache: torch.Tensor,
1261
        attn_metadata: M,
1262
        output: Optional[torch.Tensor] = None,
1263
        output_scale: Optional[torch.Tensor] = None,
1264
1265
        query_nope: Optional[torch.Tensor] = None,
        num_local_heads: Optional[int] = None,
1266
1267
1268
1269
1270
        q_ori: Optional[torch.Tensor] = None,
        key_normed: Optional[torch.Tensor] = None,
        positions: Optional[torch.Tensor] = None,
        weight: Optional[torch.Tensor] = None,
        cos_sin_cache: Optional[torch.Tensor] = None,
1271
1272
1273
1274
    ) -> torch.Tensor:

        assert output is not None, "Output tensor must be provided."

1275
1276
1277
1278
1279
        if output_scale is not None:
            raise NotImplementedError(
                "fused output quantization is not yet supported"
                " for MLACommonImpl")

1280
        if attn_metadata is None:
1281
1282
1283
1284
            # 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)
1285
1286
1287
1288
1289
1290

        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, ...]
1291
        q = q[:num_actual_toks, ...]
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
        k_c_normed = k_c_normed[:num_actual_toks, ...]
        k_pe = k_pe[:num_actual_toks, ...]

        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

        has_decode = attn_metadata.num_decodes > 0
        has_prefill = attn_metadata.num_prefills > 0
        num_decode_tokens = attn_metadata.num_decode_tokens
        prefill_k_pe = k_pe[num_decode_tokens:]
1303
1304
1305
1306
1307
1308
1309
1310
        if not envs.VLLM_USE_LIGHTOP_RMS_ROPE_CONCAT:
            decode_q = q[:num_decode_tokens]
            prefill_q = q[num_decode_tokens:]
            prefill_k_c_normed = k_c_normed[num_decode_tokens:]
        else:
            q_ori = q_ori[:num_actual_toks, ...]
            decode_q = q_ori[:num_decode_tokens]
            prefill_q = q_ori[num_decode_tokens:]
zhuwenwen's avatar
zhuwenwen committed
1311
1312
1313
1314
1315
1316
1317
1318
            
            if self.kv_cache_dtype == "auto":
                if q.dtype == torch.float16:
                    kv_cache_dtype_str = "fp16"
                elif q.dtype == torch.bfloat16:  
                    kv_cache_dtype_str = "bf16"
            else:
                kv_cache_dtype_str = self.kv_cache_dtype
1319

1320
1321
        k_c_normed_int8 = None
        k_c_normed_scale = None
1322
1323
        # write the latent and rope to kv cache
        if kv_cache.numel() > 0:
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
            if not envs.VLLM_USE_LIGHTOP_RMS_ROPE_CONCAT:
                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,
                )
            else:
1334
1335
1336
                if envs.VLLM_FUSED_RN_ROPE_INT8_QUANT:
                    k_c_normed_int8 = torch.empty((num_actual_toks, k_c_normed.size(-1)), dtype=torch.int8, device=q.device)
                    k_c_normed_scale = torch.empty((num_actual_toks, 1), dtype=torch.float32, device=q.device)
1337
1338
                if torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938" and kv_cache_dtype_str=="fp8_e4m3" and envs.VLLM_USE_FUSED_CACHE_QUANT_BMM_MLA:
                    if has_prefill:
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
                        if envs.VLLM_FUSED_RN_ROPE_INT8_QUANT:
                            from lightop import op
                            op.fused_rms_norm_rope_int8quant_contiguous(
                                positions[:num_actual_toks, ...],
                                q,
                                k_pe.squeeze(1),
                                k_c_normed, # not normed
                                key_normed[:num_actual_toks, ...], # normed
                                k_c_normed_int8,
                                k_c_normed_scale,
                                weight,
                                cos_sin_cache,
                                attn_metadata.slot_mapping.flatten(),
                                kv_cache,
                                kv_cache_dtype_str,
                                1.0,
                                False,
                                1e-6,
                            ) 
                        else:
                            fused_rms_norm_rope_contiguous(
                                positions[:num_actual_toks, ...],
                                q,
                                k_pe.squeeze(1),
                                k_c_normed, # not normed
                                key_normed[:num_actual_toks, ...], # normed
                                weight,
                                cos_sin_cache,
                                attn_metadata.slot_mapping.flatten(),
                                kv_cache,
                                kv_cache_dtype_str,
                                1.0,
                                False,
                                1e-6,
                            ) 
                    if has_decode:
                        q_tensor = torch.randn(q.shape[0], num_local_heads, self.qk_nope_head_dim + self.qk_rope_head_dim, dtype=q.dtype, device=q.device)
                        q_quant = torch.empty_like(q_tensor, dtype=torch.float8_e4m3fn, device=q.device)
                        q_scale = torch.empty(q.shape[0], dtype=torch.float32, device=q.device)
                        fuse_rmsnorm_rope_quant_qkv(
1379
                            positions[:num_actual_toks, ...],
1380
                            query_nope,
1381
                            q,
1382
1383
                            q_quant,
                            q_scale,
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
                            k_pe.squeeze(1),
                            k_c_normed, # not normed
                            key_normed[:num_actual_toks, ...], # normed
                            weight,
                            cos_sin_cache,
                            attn_metadata.slot_mapping.flatten(),
                            kv_cache,
                            kv_cache_dtype_str,
                            1.0,
                            False,
                            1e-6,
                        ) 
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
                else:
                    if envs.VLLM_FUSED_RN_ROPE_INT8_QUANT:
                        from lightop import op
                        op.fused_rms_norm_rope_int8quant_contiguous(
                            positions[:num_actual_toks, ...],
                            q,
                            k_pe.squeeze(1),
                            k_c_normed, # not normed
                            key_normed[:num_actual_toks, ...], # normed
                            k_c_normed_int8,
                            k_c_normed_scale,
                            weight,
                            cos_sin_cache,
                            attn_metadata.slot_mapping.flatten(),
                            kv_cache,
                            kv_cache_dtype_str,
                            1.0,
                            False,
                            1e-6,
                        ) 
                    else:
                        fused_rms_norm_rope_contiguous(
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
                            positions[:num_actual_toks, ...],
                            q,
                            k_pe.squeeze(1),
                            k_c_normed, # not normed
                            key_normed[:num_actual_toks, ...], # normed
                            weight,
                            cos_sin_cache,
                            attn_metadata.slot_mapping.flatten(),
                            kv_cache,
                            kv_cache_dtype_str,
                            1.0,
                            False,
                            1e-6,
                        ) 
1432
        if has_prefill:
1433
            curr_kv_quant = None
1434
            if envs.VLLM_USE_LIGHTOP_RMS_ROPE_CONCAT:
1435
1436
                prefill_k_c_normed = key_normed[:num_actual_toks, ...]
                prefill_k_c_normed = prefill_k_c_normed[num_decode_tokens:] 
1437
1438
            else:
                prefill_k_c_normed = k_c_normed[num_decode_tokens:]
1439

1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
            if envs.VLLM_FUSED_RN_ROPE_INT8_QUANT and prefill_k_c_normed is not None:
                if k_c_normed_int8 is not None and k_c_normed_scale is not None:
                    curr_kv_quant = [k_c_normed_int8[num_decode_tokens:], k_c_normed_scale[num_decode_tokens:]]
            output[num_decode_tokens:] = self._forward_prefill(
                prefill_q, 
                prefill_k_c_normed, 
                prefill_k_pe, 
                kv_cache,
                attn_metadata, 
                kv_scale=layer._k_scale,
                kv_quant_args=curr_kv_quant
            )
            
1453
        if has_decode:
1454
            assert attn_metadata.decode is not None
zhuwenwen's avatar
zhuwenwen committed
1455
            if torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938" and self.kv_cache_dtype=="fp8_e4m3" and envs.VLLM_USE_FUSED_CACHE_QUANT_BMM_MLA:
1456
                decode_q = q_quant[:num_decode_tokens]
1457
1458
1459
1460
1461
            decode_q_nope, decode_q_pe = decode_q.split(
                [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
            # Convert from (B, N, P) to (N, B, P)
            decode_q_nope = decode_q_nope.transpose(0, 1)
            # Multiply (N, B, P) x (N, P, L) -> (N, B, L)
1462
            # todo: bmm support
zhuwenwen's avatar
zhuwenwen committed
1463
            decode_ql_nope = torch.bmm(q_scale, decode_q_nope, self.W_UK_T) if torch.cuda.get_device_properties("cuda").gcnArchName.split(':')[0] == "gfx938" and self.kv_cache_dtype=="fp8_e4m3" and envs.VLLM_USE_FUSED_CACHE_QUANT_BMM_MLA else torch.bmm(decode_q_nope, self.W_UK_T) 
1464
1465
1466
            # Convert from (N, B, L) to (B, N, L)
            decode_ql_nope = decode_ql_nope.transpose(0, 1)

1467
            output[:num_decode_tokens] = self._forward_decode(
1468
                decode_ql_nope, decode_q_pe, kv_cache, attn_metadata, layer._q_scale, layer._k_scale, self.kv_cache_dtype)
1469

zhuwenwen's avatar
zhuwenwen committed
1470
        return output_padded