[Attention][MLA] Per-request scheduling for MLA chunked context (#50613)
Signed-off-by: Matthew Bonanni <mbonanni@redhat.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 5
OpenAI Codex
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
e7b8d59460
commit
b38e111d3e
@@ -17,6 +17,9 @@ from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
)
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
|
||||
@@ -99,21 +102,19 @@ class AiterFlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
chunked = self._prefill_metadata.chunked_context
|
||||
out, lse = self.flash_attn_varlen_func(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
cu_seqlens_q=self._prefill_metadata.query_start_loc,
|
||||
cu_seqlens_k=chunked.cu_seq_lens[chunk_idx],
|
||||
max_seqlen_q=self._prefill_metadata.max_query_len,
|
||||
max_seqlen_k=chunked.max_seq_lens[chunk_idx],
|
||||
cu_seqlens_q=chunk.query_start_loc,
|
||||
cu_seqlens_k=chunk.cu_seq_lens,
|
||||
max_seqlen_q=chunk.max_query_len,
|
||||
max_seqlen_k=chunk.max_seq_len,
|
||||
softmax_scale=self.scale,
|
||||
causal=False,
|
||||
return_lse=True,
|
||||
|
||||
@@ -175,7 +175,7 @@ class MLAPrefillBackend(ABC):
|
||||
@abstractmethod
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
|
||||
@@ -27,7 +27,10 @@ from vllm.v1.attention.backends.mla.prefill.base import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.attention.mla_attention import MLADims
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
MLACommonPrefillMetadata,
|
||||
MLADims,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
|
||||
|
||||
if is_flash_attn_varlen_func_available():
|
||||
@@ -450,20 +453,19 @@ class FlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
return self._flash_attn_varlen_diff_headdims(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
cu_seqlens_q=self._prefill_metadata.query_start_loc,
|
||||
cu_seqlens_k=self._prefill_metadata.chunked_context.cu_seq_lens[chunk_idx],
|
||||
max_seqlen_q=self._prefill_metadata.max_query_len,
|
||||
max_seqlen_k=self._prefill_metadata.chunked_context.max_seq_lens[chunk_idx],
|
||||
cu_seqlens_q=chunk.query_start_loc,
|
||||
cu_seqlens_k=chunk.cu_seq_lens,
|
||||
max_seqlen_q=chunk.max_query_len,
|
||||
max_seqlen_k=chunk.max_seq_len,
|
||||
softmax_scale=self.scale,
|
||||
causal=False, # Context is unmasked
|
||||
return_softmax_lse=True,
|
||||
|
||||
@@ -150,8 +150,7 @@ class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
if has_context:
|
||||
chunked_context = prefill_metadata.chunked_context
|
||||
assert chunked_context is not None
|
||||
num_chunks = chunked_context.cu_seq_lens.shape[0]
|
||||
self._ensure_chunks(num_chunks, self._workspace_buffer)
|
||||
self._ensure_chunks(len(chunked_context.chunks), self._workspace_buffer)
|
||||
|
||||
num_qo_heads = self.num_heads
|
||||
num_kv_heads = num_qo_heads
|
||||
@@ -179,12 +178,10 @@ class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
if has_context:
|
||||
chunked_context = prefill_metadata.chunked_context
|
||||
assert chunked_context is not None
|
||||
for i in range(num_chunks):
|
||||
kv_indptr_chunk = chunked_context.cu_seq_lens[i]
|
||||
|
||||
self._prefill_chunks[i].plan(
|
||||
qo_indptr=qo_indptr,
|
||||
kv_indptr=kv_indptr_chunk,
|
||||
for chunk in chunked_context.chunks:
|
||||
self._prefill_chunks[chunk.index].plan(
|
||||
qo_indptr=chunk.query_start_loc,
|
||||
kv_indptr=chunk.cu_seq_lens,
|
||||
num_qo_heads=num_qo_heads,
|
||||
num_kv_heads=num_kv_heads,
|
||||
head_dim_qk=head_dim_qk,
|
||||
@@ -227,12 +224,12 @@ class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
attn_out, lse = self._prefill_chunks[chunk_idx].run(
|
||||
attn_out, lse = self._prefill_chunks[chunk.index].run(
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
|
||||
@@ -162,16 +162,13 @@ class TokenspeedMLAPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from tokenspeed_mla import tokenspeed_mla_prefill
|
||||
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
chunked = self._prefill_metadata.chunked_context
|
||||
|
||||
# See note in run_prefill_new_tokens — `v` is a split-view of `kv_nope`
|
||||
# in `_compute_prefill_context` and arrives non-contiguous.
|
||||
v = v.contiguous()
|
||||
@@ -180,15 +177,15 @@ class TokenspeedMLAPrefillBackend(MLAPrefillBackend):
|
||||
query=q,
|
||||
key=k,
|
||||
value=v,
|
||||
seq_lens=chunked.seq_lens[chunk_idx],
|
||||
cum_seq_lens=chunked.cu_seq_lens[chunk_idx],
|
||||
max_seq_len=chunked.max_seq_lens[chunk_idx],
|
||||
batch_size=chunked.seq_lens[chunk_idx].shape[0],
|
||||
seq_lens=chunk.seq_lens,
|
||||
cum_seq_lens=chunk.cu_seq_lens,
|
||||
max_seq_len=chunk.max_seq_len,
|
||||
batch_size=chunk.num_requests,
|
||||
softmax_scale=self.scale,
|
||||
is_causal=False,
|
||||
return_lse=True,
|
||||
cum_seq_lens_q=self._prefill_metadata.query_start_loc,
|
||||
max_seq_len_q=self._prefill_metadata.max_query_len,
|
||||
cum_seq_lens_q=chunk.query_start_loc,
|
||||
max_seq_len_q=chunk.max_query_len,
|
||||
enable_pdl=False,
|
||||
)
|
||||
|
||||
|
||||
@@ -143,16 +143,13 @@ class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
|
||||
|
||||
def run_prefill_context_chunk(
|
||||
self,
|
||||
chunk_idx: int,
|
||||
chunk: "MLACommonPrefillMetadata.ContextChunk",
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from flashinfer.prefill import trtllm_ragged_attention_deepseek
|
||||
|
||||
assert self._prefill_metadata.chunked_context is not None
|
||||
assert self._prefill_metadata.chunked_context.seq_lens[chunk_idx] is not None
|
||||
|
||||
out = torch.empty(
|
||||
q.shape[0],
|
||||
q.shape[1],
|
||||
@@ -166,20 +163,16 @@ class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
|
||||
key=k,
|
||||
value=v,
|
||||
workspace_buffer=self._workspace_buffer,
|
||||
seq_lens=self._prefill_metadata.chunked_context.seq_lens[chunk_idx],
|
||||
max_q_len=self._prefill_metadata.max_query_len,
|
||||
max_kv_len=self._prefill_metadata.chunked_context.max_seq_lens[chunk_idx],
|
||||
seq_lens=chunk.seq_lens,
|
||||
max_q_len=chunk.max_query_len,
|
||||
max_kv_len=chunk.max_seq_len,
|
||||
bmm1_scale=self.scale,
|
||||
bmm2_scale=1.0,
|
||||
o_sf_scale=1.0,
|
||||
batch_size=self._prefill_metadata.chunked_context.seq_lens[chunk_idx].shape[
|
||||
0
|
||||
],
|
||||
batch_size=chunk.num_requests,
|
||||
window_left=-1,
|
||||
cum_seq_lens_q=self._prefill_metadata.query_start_loc,
|
||||
cum_seq_lens_kv=self._prefill_metadata.chunked_context.cu_seq_lens[
|
||||
chunk_idx
|
||||
],
|
||||
cum_seq_lens_q=chunk.query_start_loc,
|
||||
cum_seq_lens_kv=chunk.cu_seq_lens,
|
||||
enable_pdl=False,
|
||||
is_causal=False,
|
||||
return_lse=True,
|
||||
|
||||
@@ -9,118 +9,6 @@ from vllm.triton_utils import tl, triton
|
||||
float8_info = torch.finfo(current_platform.fp8_dtype())
|
||||
|
||||
|
||||
def mask_empty_context(
|
||||
lse: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
context_start_loc: torch.Tensor,
|
||||
) -> None:
|
||||
"""Neutralize context chunks that cover no keys before merging.
|
||||
|
||||
A prefill query whose context chunk is empty attended to no keys, so its
|
||||
partial attention is undefined: the backend leaves the output rows as
|
||||
uninitialized scratch (which may hold NaN/Inf) even when it reports an LSE
|
||||
of -inf. Sanitize both here so ``merge_attn_states`` can stay generic:
|
||||
force the LSE to -inf (zero softmax weight) and zero the undefined output
|
||||
rows (so a zero weight cannot combine with NaN/Inf). Emptiness is derived
|
||||
from the context offsets, not from the -inf LSE, so no merge kernel has to
|
||||
reason about undefined partials.
|
||||
|
||||
Args:
|
||||
lse: Chunk log-sum-exp, shape [num_heads, num_tokens].
|
||||
output: Chunk attention output, shape [num_tokens, num_heads, ...].
|
||||
query_start_loc: Prefill query cumulative offsets, shape [num_reqs + 1].
|
||||
context_start_loc: Chunk context cumulative offsets,
|
||||
shape [num_reqs + 1]; an empty chunk has a zero-length span.
|
||||
"""
|
||||
num_heads, num_tokens = lse.shape
|
||||
num_reqs = query_start_loc.shape[0] - 1
|
||||
block_size = 128
|
||||
# Reserve the worst-case number of request-local blocks.
|
||||
num_query_blocks = num_tokens // block_size + num_reqs
|
||||
is_empty = torch.zeros(num_tokens, dtype=torch.bool, device=lse.device)
|
||||
mask_empty_context_kernel[(num_query_blocks,)](
|
||||
lse,
|
||||
is_empty,
|
||||
query_start_loc,
|
||||
context_start_loc,
|
||||
lse.stride(0),
|
||||
lse.stride(1),
|
||||
num_reqs,
|
||||
NUM_HEADS=num_heads,
|
||||
BLOCK_SIZE=block_size,
|
||||
BLOCK_HEADS=8,
|
||||
num_warps=8,
|
||||
)
|
||||
output.masked_fill_(is_empty[:, None, None], 0.0)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def mask_empty_context_kernel(
|
||||
lse,
|
||||
is_empty,
|
||||
query_start_loc,
|
||||
context_start_loc,
|
||||
lse_head_stride,
|
||||
lse_token_stride,
|
||||
num_reqs,
|
||||
NUM_HEADS: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
BLOCK_HEADS: tl.constexpr,
|
||||
):
|
||||
query_block_idx = tl.program_id(0)
|
||||
|
||||
lanes = tl.arange(0, 32)
|
||||
chunk_start = 0
|
||||
req_idx = 0
|
||||
req_idx_found = False
|
||||
while (chunk_start < num_reqs) & (not req_idx_found):
|
||||
req_offsets = chunk_start + lanes
|
||||
req_mask = req_offsets < num_reqs
|
||||
query_starts = tl.load(query_start_loc + req_offsets, mask=req_mask)
|
||||
# Assume the worst-case number of blocks for each request.
|
||||
req_block_starts = query_starts // BLOCK_SIZE + req_offsets
|
||||
matched_idx = tl.sum(
|
||||
(req_mask & (req_block_starts <= query_block_idx)).to(tl.int32)
|
||||
)
|
||||
# matched_idx == 32 means the match is past this warp chunk.
|
||||
req_idx = chunk_start + matched_idx - 1
|
||||
req_idx_found = matched_idx < 32
|
||||
chunk_start += 32
|
||||
|
||||
query_start = tl.load(query_start_loc + req_idx)
|
||||
query_end = tl.load(query_start_loc + req_idx + 1)
|
||||
query_len = query_end - query_start
|
||||
req_first_block = query_start // BLOCK_SIZE + req_idx
|
||||
block_in_req = query_block_idx - req_first_block
|
||||
token_offset = block_in_req * BLOCK_SIZE
|
||||
if token_offset >= query_len:
|
||||
return
|
||||
|
||||
context_start = tl.load(context_start_loc + req_idx)
|
||||
context_end = tl.load(context_start_loc + req_idx + 1)
|
||||
if context_start != context_end:
|
||||
return
|
||||
|
||||
token_offsets = token_offset + tl.arange(0, BLOCK_SIZE)
|
||||
token_indices = query_start + token_offsets
|
||||
token_lse_offsets = token_indices * lse_token_stride
|
||||
valid_tokens = token_offsets < query_len
|
||||
tl.store(is_empty + token_indices, True, mask=valid_tokens)
|
||||
head_offsets = tl.arange(0, BLOCK_HEADS)
|
||||
for head_start in range(0, NUM_HEADS, BLOCK_HEADS):
|
||||
head_indices = head_start + head_offsets
|
||||
lse_ptrs = (
|
||||
lse + head_indices[:, None] * lse_head_stride + token_lse_offsets[None, :]
|
||||
)
|
||||
valid_heads = head_indices < NUM_HEADS
|
||||
tl.store(
|
||||
lse_ptrs,
|
||||
float("-inf"),
|
||||
mask=valid_heads[:, None] & valid_tokens[None, :],
|
||||
)
|
||||
|
||||
|
||||
# Implements section 2.2 of https://www.arxiv.org/pdf/2501.01005
|
||||
# can be used to combine partial attention results (in the split-KV case)
|
||||
def merge_attn_states(
|
||||
@@ -317,8 +205,7 @@ def merge_attn_states_kernel(
|
||||
s_scale = s_se / out_se
|
||||
out = p_out * p_scale + s_out * s_scale
|
||||
# If both sides are empty (max_lse == -inf) the scales are 0/0 = NaN; emit
|
||||
# zeros rather than NaN. Callers with empty chunks (see mask_empty_context)
|
||||
# zero those inputs, so this only guards the fully-undefined corner.
|
||||
# zeros rather than NaN.
|
||||
out = tl.where(max_lse == float("-inf"), 0.0, out)
|
||||
|
||||
if USE_FP8:
|
||||
|
||||
Reference in New Issue
Block a user