Skip to content

vllm.model_executor.layers.attention.mla_attention

MLA Common Components

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 relatively large, often near 1) and the data-movement friendly approach for "decode" (i.e. the ratio Sq / Skv is small, often near 0).

NOTE what we deem small and large is currently determined by if it is 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: * Use a single latent vector to represent the per-token entry of the KV cache. * 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 an example of both paths assuming batch size = 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] 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] W_O project v to h_t shape [N * V, H]

Compute Friendly Approach (i.e. "forward_mha"):

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

// MHA with QK headdim = P + R // V headdim = V // sdpa_o shape [Sq, N, V] sdpa_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 ) return sdpa_o @ W_O

in the actual code,

kv_b_proj is [W_UK; W_UV] concatenated per head q_b_proj is [W_UQ; W_QR] concatenated per head out_proj is W_O

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

Runtime q_c = h_t @ W_DQ q_nope = (q_c @ W_UQ).view(-1, N, P) ql_nope = einsum("snh,lnh->snl", q_nope, W_UK) 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 // sdpa_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 sdpa_o = scaled_dot_product_attention( torch.cat([ql_nope, q_pe], dim=-1), torch.cat([kv_c, k_pe], dim=-1), kv_c )

o = einsum("snl,lnv->snv", sdpa_o.reshape(-1, N, Lkv), W_UV) return o.view(-1, N * V) @ W_O

Chunked Prefill

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

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 fixed workspace size.

The chunked prefill approach is as follows:

W Workspace rows, i.e. the context rows we may gather at once, used to bound the memory usage

The context is scheduled per request: requests are packed in order, splitting the next request on an aligned boundary when needed to fill W. So a chunk covers a contiguous run of prefills and only ever the tokens and context rows of those prefills — attention, up-projection and merging are charged only to the requests it covers, and no chunk contains an empty context span. See plan_mla_context_chunks.

Only a chunk's first request can be a continuation, so accumulation performs at most one request-slice merge and one bulk write per chunk.

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

// 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, causal=True, return_softmax_lse=True )

// Compute attention with the already existing context. Shown for a single // request; with a batch, a chunk covers a run of requests and both q and the // gathered context below are sliced to that run. for chunk_idx in range(cdiv(C, W)): chunk_start = chunk_idx * W chunk_end = min(chunk_start + W, C) Sc = chunk_end - chunk_start 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,
    causal=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

Classes:

Functions:

MLAAttention

Bases: Module, AttentionLayerBase

Multi-Head Latent Attention layer.

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

This class takes query, and compressed key/value tensors as input. The class does the following:

  1. Store the input key and value tensors in the KV cache.
  2. Perform (multi-head/multi-query/grouped-query) attention.
  3. Return the output tensor.

Methods:

  • prepare_mqa_query –

    Write the KV cache, then absorb, concat (and DCP-gather) the MQA

_apply_lora_projection(x, out, *, is_query)

Add kv_b_proj adapters to the absorbed, head-major MLA projection.

_forward_dcp_decode(q, kv_cache, attn_metadata, gathered_context)

The attention output of a DCP ShardQ step's leading decode tokens (head-sharded query) on the DCP path: query gather, the DCP-local partials, LSE combine.

_gather_pcp_cache_inputs(kv_c_normed, k_pe, slot_mapping)

Gather into fixed-size buffers padded with PAD_SLOT_ID, so the cache write stays in the piecewise graph while the gather, which depends on the step's decode/prefill split, runs eagerly.

_prepare_mqa_query(mqa_q, qrep_decode, fused_q_heads=None, gather_query=True)

Absorb the MQA query (and, with gather_query, DCP-gather it).

prepare_mqa_query(q, kv_c_normed, k_pe)

Write the KV cache, then absorb, concat (and DCP-gather) the MQA query of all tokens ahead of forward, so this can overlap independent work such as the indexer. forward given the result skips its KV-cache write and attends with the leading rows, as MQA tokens come first. Only the symmetric-memory gather is moved: an NCCL gather could race concurrent collectives on the same communicator.

MLACommonBackend

Bases: AttentionBackend

Methods:

  • customize_spec –

    Per-token-head modes pack an inline fp32 scale pair after the

customize_spec(spec) classmethod

Per-token-head modes pack an inline fp32 scale pair after the latent data (single-sided: head_size_v == 0 for MLA).

MLACommonBaseImpl

Bases: MLAAttentionImpl[A], Generic[A]

Shared MLA base providing dense-MHA prefill (via the selected MLAPrefillBackend) for both dense and sparse impls; subclasses add decode (forward_mqa).

_concat_k_nope_k_pe(k_nope, k_pe)

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.

Parameters:

  • k_nope

    (Tensor) –

    Tensor of shape [..., nope_dim]

  • k_pe

    (Tensor) –

    Tensor to broadcast and concatenate, typically shape [..., 1, pe_dim] or [..., pe_dim]

Returns:

  • Tensor –

    Tensor of shape [..., nope_dim + pe_dim]

MLACommonImpl

Bases: MLACommonBaseImpl[M], Generic[M]

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

MLACommonMetadata dataclass

Bases: AttentionMetadata, Generic[D]

Metadata for MLACommon.

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

Attributes:

dcp_gathered_context property

The gathered context of a DCP ShardQ step, or None.

MLACommonMetadataBuilder

Bases: AttentionMetadataBuilder[M]

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

Methods:

build_for_cudagraph_capture(common_attn_metadata)

This method builds the metadata for full cudagraph capture. Currently, only decode is supported for full cudagraphs with MLA.

determine_prefill_query_data_type(vllm_config, model_dtype) staticmethod

Determine the query data type for prefill queries. Return FP8 dtype if cache is FP8 and prefill query quantization is enabled, else model dtype.

MLACommonPrefillMetadata dataclass

Prefill Specific Metadata

Classes:

  • ContextChunk –

    One workspace-sized slice of paged context for a run of prefills.

ContextChunk dataclass

One workspace-sized slice of paged context for a run of prefills.

QueryLenSupport

Bases: 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)

_ContextChunkPlan dataclass

Request-space layout of one context chunk, before tensors are built.

_DecodeConcatQuantFP8

Bases: QuantFP8

QuantFP8 variant that concatenates decode_ql_nope and decode_q_pe before quantization. When disabled, forward_native is compiled via torch.compile, fusing cat/reshape/quant/view together.

_make_forward(quant_fn)

Factory to create forward methods that concat before quantization.

_detect_output_quant_key(output, output_scale, output_block_scale, output_dim)

Detect the output quantization key from fusion pass parameters.

Returns the appropriate QuantKey, or None if no quantization is needed. Detection is based on output dtype and which scale tensors are present.

accumulate_mla_context_chunk(chunk, attn_output, attn_softmax_lse, output, output_lse, output_written=False)

Fold one chunk's partial into the running context partial.

Only the first request may be a continuation; its tokens are merged and the remaining token range is initialized.

Parameters:

  • chunk

    (ContextChunk) –

    The context chunk being folded in.

  • attn_output

    (Tensor) –

    The chunk's attention output.

  • attn_softmax_lse

    (Tensor) –

    The chunk's log-sum-exp values.

  • output

    (Tensor) –

    Running context partial, updated in place.

  • output_lse

    (Tensor) –

    Running log-sum-exp, updated in place.

  • output_written

    (bool, default: False ) –

    The chunk's attention output already landed in output[chunk.token_slice] because the backend was handed it as out, leaving only the lse to fold. Invalid for a continuation chunk, whose leading tokens must be merged rather than overwritten.

backend_supports_prefill_query_quantization() cached

Check if the selected MLA prefill backend supports query quantization.

Currently supported backends: - FlashInfer - TRT-LLM Ragged

Not supported: - FlashAttention (FA3/FA4) - Non-GB200 devices (FP8 prefill requires device capability 100)

build_mla_chunked_context_metadata(*, context_lens_cpu, prefill_query_start_loc_cpu, chunked_prefill_workspace, chunked_prefill_workspace_size, block_size, align_chunk_to_block, device, dcp_world_size, dcp_local_block_size, dcp_virtual_block_size, dcp_manager=None, align_indptr=False)

Build chunked-context metadata for an MLA prefill.

Shared by dense and sparse builders. Packs the prefill contexts into a flat list of workspace-sized per-request chunks and, under DCP, plans the per-rank interleaved local chunks the all-gather reduction consumes.

Parameters:

  • context_lens_cpu

    (Tensor) –

    Per-prefill context length (seq_len - query_len).

  • prefill_query_start_loc_cpu

    (Tensor) –

    Prefill query cumulative offsets (0-based).

  • chunked_prefill_workspace

    (Tensor) –

    Scratch buffer the context gather writes to.

  • chunked_prefill_workspace_size

    (int) –

    Row capacity of the workspace.

  • block_size

    (int) –

    KV cache page size for chunk-start alignment.

  • align_chunk_to_block

    (bool) –

    Round the chunk size down to block_size.

  • device

    (device) –

    Target device for the returned tensors.

  • dcp_world_size

    (int) –

    Decode-context-parallel world size (1 if disabled).

  • dcp_local_block_size

    (int) –

    Per-rank interleave block size for DCP.

  • dcp_virtual_block_size

    (int) –

    dcp_local_block_size * dcp_world_size.

  • dcp_manager

    (MLADCPManager | None, default: None ) –

    Shared MLA DCP collective manager.

  • align_indptr

    (bool, default: False ) –

    Align packed int32 indptr slices to 16 bytes for CuTe DSL.

Returns:

  • ChunkedContextMetadata | None –

    The chunked-context metadata, or None when no prefill has any context.

init_mla_context_partial(chunked_context, attn_output, attn_softmax_lse, num_tokens)

Allocate the running context partial over all prefill tokens.

Laid out like the chunk partials so the final whole-batch merge against the suffix partial sees matching head strides. Callers whose backend honors an out tensor already know that layout and can allocate directly, pairing it with neutralize_empty_context_partials.

neutralize_empty_context_partials(chunked_context, output, output_lse)

Neutralize the partial of every prefill that no chunk covers.

A prefill without context is never gathered, so nothing would write its rows; a zero output with an -inf lse carries no weight into the final merge against the suffix partial.

plan_mla_context_chunks(context_lens, row_budget, max_context_chunk, split_alignment, padded_rows)

Pack per-request contexts into workspace-sized chunks.

reorg_kvcache(allgatered_kv_c_normed, allgatered_k_pe, padded_local_chunk_seq_lens_lst, local_context_lens_allranks, local_starts, sum_seq_len, max_seq_len, toks)

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, ...]

Parameters:

  • allgatered_kv_c_normed

    (Tensor) –

    all-gathered, padded latent KV cache.

  • allgatered_k_pe

    (Tensor) –

    all-gathered, padded RoPE key cache.

  • padded_local_chunk_seq_lens_lst

    (list[int]) –

    local chunk context lengths under current CP rank.

  • local_context_lens_allranks

    (list[list[int]]) –

    local context lengths on each CP rank.

  • local_starts

    (list[int]) –

    per-request local offset into the context this chunk starts at.

  • sum_seq_len

    (int) –

    the sum of cp_chunk_seq_lens_lst.

  • max_seq_len

    (int) –

    the max value of cp_chunk_seq_lens_lst.

  • toks

    (int) –

    the number of tokens for local gather cache.

split_kv_b_proj(kv_b_proj, out_dtype, kv_lora_rank, num_heads, qk_nope_head_dim, v_head_dim)

Dequantize kv_b_proj and return W_UK [L,N,P], W_UV [L,N,V].

unified_mla_kv_cache_update(kv_c_normed, k_pe, layer_name, kv_cache_dtype, k_scale)

Returns a dummy that is passed to unified_attention to signal a side effect and the data dependency between them to ensure torch.compile preserves ordering.