Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-03 21:59:03 +07:00
1012 changed files with 61873 additions and 14499 deletions
+5 -1
View File
@@ -987,7 +987,11 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
scheduler_metadata = self._store_scheduler_metadata(scheduler_metadata)
if isinstance(causal, torch.Tensor) and causal.dtype != torch.int32:
causal = causal.to(torch.int32)
raise ValueError(
f"Per-request causal tensor must be int32, got {causal.dtype}. "
"Casting here would allocate a fresh tensor each build() and "
"break FULL CUDA graph replay; allocate the buffer as int32."
)
attn_metadata = FlashAttentionMetadata(
num_actual_tokens=num_actual_tokens,
+10
View File
@@ -860,6 +860,13 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self.use_trtllm_gen_varlen_decode = self._uses_trtllm_gen_varlen_decode(
vllm_config, self.flashinfer_trtllm_api_decode_kernel, self.use_dcp
)
# Fused draft steps advance seq_lens in place and keep block tables fixed,
# so one trtllm-gen decode build serves every step (not DCP-local seq_lens).
self.supports_draft_decode_metadata_update = (
self.flashinfer_trtllm_api_decode_kernel
== FlashInferDecodeKernel.TRTLLM_GEN
and not self.use_dcp
)
self._init_reorder_batch_threshold(
1,
supports_spec_as_decode=(
@@ -1837,6 +1844,9 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
attn_metadata.decode = FIDecode(wrapper=decode_wrapper)
return attn_metadata
def update_draft_decode_metadata(self, _metadata: FlashInferMetadata) -> None:
pass
def use_cascade_attention(self, *args, **kwargs) -> bool:
if self.kv_cache_spec.dtype != self.vllm_config.model_config.dtype:
# TODO: The cascade wrapper currently does not support setting
+33 -5
View File
@@ -8,6 +8,10 @@ from typing import Literal
import torch
from vllm.config import VllmConfig
from vllm.model_executor.layers.mamba.checkpoint import (
MambaPrefillCheckpointBuilder,
MambaPrefillCheckpointMetadata,
)
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.attention.backend import (
AttentionBackend,
@@ -48,6 +52,7 @@ class GDNAttentionMetadata:
num_spec_decode_tokens: int
num_actual_tokens: int
checkpoint: MambaPrefillCheckpointMetadata | None = None
has_initial_state: torch.Tensor | None = None
spec_query_start_loc: torch.Tensor | None = None # shape: [num_spec_decodes + 1,]
@@ -97,6 +102,9 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
self.compilation_config = vllm_config.compilation_config
self.speculative_config = vllm_config.speculative_config
self.checkpoint_builder = MambaPrefillCheckpointBuilder(
vllm_config, kv_cache_spec
)
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
_resolve_gdn_prefill_backend,
)
@@ -353,9 +361,10 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
non_spec_token_indx = torch.empty(
0, dtype=torch.int32, device=query_start_loc.device
)
# Filter by spec_sequence_masks to exclude padded sequences
# Padded sequences trail the spec decodes, so slice them off
# rather than gather with the host mask (an H2D copy + a kernel).
spec_state_indices_tensor = block_table_tensor[
spec_sequence_masks_cpu, : self.num_spec + 1
:num_spec_decodes, : self.num_spec + 1
]
non_spec_state_indices_tensor = None
# Padded sequences are always at the back, so the first
@@ -413,7 +422,10 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
)
assert num_accepted_tokens is not None
num_accepted_tokens = num_accepted_tokens[spec_sequence_masks_cpu]
if num_prefills == 0 and num_decodes == 0:
num_accepted_tokens = num_accepted_tokens[:num_spec_decodes]
else:
num_accepted_tokens = num_accepted_tokens[spec_sequence_masks_cpu]
chunk_indices: torch.Tensor | None = None
chunk_offsets: torch.Tensor | None = None
@@ -466,6 +478,13 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
else:
has_initial_state = None
checkpoint: MambaPrefillCheckpointMetadata | None = None
if num_prefills > 0:
request_rows = list(range(m.num_reqs))
if spec_sequence_masks_cpu is not None:
request_rows = (~spec_sequence_masks_cpu).nonzero().flatten().tolist()
checkpoint = self.checkpoint_builder.build(m, request_rows)
# Function code counted on either presency non-spec decode or spec decode,
# but not both.
assert not (num_decodes > 0 and num_spec_decodes > 0), (
@@ -543,6 +562,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
num_spec_decodes=num_spec_decodes,
num_spec_decode_tokens=num_spec_decode_tokens,
num_actual_tokens=m.num_actual_tokens,
checkpoint=checkpoint,
has_initial_state=has_initial_state,
chunk_indices=chunk_indices,
chunk_offsets=chunk_offsets,
@@ -601,6 +621,11 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
"""Re-gather this group's state indices. The other fields are
batch-level and stay shared with ``metadata``."""
m = metadata
checkpoint = (
m.checkpoint.regather_state_indices(blk_table)
if m.checkpoint is not None
else None
)
if self.vllm_config.cache_config.mamba_cache_mode == "align":
assert self.mamba_aligned_state_indices is not None
blk_table = self.mamba_aligned_state_indices
@@ -610,10 +635,12 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
non_spec_indices = blk_table[:, 0]
if m.num_prefills > 0:
prefill_indices = non_spec_indices[m.num_decodes :]
elif m.num_prefills == 0:
# Same as build(): padded sequences trail the spec decodes.
spec_indices = blk_table[: m.num_spec_decodes, : self.num_spec + 1]
else:
spec_indices = blk_table[masks, : self.num_spec + 1]
if m.num_prefills > 0:
non_spec_indices = prefill_indices = blk_table[~masks, 0]
non_spec_indices = prefill_indices = blk_table[~masks, 0]
if self._stage_spec_decode(
m.num_prefills, m.num_decodes, m.num_spec_decodes, m.num_spec_decode_tokens
@@ -640,6 +667,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
spec_state_indices_tensor=spec_indices,
non_spec_state_indices_tensor=non_spec_indices,
prefill_state_indices=prefill_indices,
checkpoint=checkpoint,
)
def build_for_cudagraph_capture(
+2 -21
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass, replace
from dataclasses import dataclass
from typing import Any
from vllm.v1.attention.backend import AttentionBackend, CommonAttentionMetadata
@@ -42,23 +42,4 @@ class Mamba1AttentionMetadataBuilder(
fast_build: bool = False,
**kwargs: Any,
) -> Mamba1AttentionMetadata:
common = self._compute_common_metadata(common_attn_metadata)
if (
common.num_prefills > 0
and self.vllm_config.cache_config.mamba_cache_mode == "all"
):
cu_chunk_seqlen_p, _, last_chunk_indices_p = (
self._build_chunk_metadata_tensors(
self.kv_cache_spec.block_size,
common,
common_attn_metadata,
)
)
return replace(
common,
cu_chunk_seqlen_p=cu_chunk_seqlen_p,
last_chunk_indices_p=last_chunk_indices_p,
)
return common
return self._compute_common_metadata(common_attn_metadata)
@@ -139,7 +139,6 @@ class Mamba2AttentionMetadataBuilder(
common = self._compute_common_metadata(
common_attn_metadata,
num_accepted_tokens=kwargs.get("num_accepted_tokens"),
prev_last_scheduled_idx=kwargs.get("prev_last_scheduled_idx"),
num_decode_draft_tokens_cpu=kwargs.get("num_decode_draft_tokens_cpu"),
)
+52 -257
View File
@@ -39,7 +39,6 @@ class BaseMambaAttentionMetadata:
# the batch has no prefill requests.
has_initial_states_p: torch.Tensor | None
query_start_loc_p: torch.Tensor | None
num_computed_tokens_p: torch.Tensor | None
state_indices_tensor_p: torch.Tensor | None
# The following tensors are used for decode requests and
@@ -52,13 +51,6 @@ class BaseMambaAttentionMetadata:
# Includes the bonus token (so minimum is 1)
num_accepted_tokens: torch.Tensor | None # shape: [batch,]
# The following tensors are only used for prefix caching in all mode and
# are None if disabled
block_idx_last_scheduled_token: torch.Tensor | None
block_idx_first_scheduled_token_p: torch.Tensor | None
block_idx_last_computed_token: torch.Tensor | None
block_idx_last_scheduled_token_prev_step: torch.Tensor | None
# The following tensor is only used for prefix caching in align mode
seq_lens: torch.Tensor
@@ -70,9 +62,6 @@ class BaseMambaAttentionMetadata:
# last_chunk_indices_p is a tensor of shape (batch,) that contains the
# index of the last chunk for every sequence in the (prefill) batch.
last_chunk_indices_p: torch.Tensor | None = None
# Number of block-aligned SSM states the prefill path writes, i.e.
# sum(block_idx_last_scheduled_token_p - block_idx_first_scheduled_token_p).
num_state_writes_p: int = 0
# The following attributes are for triton implementation of causal_conv1d
nums_dict: dict | None = None
@@ -87,6 +76,8 @@ class BaseMambaAttentionMetadata:
bc_pre_scratch: torch.Tensor | None = None
# ReplaySSM — FlashInfer checkpointing_ssu two-kernel scratch.
replayssm_scratch: tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None = None
# Contiguous cache-slot indices shared by all FlashInfer ReplaySSM layers.
replayssm_state_indices_d: torch.Tensor | None = None
class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
@@ -133,47 +124,11 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
self.compilation_config.max_cudagraph_capture_size,
)
if self.vllm_config.cache_config.mamba_cache_mode == "all":
max_num_blocks = (
cdiv(
self.vllm_config.model_config.max_model_len,
kv_cache_spec.block_size,
)
+ kv_cache_spec.num_speculative_blocks
)
# TODO: reduce this size as needed for decode-only cudagraph capture
self.state_indices_tensor_d: torch.Tensor = torch.empty(
(
self.decode_cudagraph_max_bs,
max_num_blocks,
),
dtype=torch.int32,
device=device,
)
self.block_idx_last_scheduled_token: torch.Tensor = torch.empty(
(self.decode_cudagraph_max_bs,),
dtype=torch.int32,
device=device,
)
self.block_idx_last_computed_token: torch.Tensor = torch.empty(
(self.decode_cudagraph_max_bs,),
dtype=torch.int32,
device=device,
)
if self.use_spec_decode:
self.block_idx_last_scheduled_token_prev_step: torch.Tensor = (
torch.empty(
(self.decode_cudagraph_max_bs,),
dtype=torch.int32,
device=device,
)
)
else:
self.state_indices_tensor_d = torch.empty(
(self.decode_cudagraph_max_bs, 1 + self.num_spec_tokens),
dtype=torch.int32,
device=device,
)
self.state_indices_tensor_d = torch.empty(
(self.decode_cudagraph_max_bs, 1 + self.num_spec_tokens),
dtype=torch.int32,
device=device,
)
# For speculative decoding, we need to store the following buffers
# for CUDA graph capture during decode
@@ -187,6 +142,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
self.decode_replayssm_scratch: (
tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None
) = None
self.decode_replayssm_state_indices_d: torch.Tensor | None = None
# ReplaySSM CUDA-graph buffers for the selected backend.
if self.use_replayssm and not self.use_flashinfer_replayssm:
self.decode_write_pos_d: torch.Tensor = torch.empty(
@@ -223,11 +179,17 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
self.decode_replayssm_scratch = allocate_checkpointing_ssu_scratch(
batch_size=scheduler_config.max_num_seqs,
num_heads=nheads,
num_predicted_tokens=1,
num_predicted_tokens=1 + self.num_spec_tokens,
max_window=self.replayssm_buffer_len,
dtype=vllm_config.model_config.dtype,
device=device,
)
# Full CUDA graphs retain capture-time tensor addresses. Keep the
# contiguous first-column view used by FlashInfer in a persistent
# buffer and refresh its contents before each replay.
self.decode_replayssm_state_indices_d = torch.empty(
(self.decode_cudagraph_max_bs,), dtype=torch.int32, device=device
)
self._init_reorder_batch_threshold(1, self.use_spec_decode)
if self.use_spec_decode:
@@ -255,23 +217,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
if self.num_spec_tokens > 0:
num_accepted_tokens = torch.diff(m.query_start_loc)
prev_last_scheduled_idx = None
if (
self.use_spec_decode
and self.vllm_config.cache_config.mamba_cache_mode == "all"
):
prev_last_scheduled_idx = torch.zeros(
(m.num_reqs,),
dtype=torch.int32,
device=m.query_start_loc.device,
)
return self.build(
0,
m,
num_accepted_tokens=num_accepted_tokens,
prev_last_scheduled_idx=prev_last_scheduled_idx,
)
return self.build(0, m, num_accepted_tokens=num_accepted_tokens)
def build(
self,
@@ -280,7 +226,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
fast_build: bool = False,
*,
num_accepted_tokens: torch.Tensor | None = None,
prev_last_scheduled_idx: torch.Tensor | None = None,
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
**kwargs: Any,
) -> M:
@@ -290,7 +235,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
return self._compute_common_metadata(
common_attn_metadata,
num_accepted_tokens=num_accepted_tokens,
prev_last_scheduled_idx=prev_last_scheduled_idx,
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
)
@@ -419,56 +363,11 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
)
return cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p
def _compute_prefix_caching_block_indices(
self,
common_attn_metadata: CommonAttentionMetadata,
mamba_block_size: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
# Block index of the last computed token
block_idx_last_computed_token = (
torch.div(
num_computed_tokens + mamba_block_size - 1,
mamba_block_size,
rounding_mode="floor",
)
- 1
)
# which is <= block index for the first scheduled token
block_idx_first_scheduled_token = (
torch.div(
num_computed_tokens + mamba_block_size,
mamba_block_size,
rounding_mode="floor",
)
- 1
)
# which is <= block index of the last scheduled token
block_idx_last_scheduled_token = (
torch.div(
common_attn_metadata.seq_lens + mamba_block_size - 1,
mamba_block_size,
rounding_mode="floor",
)
- 1
)
# -1 in case it's non-computed and causes later issues with indexing
block_idx_last_computed_token.clamp_(min=0)
# -1 in the case we have a padded request (0 seq-len)
block_idx_last_scheduled_token.clamp_(min=0)
return (
block_idx_last_computed_token,
block_idx_first_scheduled_token,
block_idx_last_scheduled_token,
)
def _compute_common_metadata(
self,
common_attn_metadata: CommonAttentionMetadata,
*,
num_accepted_tokens: torch.Tensor | None = None,
prev_last_scheduled_idx: torch.Tensor | None = None,
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
) -> M:
"""Compute metadata common to both Mamba1 and Mamba2."""
@@ -536,16 +435,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
has_initial_states_p = None
query_start_loc_p = None
query_start_loc_d = None
num_computed_tokens = None
num_computed_tokens_p = None
# for prefix caching
block_idx_first_scheduled_token = None
block_idx_first_scheduled_token_p = None
block_idx_last_computed_token = None
block_idx_last_scheduled_token = None
block_idx_last_scheduled_token_prev_step = None
num_state_writes_p = 0
# for causal_conv1d
nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None
@@ -553,35 +442,12 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
is_flush_d = None
replayssm_scratch = None
if self.vllm_config.cache_config.mamba_cache_mode == "all":
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
# Return a tensor of shape (#requests, #max blocks)
state_indices_tensor = common_attn_metadata.block_table_tensor
# Additional cache-related variables:
mamba_block_size = self.kv_cache_spec.block_size
(
block_idx_last_computed_token,
block_idx_first_scheduled_token,
block_idx_last_scheduled_token,
) = self._compute_prefix_caching_block_indices(
common_attn_metadata, mamba_block_size
)
if self.use_spec_decode and prev_last_scheduled_idx is not None:
fallback = (num_computed_tokens - 1) // mamba_block_size
fallback.clamp_(min=0)
block_idx_last_scheduled_token_prev_step = torch.where(
prev_last_scheduled_idx >= 0,
prev_last_scheduled_idx,
fallback,
)
else:
state_indices_tensor = mamba_get_block_table_tensor(
common_attn_metadata.block_table_tensor,
common_attn_metadata.seq_lens,
self.kv_cache_spec,
self.vllm_config.cache_config.mamba_cache_mode,
)
state_indices_tensor = mamba_get_block_table_tensor(
common_attn_metadata.block_table_tensor,
common_attn_metadata.seq_lens,
self.kv_cache_spec,
self.vllm_config.cache_config.mamba_cache_mode,
)
if state_indices_tensor.dim() == 1:
state_indices_tensor = state_indices_tensor.unsqueeze(-1)
@@ -591,23 +457,22 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
[num_decodes, num_prefills],
dim=0,
)
if self.vllm_config.cache_config.mamba_cache_mode != "all":
state_indices_tensor_d = state_indices_tensor_d[
:, : 1 + self.num_spec_tokens
]
state_indices_tensor_p = state_indices_tensor_p[:, 0]
state_indices_tensor_d = state_indices_tensor_d[:, : 1 + self.num_spec_tokens]
state_indices_tensor_p = state_indices_tensor_p[:, 0]
# Sometimes even with specdec enabled we get single-token prefill chunks that
# should be treated as decodes but don't have num_accepted_tokens set.
# These should be fine to process as non-spec decodes since there's only
# one token, so no risk of placing accepted tokens in the wrong slot.
if num_decodes > 0 and self.use_spec_decode and num_accepted_tokens is not None:
if num_decodes > 0 and self.use_spec_decode:
query_start_loc_d = common_attn_metadata.query_start_loc[: num_decodes + 1]
num_accepted_tokens = num_accepted_tokens[:num_decodes]
if num_accepted_tokens is None:
# Single-token prefill chunks can be reclassified as decodes before
# speculative decoding has produced acceptance counts. Treat each
# token as accepted so recurrent state and ReplaySSM trackers follow
# the normal speculative-decode path.
num_accepted_tokens = torch.diff(query_start_loc_d)
else:
num_accepted_tokens = num_accepted_tokens[:num_decodes]
if num_prefills > 0:
if num_computed_tokens is None:
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
query_start_loc_p = (
common_attn_metadata.query_start_loc[-num_prefills - 1 :]
@@ -629,33 +494,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
)
)
if self.vllm_config.cache_config.mamba_cache_mode == "all":
assert num_computed_tokens is not None
num_computed_tokens_p = num_computed_tokens[
num_reqs - num_prefills : num_reqs
]
assert block_idx_first_scheduled_token is not None
block_idx_first_scheduled_token_p = block_idx_first_scheduled_token[
num_reqs - num_prefills : num_reqs
]
# How many block-aligned states prefill will write: the same
# (block_idx_last - block_idx_first) as above, from CPU data so
# the mixer needs no D2H read. The -1 in both indices cancels.
block_size = self.kv_cache_spec.block_size
seq_lens_p_cpu = seq_lens_cpu[num_reqs - num_prefills : num_reqs]
num_computed_tokens_p_cpu, _ = self._prefill_cpu_metadata(
common_attn_metadata, num_reqs, num_prefills, num_decode_tokens
)
num_state_writes_p = int(
(
(seq_lens_p_cpu + block_size - 1) // block_size
- (num_computed_tokens_p_cpu + block_size) // block_size
)
.clamp(min=0)
.sum()
)
if self.use_replayssm and not self.use_flashinfer_replayssm and num_decodes > 0:
decode_base_cpu = common_attn_metadata.replayssm_decode_base_cpu
seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound
@@ -757,14 +595,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
replayssm_scratch=replayssm_scratch,
num_accepted_tokens=num_accepted_tokens,
query_start_loc_d=query_start_loc_d,
block_idx_last_scheduled_token=block_idx_last_scheduled_token,
block_idx_first_scheduled_token_p=block_idx_first_scheduled_token_p,
num_state_writes_p=num_state_writes_p,
block_idx_last_computed_token=block_idx_last_computed_token,
block_idx_last_scheduled_token_prev_step=(
block_idx_last_scheduled_token_prev_step
),
num_computed_tokens_p=num_computed_tokens_p,
num_reqs=num_reqs,
seq_lens=common_attn_metadata.seq_lens,
nums_dict=nums_dict,
@@ -784,15 +614,11 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
state_indices_tensor_d = metadata.state_indices_tensor_d
query_start_loc_d = metadata.query_start_loc_d
num_accepted_tokens = metadata.num_accepted_tokens
block_idx_last_scheduled_token = metadata.block_idx_last_scheduled_token
block_idx_last_computed_token = metadata.block_idx_last_computed_token
block_idx_last_scheduled_token_prev_step = (
metadata.block_idx_last_scheduled_token_prev_step
)
write_pos_d = metadata.write_pos_d
is_flush_d = metadata.is_flush_d
bc_pre_scratch = metadata.bc_pre_scratch
replayssm_scratch = metadata.replayssm_scratch
replayssm_state_indices_d = None
if (
metadata.num_prefills == 0
and metadata.num_decodes <= self.decode_cudagraph_max_bs
@@ -816,44 +642,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
1 # pad with 1st slot index
)
if self.vllm_config.cache_config.mamba_cache_mode == "all":
assert block_idx_last_scheduled_token is not None
assert block_idx_last_computed_token is not None
self.block_idx_last_scheduled_token[: metadata.num_decodes].copy_(
block_idx_last_scheduled_token[: metadata.num_decodes],
non_blocking=True,
)
block_idx_last_scheduled_token = self.block_idx_last_scheduled_token[
:padded_bs
]
block_idx_last_scheduled_token[metadata.num_decodes :] = 0
self.block_idx_last_computed_token[: metadata.num_decodes].copy_(
block_idx_last_computed_token[: metadata.num_decodes],
non_blocking=True,
)
block_idx_last_computed_token = self.block_idx_last_computed_token[
:padded_bs
]
block_idx_last_computed_token[metadata.num_decodes :] = 0
if (
self.use_spec_decode
and block_idx_last_scheduled_token_prev_step is not None
):
self.block_idx_last_scheduled_token_prev_step[
: metadata.num_decodes
].copy_(
block_idx_last_scheduled_token_prev_step[
: metadata.num_decodes
],
non_blocking=True,
)
block_idx_last_scheduled_token_prev_step = (
self.block_idx_last_scheduled_token_prev_step[:padded_bs]
)
block_idx_last_scheduled_token_prev_step[metadata.num_decodes :] = 0
if self.use_replayssm and not self.use_flashinfer_replayssm:
assert write_pos_d is not None
assert is_flush_d is not None
@@ -881,6 +669,20 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
cumAdt_vec[:padded_bs],
cb_old[:padded_bs],
)
assert self.decode_replayssm_state_indices_d is not None
self.decode_replayssm_state_indices_d[:padded_bs].copy_(
state_indices_tensor_d[:, 0], non_blocking=True
)
replayssm_state_indices_d = self.decode_replayssm_state_indices_d[
:padded_bs
]
if (
self.use_flashinfer_replayssm
and state_indices_tensor_d is not None
and replayssm_state_indices_d is None
):
replayssm_state_indices_d = state_indices_tensor_d[:, 0].contiguous()
return replace(
metadata,
@@ -891,11 +693,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
is_flush_d=is_flush_d,
bc_pre_scratch=bc_pre_scratch,
replayssm_scratch=replayssm_scratch,
block_idx_last_scheduled_token=block_idx_last_scheduled_token,
block_idx_last_computed_token=block_idx_last_computed_token,
block_idx_last_scheduled_token_prev_step=(
block_idx_last_scheduled_token_prev_step
),
replayssm_state_indices_d=replayssm_state_indices_d,
)
def update_block_table(
@@ -927,11 +725,8 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
[metadata.num_decodes, metadata.num_prefills],
dim=0,
)
if self.vllm_config.cache_config.mamba_cache_mode != "all":
state_indices_tensor_d = state_indices_tensor_d[
:, : 1 + self.num_spec_tokens
]
state_indices_tensor_p = state_indices_tensor_p[:, 0]
state_indices_tensor_d = state_indices_tensor_d[:, : 1 + self.num_spec_tokens]
state_indices_tensor_p = state_indices_tensor_p[:, 0]
new_metadata = replace(
metadata,
@@ -207,10 +207,11 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
outputs = []
if num_decode_tokens:
physical_topk, valid_counts = (
index_group.convert_decode_logical_to_physical_topk(
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
)
@@ -273,7 +273,6 @@ class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilde
"""Metadata builder for the SM100 TRT-LLM sparse MLA kernel."""
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
hisparse_supports_multi_token_decode: ClassVar[bool] = True
def __init__(
self,
@@ -502,10 +501,11 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
decode_lse: torch.Tensor | None = None
if num_decode_tokens > 0:
physical_topk, valid_counts = (
index_group.convert_decode_logical_to_physical_topk(
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
)
@@ -125,10 +125,11 @@ class FlashInferMLASparseSM120Impl(SparseMLACommonImpl[FlashInferMLASparseMetada
if num_decode_tokens:
topk_indices_physical = cast(
torch.Tensor,
index_group.convert_decode_logical_to_physical_topk(
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
),
)
@@ -443,10 +443,16 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
assert topk_indices_buffer is not None
hf_config = vllm_config.model_config.hf_text_config
assert hf_config.index_topk is not None
# fp8 KV cache is stored as uint8; plan() needs the logical dtype.
kv_plan_dtype = (
torch.float8_e4m3fn
if kv_cache_spec.dtype == torch.uint8
else kv_cache_spec.dtype
)
self.state = _SM90State(
device,
impl.num_heads,
kv_cache_spec.dtype,
kv_plan_dtype,
vllm_config.scheduler_config.max_num_batched_tokens,
topk_indices_buffer.shape[1],
kv_lora_rank=impl.kv_lora_rank,
@@ -317,7 +317,6 @@ class FlashMLASparseMetadataBuilder(
):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
require_uniform_decodes: ClassVar[bool] = True
hisparse_supports_multi_token_decode: ClassVar[bool] = True
metadata_cls = FlashMLASparseMetadata
def __init__(
@@ -490,6 +489,14 @@ class FlashMLASparseMetadataBuilder(
num_tokens - metadata.num_decode_tokens,
)
FP8Meta = FlashMLASparseMetadata.FP8SeparatePrefillDecode
# PCP decode sharding can leave a rank with only its collective-padding
# row when the global decode batch is smaller than the PCP world size.
# The row has no actual query tokens and must not be interpreted as a
# zero-length decode request by the sparse FP8 metadata builder.
if num_tokens == 0:
return FP8Meta()
decode_query_len = 0
active_num_decodes = num_decodes
if num_decodes > 0:
@@ -499,7 +506,6 @@ class FlashMLASparseMetadataBuilder(
active_num_decodes = num_decode_tokens // decode_query_len
assert active_num_decodes * decode_query_len == num_decode_tokens
FP8Meta = FlashMLASparseMetadata.FP8SeparatePrefillDecode
fp8_metadata = FP8Meta(
num_decodes=active_num_decodes,
num_prefills=num_prefills,
@@ -818,10 +824,11 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
num_decode_tokens = attn_metadata.num_decode_tokens
if num_decode_tokens > 0:
decode_topk, decode_lengths = (
index_group.convert_decode_logical_to_physical_topk(
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
)
@@ -1027,7 +1034,6 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
attn_metadata,
fp8_metadata.decode.kernel_metadata,
num_decodes,
fp8_metadata.decode.decode_query_len,
)
# Reshape q: (num_decode_tokens, num_heads, head_dim)
# -> (num_decodes, seq_len, num_heads, head_dim)
@@ -1267,16 +1273,14 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
attn_metadata: FlashMLASparseMetadata,
kernel_metadata: FlashMLASparseMetadata.FP8KernelMetadata,
num_decodes: int,
decode_query_len: int,
) -> torch.Tensor:
assert isinstance(self.index_group, HiSparseMLAIndexGroup)
physical_topk = self.index_group.convert_decode_logical_to_physical_topk(
physical_topk = self.index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
num_decodes=num_decodes,
decode_query_len=decode_query_len,
)
assert isinstance(physical_topk, torch.Tensor)
q = reshape_query_for_spec_decode(q, num_decodes)
+2 -108
View File
@@ -39,7 +39,6 @@ class SparseMLAIndexGroup:
logical_topk_indices: torch.Tensor
physical_topk_indices: torch.Tensor
valid_topk_counts: torch.Tensor
request_ids: torch.Tensor
side_stream: torch.Stream
logical_topk_ready: torch.Event
physical_topk_ready: torch.Event
@@ -230,12 +229,10 @@ class HiSparseMLAIndexGroup(SparseMLAIndexGroup):
*,
block_stride_rows: int | None,
return_valid_counts: bool,
req_id_per_token: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
cache = self.cache(layer_index)
num_tokens = logical_topk_indices.shape[0]
if req_id_per_token is None:
req_id_per_token = attn_metadata.req_id_per_token[:num_tokens]
req_id_per_token = attn_metadata.req_id_per_token[:num_tokens]
if num_tokens > self.physical_topk_indices.shape[0]:
# Prefill-sized batches do not fit the decode residency workspace.
# Non-resident prefills are staged before reaching this path.
@@ -259,107 +256,9 @@ class HiSparseMLAIndexGroup(SparseMLAIndexGroup):
logical_topk_indices=logical_topk_indices,
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
num_valid_rows=attn_metadata.query_start_loc[-1:],
)
def convert_decode_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
return_valid_counts: bool,
num_decodes: int | None = None,
decode_query_len: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
num_tokens = logical_topk_indices.shape[0]
if num_decodes is None:
num_decodes = attn_metadata.num_decodes
if decode_query_len is None:
decode_query_len = attn_metadata.decode_max_query_len
if decode_query_len == 1:
return self.convert_logical_to_physical_topk(
layer_index,
logical_topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=return_valid_counts,
req_id_per_token=self.request_ids[:num_decodes],
)
if num_tokens != num_decodes * decode_query_len:
query_start_loc = attn_metadata.query_start_loc[: num_decodes + 1]
physical_topk_indices = self.physical_topk_indices[: num_tokens + 1]
valid_topk_counts = self.valid_topk_counts[: num_tokens + 1]
request_ids = self.request_ids[:num_decodes]
cache = self.cache(layer_index)
source_block_table = cache.source_block_table
assert source_block_table is not None
for step in range(decode_query_len):
token_indices = query_start_loc[:-1] + step
active = (token_indices < query_start_loc[1:]) & (
token_indices < num_tokens
)
output_indices = torch.where(
active, token_indices, torch.full_like(token_indices, num_tokens)
).long()
token_indices = token_indices.clamp(0, num_tokens - 1).long()
step_topk = logical_topk_indices.index_select(
0, token_indices
).masked_fill(~active.unsqueeze(1), -1)
step_result = cache.swap_in(
request_ids,
block_table=source_block_table,
logical_topk_indices=step_topk,
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
)
if layer_index == 0:
if return_valid_counts:
step_indices, step_counts = step_result
valid_topk_counts.index_copy_(0, output_indices, step_counts)
else:
step_indices = step_result
physical_topk_indices.index_copy_(0, output_indices, step_indices)
physical_topk_indices = physical_topk_indices[:num_tokens]
if return_valid_counts:
return physical_topk_indices, valid_topk_counts[:num_tokens]
return physical_topk_indices
assert num_tokens == num_decodes * decode_query_len
logical_topk_by_request = logical_topk_indices.view(
num_decodes, decode_query_len, -1
)
physical_topk_by_request = self.physical_topk_indices[:num_tokens].view(
num_decodes, decode_query_len, -1
)
valid_topk_by_request = self.valid_topk_counts[:num_tokens].view(
num_decodes, decode_query_len
)
request_ids = self.request_ids[:num_decodes]
for step in range(decode_query_len):
cache = self.cache(layer_index)
source_block_table = cache.source_block_table
assert source_block_table is not None
cache.swap_in(
request_ids,
block_table=source_block_table,
logical_topk_indices=logical_topk_by_request[:, step],
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
attention_indices_out=(
physical_topk_by_request[:, step] if layer_index == 0 else None
),
valid_counts_out=(
valid_topk_by_request[:, step]
if layer_index == 0 and return_valid_counts
else None
),
)
physical_topk_indices = physical_topk_by_request.view(num_tokens, -1)
if return_valid_counts:
return physical_topk_indices, valid_topk_by_request.view(num_tokens)
return physical_topk_indices
def stage_prefill_rows(
self, layer_index: int, kv_cache: torch.Tensor, attn_metadata: Any
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -477,11 +376,6 @@ class SparseMLAIndexGroupBuilder:
dtype=torch.int32,
device=self.logical_topk_indices.device,
),
request_ids=torch.arange(
workspace_rows,
dtype=torch.int32,
device=self.logical_topk_indices.device,
),
side_stream=_create_side_stream(self.logical_topk_indices.device),
logical_topk_ready=_create_event(),
physical_topk_ready=_create_event(),
+61 -21
View File
@@ -51,7 +51,7 @@ from vllm.v1.kv_cache_interface import (
logger = init_logger(__name__)
# The DSA indexer K cache is always quantized; "auto" means fp8 (V3.2 layout)
# and mxfp4 is the opt-in Blackwell path.
# and mxfp4 is the opt-in Blackwell and gfx950 path.
DSA_INDEXER_KV_DTYPES = ("fp8", "mxfp4")
@@ -64,6 +64,28 @@ def dsa_indexer_uses_fp4(vllm_config: VllmConfig) -> bool:
f"sparse indexer (expected one of {DSA_INDEXER_KV_DTYPES})."
)
use_fp4 = kv_dtype == "mxfp4"
if use_fp4 and current_platform.is_rocm():
from vllm._aiter_ops import rocm_aiter_ops
from vllm.platforms.rocm import get_cdna_version
# Only DeepSeek-V4.1 is wired to the ROCm MXFP4 cache; other DSA models
# would silently keep their FP8 one.
model_config = vllm_config.model_config
if model_config is None or model_config.hf_config.model_type != "deepseek_v41":
raise ValueError(
"indexer_kv_dtype='mxfp4' on ROCm is only supported for "
"DeepSeek-V4.1-Flash."
)
if get_cdna_version() != 4:
raise ValueError(
"indexer_kv_dtype='mxfp4' on ROCm requires CDNA4 (MI350X/MI355X)."
)
if not rocm_aiter_ops.is_enabled():
raise ValueError(
"indexer_kv_dtype='mxfp4' on ROCm runs on aiter's kernels; enable "
"aiter with VLLM_ROCM_USE_AITER=1."
)
return True
if use_fp4 and not current_platform.is_device_capability_family(100):
raise ValueError(
"indexer_kv_dtype='mxfp4' requires Blackwell datacenter GPUs "
@@ -879,8 +901,17 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
self.use_pcp = self.pcp_world_size > 1
self.pcp_rank = get_pcp_group().rank_in_group if self.use_pcp else 0
self.cp_kv_cache_interleave_size = parallel_config.cp_kv_cache_interleave_size
# KV compression (DeepseekV4). Default to 1 for no compression.
self.compress_ratio = 1
if isinstance(self.kv_cache_spec, MLAAttentionSpec):
assert isinstance(self.kv_cache_spec.tokens_per_state, int)
self.compress_ratio = self.kv_cache_spec.tokens_per_state
# NOTE(Chen):an estimated max size of flattened_kv. Need to double check.
self.max_prefill_buffer_size = get_max_prefill_buffer_size(self.vllm_config)
# Counted in compressed rows, like the chunker's seq_lens and the
# workspace.
self.max_prefill_buffer_size = (
get_max_prefill_buffer_size(self.vllm_config) // self.compress_ratio
)
self.num_speculative_tokens = (
self.vllm_config.speculative_config.num_speculative_tokens
if self.vllm_config.speculative_config
@@ -962,14 +993,6 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
(self.num_sms + 1, 2), dtype=torch.int32, device=self.device
)
# KV compression. Default to 1 for no compression.
self.compress_ratio = 1
# Get compress_ratio for DeepseekV4 support
if isinstance(self.kv_cache_spec, MLAAttentionSpec):
# MLA compression is a whole number of tokens per state (fractions
# are whisper block pooling and never reach MLA).
assert isinstance(self.kv_cache_spec.tokens_per_state, int)
self.compress_ratio = self.kv_cache_spec.tokens_per_state
if self.dcp_world_size > 1 and self.compress_ratio > 1:
raise NotImplementedError(
"DCP is not supported with sparse indexer KV compression "
@@ -1275,17 +1298,6 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
slot_mapping = common_attn_metadata.slot_mapping
block_table = common_attn_metadata.block_table_tensor
dcp_local_seq_lens = common_attn_metadata.dcp_local_seq_lens
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.decode_threshold,
require_uniform=not (self.use_flattening or self.supports_varlen),
treat_short_extends_as_decodes=not self.use_pcp,
)
)
assert num_decodes + num_prefills == num_reqs
assert num_decode_tokens + num_prefill_tokens == num_tokens
compressed_slot_mapping = slot_mapping
indexer_block_table = block_table
@@ -1324,6 +1336,34 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
dim=0,
)
# PCP decode sharding keeps a zero-token placeholder on ranks that own
# no request in a step so collectives retain a uniform rank shape. Do
# not turn that placeholder into a zero-length indexer decode request.
if num_tokens == 0:
return DeepseekV32IndexerMetadata(
seq_lens=seq_lens,
max_seq_len=common_attn_metadata.max_seq_len,
slot_mapping=compressed_slot_mapping,
num_decodes=0,
num_decode_tokens=0,
num_prefills=0,
num_prefill_tokens=0,
prefill=None,
decode=None,
)
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.decode_threshold,
require_uniform=not (self.use_flattening or self.supports_varlen),
treat_short_extends_as_decodes=not self.use_pcp,
)
)
assert num_decodes + num_prefills == num_reqs
assert num_decode_tokens + num_prefill_tokens == num_tokens
prefill_metadata = None
if num_prefills > 0:
compressed_seq_lens = (
@@ -948,6 +948,31 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
device=device,
)
# get_ps_metadata_v1 builds the plan on the host and writes its outputs with
# blocking hipMemcpy that is not ordered on the current stream. Writing the
# device buffers directly lets step N+1's build (async scheduling) overwrite a
# plan that step N's prefill kernels are still reading. Build into pinned host
# staging instead and copy on the current stream. Two staging slots, each
# reused only after its previous H2D copy has completed.
self._fp8_ps_device_outputs = (
self.fp8_ps_work_indptr,
self.fp8_ps_work_info,
self.fp8_ps_reduce_indptr,
self.fp8_ps_reduce_final_map,
self.fp8_ps_reduce_partial_map,
)
self._fp8_ps_staging = [
tuple(
torch.empty(t.shape, dtype=t.dtype, device="cpu", pin_memory=True)
for t in self._fp8_ps_device_outputs
)
for _ in range(2)
]
# One event per slot, recorded after that slot's H2D copy. synchronize()
# on an event that has not been recorded yet returns immediately.
self._fp8_ps_staging_free = [torch.cuda.Event(), torch.cuda.Event()]
self._fp8_ps_slot = 0
from vllm.platforms import current_platform
from vllm.v1.worker.workspace import current_workspace_manager
@@ -1043,6 +1068,20 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
kvlen_granularity = 128
block_size = 1 # non-paged: each "page" is one token
slot = self._fp8_ps_slot
self._fp8_ps_slot ^= 1
staging_free = self._fp8_ps_staging_free[slot]
with gpu_sync_allowed():
staging_free.synchronize()
(
work_indptr_host,
work_info_host,
reduce_indptr_host,
reduce_final_map_host,
reduce_partial_map_host,
) = self._fp8_ps_staging[slot]
# work_metadata is not written by the host planner; it stays on device.
get_ps_metadata_v1(
qo_indptr_cpu,
kv_indptr_cpu,
@@ -1050,17 +1089,20 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
gqa_ratio,
num_head_k,
self.fp8_ps_work_metadata,
self.fp8_ps_work_indptr,
self.fp8_ps_work_info,
self.fp8_ps_reduce_indptr,
self.fp8_ps_reduce_final_map,
self.fp8_ps_reduce_partial_map,
work_indptr_host,
work_info_host,
reduce_indptr_host,
reduce_final_map_host,
reduce_partial_map_host,
qhead_granularity=qhead_granularity,
qlen_granularity=qlen_granularity,
kvlen_granularity=kvlen_granularity,
block_size=block_size,
is_causal=True,
)
for dst, src in zip(self._fp8_ps_device_outputs, self._fp8_ps_staging[slot]):
dst.copy_(src, non_blocking=True)
staging_free.record()
total_prefill_tokens = int(qo_indptr_cpu[-1].item())
kv_indices = torch.arange(
@@ -1068,12 +1110,8 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
)
# The actual number of active partial tiles for this batch is the
# final value of reduce_indptr. Resolving it here (during metadata
# build) keeps it off the per-layer forward path where a sync would
# break CUDA Graph capture. Using the device-side reduce_indptr is
# acceptable since build is allowed to incur an occasional sync.
with gpu_sync_allowed():
num_partial_tiles = int(self.fp8_ps_reduce_indptr[-1].item())
# final value of reduce_indptr, read from the host plan (no GPU sync).
num_partial_tiles = int(reduce_indptr_host[-1])
# Attach PS metadata to the metadata object so forward_mha can read it.
metadata.fp8_prefill_qo_indptr = qo_indptr
@@ -1293,10 +1331,17 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
# to the original _copy_page_indices_kernel).
# When kernel_block_size=K>1, block_table entry b covering K tokens
# gets expanded to flat indices b*K, b*K+1, ..., b*K+(K-1).
_expand_page_indices_kernel[(num_reqs,)](
# Chunk count comes from the block table width, an upper bound on
# tokens per request that is available host-side, so this adds no
# device synchronisation. Programs whose chunk lies past
# num_tokens mask out entirely.
max_tokens_per_req = block_table_tensor.shape[1] * self.kernel_block_size
num_chunks = max(1, cdiv(max_tokens_per_req, 1024))
_expand_page_indices_kernel[(num_reqs, num_chunks)](
self.paged_kv_indices,
block_table_tensor,
block_table_tensor.stride(0),
block_table_tensor.stride(1),
paged_kv_indptr,
KERNEL_BLOCK_SIZE=self.kernel_block_size,
BLOCK_SIZE=1024,
@@ -1535,7 +1580,8 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
def _expand_page_indices_kernel(
page_indices,
block_table,
block_table_stride,
block_table_stride_0,
block_table_stride_1,
cu_num_tokens,
KERNEL_BLOCK_SIZE: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
@@ -1553,32 +1599,44 @@ def _expand_page_indices_kernel(
When KERNEL_BLOCK_SIZE=K: block table entry b (covering K tokens)
is expanded to flat indices b*K, b*K+1, ..., b*K+(K-1).
"""
# One program per (request, token-chunk). Parallelising over requests
# alone degenerates at low concurrency: with num_reqs == 1 a single
# workgroup walked the whole sequence in a serial loop.
req_idx = tl.program_id(0)
row_ptr = block_table + req_idx * block_table_stride
chunk_idx = tl.program_id(1)
row_ptr = block_table + req_idx * block_table_stride_0
start_idx = tl.load(cu_num_tokens + req_idx)
num_tokens = tl.load(cu_num_tokens + req_idx + 1) - start_idx
offset = tl.arange(0, BLOCK_SIZE)
for i in tl.range(0, num_tokens, BLOCK_SIZE):
token_offsets = i + offset
mask = token_offsets < num_tokens
# The grid is sized from the block table width, an upper bound over all
# requests, so a ragged batch launches chunks past a short request's end.
# Returning here keeps those programs from issuing masked-out loads and
# stores at all.
chunk_start = chunk_idx * BLOCK_SIZE
if chunk_start >= num_tokens:
return
# Which block in the block table does this token belong to?
block_idx = token_offsets // KERNEL_BLOCK_SIZE
# Offset within that block
offset_in_block = token_offsets % KERNEL_BLOCK_SIZE
token_offsets = chunk_start + tl.arange(0, BLOCK_SIZE)
mask = token_offsets < num_tokens
# Load the block ID from the block table
block_ids = tl.load(row_ptr + block_idx, mask=mask)
# Which block in the block table does this token belong to?
block_idx = token_offsets // KERNEL_BLOCK_SIZE
# Offset within that block
offset_in_block = token_offsets % KERNEL_BLOCK_SIZE
# Compute flat index in the flattened kv_buffer
flat_indices = block_ids * KERNEL_BLOCK_SIZE + offset_in_block
# Load the block ID from the block table
# Both strides are taken from the caller: the block table is a view owned
# elsewhere, so a unit column stride must not be assumed.
block_ids = tl.load(row_ptr + block_idx * block_table_stride_1, mask=mask)
tl.store(
page_indices + start_idx + token_offsets,
flat_indices,
mask=mask,
)
# Compute flat index in the flattened kv_buffer
flat_indices = block_ids * KERNEL_BLOCK_SIZE + offset_in_block
tl.store(
page_indices + start_idx + token_offsets,
flat_indices,
mask=mask,
)
class AiterMLAHelper:
@@ -70,6 +70,50 @@ def _use_rocm_sparse_triton(
)
@triton.jit
def _fit_kpool_indices_kernel(
token_indices_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS + TAIL_WIDTH]
out_ptr, # int32 [num_tokens, NUM_TOPK_TOKENS]
ti_stride0,
ti_stride1,
out_stride0,
out_stride1,
NUM_TOPK_TOKENS: tl.constexpr,
TAIL_WIDTH: tl.constexpr,
BLOCK_T: tl.constexpr,
BLOCK_TAIL: tl.constexpr,
):
row_ptr = token_indices_ptr + tl.program_id(0) * ti_stride0
columns = tl.arange(0, BLOCK_T)
column_mask = columns < NUM_TOPK_TOKENS
history = tl.load(row_ptr + columns * ti_stride1, mask=column_mask, other=-1)
tail_columns = tl.arange(0, BLOCK_TAIL)
tail = tl.load(
row_ptr + (NUM_TOPK_TOKENS + tail_columns) * ti_stride1,
mask=tail_columns < TAIL_WIDTH,
other=-1,
)
valid_history = tl.sum((history >= 0).to(tl.int32))
valid_tail = tl.sum((tail >= 0).to(tl.int32))
keep_history = tl.minimum(valid_history, NUM_TOPK_TOKENS - valid_tail)
tail_offsets = columns - keep_history
tail_values = tl.load(
row_ptr + (NUM_TOPK_TOKENS + tail_offsets) * ti_stride1,
mask=column_mask & (tail_offsets >= 0) & (tail_offsets < TAIL_WIDTH),
other=-1,
)
fitted = tl.where(columns < keep_history, history, tail_values)
fitted = tl.where(columns < keep_history + valid_tail, fitted, -1)
tl.store(
out_ptr + tl.program_id(0) * out_stride0 + columns * out_stride1,
fitted,
mask=column_mask,
)
def fit_kpool_indices_to_aiter(
token_indices: torch.Tensor, topk_tokens: int
) -> torch.Tensor:
@@ -79,20 +123,29 @@ def fit_kpool_indices_to_aiter(
if token_indices.shape[1] == topk_tokens:
return token_indices
history = token_indices[:, :topk_tokens]
tail = token_indices[:, topk_tokens:]
valid_history = (history >= 0).sum(dim=1)
valid_tail = (tail >= 0).sum(dim=1)
keep_history = torch.minimum(valid_history, topk_tokens - valid_tail)
columns = torch.arange(topk_tokens, device=token_indices.device).unsqueeze(0)
tail_offsets = columns - keep_history.unsqueeze(1)
tail_values = torch.gather(
tail, 1, tail_offsets.clamp(min=0, max=tail.shape[1] - 1)
num_tokens, width = token_indices.shape
tail_width = width - topk_tokens
output = torch.empty(
(num_tokens, topk_tokens),
dtype=token_indices.dtype,
device=token_indices.device,
)
output = torch.where(columns < keep_history.unsqueeze(1), history, tail_values)
valid_output = columns < (keep_history + valid_tail).unsqueeze(1)
return torch.where(valid_output, output, -1)
if num_tokens == 0:
return output
_fit_kpool_indices_kernel[(num_tokens,)](
token_indices,
output,
token_indices.stride(0),
token_indices.stride(1),
output.stride(0),
output.stride(1),
NUM_TOPK_TOKENS=topk_tokens,
TAIL_WIDTH=tail_width,
BLOCK_T=triton.next_power_of_2(topk_tokens),
BLOCK_TAIL=triton.next_power_of_2(tail_width),
)
return output
@triton.jit
@@ -0,0 +1,513 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Indexer metadata for the ROCm paged MXFP4 path.
Extends the dense indexer metadata with what aiter's paged MXFP4 MQA-logits
kernel needs to read the cache in place: each prefill chunk as its requests,
packed through query_start_loc into one launch, and the decode rows as
next_n-row sequences on uniform steps. `RocmMxfp4IndexerMetadataBuilder` plans
this for any model's indexer, and a two-level indexer's candidate blocks once
a subclass sets their size. DeepSeek-V4.1's builder does, and with
``AttentionConfig.indexer_sparse_logits`` adds the per-step state the
candidate consumers share.
"""
import bisect
from dataclasses import dataclass, field, fields
import torch
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.v1.attention.backend import (
AttentionCGSupport,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerMetadata,
DeepseekV32IndexerMetadataBuilder,
DeepseekV32IndexerPrefillChunkMetadata,
DeepseekV41IndexerBackend,
)
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import (
build_rocm_mxfp4_decode_schedule,
rocm_mxfp4_consumer_rows,
rocm_mxfp4_decode_schedule_words,
rocm_paged_mxfp4_cache_layout,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
logger = init_logger(__name__)
# The consumers walk the pool instead of the context once the context is this
# many pools long. Set from kernel timings, not end-to-end runs: the gather
# loads more per key than the dense walk, so it only wins on a large cut.
_GATHER_MIN_CUT_DECODE = 3.0
_GATHER_MIN_CUT_PREFILL = 1.5
@dataclass
class RocmMxfp4PrefillPlan:
"""One prefill chunk as the requests the kernel launches on, all in one
launch: the kernel finds each row's request through query_start_loc, and
a request's rows share its KV tiles."""
requests: list[tuple[int, int, int]]
"""(first row, end row, request) per request with rows in the chunk; rows
count from ``chunk.token_start``, requests index ``chunk.block_table``."""
width: int
"""Logits columns: an upper bound on the chunk's compressed contexts."""
row_ends: torch.Tensor
"""[rows] int32 exclusive compressed key bound of each row."""
context_lens: torch.Tensor
"""[chunk.num_reqs] int32 compressed context of each request."""
query_start_loc: torch.Tensor
"""[chunk.num_reqs + 1] int32 row offsets of the chunk's requests, local to
the chunk."""
first_request: int
"""The step's index of the chunk's first request."""
block_ends: torch.Tensor | None = None
"""[rows] int32 candidate blocks each row sees, for the source's pool."""
use_gather: bool = False
@dataclass
class RocmMxfp4GatherLaunch:
"""Query rows [token_start, token_end) of one request, which the candidate
consumers score against the pool in one launch."""
token_start: int
token_end: int
block_table: torch.Tensor
"""[1, max_blocks] int32, the request's block table row."""
context_len: torch.Tensor
"""[1] int32 compressed context of the request."""
row_ends: torch.Tensor
"""[rows] int32 exclusive compressed key bound of each row."""
pool: tuple[dict, torch.Tensor] | None = None
"""The resolved candidate lists, built by the first consumer layer and
reused by the rest."""
@dataclass
class RocmMxfp4NativeDecode:
"""A decode step whose requests all have next_n query rows, as the
kernel's sequences: a workgroup then walks a KV tile once for up to
next_n rows instead of once per row."""
next_n: int
context_lens: torch.Tensor
"""[requests] int32 compressed context of each request."""
block_table: torch.Tensor
"""[requests, max_blocks] int32, each request's first flattened row."""
def native_decode(
row_lens: torch.Tensor,
row_block_table: torch.Tensor,
query_lens: list[int],
next_n: int,
context_lens: torch.Tensor,
) -> RocmMxfp4NativeDecode | None:
"""The step as next_n-row sequences, or None when a request has fewer rows.
``row_lens`` and ``row_block_table`` are the flattened rows' bounds and
block table, ``query_lens`` the decode requests' query lengths. Trailing
empty requests are cudagraph padding: they keep their next_n rows, with no
context. Only the step's shape decides, so a FULL graph captured on a
uniform batch replays the same launch on a padded one.
"""
num_reqs = len(query_lens)
num_full = next((i for i, n in enumerate(query_lens) if n != next_n), num_reqs)
if (
next_n <= 1
or row_lens.shape[0] != num_reqs * next_n
or any(query_lens[num_full:])
):
return None
return RocmMxfp4NativeDecode(
next_n, context_lens[:num_reqs], row_block_table[::next_n]
)
@dataclass
class RocmMxfp4IndexerMetadata(DeepseekV32IndexerMetadata):
prefill_plans: list[RocmMxfp4PrefillPlan] = field(default_factory=list)
"""Parallel to ``prefill.chunks``."""
decode_row_lens: torch.Tensor | None = None
"""[rows] int32 compressed context of each decode query row."""
decode_block_ends: torch.Tensor | None = None
"""[rows] int32 candidate blocks each decode row sees, for the source's
pool."""
decode_native: RocmMxfp4NativeDecode | None = None
"""The same rows as next_n-row sequences, for the dense launches."""
decode_schedule: torch.Tensor | None = None
"""The dense decode launches' work schedule, built once for the step."""
decode_use_gather: bool = False
"""Whether the candidate consumers gather for the decode rows."""
decode_gather: tuple[dict, torch.Tensor] | None = None
"""The pool the first consumer resolved for the decode rows."""
gather_launches: list[RocmMxfp4GatherLaunch] = field(default_factory=list)
"""The prefill rows of the chunks that gather, as the consumers launch
them."""
def plan_prefill_chunks(
chunks: list[DeepseekV32IndexerPrefillChunkMetadata],
query_start_loc: list[int],
seq_lens_cpu: torch.Tensor,
context_lens: torch.Tensor,
compress_ratio: int,
candidate_block_size: int,
min_gather_width: float | None,
query_start_loc_device: torch.Tensor,
) -> list[RocmMxfp4PrefillPlan]:
"""Split each chunk into its requests.
``query_start_loc`` and ``seq_lens_cpu`` are the step's host copies (the
latter an upper bound), ``context_lens`` the device compressed lengths.
A chunk covers whole requests, or a query slice of one request; either
way it launches once, packed through the chunk's part of the device
``query_start_loc``.
"""
block = candidate_block_size
plans = []
for chunk in chunks:
t0, t1 = chunk.token_start, chunk.token_end
first = bisect.bisect_right(query_start_loc, t0) - 1
requests = []
for req in range(chunk.num_reqs):
lo = max(query_start_loc[first + req], t0) - t0
hi = min(query_start_loc[first + req + 1], t1) - t0
if hi > lo:
requests.append((lo, hi, req))
reqs = slice(first, first + chunk.num_reqs)
packed = torch.clamp(query_start_loc_device[first : reqs.stop + 1], t0, t1)
packed -= t0
width = int(seq_lens_cpu[reqs].max()) // compress_ratio
row_ends = chunk.cu_seqlen_ke - chunk.cu_seqlen_ks
plans.append(
RocmMxfp4PrefillPlan(
requests=requests,
width=width,
row_ends=row_ends,
context_lens=context_lens[reqs],
query_start_loc=packed,
first_request=first,
block_ends=(row_ends + block - 1) // block if block else None,
use_gather=min_gather_width is not None and width >= min_gather_width,
)
)
return plans
def split_prefill_chunks(
context_lens: torch.Tensor,
query_lens: torch.Tensor,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
"""(request slice, query slice) chunks, as the base chunker returns them.
Nothing gathers K here, so the requests' contexts do not add up: a chunk's
logits are [rows, widest compressed context] fp32, at most
``max_logits_bytes``. A request too wide to launch whole is cut on its
query rows.
"""
def max_rows(width: int) -> int:
return max(1, max_logits_bytes // (4 * max(width, 1)))
chunks: list[tuple[slice, slice]] = []
end = 0
while end < len(context_lens):
start, rows, width = end, 0, 0
while end < len(context_lens):
q = int(query_lens[end])
w = max(width, int(context_lens[end]))
if rows and rows + q > max_rows(w):
break
rows, width = rows + q, w
end += 1
step = max_rows(width)
reqs = slice(start + request_offset, end + request_offset)
chunks.extend(
(reqs, slice(lo, min(lo + step, rows))) for lo in range(0, rows, step)
)
return chunks
def plan_gather_launches(
chunks: list[DeepseekV32IndexerPrefillChunkMetadata],
plans: list[RocmMxfp4PrefillPlan],
max_rows: int,
) -> list[RocmMxfp4GatherLaunch]:
"""The candidate consumers' launches over the chunks that gather.
A consumer's logits are [rows, pool] however long the context, so the
dense split, sized for the context, would launch it far more often than
its memory needs. Each request's rows go back together across the chunks
that cut them, then out again at most ``max_rows`` a launch.
"""
# Per request: (first token, [(plan, first row, end row)]), and the chunk
# and request index its block table and context come from.
runs: list[tuple[int, list, DeepseekV32IndexerPrefillChunkMetadata, int]] = []
last: tuple[int, int] | None = None
for chunk, plan in zip(chunks, plans):
if not plan.use_gather:
last = None
continue
for lo, hi, req in plan.requests:
request, t_lo = plan.first_request + req, chunk.token_start + lo
if last != (request, t_lo):
runs.append((t_lo, [], chunk, req))
runs[-1][1].append((plan, lo, hi))
last = (request, chunk.token_start + hi)
launches = []
for token_start, pieces, chunk, req in runs:
ends = [plan.row_ends[lo:hi] for plan, lo, hi in pieces]
row_ends = ends[0] if len(ends) == 1 else torch.cat(ends)
block_table = chunk.block_table[req : req + 1]
context_len = pieces[0][0].context_lens[req : req + 1]
for lo in range(0, row_ends.shape[0], max_rows):
hi = min(lo + max_rows, row_ends.shape[0])
launches.append(
RocmMxfp4GatherLaunch(
token_start + lo,
token_start + hi,
block_table,
context_len,
row_ends[lo:hi],
)
)
return launches
class DeepseekV41RocmMxfp4IndexerBackend(DeepseekV41IndexerBackend):
@staticmethod
def get_name() -> str:
return "DEEPSEEK_V41_ROCM_MXFP4_INDEXER"
@staticmethod
def get_supported_kernel_block_sizes(
kv_cache_spec: KVCacheSpec | None = None,
) -> list[int | MultipleOf]:
# --block-size 128 preferred.
return [64, 128]
@staticmethod
def get_builder_cls() -> type["DeepseekV41RocmMxfp4IndexerMetadataBuilder"]:
return DeepseekV41RocmMxfp4IndexerMetadataBuilder
class RocmMxfp4IndexerMetadataBuilder(DeepseekV32IndexerMetadataBuilder):
"""Dense indexer metadata plus the in-place paged launches' layout.
Requirements are checked here, at engine start.
"""
@classmethod
def get_cudagraph_support(
cls,
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> AttentionCGSupport:
# Decode rows are flattened into persistent buffers, and whether a
# step launches them as next_n-row sequences depends on its shape
# alone (see native_decode).
return AttentionCGSupport.ALWAYS
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
**kwargs,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device, **kwargs)
name = "the ROCm MXFP4 indexer"
if self.dcp_world_size > 1 or self.use_pcp:
raise NotImplementedError(
f"{name} does not support decode/prefill context parallel."
)
hf_config = vllm_config.model_config.hf_text_config
num_heads, head_dim = hf_config.index_n_heads, hf_config.index_head_dim
self.num_heads, self.head_dim = num_heads, head_dim
self.page_entries = kv_cache_spec.block_size // self.compress_ratio
self.cache_layout = rocm_paged_mxfp4_cache_layout(
num_heads, head_dim, self.page_entries
)
# Ragged steps take a row per query token, as do the candidate
# consumers' gathers. Uniform steps also launch the dense layers on
# next_n-row sequences, see native_decode.
self.use_flattening = True
# A two-level (candidate block) indexer's builder sets these.
self.candidate_block_size = 0
self.min_gather_width: float | None = None
self.decode_block_ends_buffer = torch.zeros(
self.arange_buffer.shape[0], dtype=torch.int32, device=device
)
self.context_lens_buffer = torch.zeros(
self.arange_buffer.shape[0], dtype=torch.int32, device=device
)
spec_config = vllm_config.speculative_config
# Adaptive verification replays a FULL graph on drafts reallocated
# across requests, so a step's shape does not fix its query lengths.
adaptive = spec_config is not None and spec_config.enable_adaptive_verification
self.native_next_n = 1 if adaptive else self.num_speculative_tokens + 1
# The indexer's logits width, which the decode schedule sizes slices by.
max_model_len = vllm_config.model_config.max_model_len
self.logits_width = max_model_len // self.compress_ratio
# Every dense layer of this group reads the same rows through the same
# page geometry, so the step builds their schedule once, not per layer.
self.decode_schedule_buffer = torch.empty(
rocm_mxfp4_decode_schedule_words(
num_heads, head_dim, self.page_entries, self.native_next_n
),
dtype=torch.int32,
device=device,
)
def _split_indexer_prefill_chunks( # type: ignore[override]
self,
compressed_seq_lens_cpu: torch.Tensor,
prefill_query_lens_cpu: torch.Tensor,
workspace_size: int,
max_logits_bytes: int,
request_offset: int = 0,
) -> list[tuple[slice, slice]]:
return split_prefill_chunks(
compressed_seq_lens_cpu,
prefill_query_lens_cpu,
max_logits_bytes,
request_offset,
)
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> RocmMxfp4IndexerMetadata:
base = super().build(common_prefix_len, common_attn_metadata, fast_build)
metadata = RocmMxfp4IndexerMetadata(
**{f.name: getattr(base, f.name) for f in fields(base)}
)
cm = common_attn_metadata
context_lens = self.context_lens_buffer[: cm.num_reqs]
torch.floor_divide(
cm.seq_lens[: cm.num_reqs], self.compress_ratio, out=context_lens
)
if base.decode is not None:
lengths = base.decode.seq_lens.view(-1)
metadata.decode_row_lens = lengths
block = self.candidate_block_size
if block:
ends = self.decode_block_ends_buffer[: lengths.shape[0]]
torch.add(lengths, block - 1, out=ends)
ends.floor_divide_(block)
metadata.decode_block_ends = ends
query_start_loc = cm.query_start_loc_cpu[: base.num_decodes + 1]
metadata.decode_native = native_decode(
lengths,
base.decode.block_table,
torch.diff(query_start_loc).tolist(),
self.native_next_n,
context_lens,
)
metadata.decode_schedule = build_rocm_mxfp4_decode_schedule(
lengths,
self.num_heads,
self.head_dim,
self.page_entries,
self.decode_schedule_buffer,
self.logits_width,
metadata.decode_native,
)
if base.prefill is not None:
assert cm.seq_lens_cpu_upper_bound is not None
metadata.prefill_plans = plan_prefill_chunks(
base.prefill.chunks,
cm.query_start_loc_cpu.tolist(),
cm.seq_lens_cpu_upper_bound,
context_lens,
self.compress_ratio,
self.candidate_block_size,
self.min_gather_width,
cm.query_start_loc,
)
return metadata
class DeepseekV41RocmMxfp4IndexerMetadataBuilder(RocmMxfp4IndexerMetadataBuilder):
"""DeepSeek-V4.1's two-level indexer: sets the candidate block size the
base plans with and, with ``indexer_sparse_logits``, adds the consumers'
gathers."""
def __init__(
self,
kv_cache_spec: AttentionSpec,
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
**kwargs,
) -> None:
super().__init__(kv_cache_spec, layer_names, vllm_config, device, **kwargs)
hf_config = vllm_config.model_config.hf_text_config
self.candidate_block_size = getattr(hf_config, "candidate_block_size", 0)
self.num_candidate_cols = 0
if vllm_config.attention_config.indexer_sparse_logits:
prefix = "attention_config.indexer_sparse_logits"
block = self.candidate_block_size
topk_blocks = getattr(hf_config, "candidate_topk_blocks", 0)
layout = self.cache_layout
if block <= 0 or topk_blocks <= 0:
raise ValueError(
f"{prefix} requires a two-level (candidate block) indexer "
"model such as DeepSeek-V4.1."
)
if topk_blocks & (topk_blocks - 1):
raise ValueError(
f"{prefix} on ROCm resolves the candidate pool with a sort "
f"that needs a power-of-two block count, not {topk_blocks}."
)
if self.page_entries % block or block > layout.n_per_tile:
raise ValueError(
f"{prefix} on ROCm needs {block}-entry candidate blocks to "
f"tile a {self.page_entries}-entry indexer page and fit in "
f"one {layout.n_per_tile}-entry shuffle group."
)
self.num_candidate_cols = topk_blocks * block
self.min_gather_width = self.num_candidate_cols * _GATHER_MIN_CUT_PREFILL
self.gather_rows = rocm_mxfp4_consumer_rows(self.num_candidate_cols)
logger.info_once(
"DeepSeek V4.1 indexer: candidate consumers score the %d "
"candidate positions with aiter's paged MXFP4 gather once the "
"context is %.1fx (decode) / %.1fx (prefill) as long.",
self.num_candidate_cols,
_GATHER_MIN_CUT_DECODE,
_GATHER_MIN_CUT_PREFILL,
)
def _gather_pays(self, context: int, cut: float) -> bool:
return self.num_candidate_cols > 0 and context >= cut * self.num_candidate_cols
def build(
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
fast_build: bool = False,
) -> RocmMxfp4IndexerMetadata:
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)
if metadata.decode is not None:
metadata.decode_use_gather = self._gather_pays(
metadata.max_seq_len // self.compress_ratio, _GATHER_MIN_CUT_DECODE
)
if metadata.prefill is not None and self.num_candidate_cols:
metadata.gather_launches = plan_gather_launches(
metadata.prefill.chunks, metadata.prefill_plans, self.gather_rows
)
return metadata
@@ -124,6 +124,7 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
bounded_replay=self.bounded_replay,
block_size=self.block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=self.head_dim,
dtype=self.dtype,
sliding_window=self.window_size,
+74 -240
View File
@@ -8,11 +8,7 @@ from typing import ClassVar
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import (
VllmConfig,
get_current_vllm_config_or_none,
get_layers_from_vllm_config,
)
from vllm.config import VllmConfig, get_layers_from_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
@@ -42,43 +38,9 @@ from vllm.v1.attention.backends.utils import (
from vllm.v1.attention.ops.merge_attn_states import merge_attn_states
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
_PA_GLUON_MAX_QUERY_LEN = 4
_PA_GLUON_MAX_QUERY_GROUP_SIZE = 64
# Query group sizes the gluon paged-attention decode kernel is validated for: 8, 16
_PA_GLUON_QUERY_GROUP_SIZES = (8, 16)
# The kernel is only validated for this head size and kernel block size.
_PA_GLUON_HEAD_SIZE = 128
_PA_GLUON_BLOCK_SIZE = 128
def _pa_gluon_supports(num_heads_q: int, num_heads_kv: int, head_size: int) -> bool:
"""Whether the head config can use the PA decode gluon kernel.
Requires the shuffle KV cache layout (the kernel reads K/V in that layout)
plus a head config the kernel is validated for. Both the advertised kernel
block sizes and the decode dispatch go through this, so a config can never
be offered a 128-token page that gluon will then decline to serve.
"""
return (
rocm_aiter_ops.is_shuffle_kv_cache_enabled()
and num_heads_kv > 0
and num_heads_q % num_heads_kv == 0
and num_heads_q // num_heads_kv in _PA_GLUON_QUERY_GROUP_SIZES
and head_size == _PA_GLUON_HEAD_SIZE
)
_PARTITION_SIZE_ROCM = 256
_CP_TOKENS_PER_ITER_ROCM = 32 * 1024
if current_platform.is_rocm():
from aiter.ops.triton.gluon.pa_decode_gluon import (
get_recommended_splits,
)
from aiter.ops.triton.gluon.pa_decode_gluon import (
pa_decode_gluon as _pa_decode_gluon,
)
from vllm.triton_utils import tl, triton
def block_size(x, head_dim):
@@ -168,8 +130,10 @@ if current_platform.is_rocm():
# for kv cache layout as
# K: [num_blocks, num_head, head_dim // x, page_size, x]
# V: [num_blocks, num_head, page_size // x, head_dim, x]
# The sides only sit a dense page apart when they are separate
# planes (H outermost), so take the block stride from the tensor.
# Take the block stride from the tensor, as the NHD branch does:
# the two sides only sit a dense page apart when they are separate
# planes, and models that pin a block-compact layout interleave
# them instead.
key_cache_ptr_offset = (
key_cache_ptr
+ block_id * k_cache_stride0
@@ -363,7 +327,6 @@ logger = init_logger(__name__)
@dataclass
class AiterFlashAttentionDecodeMetadata:
max_query_len: int
uniform_query_len: int | None
@dataclass
@@ -598,15 +561,8 @@ class AiterFlashAttentionMetadataBuilder(
decode_metadata = None
if num_decodes > 0:
decode_max_query_len = query_lens_cpu[:num_decodes].max().item()
uniform_query_len = (
decode_max_query_len
if num_decode_tokens == num_decodes * decode_max_query_len
else None
)
decode_metadata = AiterFlashAttentionDecodeMetadata(
max_query_len=decode_max_query_len,
uniform_query_len=uniform_query_len,
max_query_len=query_lens_cpu[:num_decodes].max().item(),
)
prefill_metadata = None
@@ -778,27 +734,9 @@ class AiterFlashAttentionMetadataBuilder(
"""
num_reqs = common_attn_metadata.num_reqs
num_tokens = common_attn_metadata.num_actual_tokens
max_query_len = common_attn_metadata.max_query_len
# Uniform-decode assumption does not hold for the
# drafter's first forward after a target step: it inherits the target's
# per-request query lengths, so rows can be longer than gluon's limit or
# ragged. Those batches need the real split, which costs a sync.
# _PA_GLUON_MAX_QUERY_LEN only binds when gluon is the decode consumer,
# so test that rather than the shuffle layout alone.
if _pa_gluon_supports(self.num_heads_q, self.num_heads_kv, self.headdim) and (
max_query_len > _PA_GLUON_MAX_QUERY_LEN
or num_tokens != num_reqs * max_query_len
):
return self.build(
common_prefix_len=0, common_attn_metadata=common_attn_metadata
)
decode_metadata = AiterFlashAttentionDecodeMetadata(
max_query_len=max_query_len,
uniform_query_len=(
max_query_len if num_tokens == num_reqs * max_query_len else None
),
max_query_len=common_attn_metadata.max_query_len,
)
return AiterFlashAttentionMetadata(
@@ -853,21 +791,6 @@ class AiterFlashAttentionBackend(AttentionBackend):
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None) -> list[int | MultipleOf]:
if not rocm_aiter_ops.is_shuffle_kv_cache_enabled():
return [16, 32]
# Only gluon serves 128-token pages; the pa_fwd_asm/ll4mi decode
# fallback is limited to 16 and 32. Advertise 128 only when gluon can
# run so selection never picks a page we cannot serve.
vllm_config = get_current_vllm_config_or_none()
if vllm_config is not None and vllm_config.model_config is not None:
mc = vllm_config.model_config
pc = vllm_config.parallel_config
if _pa_gluon_supports(
mc.get_num_attention_heads(pc),
mc.get_num_kv_heads(pc),
mc.get_head_size(),
):
return [16, 32, 128]
return [16, 32]
@classmethod
@@ -924,6 +847,14 @@ class AiterFlashAttentionBackend(AttentionBackend):
@classmethod
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]:
if rocm_aiter_ops.is_shuffle_kv_cache_enabled():
# pa_fwd_asm strides between pages by a whole dense page, so the two
# head slots customize_spec publishes have to be separate planes
# spanning every block: H outermost. Under LBHNC the slots alternate
# block by block, doubling the stride the kernel assumes. LBHNC
# stays listed for models whose mixed HNC shapes need a
# block-compact layout; those read K/V by stride instead.
return (KVCacheLayout.LHBNC, KVCacheLayout.LBHNC)
# K and V come out of the content dim as transposed views rather than
# copies, so the head dim may sit on either side of the block dim, but
# the layer must stay outermost.
@@ -1358,25 +1289,11 @@ class AiterFlashAttentionImpl(AttentionImpl):
if num_decodes > 0:
assert attn_metadata.decode_metadata is not None
decode_max_query_len = attn_metadata.decode_metadata.max_query_len
decode_query_len = attn_metadata.decode_metadata.uniform_query_len
# check if we can use the gluon paged-attention decode kernel
use_gluon = (
_pa_gluon_supports(
self.num_heads, self.num_kv_heads, self.head_size
)
and key_cache.shape[1] == _PA_GLUON_BLOCK_SIZE
and decode_query_len is not None
and decode_query_len <= _PA_GLUON_MAX_QUERY_LEN
and decode_query_len * (self.num_heads // self.num_kv_heads)
<= _PA_GLUON_MAX_QUERY_GROUP_SIZE
and (decode_query_len == 1 or attn_metadata.causal)
)
# Use unified_attention for the decodes the paged kernels can't
# take: sliding window, sinks, or a multi-token batch that gluon
# declined (pa_fwd_asm and paged_attention_v1 don't support
# sinks).
if not use_gluon and (
# take: sliding window, sinks, or a multi-token batch
# (pa_fwd_asm and paged_attention_v1 don't support sinks).
if (
self.sliding_window[0] != -1
or decode_max_query_len > 1
or self.sinks is not None
@@ -1505,145 +1422,62 @@ class AiterFlashAttentionImpl(AttentionImpl):
num_blocks, num_kv_heads, block_size // x, head_size, x
)
if use_gluon:
is_fp8_kv = is_quantized_kv_cache(self.kv_cache_dtype)
# Per-tensor descale, as a float32 [1] tensor.
k_scale_gluon = (
layer._k_scale.reshape(1).to(torch.float32)
if is_fp8_kv
else None
)
v_scale_gluon = (
layer._v_scale.reshape(1).to(torch.float32)
if is_fp8_kv
else None
)
compute_type = (
current_platform.fp8_dtype() if is_fp8_kv else query.dtype
)
# The kernel folds the query positions into the group
# dim, so the intermediate buffers are sized by the
# combined extent.
query_group_size = decode_query_len * (
num_heads // num_kv_heads
)
sliding_window_int = (
self.sliding_window[0] + 1
if self.sliding_window[0] > 0
else 0
)
if sliding_window_int > 0:
max_context_partition_num = 1
context_partition_size = 128
else:
max_context_partition_num = get_recommended_splits(
num_decodes, num_kv_heads
)
context_partition_size = _PARTITION_SIZE_ROCM
intermediate_shape = (
num_decodes,
num_kv_heads,
max_context_partition_num,
query_group_size,
)
exp_sums = torch.empty(
intermediate_shape,
dtype=torch.float32,
device=query.device,
)
max_logits = torch.empty_like(exp_sums)
temporary_output = torch.empty(
(*intermediate_shape, head_size),
dtype=output.dtype,
device=query.device,
)
_pa_decode_gluon(
output=output[:num_decode_tokens],
query=query[:num_decode_tokens],
key_cache=new_key_cache,
value_cache=new_value_cache,
context_lengths=attn_metadata.seq_lens[:num_decodes].to(
torch.int32
),
block_tables=attn_metadata.block_table[:num_decodes].to(
torch.int32
),
softmax_scale=self.scale,
query_length=decode_query_len,
max_context_partition_num=max_context_partition_num,
context_partition_size=context_partition_size,
compute_type=compute_type,
query_scale=None,
key_scale=k_scale_gluon,
value_scale=v_scale_gluon,
exp_sums=exp_sums,
max_logits=max_logits,
temporary_output=temporary_output,
alibi_slopes=self.alibi_slopes,
sinks=self.sinks,
sliding_window=sliding_window_int,
ps=True,
)
else:
# Unlike gluon, this kernel derives block addresses
# arithmetically, so it only reads the right bytes when
# each side is a dense plane of pages.
assert new_key_cache.stride(0) == (
num_kv_heads * head_size * block_size
), (
"paged_attention_common needs the K/V sides as "
"dense planes; the resolved KV cache layout "
"interleaves them within a block."
)
num_seqs = attn_metadata.seq_lens.shape[0]
max_num_partitions = (
attn_metadata.max_seq_len + _PARTITION_SIZE_ROCM - 1
) // _PARTITION_SIZE_ROCM
tmp_out = torch.empty(
(num_seqs, num_heads, max_num_partitions, head_size),
dtype=query.dtype,
device=query.device,
)
exp_sums = torch.empty(
(num_seqs, num_heads, max_num_partitions),
dtype=torch.float32,
device=query.device,
)
max_logits = torch.empty_like(exp_sums)
k_qscale = (
layer._k_scale
if attn_metadata.k_scale is None
else attn_metadata.k_scale
)
v_qscale = (
layer._v_scale
if attn_metadata.v_scale is None
else attn_metadata.v_scale
)
rocm_aiter_ops.paged_attention_common(
Q=query[:num_decode_tokens],
K=new_key_cache,
V=new_value_cache,
tmp_out=tmp_out,
max_logits=max_logits,
exp_sums=exp_sums,
max_seq_len=attn_metadata.max_seq_len,
block_tables=attn_metadata.block_table[:num_decodes],
context_lens=attn_metadata.seq_lens[:num_decodes],
block_tables_stride0=attn_metadata.block_table[
:num_decodes
].stride(0),
scale=self.scale,
K_QScale_hip=k_qscale,
V_QScale_hip=v_qscale,
K_QScale_asm=k_qscale,
V_QScale_asm=v_qscale,
out_=output[:num_decode_tokens],
kv_cache_dtype=self.kv_cache_dtype,
)
# This kernel derives block addresses arithmetically, so it
# only reads the right bytes when each side is a dense
# plane of pages.
assert new_key_cache.stride(0) == (
num_kv_heads * head_size * block_size
), (
"paged_attention_common needs the K/V sides as dense "
"planes; the resolved KV cache layout interleaves them "
"within a block."
)
num_seqs = attn_metadata.seq_lens.shape[0]
max_num_partitions = (
attn_metadata.max_seq_len + _PARTITION_SIZE_ROCM - 1
) // _PARTITION_SIZE_ROCM
tmp_out = torch.empty(
(num_seqs, num_heads, max_num_partitions, head_size),
dtype=query.dtype,
device=query.device,
)
exp_sums = torch.empty(
(num_seqs, num_heads, max_num_partitions),
dtype=torch.float32,
device=query.device,
)
max_logits = torch.empty_like(exp_sums)
k_qscale = (
layer._k_scale
if attn_metadata.k_scale is None
else attn_metadata.k_scale
)
v_qscale = (
layer._v_scale
if attn_metadata.v_scale is None
else attn_metadata.v_scale
)
rocm_aiter_ops.paged_attention_common(
Q=query[:num_decode_tokens],
K=new_key_cache,
V=new_value_cache,
tmp_out=tmp_out,
max_logits=max_logits,
exp_sums=exp_sums,
max_seq_len=attn_metadata.max_seq_len,
block_tables=attn_metadata.block_table[:num_decodes],
context_lens=attn_metadata.seq_lens[:num_decodes],
block_tables_stride0=attn_metadata.block_table[
:num_decodes
].stride(0),
scale=self.scale,
K_QScale_hip=k_qscale,
V_QScale_hip=v_qscale,
K_QScale_asm=k_qscale,
V_QScale_asm=v_qscale,
out_=output[:num_decode_tokens],
kv_cache_dtype=self.kv_cache_dtype,
)
else:
_, num_heads, head_size = query.shape
nbytes_per_qo_elem = torch.finfo(query.dtype).bits // 8
+3 -10
View File
@@ -283,7 +283,6 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
has_initial_states_p = None
has_initial_states_d = None
num_computed_tokens_p = None
# Per-request classification by mask, NOT by position. With
# spec-decode, the front decode group can contain both spec-decode
@@ -402,10 +401,9 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
assert non_spec_query_start_loc is not None
query_start_loc_d = non_spec_query_start_loc[: num_decodes + 1]
if num_prefills > 0:
num_computed_tokens_p = num_computed_tokens[
num_decodes : num_decodes + num_prefills
]
has_initial_states_p = num_computed_tokens_p > 0
has_initial_states_p = (
num_computed_tokens[num_decodes : num_decodes + num_prefills] > 0
)
assert non_spec_query_start_loc is not None
query_start_loc_p = (
non_spec_query_start_loc[num_decodes:] - num_decode_tokens
@@ -478,11 +476,6 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
query_start_loc_d=query_start_loc_d,
state_indices_tensor_p=state_indices_tensor_p,
state_indices_tensor_d=state_indices_tensor_d,
num_computed_tokens_p=num_computed_tokens_p,
block_idx_last_scheduled_token=None,
block_idx_first_scheduled_token_p=None,
block_idx_last_computed_token=None,
block_idx_last_scheduled_token_prev_step=None,
seq_lens=m.seq_lens,
)
+40 -4
View File
@@ -18,7 +18,7 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.math_utils import next_power_of_2
from vllm.utils.math_utils import cdiv, next_power_of_2
from vllm.utils.torch_utils import get_dtype_size, is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
@@ -152,10 +152,29 @@ class TritonAttentionMetadataBuilder(AttentionMetadataBuilder[TritonAttentionMet
)
self.num_par_softmax_segments = NUM_PAR_SOFTMAX_SEGMENTS
# On SM120, batches whose 16-segment grid under-fills the SMs use 64.
self.max_seqs_64_segments = 0
if current_platform.is_cuda() and current_platform.is_device_capability(
(12, 0)
):
self.max_seqs_64_segments = (current_platform.num_compute_units() - 1) // (
NUM_PAR_SOFTMAX_SEGMENTS * self.num_heads_kv
)
max_num_tokens_3d = self.seq_threshold_3D
if self.max_seqs_64_segments > 0:
self.num_par_softmax_segments = 64
# build() reuses this scratch at 16 segments with proportionally more rows.
max_num_tokens_3d = max(
min(self.max_seqs_64_segments, max_num_tokens_3d),
cdiv(
max_num_tokens_3d,
self.num_par_softmax_segments // NUM_PAR_SOFTMAX_SEGMENTS,
),
)
headdim_padded = next_power_of_2(self.headdim)
self.softmax_segm_output = torch.empty(
(
self.seq_threshold_3D,
max_num_tokens_3d,
self.num_heads_q,
self.num_par_softmax_segments,
headdim_padded,
@@ -164,12 +183,12 @@ class TritonAttentionMetadataBuilder(AttentionMetadataBuilder[TritonAttentionMet
device=device,
)
self.softmax_segm_max = torch.empty(
(self.seq_threshold_3D, self.num_heads_q, self.num_par_softmax_segments),
(max_num_tokens_3d, self.num_heads_q, self.num_par_softmax_segments),
dtype=torch.float32,
device=device,
)
self.softmax_segm_expsum = torch.empty(
(self.seq_threshold_3D, self.num_heads_q, self.num_par_softmax_segments),
(max_num_tokens_3d, self.num_heads_q, self.num_par_softmax_segments),
dtype=torch.float32,
device=device,
)
@@ -246,6 +265,23 @@ class TritonAttentionMetadataBuilder(AttentionMetadataBuilder[TritonAttentionMet
softmax_segm_max=self.softmax_segm_max,
softmax_segm_expsum=self.softmax_segm_expsum,
)
if self.max_seqs_64_segments > 0 and (
self.max_seqs_64_segments < seq_lens.shape[0]
or self.softmax_segm_max.shape[0] < num_actual_tokens
):
# The 16-segment grid fills the SMs, or the 64-segment rows cannot
# hold every query token: same scratch, 16-segment layout.
segments = NUM_PAR_SOFTMAX_SEGMENTS
attn_metadata.num_par_softmax_segments = segments
attn_metadata.softmax_segm_output = self.softmax_segm_output.view(
-1, self.num_heads_q, segments, self.softmax_segm_output.shape[-1]
)
attn_metadata.softmax_segm_max = self.softmax_segm_max.view(
-1, self.num_heads_q, segments
)
attn_metadata.softmax_segm_expsum = self.softmax_segm_expsum.view(
-1, self.num_heads_q, segments
)
mm_ranges = common_attn_metadata.mm_req_doc_ranges
if mm_ranges is not None:
@@ -56,7 +56,7 @@ class TritonAttentionDiffKVMetadataBuilder(TritonAttentionMetadataBuilder):
head_size_v_padded = next_power_of_2(head_size_v)
self.softmax_segm_output = torch.empty(
(
self.seq_threshold_3D,
self.softmax_segm_max.shape[0],
self.num_heads_q,
self.num_par_softmax_segments,
head_size_v_padded,
+5 -7
View File
@@ -291,7 +291,10 @@ def resolve_kv_cache_layout(
# specs can re-interpret HNC with different sizes as long as the total number of
# bytes is the same. If not block-compact, each spec must agree on HNC to alias
# the same page (this aliasing is done by the Hybrid Memory Allocator, HMA).
kv_cache_specs = tuple(kv_cache_specs or ())
# Specs without per-layer views lay out their own raw backing tensor.
kv_cache_specs = tuple(
spec for spec in kv_cache_specs or () if spec.has_layer_views
)
hnc_shapes = {
(spec.num_heads, spec.num_states, spec.page_size_bytes)
for spec in kv_cache_specs
@@ -1162,11 +1165,6 @@ def mamba_get_block_table_tensor(
"""Get the block table tensor for mamba kernels from the input
common_attn_metadata.block_table_tensor given different mamba cache modes.
- "all": input (#requests, cdiv(max_model_len, block_size)
+ num_speculative_blocks);
output (#requests, cdiv(max_model_len, block_size)
+ num_speculative_blocks).
- "none": input (#requests, 1 + num_speculative_blocks);
output (#requests, 1 + num_speculative_blocks).
@@ -1174,7 +1172,7 @@ def mamba_get_block_table_tensor(
output (#requests, 1 + num_speculative_blocks), which are the last
1 + num_speculative_blocks of each request.
"""
if mamba_cache_mode in ("all", "none"):
if mamba_cache_mode == "none":
return block_table
else:
assert isinstance(kv_cache_spec, MambaSpec)
+24 -8
View File
@@ -12,29 +12,42 @@ def _gather_prefill_cache_inputs(
tensors: tuple[torch.Tensor, ...],
slot_mapping: torch.Tensor,
num_decode_tokens: int,
shard_decode_requests: bool = False,
) -> tuple[tuple[torch.Tensor, ...], torch.Tensor]:
"""Keep replicated decode writes local and gather partitioned prefills."""
"""Gather PCP cache inputs while preserving replicated KV-cache state.
PCP-only execution shards decode requests across ranks. In that mode each
rank must gather the other owners' decode KV as well as partitioned prefill
KV so every PCP rank retains a complete cache replica. DCP execution keeps
decode requests replicated and uses the legacy prefill-only gather.
"""
local_num_tokens = tensors[0].shape[0]
assert all(tensor.shape[0] == local_num_tokens for tensor in tensors)
assert 0 <= num_decode_tokens <= local_num_tokens
# Replicated draft decodes use unexpanded slot mappings, even with DP padding.
if (
num_decode_tokens == local_num_tokens
or slot_mapping.shape[0] <= local_num_tokens
):
if slot_mapping.shape[0] <= local_num_tokens:
return (
tuple(tensor[:num_decode_tokens] for tensor in tensors),
slot_mapping[:num_decode_tokens],
)
pcp_group = get_pcp_group()
pcp_size = pcp_group.world_size
gathered_slot_mapping = slot_mapping[: pcp_size * local_num_tokens]
if shard_decode_requests:
gathered_inputs = tuple(
pcp_group.all_gather(tensor.contiguous(), dim=0) for tensor in tensors
)
return gathered_inputs, gathered_slot_mapping
if num_decode_tokens == local_num_tokens:
return tensors, slot_mapping[:num_decode_tokens]
gathered_prefills = tuple(
pcp_group.all_gather(tensor[num_decode_tokens:].contiguous(), dim=0)
for tensor in tensors
)
pcp_size = pcp_group.world_size
gathered_slot_mapping = slot_mapping[: pcp_size * local_num_tokens]
if num_decode_tokens == 0:
return gathered_prefills, gathered_slot_mapping
@@ -58,6 +71,7 @@ def maybe_gather_mla_latent_cache_inputs(
slot_mapping: torch.Tensor | None,
num_decode_tokens: int | None,
use_pcp: bool,
pcp_shard_decode_requests: bool = False,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
if not use_pcp or num_decode_tokens is None:
return kv_c_normed, k_pe, slot_mapping
@@ -68,6 +82,7 @@ def maybe_gather_mla_latent_cache_inputs(
(kv_c_normed, k_pe_flat),
slot_mapping,
num_decode_tokens,
pcp_shard_decode_requests,
)
cache_k_pe = cache_k_pe_flat.view(-1, *k_pe.shape[1:])
return cache_kv_c, cache_k_pe, cache_slot_mapping
@@ -78,11 +93,12 @@ def maybe_gather_indexer_k(
slot_mapping: torch.Tensor,
num_decode_tokens: int,
use_pcp: bool,
pcp_shard_decode_requests: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
if not use_pcp:
return k, slot_mapping
(cache_k,), cache_slot_mapping = _gather_prefill_cache_inputs(
(k,), slot_mapping, num_decode_tokens
(k,), slot_mapping, num_decode_tokens, pcp_shard_decode_requests
)
return cache_k, cache_slot_mapping
@@ -0,0 +1,676 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Sparse attention indexer on aiter's paged MXFP4 MQA-logits kernel.
gfx950 only. The kernel reads the preshuffled paged indexer K cache in place,
so no layer gathers K into a contiguous buffer, prefill included. Any model
whose indexer supplies the inputs `rocm_mxfp4_sparse_attn_indexer` documents
can run the dense path. DeepSeek-V4.1's two-level indexer adds to it: the
candidate source takes its block maxima from the same walk that writes its
logits, and the candidate consumers can walk the candidate pool instead of
the whole context: the pool is resolved once per step and shared by all of
them.
"""
import functools
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, NamedTuple
import torch
import vllm.envs as envs
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CUDAGraphMode
from vllm.forward_context import get_forward_context
from vllm.model_executor.kernels.attention.dsa.candidate_blocks import (
apply_candidate_mask,
)
from vllm.triton_utils import tl, triton
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_apply_candidate_mask_strided,
_max_decode_logits_rows,
)
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerPrefillChunkMetadata,
)
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
RocmMxfp4GatherLaunch,
RocmMxfp4IndexerMetadata,
RocmMxfp4NativeDecode,
RocmMxfp4PrefillPlan,
)
MXFP4_BLOCK_SIZE = 32
@functools.cache
def _aiter():
"""The aiter module with the paged MXFP4 MQA-logits launcher, its schedule
and cache_format."""
from aiter.ops.triton.attention import pa_mqa_logits_mxfp4
return pa_mqa_logits_mxfp4
@functools.cache
def _aiter_topk() -> Callable[..., None]:
"""The aiter per-row top-k."""
from aiter.ops.topk import top_k_per_row_decode
return top_k_per_row_decode
class RocmPagedMxfp4CacheLayout(NamedTuple):
"""The byte order of an indexer K page, as the kernel reads it, and the
shuffle pattern aiter's K cache op writes it with.
A page is cut into runs of ``n_per_tile`` tokens. Inside a run, each token's
packed values are split into ``d_per_tile``-byte chunks along the head
dimension, and the run stores chunk 0 of every token, then chunk 1, and so
on: ``[chunk, token, byte]``. Its e8m0 scales are stored as
``[scale % scale_lanes, token, scale // scale_lanes]``.
"""
n_per_tile: int
d_per_tile: int
scale_lanes: int
# The scale order the kernel reads: aiter's mode 1, a lane's scales innermost.
# cache_format does not report the order or the lane split yet.
_SCALE_ORDER = 1
_WAVE_SIZE = 64
@functools.cache
def rocm_paged_mxfp4_cache_layout(
num_heads: int, head_dim: int, page_entries: int
) -> RocmPagedMxfp4CacheLayout:
"""The K page layout from aiter's ``cache_format``, the only place vLLM
reads it, so a change there cannot reach the writer unchecked.
Raises:
ValueError: aiter rejects the page size, or describes an order this
layout cannot express.
"""
fmt = _aiter().cache_format(num_heads, head_dim, page_entries)
try:
n_per_tile = int(fmt["n_per_tile"])
d_per_tile = int(fmt["d_per_tile"])
scale_order = fmt.get("scale_mode", _SCALE_ORDER)
scale_lanes = int(fmt.get("scale_lanes", _WAVE_SIZE // n_per_tile))
except (KeyError, TypeError, ValueError, ZeroDivisionError) as e:
raise ValueError(f"aiter's cache_format() returned {fmt!r}") from e
if (
scale_order != _SCALE_ORDER
or min(n_per_tile, d_per_tile, scale_lanes) <= 0
or page_entries % n_per_tile
or (head_dim // 2) % d_per_tile
or (head_dim // MXFP4_BLOCK_SIZE) % scale_lanes
):
raise ValueError(
f"aiter's cache_format() returned {fmt!r} for {num_heads} heads of "
f"{head_dim} in {page_entries}-entry pages, a K page order "
"RocmPagedMxfp4CacheLayout cannot express"
)
return RocmPagedMxfp4CacheLayout(n_per_tile, d_per_tile, scale_lanes)
def rocm_mxfp4_decode_schedule_words(
num_heads: int, head_dim: int, page_entries: int, next_n: int = 1
) -> int:
"""int32 words of the largest schedule a decode step can build, flattened or
not. The slice cap can take it past target_wgs, up to SCHED_SLOT_CAP."""
words = 4 * _aiter().SCHED_SLOT_CAP
for rows in {1, next_n}:
config = _aiter().select_config(num_heads, head_dim, rows, page_entries)
words = max(words, 4 * config["target_wgs"])
return words
def build_rocm_mxfp4_decode_schedule(
row_lens: torch.Tensor,
num_heads: int,
head_dim: int,
page_entries: int,
out: torch.Tensor,
logits_width: int,
native: "RocmMxfp4NativeDecode | None" = None,
) -> torch.Tensor | None:
"""Work descriptors that even out a decode step, or None where the static
grid already fills the machine. Depends only on the rows' lengths, the
cache geometry and the logits width, so one serves every layer of a group.
The width sizes the slices, capped the way the static grid caps them."""
if native is None:
return _aiter().build_schedule(
row_lens,
1,
num_heads,
head_dim,
page_entries,
out=out,
max_model_len=logits_width,
)
return _aiter().build_schedule(
native.context_lens,
native.next_n,
num_heads,
head_dim,
page_entries,
out=out,
row_ends=row_lens,
max_model_len=logits_width,
)
def _kv_view(kv_cache: torch.Tensor, head_dim: int) -> torch.Tensor:
"""The indexer cache as [pages, entries, 1, bytes]. The page stride is the
block-major pool's, not the page's own size."""
num_pages, entries, width = kv_cache.shape
assert kv_cache.dtype == torch.uint8
assert width == head_dim // 2 + head_dim // MXFP4_BLOCK_SIZE, width
return torch.as_strided(
kv_cache, (num_pages, entries, 1, width), (kv_cache.stride(0), width, width, 1)
)
def rocm_mxfp4_consumer_rows(num_candidate_cols: int) -> int:
"""Query rows per candidate-consumer launch. Its logits are [rows, pool]
fp32 whatever the context, so the logits budget alone sizes it."""
budget = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
return max(1, budget // (4 * num_candidate_cols))
def reserve_rocm_mxfp4_indexer_workspace(
hidden_states: torch.Tensor,
logits_width: int,
candidate_block_size: int = 0,
gather_block_size: int = 0,
num_candidate_cols: int = 0,
) -> None:
"""Profiling run: claim the decode logits workspace and the peak prefill
logits, block scores included when the layer writes them, candidate lists
when it gathers."""
rows = _max_decode_logits_rows(hidden_states.shape[0])
specs = [((rows, logits_width), torch.float32)]
budget = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
if candidate_block_size:
nblocks = triton.cdiv(logits_width, candidate_block_size)
specs.append(((rows, nblocks), torch.float32))
budget += budget // candidate_block_size
if gather_block_size:
# aiter allocates the candidate lists: each gathered row, 8 B per
# candidate block (int32 slot and position). The first consumer builds
# them and they live until the step ends, across the later layers, so
# one reservation is held for the rest of the forward.
held = get_forward_context().additional_kwargs
if "rocm_mxfp4_candidate_lists" not in held:
held["rocm_mxfp4_candidate_lists"] = torch.empty(
hidden_states.shape[0] * (num_candidate_cols // gather_block_size) * 8,
dtype=torch.uint8,
device=hidden_states.device,
)
current_workspace_manager().get_simultaneous(*specs)
torch.empty(budget, dtype=torch.uint8, device=hidden_states.device)
def _topk(
logits: torch.Tensor, lengths: torch.Tensor, out: torch.Tensor, k: int
) -> None:
"""Top-k over each row's [0, lengths[row]); -1 pads rows shorter than k.
aiter's kernel is faster on the candidate top-k and from 128 rows on; below
that, a wide decode step is faster on vLLM's. Shape alone decides, so a FULL
graph replays the same choice at every context length.
"""
rows, width = logits.shape
if rows == 0:
return
if width >= k and (k >= 2048 or rows >= 128):
_aiter_topk()(
logits,
1,
lengths.reshape(-1),
out,
rows,
logits.stride(0),
logits.stride(1),
k=k,
)
else:
torch.ops._C.top_k_per_row_decode(
logits, 1, lengths, out, rows, logits.stride(0), logits.stride(1), k
)
@triton.jit
def _remap_compact_topk_kernel(
idx_ptr,
idx_stride,
pos_ptr,
pos_stride,
K: tl.constexpr,
BLOCK: tl.constexpr,
PADDED_K: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
cols = tl.arange(0, PADDED_K)
live = cols < K
slot = tl.load(idx_ptr + row * idx_stride + cols, mask=live, other=-1)
hit = slot >= 0
slot = tl.where(hit, slot, 0)
start = tl.load(
pos_ptr + row * pos_stride + slot // BLOCK, mask=live & hit, other=0
)
tl.store(
idx_ptr + row * idx_stride + cols,
tl.where(hit, start + slot % BLOCK, -1).to(tl.int32),
mask=live,
)
def _remap_compact_topk(
indices: torch.Tensor, positions: torch.Tensor, block: int
) -> None:
"""Candidate slots to context positions, in place: slot j sits in pool
block j // block, which starts at positions[j // block]."""
rows, k = indices.shape
if rows == 0:
return
_remap_compact_topk_kernel[(rows,)](
indices,
indices.stride(0),
positions,
positions.stride(0),
K=k,
BLOCK=block,
PADDED_K=triton.next_power_of_2(k),
num_warps=4,
)
@dataclass
class _Layer:
"""One indexer layer's inputs and outputs for this step."""
metadata: "RocmMxfp4IndexerMetadata"
kv: torch.Tensor
q: torch.Tensor
q_scale: torch.Tensor
weights: torch.Tensor
topk_buffer: torch.Tensor
topk_tokens: int
compress_ratio: int
candidates: torch.Tensor | None
block: int
full_graph: bool
@property
def num_heads(self) -> int:
return self.q.shape[1]
@property
def head_dim(self) -> int:
return self.q.shape[2] * 2
def rows(self, lo: int, hi: int, seqs: int = 1) -> tuple[torch.Tensor, ...]:
"""Q, its scales and the weights of token rows [lo, hi), as ``seqs``
sequences of next_n rows each."""
return (
self.q[lo:hi].view(seqs, -1, *self.q.shape[1:]),
self.q_scale[lo:hi].view(seqs, -1, *self.q_scale.shape[1:]),
self.weights[lo:hi],
)
def decode_rows(self, n: int) -> tuple[torch.Tensor, ...]:
"""The first n token rows, one sequence each."""
return (
self.q[:n].unsqueeze(1),
self.q_scale[:n].unsqueeze(1),
self.weights[:n],
)
def _layer(
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_indices_buffer: torch.Tensor,
topk_tokens: int,
head_dim: int,
compress_ratio: int,
candidate_blocks: torch.Tensor | None,
candidate_block_size: int,
) -> _Layer:
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
RocmMxfp4IndexerMetadata,
)
forward_context = get_forward_context()
attn_metadata = forward_context.attn_metadata
assert isinstance(attn_metadata, dict)
metadata = attn_metadata[k_cache_prefix]
assert isinstance(metadata, RocmMxfp4IndexerMetadata), (
"the ROCm MXFP4 indexer needs RocmMxfp4IndexerMetadataBuilder metadata"
)
kv = _kv_view(kv_cache, head_dim)
num_heads = q_values.shape[1]
return _Layer(
metadata=metadata,
kv=kv,
q=q_values,
# The fused Q kernel returns one int32 per head; the kernel reads the
# four ue8m0 bytes behind it.
q_scale=q_scale.view(torch.uint8).view(q_scale.shape[0], num_heads, -1),
weights=weights,
topk_buffer=topk_indices_buffer,
topk_tokens=topk_tokens,
compress_ratio=compress_ratio,
candidates=candidate_blocks,
block=candidate_block_size,
full_graph=forward_context.cudagraph_runtime_mode == CUDAGraphMode.FULL,
)
def _block_scores(layer: _Layer, scores: torch.Tensor | None) -> dict:
if scores is None:
return {}
return dict(
calc_block_scores=True, block_scores=scores, candidate_block_size=layer.block
)
def _dense_prefill(
layer: _Layer,
chunk: "DeepseekV32IndexerPrefillChunkMetadata",
plan: "RocmMxfp4PrefillPlan",
candidate_write: bool,
) -> None:
pa = _aiter()
t0, t1 = chunk.token_start, chunk.token_end
logits = layer.q.new_empty((t1 - t0, plan.width), dtype=torch.float32)
scores = None
if candidate_write:
nblocks = triton.cdiv(plan.width, layer.block)
scores = layer.q.new_empty((t1 - t0, nblocks), dtype=torch.float32)
# One launch for the chunk: the kernel finds each row's request from
# query_start_loc on its own grid.
pa.paged_mxfp4_mqa_logits(
layer.q[t0:t1],
layer.q_scale[t0:t1],
layer.kv,
layer.weights[t0:t1],
plan.context_lens,
chunk.block_table,
plan.width,
out_logits=logits,
clean_logits=False,
row_ends=plan.row_ends,
query_start_loc=plan.query_start_loc,
**_block_scores(layer, scores),
)
candidates = None if layer.candidates is None else layer.candidates[t0:t1]
if scores is not None:
assert candidates is not None and plan.block_ends is not None
_topk(scores, plan.block_ends, candidates, candidates.shape[1])
elif candidates is not None:
apply_candidate_mask(logits, None, plan.row_ends, candidates, layer.block)
_topk(
logits,
plan.row_ends,
layer.topk_buffer[t0:t1, : layer.topk_tokens],
layer.topk_tokens,
)
def _dense_decode(layer: _Layer, logits_width: int, candidate_write: bool) -> None:
metadata = layer.metadata
lengths = metadata.decode_row_lens
assert metadata.decode is not None and lengths is not None
rows = lengths.shape[0]
specs = [((rows, logits_width), torch.float32)]
if candidate_write:
specs.append(((rows, triton.cdiv(logits_width, layer.block)), torch.float32))
logits, *scores = current_workspace_manager().get_simultaneous(*specs)
native = metadata.decode_native
if native is not None:
# A request's next_n rows go in as one sequence, so a workgroup walks
# each KV tile once for all of them.
q, q_scale, weights = layer.rows(0, rows, native.context_lens.shape[0])
context_lens, block_table, row_ends = (
native.context_lens,
native.block_table,
lengths,
)
else:
q, q_scale, weights = layer.decode_rows(rows)
context_lens, block_table, row_ends = lengths, metadata.decode.block_table, None
assert block_table.shape[0] == rows, "one block-table row per query row"
_aiter().paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
context_lens,
block_table,
logits_width,
out_logits=logits,
clean_logits=False,
row_ends=row_ends,
schedule=metadata.decode_schedule,
**_block_scores(layer, scores[0] if scores else None),
)
candidates = None if layer.candidates is None else layer.candidates[:rows]
if scores:
assert candidates is not None and metadata.decode_block_ends is not None
_topk(scores[0], metadata.decode_block_ends, candidates, candidates.shape[1])
elif candidates is not None:
_apply_candidate_mask_strided(logits, None, lengths, candidates, layer.block)
_topk(
logits,
lengths,
layer.topk_buffer[:rows, : layer.topk_tokens],
layer.topk_tokens,
)
def _gather_prefill(
layer: _Layer, launch: "RocmMxfp4GatherLaunch", num_cols: int
) -> None:
pa = _aiter()
assert layer.candidates is not None
t0, t1 = launch.token_start, launch.token_end
if launch.pool is None:
launch.pool = pa.build_candidate_gather(
layer.candidates[t0:t1],
launch.row_ends,
launch.block_table.expand(t1 - t0, -1),
layer.kv,
layer.num_heads,
layer.head_dim,
layer.block,
)
gather, slot_ends = launch.pool
compact = layer.q.new_empty((t1 - t0, num_cols), dtype=torch.float32)
q, q_scale, weights = layer.rows(t0, t1)
pa.paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
launch.context_len,
launch.block_table,
num_cols,
out_logits=compact,
clean_logits=False,
row_ends=slot_ends,
use_gather=True,
candidates=gather,
)
out = layer.topk_buffer[t0:t1, : layer.topk_tokens]
_topk(compact, slot_ends, out, layer.topk_tokens)
_remap_compact_topk(out, gather["positions"], layer.block)
def _gather_decode(layer: _Layer, num_cols: int) -> None:
pa = _aiter()
assert layer.candidates is not None
metadata = layer.metadata
lengths = metadata.decode_row_lens
assert metadata.decode is not None and lengths is not None
block_table = metadata.decode.block_table
rows = lengths.shape[0]
if metadata.decode_gather is None:
metadata.decode_gather = pa.build_candidate_gather(
layer.candidates[:rows],
lengths,
block_table,
layer.kv,
layer.num_heads,
layer.head_dim,
layer.block,
)
gather, slot_ends = metadata.decode_gather
(compact,) = current_workspace_manager().get_simultaneous(
((rows, num_cols), torch.float32)
)
q, q_scale, weights = layer.decode_rows(rows)
pa.paged_mxfp4_mqa_logits(
q,
q_scale,
layer.kv,
weights,
lengths,
block_table,
num_cols,
out_logits=compact,
clean_logits=False,
row_ends=slot_ends,
use_gather=True,
candidates=gather,
)
out = layer.topk_buffer[:rows, : layer.topk_tokens]
_topk(compact, slot_ends, out, layer.topk_tokens)
_remap_compact_topk(out, gather["positions"], layer.block)
@eager_break_during_capture
def rocm_mxfp4_sparse_attn_indexer(
hidden_states: torch.Tensor,
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_tokens: int,
head_dim: int,
max_model_len: int,
topk_indices_buffer: torch.Tensor,
compress_ratio: int = 1,
candidate_blocks: torch.Tensor | None = None,
candidate_block_size: int = 0,
candidate_write: bool = False,
) -> torch.Tensor:
"""Dense indexer: every layer that scores the whole context, the
candidate source included. With ``candidate_blocks`` and not
``candidate_write`` the scores are masked to the pool first, as the
shared path does.
The model supplies ``q_values`` [T, H, D // 2] packed e2m1, ``q_scale``
holding each head's D // 32 ue8m0 bytes (one int32 per head at D = 128),
fp32 ``weights`` with the softmax and head scales folded in, and
``kv_cache`` pages in `rocm_paged_mxfp4_cache_layout` order for H heads.
"""
if not isinstance(get_forward_context().attn_metadata, dict):
reserve_rocm_mxfp4_indexer_workspace(
hidden_states,
max_model_len,
candidate_block_size if candidate_write else 0,
)
return topk_indices_buffer
layer = _layer(
k_cache_prefix,
kv_cache,
q_values,
q_scale,
weights,
topk_indices_buffer,
topk_tokens,
head_dim,
compress_ratio,
candidate_blocks,
candidate_block_size,
)
metadata = layer.metadata
topk_indices_buffer[: hidden_states.shape[0]] = -1
if metadata.prefill is not None:
for chunk, plan in zip(metadata.prefill.chunks, metadata.prefill_plans):
_dense_prefill(layer, chunk, plan, candidate_write)
if metadata.decode is not None:
_dense_decode(layer, max_model_len, candidate_write)
return topk_indices_buffer
@eager_break_during_capture
def rocm_mxfp4_sparse_mqa_indexer(
hidden_states: torch.Tensor,
k_cache_prefix: str,
kv_cache: torch.Tensor,
q_values: torch.Tensor,
q_scale: torch.Tensor,
weights: torch.Tensor,
topk_tokens: int,
head_dim: int,
max_model_len: int,
topk_indices_buffer: torch.Tensor,
compress_ratio: int,
candidate_blocks: torch.Tensor,
candidate_block_size: int,
num_candidate_cols: int,
) -> torch.Tensor:
"""Candidate consumer: score only the source's pool where the builder's
length gate says it pays, else the dense walk masked to the pool."""
if not isinstance(get_forward_context().attn_metadata, dict):
reserve_rocm_mxfp4_indexer_workspace(
hidden_states,
max(max_model_len, num_candidate_cols),
gather_block_size=candidate_block_size,
num_candidate_cols=num_candidate_cols,
)
return topk_indices_buffer
layer = _layer(
k_cache_prefix,
kv_cache,
q_values,
q_scale,
weights,
topk_indices_buffer,
topk_tokens,
head_dim,
compress_ratio,
candidate_blocks,
candidate_block_size,
)
metadata = layer.metadata
topk_indices_buffer[: hidden_states.shape[0]] = -1
if metadata.prefill is not None:
for chunk, plan in zip(metadata.prefill.chunks, metadata.prefill_plans):
if not plan.use_gather:
_dense_prefill(layer, chunk, plan, candidate_write=False)
for launch in metadata.gather_launches:
_gather_prefill(layer, launch, num_candidate_cols)
if metadata.decode is not None:
# A FULL graph cannot follow the per-step gate; the gather is the side
# that stays flat in the context length.
if metadata.decode_use_gather or layer.full_graph:
_gather_decode(layer, num_candidate_cols)
else:
_dense_decode(layer, max_model_len, candidate_write=False)
return topk_indices_buffer
@@ -217,7 +217,7 @@ def kernel_unified_attention(
SLIDING_WINDOW: tl.constexpr, # int
USE_CAUSAL: tl.constexpr, # bool
USE_PER_SEQ_CAUSAL: tl.constexpr, # bool
per_seq_causal_ptr, # [num_seqs] bool, or None
per_seq_causal_ptr, # [num_seqs] int32, or None
USE_MM_PREFIX: tl.constexpr, # bool
MAX_MM_RANGES: tl.constexpr, # int
mm_prefix_range_ptr,
+29 -15
View File
@@ -58,13 +58,15 @@ def flash_attn_maxseqlen_wrapper(
max_seqlen = max_seqlen.item()
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v])
if current_platform.is_cuda() and torch.cuda.is_current_stream_capturing():
# workaround for encoder CUDA-graph replay paddings with NaNs edge case
kwargs["out"] = torch.zeros(
q.shape[0], q.shape[1], v.shape[-1], dtype=q.dtype, device=q.device
)
supports_out = not current_platform.is_rocm()
if supports_out:
if current_platform.is_cuda() and torch.cuda.is_current_stream_capturing():
# workaround for encoder CUDA-graph replay paddings with NaNs edge case
kwargs["out"] = torch.zeros(
q.shape[0], q.shape[1], v.shape[-1], dtype=q.dtype, device=q.device
)
else:
kwargs["out"] = torch.empty_like(q, memory_format=torch.contiguous_format)
output = flash_attn_varlen_func(
q,
k,
@@ -78,6 +80,8 @@ def flash_attn_maxseqlen_wrapper(
softmax_scale=scale,
**kwargs,
)
if not supports_out:
output = output.contiguous()
context_layer = einops.rearrange(output, "(b s) h d -> b s h d", b=batch_size)
return context_layer
@@ -93,7 +97,7 @@ def flash_attn_maxseqlen_wrapper_fake(
cu_seqlens: torch.Tensor | None = None,
max_seqlen: torch.Tensor | None = None,
) -> torch.Tensor:
return torch.empty_like(q)
return torch.empty_like(q, memory_format=torch.contiguous_format)
direct_register_custom_op(
@@ -179,7 +183,7 @@ def triton_attn_wrapper(
max_seqlen = max_seqlen.item()
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v])
output = torch.empty_like(q)
output = torch.empty_like(q, memory_format=torch.contiguous_format)
context_attention_fwd(
q,
k,
@@ -207,7 +211,7 @@ def triton_attn_wrapper_fake(
cu_seqlens: torch.Tensor | None = None,
max_seqlen: torch.Tensor | None = None,
) -> torch.Tensor:
return torch.empty_like(q)
return torch.empty_like(q, memory_format=torch.contiguous_format)
direct_register_custom_op(
@@ -281,7 +285,7 @@ def torch_sdpa_wrapper(
v = v.contiguous()
if cu_seqlens is None:
return apply_sdpa(q, k, v, scale=scale, enable_gqa=enable_gqa)
return apply_sdpa(q, k, v, scale=scale, enable_gqa=enable_gqa).contiguous()
outputs = []
@@ -302,11 +306,11 @@ def torch_sdpa_wrapper_fake(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
scale: float | None,
cu_seqlens: torch.Tensor | None,
scale: float | None = None,
cu_seqlens: torch.Tensor | None = None,
enable_gqa: bool = False,
) -> torch.Tensor:
return torch.empty_like(q)
return torch.empty_like(q, memory_format=torch.contiguous_format)
direct_register_custom_op(
@@ -368,6 +372,11 @@ def flashinfer_wrapper(
with gpu_sync_allowed():
max_seqlen = max_seqlen.item()
output_buffer = torch.empty_like(
q,
dtype=o_data_type,
memory_format=torch.contiguous_format,
)
output, _ = cudnn_batch_prefill_with_kv_cache(
q,
k,
@@ -388,6 +397,7 @@ def flashinfer_wrapper(
k_scale=k_scale,
v_scale=v_scale,
o_data_type=o_data_type,
out=output_buffer,
)
if is_reshaped:
@@ -410,7 +420,11 @@ def vit_flashinfer_wrapper_fake(
v_scale: torch.Tensor | None = None,
o_data_type: torch.dtype | None = None,
) -> torch.Tensor:
return torch.empty_like(q, dtype=o_data_type or q.dtype)
return torch.empty_like(
q,
dtype=o_data_type,
memory_format=torch.contiguous_format,
)
direct_register_custom_op(
+3 -2
View File
@@ -25,6 +25,7 @@ from vllm.v1.core.kv_cache_utils import (
make_block_hash_with_group_id,
maybe_convert_block_hash,
resolve_block_hashes,
to_event_extra_keys,
)
from vllm.v1.request import Request
@@ -367,7 +368,7 @@ class BlockPool:
lora_id=request.lora_request.adapter_id if request.lora_request else None,
medium=self.medium,
lora_name=request.lora_request.name if request.lora_request else None,
extra_keys=extra_keys_list if extra_keys_list else None,
extra_keys=to_event_extra_keys(extra_keys_list),
group_idx=kv_cache_group_id,
session_id=request.session_id,
)
@@ -557,7 +558,7 @@ class BlockPool:
lora_name=request.lora_request.name
if request.lora_request
else None,
extra_keys=[extra_keys],
extra_keys=to_event_extra_keys([extra_keys]),
group_idx=kv_cache_group_id,
session_id=request.session_id,
)
+9
View File
@@ -174,6 +174,7 @@ class KVCacheCoordinator(ABC):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
"""Get the number of device blocks needed to be allocated for the request.
@@ -195,12 +196,19 @@ class KVCacheCoordinator(ABC):
per-request admission cap (SWA / chunked-local). Set only by
the full-sequence admission gate; per-step allocation must
leave it False so the predictor matches `allocate_new_blocks`.
prefill_end: The token index the request's prefill ends at, the
same value the scheduler splits chunks against. Under sparse
retention Mamba reserves a prefill checkpoint only on the chunk
reaching it; under dense retention every chunk publishes a
state, so it is ignored (0).
Returns:
The number of blocks to allocate.
"""
num_blocks_to_allocate = 0
if self.retention_interval != 0:
prefill_end = 0
for i, manager in enumerate(self.single_type_managers):
if isinstance(manager, CrossAttentionManager):
# For cross-attention, we issue a single static allocation
@@ -223,6 +231,7 @@ class KVCacheCoordinator(ABC):
num_local_computed_tokens,
num_tokens_main_model,
apply_admission_cap=apply_admission_cap,
prefill_end=prefill_end,
)
return num_blocks_to_allocate
+6
View File
@@ -512,6 +512,10 @@ class KVCacheManager:
):
watermark_blocks = self.watermark_blocks
# Matches the scheduler's own prefill boundary: `num_tokens - 1`
# extends it to resumed requests replaying their output tokens.
prefill_end = max(request.num_prompt_tokens, request.num_tokens - 1)
if full_sequence_must_fit:
# First check and fail if the full request sequence won't fit.
full_num_tokens = min(request.num_tokens, self.max_model_len)
@@ -525,6 +529,7 @@ class KVCacheManager:
num_local_computed_tokens=num_local_computed_tokens,
num_tokens_main_model=full_num_tokens,
apply_admission_cap=True,
prefill_end=prefill_end,
)
required_blocks = num_blocks_to_allocate + watermark_blocks
if required_blocks > self.block_pool.get_num_free_blocks():
@@ -559,6 +564,7 @@ class KVCacheManager:
+ num_external_computed_tokens,
num_local_computed_tokens=num_local_computed_tokens,
num_tokens_main_model=num_tokens_main_model,
prefill_end=prefill_end,
)
# Keep `reserved_blocks` free for other in-flight sequences, and an
+102 -25
View File
@@ -9,7 +9,7 @@ import os
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field, replace
from functools import partial
from functools import partial, reduce
from typing import TYPE_CHECKING, Any, NamedTuple, NewType, TypeAlias, cast, overload
from vllm import envs
@@ -21,7 +21,6 @@ from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.mem_utils import format_gib
from vllm.utils.torch_utils import get_dtype_size
from vllm.v1.hisparse.layout import (
get_hisparse_gpu_memory_usage,
get_hisparse_host_pool_bytes,
get_hisparse_kv_cache_config,
get_hisparse_kv_cache_groups,
@@ -502,8 +501,8 @@ def _gen_mm_extra_hash_keys(
) -> tuple[list[Any], int]:
"""Generate extra keys related to MultiModal request for block hash
computation. For multi-modal inputs, the extra keys are
(mm_hash, start_offset) that indicate a mm input contained in the
block and its starting offset in the block tokens.
("mm", mm_hash, start_offset) tuples that indicate a mm input contained
in the block and its starting offset in the block tokens.
Args:
request: The request object.
@@ -549,7 +548,7 @@ def _gen_mm_extra_hash_keys(
# relative to the start of the block so prefix-cache keys stay
# distinct when the same MM item appears at different positions
# within otherwise-identical placeholder blocks.
extra_keys.append((mm_feature.identifier, offset - start_token_idx))
extra_keys.append(("mm", mm_feature.identifier, offset - start_token_idx))
if end_token_idx >= offset + length:
# If this block contains the end of the current mm input,
@@ -565,25 +564,29 @@ def _gen_mm_extra_hash_keys(
return extra_keys, curr_mm_idx
def _gen_lora_extra_hash_keys(request: Request) -> list[str]:
def _gen_lora_extra_hash_keys(request: Request) -> list[tuple[str, str, str]]:
"""Generate extra keys related to LoRA for block hash computation.
The adapter path is included so that re-pointing a LoRA name at a different
adapter does not reuse KV computed with the previous one.
Args:
request: The request object.
Returns:
Return LoRA name of the request if it is a LoRA request. Return empty
list otherwise.
Return the LoRA name and path of the request if it is a LoRA request.
Return empty list otherwise.
"""
if not request.lora_request:
lora_request = request.lora_request
if not lora_request:
return []
return [request.lora_request.lora_name]
return [("lora", lora_request.lora_name, lora_request.lora_path)]
def _gen_prompt_embeds_extra_hash_keys(
request: Request, start_token_idx: int, end_token_idx: int
) -> list[bytes]:
) -> list[tuple[str, bytes]]:
"""Generate extra keys related to prompt embeds for block hash computation.
Args:
@@ -605,7 +608,7 @@ def _gen_prompt_embeds_extra_hash_keys(
# Hash prompt embeds once per block and cache on request
embeds_hash = hashlib.sha256(tensor_data(block_prompt_embeds)).digest()
request._prompt_embeds_per_block_hashes[block_range] = embeds_hash
return [embeds_hash]
return [("prompt_embeds", embeds_hash)]
def generate_block_hash_extra_keys(
@@ -629,9 +632,11 @@ def generate_block_hash_extra_keys(
mm_extra_keys, new_start_mm_idx = _gen_mm_extra_hash_keys(
request, start_token_idx, end_token_idx, start_mm_idx
)
lora_extra_keys: list[str] = _gen_lora_extra_hash_keys(request)
cache_salt_keys: list[str] = (
[request.cache_salt] if (start_token_idx == 0 and request.cache_salt) else []
lora_extra_keys = _gen_lora_extra_hash_keys(request)
cache_salt_keys: list[tuple[str, str]] = (
[("cache_salt", request.cache_salt)]
if (start_token_idx == 0 and request.cache_salt)
else []
)
prompt_embeds_keys = _gen_prompt_embeds_extra_hash_keys(
request, start_token_idx, end_token_idx
@@ -647,6 +652,35 @@ def generate_block_hash_extra_keys(
return tuple(extra_keys), new_start_mm_idx
def to_event_extra_keys(
extra_keys: Iterable[tuple[Any, ...] | None] | None,
) -> list[tuple[Any, ...] | None] | None:
"""Convert block-hash extra keys to the untagged per-block list published
in KV events.
External KV event consumers parse the pre-tagging shapes: bare LoRA names
and cache salts, ``(mm_identifier, offset)`` pairs and bare prompt-embeds
digests. Events keep that format until consumers handle the tagged keys.
Args:
extra_keys: One entry per block, each as returned by
`generate_block_hash_extra_keys`, or None.
Returns:
One untagged entry per block, or None if there are no entries.
"""
if not extra_keys:
return None
event_keys = [
None
if keys is None
else tuple(key[1:] if key[0] == "mm" else key[1] for key in keys)
for keys in extra_keys
]
return event_keys or None
def hash_block_tokens(
hash_function: Callable[[Any], bytes],
parent_block_hash: BlockHash | None,
@@ -714,7 +748,9 @@ def resolve_kv_cache_block_sizes(
group's effective block size. Attention groups are scaled by DCP;
Mamba groups keep their full per-rank state and are not scaled.
- ``hash_block_size`` is the granularity at which ``Request.block_hashes``
is computed. Single group: equals scheduler block size. Multiple groups:
is computed. Single group: equals scheduler block size, and any other
``cache_config.prefix_match_unit`` is rejected while block hashing is
active. Multiple groups:
``cache_config.prefix_match_unit`` override if set, else the GCD of
group block sizes; every group's block size must be divisible by it.
Returns the scheduler block size (i.e. disables finer hashing) if block
@@ -728,6 +764,21 @@ def resolve_kv_cache_block_sizes(
if groups and not groups[0].kv_cache_spec.dcp_sharded:
dcp = 1
bs = cache_config.block_size * dcp
# The Mamba prefill checkpoint builder reads prefix_match_unit directly,
# so a value dropped here puts its checkpoints off the scheduler's grid.
if (
cache_config.prefix_match_unit not in (None, bs)
and len(groups) == 1
and (
cache_config.enable_prefix_caching
or vllm_config.kv_transfer_config is not None
)
):
raise ValueError(
f"Invalid prefix_match_unit={cache_config.prefix_match_unit}; "
"with a single KV cache group, prefix-cache hits land on the "
f"block size ({bs}). Unset it or set it to {bs}."
)
return bs, bs
group_block_sizes = [
@@ -1103,7 +1154,9 @@ def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
`available_memory` into `num_blocks`. Used to compute the effective KV cache
capacity once `num_gpu_blocks_override` is applied.
"""
return _get_kv_cache_bytes_per_block(kv_cache_groups)
return _get_kv_cache_bytes_per_block(
[group for group in kv_cache_groups if not group.host_resident]
)
def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
@@ -2361,6 +2414,26 @@ def get_kv_cache_groups(
return groups
def _layer_tp_replicas(spec: KVCacheSpec, tp_size: int, dcp_size: int) -> int:
if not isinstance(spec, AttentionSpec) or spec.max_tp_shards is None:
return 1
if spec.dcp_sharded and dcp_size > 1:
return 1
return max(1, tp_size // spec.max_tp_shards)
def kv_cache_groups_tp_replicas(
groups: list[KVCacheGroupSpec], tp_size: int, dcp_size: int = 1
) -> int:
"""Consecutive TP ranks holding identical KV for every layer."""
specs = [spec for g in groups for spec in iter_layer_specs(g.kv_cache_spec)]
if not specs:
return 1
return reduce(
math.gcd, (_layer_tp_replicas(s, tp_size, dcp_size) for s in specs), tp_size
)
def generate_scheduler_kv_cache_config(
kv_cache_configs: list[KVCacheConfig],
) -> KVCacheConfig:
@@ -2428,12 +2501,10 @@ def _max_memory_usage_bytes_from_groups(
Each group independently claims blocks from the shared pool, so a request consumes
the sum of the per-group block counts, i.e. ``bytes_per_block * total_blocks``.
"""
kv_cache_groups = [group for group in kv_cache_groups if not group.host_resident]
if not kv_cache_groups:
return 0
if vllm_config.attention_config.hisparse_config is not None:
return get_hisparse_gpu_memory_usage(vllm_config, kv_cache_groups)
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
(
attn_group,
@@ -2491,12 +2562,11 @@ def _estimate_max_model_len_from_groups(
vllm_config.model_config.max_model_len = model_len
if hisparse_enabled:
try:
config = get_kv_cache_config_from_groups(
get_kv_cache_config_from_groups(
vllm_config, kv_cache_groups, available_memory
)
except ValueError:
return False
return get_max_concurrency_for_kv_cache_config(vllm_config, config) >= 1
return (
_max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups)
<= available_memory
@@ -2606,6 +2676,9 @@ def _project_kv_cache_groups_to_worker(
worker_layer_names = [
layer_name for layer_name in group.layer_names if layer_name in worker_spec
]
if len(worker_layer_names) == len(group.layer_names):
projected_groups.append(group)
continue
group_spec = group.kv_cache_spec
if worker_layer_names and isinstance(group_spec, UniformTypeKVCacheSpecs):
group_spec = UniformTypeKVCacheSpecs(
@@ -2721,9 +2794,6 @@ def get_kv_cache_configs(
adjusted_memory.append(override * bytes_per_block)
available_memory = adjusted_memory
if vllm_config.attention_config.hisparse_config is not None:
available_memory = [min(available_memory)] * len(available_memory)
# Reserve the null block BlockPool permanently holds back, so auto-fit and
# the capacity check both plan against usable blocks. Allocation below
# still uses the full memory.
@@ -2775,6 +2845,13 @@ def get_kv_cache_configs(
vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups)
)
for kv_cache_config in kv_cache_configs:
kv_cache_config.kv_tp_replicas = kv_cache_groups_tp_replicas(
kv_cache_config.kv_cache_groups,
vllm_config.parallel_config.tensor_parallel_size,
vllm_config.parallel_config.decode_context_parallel_size,
)
return kv_cache_configs
+19 -8
View File
@@ -1,15 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Async scheduling for diffusion requests.
These rules live here so Scheduler.schedule() and AsyncScheduler stay
unchanged. VllmConfig selects this class for a diffusion model under async
scheduling. A sync scheduler creates no output placeholders, which both rules
read.
"""
"""Canvas-width handling and async read deferral for diffusion requests."""
from vllm.v1.core.sched.async_scheduler import AsyncScheduler
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.outputs import DraftTokenIds
from vllm.v1.request import Request
@@ -38,7 +34,22 @@ def _read_in_flight(request: Request, width: int) -> bool:
return request.num_output_placeholders >= steps * width
class DiffusionAsyncScheduler(AsyncScheduler):
class DiffusionScheduler(Scheduler):
def update_draft_token_ids(self, draft_token_ids: DraftTokenIds) -> None:
for i, (req_id, token_ids) in enumerate(
zip(draft_token_ids.req_ids, draft_token_ids.draft_token_ids)
):
request = self.requests.get(req_id)
if request is None:
continue
width = diffusion_canvas_width(request, self.num_spec_tokens)
# Remove padded positions before the base scheduler validates grammar.
if len(token_ids) > width:
draft_token_ids.draft_token_ids[i] = token_ids[:width]
super().update_draft_token_ids(draft_token_ids)
class DiffusionAsyncScheduler(DiffusionScheduler, AsyncScheduler):
def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput:
for request in self.running:
width = diffusion_canvas_width(request, self.num_spec_tokens)
+5
View File
@@ -335,3 +335,8 @@ class GrammarOutput:
structured_output_request_ids: list[str]
# Bitmask ordered as structured_output_request_ids.
grammar_bitmask: "npt.NDArray[np.int32]"
# Per request, ordered as structured_output_request_ids: how many leading
# drafts the bitmask constrained. `grammar_bitmask` fills every row after
# the first -1 placeholder with the all-permissive `_full_mask`, so drafts
# from this index on must not be accepted. None invalidates every draft.
num_acceptable_drafts: list[int] | None = None
+45 -11
View File
@@ -62,6 +62,10 @@ from vllm.v1.kv_cache_interface import (
)
from vllm.v1.metrics.perf import ModelMetrics, PerfStats
from vllm.v1.metrics.stats import (
KV_FETCH_COMPLETED_WAITING,
KV_FETCH_IN_PROGRESS,
KV_FETCH_STAGES,
KV_FETCH_WAITING_TO_START,
PrefixCacheStats,
RequestSpecDecodeMetrics,
SchedulerStats,
@@ -71,6 +75,7 @@ from vllm.v1.request import Request, RequestStatus, StreamingUpdate
from vllm.v1.spec_decode.dynamic.utils import build_dynamic_sd_schedule_lookup
from vllm.v1.spec_decode.metrics import SpecDecodingStats
from vllm.v1.structured_output import StructuredOutputManager
from vllm.v1.structured_output.utils import strip_speculative_padding
from vllm.v1.utils import record_function_or_nullcontext
logger = init_logger(__name__)
@@ -411,6 +416,13 @@ class Scheduler(SchedulerInterface):
# async KV loads). Their remaining-block reservation gates async loads.
self._inflight_prefills: set[Request] = set()
# Requests with an async KV load, by stage (KV_FETCH_STAGES).
# None when not tracked (stats disabled or no KV connector).
self._kv_fetch_stages: dict[Request, str] | None = (
{} if self.log_stats and self.connector is not None else None
)
self._kv_fetch_counts: dict[str, int] = dict.fromkeys(KV_FETCH_STAGES, 0)
def _mamba_block_aligned_split(
self,
request: Request,
@@ -1038,6 +1050,9 @@ class Scheduler(SchedulerInterface):
num_local_cached_tokens=num_new_local_computed_tokens,
num_external_cached_tokens=num_external_computed_tokens,
)
self._set_kv_fetch_stage(
request, KV_FETCH_WAITING_TO_START if load_kv_async else None
)
else:
# KVTransfer: WAITING reqs have num_computed_tokens > 0
# after async KV recvs are completed. A streaming-input
@@ -1115,6 +1130,7 @@ class Scheduler(SchedulerInterface):
if (
not self.scheduler_config.enable_chunked_prefill
and num_new_tokens > request_token_budget
and not self.is_mm_encoder_only
):
# If chunked_prefill is disabled,
# we can stop the scheduling here.
@@ -1274,6 +1290,7 @@ class Scheduler(SchedulerInterface):
# only the successfully loaded tokens.
request.num_computed_tokens = num_computed_tokens
self._inflight_prefills.add(request)
self._set_kv_fetch_stage(request, KV_FETCH_IN_PROGRESS)
if self.needs_kv_cache_zeroing:
# Skip zeroing of the blocks the async load will
# overwrite; the zeroing could race the write.
@@ -1314,6 +1331,7 @@ class Scheduler(SchedulerInterface):
input_budget -= num_new_tokens + draft_slots
request.status = RequestStatus.RUNNING
request.num_computed_tokens = num_computed_tokens
self._set_kv_fetch_stage(request, None)
if pad_spec_decode:
assert num_new_tokens == 1 + self.num_spec_tokens
scheduled_spec_decode_tokens[request_id] = [
@@ -1962,7 +1980,14 @@ class Scheduler(SchedulerInterface):
structured_output_request_ids,
scheduler_output.scheduled_spec_decode_tokens,
)
return GrammarOutput(structured_output_request_ids, bitmask)
spec_tokens = scheduler_output.scheduled_spec_decode_tokens
num_acceptable_drafts = [
len(strip_speculative_padding(spec_tokens.get(req_id, [])))
for req_id in structured_output_request_ids
]
return GrammarOutput(
structured_output_request_ids, bitmask, num_acceptable_drafts
)
def update_from_output(
self,
@@ -2579,6 +2604,11 @@ class Scheduler(SchedulerInterface):
)
if self.connector is not None:
self.connector.on_new_request(request)
kv_transfer_params = request.kv_transfer_params
if kv_transfer_params and kv_transfer_params.get("do_remote_prefill"):
# Count P/D requests on arrival: connector matching is
# skipped while all run slots are taken.
self._set_kv_fetch_stage(request, KV_FETCH_WAITING_TO_START)
if self.log_stats:
request.record_event(EngineCoreEventType.QUEUED)
@@ -2655,6 +2685,7 @@ class Scheduler(SchedulerInterface):
if self.aux_output_connector is not None:
self.aux_output_connector.request_finished(request)
self._inflight_prefills.discard(request)
self._set_kv_fetch_stage(request, None)
connector_delay_free_blocks, kv_xfer_params = self._connector_finished(request)
# EC Connector: mirror the KV hook. The contract requires firing
@@ -2781,16 +2812,6 @@ class Scheduler(SchedulerInterface):
Otherwise, this method will only reset the KV prefix cache when there
is no running requests taking KV cache.
"""
if reset_running_requests and self.aux_output_connector is not None:
if self._pause_state != PauseState.PAUSED_ALL:
raise RuntimeError(
"AuxOutput Connector only supports resetting running requests "
"after pause(mode='keep')."
)
if any(request.num_in_flight_tokens for request in self.requests.values()):
raise RuntimeError(
"AuxOutput Connector cannot reset while model output is in flight."
)
if reset_running_requests:
# For logging.
timestamp = time.monotonic()
@@ -2890,6 +2911,7 @@ class Scheduler(SchedulerInterface):
num_running_reqs=num_running,
num_waiting_reqs=num_waiting - num_deferred,
num_skipped_waiting_reqs=num_deferred,
num_kv_fetch_reqs_by_stage=self._kv_fetch_counts.copy(),
kv_cache_usage=self.kv_cache_manager.usage,
prefix_cache_stats=prefix_cache_stats,
connector_prefix_cache_stats=connector_prefix_cache_stats,
@@ -3012,6 +3034,7 @@ class Scheduler(SchedulerInterface):
num_local_computed_tokens=request.num_computed_tokens,
num_tokens_main_model=full_num_tokens,
apply_admission_cap=True,
prefill_end=max(request.num_prompt_tokens, request.num_tokens - 1),
)
return num_blocks + self._spec_decode_step_blocks()
@@ -3028,6 +3051,16 @@ class Scheduler(SchedulerInterface):
1 + self.num_spec_tokens + self.num_lookahead_tokens, self.block_size
)
def _set_kv_fetch_stage(self, request: Request, stage: str | None) -> None:
kv_fetch_stages = self._kv_fetch_stages
if kv_fetch_stages is not None:
prev_stage = kv_fetch_stages.pop(request, None)
if prev_stage is not None:
self._kv_fetch_counts[prev_stage] -= 1
if stage is not None:
kv_fetch_stages[request] = stage
self._kv_fetch_counts[stage] += 1
def _inflight_prefill_reserved_blocks(self) -> int:
"""Num blocks in-flight prefills still need to finish (their reservation)."""
return sum(
@@ -3148,6 +3181,7 @@ class Scheduler(SchedulerInterface):
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
self._set_kv_fetch_stage(req, KV_FETCH_COMPLETED_WAITING)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
+54 -63
View File
@@ -112,7 +112,7 @@ class SingleTypeKVCacheManager(ABC):
self.kv_cache_spec = kv_cache_spec
self.block_pool = block_pool
self.enable_caching = enable_caching
self._max_admission_blocks_per_request = max_admission_blocks_per_request
self.max_admission_blocks_per_request = max_admission_blocks_per_request
# Record newly allocated block ids only when worker-side zeroing will
# consume them and this manager holds a spec type that gets zeroed.
self._record_new_block_ids = (
@@ -184,6 +184,7 @@ class SingleTypeKVCacheManager(ABC):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
"""Get the number of blocks needed to be allocated for the request.
@@ -201,15 +202,19 @@ class SingleTypeKVCacheManager(ABC):
model in spec decode). w/o spec decode, it is num_tokens;
with spec decode, it is num_tokens - num_lookahead_tokens.
apply_admission_cap: If True, clamp by `num_required_blocks` by
`_max_admission_blocks_per_request`for recycling-aware specs
`max_admission_blocks_per_request`for recycling-aware specs
(SWA, chunked-local).
prefill_end: The token index the request's prefill ends at, the
same value the scheduler splits chunks against. Mamba reserves
a prefill checkpoint only on the chunk reaching it; 0 (dense
retention) reserves one on every chunk.
Returns:
The number of blocks to allocate.
"""
num_required_blocks = cdiv(num_tokens, self.block_size)
if apply_admission_cap and self._max_admission_blocks_per_request is not None:
if apply_admission_cap and self.max_admission_blocks_per_request is not None:
# Recycling-aware specs (SWA, chunked-local) cap the per-request
# reservation here so admission matches the startup pool sizer
# (`SlidingWindowSpec.max_admission_blocks_per_request` / its
@@ -220,7 +225,7 @@ class SingleTypeKVCacheManager(ABC):
# Drift between the two would re-introduce the deadlock from
# issue #39734 or, worse, mid-prefill OOM.
num_required_blocks = min(
num_required_blocks, self._max_admission_blocks_per_request
num_required_blocks, self.max_admission_blocks_per_request
)
num_req_blocks = len(self.req_to_blocks.get(request_id, ()))
@@ -1215,6 +1220,7 @@ class CircularBufferManager(FullAttentionManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
return 0 if self.req_to_blocks.get(request_id) else 1
@@ -1687,12 +1693,14 @@ class MambaManager(SingleTypeKVCacheManager):
query_start: int,
query_end: int,
checkpoint_position: int,
prefill_end: int,
) -> bool:
assert isinstance(self.kv_cache_spec, MambaSpec)
checkpoint_idx = cdiv(query_end, self.block_size) - 2
blocks = self.req_to_blocks[request_id]
return (
self.has_prefill_checkpoint_blocks
and query_end >= prefill_end
and is_mamba_prefill_checkpoint_valid(
query_start=query_start,
query_end=query_end,
@@ -1721,6 +1729,7 @@ class MambaManager(SingleTypeKVCacheManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
assert isinstance(self.kv_cache_spec, MambaSpec)
if (
@@ -1747,6 +1756,7 @@ class MambaManager(SingleTypeKVCacheManager):
num_local_computed_tokens,
num_tokens_main_model,
apply_admission_cap=apply_admission_cap,
prefill_end=prefill_end,
)
else:
# We don't allocate blocks for lookahead tokens in align mode, because if
@@ -1774,6 +1784,11 @@ class MambaManager(SingleTypeKVCacheManager):
)
if has_partial_hit:
num_new_blocks = max(num_new_blocks, 0) + 1
# Keyed on the chunk end like the worker's
# `compute_mamba_prefill_checkpoints`, which writes the state there.
# The helper returns a boundary strictly below its input, so every
# chunk has one; under sparse retention only the prefill-end chunk's
# is kept, so `prefill_end` skips reserving blocks for the others.
checkpoint_position = get_mamba_prefill_checkpoint_position(
num_tokens,
self.block_pool.hash_block_size,
@@ -1784,6 +1799,7 @@ class MambaManager(SingleTypeKVCacheManager):
total_computed_tokens,
num_tokens,
checkpoint_position,
prefill_end,
):
checkpoint_position = 0
checkpoint_block = int(checkpoint_position > 0)
@@ -2051,9 +2067,21 @@ class MambaManager(SingleTypeKVCacheManager):
blocks = self.req_to_blocks[request.request_id]
assert 0 <= checkpoint_idx < len(blocks)
checkpoint_block = blocks[checkpoint_idx]
# The prompt's final chunk caches only up to its last full block,
# so ``num_tokens < num_prompt_tokens`` holds there too; its
# checkpoint is the prompt's reusable boundary, not a transient one.
is_prompt_checkpoint = (
checkpoint_position
== get_mamba_prefill_checkpoint_position(
request.num_prompt_tokens,
hash_block_size,
self.drop_eagle_checkpoint_block,
)
)
if (
retention_interval == 0
and num_tokens < request.num_prompt_tokens
and not is_prompt_checkpoint
and checkpoint_position != request.shared_prefix_boundary
):
# retention_interval == 0 keeps this transient checkpoint
@@ -2220,8 +2248,8 @@ class SinkFullAttentionManager(FullAttentionManager):
class HiSparseSourceManager(FullAttentionManager):
"""Host-tier manager with a private pool; publishes hashes once durable.
Host capacity is best effort: a page that cannot get a host block keeps a
null host entry, so its GPU copy is never written back and stays pinned.
Every page gets a host block: allocation fails when the host pool cannot
back it, so each GPU-resident page can be written back and later reclaimed.
"""
coordinator: "HiSparseCoordinator | None" = None
@@ -2244,7 +2272,7 @@ class HiSparseSourceManager(FullAttentionManager):
enable_caching=self.enable_caching and self.kv_cache_spec.prefix_cacheable,
hash_block_size=device_pool.hash_block_size,
enable_kv_cache_events=device_pool.enable_kv_cache_events,
metrics_collector=device_pool.metrics_collector,
metrics_collector=None,
medium=MEDIUM_CPU,
event_owner=device_pool,
)
@@ -2269,45 +2297,23 @@ class HiSparseSourceManager(FullAttentionManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
if (
total_computed_tokens > num_local_computed_tokens
or self._has_partial_local_hit(
new_computed_blocks, num_local_computed_tokens
)
):
# External loads need real destinations; future GPU-computed pages
# remain best effort. Use the same admission sentinel as Mamba.
required = super().get_num_blocks_to_allocate(
request_id,
total_computed_tokens,
new_computed_blocks,
total_computed_tokens,
num_local_computed_tokens,
total_computed_tokens,
)
if required > self.block_pool.get_num_free_blocks():
assert self.coordinator is not None
assert self.coordinator.gpu_pool is not None
return self.coordinator.gpu_pool.num_gpu_blocks + 1
return 0
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
req_blocks = self.req_to_blocks[request_id]
num_required = cdiv(num_tokens, self.block_size)
num_free = self.block_pool.get_num_free_blocks()
if request_id in self._partial_hit_reqs:
num_free -= 1
fit_blocks = min(num_required, len(req_blocks) + max(0, num_free))
new_blocks = super().allocate_new_blocks(
required = super().get_num_blocks_to_allocate(
request_id,
fit_blocks * self.block_size,
min(num_tokens_main_model, fit_blocks * self.block_size),
num_tokens,
new_computed_blocks,
total_computed_tokens,
num_local_computed_tokens,
num_tokens_main_model,
)
req_blocks.extend([self._null_block] * (num_required - len(req_blocks)))
return new_blocks
# Host blocks come from a private pool, so they never count against
# the GPU pool. Use the same admission sentinel as Mamba instead.
if required > self.block_pool.get_num_free_blocks():
assert self.coordinator is not None
assert self.coordinator.gpu_pool is not None
return self.coordinator.gpu_pool.num_gpu_blocks + 1
return 0
def allocate_external_computed_blocks(
self,
@@ -2369,12 +2375,6 @@ class _HiSparseAuxiliaryManager(SingleTypeKVCacheManager):
coordinator: "HiSparseCoordinator | None" = None
def __init__(self, kv_cache_spec: KVCacheSpec, **kwargs) -> None:
# Never prefix-cached, but the per-step ``cache_blocks`` hook is where
# residency work runs, so stay opted in regardless of prefix caching.
kwargs["enable_caching"] = True
super().__init__(kv_cache_spec, **kwargs)
def cache_blocks(
self,
request: Request,
@@ -2427,6 +2427,7 @@ class HiSparseHotManager(_HiSparseAuxiliaryManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
assert not new_computed_blocks
# A hot region is needed to read host-backed history: an external
@@ -2490,6 +2491,8 @@ class HiSparseHotManager(_HiSparseAuxiliaryManager):
class HiSparseResidentManager(_HiSparseAuxiliaryManager):
"""Track GPU-resident pages for otherwise host-backed KV."""
max_admission_blocks_per_request: int
def get_num_blocks_to_allocate(
self,
request_id: str,
@@ -2499,6 +2502,7 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
del num_tokens_main_model
assert not new_computed_blocks
@@ -2515,8 +2519,7 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
host_pages = cdiv(num_local_computed_tokens, self.block_size)
required = cdiv(num_tokens, self.block_size)
if apply_admission_cap:
assert self._max_admission_blocks_per_request is not None
required = min(required, self._max_admission_blocks_per_request)
required = min(required, self.max_admission_blocks_per_request)
return max(required - max(existing, host_pages), 0)
def allocate_external_computed_blocks(
@@ -2551,18 +2554,6 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
assert self.coordinator is not None
self.coordinator.commit_computed_blocks(request_id, num_host_pages)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
assert self.coordinator is not None
self.coordinator.plan_prefix_materialization(request.request_id, num_tokens)
self.coordinator.update_residency(request.request_id)
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
+6 -1
View File
@@ -1110,12 +1110,14 @@ class AsyncLLM(EngineClient):
if self.logger_manager is not None:
self.logger_manager.record_sleep_state(1, 0)
async def wake_up(self, tags: list[str] | None = None) -> None:
async def wake_up(self, tags: list[str] | None = None) -> bool:
fully_awake = await self.engine_core.wake_up_async(tags)
if self.logger_manager is not None and fully_awake:
self.logger_manager.record_sleep_state(0, 0)
return fully_awake
async def checkpoint_prepare(self) -> None:
await self.collective_rpc("checkpoint_prepare")
@@ -1125,6 +1127,9 @@ class AsyncLLM(EngineClient):
async def is_sleeping(self) -> bool:
return await self.engine_core.is_sleeping_async()
async def compute_weight_checksums(self) -> list[dict[str, str]]:
return await self.engine_core.compute_weight_checksums_async()
async def add_lora(self, lora_request: LoRARequest) -> bool:
"""Load a new LoRA adapter into the engine for future requests."""
return await self.engine_core.add_lora_async(lora_request)
+3
View File
@@ -1005,6 +1005,9 @@ class EngineCore:
def execute_dummy_batch(self):
self.model_executor.execute_dummy_batch()
def compute_weight_checksums(self) -> list[dict[str, str]]:
return self.collective_rpc("compute_weight_checksums")
def add_lora(self, lora_request: LoRARequest) -> bool:
return self.model_executor.add_lora(lora_request)
+30 -14
View File
@@ -1239,6 +1239,23 @@ class AsyncMPClient(MPClient):
async def call_utility_async(self, method: str, *args) -> Any:
return await self._call_utility_async(method, *args, engine=self.core_engine)
async def call_utility_all_async(self, method: str, *args) -> list[Any]:
# Like the Rust client's call_utility: one result per managed engine.
return await asyncio.gather(
*[
self._call_utility_async(method, *args, engine=engine)
for engine in self.core_engines
]
)
async def call_utility_consensus_async(self, method: str, *args) -> Any:
results = await self.call_utility_all_async(method, *args)
if any(result != results[0] for result in results):
raise RuntimeError(
f"Engines returned different {method} results: {results}"
)
return results[0]
async def _call_utility_async(
self, method: str, *args, engine: EngineIdentity
) -> Any:
@@ -1274,7 +1291,7 @@ class AsyncMPClient(MPClient):
await self.call_utility_async("resume_scheduler")
async def is_scheduler_paused_async(self) -> bool:
return await self.call_utility_async("is_scheduler_paused")
return await self.call_utility_consensus_async("is_scheduler_paused")
async def profile_async(
self, is_start: bool = True, profile_prefix: str | None = None
@@ -1287,8 +1304,10 @@ class AsyncMPClient(MPClient):
async def reset_prefix_cache_async(
self, reset_running_requests: bool = False, reset_connector: bool = False
) -> bool:
return await self.call_utility_async(
"reset_prefix_cache", reset_running_requests, reset_connector
return all(
await self.call_utility_all_async(
"reset_prefix_cache", reset_running_requests, reset_connector
)
)
async def reset_encoder_cache_async(self) -> None:
@@ -1301,10 +1320,10 @@ class AsyncMPClient(MPClient):
await self.call_utility_async("release_kv_cache_memory")
async def wake_up_async(self, tags: list[str] | None = None) -> bool:
return await self.call_utility_async("wake_up", tags)
return all(await self.call_utility_all_async("wake_up", tags))
async def is_sleeping_async(self) -> bool:
return await self.call_utility_async("is_sleeping")
return await self.call_utility_consensus_async("is_sleeping")
async def execute_dummy_batch_async(self) -> None:
await self.call_utility_async("execute_dummy_batch")
@@ -1313,7 +1332,7 @@ class AsyncMPClient(MPClient):
await self.call_utility_async("set_weight_version", weight_version)
async def get_weight_version_async(self) -> str:
return await self.call_utility_async("get_weight_version")
return await self.call_utility_consensus_async("get_weight_version")
async def add_lora_async(self, lora_request: LoRARequest) -> bool:
return await self.call_utility_async("add_lora", lora_request)
@@ -1343,6 +1362,10 @@ class AsyncMPClient(MPClient):
"collective_rpc", method, timeout, args, kwargs
)
async def compute_weight_checksums_async(self) -> list[dict[str, str]]:
per_engine = await self.call_utility_all_async("compute_weight_checksums")
return [worker for workers in per_engine for worker in workers]
async def handle_fault(
self, ft_request: FaultToleranceRequest
) -> FaultToleranceResult:
@@ -1645,14 +1668,7 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
async def call_utility_async(self, method: str, *args) -> Any:
# Only the result from the first engine is returned.
return (
await asyncio.gather(
*[
self._call_utility_async(method, *args, engine=engine)
for engine in self.core_engines
]
)
)[0]
return (await self.call_utility_all_async(method, *args))[0]
@staticmethod
async def process_engine_outputs(
+6 -7
View File
@@ -3,9 +3,7 @@
import sys
from abc import ABC, abstractmethod
import tokenizers
import tokenizers.decoders
from packaging import version
from tokenizers import Tokenizer
from transformers import TokenizersBackend
@@ -20,14 +18,15 @@ from vllm.v1.engine import EngineCoreRequest
logger = init_logger(__name__)
# Only tokenizers >= 0.22.0 supports DecodeStream with native prefill
# (ids parameter) used for FastIncrementalDetokenizer.
USE_FAST_DETOKENIZER = version.parse(tokenizers.__version__) >= version.parse("0.22.0")
# Error string from https://github.com/huggingface/tokenizers/blob/909fdde2a4ffedd9295206f705eb612be2a91b12/tokenizers/src/tokenizer/mod.rs#L1042
INVALID_PREFIX_ERR_MSG = "Invalid prefix encountered"
def uses_fast_detokenizer(tokenizer: TokenizerLike) -> bool:
"""Whether the engine detokenizes with `FastIncrementalDetokenizer`."""
return isinstance(tokenizer, TokenizersBackend)
class IncrementalDetokenizer:
def __init__(self):
self.token_ids: list[int] = []
@@ -58,7 +57,7 @@ class IncrementalDetokenizer:
# No tokenizer => skipping detokenization.
return IncrementalDetokenizer()
if USE_FAST_DETOKENIZER and isinstance(tokenizer, TokenizersBackend):
if uses_fast_detokenizer(tokenizer):
# Fast tokenizer => use tokenizers library DecodeStream.
return FastIncrementalDetokenizer(tokenizer, request)
+3 -32
View File
@@ -158,7 +158,6 @@ class InputProcessor:
else None
),
vocab_size=self.model_config.get_vocab_size(),
async_scheduling=self.vllm_config.scheduler_config.async_scheduling,
)
if self.model_config.return_sampling_mask:
@@ -557,9 +556,6 @@ class InputProcessor:
prompt_input: SingletonInput,
prompt_type: Literal["encoder", "decoder"],
) -> None:
model_config = self.model_config
tokenizer = self.tokenizer
prompt_ids = (
None
if prompt_input["type"] == "embeds"
@@ -596,34 +592,9 @@ class InputProcessor:
f"by setting --limit-mm-per-prompt at startup."
)
if prompt_ids and tokenizer is not None:
max_input_id = max(prompt_ids, default=0)
min_input_id = min(prompt_ids, default=0)
# NOTE: tokenizer.max_token_id is the tokenizer’s vocab size while
# self.model_config.get_vocab_size() is the model’s vocab size.
# For Qwen3 models, the language model has extra tokens that do
# not exist in the tokenizer, and vice versa for multimodal
# placeholder tokens in some multimodal models.
# See https://github.com/QwenLM/Qwen3/issues/29#issuecomment-1933720399 # noqa: E501
# and https://github.com/vllm-project/vllm/pull/22471#discussion_r2312251421 # noqa: E501
# Here we take the max of the two to determine if a token id is
# truly out-of-vocabulary.
model_vocab_size = model_config.get_vocab_size()
# A negative id is out of vocabulary just like an over-large one,
# but is not caught by the upper-bound check below. Reject it here
# so it is not used as an embedding index downstream. This
# validation path is shared by generate, embedding and pooling
# requests, so the check covers all three.
if min_input_id < 0:
raise VLLMValidationError(
f"Token id {min_input_id} is out of vocabulary"
)
if max_input_id > max(tokenizer.max_token_id, model_vocab_size - 1):
raise VLLMValidationError(
f"Token id {max_input_id} is out of vocabulary"
)
# Shared by generate, embedding and pooling requests.
if prompt_ids:
self.renderer.validate_token_ids(prompt_ids)
def _validate_model_inputs(
self,
+3 -1
View File
@@ -386,12 +386,14 @@ class LLMEngine:
if self.logger_manager is not None:
self.logger_manager.record_sleep_state(1, 0)
def wake_up(self, tags: list[str] | None = None):
def wake_up(self, tags: list[str] | None = None) -> bool:
fully_awake = self.engine_core.wake_up(tags)
if self.logger_manager is not None and fully_awake:
self.logger_manager.record_sleep_state(0, 0)
return fully_awake
def is_sleeping(self) -> bool:
return self.engine_core.is_sleeping()
+8 -2
View File
@@ -439,10 +439,16 @@ class RequestState:
logprobs = logprobs[-num_new_tokens:] if num_new_tokens else logprobs[:0]
sampling_mask = None
if finished and self.sampling_mask_chunks:
if (delta or finished) and self.sampling_mask_chunks:
sampling_mask = SamplingMask(
[chunk.token_ids.tolist() for chunk in self.sampling_mask_chunks]
[
position
for chunk in self.sampling_mask_chunks
for position in chunk.to_nested_list()
]
)
if delta:
self.sampling_mask_chunks.clear()
# Concatenate routed experts on finish
routed_experts = None
+106 -49
View File
@@ -28,9 +28,9 @@ from vllm.utils.network_utils import (
get_tcp_uri,
zmq_socket_ctx,
)
from vllm.utils.system_utils import get_mp_context
from vllm.utils.system_utils import get_mp_context, set_env_var
from vllm.v1.engine.coordinator import DPCoordinator
from vllm.v1.executor import Executor
from vllm.v1.executor import Executor, UniProcExecutor
from vllm.v1.executor.ray_utils import WORKER_SPECIFIC_ENV_VARS
from vllm.v1.utils import _SubprocessWrapper, get_engine_client_zmq_addr, shutdown
@@ -124,6 +124,31 @@ def _get_bundle_node_ip(bundle: dict[str, float]) -> str:
raise ValueError(f"Missing node affinity in placement bundle: {bundle}")
def _dp_nodes_master_first(
available_resources: dict[str, dict], dp_master_ip: str
) -> list[tuple[str, dict]]:
"""Live Ray nodes as ``(node_id, resources)`` with the DP master first.
The master is found through the ``node:<ip>`` resource Ray sets on every
node, so this works with the resource maps from ``ray._private.state``.
Do not replace it with ``ray.util.state.list_nodes()``: that API goes
through the dashboard HTTP server and only exists with ``ray[default]``
(see #23822).
"""
master_key = f"node:{dp_master_ip}"
nodes = sorted(
available_resources.items(), key=lambda item: master_key not in item[1]
)
assert len(nodes) > 0, "No nodes with resources found in Ray cluster."
assert master_key in nodes[0][1], (
f"The DP master node (ip: {dp_master_ip}) is missing or dead"
)
assert len(nodes) == 1 or master_key not in nodes[1][1], (
"There can only be one head node"
)
return nodes
def _node_ip_from_resources(node_resources: dict) -> str | None:
"""Return the node IP encoded in a Ray per-node resource dict, or None.
@@ -141,6 +166,42 @@ def _node_ip_from_resources(node_resources: dict) -> str | None:
return None
@contextlib.contextmanager
def _configure_uniproc_startup_threads(
executor_class: type[Executor], local_engine_count: int
) -> Iterator[None]:
if (
not issubclass(executor_class, UniProcExecutor)
or current_platform.is_cpu()
or "OMP_NUM_THREADS" in os.environ
):
yield
return
import torch
from vllm.utils.torch_utils import (
OMP_NUM_THREADS_SET_BY_VLLM,
set_default_torch_num_threads,
startup_omp_num_threads,
)
original_threads = torch.get_num_threads()
num_threads = min(original_threads, startup_omp_num_threads(local_engine_count))
torch_threads = (
set_default_torch_num_threads(num_threads)
if num_threads < original_threads
else contextlib.nullcontext()
)
# Fork inherits Torch's setting; spawn reads OMP_NUM_THREADS on import.
with (
set_env_var("OMP_NUM_THREADS", str(num_threads)),
set_env_var(OMP_NUM_THREADS_SET_BY_VLLM, "1"),
torch_threads,
):
yield
class CoreEngineProcManager:
"""Utility class to handle creation, readiness, and shutdown
of background processes used by the AsyncLLM and LLMEngine.
@@ -204,34 +265,36 @@ class CoreEngineProcManager:
# pickles process args at start() time, sequentially per rank.
user_assigned_gpu_ids = vllm_config.parallel_config.assigned_physical_gpu_ids
try:
for proc, local_dp_rank in zip(self.processes, local_dp_ranks):
# Populate the logical-to-physical GPU mapping in DP for
# platforms that cannot rely on
# torch.accelerator.set_device_index(), and for Ray.
needs_device_env_isolation = not (
current_platform.is_cuda_alike() or current_platform.is_xpu()
)
if is_dp and (
needs_device_env_isolation or vllm_config.parallel_config.use_ray
):
set_assigned_physical_gpu_ids_for_dp_rank(
vllm_config, local_dp_rank, user_assigned_gpu_ids
with _configure_uniproc_startup_threads(executor_class, local_engine_count):
for proc, local_dp_rank in zip(self.processes, local_dp_ranks):
# Populate the logical-to-physical GPU mapping in DP for
# platforms that cannot rely on
# torch.accelerator.set_device_index(), and for Ray.
needs_device_env_isolation = not (
current_platform.is_cuda_alike() or current_platform.is_xpu()
)
if is_dp and (
needs_device_env_isolation
or vllm_config.parallel_config.use_ray
):
set_assigned_physical_gpu_ids_for_dp_rank(
vllm_config, local_dp_rank, user_assigned_gpu_ids
)
with numa_utils.configure_subprocess(
# EngineCore itself does not have a TP/PP-local rank.
# When DP is enabled, set_assigned_physical_gpu_ids_for_dp_rank()
# populates the logical-to-physical mapping for this DP
# shard, so local_rank=0 means "the first local GPU in
# this shard". The actual TP/PP worker processes spawned
# by the executor are bound separately with their own
# local_rank values.
vllm_config,
local_rank=0,
dp_local_rank=local_dp_rank,
process_kind="EngineCore",
):
proc.start()
with numa_utils.configure_subprocess(
# EngineCore itself does not have a TP/PP-local rank.
# set_assigned_physical_gpu_ids_for_dp_rank() populates
# the logical-to-physical mapping for this DP
# shard, so local_rank=0 means "the first local GPU in
# this shard". The actual TP/PP worker processes spawned
# by the executor are bound separately with their own
# local_rank values.
vllm_config,
local_rank=0,
dp_local_rank=local_dp_rank,
process_kind="EngineCore",
):
proc.start()
finally:
# Kill other procs if not all are running.
if self.finished_procs():
@@ -561,14 +624,12 @@ class CoreEngineActorManager:
placement_groups: list[PlacementGroup] = []
local_dp_ranks: list[int] = []
dp_master_ip_key = f"node:{dp_master_ip}"
nodes = sorted(
available_resources.values(), key=lambda x: dp_master_ip_key not in x
)
assert len(nodes) > 0, "No nodes with resources found in Ray cluster."
assert dp_master_ip_key in nodes[0], (
f"The DP master node (ip: {dp_master_ip}) is missing or dead"
)
nodes = [
node_resources
for _, node_resources in _dp_nodes_master_first(
available_resources, dp_master_ip
)
]
# optionally restrict DP placement to a caller-provided node set.
requested_node_ips = {
@@ -767,7 +828,6 @@ class CoreEngineActorManager:
available_resources_per_node,
total_resources_per_node,
)
from ray.util.state import list_nodes
old_dp_size = old_vllm_config.parallel_config.data_parallel_size
num_pg_to_create = new_data_parallel_size - old_dp_size
@@ -778,30 +838,27 @@ class CoreEngineActorManager:
dp_master_ip = old_vllm_config.parallel_config.data_parallel_master_ip
world_size = old_vllm_config.parallel_config.world_size
nodes = list_nodes()
nodes = sorted(nodes, key=lambda node: node.node_ip != dp_master_ip)
assert nodes[0].node_ip == dp_master_ip, "The first node must be the head node"
assert len(nodes) == 1 or nodes[1].node_ip != dp_master_ip, (
"There can only be one head node"
)
# Both maps are keyed by node id and only contain live nodes.
available_resources = available_resources_per_node()
total_resources = total_resources_per_node()
nodes = _dp_nodes_master_first(available_resources, dp_master_ip)
placement_groups = []
local_dp_ranks = []
num_pg_created = 0
device_str = current_platform.ray_device_key
for node in nodes:
for node_id, node_resources in nodes:
if num_pg_created >= num_pg_to_create:
break
node_ip = node.node_ip
node_id = node.node_id
if device_str not in available_resources[node_id]:
node_ip = _node_ip_from_resources(node_resources)
assert node_ip is not None, (
f"No node IP key found in node resources: {node_resources}"
)
if device_str not in node_resources:
continue
available_gpus = int(available_resources[node_id][device_str])
available_gpus = int(node_resources[device_str])
# Get total GPUs on this node from the node's resources
# Ray stores node resources with node ID as key
+18 -9
View File
@@ -12,6 +12,7 @@ from vllm.config import VllmConfig
from vllm.v1.hisparse.layout import (
HISPARSE_HOT_SUFFIX,
HISPARSE_RESIDENT_SUFFIX,
get_hisparse_kv_cache_groups,
)
from vllm.v1.hisparse.runtime import (
HiSparseCacheHandle,
@@ -36,21 +37,20 @@ if TYPE_CHECKING:
from vllm.v1.worker.gpu.block_table import BlockTables
def resolve_hisparse_block_size(
def resolve_hisparse_specs(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
attn_layers: Mapping[str, "AttentionLayerBase"],
) -> None:
"""Resolve a common kernel block size in-place for HiSparse MLA specs."""
if vllm_config.attention_config.hisparse_config is None:
return
) -> dict[str, KVCacheSpec]:
"""Resolve a common kernel block size for HiSparse MLA specs, and add the
resident/hot specs HiSparse derives from them."""
mla_specs = {
name: spec
for name, spec in kv_cache_spec.items()
if isinstance(spec, MLAAttentionSpec)
}
if not mla_specs:
return
return kv_cache_spec
block_sizes = {spec.block_size for spec in mla_specs.values()}
if len(block_sizes) != 1:
raise ValueError("HiSparse requires one scheduler block size.")
@@ -62,10 +62,18 @@ def resolve_hisparse_block_size(
"HiSparse requires a GPU block size supported by every sparse "
f"attention and indexer backend: {error}"
) from error
kv_cache_spec.update(
(name, spec.copy_with_new_block_size(block_size))
kv_cache_spec = kv_cache_spec | {
name: spec.copy_with_new_block_size(block_size)
for name, spec in mla_specs.items()
)
}
groups = get_hisparse_kv_cache_groups(vllm_config, kv_cache_spec)
assert groups is not None
return kv_cache_spec | {
layer_name: group.kv_cache_spec
for group in groups
if isinstance(group.kv_cache_spec, (HiSparseResidentSpec, HiSparseHotSpec))
for layer_name in group.layer_names
}
def allocate_hisparse_kv_caches(
@@ -276,6 +284,7 @@ def bind_hisparse_kv_caches(
assert source_cache.untyped_storage().data_ptr() == (
host_pool.registered.untyped_storage().data_ptr()
)
cache_handle.draft_layer = forward_context[layer_name].is_draft_layer
cache_handle.runtime.shared_host_region = host_pool.shared_region
cache_handle.runtime.bind_source_cache(
source_cache,
+135 -32
View File
@@ -44,6 +44,8 @@ class _PendingPublication:
num_pages: int
retention_interval: int | None
replay_boundaries: Sequence[int]
detached_blocks: list[KVCacheBlock] | None = None
num_cached_blocks: int = 0
@dataclass
@@ -64,6 +66,8 @@ class _HiSparseRequestState:
copies_recorded_blocks: int = 0
pinned_clean: set[int] = field(default_factory=set)
unpinned_pages: set[int] = field(default_factory=set)
# Prefix pages whose GPU copies are adopted after the admitting allocation.
pages_to_adopt: int = 0
@dataclass
@@ -95,9 +99,12 @@ class HiSparseCoordinator:
kv_cache_config: KVCacheConfig,
managers: tuple[SingleTypeKVCacheManager, ...],
max_model_len: int,
*,
num_reprefillable_tokens: int,
) -> None:
self.managers = managers
self.max_model_len = max_model_len
self.num_reprefillable_tokens = num_reprefillable_tokens
groups = kv_cache_config.kv_cache_groups
resident_managers: list[HiSparseResidentManager] = []
@@ -193,7 +200,9 @@ class HiSparseCoordinator:
state = self._get_request_state(request_id)
state.valid_pages.update(range(num_host_pages))
state.ready_prefix_pages = max(num_host_pages, state.ready_prefix_pages)
self._adopt_copies(request_id, state, host_blocks[:num_host_pages])
# Adopting pins copies out of the free pool, so it must wait until the
# allocation admission counted on has run (see update_residency).
state.pages_to_adopt = max(state.pages_to_adopt, num_host_pages)
state.copies_recorded_blocks = max(state.copies_recorded_blocks, num_host_pages)
def take_host_block_copies(self) -> tuple[KVCacheBlockCopy, ...]:
@@ -258,6 +267,7 @@ class HiSparseCoordinator:
if manager.adopt_resident_page(request_id, host_idx, block):
manager.block_pool.touch([block])
state.pinned_clean.add(host_idx)
self.block_table_updates.add(request_id)
def _record_copies(self, request_id: str, num_computed_tokens: int) -> None:
"""Index the GPU copies of just-published host blocks for later hits."""
@@ -312,6 +322,19 @@ class HiSparseCoordinator:
manager.has_hot(request_id) for manager in self.hot_managers
)
def _fills_admission_window(self, request_id: str) -> bool:
"""Whether the request holds the resident pages admission reserved.
Admission caps a request's resident pages at the in-flight window,
assuming older pages move to host; keeping them pinned past it lets a
chunked prefill outgrow the pool it was admitted into.
"""
return any(
len(manager.req_to_blocks.get(request_id, ()))
>= manager.max_admission_blocks_per_request
for manager in self.resident_managers
)
def _resident_page_blocks(
self, request_id: str, page_idx: int
) -> list[KVCacheBlock] | None:
@@ -343,7 +366,8 @@ class HiSparseCoordinator:
return True
def _unpin_clean_pages(self, request_id: str, state: _HiSparseRequestState) -> None:
for page_idx in sorted(state.pinned_clean):
# Tail first, so a prefix loses its tail pages before its head.
for page_idx in sorted(state.pinned_clean, reverse=True):
self._unpin_page(request_id, state, page_idx)
def _page_became_clean(
@@ -383,15 +407,24 @@ class HiSparseCoordinator:
A request that can read from host releases every clean sealed page to
the pool. One that cannot keeps its pages pinned until the shared pool
runs low, then asks for a hot region. Pages remain pinned until that region
is allocated on a subsequent scheduling pass.
runs low, or until it holds the resident pages admission reserved for
it, then asks for a hot region. Pages remain pinned until that region is
allocated on a subsequent scheduling pass.
"""
if not self.resident_managers:
return
state = self._get_request_state(request_id)
if state.pages_to_adopt:
assert self.host_manager is not None
host_blocks = self.host_manager.req_to_blocks.get(request_id, ())
self._adopt_copies(request_id, state, host_blocks[: state.pages_to_adopt])
state.pages_to_adopt = 0
if not self._can_read_from_host(request_id):
assert self.gpu_pool is not None
if self.gpu_pool.get_num_free_blocks() >= self.transition_watermark:
if (
self.gpu_pool.get_num_free_blocks() >= self.transition_watermark
and not self._fills_admission_window(request_id)
):
return
for manager in self.hot_managers:
manager.require_hot(request_id)
@@ -402,6 +435,22 @@ class HiSparseCoordinator:
# Host publication and spills
# ------------------------------------------------------------------
def advance_scheduled(self, requests: Iterable[tuple[str, int]]) -> None:
"""Run the per-step residency work for each scheduled request.
``requests`` pairs a request id with the number of tokens computed
once the step completes. As in ``KVCacheCoordinator.cache_blocks``, the
last ``num_reprefillable_tokens`` are not final yet and are not written
back.
"""
if not self.resident_managers:
return
for request_id, num_tokens in requests:
self.plan_prefix_materialization(
request_id, max(0, num_tokens - self.num_reprefillable_tokens)
)
self.update_residency(request_id)
def plan_prefix_materialization(
self, request_id: str, num_computed_tokens: int
) -> None:
@@ -416,9 +465,8 @@ class HiSparseCoordinator:
)
state = self._get_request_state(request_id)
budget = max(self.max_spill_pages - len(self.spills_to_send), 0)
for page_idx in range(num_pages):
if page_idx < importing_pages:
continue
first_page = max(state.ready_prefix_pages, importing_pages)
for page_idx in range(first_page, num_pages):
if budget == 0:
break
if page_idx in state.pending_pages:
@@ -441,47 +489,47 @@ class HiSparseCoordinator:
*,
replay_boundaries: Sequence[int],
) -> None:
"""Publish host-source hashes only after their pages are durable."""
"""Publish host-source hashes of the pages that are already durable."""
manager = self.host_manager
if manager is None:
return
num_pages = num_computed_tokens // manager.block_size
request_id = request.request_id
state = self._get_request_state(request_id)
if state.ready_prefix_pages >= num_pages:
manager.publish_blocks(
request,
num_computed_tokens,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
self._record_copies(request_id, num_computed_tokens)
state.publication = None
return
state.publication = _PendingPublication(
self._get_request_state(request_id).publication = _PendingPublication(
request=request,
num_computed_tokens=num_computed_tokens,
num_pages=num_pages,
num_pages=num_computed_tokens // manager.block_size,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
self._publish_host_blocks_if_ready(request_id)
def _publish_host_blocks_if_ready(self, request_id: str) -> None:
"""Publish the durable prefix of the pending publication.
Host writes trail a long prefill by about a chunk, so waiting for the
whole computed prefix would publish nothing until the prefill ends, and
a prefill preempted before then would recompute from the start.
"""
state = self.request_states.get(request_id)
if state is None:
return
publication = state.publication
if publication is None or state.ready_prefix_pages < publication.num_pages:
if publication is None:
return
assert self.host_manager is not None
num_tokens = min(
publication.num_computed_tokens,
state.ready_prefix_pages * self.host_manager.block_size,
)
self.host_manager.publish_blocks(
publication.request,
publication.num_computed_tokens,
num_tokens,
retention_interval=publication.retention_interval,
replay_boundaries=publication.replay_boundaries,
)
self._record_copies(request_id, publication.num_computed_tokens)
state.publication = None
self._record_copies(request_id, num_tokens)
if state.ready_prefix_pages >= publication.num_pages:
state.publication = None
def record_pending_host_import(self, request_id: str, num_tokens: int) -> None:
"""Note a prefix an external load is populating in host pages."""
@@ -660,10 +708,13 @@ class HiSparseCoordinator:
return command
def has_pending_reclamation(self) -> bool:
"""Whether an in-flight spill will free GPU blocks on completion."""
"""Whether an in-flight spill will free GPU or host blocks on completion."""
return any(
pending.page[0] in self.request_states
and self._can_read_from_host(pending.page[0])
pending.host_block.ref_cnt == 1
or (
pending.page[0] in self.request_states
and self._can_read_from_host(pending.page[0])
)
for pending in self.pending_spills.values()
)
@@ -721,6 +772,10 @@ class HiSparseCoordinator:
if pending.restore:
self._record_copy(request_id, page_idx, pending.host_block)
completed_request_ids.add(request_id)
elif pending.request_state.publication is not None:
if not pending.restore:
pending.request_state.valid_pages.add(page_idx)
self._publish_detached_blocks(pending.request_state)
assert self.host_manager is not None
self.host_manager.block_pool.free_blocks([pending.host_block])
for request_id in completed_request_ids:
@@ -729,17 +784,62 @@ class HiSparseCoordinator:
state.ready_prefix_pages += 1
self._publish_host_blocks_if_ready(request_id)
def _publish_detached_blocks(self, state: _HiSparseRequestState) -> None:
publication = state.publication
if publication is None or state.pending_pages:
return
blocks = publication.detached_blocks
if blocks is None:
return
assert self.host_manager is not None
while state.ready_prefix_pages in state.valid_pages:
state.ready_prefix_pages += 1
# The host group uses full-attention retention. Only sealed pages with
# completed copies can outlive the request, including on cancellation.
self.host_manager.block_pool.cache_full_blocks(
request=publication.request,
blocks=blocks,
num_cached_blocks=publication.num_cached_blocks,
num_full_blocks=min(state.ready_prefix_pages, publication.num_pages),
block_size=self.host_manager.block_size,
kv_cache_group_id=self.host_manager.kv_cache_group_id,
)
self.host_manager.block_pool.free_blocks(reversed(blocks))
state.publication = None
def free(self, request_id: str) -> None:
"""Detach the request; its clean pages stay readable copies in the pool."""
self._pending_imports.pop(request_id, None)
state = self.request_states.pop(request_id, None)
if state is None:
return
publication = state.publication
if (
publication is not None
and publication.request.is_finished()
and state.pending_pages
):
assert self.host_manager is not None
publication.detached_blocks = self.host_manager.req_to_blocks[request_id][
: publication.num_pages
]
publication.num_cached_blocks = self.host_manager.num_cached_block.get(
request_id, 0
)
# Completed pages need leases too: another allocation may evict
# them before the remaining copies finish and the prefix publishes.
self.host_manager.block_pool.touch(publication.detached_blocks)
else:
# Preemption can cancel a scheduled forward after its spills were
# planned, so its copies do not prove that the KV was computed.
state.publication = None
for manager in self.resident_managers:
blocks = manager.req_to_blocks.get(request_id)
if not blocks:
continue
for page_idx, block in enumerate(blocks):
# Tail first, so a prefix loses its tail pages before its head.
for page_idx in reversed(range(len(blocks))):
block = blocks[page_idx]
if block.is_null:
continue
if page_idx in state.unpinned_pages:
@@ -771,7 +871,10 @@ def get_hisparse_coordinator(
assert isinstance(coordinator, HiSparseCoordinator)
return coordinator
coordinator = HiSparseCoordinator(
kv_cache_manager.kv_cache_config, managers, kv_cache_manager.max_model_len
kv_cache_manager.kv_cache_config,
managers,
kv_cache_manager.max_model_len,
num_reprefillable_tokens=kv_cache_manager.coordinator.num_reprefillable_tokens,
)
if coordinator.host_manager is None:
raise ValueError("No HiSparse cache group is configured.")
+41 -24
View File
@@ -47,6 +47,10 @@ class HiSparseLayout:
def get_hisparse_kv_cache_groups(
vllm_config: VllmConfig, kv_cache_spec: dict[str, KVCacheSpec]
) -> list[KVCacheGroupSpec] | None:
"""The groups HiSparse allocates: the host source group, then the GPU
groups sharing one device pool. Derived resident/hot specs in
`kv_cache_spec` (see `resolve_hisparse_specs`) are laid out again
from the attention specs they belong to."""
attention_config = getattr(vllm_config, "attention_config", None)
if attention_config is None or attention_config.hisparse_config is None:
return None
@@ -59,9 +63,11 @@ def get_hisparse_kv_cache_groups(
other_specs = {
name: spec
for name, spec in kv_cache_spec.items()
if not isinstance(spec, MLAAttentionSpec)
if not isinstance(
spec, (MLAAttentionSpec, HiSparseResidentSpec, HiSparseHotSpec)
)
}
if not mla_specs or not other_specs:
if not mla_specs:
return None
from vllm.v1.core.kv_cache_utils import get_kv_cache_groups
@@ -69,7 +75,10 @@ def get_hisparse_kv_cache_groups(
mla_group_spec = UniformTypeKVCacheSpecs.from_specs(mla_specs)
assert mla_group_spec is not None
mla_group = KVCacheGroupSpec(list(mla_specs), mla_group_spec)
return [mla_group, *get_kv_cache_groups(vllm_config, other_specs)]
regular_groups = (
get_kv_cache_groups(vllm_config, other_specs) if other_specs else []
)
return _lay_out_hisparse_groups(vllm_config, [mla_group, *regular_groups])
def get_hisparse_host_pool_bytes(vllm_config: VllmConfig) -> int:
@@ -112,24 +121,9 @@ def _partition_hisparse_specs(
return source_specs, indexer_specs
def get_hisparse_gpu_memory_usage(
vllm_config: VllmConfig,
kv_cache_groups: list[KVCacheGroupSpec],
) -> int:
_, indexer_specs = _partition_hisparse_specs(kv_cache_groups)
return sum(
spec.max_memory_usage_bytes(vllm_config) for spec in indexer_specs.values()
) + sum(
group.kv_cache_spec.max_memory_usage_bytes(vllm_config)
for group in kv_cache_groups[1:]
)
def create_hisparse_layout(
vllm_config: VllmConfig,
groups: list[KVCacheGroupSpec],
host_budget: int,
) -> HiSparseLayout:
def _lay_out_hisparse_groups(
vllm_config: VllmConfig, groups: list[KVCacheGroupSpec]
) -> list[KVCacheGroupSpec]:
source_specs, indexer_specs = _partition_hisparse_specs(groups)
block_sizes = {
spec.block_size for spec in (*source_specs.values(), *indexer_specs.values())
@@ -225,20 +219,43 @@ def create_hisparse_layout(
enable_kv_transfer=True,
)
regular_groups = groups[1:]
gpu_groups = [indexer_group, *resident_groups, *hot_groups, *regular_groups]
return [
source_group,
indexer_group,
*resident_groups,
*hot_groups,
*regular_groups,
]
def create_hisparse_layout(
vllm_config: VllmConfig,
groups: list[KVCacheGroupSpec],
host_budget: int,
) -> HiSparseLayout:
"""Size the host pool for groups laid out by `get_hisparse_kv_cache_groups`."""
(source_group,) = [group for group in groups if group.host_resident]
shared_host_pool = use_shared_hisparse_host_pool(vllm_config)
host_block_stride = get_hisparse_host_block_stride(
sum(spec.page_size_bytes for spec in source_specs.values()),
source_group.kv_cache_spec.page_size_bytes,
use_shared_host_pool=shared_host_pool,
)
host_num_blocks = host_budget // host_block_stride
if host_num_blocks <= 0:
raise ValueError("HiSparse has no allocatable host blocks.")
# Every computed page needs a host block, so one request at max_model_len
# must fit alongside the pool's null block and a copy-on-write tail.
gpu_block_size = source_group.kv_cache_spec.block_size
min_host_blocks = cdiv(vllm_config.model_config.max_model_len, gpu_block_size) + 2
if host_num_blocks < min_host_blocks:
raise ValueError(
f"HiSparse host pool has {host_num_blocks} blocks but max_model_len "
f"needs {min_host_blocks}; increase host_pool_gib."
)
return HiSparseLayout(
source_group=source_group,
device_groups=gpu_groups,
device_groups=[group for group in groups if not group.host_resident],
host_num_blocks=host_num_blocks,
host_block_stride=host_block_stride,
shared_host_pool=shared_host_pool,
+57 -2
View File
@@ -19,7 +19,8 @@ from vllm.distributed import get_tp_group
from vllm.forward_context import get_forward_context, in_piecewise_cudagraph
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.mem_utils import get_max_shared_memory_bytes
from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backend import max_decode_query_len
from vllm.v1.kv_offload.cpu.shared_offload_region import SharedOffloadRegion
@@ -96,6 +97,9 @@ class PagedCacheView:
class ResolvedHiSparseConfig:
top_k: int
device_buffer_size: int
# Most host rows one request's decode rows can select in a step: every
# verification row's top-k.
max_union_rows: int
eager_host_mirror: bool = True
@classmethod
@@ -151,10 +155,38 @@ class ResolvedHiSparseConfig:
return cls(
top_k=model_top_k,
device_buffer_size=device_buffer_size,
max_union_rows=min_device_buffer_size,
eager_host_mirror=config.eager_host_mirror,
)
def _check_residency_shared_memory(
device: torch.device, config: ResolvedHiSparseConfig
) -> None:
"""Reject a config whose residency resolver exceeds per-block shared memory."""
# Mirrors hisparse_resolve_residency's layout: union hash keys and values
# (plus an empty slot), per-chunk offsets, five counters, done bits, and
# the int16 compacted LRU.
hot_size = config.device_buffer_size
num_chunks = cdiv(hot_size, 32)
required = 4 * (2 * (config.max_union_rows + 1) + 3 * num_chunks + 7) + 2 * hot_size
device_index = (
device.index
if device.index is not None
else torch.accelerator.current_device_index()
)
available = get_max_shared_memory_bytes(device_index)
if required > available:
raise ValueError(
"HiSparse residency resolution needs "
f"{required} B of shared memory per block for "
f"device_buffer_size={config.device_buffer_size} and "
f"{config.max_union_rows} rows per request "
"(decode query length x index_topk), but the device allows "
f"{available} B. Lower device_buffer_size or num_speculative_tokens."
)
def check_hisparse_host_memory(pool_bytes: int) -> None:
"""Reject a physical host-pool allocation that cannot fit in RAM."""
mem = psutil.virtual_memory()
@@ -630,6 +662,10 @@ class HiSparseIndexGroup:
self.lru_init = torch.arange(region_stride, dtype=torch.int16, device=device)
self.lru_slots = self.lru_init.repeat(max_num_reqs, 1).contiguous()
self.shared_topk = _create_shared_topk_state(device, max_swap_rows, top_k)
# Request ids the resolver reads, built on the copy stream: a
# compute-stream write would race with its logical_topk_ready wait.
self.row_indices = torch.arange(max_swap_rows, dtype=torch.int32, device=device)
self.request_ids = torch.empty_like(self.row_indices)
self.copy_stream = (
copy_stream if copy_stream is not None else _create_copy_stream(device)
)
@@ -677,6 +713,9 @@ class HiSparseRuntime:
# Logical slots per request. Physical rows come from its ephemeral HMA
# block table and need not be contiguous in the shared slab.
self.region_stride = config.device_buffer_size
self.max_union_rows = config.max_union_rows
if self.device.type == "cuda":
_check_residency_shared_memory(self.device, config)
row_bytes = row_width * kv_dtype.itemsize
if row_bytes % 16 != 0:
@@ -919,6 +958,7 @@ class HiSparseRuntime:
group.lru_slots,
request_state_indices,
self.region_stride,
self.max_union_rows,
None,
group.swap_stats,
physical_topk_indices,
@@ -961,6 +1001,7 @@ class HiSparseRuntime:
shared_rows: slice,
attention_indices_out: torch.Tensor | None,
valid_counts_out: torch.Tensor | None,
num_valid_rows: torch.Tensor,
) -> None:
group = self.index_group
compute_stream = current_stream()
@@ -969,9 +1010,17 @@ class HiSparseRuntime:
else:
group.copy_stream.wait_stream(compute_stream)
with group.copy_stream:
# CUDA-graph padding rows past the batch's tokens map to request 0;
# mark them -1 so residency resolution skips them.
num_tokens = logical_topk_indices.shape[0]
request_ids = group.request_ids[:num_tokens]
request_ids.copy_(req_id_per_token)
request_ids.masked_fill_(
group.row_indices[:num_tokens] >= num_valid_rows, -1
)
self._resolve_residency(
resident=resident,
req_id_per_token=req_id_per_token,
req_id_per_token=request_ids,
block_table=block_table,
topk_indices=logical_topk_indices,
block_size=block_size,
@@ -1015,6 +1064,7 @@ class HiSparseRuntime:
block_table: torch.Tensor,
logical_topk_indices: torch.Tensor,
block_size: int,
num_valid_rows: torch.Tensor,
return_valid_counts: bool = False,
attention_indices_out: torch.Tensor | None = None,
valid_counts_out: torch.Tensor | None = None,
@@ -1038,6 +1088,7 @@ class HiSparseRuntime:
shared_rows=shared_rows,
attention_indices_out=attention_indices_out,
valid_counts_out=valid_counts_out,
num_valid_rows=num_valid_rows,
)
if not self._swap_staged:
@@ -1074,6 +1125,8 @@ class HiSparseCacheHandle:
self.mirror_staging_cache: torch.Tensor | None = None
self.mirror_staging_slots: torch.Tensor | None = None
self.submit_layer_mirror: Callable[[], None] | None = None
# Speculator layers write their rows after the target forward.
self.draft_layer = False
self.index_group_caches: list[HiSparseCacheHandle] = [self]
def prepare_group_for_batch(self, attn_metadata: Any | None) -> None:
@@ -1167,6 +1220,7 @@ class HiSparseCacheHandle:
logical_topk_indices: torch.Tensor,
*,
block_size: int,
num_valid_rows: torch.Tensor,
return_valid_counts: bool = False,
attention_indices_out: torch.Tensor | None = None,
valid_counts_out: torch.Tensor | None = None,
@@ -1180,6 +1234,7 @@ class HiSparseCacheHandle:
return_valid_counts=return_valid_counts,
attention_indices_out=attention_indices_out,
valid_counts_out=valid_counts_out,
num_valid_rows=num_valid_rows,
)
+17 -8
View File
@@ -472,9 +472,11 @@ class HiSparseResidentSpec(KVCacheSpec):
return cdiv(num_tokens, self.block_size)
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
return cdiv(vllm_config.model_config.max_model_len, self.block_size) * (
self.page_size
max_blocks = self.max_admission_blocks_per_request(
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
max_model_len=vllm_config.model_config.max_model_len,
)
return max_blocks * self.page_size
@property
def has_layer_views(self) -> bool:
@@ -484,6 +486,9 @@ class HiSparseResidentSpec(KVCacheSpec):
@dataclass(frozen=True, kw_only=True)
class AttentionSpec(KVCacheSpec):
dcp_sharded: bool = True
max_tp_shards: int | None = None
"""Distinct shards this cache splits into across TP; TP ranks beyond this
hold replicas. None: unknown, treated as not replicated."""
num_kv_heads: int
head_size: int
dtype: torch.dtype
@@ -618,6 +623,7 @@ class FullAttentionSpec(AttentionSpec):
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
max_tp_shards=specs[0].max_tp_shards,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -705,6 +711,7 @@ class MLAAttentionSpec(FullAttentionSpec):
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
max_tp_shards=specs[0].max_tp_shards,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -768,6 +775,7 @@ class RSWASpec(FullAttentionSpec):
dtype=base.dtype,
kv_quant_mode=base.kv_quant_mode,
dcp_sharded=base.dcp_sharded,
max_tp_shards=base.max_tp_shards,
page_size_padded=base.page_size_padded,
num_head_slots=base.num_head_slots,
state_content_bytes=base.state_content_bytes,
@@ -960,6 +968,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
bounded_replay_set = set(spec.bounded_replay for spec in specs)
block_stride_alignment_set = {spec.block_stride_alignment for spec in specs}
assert len({spec.dcp_sharded for spec in specs}) == 1
assert len({spec.max_tp_shards for spec in specs}) == 1
assert (
len(cache_dtype_str_set) == 1
and len(tokens_per_state_set) == 1
@@ -980,6 +989,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
head_size=specs[0].head_size,
dtype=specs[0].dtype,
dcp_sharded=specs[0].dcp_sharded,
max_tp_shards=specs[0].max_tp_shards,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -1071,12 +1081,7 @@ class MambaSpec(KVCacheSpec):
return None
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
if vllm_config.cache_config.mamba_cache_mode == "all":
max_model_len = vllm_config.model_config.max_model_len
return (
cdiv(max_model_len, self.block_size) + self.num_speculative_blocks
) * self.page_size_bytes
elif vllm_config.cache_config.mamba_cache_mode == "align":
if vllm_config.cache_config.mamba_cache_mode == "align":
return self.page_size_bytes * (
2 + self.num_speculative_blocks + self.num_prefill_checkpoint_blocks
)
@@ -1197,6 +1202,7 @@ class SinkFullAttentionSpec(FullAttentionSpec):
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
max_tp_shards=specs[0].max_tp_shards,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -1483,6 +1489,9 @@ class KVCacheConfig:
hisparse_shared_host_pool: bool = False
"""Whether local TP ranks share one physical HiSparse host pool."""
kv_tp_replicas: int = 1
"""Consecutive TP ranks holding identical KV for every layer (1: none)."""
@cached_property
def transfer_group_ids(self) -> tuple[int, ...]:
"""IDs of cache groups that participate in external KV transfer."""
+12 -3
View File
@@ -9,6 +9,7 @@ subsystems, such as the KV connector and offloading metrics, keep their own
boundaries.
"""
from collections.abc import Mapping
from typing import Literal, get_args
BucketFamilyKey = Literal[
@@ -205,23 +206,31 @@ def build_1_2_5_buckets(max_value: int) -> list[float]:
def histogram_buckets(
family: BucketFamilyKey,
max_model_len: int | None = None,
overrides: Mapping[str, list[float]] | None = None,
) -> list[float]:
"""Return the default bucket boundaries for a histogram family.
"""Return the bucket boundaries for a histogram family.
Args:
family: Canonical bucket family key.
max_model_len: Cap for the token-count series of the
`request_tokens` family; required for that family and ignored
otherwise.
overrides: Mapping from family key to replacement bucket bounds.
A present key replaces the family's defaults verbatim. Values
must already be validated; the single validation point is
`ObservabilityConfig.custom_histogram_buckets`.
Returns:
A fresh list of bucket upper bounds; callers may mutate it freely.
Raises:
ValueError: If `family` is `request_tokens` and `max_model_len`
is None.
ValueError: If `family` is `request_tokens`, no override is given,
and `max_model_len` is None.
"""
if overrides is not None and (custom := overrides.get(family)) is not None:
return list(custom)
if family == "request_tokens":
if max_model_len is None:
raise ValueError(
+63 -8
View File
@@ -26,6 +26,7 @@ from vllm.v1.metrics.buckets import histogram_buckets
from vllm.v1.metrics.perf import PerfMetricsLogging, PerfMetricsProm
from vllm.v1.metrics.prometheus import unregister_vllm_metrics
from vllm.v1.metrics.stats import (
KV_FETCH_STAGES,
CachingMetrics,
IterationStats,
MultiModalCacheStats,
@@ -292,6 +293,13 @@ class LoggingStatLogger(StatLoggerBase):
log_parts.append("Deferred: %d reqs")
log_args.append(self.last_scheduler_stats.num_skipped_waiting_reqs)
kv_fetch = self.last_scheduler_stats.num_kv_fetch_reqs_by_stage
if any(kv_fetch.values()):
log_parts.append(
"KV fetch: %d waiting to start, %d in progress, %d completed waiting"
)
log_args.extend(kv_fetch.get(stage, 0) for stage in KV_FETCH_STAGES)
if self.num_preemptions > 0:
log_parts.append("Preemptions: %d")
log_args.append(self.num_preemptions)
@@ -393,6 +401,10 @@ class AggregatedLoggingStatLogger(LoggingStatLogger, AggregateStatLoggerBase):
self.last_scheduler_stats.num_skipped_waiting_reqs += (
last_scheduler_stats.num_skipped_waiting_reqs
)
engine_kv_fetch = last_scheduler_stats.num_kv_fetch_reqs_by_stage
total_kv_fetch = self.last_scheduler_stats.num_kv_fetch_reqs_by_stage
for stage, num_reqs in engine_kv_fetch.items():
total_kv_fetch[stage] = total_kv_fetch.get(stage, 0) + num_reqs
self.last_scheduler_stats.kv_cache_usage += (
last_scheduler_stats.kv_cache_usage
)
@@ -547,6 +559,30 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
gauge_waiting_by_reason, per_engine_labelvalues_with_reason
)
self.gauge_kv_fetch_by_stage: dict[str, dict[int, Gauge]] = {}
kv_transfer_config = vllm_config.kv_transfer_config
if kv_transfer_config is not None and kv_transfer_config.is_kv_consumer:
gauge_kv_fetch_by_stage = self._gauge_cls(
name="vllm:num_requests_kv_fetch_by_stage",
documentation=(
"Number of waiting requests by async KV load stage. "
"Stage labels: 'waiting_to_start' = needs an async KV load "
"that has not started; 'in_progress' = load started and not "
"yet reported finished; 'completed_waiting' = load finished, "
"request not running yet."
),
multiprocess_mode="mostrecent",
labelnames=labelnames + ["stage"],
)
for stage in KV_FETCH_STAGES:
per_engine_labelvalues_with_stage = {
idx: labelvalues + [stage]
for idx, labelvalues in per_engine_labelvalues.items()
}
self.gauge_kv_fetch_by_stage[stage] = create_metric_per_engine(
gauge_kv_fetch_by_stage, per_engine_labelvalues_with_stage
)
gauge_engine_sleep_state = self._gauge_cls(
name="vllm:engine_sleep_state",
documentation=(
@@ -739,15 +775,28 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
for idx in engine_indexes
}
custom_buckets = vllm_config.observability_config.custom_histogram_buckets
request_tokens_buckets = histogram_buckets(
"request_tokens", max_model_len=max_model_len
"request_tokens", max_model_len=max_model_len, overrides=custom_buckets
)
iteration_tokens_buckets = histogram_buckets(
"iteration_tokens", overrides=custom_buckets
)
request_params_n_buckets = histogram_buckets(
"request_params_n", overrides=custom_buckets
)
time_to_first_token_buckets = histogram_buckets(
"time_to_first_token", overrides=custom_buckets
)
inter_token_latency_buckets = histogram_buckets(
"inter_token_latency", overrides=custom_buckets
)
request_latency_buckets = histogram_buckets(
"request_latency", overrides=custom_buckets
)
request_num_preemptions_buckets = histogram_buckets(
"request_num_preemptions", overrides=custom_buckets
)
iteration_tokens_buckets = histogram_buckets("iteration_tokens")
request_params_n_buckets = histogram_buckets("request_params_n")
time_to_first_token_buckets = histogram_buckets("time_to_first_token")
inter_token_latency_buckets = histogram_buckets("inter_token_latency")
request_latency_buckets = histogram_buckets("request_latency")
request_num_preemptions_buckets = histogram_buckets("request_num_preemptions")
#
# Histograms of counts
@@ -925,7 +974,9 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
# KV Cache residency metrics
#
if self.kv_cache_metrics_enabled:
kv_cache_residency_buckets = histogram_buckets("kv_cache_residency")
kv_cache_residency_buckets = histogram_buckets(
"kv_cache_residency", overrides=custom_buckets
)
histogram_kv_block_lifetime = self._histogram_cls(
name="vllm:kv_block_lifetime_seconds",
@@ -1047,6 +1098,10 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
self.gauge_waiting_by_reason[WAITING_REASON_DEFERRED][engine_idx].set(
scheduler_stats.num_skipped_waiting_reqs
)
for stage, gauges in self.gauge_kv_fetch_by_stage.items():
gauges[engine_idx].set(
scheduler_stats.num_kv_fetch_reqs_by_stage.get(stage, 0)
)
self.gauge_kv_cache_usage[engine_idx].set(scheduler_stats.kv_cache_usage)
self.counter_prefix_cache_queries[engine_idx].inc(
+12
View File
@@ -182,6 +182,16 @@ class SchedulerIterationDetails:
is_dummy: bool = False
KV_FETCH_WAITING_TO_START = "waiting_to_start"
KV_FETCH_IN_PROGRESS = "in_progress"
KV_FETCH_COMPLETED_WAITING = "completed_waiting"
KV_FETCH_STAGES = (
KV_FETCH_WAITING_TO_START,
KV_FETCH_IN_PROGRESS,
KV_FETCH_COMPLETED_WAITING,
)
@dataclass
class SchedulerStats:
"""Stats associated with the scheduler."""
@@ -192,6 +202,8 @@ class SchedulerStats:
# waiting requests deferred by transient constraints or a blocked status
num_skipped_waiting_reqs: int = 0
num_kv_fetch_reqs_by_stage: dict[str, int] = field(default_factory=dict)
# These are used for internal DP load-balancing.
step_counter: int = 0
current_wave: int = 0
+10 -4
View File
@@ -57,19 +57,25 @@ class LogprobsLists(NamedTuple):
class SamplingMaskLists(NamedTuple):
"""CSR sampling masks; a step slice holds one position (``offsets=None``)."""
"""CSR sampling masks; a request slice may contain multiple positions."""
# [num_kept_tokens]
token_ids: np.ndarray
# [num_positions + 1], or None for a single position
offsets: np.ndarray | None = None
# Unused with one position per request; kept for the wire layout.
# [num_requests + 1] for multi-position request batches.
cu_num_generated_tokens: list[int] | None = None
def slice_request(self, req_idx: int, num_positions: int) -> "SamplingMaskLists":
assert num_positions == 1 and self.offsets is not None
assert self.offsets is not None
cu = self.cu_num_generated_tokens
start = req_idx if cu is None else cu[req_idx]
end = start + num_positions
lo, hi = self.offsets[start], self.offsets[end]
if num_positions == 1:
return SamplingMaskLists(self.token_ids[lo:hi])
return SamplingMaskLists(
self.token_ids[self.offsets[req_idx] : self.offsets[req_idx + 1]]
self.token_ids[lo:hi], self.offsets[start : end + 1] - lo
)
def to_nested_list(self) -> list[list[int]]:
+7
View File
@@ -0,0 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused Triton kernels for late-interaction (MaxSim) scoring."""
from .flash_maxsim_rerank import flash_maxsim_rerank_direct
__all__ = ["flash_maxsim_rerank_direct"]
+85
View File
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared utilities for flash-maxsim kernels: padding, autotune configs,
and pruning."""
from vllm.triton_utils import triton
def _next_pow2(x: int) -> int:
return 1 << (x - 1).bit_length()
def _get_configs() -> list:
"""Autotune grid over (BLOCK_Q, BLOCK_D); `_prune_configs` filters by
SMEM budget and Lq at runtime, so one list is safe across GPUs."""
return [
triton.Config({"BLOCK_Q": 16, "BLOCK_D": 16}, num_warps=2, num_stages=2),
triton.Config({"BLOCK_Q": 16, "BLOCK_D": 32}, num_warps=2, num_stages=2),
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 16}, num_warps=2, num_stages=2),
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 32}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 128}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_Q": 64, "BLOCK_D": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_Q": 64, "BLOCK_D": 128}, num_warps=8, num_stages=1),
triton.Config({"BLOCK_Q": 128, "BLOCK_D": 64}, num_warps=8, num_stages=1),
triton.Config({"BLOCK_Q": 128, "BLOCK_D": 128}, num_warps=8, num_stages=1),
]
def _smem_budget() -> int:
"""Per-block opt-in shared-memory budget of the active device (bytes):
Triton driver query, else a conservative capability table."""
try:
driver = triton.runtime.driver.active
props = driver.utils.get_device_properties(driver.get_current_device())
return int(props["max_shared_mem"])
except Exception:
try:
from vllm.platforms import current_platform
cap = current_platform.get_device_capability()
if cap is not None:
if cap.major >= 9:
return 232_448 # Hopper+: 227 KB opt-in
if cap.major == 8:
return 101_376 # worst sm_8x (86/89); A100 has more
except Exception:
pass
return 98_304 # conservative pre-Ampere default
def _prune_configs(configs, named_args, **kwargs):
"""Reject configs that exceed the GPU's shared-memory budget.
BLOCK_Q and BLOCK_D load fp16 tiles of size [BLOCK_*, d_pad] — the
kernels index with ``tl.arange(0, d_pad)``, so the estimate must use
the padded dimension, not the real one (d=513 pads to 1024 and
nearly doubles the tile) — and the [BLOCK_Q, BLOCK_D] score tile is
fp32. Total:
(BLOCK_Q*d_pad + BLOCK_D*d_pad)*2 + BLOCK_Q*BLOCK_D*4 bytes.
"""
Lq = named_args.get("Lq", 32)
d_pad = named_args.get("d_pad")
if d_pad is None:
d_pad = _next_pow2(max(named_args.get("d", 128), 16))
smem_limit = _smem_budget()
def _est(cfg):
bq = cfg.kwargs["BLOCK_Q"]
bd = cfg.kwargs["BLOCK_D"]
return (bq * d_pad + bd * d_pad) * 2 + bq * bd * 4
pruned = []
for cfg in configs:
if cfg.kwargs["BLOCK_Q"] > Lq * 2:
continue
if _est(cfg) > smem_limit:
continue
pruned.append(cfg)
if pruned:
return pruned
# Nothing fits the estimate (large d_pad on a small-SMEM device).
# Return the single smallest-footprint config — a deterministic
# least-bad launch attempt — never arbitrary rejected configs.
return [min(configs, key=_est)]
@@ -0,0 +1,204 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Flash-MaxSim rerank: one query vs variable-length docs in a packed tensor.
The kernel reads doc embeddings directly from a packed [total_tokens, d]
tensor using per-doc (offset, length) pairs — no padding, no per-doc
tensors, no materialised [B, Lq, Ld] similarity tensor.
Entry point:
flash_maxsim_rerank_direct(Q, batch_tensor, doc_offsets, doc_lengths, max_ld)
doc_offsets[i] = start token index of doc i in batch_tensor.
doc_lengths[i] = number of tokens in doc i.
Docs can be scattered (non-contiguous) in the batch tensor.
"""
import torch
from vllm.triton_utils import tl, triton
from ._common import _get_configs, _next_pow2, _prune_configs
def _round_to_bucket(x):
"""Round up to nearest bucket: 32, 64, 128, 256, 512, 1024, 2048, 4096."""
for b in [32, 64, 128, 256, 512, 1024, 2048, 4096]:
if x <= b:
return b
return _next_pow2(x)
# Kernel: shared Q, scattered D via (offset, length) per doc
@triton.autotune(
configs=_get_configs(),
key=["Lq_bucket", "max_Ld_bucket", "d_pad"],
prune_configs_by={"early_config_prune": _prune_configs},
)
@triton.jit
def _maxsim_rerank_kernel(
Q_ptr,
D_ptr,
doc_offsets_ptr,
doc_lengths_ptr,
scores_ptr,
B,
Lq,
Lq_bucket: tl.constexpr,
max_Ld_bucket: tl.constexpr,
d: tl.constexpr,
d_pad: tl.constexpr,
stride_q_t,
stride_q_d,
stride_d_t,
stride_d_d,
BLOCK_Q: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""One program per doc. Q shared (read from same location). D scattered."""
pid = tl.program_id(0)
if pid >= B:
return
# Each doc has its own offset and length in the batch tensor.
# int64: (d_start + d_off) * stride overflows int32 past ~16.7M batch
# tokens (same widen-on-load as the pairs kernel below; the host-side
# offsets tensor stays int32, which indexes any realistic batch).
d_start = tl.load(doc_offsets_ptr + pid).to(tl.int64)
d_len = tl.load(doc_lengths_ptr + pid).to(tl.int32)
k_off = tl.arange(0, d_pad)
k_mask = k_off < d
score_acc = tl.zeros([], dtype=tl.float32)
# Q is shared — always read from start of Q_ptr
for q_blk in tl.static_range(0, Lq_bucket, BLOCK_Q):
q_off = q_blk + tl.arange(0, BLOCK_Q)
q_valid = q_off < Lq
Q_block = tl.load(
Q_ptr + q_off[:, None] * stride_q_t + k_off[None, :] * stride_q_d,
mask=q_valid[:, None] & k_mask[None, :],
other=0.0,
).to(tl.float16)
m = tl.full([BLOCK_Q], float("-inf"), dtype=tl.float32)
for d_blk in range(0, max_Ld_bucket, BLOCK_D):
d_off = d_blk + tl.arange(0, BLOCK_D)
d_valid = d_off < d_len
D_block = tl.load(
D_ptr
+ (d_start + d_off[:, None]) * stride_d_t
+ k_off[None, :] * stride_d_d,
mask=d_valid[:, None] & k_mask[None, :],
other=0.0,
).to(tl.float16)
S = tl.dot(Q_block, tl.trans(D_block))
S = tl.where(d_valid[None, :], S, float("-inf"))
m = tl.maximum(m, tl.max(S, axis=1))
m = tl.where(q_valid, m, 0.0)
score_acc += tl.sum(m)
tl.store(scores_ptr + pid, score_acc)
# Internal helper
def _run_rerank_kernel(Q, D_tensor, doc_offsets, doc_lengths, max_seqlen_d):
"""Common kernel launch for both rerank and rerank_direct."""
assert Q.is_cuda, f"Q must be on CUDA, got {Q.device}"
assert D_tensor.is_cuda, f"D must be on CUDA, got {D_tensor.device}"
Lq, d = Q.shape
B = doc_offsets.shape[0]
d_pad = _next_pow2(max(d, 16))
Q = Q.contiguous().half()
# D_tensor is NOT copied — kernel reads from it directly
if not D_tensor.is_contiguous():
D_tensor = D_tensor.contiguous()
if D_tensor.dtype != torch.float16:
D_tensor = D_tensor.half()
doc_offsets = doc_offsets.to(torch.int32).contiguous()
doc_lengths = doc_lengths.to(torch.int32).contiguous()
scores = torch.empty(B, device=Q.device, dtype=torch.float32)
if B == 0:
return scores
# Pad Q dimension if needed (Q is small, safe to copy).
# D is NOT padded — the kernel uses k_mask to handle d < d_pad.
# This preserves zero-copy: D_tensor is read in-place.
if d < d_pad:
Q_pad = torch.zeros(Lq, d_pad, device=Q.device, dtype=Q.dtype)
Q_pad[:, :d] = Q
else:
Q_pad = Q
D_pad = D_tensor
Lq_bucket = _round_to_bucket(Lq)
max_ld_bucket = _round_to_bucket(max_seqlen_d)
_maxsim_rerank_kernel[(B,)](
Q_pad,
D_pad,
doc_offsets,
doc_lengths,
scores,
B,
Lq,
Lq_bucket,
max_ld_bucket,
d,
d_pad,
Q_pad.stride(0),
Q_pad.stride(1),
D_pad.stride(0),
D_pad.stride(1),
)
return scores
# Public API
def flash_maxsim_rerank_direct(
Q: torch.Tensor,
batch_tensor: torch.Tensor,
doc_offsets: torch.Tensor,
doc_lengths: torch.Tensor,
max_seqlen_d: int,
) -> torch.Tensor:
"""TRUE zero-copy: score query against docs scattered in a batch tensor.
The kernel reads doc embeddings directly from batch_tensor at the
positions specified by doc_offsets. No torch.stack, no torch.cat,
no copy of any kind. The batch tensor is the model's output.
Memory for doc scoring: 0 bytes additional.
Args:
Q: [Lq, d] — single query embedding (from cache)
batch_tensor: [total_tokens, d] — the model's projected output tensor.
Contains ALL requests' tokens (queries + docs + others).
doc_offsets: [B] int32 — start token index of each doc in batch_tensor
doc_lengths: [B] int32 — number of tokens per doc
max_seqlen_d: int — max(doc_lengths)
Returns:
scores: [B] float32 — one MaxSim score per document
"""
assert Q.dim() == 2, f"Q must be 2D [Lq, d], got {Q.dim()}D"
assert batch_tensor.dim() == 2, (
f"batch_tensor must be 2D, got {batch_tensor.dim()}D"
)
assert Q.shape[1] == batch_tensor.shape[1]
return _run_rerank_kernel(Q, batch_tensor, doc_offsets, doc_lengths, max_seqlen_d)
+67 -2
View File
@@ -4,6 +4,7 @@ from collections.abc import Iterable
import torch
from vllm.logger import init_logger
from vllm.pooling_params import PoolingParams
from vllm.v1.outputs import PoolerOutput
from vllm.v1.pool.late_interaction import (
@@ -12,17 +13,29 @@ from vllm.v1.pool.late_interaction import (
compute_maxsim_score_batched,
)
logger = init_logger(__name__)
class LateInteractionRunner:
"""Worker-side state and postprocessing for late-interaction scoring."""
def __init__(self) -> None:
def __init__(self, enable_flash: bool = True) -> None:
# query_key -> token embeddings for late-interaction scoring.
self._query_cache: dict[str, torch.Tensor] = {}
# query_key -> remaining number of docs that should use this query.
self._query_uses: dict[str, int] = {}
# doc request id -> query key.
self._doc_query_keys: dict[str, str] = {}
# Fused Triton scoring (PoolerConfig.enable_flash_late_interaction
# gates it; a runtime kernel failure disables it for the process).
if enable_flash:
try:
from vllm.v1.pool.flash_maxsim import ( # noqa: F401
flash_maxsim_rerank_direct,
)
except ImportError:
enable_flash = False
self._flash_enabled = enable_flash
def clear(self) -> None:
self._query_cache.clear()
@@ -116,7 +129,7 @@ class LateInteractionRunner:
raise ValueError(f"Unsupported late-interaction mode: {mode!r}")
if score_indices:
score_values = compute_maxsim_score_batched(score_queries, score_docs)
score_values = self._score(score_queries, score_docs)
for i, req_id, query_key, score in zip(
score_indices, score_req_ids, score_query_keys, score_values
):
@@ -126,6 +139,58 @@ class LateInteractionRunner:
return outputs
def _score(
self,
queries: list[torch.Tensor],
docs: list[torch.Tensor],
) -> list[torch.Tensor]:
"""Score (query_i, doc_i) pairs: the fused Triton kernel handles the
common rerank pattern (one shared query, CUDA inputs); multiple
distinct queries, CPU tensors, or a kernel failure fall back to the
reference scorer."""
if self._flash_enabled and docs and queries[0].is_cuda:
first = queries[0]
if all(q is first for q in queries):
try:
return self._score_flash_shared_query(first, docs)
except Exception as exc:
# A persistent compile/launch failure must not take down
# requests: serve through the reference scorer and stop
# trying the kernel for the rest of the process.
self._flash_enabled = False
logger.warning(
"flash-maxsim scoring failed (%s); falling back to "
"the reference MaxSim path for this process.",
exc,
)
return compute_maxsim_score_batched(queries, docs)
@staticmethod
def _score_flash_shared_query(
query: torch.Tensor,
docs: list[torch.Tensor],
) -> list[torch.Tensor]:
"""One kernel launch for all docs against a single shared query:
docs pack into one [total_tokens, d] tensor (single cat, no padding)
and the kernel reads each by (offset, length) — the [B, Lq, Ld]
similarity tensor is never materialised."""
from vllm.v1.pool.flash_maxsim import flash_maxsim_rerank_direct
device = docs[0].device
lengths = [int(d.shape[0]) for d in docs]
offsets = [0] * len(lengths)
for i in range(1, len(lengths)):
offsets[i] = offsets[i - 1] + lengths[i - 1]
packed = docs[0] if len(docs) == 1 else torch.cat(docs, dim=0)
scores = flash_maxsim_rerank_direct(
query,
packed,
torch.tensor(offsets, device=device, dtype=torch.int32),
torch.tensor(lengths, device=device, dtype=torch.int32),
max(lengths),
)
return list(scores.unbind(0))
def _release_query_use(self, query_key: str) -> None:
remaining = self._query_uses.get(query_key, 1) - 1
if remaining <= 0:
+22 -11
View File
@@ -319,9 +319,11 @@ class TopKTopPSampler(nn.Module):
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""PyTorch-native implementation of top-k and top-p sampling for CPU.
"""Fused Gumbel-max sampling for CPU.
The logits tensor may be updated in-place.
Uses a precomputed Gumbel table + single-pass argmax over logits,
skipping softmax and intermediate allocations entirely.
Falls back to the native path when fp64 Gumbel noise is requested.
"""
logits = apply_top_k_top_p(logits, k, p)
logits_to_return = None
@@ -330,16 +332,25 @@ class TopKTopPSampler(nn.Module):
elif self.logprobs_mode == "processed_logprobs":
logits_to_return = logits.log_softmax(dim=-1, dtype=torch.float32)
if not generators and not self.use_fp64_gumbel:
return compiled_random_sample(logits), logits_to_return
if self.use_fp64_gumbel:
probs = logits.softmax(dim=-1, dtype=torch.float32)
q = empty_exponential_noise_like(probs, self.use_fp64_gumbel)
q.exponential_()
for i, generator in generators.items():
q[i].exponential_(generator=generator)
return sample_with_exponential_noise(probs, q), logits_to_return
probs = logits.softmax(dim=-1, dtype=torch.float32)
q = empty_exponential_noise_like(probs, self.use_fp64_gumbel)
q.exponential_()
for i, generator in generators.items():
q[i].exponential_(generator=generator)
return sample_with_exponential_noise(probs, q), logits_to_return
batch_size = logits.shape[0]
seeds = torch.randint(0, 2**31, (batch_size,), dtype=torch.long)
for i, gen in generators.items():
seeds[i] = torch.randint(
0, 2**31, (1,), generator=gen, dtype=torch.long
).item()
logits_f32 = logits.to(dtype=torch.float32)
return (
torch.ops._C.fused_gumbel_argmax(logits_f32, seeds),
logits_to_return,
)
def _init_aiter_ops(self) -> bool:
if self._aiter_ops_import_failed:
+2 -2
View File
@@ -103,7 +103,7 @@ def _update_min_larger_stats(data, above_mask, min_larger, num_min_larger, senti
return min_larger, num_min_larger
@triton.jit
@triton.jit(do_not_specialize_on_alignment=["BATCH_SIZE"])
def _topk_topp_kernel(
LOGITS,
LOGITS_STRIDE_0,
@@ -1225,7 +1225,7 @@ def _topp_sb_combine(
)
@triton.jit
@triton.jit(do_not_specialize_on_alignment=["ROUND"])
def _topp_sb_step_kernel(
LOGITS,
LOGITS_STRIDE_0,
+3
View File
@@ -6,6 +6,7 @@ import torch
import torch.nn as nn
from vllm.config.model import LogprobsMode
from vllm.platforms import current_platform
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.torch_utils import PIN_MEMORY
from vllm.v1.outputs import LogprobsTensors, SamplerOutput
@@ -239,6 +240,8 @@ class Sampler(nn.Module):
@staticmethod
def greedy_sample(logits: torch.Tensor) -> torch.Tensor:
if current_platform.is_cpu():
return torch.ops._C.greedy_argmax(logits)
return logits.argmax(dim=-1).view(-1)
def sample(
+2 -3
View File
@@ -34,6 +34,7 @@ from vllm.v1.core.kv_cache_utils import (
maybe_convert_block_hash,
resolve_block_hashes,
resolve_dcp_kv_block_size,
to_event_extra_keys,
)
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import (
@@ -1147,9 +1148,7 @@ class SimpleCPUOffloadScheduler:
lora_id=meta.lora_id if meta else None,
medium=self.kv_event_medium,
lora_name=meta.lora_name if meta else None,
extra_keys=(
[extra_keys] if extra_keys is not None else None
),
extra_keys=to_event_extra_keys(extra_keys and [extra_keys]),
group_idx=group_idx,
kv_cache_spec_kind=get_kv_cache_spec_kind(spec).value,
kv_cache_spec_sliding_window=(
+18 -1
View File
@@ -354,6 +354,7 @@ class RustFrontendProcessManager:
engine_count: int,
data_parallel_size: int,
stats_update_address: str | None = None,
grpc_sock: Any | None = None,
):
import os
import subprocess
@@ -377,6 +378,12 @@ class RustFrontendProcessManager:
"--data-parallel-size",
str(data_parallel_size),
]
pass_fds = [fd]
if grpc_sock is not None:
grpc_fd = grpc_sock.fileno()
os.set_inheritable(grpc_fd, True)
cmd.extend(["--grpc-listen-fd", str(grpc_fd)])
pass_fds.append(grpc_fd)
if stats_update_address is not None:
cmd.extend(["--coordinator-address", stats_update_address])
from vllm.entrypoints.serve.utils.api_utils import jsonify_non_default_args
@@ -391,6 +398,16 @@ class RustFrontendProcessManager:
"data_parallel_hybrid_lb",
},
)
# `model_tag` is the positional `vllm serve` model argument. When the
# model is supplied only through `--config`, argparse populates `model`
# while leaving `model_tag` unset. The Rust frontend requires
# `model_tag` in its JSON bootstrap payload, so use the resolved model
# as a fallback.
model_tag = getattr(args, "model_tag", None) or getattr(args, "model", None)
if model_tag is not None:
args_dict["model_tag"] = model_tag
# The Rust `frontend` subcommand parses --args-json via serde_json,
# which bypasses clap and therefore ignores any `#[arg(env = ...)]`
# declarations on SharedRuntimeArgs fields. Forward the env-driven
@@ -408,7 +425,7 @@ class RustFrontendProcessManager:
redacted_json = json.dumps(redact_sensitive_args(args_dict), sort_keys=True)
logger.info("Launching Rust frontend: %s", " ".join(cmd[:-1] + [redacted_json]))
self._proc = subprocess.Popen(cmd, pass_fds=(fd,))
self._proc = subprocess.Popen(cmd, pass_fds=pass_fds)
# Create a process wrapper with a sentinel fd for monitoring
self.processes: list[_SubprocessWrapper] = [
+11 -2
View File
@@ -119,8 +119,9 @@ class GPUWatermarkSampler(Sampler):
self,
expanded_idx_mapping: torch.Tensor,
contexts: torch.Tensor,
expanded_local_pos: torch.Tensor | None = None,
) -> torch.Tensor:
return repeated_context_mask(
repeated = repeated_context_mask(
self.req_states.all_token_ids.gpu,
expanded_idx_mapping,
self.req_states.prompt_len.gpu,
@@ -128,8 +129,16 @@ class GPUWatermarkSampler(Sampler):
contexts,
self.deduplicate_contexts_max_history,
include_prompt=self.deduplicate_contexts == "all",
skip_partial_context=self.deduplicate_contexts == "all",
skip_partial_context=(
self.deduplicate_contexts == "all" and expanded_local_pos is None
),
history_offsets=expanded_local_pos,
local_positions=expanded_local_pos,
num_speculative_steps=(
self.num_speculative_tokens if expanded_local_pos is not None else 0
),
)
return repeated
def _get_contexts(
self,
+4
View File
@@ -94,6 +94,10 @@ class GumbelWatermarker(Watermarker):
seeds=random_sampler.seeds,
positions=random_sampler.positions,
use_fp64=random_sampler.use_fp64,
is_drafting=random_sampler.is_drafting,
logits_cache=random_sampler.logits_cache,
logits_cache_col=random_sampler.logits_cache_col,
logits_cache_source=random_sampler.logits_cache_source,
)
return WatermarkSample(token_ids, logits)
+112 -10
View File
@@ -3,14 +3,16 @@
import torch
from vllm.config.watermarking import WatermarkConfig
from vllm.config.watermarking import WatermarkConfig, WatermarkContextScope
from vllm.v1.watermarking.factory import create_watermarker
from vllm.v1.watermarking.gumbel import GumbelWatermarker
from vllm.v1.watermarking.prfs import PhiloxPRF
from vllm.v1.watermarking.watermarker import (
RandomSampler,
SupportsSpeculativeDecoding,
Watermarker,
)
from vllm.v1.worker.gpu.sample.watermark import draft_watermarking_mask
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import rejection_sample
@@ -20,8 +22,14 @@ class DraftWatermarker:
watermarker: Watermarker,
max_num_reqs: int,
device: torch.device,
num_speculative_steps: int,
deduplicate_contexts: WatermarkContextScope,
deduplicate_contexts_max_history: int | None,
) -> None:
self.watermarker = watermarker
self.num_speculative_steps = num_speculative_steps
self.deduplicate_contexts = deduplicate_contexts
self.deduplicate_contexts_max_history = deduplicate_contexts_max_history
self.contexts = torch.zeros(
max_num_reqs,
watermarker.context_width,
@@ -29,30 +37,112 @@ class DraftWatermarker:
device=device,
)
self.enabled = torch.zeros(max_num_reqs, dtype=torch.bool, device=device)
self.prior_contexts = torch.zeros(
max_num_reqs,
num_speculative_steps,
watermarker.context_width,
dtype=torch.int64,
device=device,
)
self.all_token_ids: torch.Tensor | None = None
self.prompt_lens: torch.Tensor | None = None
self.total_lens: torch.Tensor | None = None
def prepare(self, contexts: torch.Tensor, enabled: torch.Tensor) -> None:
def prepare(
self,
contexts: torch.Tensor,
enabled: torch.Tensor,
all_token_ids: torch.Tensor,
prompt_lens: torch.Tensor,
total_lens: torch.Tensor,
) -> None:
num_reqs = contexts.shape[0]
self.contexts[:num_reqs].copy_(contexts)
self.enabled[:num_reqs].copy_(enabled)
self.all_token_ids = all_token_ids
self.prompt_lens = prompt_lens
self.total_lens = total_lens
def _sampling_state(
self,
logits: torch.Tensor,
idx_mapping: torch.Tensor,
request_temperatures: torch.Tensor,
draft_step: int | torch.Tensor,
contexts: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
num_rows = logits.shape[0]
steps = torch.as_tensor(draft_step, device=logits.device, dtype=torch.int64)
if steps.ndim == 0:
steps = steps.expand(num_rows)
enabled = self.enabled[:num_rows] & (request_temperatures != 0)
if self.deduplicate_contexts == "none":
return steps, enabled
assert self.all_token_ids is not None
assert self.prompt_lens is not None
assert self.total_lens is not None
enabled = draft_watermarking_mask(
self.all_token_ids,
idx_mapping,
self.prompt_lens,
self.total_lens,
self.prior_contexts,
contexts,
steps,
enabled,
self.deduplicate_contexts_max_history,
include_prompt=self.deduplicate_contexts == "all",
)
return steps, enabled
def sample(
self,
logits: torch.Tensor,
ordinary_sampled: torch.Tensor,
idx_mapping: torch.Tensor,
temperature: torch.Tensor,
seed: torch.Tensor,
pos: torch.Tensor,
apply_temperature: bool,
is_drafting: bool,
logits_cache: torch.Tensor | None = None,
logits_cache_col: torch.Tensor | None = None,
use_fp64: bool = False,
logits_cache_source: torch.Tensor | None = None,
) -> torch.Tensor:
assert apply_temperature
assert is_drafting
assert logits_cache is not None
assert logits_cache_col is not None
num_rows = logits.shape[0]
request_temperatures = temperature[idx_mapping]
contexts = self.contexts[:num_rows]
steps, enabled = self._sampling_state(
logits, idx_mapping, request_temperatures, logits_cache_col, contexts
)
processed_logits = logits / torch.where(
request_temperatures == 0, 1, request_temperatures
).unsqueeze(-1)
watermarked = self.watermarker.sample(
random_sampler = RandomSampler(
expanded_idx_mapping=idx_mapping,
temperatures=temperature,
seeds=seed,
positions=pos,
use_fp64=use_fp64,
is_drafting=True,
logits_cache=logits_cache,
logits_cache_col=steps,
logits_cache_source=(
logits if logits_cache_source is None else logits_cache_source
),
)
sampled = self.watermarker.sample(
processed_logits,
self.contexts[: logits.shape[0]],
contexts,
random_sampler=random_sampler,
skip_mask=~enabled,
).token_ids
enabled = self.enabled[: logits.shape[0]] & (request_temperatures != 0)
sampled = torch.where(enabled, watermarked, ordinary_sampled)
contexts = self.contexts[: logits.shape[0]]
contexts.copy_(torch.cat((contexts[:, 1:], sampled.unsqueeze(-1)), dim=-1))
return sampled
@@ -68,9 +158,19 @@ def create_speculative_draft_watermarker(
max_num_reqs: int,
device: torch.device,
allow_target_only: bool,
num_speculative_steps: int = 1,
deduplicate_contexts: WatermarkContextScope = "none",
deduplicate_contexts_max_history: int | None = 8192,
) -> DraftWatermarker | None:
if isinstance(watermarker, SupportsSpeculativeDecoding):
return DraftWatermarker(watermarker.draft_watermarker, max_num_reqs, device)
return DraftWatermarker(
watermarker.draft_watermarker,
max_num_reqs,
device,
num_speculative_steps,
deduplicate_contexts,
deduplicate_contexts_max_history,
)
if allow_target_only:
return None
raise ValueError(
@@ -130,9 +230,10 @@ def watermarked_rejection_sample(
contexts: torch.Tensor,
watermarking: torch.Tensor,
watermarker: Watermarker,
watermarking_skip_mask: torch.Tensor | None = None,
use_fp64: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Use the target key for rejection recovery and bonus tokens."""
"""Use the target key except at contexts selected for ordinary sampling."""
assert contexts.shape == (target_logits.shape[0], watermarker.context_width)
return rejection_sample(
target_logits,
@@ -149,5 +250,6 @@ def watermarked_rejection_sample(
use_fp64=use_fp64,
contexts=contexts,
watermarking=watermarking,
watermarking_skip_mask=watermarking_skip_mask,
watermark_key=_resolve_watermark_key(watermarker),
)
+8 -1
View File
@@ -23,6 +23,10 @@ class RandomSampler:
seeds: torch.Tensor
positions: torch.Tensor
use_fp64: bool = False
is_drafting: bool = False
logits_cache: torch.Tensor | None = None
logits_cache_col: torch.Tensor | None = None
logits_cache_source: torch.Tensor | None = None
def __call__(self, logits: torch.Tensor) -> torch.Tensor:
return gumbel_sample(
@@ -32,7 +36,10 @@ class RandomSampler:
self.seeds,
self.positions,
apply_temperature=False,
is_drafting=False,
is_drafting=self.is_drafting,
logits_cache=self.logits_cache,
logits_cache_col=self.logits_cache_col,
logits_cache_source=self.logits_cache_source,
use_fp64=self.use_fp64,
)
+1 -1
View File
@@ -185,7 +185,7 @@ class AsyncOutput(AsyncModelRunnerOutput):
if self.sampling_mask_tensors is not None:
self.model_runner_output.sampling_masks = (
self.sampling_mask_tensors.tolists()
self.sampling_mask_tensors.tolists(self.num_sampled_tokens_np)
)
if self.num_nans is not None:
+3 -2
View File
@@ -23,7 +23,7 @@ from vllm.v1.attention.backend import (
from vllm.v1.attention.backends.utils import create_fast_prefill_custom_backend
from vllm.v1.hisparse.binding import (
init_hisparse_kv_cache,
resolve_hisparse_block_size,
resolve_hisparse_specs,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
@@ -142,7 +142,8 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
if isinstance(spec, AttentionSpec):
spec = attn_module.get_attn_backend().customize_spec(spec)
kv_cache_spec[layer_name] = spec
resolve_hisparse_block_size(vllm_config, kv_cache_spec, attn_layers)
if vllm_config.attention_config.hisparse_config is not None:
kv_cache_spec = resolve_hisparse_specs(vllm_config, kv_cache_spec, attn_layers)
return kv_cache_spec
+4
View File
@@ -103,6 +103,9 @@ class InputBatch:
# [num_reqs] per-request prompt length, only populated for R-SWA.
prompt_lens: torch.Tensor | None
# [num_reqs] only populated for non-dummy pipeline-parallel batches.
max_seq_len_np: np.ndarray | None = None
# Longest query the batch may contain. Set when a cudagraph descriptor promises
# a query length this batch's own split does not reach, so attention metadata
# stays valid for every replay the graph serves.
@@ -203,6 +206,7 @@ class InputBatch:
num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32),
is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_),
has_prefill=False,
max_seq_len_np=None,
decode_graph_eligible=True,
input_ids=input_ids,
positions=positions,
+33 -7
View File
@@ -164,7 +164,10 @@ from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import DraftTokensHandler
from vllm.v1.worker.gpu.states import RequestState
from vllm.v1.worker.gpu.structured_outputs import StructuredOutputsWorker
from vllm.v1.worker.gpu.structured_outputs import (
StructuredOutputsWorker,
grammar_invalid_drafts,
)
from vllm.v1.worker.gpu.ubatch_utils import (
UBatchRunner,
UBatchState,
@@ -802,6 +805,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
skip_eplb: bool = False,
is_profile: bool = False,
valid_dummy_state_slots: bool = False,
randomize_inputs: bool = False,
**kwargs,
) -> tuple[torch.Tensor | None, torch.Tensor | None]:
if skip_attn and not is_profile:
@@ -875,6 +879,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
is_profile=is_profile,
context_len=context_len,
valid_dummy_state_slots=valid_dummy_state_slots,
randomize_inputs=randomize_inputs,
)
self.kv_connector.set_disabled(False)
@@ -914,8 +919,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
spec_hidden_states = pre_hc_hidden_states[: hidden_states.shape[0]] # type: ignore[union-attr]
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler._get_contexts(input_batch.idx_mapping),
self.sampler.watermarking.gpu[input_batch.idx_mapping],
self.sampler, input_batch.idx_mapping
)
with use_workspace_lane(self._draft_workspace_lane):
self.speculator.propose(
@@ -966,7 +970,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.pooling_runner.dummy_pooler_run(hidden_states)
@torch.inference_mode()
def profile_run(self) -> None:
def profile_run(self, randomize_inputs: bool = False) -> None:
if self.supports_mm_inputs and self.is_first_pp_rank:
mm_config = self.model_config.multimodal_config
if mm_config is not None and not mm_config.skip_mm_profiling:
@@ -979,7 +983,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
hidden_states, sample_hidden_states = self._dummy_run(
self.max_num_tokens, skip_attn=True, is_profile=True
self.max_num_tokens,
skip_attn=True,
is_profile=True,
randomize_inputs=randomize_inputs,
)
# Only run sampler/pooler on last PP rank (non-last ranks return None).
@@ -1272,6 +1279,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
]
is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np
has_prefill = bool(is_prefilling_np.any())
max_seq_len_np = None
if self.use_pp and has_prefill:
# consumed by the PP `compute_need_sampled_mask` for batches with prefill.
max_seq_len_np = self.req_states.max_seq_len[idx_mapping_np]
num_draft_tokens_np = None
if draft_tokens:
@@ -1310,6 +1321,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
has_prefill=has_prefill,
prefill_runs_as_decode_np=prefill_runs_as_decode_np,
decode_graph_eligible=decode_graph_eligible,
max_seq_len_np=max_seq_len_np,
)
return batch_state, get_uniform_decode_token_count(
num_reqs, num_toks, max_query_len, decode_graph_eligible
@@ -1497,6 +1509,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
has_prefill=batch_req_state.has_prefill,
prefill_runs_as_decode_np=batch_req_state.prefill_runs_as_decode_np,
decode_graph_eligible=batch_req_state.decode_graph_eligible,
max_seq_len_np=batch_req_state.max_seq_len_np,
input_ids=self.input_buffers.input_ids[:num_tokens_after_padding],
positions=self.input_buffers.positions[:num_tokens_after_padding],
is_padding=is_padding,
@@ -1577,6 +1590,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
sample_hidden_states = hidden_states[input_batch.logits_indices]
logits = self.model.compute_logits(sample_hidden_states)
invalid_drafts = None
# A diffusion prefill has no logit rows even when a bitmask row
# arrived for it.
if grammar_output is not None and logits.shape[0] > 0:
@@ -1588,6 +1602,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
grammar_output.structured_output_request_ids,
grammar_output.grammar_bitmask,
)
invalid_drafts = grammar_invalid_drafts(
input_batch,
grammar_output.structured_output_request_ids,
grammar_output.num_acceptable_drafts,
)
sampler_output: SamplerOutput | None
if input_batch.num_reqs == 0:
@@ -1606,6 +1625,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
input_batch,
# Draft logits are needed for probabilistic rejection sampling.
self.speculator.draft_logits,
invalid_drafts,
)
if shard_metadata is not None:
@@ -1681,6 +1701,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
is_profile: bool = False,
context_len: int = 0,
valid_dummy_state_slots: bool = False,
randomize_inputs: bool = False,
) -> ModelRunnerOutput | IntermediateTensors | None:
if not dummy_run:
# Update the request states.
@@ -1799,6 +1820,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# so MoE memory is measured and MoE kernels are exercised.
is_padding=not is_profile,
)
if randomize_inputs:
# All-zero input_ids route every token to the same experts.
input_batch.input_ids.random_(0, self.vocab_size)
if self.pcp_manager is not None:
input_batch = self.pcp_manager.prepare_inputs_to_capture(input_batch)
if skip_attn_for_dummy_run:
@@ -2064,6 +2088,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Non-last PP rank: hidden_states is None because this rank produced
# IntermediateTensors instead of final hidden states. Receive the
# sampled tokens broadcast from the last rank and update local state.
if self.pcp_manager is not None:
input_batch = self.pcp_manager.global_batch
assert self.pp_handler is not None
all_decode_next = self.pp_handler.receive(input_batch)
# Optimistically update num_computed_tokens for entire batch here.
@@ -2192,8 +2218,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
spec_hidden_states = pre_hc_hidden_states[: draft_hidden_states.size(0)]
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler._get_contexts(input_batch.idx_mapping),
self.sampler.watermarking.gpu[input_batch.idx_mapping],
self.sampler, input_batch.idx_mapping
)
with use_workspace_lane(self._draft_workspace_lane):
draft_tokens = self.speculator.propose(
@@ -2382,6 +2407,7 @@ class BatchReqState(NamedTuple):
prefill_len_np: np.ndarray # [num_reqs]
num_computed_prefill_tokens_np: np.ndarray # [num_reqs]
is_prefilling_np: np.ndarray # [num_reqs]
max_seq_len_np: np.ndarray | None # [num_reqs], None in non-pp case
has_prefill: bool
prefill_runs_as_decode_np: np.ndarray | None # [num_reqs]
decode_graph_eligible: bool
+32 -5
View File
@@ -49,6 +49,7 @@ class PCPManager:
pcp_world_size: int,
pcp_rank: int,
device: torch.device,
shard_decode_requests: bool,
max_num_reqs: int | None = None,
max_num_tokens: int | None = None,
block_tables: BlockTables | None = None,
@@ -62,6 +63,7 @@ class PCPManager:
self.dcp_world_size = dcp_world_size
self.dcp_rank = dcp_rank
self.cp_interleave = cp_interleave
self.shard_decode_requests = shard_decode_requests
self._global_batch: InputBatch | None = None
self._local_batch: InputBatch | None = None
@@ -131,8 +133,6 @@ class PCPManager:
if not model_config.use_mla:
raise NotImplementedError("MRV2 PCP currently supports MLA models only.")
if parallel_config.pipeline_parallel_size > 1:
raise NotImplementedError("MRV2 PCP does not support PP yet.")
if model_config.is_encoder_decoder:
raise NotImplementedError(
"MRV2 PCP does not support encoder-decoder models yet."
@@ -250,6 +250,7 @@ class PCPManager:
Decodes, and prefills too short to fill all eight, are replicated instead.
"""
decode_ordinal = 0
num_chunks = 2 * self.pcp_world_size
replicated = self.replicated_requests(num_scheduled_tokens, is_prefilling)
for global_batch_req_idx, num_tokens in enumerate(num_scheduled_tokens):
@@ -260,7 +261,16 @@ class PCPManager:
if not replicated[global_batch_req_idx]:
chunk_size = (query_len + num_chunks - 1) // num_chunks
chunk_indices = (rank, num_chunks - 1 - rank)
else: # decodes, and short prefills under DCP, are replicated
elif self.shard_decode_requests:
chunk_size = query_len
# KV and hidden states are gathered back to every PCP rank, so
# decode ownership does not need to persist across steps. Use a
# compact decode-only ordinal to keep each step exactly
# balanced even when prefills and zero-token rows are present.
owner_rank = decode_ordinal % self.pcp_world_size
decode_ordinal += 1
chunk_indices = (0,) if rank == owner_rank else ()
else: # DCP requires decode queries on every participating rank.
chunk_size = query_len
chunk_indices = (0,)
@@ -348,8 +358,18 @@ class PCPManager:
segment.global_batch_slice.stop,
dtype=np.int64,
)
# Cache insertion pairs one slot entry with each rank's local decode.
if replicated[segment.global_batch_req_idx] and rank != 0:
# Replicated rows contain identical KV, so rank 0 is the
# canonical writer. A sharded decode has exactly one owner and
# therefore needs no de-duplication here.
is_sharded_decode = (
not bool(is_prefilling[segment.global_batch_req_idx])
and self.shard_decode_requests
)
if (
replicated[segment.global_batch_req_idx]
and not is_sharded_decode
and rank != 0
):
continue
gathered_kv_write_mask[padded_gathered_slice] = True
hidden_restore_idx[segment.global_batch_slice] = np.arange(
@@ -406,6 +426,11 @@ class PCPManager:
assert self._input_buffers is not None
return self._input_buffers
@property
def global_batch(self) -> InputBatch:
assert self._global_batch is not None
return self._global_batch
def partition_batch(
self, input_batch: InputBatch, batch_desc: "BatchExecutionDescriptor"
) -> InputBatch:
@@ -646,6 +671,7 @@ class PCPManager:
prefill_len_np=local_prefill_len_np,
num_computed_prefill_tokens_np=local_num_computed_prefill_tokens_np,
is_prefilling_np=local_is_prefilling_np,
max_seq_len_np=None,
has_prefill=local_has_prefill,
decode_graph_eligible=not local_has_prefill,
prefill_runs_as_decode_np=None,
@@ -825,6 +851,7 @@ def maybe_build_pcp_manager(
pcp_world_size=pcp_size,
pcp_rank=pcp_rank,
device=device,
shard_decode_requests=parallel_config.pcp_shard_decode_requests,
max_num_reqs=vllm_config.scheduler_config.max_num_seqs,
max_num_tokens=vllm_config.scheduler_config.max_num_batched_tokens,
block_tables=block_tables,
+5 -1
View File
@@ -51,7 +51,11 @@ class PoolingRunner:
self.pooling_params: dict[int, PoolingParams] = {}
self.pooling_states: dict[int, PoolingStates] = {}
self.prompt_token_ids: dict[int, torch.Tensor] = {}
self.late_interaction_runner = LateInteractionRunner()
pooler_config = self.model_config.pooler_config
self.late_interaction_runner = LateInteractionRunner(
enable_flash=pooler_config is None
or getattr(pooler_config, "enable_flash_late_interaction", True)
)
@staticmethod
def get_supported_tasks(model: nn.Module) -> list[PoolingTask]:
+10 -5
View File
@@ -37,14 +37,19 @@ class PendingRecv:
def compute_need_sampled_mask(input_batch: InputBatch) -> np.ndarray | None:
"""Return a bool array of shape `[input_batch.num_reqs]` marking requests
that produce a sampled token this step, and therefore must have that token
(and the draft block proposed from it) propagated to the earlier PP stages.
Returns None if no request in the batch produces a sample."""
with outputs that might be needed in a subsequent (decode) step.
Returns None if no sampled outputs are needed in the requests' next step."""
old_computed = input_batch.num_computed_tokens_np
prefill_len = input_batch.prefill_len_np
# Exclude non-final prefill chunks (they don't produce a sample).
produces_sample = old_computed + input_batch.num_scheduled_tokens >= prefill_len
return produces_sample if produces_sample.any() else None
need_sampled_mask = old_computed + input_batch.num_scheduled_tokens >= prefill_len
if input_batch.max_seq_len_np is not None:
# Also exclude final prefill chunks whose single sampled token reaches
# the request's length cap.
finished_prefill = prefill_len + 1 >= input_batch.max_seq_len_np
finished_prefill &= input_batch.is_prefilling_np
need_sampled_mask &= ~finished_prefill
return need_sampled_mask if need_sampled_mask.any() else None
class PPHandler:
+7
View File
@@ -339,9 +339,16 @@ def _shard_grammar_output(
cursor += num_req_logits
if not local_ids:
return None
# num_acceptable_drafts is ordered with structured_output_request_ids.
num_acceptable = grammar_output.num_acceptable_drafts
if num_acceptable is not None:
owned = set(local_ids)
ids = grammar_output.structured_output_request_ids
num_acceptable = [n for i, n in zip(ids, num_acceptable) if i in owned]
return GrammarOutput(
structured_output_request_ids=local_ids,
grammar_bitmask=grammar_output.grammar_bitmask[keep_indices],
num_acceptable_drafts=num_acceptable,
)
+29 -1
View File
@@ -220,6 +220,8 @@ def gumbel_block_argmax(
logits_cache_stride_0,
logits_cache_stride_1,
logits_cache_col_ptr,
logits_cache_source_ptr,
logits_cache_source_stride,
vocab_size,
IS_DRAFTING: tl.constexpr,
APPLY_TEMPERATURE: tl.constexpr,
@@ -240,12 +242,16 @@ def gumbel_block_argmax(
col = tl.load(logits_cache_col_ptr + token_idx)
else:
col = tl.load(logits_cache_col_ptr)
cached_logits = tl.load(
logits_cache_source_ptr + token_idx * logits_cache_source_stride + block,
mask=mask,
)
tl.store(
logits_cache_ptr
+ req_state_idx * logits_cache_stride_0
+ col * logits_cache_stride_1
+ block,
logits,
cached_logits,
mask=mask & is_valid_req,
)
@@ -275,6 +281,8 @@ def _gumbel_sample_kernel(
logits_cache_stride_0,
logits_cache_stride_1,
logits_cache_col_ptr,
logits_cache_source_ptr,
logits_cache_source_stride,
logits_ptr,
logits_stride,
expanded_idx_mapping_ptr,
@@ -312,6 +320,8 @@ def _gumbel_sample_kernel(
logits_cache_stride_0,
logits_cache_stride_1,
logits_cache_col_ptr,
logits_cache_source_ptr,
logits_cache_source_stride,
vocab_size,
IS_DRAFTING=IS_DRAFTING,
APPLY_TEMPERATURE=APPLY_TEMPERATURE,
@@ -334,6 +344,7 @@ def gumbel_sample(
logits_cache: torch.Tensor | None = None, # [max_num_reqs, num_cols, vocab_size]
logits_cache_col: torch.Tensor | None = None, # scalar or [num_tokens]
use_fp64: bool = False,
logits_cache_source: torch.Tensor | None = None,
) -> torch.Tensor:
# Enforce contiguity on non-strided input tensors
expanded_idx_mapping = expanded_idx_mapping.contiguous()
@@ -342,11 +353,26 @@ def gumbel_sample(
logits_cache_col = logits_cache_col.contiguous()
num_tokens, vocab_size = logits.shape
if logits_cache is not None:
if logits_cache_source is None:
logits_cache_source = logits
assert logits_cache_source.shape == logits.shape, (
"logits cache source must match sampled logits shape"
)
assert logits_cache_source.device == logits.device, (
"logits cache source must be on the sampled logits device"
)
assert logits_cache_source.dtype == logits_cache.dtype, (
"logits cache source and destination must have the same dtype"
)
assert logits_cache.size(-1) >= vocab_size, (
f"draft logits cache vocab dim ({logits_cache.size(-1)}) is narrower "
f"than the sampled logits ({vocab_size}). Cached logits would be "
"truncated."
)
elif logits_cache_source is not None:
raise ValueError("logits_cache_source requires logits_cache")
if logits_cache_source is not None and logits_cache_source.stride(-1) != 1:
logits_cache_source = logits_cache_source.contiguous()
BLOCK_SIZE = 1024
num_blocks = triton.cdiv(vocab_size, BLOCK_SIZE)
local_argmax = logits.new_empty(num_tokens, num_blocks, dtype=torch.int64)
@@ -362,6 +388,8 @@ def gumbel_sample(
logits_cache.stride(0) if logits_cache is not None else 0,
logits_cache.stride(1) if logits_cache is not None else 0,
logits_cache_col,
logits_cache_source,
logits_cache_source.stride(0) if logits_cache_source is not None else 0,
logits,
logits.stride(0),
expanded_idx_mapping,
+70 -21
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from typing import NamedTuple
@@ -27,6 +28,7 @@ def _compact_sampling_mask_kernel(
logits_ptr,
logits_row_stride,
logits_col_stride,
cu_num_logits_ptr,
num_sampled_tokens_ptr,
token_ids_ptr,
token_ids_row_stride,
@@ -35,25 +37,32 @@ def _compact_sampling_mask_kernel(
counts_ptr,
vocab_size,
max_num_kept,
ROWS_PER_REQUEST: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
"""Per row: first ``max_num_kept`` finite-logit ids, the full count, the bitmask."""
req_idx = tl.program_id(0)
is_active = tl.load(num_sampled_tokens_ptr + req_idx) > 0
output_row = tl.program_id(0)
req_idx = output_row // ROWS_PER_REQUEST
slot_idx = output_row % ROWS_PER_REQUEST
if slot_idx >= tl.load(num_sampled_tokens_ptr + req_idx):
tl.store(counts_ptr + output_row, 0)
return
source_row = tl.load(cu_num_logits_ptr + req_idx) + slot_idx
count = tl.zeros((), dtype=tl.int32)
for start_idx in range(0, vocab_size, BLOCK_SIZE):
offsets = start_idx + tl.arange(0, BLOCK_SIZE)
logits = tl.load(
logits_ptr + req_idx * logits_row_stride + offsets * logits_col_stride,
logits_ptr + source_row * logits_row_stride + offsets * logits_col_stride,
mask=offsets < vocab_size,
other=-float("inf"),
)
keep = (logits > -float("inf")) & (logits < float("inf")) & is_active
keep = (logits > -float("inf")) & (logits < float("inf"))
keep_i32 = keep.to(tl.int32)
pos = count + tl.cumsum(keep_i32, axis=0) - keep_i32
tl.store(
token_ids_ptr + req_idx * token_ids_row_stride + pos,
token_ids_ptr + output_row * token_ids_row_stride + pos,
offsets.to(tl.int32),
mask=keep & (pos < max_num_kept),
)
@@ -62,12 +71,12 @@ def _compact_sampling_mask_kernel(
bits = tl.reshape(keep_i32, (BLOCK_SIZE // 8, 8)) << tl.arange(0, 8)[None, :]
byte_offsets = start_idx // 8 + tl.arange(0, BLOCK_SIZE // 8)
tl.store(
packed_mask_ptr + req_idx * packed_mask_row_stride + byte_offsets,
packed_mask_ptr + output_row * packed_mask_row_stride + byte_offsets,
tl.sum(bits, axis=1).to(tl.uint8),
mask=byte_offsets < tl.cdiv(vocab_size, 8),
)
tl.store(counts_ptr + req_idx, count)
tl.store(counts_ptr + output_row, count)
# Bounds the [num_reqs, width] int32 buffer; wider rows use the bitmask instead.
@@ -78,37 +87,46 @@ class SamplingMaskTensors(NamedTuple):
"""Device-side masks pending async D2H: compact ids, plus the bitmask as
the exact fallback for rows wider than ``max_num_kept``."""
# [num_requests, max_num_kept]
# [num_requests * rows_per_request, max_num_kept]
token_ids: torch.Tensor
# [num_requests, ceil(vocab_size / 8)]
# [num_requests * rows_per_request, ceil(vocab_size / 8)]
packed_mask: torch.Tensor
# [num_requests]
# [num_requests * rows_per_request]
counts: torch.Tensor
vocab_size: int
# Fixed request-major output slots. Ordinary sampling has one slot.
rows_per_request: int = 1
@classmethod
def from_logits(
cls,
logits: torch.Tensor,
cu_num_logits: torch.Tensor,
num_sampled_tokens: torch.Tensor,
max_num_kept: int,
rows_per_request: int = 1,
) -> SamplingMaskTensors:
"""Capture the finite-logit support of every row with a sampled token."""
num_reqs, vocab_size = logits.shape
"""Capture committed target supports in fixed request-major slots."""
num_reqs = num_sampled_tokens.shape[0]
vocab_size = logits.shape[1]
max_num_kept = min(max_num_kept, vocab_size, MAX_COMPACT_SUPPORT)
num_output_rows = num_reqs * rows_per_request
device = logits.device
token_ids = torch.empty(
(num_reqs, max_num_kept), dtype=torch.int32, device=device
(num_output_rows, max_num_kept), dtype=torch.int32, device=device
)
packed_mask = torch.empty(
(num_reqs, (vocab_size + 7) // 8), dtype=torch.uint8, device=device
(num_output_rows, (vocab_size + 7) // 8),
dtype=torch.uint8,
device=device,
)
counts = torch.empty(num_reqs, dtype=torch.int32, device=device)
_compact_sampling_mask_kernel[(num_reqs,)](
counts = torch.empty(num_output_rows, dtype=torch.int32, device=device)
_compact_sampling_mask_kernel[(num_output_rows,)](
logits,
logits.stride(0),
logits.stride(1),
cu_num_logits,
num_sampled_tokens,
token_ids,
token_ids.stride(0),
@@ -117,9 +135,23 @@ class SamplingMaskTensors(NamedTuple):
counts,
vocab_size,
max_num_kept,
ROWS_PER_REQUEST=rows_per_request,
BLOCK_SIZE=8192,
)
return cls(token_ids, packed_mask, counts, vocab_size)
return cls(token_ids, packed_mask, counts, vocab_size, rows_per_request)
@classmethod
def cat(cls, chunks: Sequence[SamplingMaskTensors]) -> SamplingMaskTensors:
"""Join request-contiguous chunks that share one output layout."""
first = chunks[0]
assert len({(c.vocab_size, c.rows_per_request) for c in chunks}) == 1
return cls(
torch.cat([chunk.token_ids for chunk in chunks]),
torch.cat([chunk.packed_mask for chunk in chunks]),
torch.cat([chunk.counts for chunk in chunks]),
first.vocab_size,
first.rows_per_request,
)
def to_cpu_nonblocking(self) -> SamplingMaskTensors:
if self.token_ids.device.type == "cpu":
@@ -129,15 +161,31 @@ class SamplingMaskTensors(NamedTuple):
self.packed_mask.to("cpu", non_blocking=True),
self.counts.to("cpu", non_blocking=True),
self.vocab_size,
self.rows_per_request,
)
def tolists(self) -> SamplingMaskLists:
"""CSR over all requests; rows without a sampled token are empty."""
def tolists(
self, num_sampled_tokens: np.ndarray | None = None
) -> SamplingMaskLists:
"""Convert fixed output rows to the scheduler's CSR representation."""
counts = self.counts.cpu().numpy()
token_ids = self.token_ids.cpu().numpy()
packed_mask = self.packed_mask.cpu().numpy()
width = token_ids.shape[1]
cu_num_generated_tokens = None
if self.rows_per_request == 1:
sampled_rows = np.arange(len(counts))
else:
assert num_sampled_tokens is not None
active_slots = (
np.arange(self.rows_per_request)[None, :] < num_sampled_tokens[:, None]
)
sampled_rows = np.flatnonzero(active_slots)
cu_num_generated_tokens = np.cumsum(
np.concatenate(([0], num_sampled_tokens))
).tolist()
def support(row: int) -> np.ndarray:
if counts[row] <= width:
return token_ids[row, : counts[row]]
@@ -147,7 +195,8 @@ class SamplingMaskTensors(NamedTuple):
)
return np.flatnonzero(bits).astype(np.int32, copy=False)
supports = [support(row) for row in range(len(counts))]
supports = [support(row) for row in sampled_rows]
offsets = np.zeros(len(supports) + 1, dtype=np.int64)
np.cumsum([len(s) for s in supports], out=offsets[1:])
return SamplingMaskLists(np.concatenate(supports), offsets)
flat = np.concatenate([np.empty(0, dtype=np.int32), *supports])
return SamplingMaskLists(flat, offsets, cu_num_generated_tokens)
+4 -1
View File
@@ -203,7 +203,10 @@ class Sampler:
# Size by the validated top_k batch max; wider supports use the bitmask.
max_num_kept = int(np.max(self.sampling_states.top_k.np[idx_mapping_np]))
sampling_mask_tensors = SamplingMaskTensors.from_logits(
processed_logits, num_sampled, max_num_kept
processed_logits,
input_batch.cu_num_logits,
num_sampled,
max_num_kept,
)
# These are GPU tensors.
+315 -7
View File
@@ -51,12 +51,25 @@ def _repeated_context_mask_kernel(
req_indices_ptr,
prompt_lens_ptr,
total_lens_ptr,
history_offsets_ptr,
history_offsets_stride,
contexts_ptr,
context_stride,
local_positions_ptr,
prior_contexts_ptr,
prior_contexts_stride_0,
prior_contexts_stride_1,
steps_ptr,
steps_stride,
enabled_ptr,
CONTEXT_WIDTH: tl.constexpr,
NUM_SPECULATIVE_STEPS: tl.constexpr,
MAX_HISTORY: tl.constexpr,
INCLUDE_PROMPT: tl.constexpr,
SKIP_PARTIAL_CONTEXT: tl.constexpr,
HAS_HISTORY_OFFSETS: tl.constexpr,
SPECULATIVE_CONTEXTS: tl.constexpr,
DRAFT_CONTEXTS: tl.constexpr,
BLOCK: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
@@ -71,12 +84,16 @@ def _repeated_context_mask_kernel(
return
sequence_start = 0 if INCLUDE_PROMPT else prompt_len
history_len = total_len - sequence_start
history_offset = 0
if HAS_HISTORY_OFFSETS:
history_offset = tl.load(history_offsets_ptr + row * history_offsets_stride)
offsets = tl.arange(0, BLOCK)
repeated = tl.full((), 0, tl.int32)
scan_start = 0
if MAX_HISTORY > 0:
scan_start = tl.maximum(history_len - MAX_HISTORY, 0)
remaining_history = tl.maximum(MAX_HISTORY - history_offset, 0)
scan_start = tl.maximum(history_len - remaining_history, 0)
# Aligned loop bounds let the per-lane offsets fold into immediates.
aligned_start = (scan_start // BLOCK) * BLOCK
for block_start in tl.range(aligned_start, history_len, BLOCK):
@@ -96,6 +113,93 @@ def _repeated_context_mask_kernel(
)
matches &= historical_token == context_token
repeated |= tl.max(matches.to(tl.int32), axis=0)
if SPECULATIVE_CONTEXTS:
local_pos = tl.load(local_positions_ptr + row)
if INCLUDE_PROMPT:
partial_context = tl.full((), 0, tl.int32)
for context_offset in range(CONTEXT_WIDTH):
context_token = tl.load(
contexts_ptr + row * context_stride + context_offset
)
partial_context |= context_token < 0
repeated |= partial_context
for offset in range(1, NUM_SPECULATIVE_STEPS + 1):
prior_row = row - offset
in_history = (prior_row >= 0) & (local_pos >= offset)
if MAX_HISTORY > 0:
in_history &= offset <= MAX_HISTORY
prior_req_idx = tl.load(
req_indices_ptr + tl.maximum(prior_row, 0),
mask=in_history,
other=-1,
)
prior_local_pos = tl.load(
local_positions_ptr + tl.maximum(prior_row, 0),
mask=in_history,
other=-1,
)
matches = (
in_history
& (req_idx == prior_req_idx)
& (local_pos == prior_local_pos + offset)
)
for context_offset in range(CONTEXT_WIDTH):
context_token = tl.load(
contexts_ptr + row * context_stride + context_offset
)
prior_token = tl.load(
contexts_ptr
+ tl.maximum(prior_row, 0) * context_stride
+ context_offset,
mask=in_history,
other=-2,
)
matches &= context_token == prior_token
repeated |= matches
if DRAFT_CONTEXTS:
step = tl.load(steps_ptr + row * steps_stride).to(tl.int64)
partial_context = tl.full((), 0, tl.int32)
for context_offset in range(CONTEXT_WIDTH):
context_token = tl.load(
contexts_ptr + row * context_stride + context_offset
)
partial_context |= context_token < 0
if INCLUDE_PROMPT:
repeated |= partial_context
for prior_step in range(NUM_SPECULATIVE_STEPS):
in_history = prior_step < step
if MAX_HISTORY > 0:
in_history &= prior_step >= step - MAX_HISTORY
matches = in_history
for context_offset in range(CONTEXT_WIDTH):
context_token = tl.load(
contexts_ptr + row * context_stride + context_offset
)
prior_token = tl.load(
prior_contexts_ptr
+ row * prior_contexts_stride_0
+ prior_step * prior_contexts_stride_1
+ context_offset
)
matches &= context_token == prior_token
repeated |= matches
for context_offset in range(CONTEXT_WIDTH):
context_token = tl.load(
contexts_ptr + row * context_stride + context_offset
)
tl.store(
prior_contexts_ptr
+ row * prior_contexts_stride_0
+ step * prior_contexts_stride_1
+ context_offset,
context_token,
)
enabled = tl.load(enabled_ptr + row)
repeated = enabled & (repeated == 0)
tl.store(output_ptr + row, repeated)
@@ -108,6 +212,7 @@ def _repeated_context_mask_cpu(
max_history: int | None = None,
include_prompt: bool = False,
skip_partial_context: bool = False,
history_offsets: torch.Tensor | None = None,
) -> torch.Tensor:
"""Reference implementation; the parity tests check the Triton kernel against it."""
repeated = torch.zeros(len(req_indices), dtype=torch.bool)
@@ -124,8 +229,11 @@ def _repeated_context_mask_cpu(
history_tokens = all_token_ids[req_idx, sequence_start:total_len].tolist()
prefix = [-1] * contexts.shape[-1]
current_context = tuple(contexts[row].tolist())
history_offset = 0 if history_offsets is None else int(history_offsets[row])
history_start = (
max(0, len(history_tokens) - max_history) if max_history is not None else 0
max(0, len(history_tokens) - max(0, max_history - history_offset))
if max_history is not None
else 0
)
for history_pos, token_id in enumerate(history_tokens):
if history_pos >= history_start and (
@@ -146,6 +254,9 @@ def repeated_context_mask(
max_history: int | None = None,
include_prompt: bool = False,
skip_partial_context: bool = False,
history_offsets: torch.Tensor | None = None,
local_positions: torch.Tensor | None = None,
num_speculative_steps: int = 0,
) -> torch.Tensor:
"""Return, per row, whether the row's context already occurred in its history.
@@ -163,12 +274,23 @@ def repeated_context_mask(
include_prompt: Search the prompt as well as the generated tokens.
skip_partial_context: Mark contexts containing start padding so they use
ordinary sampling.
history_offsets: Number of newer, non-committed positions preceding each
context. These positions count toward `max_history`. Must be 1-D
over rows; a stride-0 broadcast row is fine.
local_positions: Position within each request's speculative block. When
provided, compare each context with earlier contexts in that block.
num_speculative_steps: Maximum number of draft tokens in the block.
"""
if max_history is not None and max_history < 1:
raise ValueError("max_history must be positive or None")
if (local_positions is None) != (num_speculative_steps == 0):
raise ValueError(
"local_positions and positive num_speculative_steps must be "
"provided together"
)
if all_token_ids.device.type == "cpu":
return _repeated_context_mask_cpu(
repeated = _repeated_context_mask_cpu(
all_token_ids,
req_indices,
prompt_lens,
@@ -177,10 +299,42 @@ def repeated_context_mask(
max_history,
include_prompt,
skip_partial_context,
history_offsets,
)
if local_positions is not None:
max_offset = num_speculative_steps + 1
if max_history is not None:
max_offset = min(max_offset, max_history + 1)
for offset in range(1, max_offset):
prior_contexts = torch.cat(
(contexts[:offset], contexts[:-offset]), dim=0
)
prior_requests = torch.cat(
(req_indices[:offset], req_indices[:-offset]), dim=0
)
prior_local_pos = torch.cat(
(local_positions[:offset], local_positions[:-offset]), dim=0
)
repeated |= (
(req_indices >= 0)
& (local_positions >= offset)
& (req_indices == prior_requests)
& (local_positions == prior_local_pos + offset)
& (contexts == prior_contexts).all(dim=-1)
)
if include_prompt:
repeated |= (contexts < 0).any(dim=-1)
return repeated
if contexts.stride(-1) != 1:
contexts = contexts.contiguous()
# Only history_offsets passes its row stride to the kernel.
req_indices = req_indices.contiguous()
if local_positions is not None:
local_positions = local_positions.contiguous()
# `prompt_lens` and `total_lens` are indexed flat by request slot, and
# `all_token_ids` takes a row stride but is read flat within the row. Those
# three are contiguous by contract; every caller owns them outright.
repeated = torch.empty(len(req_indices), dtype=torch.bool, device=contexts.device)
_repeated_context_mask_kernel[(len(req_indices),)](
repeated,
@@ -189,17 +343,104 @@ def repeated_context_mask(
req_indices,
prompt_lens,
total_lens,
history_offsets,
0 if history_offsets is None else history_offsets.stride(0),
contexts,
contexts.stride(0),
local_positions,
None,
0,
0,
None,
0,
None,
CONTEXT_WIDTH=contexts.shape[-1],
NUM_SPECULATIVE_STEPS=num_speculative_steps,
MAX_HISTORY=0 if max_history is None else max_history,
INCLUDE_PROMPT=include_prompt,
SKIP_PARTIAL_CONTEXT=skip_partial_context,
HAS_HISTORY_OFFSETS=history_offsets is not None,
SPECULATIVE_CONTEXTS=local_positions is not None,
DRAFT_CONTEXTS=False,
BLOCK=512,
)
return repeated
def draft_watermarking_mask(
all_token_ids: torch.Tensor,
req_indices: torch.Tensor,
prompt_lens: torch.Tensor,
total_lens: torch.Tensor,
prior_contexts: torch.Tensor,
contexts: torch.Tensor,
steps: torch.Tensor,
enabled: torch.Tensor,
max_history: int | None,
include_prompt: bool,
) -> torch.Tensor:
if contexts.device.type == "cpu":
repeated = repeated_context_mask(
all_token_ids,
req_indices,
prompt_lens,
total_lens,
contexts,
max_history,
include_prompt=include_prompt,
history_offsets=steps,
)
prior_steps = torch.arange(prior_contexts.shape[1]).unsqueeze(0)
in_history = prior_steps < steps.unsqueeze(1)
if max_history is not None:
in_history &= prior_steps >= steps.unsqueeze(1) - max_history
repeated |= (
(prior_contexts[: len(contexts)] == contexts.unsqueeze(1)).all(dim=-1)
& in_history
).any(dim=-1)
if include_prompt:
repeated |= (contexts < 0).any(dim=-1)
row_indices = torch.arange(len(contexts))
prior_contexts.index_put_((row_indices, steps), contexts)
return enabled & ~repeated
if contexts.stride(-1) != 1:
contexts = contexts.contiguous()
# Only `steps` passes its row stride to the kernel.
req_indices = req_indices.contiguous()
enabled = enabled.contiguous()
active = torch.empty(len(contexts), dtype=torch.bool, device=contexts.device)
_repeated_context_mask_kernel[(len(contexts),)](
active,
all_token_ids,
all_token_ids.stride(0),
req_indices,
prompt_lens,
total_lens,
steps,
steps.stride(0),
contexts,
contexts.stride(0),
None,
prior_contexts,
prior_contexts.stride(0),
prior_contexts.stride(1),
steps,
steps.stride(0),
enabled,
NUM_SPECULATIVE_STEPS=prior_contexts.shape[1],
CONTEXT_WIDTH=contexts.shape[1],
MAX_HISTORY=0 if max_history is None else max_history,
INCLUDE_PROMPT=include_prompt,
SKIP_PARTIAL_CONTEXT=False,
HAS_HISTORY_OFFSETS=True,
SPECULATIVE_CONTEXTS=False,
DRAFT_CONTEXTS=True,
BLOCK=512,
)
return active
@triton.jit
def _mulhilo32(multiplier: tl.constexpr, value):
high = tl_math.umulhi(multiplier, value)
@@ -351,28 +592,58 @@ def _philox_gumbel_kernel(
seeds_ptr,
pos_ptr,
temp_ptr,
logits_cache_ptr,
logits_cache_stride_0,
logits_cache_stride_1,
logits_cache_col_ptr,
logits_cache_source_ptr,
logits_cache_source_stride,
key_0_value,
key_1_value,
vocab_size,
CONTEXT_WIDTH: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
USE_FP64: tl.constexpr,
IS_DRAFTING: tl.constexpr,
PER_TOKEN_COL: tl.constexpr,
):
row = tl.program_id(0).to(tl.int64)
block_index = tl.program_id(1)
groups = block_index * (BLOCK_SIZE // 4) + tl.arange(0, BLOCK_SIZE // 4)
candidate = block_index * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = candidate < vocab_size
if skip_mask_ptr is not None:
req_state_idx = row
valid_req = True
if expanded_idx_mapping_ptr is not None:
req_state_idx = tl.load(expanded_idx_mapping_ptr + row).to(tl.int64)
valid_req = req_state_idx >= 0
if logits_cache_ptr is not None:
if PER_TOKEN_COL:
col = tl.load(logits_cache_col_ptr + row)
else:
col = tl.load(logits_cache_col_ptr)
cached_logits = tl.load(
logits_cache_source_ptr + row * logits_cache_source_stride + candidate,
mask=mask,
)
tl.store(
logits_cache_ptr
+ req_state_idx * logits_cache_stride_0
+ col * logits_cache_stride_1
+ candidate,
cached_logits,
mask=mask & valid_req,
)
if skip_mask_ptr is not None: # noqa: SIM102
if tl.load(skip_mask_ptr + row):
temp = tl.load(temp_ptr + req_state_idx, mask=valid_req, other=0.0).to(
tl.float32
)
seed = tl.load(seeds_ptr + req_state_idx, mask=valid_req, other=0)
pos = tl.load(pos_ptr + row)
candidate = block_index * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = candidate < vocab_size
logits_row = logits_ptr + row * logits_stride
logits = tl.load(logits_row + candidate, mask=mask, other=float("-inf")).to(
tl.float32
@@ -384,7 +655,7 @@ def _philox_gumbel_kernel(
seed,
pos,
temp,
IS_DRAFTING=False,
IS_DRAFTING=IS_DRAFTING,
USE_FP64=USE_FP64,
APPLY_TEMPERATURE=False,
)
@@ -443,12 +714,37 @@ def philox_gumbel_sample(
seeds: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
use_fp64: bool = False,
is_drafting: bool = False,
logits_cache: torch.Tensor | None = None,
logits_cache_col: torch.Tensor | None = None,
logits_cache_source: torch.Tensor | None = None,
) -> torch.Tensor:
sampling_state = (expanded_idx_mapping, temperatures, seeds, positions)
if skip_mask is None and any(value is not None for value in sampling_state):
raise ValueError("sampling state requires skip_mask")
if skip_mask is not None and any(value is None for value in sampling_state):
raise ValueError("skip_mask requires complete sampling state")
if logits_cache is not None:
if logits_cache_col is None or logits_cache_source is None:
raise ValueError("logits cache requires its column and source logits")
if expanded_idx_mapping is None:
raise ValueError("logits cache requires expanded_idx_mapping")
assert logits_cache_source.shape == logits.shape, (
"logits cache source must match sampled logits shape"
)
assert logits_cache_source.device == logits.device, (
"logits cache source must be on the sampled logits device"
)
assert logits_cache_source.dtype == logits_cache.dtype, (
"logits cache source and destination must have the same dtype"
)
assert logits_cache.size(-1) >= logits.shape[-1], (
f"draft logits cache vocab dim ({logits_cache.size(-1)}) is narrower "
f"than the sampled logits ({logits.shape[-1]}). Cached logits would be "
"truncated."
)
elif logits_cache_col is not None or logits_cache_source is not None:
raise ValueError("logits cache column and source require logits_cache")
if logits.stride(-1) != 1:
logits = logits.contiguous()
@@ -460,6 +756,10 @@ def philox_gumbel_sample(
expanded_idx_mapping = expanded_idx_mapping.contiguous()
if positions is not None:
positions = positions.contiguous()
if logits_cache_col is not None:
logits_cache_col = logits_cache_col.contiguous()
if logits_cache_source is not None and logits_cache_source.stride(-1) != 1:
logits_cache_source = logits_cache_source.contiguous()
num_tokens, vocab_size = logits.shape
block_size = 1024
num_blocks = triton.cdiv(vocab_size, block_size)
@@ -483,12 +783,20 @@ def philox_gumbel_sample(
seeds,
positions,
temperatures,
logits_cache,
logits_cache.stride(0) if logits_cache is not None else 0,
logits_cache.stride(1) if logits_cache is not None else 0,
logits_cache_col,
logits_cache_source,
logits_cache_source.stride(0) if logits_cache_source is not None else 0,
key & _UINT32_MASK_VALUE,
key >> 32,
vocab_size,
CONTEXT_WIDTH=contexts.shape[-1],
BLOCK_SIZE=block_size,
USE_FP64=use_fp64,
IS_DRAFTING=is_drafting,
PER_TOKEN_COL=logits_cache_col is not None and logits_cache_col.dim() > 0,
)
max_block_index = local_max.argmax(dim=-1, keepdim=True)
return local_argmax.gather(dim=-1, index=max_block_index).view(-1)
@@ -135,7 +135,12 @@ class DSparkSpeculator(DFlashSpeculator):
# sample_pos is the predicted token's position P. Sampling keys a draw
# by the position before the sampled token, P-1.
sampled = gumbel_sample(
sampler = (
gumbel_sample
if self.draft_watermarker is None
else self.draft_watermarker.sample
)
return sampler(
logits,
idx_map,
self.temperature,
@@ -147,11 +152,6 @@ class DSparkSpeculator(DFlashSpeculator):
logits_cache_col=self._step_cols[step],
use_fp64=self.use_fp64_gumbel,
)
if self.draft_watermarker is not None:
sampled = self.draft_watermarker.sample(
logits, sampled, idx_map, self.temperature
)
return sampled
def _sample_sequential(self, num_reqs: int, head_hidden: torch.Tensor) -> None:
if self._draft_topk is not None:
@@ -13,10 +13,14 @@ from vllm.v1.worker.gpu.spec_decode.utils import get_pp_safe_draft_load_config
def _should_share(eagle: nn.Module, flag: str, draft, target) -> bool:
"""Share when the draft has no own copy, or its copy matches the target."""
if not getattr(eagle, flag, False) or draft is None:
"""Share unless the draft declares its own copy that differs from the target.
A draft that declares its own copy but has no top-level one (e.g. MTP
heads stored per layer) keeps it.
"""
if not getattr(eagle, flag, False):
return True
if target is None:
if draft is None or target is None:
return False
# torch.equal on GPU allocates a bool mask the size of the input.
# Use the faster GPU path when there is plenty of headroom;
@@ -253,6 +253,17 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
)
return self.draft_tokens[:num_reqs]
# Each MTP module may carry its own LM head, selected by spec_step_idx.
def compute_draft_logits(
self, hidden_states: torch.Tensor, spec_step_idx: int
) -> torch.Tensor:
return self.model.compute_logits(hidden_states, spec_step_idx=spec_step_idx)
def get_draft_top_tokens(
self, hidden_states: torch.Tensor, spec_step_idx: int
) -> torch.Tensor:
return self.model.get_top_tokens(hidden_states, spec_step_idx=spec_step_idx)
@torch.inference_mode()
def _run_model(
self,
@@ -427,6 +438,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
self.seeds,
self.current_draft_step,
self.draft_logits,
spec_step_idx=step,
)
self.draft_tokens[:num_reqs, step] = draft_tokens
@@ -18,7 +18,7 @@ from vllm.v1.worker.gpu.input_batch import (
)
from vllm.v1.worker.gpu.metrics.logits import get_num_nans
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
from vllm.v1.worker.gpu.sample.output import SamplerOutput
from vllm.v1.worker.gpu.sample.output import SamplerOutput, SamplingMaskTensors
from vllm.v1.worker.gpu.sample.sampler import Sampler
from vllm.v1.worker.gpu.sample.states import NO_LOGPROBS
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import (
@@ -226,11 +226,18 @@ class RejectionSampler:
if self.watermark_key is None:
return {}
assert isinstance(self.sampler, GPUWatermarkSampler)
contexts = self.sampler._get_contexts(
expanded_idx_mapping, expanded_local_pos, draft_sampled
)
watermarking_skip_mask = None
if self.sampler.deduplicate_contexts != "none":
watermarking_skip_mask = self.sampler._get_repeated_contexts(
expanded_idx_mapping, contexts, expanded_local_pos
)
return {
"contexts": self.sampler._get_contexts(
expanded_idx_mapping, expanded_local_pos, draft_sampled
),
"contexts": contexts,
"watermarking": self.sampler.watermarking.gpu,
"watermarking_skip_mask": watermarking_skip_mask,
"watermark_key": self.watermark_key,
}
@@ -246,6 +253,7 @@ class RejectionSampler:
expanded_idx_mapping: torch.Tensor,
expanded_local_pos: torch.Tensor,
seq_lens_upper_bound_np: np.ndarray,
verify_draft_sampled: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
processed_logits = self.sampler.apply_sampling_params(
logits,
@@ -260,7 +268,7 @@ class RejectionSampler:
sampled, num_sampled = rejection_sample(
processed_logits,
draft_logits,
draft_sampled,
verify_draft_sampled,
cu_num_logits,
pos,
idx_mapping,
@@ -287,7 +295,15 @@ class RejectionSampler:
pos: torch.Tensor,
max_chunk_logits: int,
max_num_logprobs: int,
) -> tuple[torch.Tensor, torch.Tensor, LogprobsTensors | None]:
verify_draft_sampled: torch.Tensor | None = None,
) -> tuple[
torch.Tensor,
torch.Tensor,
LogprobsTensors | None,
SamplingMaskTensors | None,
]:
if verify_draft_sampled is None:
verify_draft_sampled = draft_sampled
cu_num_logits_np = input_batch.cu_num_logits_np
use_processed_logits = self.sampler.logprobs_mode in PROCESSED_LOGPROBS_MODES
num_reqs = input_batch.num_reqs
@@ -305,6 +321,14 @@ class RejectionSampler:
sampled_chunks: list[torch.Tensor] = []
num_sampled_chunks: list[torch.Tensor] = []
logprobs_chunks: list[LogprobsTensors] = []
sampling_mask_chunks: list[SamplingMaskTensors] = []
max_num_kept = None
if self.sampler.return_sampling_mask:
max_num_kept = int(
np.max(
self.sampler.sampling_states.top_k.np[input_batch.idx_mapping_np]
)
)
for start, end in request_chunks:
lo = int(cu_num_logits_np[start])
@@ -323,6 +347,7 @@ class RejectionSampler:
input_batch.expanded_idx_mapping[lo:hi],
input_batch.expanded_local_pos[lo:hi],
input_batch.seq_lens_cpu_upper_bound.numpy()[start:end],
verify_draft_sampled[lo:hi],
)
chunk_logprobs = self._get_logprobs_tensors(
sampled,
@@ -334,13 +359,31 @@ class RejectionSampler:
)
if chunk_logprobs is not None:
logprobs_chunks.append(chunk_logprobs)
if max_num_kept is not None:
sampling_mask_chunks.append(
SamplingMaskTensors.from_logits(
processed_logits,
chunk_cu_num_logits,
num_sampled,
max_num_kept,
self.num_speculative_steps + 1,
)
)
del processed_logits
sampled_chunks.append(sampled)
num_sampled_chunks.append(num_sampled)
if len(sampled_chunks) == 1:
logprobs_tensors = logprobs_chunks[0] if logprobs_chunks else None
return sampled_chunks[0], num_sampled_chunks[0], logprobs_tensors
sampling_mask_tensors = (
sampling_mask_chunks[0] if sampling_mask_chunks else None
)
return (
sampled_chunks[0],
num_sampled_chunks[0],
logprobs_tensors,
sampling_mask_tensors,
)
logprobs_tensors = None
if logprobs_chunks:
@@ -354,13 +397,19 @@ class RejectionSampler:
sampled = torch.cat(sampled_chunks)
num_sampled = torch.cat(num_sampled_chunks)
return sampled, num_sampled, logprobs_tensors
sampling_mask_tensors = (
SamplingMaskTensors.cat(sampling_mask_chunks)
if sampling_mask_chunks
else None
)
return sampled, num_sampled, logprobs_tensors, sampling_mask_tensors
def __call__(
self,
logits: torch.Tensor,
input_batch: InputBatch,
draft_logits: torch.Tensor | None = None,
invalid_drafts: torch.Tensor | None = None,
) -> SamplerOutput:
# NOTE(woosuk): We intentionally compute num_nans before sampling to make clear
# that num_nans is computed before applying penalties and temperature.
@@ -375,11 +424,24 @@ class RejectionSampler:
self.sampler.req_states.prefill_len.gpu,
)
# Marking a draft invalid (`is_valid_draft = draft_sampled >= 0`) pins the
# accepted length before it reaches a permissive bitmask row. Only
# verification sees the copy: `apply_sampling_params` and watermarking
# keep the real draft ids.
verify_draft_sampled = draft_sampled
if invalid_drafts is not None:
verify_draft_sampled = draft_sampled.masked_fill(invalid_drafts, -1)
max_num_logprobs = self.sampler.sampling_states.max_num_logprobs(
input_batch.idx_mapping_np
)
chunk_logit_limit = get_max_chunk_logits(logits.shape[1])
sampled, num_sampled, logprobs_tensors = self._verify_in_chunks(
(
sampled,
num_sampled,
logprobs_tensors,
sampling_mask_tensors,
) = self._verify_in_chunks(
logits,
input_batch,
draft_logits,
@@ -387,6 +449,7 @@ class RejectionSampler:
pos,
chunk_logit_limit,
max_num_logprobs,
verify_draft_sampled,
)
num_sampled, num_rejected = get_num_sampled_and_rejected(
@@ -403,4 +466,5 @@ class RejectionSampler:
num_nans=num_nans,
num_sampled=num_sampled,
num_rejected=num_rejected,
sampling_mask_tensors=sampling_mask_tensors,
)
@@ -564,7 +564,6 @@ def _rejection_kernel(
# stores the target argmax upon first rejection, so it rejects the
# placeholder via `accepted` instead.
verifying &= is_valid_draft
if verifying:
pos = tl.load(pos_ptr + logit_idx)
u = tl_rand32(seed, pos, includes_zero=False)
@@ -719,6 +718,8 @@ def _seeded_resample_argmax(
0, # logits_cache_stride_0
0, # logits_cache_stride_1
None, # logits_cache_col_ptr
None, # logits_cache_source_ptr
0, # logits_cache_source_stride
vocab_size,
IS_DRAFTING=False,
APPLY_TEMPERATURE=False,
@@ -766,6 +767,7 @@ def _resample_kernel(
contexts_stride,
# [max_num_reqs], uint8 view of a bool tensor
watermarking_ptr,
watermarking_skip_mask_ptr,
watermark_key_0,
watermark_key_1,
vocab_size,
@@ -775,6 +777,7 @@ def _resample_kernel(
USE_BLOCK_VERIFICATION: tl.constexpr,
CONTEXT_WIDTH: tl.constexpr,
WATERMARK: tl.constexpr,
DEDUPLICATE_CONTEXTS: tl.constexpr,
):
req_idx = tl.program_id(0)
resample_idx = tl.load(rejected_step_ptr + req_idx)
@@ -807,6 +810,25 @@ def _resample_kernel(
).to(tl.float32)
# Compute the residual logits to resample the rejected token from.
is_watermarked = False
if WATERMARK:
is_watermarked = (
tl.load(
watermarking_ptr + req_state_idx,
mask=req_state_idx >= 0,
other=0,
)
!= 0
)
skip_watermarking = False
if DEDUPLICATE_CONTEXTS:
skip_watermarking = (
(tl.load(watermarking_skip_mask_ptr + resample_token_idx) != 0)
& is_watermarked
& (temp != 0.0)
)
if is_bonus or not is_valid_rejected_draft:
# Bonus token (no rejections) or -1 placeholder token. In either case,
# directly use the target logits.
@@ -868,15 +890,7 @@ def _resample_kernel(
# Resample the rejected/bonus token.
if WATERMARK:
# Padded and greedy rows retain the stock draw.
is_watermarked = (
tl.load(
watermarking_ptr + req_state_idx,
mask=req_state_idx >= 0,
other=0,
)
!= 0
)
if is_watermarked & (temp != 0.0):
if is_watermarked & (temp != 0.0) & ~skip_watermarking:
watermark_value, idx = philox_gumbel_block_argmax(
residual_logits,
mask,
@@ -1023,6 +1037,7 @@ def rejection_sample(
use_block_verification: bool = False,
contexts: torch.Tensor | None = None,
watermarking: torch.Tensor | None = None,
watermarking_skip_mask: torch.Tensor | None = None,
watermark_key: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert target_logits.ndim == 2 and target_logits.stride(-1) == 1
@@ -1036,9 +1051,13 @@ def rejection_sample(
assert watermark == (watermarking is not None) == (watermark_key is not None), (
"contexts, watermarking and watermark_key must be set together."
)
assert watermarking_skip_mask is None or watermark, (
"watermarking_skip_mask requires watermarking."
)
contexts_stride = 0
context_width = 1
watermarking_bytes: torch.Tensor | None = None
watermarking_skip_mask_bytes: torch.Tensor | None = None
watermark_key_0 = 0
watermark_key_1 = 0
if contexts is not None:
@@ -1053,6 +1072,12 @@ def rejection_sample(
contexts_stride = contexts.stride(0)
context_width = contexts.shape[-1]
watermarking_bytes = watermarking.view(torch.uint8)
if watermarking_skip_mask is not None:
assert watermarking_skip_mask.shape == (num_logits,)
assert watermarking_skip_mask.dtype == torch.bool
if not watermarking_skip_mask.is_contiguous():
watermarking_skip_mask = watermarking_skip_mask.contiguous()
watermarking_skip_mask_bytes = watermarking_skip_mask.view(torch.uint8)
watermark_key_0 = watermark_key & 0xFFFFFFFF
watermark_key_1 = watermark_key >> 32
draft_logits_stride_0 = 0
@@ -1269,6 +1294,7 @@ def rejection_sample(
contexts,
contexts_stride,
watermarking_bytes,
watermarking_skip_mask_bytes,
watermark_key_0,
watermark_key_1,
vocab_size,
@@ -1278,6 +1304,7 @@ def rejection_sample(
USE_BLOCK_VERIFICATION=use_block_verification,
CONTEXT_WIDTH=context_width,
WATERMARK=watermark,
DEDUPLICATE_CONTEXTS=watermarking_skip_mask is not None,
)
# Insert the resampled tokens into the output sampled.
+41 -17
View File
@@ -38,6 +38,7 @@ from vllm.v1.worker.gpu.spec_decode.acceptance_estimator import (
from vllm.v1.worker.utils import AttentionGroup
if TYPE_CHECKING:
from vllm.v1.watermarking.gpu_sampler import GPUWatermarkSampler
from vllm.v1.worker.gpu.pcp_manager import PCPManager
logger = init_logger(__name__)
@@ -198,6 +199,9 @@ class DraftModelSpeculator(BaseSpeculator):
self.max_num_reqs,
device,
watermark_config.allow_target_only_watermarking,
self.num_speculative_steps,
watermark_config.deduplicate_contexts,
watermark_config.deduplicate_contexts_max_history,
)
self.supports_mm_inputs = False
@@ -220,13 +224,13 @@ class DraftModelSpeculator(BaseSpeculator):
self.model = self.load_draft_model(target_model, target_attn_layer_names)
self._validate_local_argmax_reduction()
all_attn_layers = set[str](
get_layers_from_vllm_config(
self.vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
).keys()
all_attn_layers = get_layers_from_vllm_config(
self.vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
)
self.draft_attn_layer_names = all_attn_layers - target_attn_layer_names
self.draft_attn_layer_names = set(all_attn_layers) - target_attn_layer_names
for layer_name in self.draft_attn_layer_names:
all_attn_layers[layer_name].is_draft_layer = True
target_supports_mm = self.vllm_config.model_config.supports_multimodal_inputs
draft_supports_mm = supports_multimodal_embeddings(self.model)
@@ -399,6 +403,16 @@ class DraftModelSpeculator(BaseSpeculator):
"(communication: O(2*tp_size) vs O(vocab_size))."
)
def compute_draft_logits(
self, hidden_states: torch.Tensor, spec_step_idx: int
) -> torch.Tensor:
return self.model.compute_logits(hidden_states)
def get_draft_top_tokens(
self, hidden_states: torch.Tensor, spec_step_idx: int
) -> torch.Tensor:
return self.model.get_top_tokens(hidden_states)
def sample_draft(
self,
hidden_states: torch.Tensor,
@@ -408,10 +422,19 @@ class DraftModelSpeculator(BaseSpeculator):
seeds: torch.Tensor,
draft_step: torch.Tensor,
draft_logits: torch.Tensor | None,
spec_step_idx: int = 0,
) -> torch.Tensor:
if draft_logits is None and self.use_local_argmax_reduction:
return self.get_draft_top_tokens(hidden_states, spec_step_idx)
logits = self.compute_draft_logits(hidden_states, spec_step_idx)
if draft_logits is not None:
logits = self.model.compute_logits(hidden_states)
sampled = gumbel_sample(
sampler = (
gumbel_sample
if self.draft_watermarker is None
else self.draft_watermarker.sample
)
sampled = sampler(
logits,
idx_mapping,
temperature,
@@ -423,14 +446,7 @@ class DraftModelSpeculator(BaseSpeculator):
logits_cache_col=draft_step,
use_fp64=self.use_fp64_gumbel,
)
if self.draft_watermarker is not None:
sampled = self.draft_watermarker.sample(
logits, sampled, idx_mapping, temperature
)
elif self.use_local_argmax_reduction:
return self.model.get_top_tokens(hidden_states)
else:
logits = self.model.compute_logits(hidden_states)
sampled = logits.argmax(dim=-1)
self._maybe_predict_acceptance(logits, idx_mapping, draft_step)
return sampled
@@ -462,11 +478,19 @@ class DraftModelSpeculator(BaseSpeculator):
self.acceptance_estimator.step(idx_mapping, num_sampled, num_rejected)
def prepare_watermarking(
self, contexts: torch.Tensor, watermarking: torch.Tensor
self,
sampler: "GPUWatermarkSampler",
idx_mapping: torch.Tensor,
) -> None:
if self.draft_watermarker is None:
return
self.draft_watermarker.prepare(contexts, watermarking)
self.draft_watermarker.prepare(
sampler._get_contexts(idx_mapping),
sampler.watermarking.gpu[idx_mapping],
sampler.req_states.all_token_ids.gpu,
sampler.req_states.prompt_len.gpu,
sampler.req_states.total_len.gpu,
)
def _copy_request_inputs(
self,
+37
View File
@@ -35,6 +35,43 @@ def _build_grammar_mapping(
return mapping
def grammar_invalid_drafts(
input_batch: InputBatch,
grammar_req_ids: list[str],
num_acceptable_drafts: list[int] | None,
) -> torch.Tensor | None:
"""Mask over logit rows whose draft was verified against a permissive row.
Draft i sits at local position i + 1, and drafts from `num_acceptable_drafts`
on met `_full_mask`. Local positions come from the device `cu_num_logits`, so
this stays right when adaptive verification trims drafts on device.
Returns None when there is nothing to invalidate.
"""
if not grammar_req_ids or input_batch.num_draft_tokens == 0:
return None
req_id_to_idx = {req_id: i for i, req_id in enumerate(input_batch.req_ids)}
limit = np.full(input_batch.num_reqs, np.iinfo(np.int32).max, dtype=np.int32)
for i, req_id in enumerate(grammar_req_ids):
req_idx = req_id_to_idx.get(req_id)
if req_idx is not None:
# None (an older scheduler, or warmup): invalidate the whole window.
limit[req_idx] = (
num_acceptable_drafts[i] if num_acceptable_drafts is not None else 0
)
# Adaptive verification only trims drafts, so this bound holds either way.
num_drafts = input_batch.num_draft_tokens_per_req
if num_drafts is not None and (limit >= num_drafts).all():
return None
local_pos = input_batch.expanded_local_pos
cu_num_logits = input_batch.cu_num_logits
row_limit = torch.repeat_interleave(
async_tensor_h2d(limit, device=local_pos.device),
cu_num_logits[1:] - cu_num_logits[:-1],
output_size=local_pos.shape[0],
)
return local_pos > row_limit
class StructuredOutputsWorker:
def __init__(
self,
+1
View File
@@ -194,6 +194,7 @@ def _slice_input_batch(
if input_batch.prompt_lens is None
else input_batch.prompt_lens[req_start:req_stop]
),
max_seq_len_np=None,
fast_prefill=None,
)
+5 -34
View File
@@ -967,11 +967,6 @@ class GPUModelRunner(
self.mamba_state_idx: dict[str, int] = {}
self._mamba_bufs: mamba_utils.MambaBuffers | None = None
self._mamba_state_copy_funcs: MambaStateCopyFuncsByType | None = None
self.mamba_prev_last_scheduled_idx: CpuGpuBuffer | None = None
if self.cache_config.mamba_cache_mode == "all" and self.num_spec_tokens > 0:
self.mamba_prev_last_scheduled_idx = self._make_buffer(
self.max_num_reqs, dtype=torch.int32
)
self.layerwise_nvtx_hooks_registered = False
def update_max_model_len(self, max_model_len: int) -> None:
@@ -1608,17 +1603,6 @@ class GPUModelRunner(
assert self.num_accepted_tokens_event is not None
self.num_accepted_tokens_event.record()
if self.cache_config.mamba_cache_mode == "all":
mamba_utils.postprocess_mamba_all(
scheduler_output,
self.kv_cache_config,
self.input_batch,
self.requests,
self.mamba_state_idx,
self.num_spec_tokens,
num_reqs,
)
def _update_streaming_request(
self, req_id: str, new_req_data: NewRequestData
) -> CachedRequestState:
@@ -2127,15 +2111,6 @@ class GPUModelRunner(
self.num_accepted_tokens.np.fill(1)
self.num_accepted_tokens.gpu.fill_(1)
if self.mamba_prev_last_scheduled_idx is not None:
mamba_utils.preprocess_mamba_all_specdec(
scheduler_output,
self.input_batch,
self.mamba_state_idx,
num_reqs,
self.mamba_prev_last_scheduled_idx,
)
# Update num_computed_tokens on GPU. In async spec decode,
# CPU values are optimistic (all drafts accepted). The kernel
# corrects on GPU using the previous step's
@@ -2511,13 +2486,6 @@ class GPUModelRunner(
:num_reqs_padded
],
)
if (
isinstance(builder, Mamba2AttentionMetadataBuilder)
and self.mamba_prev_last_scheduled_idx is not None
):
extra_attn_metadata_args["prev_last_scheduled_idx"] = (
self.mamba_prev_last_scheduled_idx.gpu[:num_reqs_padded]
)
if for_cudagraph_capture:
attn_metadata_i = builder.build_for_cudagraph_capture(
@@ -5735,6 +5703,9 @@ class GPUModelRunner(
- during profile_run
- during DP rank dummy run
"""
# The worker also resolves this flag and passes randomize_inputs, but
# V1 has internal dummy runs (e.g. CUDA graph capture) that don't go
# through the worker, so keep the check here too.
dp_size = self.vllm_config.parallel_config.data_parallel_size
randomize_inputs = randomize_inputs or (
envs.VLLM_RANDOMIZE_DP_DUMMY_INPUTS and dp_size > 1
@@ -6420,7 +6391,7 @@ class GPUModelRunner(
max_task = max(output_size.items(), key=lambda x: x[1])[0]
return self._dummy_pooler_run_task(hidden_states, max_task)
def profile_run(self) -> None:
def profile_run(self, randomize_inputs: bool = False) -> None:
# Profile with multimodal encoder & encoder cache.
if self.supports_mm_inputs:
mm_config = self.model_config.multimodal_config
@@ -6481,7 +6452,7 @@ class GPUModelRunner(
# Add `is_profile` here to pre-allocate communication buffers
hidden_states, last_hidden_states = self._dummy_run(
self.max_num_tokens, is_profile=True
self.max_num_tokens, is_profile=True, randomize_inputs=randomize_inputs
)
if get_pp_group().is_last_rank:
if self.is_pooling_model:
+64 -18
View File
@@ -57,6 +57,11 @@ from vllm.distributed.weight_transfer import (
)
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
from vllm.model_executor.model_loader import get_model_loader
from vllm.model_executor.model_loader.weight_checksum import (
compute_tensor_digests,
zero_weights,
)
from vllm.model_executor.warmup.kernel_warmup import kernel_warmup
from vllm.multimodal.gpu_ipc_memory import reserve_mm_ipc_gpu_memory
from vllm.platforms import current_platform
@@ -341,6 +346,22 @@ class Worker(WorkerBase):
def checkpoint_restore(self) -> None:
checkpoint_restore_distributed_state()
def _weight_checksum_prefix(self) -> str:
# data_parallel_rank is 0 in dense workers; only the index is unique.
dp = self.parallel_config.data_parallel_index
pp = get_pp_group().rank_in_group
pcp = get_pcp_group().rank_in_group
tp = get_tp_group().rank_in_group
return f"dp{dp}:pp{pp}:pcp{pcp}:tp{tp}:"
def compute_weight_checksums(self) -> dict[str, str]:
prefix = self._weight_checksum_prefix()
digests = compute_tensor_digests(self.model_runner.get_model())
return {prefix + name: digest for name, digest in digests.items()}
def reset_weights(self) -> None:
zero_weights(self.model_runner.get_model())
def _maybe_get_memory_pool_context(self, tag: str) -> AbstractContextManager:
if (
current_platform.is_cuda_alike()
@@ -487,7 +508,13 @@ class Worker(WorkerBase):
# take current memory snapshot
self.init_snapshot = init_snapshot = MemorySnapshot(device=self.device)
self.requested_memory = request_memory(init_snapshot, self.cache_config)
# Weights from external model loader process
external_weight_memory = get_model_loader(
self.load_config
).get_external_weight_memory(self.vllm_config)
self.requested_memory = request_memory(
init_snapshot, self.cache_config, external_weight_memory
)
logger.debug("worker init memory snapshot: %r", self.init_snapshot)
logger.debug(
"worker requested memory: %sGiB", format_gib(self.requested_memory)
@@ -495,15 +522,26 @@ class Worker(WorkerBase):
else:
raise RuntimeError(f"Unsupported device type: {self.device_config.device}")
self._init_workspace_and_model_runner()
def _init_workspace_and_model_runner(self) -> None:
"""Set up the workspace manager, build the model runner, report usage."""
# DSpark target and draft CUDA graphs retain workspace views concurrently.
num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1
init_workspace_manager(
self.device,
num_ubatches,
_num_workspace_lanes(self.vllm_config, self.use_v2_model_runner),
# Scratch holds no state across steps: discard it on sleep.
alloc_context=lambda: self._maybe_get_memory_pool_context("workspace"),
)
self.model_runner: GPUModelRunner = self._make_model_runner()
if self.rank == 0:
# If usage stat is enabled, collect relevant info.
report_usage_stats(self.vllm_config)
# Construct the model runner
def _make_model_runner(self) -> "GPUModelRunner":
"""Construct the platform's model runner; subclasses override this."""
if self.use_v2_model_runner:
if self.vllm_config.is_mm_encoder_only:
from vllm.v1.worker.mm_encoder_model_runner import (
@@ -515,19 +553,10 @@ class Worker(WorkerBase):
)
# HACK(woosuk): This is a temporary fix to avoid type errors.
self.model_runner: GPUModelRunner = GPUModelRunnerV2( # type: ignore
self.vllm_config, self.device
)
else:
from vllm.v1.worker.gpu_model_runner import (
GPUModelRunner as GPUModelRunnerV1,
)
return GPUModelRunnerV2(self.vllm_config, self.device) # type: ignore
from vllm.v1.worker.gpu_model_runner import GPUModelRunner as GPUModelRunnerV1
self.model_runner = GPUModelRunnerV1(self.vllm_config, self.device)
if self.rank == 0:
# If usage stat is enabled, collect relevant info.
report_usage_stats(self.vllm_config)
return GPUModelRunnerV1(self.vllm_config, self.device)
def handle_ft_command(self, ft_request):
assert self.worker_sentinel is not None
@@ -586,7 +615,7 @@ class Worker(WorkerBase):
if kv_cache_memory_bytes := self.cache_config.kv_cache_memory_bytes:
# still need a profile run which compiles the model for
# max_num_batched_tokens
self.model_runner.profile_run()
self.model_runner.profile_run(randomize_inputs=self.randomize_dummy_inputs)
msg = (
f"Initial free memory {format_gib(self.init_snapshot.free_memory)} "
@@ -623,7 +652,7 @@ class Worker(WorkerBase):
# memory_profiling measures, restoring the original limit.
self._scoped_allocator_max_split(max_split_size_mb=20),
):
self.model_runner.profile_run()
self.model_runner.profile_run(randomize_inputs=self.randomize_dummy_inputs)
# Profile CUDA graph memory if graphs will be captured.
# ROCm is included: #44825 moved the profiler to
@@ -858,7 +887,12 @@ class Worker(WorkerBase):
# We skip EPLB here since we don't want to record dummy metrics
for size in sorted(warmup_sizes, reverse=True):
logger.info("Compile and warming up model for size %d", size)
self.model_runner._dummy_run(size, skip_eplb=True, remove_lora=False)
self.model_runner._dummy_run(
size,
skip_eplb=True,
remove_lora=False,
randomize_inputs=self.randomize_dummy_inputs,
)
self.model_runner.maybe_remove_all_loras(self.model_runner.lora_config)
# Warmup and tune the kernels used during model execution before
@@ -1360,9 +1394,21 @@ class Worker(WorkerBase):
# Recreate it so the next profile_prefix is honored.
self.profiler = None
@property
def randomize_dummy_inputs(self) -> bool:
# Not cached: elastic EP rewrites parallel_config in place on reconfigure.
return (
envs.VLLM_RANDOMIZE_DP_DUMMY_INPUTS
and self.parallel_config.data_parallel_size > 1
)
def execute_dummy_batch(self) -> None:
num_tokens = getattr(self.model_runner, "uniform_decode_query_len", 1)
self.model_runner._dummy_run(num_tokens, uniform_decode=True)
self.model_runner._dummy_run(
num_tokens,
uniform_decode=True,
randomize_inputs=self.randomize_dummy_inputs,
)
def add_lora(self, lora_request: LoRARequest) -> bool:
return self.model_runner.add_lora(lora_request)
-47
View File
@@ -1535,53 +1535,6 @@ def preprocess_mamba(
do_mamba_copy_block(copy_bufs)
def postprocess_mamba_all(
scheduler_output: SchedulerOutput,
kv_cache_config: KVCacheConfig,
input_batch: InputBatch,
requests: dict[str, CachedRequestState],
mamba_state_idx: dict[str, int],
num_spec_tokens: int,
num_reqs: int,
):
"""All-mode postprocess (only meaningful with num_spec_tokens > 0):
record per-request the block index of the last token scheduled this
step, so the next step can anchor its in-place writes when accepted
drafts leave the sequence at a non-block-aligned position.
"""
if num_spec_tokens <= 0:
return
mamba_groups = get_mamba_groups(kv_cache_config)
block_sizes = {mamba_spec.block_size for mamba_spec in mamba_groups}
assert len(block_sizes) == 1, "all mamba groups must share block_size"
block_size = next(iter(block_sizes))
full_decode_len = 1 + num_spec_tokens
scheduled = scheduler_output.num_scheduled_tokens
for req_id in input_batch.req_ids[:num_reqs]:
num_query = scheduled.get(req_id, 0)
if num_query == full_decode_len:
req = requests[req_id]
seq_len = req.num_computed_tokens + num_query
mamba_state_idx[req_id] = max(0, (seq_len - 1) // block_size)
else:
mamba_state_idx.pop(req_id, None)
def preprocess_mamba_all_specdec(
scheduler_output: SchedulerOutput,
input_batch: InputBatch,
mamba_state_idx: dict[str, int],
num_reqs: int,
prev_last_scheduled_idx_buf: CpuGpuBuffer,
) -> None:
cleanup_mamba_state_idx(scheduler_output, mamba_state_idx)
np_view = prev_last_scheduled_idx_buf.np
for i, req_id in enumerate(input_batch.req_ids[:num_reqs]):
np_view[i] = mamba_state_idx.get(req_id, -1)
np_view[num_reqs:].fill(-1)
prev_last_scheduled_idx_buf.copy_to_gpu()
def postprocess_mamba_align_gpu(
*,
bufs: "MambaBuffers",
+38 -1
View File
@@ -536,7 +536,11 @@ def sanity_check_mm_encoder_outputs(
)
def request_memory(init_snapshot: MemorySnapshot, cache_config: CacheConfig) -> int:
def request_memory(
init_snapshot: MemorySnapshot,
cache_config: CacheConfig,
external_weight_memory: int = 0,
) -> int:
"""Calculate the amount of memory required by vLLM, then validate
that the current amount of free memory is sufficient for that.
"""
@@ -544,6 +548,39 @@ def request_memory(init_snapshot: MemorySnapshot, cache_config: CacheConfig) ->
init_snapshot.total_memory * cache_config.gpu_memory_utilization
)
if external_weight_memory > 0:
engine_memory = requested_memory - external_weight_memory
if engine_memory <= 0:
raise ValueError(
f"Externally held weights on device {init_snapshot.device_} "
f"({format_gib(external_weight_memory)}/"
f"{format_gib(init_snapshot.total_memory)} GiB) exceed the "
"desired GPU memory utilization "
f"({cache_config.gpu_memory_utilization}, "
f"{format_gib(requested_memory)} GiB). Increase GPU memory "
"utilization or reduce GPU memory used by other processes."
)
if init_snapshot.free_memory < engine_memory:
raise ValueError(
f"Free memory on device {init_snapshot.device_} "
f"({format_gib(init_snapshot.free_memory)}/"
f"{format_gib(init_snapshot.total_memory)} GiB) on startup "
"is less than the engine's budget after excluding "
"external process's weights "
f"({cache_config.gpu_memory_utilization}, "
f"{format_gib(engine_memory)} GiB). Decrease GPU memory "
"utilization or reduce GPU memory used by other processes."
)
logger.info_once(
"Weights are held outside this process: of the %s GiB "
"utilization budget, %s GiB is externally held and "
"%s GiB remains for the engine's own allocations.",
format_gib(requested_memory),
format_gib(external_weight_memory),
format_gib(engine_memory),
)
return engine_memory
if init_snapshot.free_memory < requested_memory:
raise ValueError(
f"Free memory on device {init_snapshot.device_} "
+11 -5
View File
@@ -4,7 +4,7 @@
import inspect
import os
from collections.abc import Callable, Hashable, Iterator
from contextlib import contextmanager
from contextlib import AbstractContextManager, contextmanager, nullcontext
from contextvars import ContextVar
from itertools import accumulate
from math import prod
@@ -58,8 +58,10 @@ class WorkspaceManager:
device: torch.device,
num_ubatches: int | None = None,
num_lanes: int = 1,
alloc_context: Callable[[], AbstractContextManager] = nullcontext,
):
self._device = device
self._alloc_context = alloc_context
# Cache num ubatches at init based on configuration (default to 1)
self._num_ubatches = num_ubatches if num_ubatches is not None else 1
if num_lanes < 1:
@@ -261,9 +263,11 @@ class WorkspaceManager:
# dead segment in reserved memory which can cause higher peak
# memory usage.
torch.accelerator.empty_cache()
self._current_workspaces[workspace_id] = torch.empty(
(required_bytes,), dtype=torch.uint8, device=self._device
)
# In sleep mode, entering the pool also trims outgrown buffers.
with self._alloc_context():
self._current_workspaces[workspace_id] = torch.empty(
(required_bytes,), dtype=torch.uint8, device=self._device
)
current_workspace = self._current_workspaces[workspace_id]
if envs.VLLM_DEBUG_WORKSPACE:
@@ -308,6 +312,7 @@ def init_workspace_manager(
device: torch.device,
num_ubatches: int | None = None,
num_lanes: int = 1,
alloc_context: Callable[[], AbstractContextManager] = nullcontext,
) -> None:
"""Initialize the workspace manager with a device.
@@ -318,6 +323,7 @@ def init_workspace_manager(
device: The device to allocate workspace on.
num_ubatches: Number of workspace ubatch slots. Defaults to 1.
num_lanes: Number of independent execution lanes per ubatch. Defaults to 1.
alloc_context: Factory for the context scratch is allocated in.
"""
global _manager
@@ -328,7 +334,7 @@ def init_workspace_manager(
_manager._device,
device,
)
_manager = WorkspaceManager(device, num_ubatches, num_lanes)
_manager = WorkspaceManager(device, num_ubatches, num_lanes, alloc_context)
def lock_workspace() -> None:
+13
View File
@@ -11,6 +11,7 @@ from vllm.v1.worker.gpu.model_runner import (
GPUModelRunner as GPUModelRunnerV2,
)
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
from vllm.v1.worker.mm_encoder_model_runner import MMEncoderModelRunner
class XPUModelRunner(GPUModelRunner):
@@ -39,6 +40,18 @@ class XPUModelRunnerV2(GPUModelRunnerV2):
super().__init__(vllm_config, device)
class XPUMMEncoderModelRunner(MMEncoderModelRunner):
"""An encoder-only model runner for XPU devices."""
def __init__(
self,
vllm_config: VllmConfig,
device: torch.device,
):
with _torch_cuda_wrapper():
super().__init__(vllm_config, device)
@contextmanager
def _torch_cuda_wrapper():
# Replace cuda APIs with xpu APIs. Each callable gets its own functools.partial
+16 -15
View File
@@ -10,10 +10,12 @@ from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.mem_utils import MemorySnapshot, format_gib
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.utils import report_usage_stats
from vllm.v1.worker.gpu_worker import Worker, init_worker_distributed_environment
from vllm.v1.worker.workspace import init_workspace_manager
from vllm.v1.worker.xpu_model_runner import XPUModelRunner, XPUModelRunnerV2
from vllm.v1.worker.xpu_model_runner import (
XPUMMEncoderModelRunner,
XPUModelRunner,
XPUModelRunnerV2,
)
from .utils import request_memory
@@ -210,19 +212,18 @@ class XPUWorker(Worker):
"worker requested memory: %sGiB", format_gib(self.requested_memory)
)
# Initialize workspace manager
num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1
init_workspace_manager(self.device, num_ubatches)
self._init_workspace_and_model_runner()
# Construct the model runner
model_runner = XPUModelRunnerV2 if self.use_v2_model_runner else XPUModelRunner
self.model_runner = model_runner( # type: ignore
self.vllm_config, self.device
)
if self.rank == 0:
# If usage stat is enabled, collect relevant info.
report_usage_stats(self.vllm_config)
def _make_model_runner(self):
if self.use_v2_model_runner:
model_runner = (
XPUMMEncoderModelRunner
if self.vllm_config.is_mm_encoder_only
else XPUModelRunnerV2
)
else:
model_runner = XPUModelRunner # type: ignore[assignment]
return model_runner(self.vllm_config, self.device) # type: ignore
def shutdown(self) -> None:
logger.info(