Add pydocstyle to the ruff rules (#52136)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com> Signed-off-by: Harry Mellor <hej.mellor@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
804e5377aa
commit
8c1557a79c
@@ -34,8 +34,7 @@ from vllm.v1.kv_cache_interface import KVCacheLayout, get_kv_quant_mode
|
||||
|
||||
|
||||
class AttentionType(str, Enum):
|
||||
"""
|
||||
Attention type.
|
||||
"""Attention type.
|
||||
Use string to be compatible with `torch.compile`.
|
||||
"""
|
||||
|
||||
@@ -366,7 +365,8 @@ class AttentionBackend(ABC):
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
|
||||
"""Layouts this backend's kernels can consume, most preferred first, or
|
||||
None when the kernels consume any layout and express no preference."""
|
||||
None when the kernels consume any layout and express no preference.
|
||||
"""
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
@@ -383,8 +383,7 @@ T = TypeVar("T", bound=AttentionMetadata)
|
||||
|
||||
@dataclass
|
||||
class CommonAttentionMetadata:
|
||||
"""
|
||||
Per-batch attention metadata, shared across layers and backends.
|
||||
"""Per-batch attention metadata, shared across layers and backends.
|
||||
AttentionMetadataBuilder instances use it to construct per-layer metadata.
|
||||
|
||||
For many of the tensors we keep both GPU and CPU versions.
|
||||
@@ -559,7 +558,8 @@ M = TypeVar("M")
|
||||
class AttentionCGSupport(Enum):
|
||||
"""Constants for the cudagraph support of the attention backend
|
||||
Here we do not consider the cascade attention, as currently
|
||||
it is never cudagraph supported."""
|
||||
it is never cudagraph supported.
|
||||
"""
|
||||
|
||||
ALWAYS = 3
|
||||
"""Cudagraph always supported; supports mixed-prefill-decode"""
|
||||
@@ -655,8 +655,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> M:
|
||||
"""
|
||||
Central method that builds attention metadata.
|
||||
"""Central method that builds attention metadata.
|
||||
Some builders (MLA) require reorder_batch to be called prior to build.
|
||||
|
||||
Args:
|
||||
@@ -665,6 +664,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
fast_build: The meta-data will prioritize speed of building over
|
||||
then speed at execution. Can be used for spec-decode where the
|
||||
result of a build call may only be used for few layers/iters.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -674,8 +674,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
blk_table: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
) -> M:
|
||||
"""
|
||||
Update the block table for the attention metadata.
|
||||
"""Update the block table for the attention metadata.
|
||||
Faster when theres multiple kv-cache groups that create virtually the
|
||||
same metadata but just with different block tables.
|
||||
|
||||
@@ -686,8 +685,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
def build_for_cudagraph_capture(
|
||||
self, common_attn_metadata: CommonAttentionMetadata
|
||||
) -> M:
|
||||
"""
|
||||
Build attention metadata for CUDA graph capture. Uses build by default.
|
||||
"""Build attention metadata for CUDA graph capture. Uses build by default.
|
||||
Subclasses that override this method should call self.build or
|
||||
super().build_for_cudagraph_capture.
|
||||
"""
|
||||
@@ -700,8 +698,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
draft_index: int,
|
||||
) -> M:
|
||||
"""
|
||||
Build attention metadata for draft model. Uses build by default.
|
||||
"""Build attention metadata for draft model. Uses build by default.
|
||||
|
||||
Args:
|
||||
common_attn_metadata: The common attention metadata.
|
||||
@@ -710,6 +707,7 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
draft attempt for the i-th token.
|
||||
For tree-based attention, this index instead refers to the
|
||||
draft attempt for the i-th level in the tree of tokens.
|
||||
|
||||
"""
|
||||
return self.build(
|
||||
common_prefix_len=0,
|
||||
@@ -910,8 +908,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
raise NotImplementedError
|
||||
|
||||
def fused_output_quant_supported(self, quant_key: "QuantKey") -> bool:
|
||||
"""
|
||||
Does this attention implementation support fused output quantization.
|
||||
"""Does this attention implementation support fused output quantization.
|
||||
This is used by the AttnFusionPass to only fuse output quantization
|
||||
onto implementations that support it.
|
||||
|
||||
@@ -920,20 +917,19 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
|
||||
Returns:
|
||||
is fusion supported for this type of quantization
|
||||
|
||||
"""
|
||||
return False
|
||||
|
||||
def fused_qk_norm_rope_kvcache_supported(self):
|
||||
"""
|
||||
Does this attention implementation support fused QKNorm+RoPE+KVCache fusion.
|
||||
"""Does this attention implementation support fused QKNorm+RoPE+KVCache fusion.
|
||||
This is used by the QkNormRopeKvCachePattern to only fuse the QKNorm ops
|
||||
with the RoPE ops and the KV cache update for implementations that support it.
|
||||
"""
|
||||
return False
|
||||
|
||||
def fused_rope_kvcache_supported(self):
|
||||
"""
|
||||
Does this attention implementation support RoPE+KVCache fusion.
|
||||
"""Does this attention implementation support RoPE+KVCache fusion.
|
||||
This is used by the RopeKVCacheFusionPass to only fuse the RoPE ops
|
||||
with the KV cache update for implementations that support it.
|
||||
"""
|
||||
@@ -954,8 +950,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
kv_cache: torch.Tensor,
|
||||
layer_slot_mapping: torch.Tensor,
|
||||
):
|
||||
"""
|
||||
If `fused_qk_norm_rope_kvcache_supported` returns True, this method
|
||||
"""If `fused_qk_norm_rope_kvcache_supported` returns True, this method
|
||||
will be called by the fused custom op. Applies QK-norm + RoPE and
|
||||
writes K/V to the KV cache. Results are written to the pre-allocated
|
||||
q_out and k_out tensors; V is split from QKV at the graph level.
|
||||
@@ -974,8 +969,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
kv_cache: torch.Tensor,
|
||||
layer_slot_mapping: torch.Tensor,
|
||||
):
|
||||
"""
|
||||
If `fused_rope_kvcache_supported` returns True, this method will be called
|
||||
"""If `fused_rope_kvcache_supported` returns True, this method will be called
|
||||
by torch.ops.vllm.fused_rope_and_unified_kv_cache_update
|
||||
to perform the inplace RoPE and KV cache update.
|
||||
"""
|
||||
@@ -1040,8 +1034,7 @@ class MLAAttentionImpl(AttentionImplBase[T], Generic[T]):
|
||||
raise NotImplementedError
|
||||
|
||||
def fused_output_quant_supported(self, quant_key: "QuantKey"):
|
||||
"""
|
||||
Does this attention implementation support fused output quantization.
|
||||
"""Does this attention implementation support fused output quantization.
|
||||
Since MLA quantization is done manually in forward_impl (common code),
|
||||
all MLA backends support it by default.
|
||||
"""
|
||||
@@ -1080,9 +1073,7 @@ def subclass_attention_backend(
|
||||
attention_backend_cls: type[AttentionBackend],
|
||||
builder_cls: type[AttentionMetadataBuilder[M]],
|
||||
) -> type[AttentionBackend]:
|
||||
"""
|
||||
Return a new subclass where `get_builder_cls` returns `builder_cls`.
|
||||
"""
|
||||
"""Return a new subclass where `get_builder_cls` returns `builder_cls`."""
|
||||
name: str = name_prefix + attention_backend_cls.__name__ # type: ignore
|
||||
|
||||
return type(
|
||||
|
||||
@@ -84,7 +84,8 @@ class CPUAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def supports_attn_type(cls, attn_type: str) -> bool:
|
||||
"""CPU attention supports decoder,
|
||||
encoder-only and encoder-decoder attention."""
|
||||
encoder-only and encoder-decoder attention.
|
||||
"""
|
||||
return attn_type in (
|
||||
AttentionType.DECODER,
|
||||
AttentionType.ENCODER,
|
||||
@@ -349,14 +350,22 @@ class CPUAttentionBackendImpl(AttentionImpl):
|
||||
"""Forward pass for CPU attention backend.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, num_kv_heads, block_size, 2 * head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization; not supported
|
||||
by this backend.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
|
||||
@@ -357,6 +357,7 @@ def is_flash_attn_varlen_func_available() -> bool:
|
||||
|
||||
Returns:
|
||||
bool: True if a working flash_attn_varlen_func implementation is available.
|
||||
|
||||
"""
|
||||
if current_platform.is_cuda() or current_platform.is_xpu():
|
||||
# CUDA and XPU always have flash_attn_varlen_func available
|
||||
|
||||
@@ -766,8 +766,7 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
fast_build: bool = False,
|
||||
) -> FlashAttentionMetadata:
|
||||
"""
|
||||
fast_build disables AOT scheduling, used when there will be few
|
||||
"""fast_build disables AOT scheduling, used when there will be few
|
||||
iterations i.e. spec-decode
|
||||
"""
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
@@ -1178,17 +1177,25 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
"""Forward pass with FlashAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, num_kv_heads, block_size, 2 * head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization; not supported
|
||||
by this backend.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
NOTE: FP8 quantization, flash-attn expect the size of
|
||||
{q,k,v}_descale to be (num_sequences, num_kv_heads).
|
||||
We use torch's .expand() to avoid duplicating values
|
||||
|
||||
"""
|
||||
assert self.vllm_flash_attn_version is not None, (
|
||||
"FlashAttention version not detected."
|
||||
@@ -1665,6 +1672,7 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
output: shape = [num_encoder_tokens, num_heads, head_size]
|
||||
attn_metadata: Encoder attention metadata
|
||||
layer: The attention layer
|
||||
|
||||
"""
|
||||
assert self.vllm_flash_attn_version is not None, (
|
||||
"FlashAttention version not detected."
|
||||
|
||||
@@ -131,17 +131,25 @@ class FlashAttentionDiffKVImpl(FlashAttentionImpl):
|
||||
"""Forward pass with FlashAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size_v]
|
||||
kv_cache: shape =
|
||||
[num_blocks, block_size, num_kv_heads, head_size + head_size_v]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization; not supported
|
||||
by this backend.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size_v]
|
||||
NOTE: FP8 quantization, flash-attn expect the size of
|
||||
{q,k,v}_descale to be (num_sequences, num_kv_heads).
|
||||
We use torch's .expand() to avoid duplicating values
|
||||
|
||||
"""
|
||||
assert self.vllm_flash_attn_version is not None, (
|
||||
"FlashAttention version not detected."
|
||||
|
||||
@@ -398,7 +398,8 @@ class FlashInferBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
|
||||
"""NVFP4 stores K and V as separate per-head slots of packed fp4 data
|
||||
plus fp8 block scales."""
|
||||
plus fp8 block scales.
|
||||
"""
|
||||
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
|
||||
return spec
|
||||
hs_k = nvfp4_kv_cache_full_dim(spec.head_size)
|
||||
@@ -1253,9 +1254,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
num_reqs: int,
|
||||
page_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Compute paged_kv_indptr, paged_kv_indices, paged_kv_last_page_len for FlashInfer
|
||||
attention.
|
||||
"""Compute paged_kv_indptr, paged_kv_indices and paged_kv_last_page_len.
|
||||
|
||||
Results are stored in self.paged_kv_indptr,
|
||||
self.paged_kv_indices, self.paged_kv_last_page_len buffers.
|
||||
@@ -1964,6 +1963,7 @@ class FlashInferImpl(AttentionImpl):
|
||||
"""Forward pass with FlashInfer.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size], or None for a
|
||||
KV-sharing decoder layer.
|
||||
@@ -1971,8 +1971,15 @@ class FlashInferImpl(AttentionImpl):
|
||||
KV-sharing decoder layer.
|
||||
kv_cache: [num_blocks, num_kv_heads, block_size, 2*head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization. Enables the
|
||||
attention+quantization fusion path when provided.
|
||||
output_block_scale: Block scale for fused output quantization,
|
||||
required for nvfp4 output and rejected for fp8 output.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if attn_metadata is None:
|
||||
# Profiling run.
|
||||
@@ -2638,8 +2645,7 @@ def fast_plan_decode(
|
||||
fixed_split_size: int = -1,
|
||||
disable_split_kv: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for
|
||||
"""A faster version of BatchDecodeWithPagedKVCacheWrapper::plan used for
|
||||
cudagraph capture/replay, while the no cudagraph version turns back
|
||||
to the original plan.
|
||||
using original plan after passing host-side buffers:
|
||||
|
||||
@@ -165,8 +165,7 @@ def physical_to_logical_mapping(
|
||||
block_size: int,
|
||||
total_blocks: int,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Creates an inverse mapping from physical block locations to logical indices.
|
||||
"""Creates an inverse mapping from physical block locations to logical indices.
|
||||
|
||||
The original block_table maps from logical blocks to physical locations:
|
||||
|
||||
@@ -239,6 +238,7 @@ def physical_to_logical_mapping(
|
||||
A tensor of shape [max_reqs, total_blocks] where each entry
|
||||
physical_to_logical[req_id, physical_block] contains the logical
|
||||
block index for that physical block, or -1 if unused.
|
||||
|
||||
"""
|
||||
max_reqs, max_num_blocks = block_table.shape
|
||||
device = block_table.device
|
||||
@@ -275,8 +275,7 @@ def unique_static_unsorted(
|
||||
ignored_val: int = 0, # value to ignore
|
||||
pad_val: int = -1, # sentinel for unused slots
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
- Keeps the first occurrence of each non-zero value while preserving order,
|
||||
"""- Keeps the first occurrence of each non-zero value while preserving order,
|
||||
then left-packs those uniques and fills the rest with `pad_val`.
|
||||
- Returns (packed, keep_mask) with the *same shape* as `x`.
|
||||
- Requires that all values be in the range [0, M]
|
||||
@@ -286,6 +285,7 @@ def unique_static_unsorted(
|
||||
|
||||
Example:
|
||||
x =[3, 1, 0, 1, 2], M=3, ignored_val=0 => [3, 1, 2, -1, -1]
|
||||
|
||||
"""
|
||||
if not (-1 <= pad_val <= M):
|
||||
raise ValueError("`pad_val` must lie in [-1, M]")
|
||||
@@ -349,6 +349,7 @@ class BlockSparsityHint(NamedTuple):
|
||||
hint_fn: (q_block_idx [num_tokens, 1], kv_block_idx [1, num_kv_blocks],
|
||||
block_size int) -> bool Tensor [num_tokens, num_kv_blocks].
|
||||
Returns True for block pairs that may contain non-masked elements.
|
||||
|
||||
"""
|
||||
|
||||
hint_fn: _block_sparsity_hint_signature
|
||||
@@ -435,6 +436,7 @@ class FlexAttentionMetadata:
|
||||
|
||||
Returns:
|
||||
tuple of (is_valid, logical_q_idx, logical_kv_idx)
|
||||
|
||||
"""
|
||||
# Map query indices to corresponding request indices
|
||||
q_req = request_lookup[q_idx]
|
||||
@@ -512,7 +514,6 @@ class FlexAttentionMetadata:
|
||||
Note that the sliding window mask here is bidirectional, we need
|
||||
to mask it with the bidirectional/causal mask for encoder/decoder.
|
||||
"""
|
||||
|
||||
if self.sliding_window is None:
|
||||
raise ValueError("sliding_window must be set for sliding window attention")
|
||||
|
||||
@@ -540,7 +541,6 @@ class FlexAttentionMetadata:
|
||||
|
||||
def get_prefix_lm_mask_mod(self) -> _mask_mod_signature:
|
||||
"""Creates the prefix LM mask_mod function for FlexAttention."""
|
||||
|
||||
assert self.doc_ids is not None
|
||||
request_lookup = self.doc_ids
|
||||
|
||||
@@ -587,7 +587,6 @@ class FlexAttentionMetadata:
|
||||
far-away generated tokens that fall outside the window and outside the
|
||||
prefix.
|
||||
"""
|
||||
|
||||
assert self.doc_ids is not None
|
||||
assert self.rswa_prefix_lens is not None
|
||||
assert self.rswa_window is not None
|
||||
@@ -1291,14 +1290,22 @@ class FlexAttentionImpl(AttentionImpl):
|
||||
"""Forward pass with FLexAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, num_kv_heads, block_size, 2 * head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization; not supported
|
||||
by this backend.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
|
||||
@@ -524,8 +524,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
def build_for_cudagraph_capture(
|
||||
self, common_attn_metadata: CommonAttentionMetadata
|
||||
):
|
||||
"""
|
||||
This method builds the metadata for full cudagraph capture.
|
||||
"""This method builds the metadata for full cudagraph capture.
|
||||
Currently, only decode is supported for full cudagraphs with Mamba.
|
||||
"""
|
||||
m = common_attn_metadata
|
||||
|
||||
@@ -23,8 +23,7 @@ def compute_varlen_chunk_metadata(
|
||||
query_start_loc: torch.Tensor,
|
||||
chunk_size: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Build chunk-aligned, variable-length metadata used by Mamba2 SSD kernels.
|
||||
"""Build chunk-aligned, variable-length metadata used by Mamba2 SSD kernels.
|
||||
|
||||
Given per-sequence cumulative token starts `query_start_loc` of shape [B+1]
|
||||
and a physical `chunk_size`, returns three tensors on the same device:
|
||||
|
||||
@@ -227,8 +227,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
def build_for_cudagraph_capture(
|
||||
self, common_attn_metadata: CommonAttentionMetadata
|
||||
) -> M:
|
||||
"""
|
||||
This method builds the metadata for full cudagraph capture.
|
||||
"""This method builds the metadata for full cudagraph capture.
|
||||
Currently, only decode is supported for full cudagraphs with Mamba.
|
||||
"""
|
||||
m = common_attn_metadata
|
||||
@@ -276,8 +275,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
|
||||
**kwargs: Any,
|
||||
) -> M:
|
||||
"""
|
||||
Default build implementation for Mamba-like attention backends.
|
||||
"""Default build implementation for Mamba-like attention backends.
|
||||
Subclasses (e.g., Mamba2) can override to add additional metadata.
|
||||
"""
|
||||
return self._compute_common_metadata(
|
||||
@@ -294,8 +292,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
num_computed_tokens_p_cpu: torch.Tensor,
|
||||
query_start_loc_p_cpu: torch.Tensor,
|
||||
) -> tuple[list[int], list[int], list[int]]:
|
||||
"""
|
||||
Compute chunk-specific metadata for Mamba models.
|
||||
"""Compute chunk-specific metadata for Mamba models.
|
||||
|
||||
The code below carefully constructs the chunks such that:
|
||||
1. Chunks contain tokens from a *single* sequence only.
|
||||
@@ -382,8 +379,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
common: M,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Compute chunk metadata and return as device tensors.
|
||||
"""Compute chunk metadata and return as device tensors.
|
||||
Returns (cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p).
|
||||
"""
|
||||
num_prefills = common.num_prefills
|
||||
@@ -463,9 +459,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
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.
|
||||
"""
|
||||
"""Compute metadata common to both Mamba1 and Mamba2."""
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
|
||||
# Treat multi-token queries as decode requests when
|
||||
@@ -752,8 +746,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
self,
|
||||
metadata: M,
|
||||
) -> M:
|
||||
"""
|
||||
Update the metadata for cudagraph capture.
|
||||
"""Update the metadata for cudagraph capture.
|
||||
Currently, only decode is supported for full cudagraphs with Mamba.
|
||||
"""
|
||||
state_indices_tensor_d = metadata.state_indices_tensor_d
|
||||
|
||||
@@ -63,7 +63,8 @@ _SPLIT_OCCUPANCY_MULTIPLIER = 2
|
||||
|
||||
def _compute_num_kv_splits(max_seq_len: int, num_threads: int) -> int:
|
||||
"""Mirrors TritonMLAImpl's _compute_num_kv_splits, using the CPU thread
|
||||
count in place of SM count."""
|
||||
count in place of SM count.
|
||||
"""
|
||||
ideal_splits = 1
|
||||
while ideal_splits < max(1, max_seq_len // _MIN_WORK_PER_SPLIT):
|
||||
ideal_splits *= 2
|
||||
|
||||
@@ -437,7 +437,6 @@ class FlashMLASparseMetadataBuilder(
|
||||
be the full batch or only decodes when prefills use dense MHA. This avoids
|
||||
the BF16 prefill kernel's head-padding overhead at high TP.
|
||||
"""
|
||||
|
||||
scheduler_metadata, _ = get_mla_metadata()
|
||||
return FlashMLASparseMetadata.FP8KernelMetadata(
|
||||
scheduler_metadata=scheduler_metadata,
|
||||
@@ -848,7 +847,8 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
prefill_meta: "FlashMLASparseMetadata.FP8SeparatePrefillDecode.Prefill",
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""All-gather this rank's upconverted KV shard so the chunk's rows attend
|
||||
the whole context, and map their top-k onto the rank-major result."""
|
||||
the whole context, and map their top-k onto the rank-major result.
|
||||
"""
|
||||
shard_rows = int(chunk.chunk_tot_seqlen)
|
||||
assert self.gathered_kv_workspace is not None
|
||||
gathered_kv = self.gathered_kv_workspace[: self.dcp_world_size * shard_rows]
|
||||
|
||||
@@ -1118,7 +1118,8 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
|
||||
def _prefill_split_seq_lens(self, seq_lens_cpu: torch.Tensor) -> torch.Tensor:
|
||||
"""Per-request KV lengths the prefill chunker budgets logits with;
|
||||
subclasses whose logits rows are wider than the context override."""
|
||||
subclasses whose logits rows are wider than the context override.
|
||||
"""
|
||||
return seq_lens_cpu
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -24,7 +24,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class AiterFlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
"""AITER FlashAttention backend for MLA prefill"""
|
||||
"""AITER FlashAttention backend for MLA prefill."""
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
|
||||
@@ -70,7 +70,8 @@ class MLAPrefillBackend(ABC):
|
||||
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
|
||||
"""Whether `run_prefill_new_tokens` can write quantized output
|
||||
directly (fused) for the given quant key, skipping the post-quant
|
||||
pass. Overridden by backends that support it."""
|
||||
pass. Overridden by backends that support it.
|
||||
"""
|
||||
return False
|
||||
|
||||
def supports_out(self) -> bool:
|
||||
|
||||
@@ -65,6 +65,7 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
|
||||
|
||||
Raises:
|
||||
ValueError: If Backend.CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
path = _MLA_PREFILL_OVERRIDES.get(self, self.value)
|
||||
if not path:
|
||||
@@ -85,6 +86,7 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
|
||||
Raises:
|
||||
ImportError: If the backend class cannot be imported
|
||||
ValueError: If CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
return resolve_obj_by_qualname(self.get_path())
|
||||
|
||||
@@ -130,6 +132,7 @@ def register_mla_prefill_backend(
|
||||
MLAPrefillBackendEnum.CUSTOM,
|
||||
"my.module.MyCustomPrefillBackend"
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
def decorator(cls: type) -> type:
|
||||
|
||||
@@ -57,6 +57,7 @@ def _get_mla_prefill_backend_priorities(
|
||||
|
||||
Returns:
|
||||
List of backends in priority order (highest priority first).
|
||||
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -104,6 +105,7 @@ def get_mla_prefill_backend(
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -173,6 +175,7 @@ def _auto_select_mla_prefill_backend(
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
|
||||
"""
|
||||
priorities = _get_mla_prefill_backend_priorities(
|
||||
device_capability,
|
||||
|
||||
@@ -710,6 +710,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
attn_out_dtype: Dtype of the attention output buffer, used to size
|
||||
the padded-head output scratch (small head counts only).
|
||||
device: Target device for the buffers.
|
||||
|
||||
"""
|
||||
from aiter import get_ps_metadata_info_v1
|
||||
|
||||
@@ -1328,8 +1329,7 @@ def _expand_page_indices_kernel(
|
||||
|
||||
|
||||
class AiterMLAHelper:
|
||||
"""
|
||||
AITER MLA persistent (asm) decode requires a multiple of 16 heads. Unaligned
|
||||
"""AITER MLA persistent (asm) decode requires a multiple of 16 heads. Unaligned
|
||||
head counts through 128 are padded to the next multiple of 16 by tiling the
|
||||
query heads and slicing to the padded size. Native H24 AITER builds bypass
|
||||
that padding. Small divisors of 16 retain the existing repeat_interleave and
|
||||
|
||||
@@ -167,8 +167,7 @@ def triton_convert_req_index_to_global_index(
|
||||
NUM_TOPK_TOKENS: int = 2048,
|
||||
BLOCK_N: int = 128, # tile width along columns
|
||||
):
|
||||
"""
|
||||
out[token_id, indice_id] =
|
||||
"""out[token_id, indice_id] =
|
||||
block_table[req_id[token_id],
|
||||
token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_SIZE
|
||||
+ token_indices[token_id, indice_id] % BLOCK_SIZE
|
||||
|
||||
@@ -426,6 +426,7 @@ def _remap_tiling(
|
||||
|
||||
Returns:
|
||||
(single_tile, block_n, tiles_per_row, num_warps)
|
||||
|
||||
"""
|
||||
single_tile = (
|
||||
count_valid and triton.next_power_of_2(NUM_TOPK_TOKENS) == NUM_TOPK_TOKENS
|
||||
@@ -454,8 +455,7 @@ def triton_convert_req_index_to_global_index(
|
||||
out: torch.Tensor | None = None,
|
||||
valid_counts_out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
out[token_id, indice_id] =
|
||||
"""out[token_id, indice_id] =
|
||||
block_table[req_id[token_id],
|
||||
token_indices[token_id, indice_id] // BLOCK_SIZE] * BLOCK_SIZE
|
||||
+ token_indices[token_id, indice_id] % BLOCK_SIZE
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Attention backend registry"""
|
||||
"""Attention backend registry."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from enum import Enum, EnumMeta
|
||||
@@ -161,6 +161,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
|
||||
Raises:
|
||||
ValueError: If Backend.CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
path = _ATTN_OVERRIDES.get(self, self.value)
|
||||
if not path:
|
||||
@@ -181,6 +182,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
Raises:
|
||||
ImportError: If the backend class cannot be imported
|
||||
ValueError: If Backend.CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
return resolve_obj_by_qualname(self.get_path())
|
||||
|
||||
@@ -189,6 +191,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
|
||||
Returns:
|
||||
True if the backend has a registered override
|
||||
|
||||
"""
|
||||
return self in _ATTN_OVERRIDES
|
||||
|
||||
@@ -224,6 +227,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
|
||||
Raises:
|
||||
ValueError: If Backend.CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
path = _MAMBA_ATTN_OVERRIDES.get(self, self.value)
|
||||
if not path:
|
||||
@@ -244,6 +248,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
Raises:
|
||||
ImportError: If the backend class cannot be imported
|
||||
ValueError: If Backend.CUSTOM is used without being registered
|
||||
|
||||
"""
|
||||
return resolve_obj_by_qualname(self.get_path())
|
||||
|
||||
@@ -252,6 +257,7 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
|
||||
Returns:
|
||||
True if the backend has a registered override
|
||||
|
||||
"""
|
||||
return self in _MAMBA_ATTN_OVERRIDES
|
||||
|
||||
@@ -275,6 +281,7 @@ def register_backend(
|
||||
backend: The AttentionBackendEnum member to register
|
||||
class_path: Optional class path. If not provided and used as
|
||||
decorator, will be auto-generated from the class.
|
||||
is_mamba: Whether the backend is a Mamba attention backend.
|
||||
|
||||
Returns:
|
||||
Decorator function if class_path is None, otherwise a no-op
|
||||
@@ -300,6 +307,7 @@ def register_backend(
|
||||
AttentionBackendEnum.CUSTOM,
|
||||
"my.module.MyCustomBackend"
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
def decorator(cls: type) -> type:
|
||||
|
||||
@@ -770,8 +770,7 @@ class AiterFlashAttentionMetadataBuilder(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
draft_index: int,
|
||||
) -> AiterFlashAttentionMetadata:
|
||||
"""
|
||||
Build attention metadata for draft model without CPU-GPU sync.
|
||||
"""Build attention metadata for draft model without CPU-GPU sync.
|
||||
|
||||
During EAGLE drafting all requests are uniform decodes, so we can
|
||||
skip split_decodes_prefills_and_extends() and avoid all .cpu() /
|
||||
@@ -1189,17 +1188,25 @@ class AiterFlashAttentionImpl(AttentionImpl):
|
||||
"""Forward pass with AiterFlashAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, 2, block_size, num_kv_heads, head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization; not supported
|
||||
by this backend.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
NOTE: FP8 quantization, flash-attn expect the size of
|
||||
{q,k,v}_descale to be (num_sequences, num_kv_heads).
|
||||
We use torch's .expand() to avoid duplicating values
|
||||
|
||||
"""
|
||||
if output_scale is not None or output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
|
||||
@@ -110,7 +110,8 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
"""Keep K and V packed in the content dim, unlike the native HIP
|
||||
kernels the base class targets."""
|
||||
kernels the base class targets.
|
||||
"""
|
||||
# block_size == 1 is the per-token page-size probe (see
|
||||
# Platform.get_page_size_bytes); real blocks must be gatherable in
|
||||
# 16-token units by the ROCm kernel.
|
||||
@@ -207,14 +208,21 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
|
||||
"""Forward pass with FlashAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, 2, block_size, num_kv_heads, head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
|
||||
@@ -244,7 +244,8 @@ class RocmAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
"""K and V as two head groups so the native HIP kernels address each side
|
||||
as one contiguous region (x-packed interior applied in split_kv_cache)."""
|
||||
as one contiguous region (x-packed interior applied in split_kv_cache).
|
||||
"""
|
||||
if spec.state_content_bytes is not None:
|
||||
return spec
|
||||
assert spec.head_size == spec.head_size_v, (
|
||||
@@ -344,6 +345,7 @@ class RocmAttentionImpl(AttentionImpl):
|
||||
output: shape = [num_encoder_tokens, num_heads, head_size]
|
||||
attn_metadata: Encoder attention metadata
|
||||
layer: The attention layer
|
||||
|
||||
"""
|
||||
# For encoder attention, process FP8 quantization if needed
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
@@ -390,14 +392,21 @@ class RocmAttentionImpl(AttentionImpl):
|
||||
"""Forward pass with FlashAttention.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: logical [num_blocks, 2, block_size, num_kv_heads *
|
||||
head_size] under LHBNC (physically K/V-group-first)
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
|
||||
@@ -275,7 +275,8 @@ class TritonAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
|
||||
"""Per-token-head modes pack inline fp32 scales after each head's
|
||||
data, so the content is (data + one scale) per K/V side."""
|
||||
data, so the content is (data + one scale) per K/V side.
|
||||
"""
|
||||
mode = spec.kv_quant_mode
|
||||
if spec.state_content_bytes is not None or not mode.is_per_token_head:
|
||||
return spec
|
||||
@@ -557,14 +558,21 @@ class TritonAttentionImpl(AttentionImpl):
|
||||
"""Forward pass with Paged Attention impl. in Triton.
|
||||
|
||||
Args:
|
||||
layer: The attention layer, providing the q/k/v quantization scales.
|
||||
query: shape = [num_tokens, num_heads, head_size]
|
||||
key: shape = [num_tokens, num_kv_heads, head_size]
|
||||
value: shape = [num_tokens, num_kv_heads, head_size]
|
||||
kv_cache: shape =
|
||||
[num_blocks, num_kv_heads, block_size, 2 * head_size]
|
||||
attn_metadata: Metadata for attention.
|
||||
output: Tensor that the attention result is written into.
|
||||
output_scale: Scale for fused output quantization.
|
||||
output_block_scale: Block scale for fused output quantization;
|
||||
not supported by this backend.
|
||||
|
||||
Returns:
|
||||
shape = [num_tokens, num_heads * head_size]
|
||||
|
||||
"""
|
||||
if output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
@@ -724,6 +732,7 @@ class TritonAttentionImpl(AttentionImpl):
|
||||
output: shape = [num_encoder_tokens, num_heads, head_size]
|
||||
attn_metadata: Encoder attention metadata
|
||||
layer: The attention layer
|
||||
|
||||
"""
|
||||
# Quantized KV cache is not supported for encoder attention.
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
|
||||
@@ -324,8 +324,7 @@ def resolve_kv_cache_layout(
|
||||
|
||||
@dataclass
|
||||
class PerLayerParameters:
|
||||
"""
|
||||
Currently, FlashInfer backend only support models in which all layers share
|
||||
"""Currently, FlashInfer backend only support models in which all layers share
|
||||
the same values for the following hyperparameters. Should not be used for
|
||||
trtllm-gen backend since it supports different values for the following
|
||||
hyperparameters.
|
||||
@@ -343,11 +342,9 @@ class PerLayerParameters:
|
||||
def get_per_layer_parameters(
|
||||
vllm_config: VllmConfig, layer_names: list[str], cls_: type["AttentionImpl"]
|
||||
) -> dict[str, PerLayerParameters]:
|
||||
"""
|
||||
Scan layers in `layer_names` and determine some hyperparameters
|
||||
"""Scan layers in `layer_names` and determine some hyperparameters
|
||||
to use during `plan`.
|
||||
"""
|
||||
|
||||
layers = get_layers_from_vllm_config(
|
||||
vllm_config,
|
||||
AttentionLayerBase, # type: ignore[type-abstract]
|
||||
@@ -405,8 +402,7 @@ def get_num_attention_heads_from_layers(
|
||||
def infer_global_hyperparameters(
|
||||
per_layer_params: dict[str, PerLayerParameters],
|
||||
) -> PerLayerParameters:
|
||||
"""
|
||||
Currently, FlashInfer backend other than trtllm-gen
|
||||
"""Currently, FlashInfer backend other than trtllm-gen
|
||||
only support models in which all layers share
|
||||
the same values for the following hyperparameters:
|
||||
- `window_left`
|
||||
@@ -416,7 +412,6 @@ def infer_global_hyperparameters(
|
||||
So this function asserts that all layers share the same values for these
|
||||
hyperparameters and returns the global values.
|
||||
"""
|
||||
|
||||
assert len(per_layer_params) > 0, "No attention layers found in the model."
|
||||
|
||||
param_sets = list(per_layer_params.values())
|
||||
@@ -710,8 +705,7 @@ def split_decodes_prefills_and_extends(
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
decode_threshold: int = 1,
|
||||
) -> tuple[int, int, int, int, int, int]:
|
||||
"""
|
||||
Assuming a reordered batch, finds the boundary between prefill and decode
|
||||
"""Assuming a reordered batch, finds the boundary between prefill and decode
|
||||
requests.
|
||||
|
||||
Args:
|
||||
@@ -726,6 +720,7 @@ def split_decodes_prefills_and_extends(
|
||||
num_decode_tokens: The number of tokens in the decode requests.
|
||||
num_extend_tokens: The number of tokens in the extend requests.
|
||||
num_prefill_tokens: The number of tokens in the prefill requests.
|
||||
|
||||
"""
|
||||
max_query_len = common_attn_metadata.max_query_len
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
@@ -784,8 +779,7 @@ def split_decodes_and_prefills(
|
||||
require_uniform: bool = False,
|
||||
treat_short_extends_as_decodes: bool = True,
|
||||
) -> tuple[int, int, int, int]:
|
||||
"""
|
||||
Assuming a reordered batch, finds the boundary between prefill and decode
|
||||
"""Assuming a reordered batch, finds the boundary between prefill and decode
|
||||
requests.
|
||||
|
||||
The batch is expected to be ordered as:
|
||||
@@ -807,6 +801,7 @@ def split_decodes_and_prefills(
|
||||
num_prefills: The number of prefill requests.
|
||||
num_decode_tokens: The number of tokens in the decode requests.
|
||||
num_prefill_tokens: The number of tokens in the prefill requests.
|
||||
|
||||
"""
|
||||
max_query_len = common_attn_metadata.max_query_len
|
||||
num_reqs = common_attn_metadata.num_reqs
|
||||
@@ -855,16 +850,17 @@ def split_decodes_and_prefills(
|
||||
def split_prefill_chunks(
|
||||
seq_lens_cpu: torch.Tensor, workspace_size: int, request_offset: int = 0
|
||||
) -> list[tuple[int, int]]:
|
||||
"""
|
||||
Split the prefill requests into chunks such that the total sequence length
|
||||
"""Split the prefill requests into chunks such that the total sequence length
|
||||
of each chunk is less than or equal to the workspace size.
|
||||
|
||||
Args:
|
||||
seq_lens_cpu: The sequence lengths of the prefill requests on CPU.
|
||||
workspace_size: The maximum workspace size (in tokens) per chunk.
|
||||
request_offset: The offset to add to the request indices.
|
||||
|
||||
Returns:
|
||||
A list of tuples of (reqs_start, reqs_end) representing chunk boundaries.
|
||||
|
||||
"""
|
||||
chunk_bounds = []
|
||||
i, n = 0, len(seq_lens_cpu)
|
||||
@@ -884,8 +880,7 @@ def reorder_batch_to_split_decodes_and_prefills(
|
||||
scheduler_output: "SchedulerOutput",
|
||||
decode_threshold: int = 1,
|
||||
) -> bool:
|
||||
"""
|
||||
Reorders the batch to split into prefill and decode requests; places all
|
||||
"""Reorders the batch to split into prefill and decode requests; places all
|
||||
requests with <= decode_threshold tokens at the front of the batch.
|
||||
|
||||
The batch is reordered into 4 regions:
|
||||
@@ -896,6 +891,7 @@ def reorder_batch_to_split_decodes_and_prefills(
|
||||
|
||||
Returns:
|
||||
True if the batch was modified, False otherwise.
|
||||
|
||||
"""
|
||||
num_reqs = len(input_batch.req_ids)
|
||||
num_scheduled_tokens = [
|
||||
@@ -960,8 +956,7 @@ def reorder_batch_to_split_decodes_and_prefills(
|
||||
|
||||
|
||||
def reshape_query_for_spec_decode(query: torch.Tensor, batch_size: int) -> torch.Tensor:
|
||||
"""
|
||||
Reshapes the query tensor for the specified batch size, so that
|
||||
"""Reshapes the query tensor for the specified batch size, so that
|
||||
it has shape (batch_size, seq_len, num_heads, head_dim).
|
||||
"""
|
||||
assert query.dim() == 3, f"query must be 3D, got {query.dim()}D"
|
||||
@@ -976,8 +971,7 @@ def reshape_query_for_spec_decode(query: torch.Tensor, batch_size: int) -> torch
|
||||
|
||||
|
||||
def reshape_attn_output_for_spec_decode(attn_output: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Reshapes the attention output tensor, so that
|
||||
"""Reshapes the attention output tensor, so that
|
||||
the batch_size and seq_len dimensions are combined.
|
||||
"""
|
||||
if attn_output.dim() == 3:
|
||||
@@ -1143,8 +1137,7 @@ def mamba_get_block_table_tensor(
|
||||
kv_cache_spec: KVCacheSpec,
|
||||
mamba_cache_mode: str,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Get the block table tensor for mamba kernels from the input
|
||||
"""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)
|
||||
|
||||
@@ -178,6 +178,7 @@ def pack_seq_triton(
|
||||
|
||||
Returns:
|
||||
packed: [B, Lmax, ...] — packed tensor.
|
||||
|
||||
"""
|
||||
is_uint8 = x.dtype == torch.uint8
|
||||
if is_uint8:
|
||||
@@ -334,8 +335,7 @@ def unpack_seq_triton(
|
||||
block_t: int = 64,
|
||||
block_d: int = 64,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Unpack a packed decode query tensor back to the original format.
|
||||
"""Unpack a packed decode query tensor back to the original format.
|
||||
Efficient Triton implementation.
|
||||
|
||||
Args:
|
||||
@@ -346,8 +346,8 @@ def unpack_seq_triton(
|
||||
|
||||
Returns:
|
||||
unpacked_tensor: [N, ...] where N = sum(lengths)
|
||||
"""
|
||||
|
||||
"""
|
||||
# Handle multi-dimensional input by reshaping to (B, Lmax, -1)
|
||||
original_shape = packed_tensor.shape
|
||||
if len(original_shape) > 3:
|
||||
|
||||
@@ -133,8 +133,7 @@ class CorrectAttnCPOutKernel(VllmTritonJitKernel["CorrectAttnCPOutKernel.Compile
|
||||
N_ROUNDED: tl.constexpr,
|
||||
IS_BASE_E: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Apply the all-gathered lses to correct each local rank's attention
|
||||
"""Apply the all-gathered lses to correct each local rank's attention
|
||||
output. we still need perform a cross-rank reduction to obtain the
|
||||
final attention output.
|
||||
|
||||
@@ -147,6 +146,17 @@ class CorrectAttnCPOutKernel(VllmTritonJitKernel["CorrectAttnCPOutKernel.Compile
|
||||
Pointer to output tensor of shape [ B, H, D ]
|
||||
vlse_ptr (triton.PointerType):
|
||||
Pointer to output tensor of shape [ B, H ]
|
||||
outputs_stride_B (int): Batch stride of ``outputs_ptr``
|
||||
outputs_stride_H (int): Head stride of ``outputs_ptr``
|
||||
outputs_stride_D (int): Head-dim stride of ``outputs_ptr``
|
||||
lses_stride_N (int): Rank stride of ``lses_ptr``
|
||||
lses_stride_B (int): Batch stride of ``lses_ptr``
|
||||
lses_stride_H (int): Head stride of ``lses_ptr``
|
||||
lse_idx (int): Index of this rank's lse within the all-gathered tensor
|
||||
HEAD_DIM: Head dimension, as a constexpr
|
||||
N_ROUNDED: Rank count rounded to a power of two, as a constexpr
|
||||
IS_BASE_E: Whether the lses are natural-log based, as a constexpr
|
||||
|
||||
"""
|
||||
batch_idx = tl.program_id(axis=0).to(tl.int64)
|
||||
head_idx = tl.program_id(axis=1).to(tl.int64)
|
||||
@@ -376,9 +386,11 @@ def correct_attn_out(
|
||||
lses: Tensor of shape [ N, B, H ]
|
||||
cp_rank: Current rank in the context-parallel group
|
||||
ctx: Triton context to avoid recompilation
|
||||
is_lse_base_on_e: Whether the lses use base e rather than base 2
|
||||
|
||||
Returns:
|
||||
Tuple of (out, lse) with corrected attention and final log-sum-exp.
|
||||
|
||||
"""
|
||||
if ctx is None:
|
||||
ctx = CPTritonContext()
|
||||
@@ -431,8 +443,7 @@ def _cp_lse_common(
|
||||
seq_lens: torch.Tensor | None = None,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
):
|
||||
"""
|
||||
cp_attn_out: [ B, H, D ]
|
||||
"""cp_attn_out: [ B, H, D ]
|
||||
cp_attn_lse: [ B, H ]
|
||||
"""
|
||||
if cp_group.world_size == 1:
|
||||
@@ -466,8 +477,7 @@ def cp_lse_ag_out_rs(
|
||||
seq_lens: torch.Tensor | None = None,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
):
|
||||
"""
|
||||
cp_attn_out: [ B, H, D ]
|
||||
"""cp_attn_out: [ B, H, D ]
|
||||
cp_attn_lse: [ B, H ]
|
||||
"""
|
||||
out, lse = _cp_lse_common(
|
||||
@@ -499,8 +509,7 @@ def cp_lse_ag_out_ar(
|
||||
seq_lens: torch.Tensor | None = None,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
):
|
||||
"""
|
||||
cp_attn_out: [ B, H, D ]
|
||||
"""cp_attn_out: [ B, H, D ]
|
||||
cp_attn_lse: [ B, H ]
|
||||
"""
|
||||
out, lse = _cp_lse_common(
|
||||
@@ -528,8 +537,7 @@ def _lse_weighted_combine(
|
||||
return_lse: bool = False,
|
||||
is_lse_base_on_e: bool = True,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
CPU reference implementation for LSE-weighted combination.
|
||||
"""CPU reference implementation for LSE-weighted combination.
|
||||
|
||||
This is a pure PyTorch implementation used for testing and validation.
|
||||
|
||||
@@ -545,6 +553,7 @@ def _lse_weighted_combine(
|
||||
|
||||
Returns:
|
||||
Combined output [B, H, D], and optionally global LSE [B, H]
|
||||
|
||||
"""
|
||||
N, B, H, D = outputs.shape
|
||||
|
||||
@@ -936,8 +945,7 @@ def dcp_a2a_lse_reduce(
|
||||
seq_lens: torch.Tensor | None = None,
|
||||
query_start_loc: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Combine partial attention outputs across DCP ranks using All-to-All.
|
||||
"""Combine partial attention outputs across DCP ranks using All-to-All.
|
||||
|
||||
The output and LSE are packed into a single output-dtype buffer, sent
|
||||
with one All-to-All, then unpacked and combined with exact LSE weighting.
|
||||
@@ -955,6 +963,7 @@ def dcp_a2a_lse_reduce(
|
||||
Returns:
|
||||
Combined output [B, H/N, D] (head-scattered)
|
||||
If return_lse=True, also returns global_lse [B, H/N]
|
||||
|
||||
"""
|
||||
world_size = cp_group.world_size
|
||||
|
||||
|
||||
@@ -49,9 +49,7 @@ def _is_flashmla_available() -> tuple[bool, str | None]:
|
||||
|
||||
|
||||
def is_flashmla_dense_supported() -> tuple[bool, str | None]:
|
||||
"""
|
||||
Return: is_supported_flag, unsupported_reason (optional).
|
||||
"""
|
||||
"""Return: is_supported_flag, unsupported_reason (optional)."""
|
||||
is_available, maybe_reason = _is_flashmla_available()
|
||||
if not is_available:
|
||||
return False, maybe_reason
|
||||
@@ -61,9 +59,7 @@ def is_flashmla_dense_supported() -> tuple[bool, str | None]:
|
||||
|
||||
|
||||
def is_flashmla_sparse_supported() -> tuple[bool, str | None]:
|
||||
"""
|
||||
Return: is_supported_flag, unsupported_reason (optional).
|
||||
"""
|
||||
"""Return: is_supported_flag, unsupported_reason (optional)."""
|
||||
is_available, maybe_reason = _is_flashmla_available()
|
||||
if not is_available:
|
||||
return False, maybe_reason
|
||||
|
||||
@@ -106,8 +106,8 @@ def merge_attn_states(
|
||||
are treated as having context.
|
||||
output_scale: Optional scalar tensor for FP8 static quantization.
|
||||
When provided, output must be FP8 dtype.
|
||||
"""
|
||||
|
||||
"""
|
||||
# Both the CUDA and Triton kernels derive the suffix head stride from
|
||||
# prefix_output, so suffix_output must share the same head stride.
|
||||
assert prefix_output.stride(1) == suffix_output.stride(1), (
|
||||
|
||||
@@ -654,6 +654,7 @@ def rocm_fp8_paged_mqa_logits(
|
||||
Returns:
|
||||
Logits tensor of shape [B * next_n, max_model_len], dtype
|
||||
`torch.float32`.
|
||||
|
||||
"""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
@@ -737,6 +738,7 @@ def fp8_mqa_logits_torch(
|
||||
|
||||
Returns:
|
||||
Logits tensor of shape [M, N], dtype `torch.float32`.
|
||||
|
||||
"""
|
||||
k_fp8, scale = kv
|
||||
seq_len_kv = k_fp8.shape[0]
|
||||
@@ -805,8 +807,8 @@ def rocm_fp8_mqa_logits(
|
||||
|
||||
Returns:
|
||||
Logits tensor of shape [M, N], dtype `torch.float32`.
|
||||
"""
|
||||
|
||||
"""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
k_fp8, scale = kv
|
||||
|
||||
@@ -24,8 +24,7 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ==============================================================================
|
||||
"""
|
||||
Memory-efficient attention for decoding.
|
||||
"""Memory-efficient attention for decoding.
|
||||
It supports page size >= 1.
|
||||
"""
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ==============================================================================
|
||||
"""
|
||||
Memory-efficient attention for prefill.
|
||||
"""Memory-efficient attention for prefill.
|
||||
It supports page size = 1.
|
||||
"""
|
||||
|
||||
@@ -229,8 +228,7 @@ def context_attention_fwd(
|
||||
sinks: torch.Tensor | None = None,
|
||||
sinks_bias_key0: bool = False,
|
||||
):
|
||||
"""
|
||||
q, k, v: [b * s, head, head_dim]
|
||||
"""q, k, v: [b * s, head, head_dim]
|
||||
b_start_loc: [b]
|
||||
b_seq_len: [b]
|
||||
out: [b * s, head, head_dim]
|
||||
|
||||
@@ -45,7 +45,8 @@ def _store_quantized_value(
|
||||
BLOCK_GRP: tl.constexpr,
|
||||
):
|
||||
"""Uniform quantization of values to VQB bits, pack, and store with
|
||||
scale/zero in the per-block SoA metadata region (Opt#3 layout)."""
|
||||
scale/zero in the per-block SoA metadata region (Opt#3 layout).
|
||||
"""
|
||||
if VQB == 3:
|
||||
val_vec = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(
|
||||
tl.float32
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
This file contains ops for ViT attention to be compatible with torch.compile
|
||||
"""This file contains ops for ViT attention to be compatible with torch.compile
|
||||
as there are operations here not supported by torch.compile (for instance,
|
||||
`.item()` in flash attention)
|
||||
|
||||
@@ -238,8 +237,7 @@ def apply_sdpa(
|
||||
scale: float | None = None,
|
||||
enable_gqa: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Input shape:
|
||||
"""Input shape:
|
||||
(batch_size x seq_len x num_heads x head_size)
|
||||
"""
|
||||
q, k, v = (einops.rearrange(x, "b s h d -> b h s d") for x in [q, k, v])
|
||||
|
||||
@@ -185,15 +185,20 @@ def triton_bf16_mla_sparse_interface(
|
||||
d_v: int = 512,
|
||||
block_dpe: int = 64,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
out : [num_tokens, num_heads_q, d_v]
|
||||
"""Out : [num_tokens, num_heads_q, d_v]
|
||||
max_logits : [num_tokens, num_heads_q]
|
||||
lse : logsumexp, [num_tokens, num_heads_q]
|
||||
|
||||
Args:
|
||||
q: Query tensor, [num_tokens, num_heads_q, dim_qk].
|
||||
kv: Latent KV cache tensor.
|
||||
indices: Sparse KV indices selected for each query token.
|
||||
sm_scale: Softmax scale applied to the QK product.
|
||||
d_v: Size of the value dimension.
|
||||
block_dpe: Size of positional embedding portion of dim_qk.
|
||||
Set to 0 when q/kv contain only the nope latent (e.g. DSv4
|
||||
prefill where RoPE is not split out).
|
||||
|
||||
"""
|
||||
num_tokens, num_heads_q, dim_qk = q.shape
|
||||
_, num_heads_kv, _ = kv.shape
|
||||
|
||||
@@ -85,6 +85,7 @@ def get_attn_spec_kind(
|
||||
|
||||
Returns:
|
||||
The ``KVCacheSpecKind`` the layer maps to.
|
||||
|
||||
"""
|
||||
from vllm.v1.kv_cache_interface import KVCacheSpecKind
|
||||
|
||||
@@ -115,7 +116,6 @@ def get_attn_backend(
|
||||
has_sliding_window: bool = False,
|
||||
) -> type[AttentionBackend]:
|
||||
"""Selects which attention backend to use and lazily imports it."""
|
||||
|
||||
if kv_cache_dtype is not None:
|
||||
valid_cache_dtypes = get_args(CacheDType)
|
||||
assert kv_cache_dtype in valid_cache_dtypes, (
|
||||
|
||||
+21
-18
@@ -31,8 +31,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class BlockHashToBlockMap:
|
||||
"""
|
||||
Cache of blocks that are used for prefix caching. It caches blocks
|
||||
"""Cache of blocks that are used for prefix caching. It caches blocks
|
||||
from hash directly to a block or multiple blocks
|
||||
(i.e. {block_hash: KVCacheBlocks})
|
||||
- Mostly block_hash maps to a single KVCacheBlock, and KVCacheBlocks
|
||||
@@ -59,9 +58,7 @@ class BlockHashToBlockMap:
|
||||
] = {}
|
||||
|
||||
def get_one_block(self, key: BlockHashWithGroupId) -> KVCacheBlock | None:
|
||||
"""
|
||||
Gets any block with the given block hash key.
|
||||
"""
|
||||
"""Gets any block with the given block hash key."""
|
||||
blocks = self._cache.get(key)
|
||||
if blocks is not None:
|
||||
if isinstance(blocks, KVCacheBlock):
|
||||
@@ -72,9 +69,7 @@ class BlockHashToBlockMap:
|
||||
return None
|
||||
|
||||
def contain(self, key: BlockHashWithGroupId, block_id: int) -> bool:
|
||||
"""
|
||||
Checks whether the key maps to the given block ID.
|
||||
"""
|
||||
"""Checks whether the key maps to the given block ID."""
|
||||
blocks = self._cache.get(key)
|
||||
if blocks is None:
|
||||
return False
|
||||
@@ -86,9 +81,7 @@ class BlockHashToBlockMap:
|
||||
return False
|
||||
|
||||
def insert(self, key: BlockHashWithGroupId, block: KVCacheBlock) -> None:
|
||||
"""
|
||||
Inserts the KVCacheBlock to the cache
|
||||
"""
|
||||
"""Inserts the KVCacheBlock to the cache"""
|
||||
blocks = self._cache.get(key)
|
||||
if blocks is None:
|
||||
# When key is not found, attach a single block to the key
|
||||
@@ -104,9 +97,7 @@ class BlockHashToBlockMap:
|
||||
self._unexpected_blocks_type(blocks)
|
||||
|
||||
def pop(self, key: BlockHashWithGroupId, block_id: int) -> KVCacheBlock | None:
|
||||
"""
|
||||
Checks if block_hash exists and pop block_id from the cache
|
||||
"""
|
||||
"""Checks if block_hash exists and pop block_id from the cache"""
|
||||
blocks = self._cache.pop(key, None)
|
||||
if blocks is None:
|
||||
# block_hash not found in the cache
|
||||
@@ -158,6 +149,7 @@ class BlockPool:
|
||||
enable_kv_cache_events: Whether to enable kv cache events.
|
||||
metrics_collector: Optional metrics collector for tracking block residency.
|
||||
medium: Storage medium reported in KV cache events.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -214,6 +206,7 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
The cached blocks if exists, or None.
|
||||
|
||||
"""
|
||||
cached_blocks = []
|
||||
for group_id in kv_cache_group_ids:
|
||||
@@ -261,6 +254,7 @@ class BlockPool:
|
||||
consults a subset of blocks (e.g. SWA tail-window), so blocks
|
||||
that can never serve a hit stay out of the prefix-cache hash
|
||||
map.
|
||||
|
||||
"""
|
||||
if num_cached_blocks >= num_full_blocks:
|
||||
return
|
||||
@@ -395,6 +389,7 @@ class BlockPool:
|
||||
num_cached_blocks: Number of blocks that were cache hits.
|
||||
block_size: Number of tokens per block.
|
||||
kv_cache_group_id: The KV cache group ID.
|
||||
|
||||
"""
|
||||
if not self.enable_kv_cache_events or num_cached_blocks == 0:
|
||||
return
|
||||
@@ -491,6 +486,7 @@ class BlockPool:
|
||||
Returns:
|
||||
The hash key with group ID if a partial entry can be registered;
|
||||
otherwise ``None`` for null blocks.
|
||||
|
||||
"""
|
||||
if block.is_null:
|
||||
return None
|
||||
@@ -671,6 +667,7 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
A list of new block.
|
||||
|
||||
"""
|
||||
if num_blocks > self.get_num_free_blocks():
|
||||
raise ValueError(f"Cannot get {num_blocks} free blocks from the pool")
|
||||
@@ -724,8 +721,7 @@ class BlockPool:
|
||||
self.free_block_queue.append_n(released)
|
||||
|
||||
def _maybe_evict_cached_block(self, block: KVCacheBlock) -> bool:
|
||||
"""
|
||||
If a block is cached in `cached_block_hash_to_block`, we reset its hash
|
||||
"""If a block is cached in `cached_block_hash_to_block`, we reset its hash
|
||||
metadata and evict it from the cache.
|
||||
|
||||
Args:
|
||||
@@ -733,6 +729,7 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
True if the block is evicted, False otherwise.
|
||||
|
||||
"""
|
||||
# Clean up metrics tracking first to prevent leaks
|
||||
if self.metrics_collector:
|
||||
@@ -753,6 +750,7 @@ class BlockPool:
|
||||
|
||||
Args:
|
||||
blocks: A list of blocks to touch.
|
||||
|
||||
"""
|
||||
for block in blocks:
|
||||
# ref_cnt=0 means this block is in the free list (i.e. eviction
|
||||
@@ -774,6 +772,7 @@ class BlockPool:
|
||||
Args:
|
||||
ordered_blocks: A list of blocks to free ordered by their eviction
|
||||
priority.
|
||||
|
||||
"""
|
||||
# Identify blocks with hash (LRU cache) and without it (never match APC)
|
||||
blocks_to_evict_last = []
|
||||
@@ -800,7 +799,7 @@ class BlockPool:
|
||||
pool.free_blocks(blocks)
|
||||
|
||||
def evict_blocks(self, block_ids: set[int]) -> None:
|
||||
"""evict blocks from the prefix cache by their block IDs.
|
||||
"""Evict blocks from the prefix cache by their block IDs.
|
||||
|
||||
only evicts blocks that are currently cached (have a hash). blocks
|
||||
with ref_cnt > 0 are not freed from the block pool, only evicted
|
||||
@@ -808,6 +807,7 @@ class BlockPool:
|
||||
|
||||
Args:
|
||||
block_ids: Set of block IDs to evict from cache.
|
||||
|
||||
"""
|
||||
for block_id in block_ids:
|
||||
assert block_id < len(self.blocks), (
|
||||
@@ -826,6 +826,7 @@ class BlockPool:
|
||||
Returns:
|
||||
bool: True if the prefix cache is successfully reset,
|
||||
False otherwise.
|
||||
|
||||
"""
|
||||
num_used_blocks = self.num_gpu_blocks - self.get_num_free_blocks()
|
||||
if num_used_blocks != 1: # The null block is always marked as used
|
||||
@@ -863,6 +864,7 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
The number of free blocks.
|
||||
|
||||
"""
|
||||
return self.free_block_queue.num_free_blocks
|
||||
|
||||
@@ -871,8 +873,8 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
The KV cache usage (between 0.0 and 1.0).
|
||||
"""
|
||||
|
||||
"""
|
||||
# Subtract 1 to account for null block.
|
||||
total_gpu_blocks = self.num_gpu_blocks - 1
|
||||
if not total_gpu_blocks:
|
||||
@@ -884,6 +886,7 @@ class BlockPool:
|
||||
|
||||
Returns:
|
||||
A list of KV cache events.
|
||||
|
||||
"""
|
||||
if not self.enable_kv_cache_events:
|
||||
return []
|
||||
|
||||
@@ -64,6 +64,7 @@ class EncoderCacheManager:
|
||||
make space when needed.
|
||||
freed: List of mm_hash strings that were actually evicted since the
|
||||
last call to get_freed_mm_hashes(). This list is cleared on return.
|
||||
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
@@ -113,6 +114,7 @@ class EncoderCacheManager:
|
||||
|
||||
Returns:
|
||||
True if the encoder output for this input is already cached
|
||||
|
||||
"""
|
||||
mm_hash = request.mm_features[input_id].identifier
|
||||
# Not cached at all
|
||||
@@ -162,6 +164,7 @@ class EncoderCacheManager:
|
||||
|
||||
Note: This method does not allocate physical memory for the encoder
|
||||
output but only the state of EncoderCacheManager.
|
||||
|
||||
"""
|
||||
num_embeds = request.get_num_encoder_embeds(input_id)
|
||||
|
||||
@@ -198,8 +201,8 @@ class EncoderCacheManager:
|
||||
|
||||
Note:
|
||||
This method assumes can_allocate() returned True for the same input.
|
||||
"""
|
||||
|
||||
"""
|
||||
mm_hash = request.mm_features[input_id].identifier
|
||||
request_id = request.request_id
|
||||
if mm_hash not in self.cached:
|
||||
@@ -222,7 +225,7 @@ class EncoderCacheManager:
|
||||
return self.request_cached_ids.get(request.request_id, set())
|
||||
|
||||
def free_encoder_input(self, request: Request, input_id: int) -> None:
|
||||
"""Free the request's reference to the encoder input (`mm_data`)
|
||||
"""Free the request's reference to the encoder input (`mm_data`).
|
||||
|
||||
When the reference set for the corresponding `mm_hash` becomes empty,
|
||||
the entry is appended to `freeable` and `num_freeable_slots` is
|
||||
@@ -279,6 +282,7 @@ class EncoderCacheManager:
|
||||
call to be used by the scheduler to notify workers about which
|
||||
encoder outputs can be removed from their caches. The internal
|
||||
list is cleared after this call.
|
||||
|
||||
"""
|
||||
# An entry evicted early in the scheduling pass can be allocated again
|
||||
# later in the same pass. Keep its worker-side tensor in that case.
|
||||
@@ -307,8 +311,8 @@ def compute_mm_encoder_budget(
|
||||
from the input sequence.
|
||||
- Space budget for encoder cache size, measured in number of tokens
|
||||
from the input sequence.
|
||||
"""
|
||||
|
||||
"""
|
||||
if not mm_max_toks_per_item:
|
||||
logger.warning(
|
||||
"All non-text modalities supported by the model have been "
|
||||
|
||||
@@ -64,9 +64,7 @@ def _validate_prefix_cache_retention_interval(
|
||||
|
||||
|
||||
class KVCacheCoordinator(ABC):
|
||||
"""
|
||||
Coordinate the KV cache of different KV cache groups.
|
||||
"""
|
||||
"""Coordinate the KV cache of different KV cache groups."""
|
||||
|
||||
enable_partial_hash_hits = False
|
||||
|
||||
@@ -179,8 +177,7 @@ class KVCacheCoordinator(ABC):
|
||||
num_tokens_main_model: int,
|
||||
apply_admission_cap: bool = False,
|
||||
) -> int:
|
||||
"""
|
||||
Get the number of device blocks needed to be allocated for the request.
|
||||
"""Get the number of device blocks needed to be allocated for the request.
|
||||
|
||||
Args:
|
||||
request_id: The request ID.
|
||||
@@ -203,6 +200,7 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
Returns:
|
||||
The number of blocks to allocate.
|
||||
|
||||
"""
|
||||
num_blocks_to_allocate = 0
|
||||
for i, manager in enumerate(self.single_type_managers):
|
||||
@@ -237,8 +235,7 @@ class KVCacheCoordinator(ABC):
|
||||
num_local_computed_tokens: int,
|
||||
num_external_computed_tokens: int,
|
||||
) -> None:
|
||||
"""
|
||||
Add the new computed blocks to the request. Optionally allocate new
|
||||
"""Add the new computed blocks to the request. Optionally allocate new
|
||||
blocks for external computed tokens (if any).
|
||||
|
||||
Args:
|
||||
@@ -247,6 +244,7 @@ class KVCacheCoordinator(ABC):
|
||||
prefix cache.
|
||||
num_local_computed_tokens: The number of local computed tokens.
|
||||
num_external_computed_tokens: The number of external computed tokens.
|
||||
|
||||
"""
|
||||
# A running request is already tracked in num_cached_block and won't
|
||||
# have new prefix-cache hits, so this is a no-op for it.
|
||||
@@ -283,8 +281,7 @@ class KVCacheCoordinator(ABC):
|
||||
num_tokens_main_model: int,
|
||||
num_encoder_tokens: int = 0,
|
||||
) -> tuple[list[KVCacheBlock], ...]:
|
||||
"""
|
||||
Allocate new blocks for the request to give it at least `num_tokens`
|
||||
"""Allocate new blocks for the request to give it at least `num_tokens`
|
||||
token slots.
|
||||
|
||||
Args:
|
||||
@@ -299,6 +296,7 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
Returns:
|
||||
The new allocated blocks.
|
||||
|
||||
"""
|
||||
return tuple(
|
||||
manager.allocate_new_blocks(
|
||||
@@ -333,14 +331,14 @@ class KVCacheCoordinator(ABC):
|
||||
return tuple(sorted({max(resend - block, 0), max(extension - block, 0)}))
|
||||
|
||||
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
|
||||
"""
|
||||
Cache the blocks for the request.
|
||||
"""Cache the blocks for the request.
|
||||
|
||||
Args:
|
||||
request: The request.
|
||||
num_computed_tokens: The total number of tokens
|
||||
that need to be cached
|
||||
(including tokens that are already cached).
|
||||
|
||||
"""
|
||||
boundaries = self.get_replay_boundaries(request)
|
||||
for manager in self.single_type_managers:
|
||||
@@ -380,18 +378,17 @@ class KVCacheCoordinator(ABC):
|
||||
return all([pool.reset_prefix_cache() for pool in pools])
|
||||
|
||||
def free(self, request_id: str) -> None:
|
||||
"""
|
||||
Free the blocks for the request.
|
||||
"""Free the blocks for the request.
|
||||
|
||||
Args:
|
||||
request_id: The request ID.
|
||||
|
||||
"""
|
||||
for manager in self.single_type_managers:
|
||||
manager.free(request_id)
|
||||
|
||||
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
|
||||
"""
|
||||
Pop the request's bookkeeping from all single-type managers and
|
||||
"""Pop the request's bookkeeping from all single-type managers and
|
||||
return its blocks without returning them to the block pool. The
|
||||
caller must eventually pass the returned blocks to
|
||||
`block_pool.free_blocks`, freeing them in reverse order (so that
|
||||
@@ -402,6 +399,7 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
Returns:
|
||||
The request's blocks in allocation order.
|
||||
|
||||
"""
|
||||
blocks: list[KVCacheBlock] = []
|
||||
for manager in self.single_type_managers:
|
||||
@@ -409,8 +407,7 @@ class KVCacheCoordinator(ABC):
|
||||
return blocks
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> list[int]:
|
||||
"""
|
||||
Get the number of common prefix blocks for all requests with allocated
|
||||
"""Get the number of common prefix blocks for all requests with allocated
|
||||
KV cache for each kv cache group.
|
||||
|
||||
Args:
|
||||
@@ -419,6 +416,7 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
Returns:
|
||||
list[int]: The number of common prefix blocks for each kv cache group.
|
||||
|
||||
"""
|
||||
return [
|
||||
manager.get_num_common_prefix_blocks(running_request_id)
|
||||
@@ -431,8 +429,7 @@ class KVCacheCoordinator(ABC):
|
||||
processed_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Remove the blocks that are no longer needed from `blocks` and replace
|
||||
"""Remove the blocks that are no longer needed from `blocks` and replace
|
||||
the removed blocks with null_block.
|
||||
|
||||
Args:
|
||||
@@ -442,6 +439,7 @@ class KVCacheCoordinator(ABC):
|
||||
num_prompt_tokens: Optional prompt length. R-SWA managers use this to
|
||||
free gap blocks between the prefill tail and decode window; other
|
||||
manager types ignore it.
|
||||
|
||||
"""
|
||||
for manager in self.single_type_managers:
|
||||
manager.remove_skipped_blocks(
|
||||
@@ -449,9 +447,7 @@ class KVCacheCoordinator(ABC):
|
||||
)
|
||||
|
||||
def get_blocks(self, request_id: str) -> tuple[list[KVCacheBlock], ...]:
|
||||
"""
|
||||
Get the blocks for the request.
|
||||
"""
|
||||
"""Get the blocks for the request."""
|
||||
return tuple(
|
||||
manager.req_to_blocks.get(request_id) or []
|
||||
for manager in self.single_type_managers
|
||||
@@ -465,7 +461,8 @@ class KVCacheCoordinator(ABC):
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
|
||||
"""Returns the per-group hit blocks, the hit length, and the number of
|
||||
``num_uncached_common_prefix_tokens`` (a shared prefix that a
|
||||
sparse-retention group has not cached yet; 0 unless hybrid)."""
|
||||
sparse-retention group has not cached yet; 0 unless hybrid).
|
||||
"""
|
||||
pass
|
||||
|
||||
def new_step_starts(self) -> None:
|
||||
@@ -475,8 +472,7 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
|
||||
class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
|
||||
"""
|
||||
KV cache coordinator to use if prefix caching is disabled or unsupported.
|
||||
"""KV cache coordinator to use if prefix caching is disabled or unsupported.
|
||||
In contrast to UnitaryKVCacheCoordinator and HybridKVCacheCoordinator,
|
||||
supports arbitrary numbers of KV cache groups (including 0 groups).
|
||||
Does not implement any features related to prefix caching.
|
||||
@@ -527,8 +523,7 @@ class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
|
||||
|
||||
|
||||
class UnitaryKVCacheCoordinator(KVCacheCoordinator):
|
||||
"""
|
||||
KV cache coordinator for models with only one KV cache group. This is the
|
||||
"""KV cache coordinator for models with only one KV cache group. This is the
|
||||
case for models with only one KV cache type, e.g., all attention layers use
|
||||
full attention or all attention layers use sliding window attention.
|
||||
"""
|
||||
@@ -613,8 +608,7 @@ class SpecGroup(NamedTuple):
|
||||
|
||||
|
||||
class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
"""
|
||||
KV cache coordinator for hybrid models with multiple KV cache types, and
|
||||
"""KV cache coordinator for hybrid models with multiple KV cache types, and
|
||||
thus multiple kv cache groups.
|
||||
"""
|
||||
|
||||
@@ -733,8 +727,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
)
|
||||
|
||||
def verify_and_split_kv_cache_groups(self) -> None:
|
||||
"""
|
||||
Groups KV cache groups by their spec type for efficient batch processing
|
||||
"""Groups KV cache groups by their spec type for efficient batch processing
|
||||
during cache hit lookup.
|
||||
"""
|
||||
self.attention_groups: list[SpecGroup] = []
|
||||
@@ -843,8 +836,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
block_hashes: list[BlockHash],
|
||||
max_cache_hit_length: int,
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
|
||||
"""
|
||||
Find the longest cache hit using an iterative fixed-point algorithm.
|
||||
"""Find the longest cache hit using an iterative fixed-point algorithm.
|
||||
|
||||
Each attention type either accepts the current candidate length or
|
||||
reduces it. If any type reduces the length, restart checks over all
|
||||
@@ -861,8 +853,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
- The number of tokens of the reconciled (combined) cache hit.
|
||||
- ``num_uncached_common_prefix_tokens``: a shared prefix that a
|
||||
sparse-retention group has not cached yet (0 unless hybrid).
|
||||
"""
|
||||
|
||||
"""
|
||||
num_groups = len(self.kv_cache_config.kv_cache_groups)
|
||||
hit_length = max_cache_hit_length
|
||||
longest_hit_length = 0
|
||||
@@ -985,8 +977,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
|
||||
Returns:
|
||||
(blocks_per_group, hit_lengths_per_group)
|
||||
"""
|
||||
|
||||
"""
|
||||
num_groups = len(self.kv_cache_config.kv_cache_groups)
|
||||
hit_blocks: list[list[KVCacheBlock]] = [[] for _ in range(num_groups)]
|
||||
hit_lengths: list[int] = [0] * num_groups
|
||||
|
||||
@@ -33,8 +33,7 @@ logger = init_logger(__name__)
|
||||
|
||||
@dataclass
|
||||
class KVCacheBlocks:
|
||||
"""
|
||||
The allocation result of KVCacheManager, work as the interface between
|
||||
"""The allocation result of KVCacheManager, work as the interface between
|
||||
Scheduler and KVCacheManager, to hide KVCacheManager's internal data
|
||||
structure from the Scheduler.
|
||||
"""
|
||||
@@ -85,8 +84,7 @@ class KVCacheBlocks:
|
||||
*,
|
||||
group_ids: Sequence[int] | None = None,
|
||||
) -> tuple[list[int], ...] | None:
|
||||
"""
|
||||
Converts the KVCacheBlocks instance to block_ids.
|
||||
"""Converts the KVCacheBlocks instance to block_ids.
|
||||
|
||||
Args:
|
||||
allow_none: Return None when every selected group is empty.
|
||||
@@ -97,6 +95,7 @@ class KVCacheBlocks:
|
||||
- the outer tuple corresponds to KV cache groups
|
||||
- each inner list contains the block_ids of the blocks in that
|
||||
group
|
||||
|
||||
"""
|
||||
groups = (
|
||||
self.blocks
|
||||
@@ -125,9 +124,7 @@ class KVCacheBlocks:
|
||||
]
|
||||
|
||||
def new_empty(self) -> "KVCacheBlocks":
|
||||
"""
|
||||
Creates a new KVCacheBlocks instance with no blocks.
|
||||
"""
|
||||
"""Creates a new KVCacheBlocks instance with no blocks."""
|
||||
return KVCacheBlocks(tuple(() for _ in range(len(self.blocks))))
|
||||
|
||||
|
||||
@@ -232,6 +229,7 @@ class KVCacheManager:
|
||||
|
||||
Returns:
|
||||
The KV cache usage (between 0.0 and 1.0).
|
||||
|
||||
"""
|
||||
return self.block_pool.get_usage()
|
||||
|
||||
@@ -240,6 +238,7 @@ class KVCacheManager:
|
||||
|
||||
Returns:
|
||||
The current prefix caching stats, or None if logging is disabled.
|
||||
|
||||
"""
|
||||
if not self.log_stats:
|
||||
return None
|
||||
@@ -278,6 +277,7 @@ class KVCacheManager:
|
||||
window) has not cached yet (Marconi-style APC), or 0 if none.
|
||||
Pinned so sparse prefix-cache retention does not drop
|
||||
the junction and defeat cross-request reuse.
|
||||
|
||||
"""
|
||||
# We skip finding the prefix cache hit when prefix caching is
|
||||
# disabled or the request is marked as skipping kv cache read
|
||||
@@ -340,6 +340,7 @@ class KVCacheManager:
|
||||
Returns:
|
||||
The ``get_computed_blocks`` triple (blocks, number of local computed
|
||||
tokens, shared-prefix boundary) plus ``hit_diverged``.
|
||||
|
||||
"""
|
||||
coordinator = self.coordinator
|
||||
if not (
|
||||
@@ -462,6 +463,7 @@ class KVCacheManager:
|
||||
|
||||
Returns:
|
||||
A list of new allocated blocks.
|
||||
|
||||
"""
|
||||
# When loading KV data asynchronously, we may have zero new tokens to
|
||||
# compute while still allocating slots for externally computed tokens.
|
||||
@@ -607,6 +609,7 @@ class KVCacheManager:
|
||||
|
||||
Args:
|
||||
request: The request to free the blocks.
|
||||
|
||||
"""
|
||||
self.coordinator.free(request.request_id)
|
||||
|
||||
@@ -624,6 +627,7 @@ class KVCacheManager:
|
||||
processed_computed_tokens: Computed-token prefix length covering
|
||||
fully processed and committed tokens only (safe to free).
|
||||
num_prompt_tokens: Optional prompt length for R-SWA gap eviction.
|
||||
|
||||
"""
|
||||
self.coordinator.remove_skipped_blocks(
|
||||
request_id, processed_computed_tokens, num_prompt_tokens
|
||||
@@ -639,14 +643,16 @@ class KVCacheManager:
|
||||
|
||||
Returns:
|
||||
The request's blocks in allocation order.
|
||||
|
||||
"""
|
||||
return self.coordinator.pop_blocks_for_free(request.request_id)
|
||||
|
||||
def evict_blocks(self, block_ids: set[int]) -> None:
|
||||
"""evict blocks from the prefix cache by their block IDs.
|
||||
"""Evict blocks from the prefix cache by their block IDs.
|
||||
|
||||
Args:
|
||||
block_ids: Set of block IDs to evict from cache.
|
||||
|
||||
"""
|
||||
self.block_pool.evict_blocks(block_ids)
|
||||
|
||||
@@ -658,6 +664,7 @@ class KVCacheManager:
|
||||
Returns:
|
||||
bool: True if the prefix cache is successfully reset,
|
||||
False otherwise.
|
||||
|
||||
"""
|
||||
if not self.coordinator.reset_prefix_cache():
|
||||
return False
|
||||
@@ -697,6 +704,7 @@ class KVCacheManager:
|
||||
Returns:
|
||||
list[int]: The number of common prefix blocks for each kv cache
|
||||
group.
|
||||
|
||||
"""
|
||||
return self.coordinator.get_num_common_prefix_blocks(running_request_id)
|
||||
|
||||
@@ -705,6 +713,7 @@ class KVCacheManager:
|
||||
|
||||
Returns:
|
||||
A list of KV cache events.
|
||||
|
||||
"""
|
||||
events = self.block_pool.take_events()
|
||||
for event in events:
|
||||
@@ -792,6 +801,7 @@ class KVCacheManager:
|
||||
request: The request to cache the blocks.
|
||||
num_computed_tokens: The number of computed tokens, including tokens
|
||||
that are already cached and tokens to be cached.
|
||||
|
||||
"""
|
||||
if self.enable_caching:
|
||||
self.coordinator.cache_blocks(request, num_computed_tokens)
|
||||
@@ -846,7 +856,8 @@ class KVCacheManager:
|
||||
self, request_id: str, start_token: int, end_token: int
|
||||
) -> list[int]:
|
||||
"""The request's block ids covering [start_token, end_token), from
|
||||
the groups whose new blocks are zeroed by the worker."""
|
||||
the groups whose new blocks are zeroed by the worker.
|
||||
"""
|
||||
ids: list[int] = []
|
||||
for mgr in self.coordinator.single_type_managers:
|
||||
if mgr.records_new_block_ids:
|
||||
|
||||
@@ -263,6 +263,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Args:
|
||||
blocks: A list of KVCacheBlock objects.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, blocks: list[KVCacheBlock]) -> None:
|
||||
@@ -300,6 +301,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Returns:
|
||||
The first free block.
|
||||
|
||||
"""
|
||||
if (
|
||||
self.fake_free_list_head.next_free_block is self.fake_free_list_tail
|
||||
@@ -340,6 +342,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Returns:
|
||||
A list of n free blocks.
|
||||
|
||||
"""
|
||||
if n == 0:
|
||||
return []
|
||||
@@ -370,6 +373,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Args:
|
||||
block: The block to remove.
|
||||
|
||||
"""
|
||||
if block.prev_free_block is None or block.next_free_block is None:
|
||||
# This should not happen if the block is from the free list.
|
||||
@@ -391,6 +395,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Args:
|
||||
block: The block to append.
|
||||
|
||||
"""
|
||||
if self.fake_free_list_tail.prev_free_block is None:
|
||||
raise RuntimeError(
|
||||
@@ -434,6 +439,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Args:
|
||||
blocks: The blocks to append.
|
||||
|
||||
"""
|
||||
if len(blocks) == 0:
|
||||
return
|
||||
@@ -459,6 +465,7 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
Returns:
|
||||
A list of free blocks.
|
||||
|
||||
"""
|
||||
ret = []
|
||||
if self.fake_free_list_head.next_free_block is None:
|
||||
@@ -505,6 +512,7 @@ def _gen_mm_extra_hash_keys(
|
||||
|
||||
Returns:
|
||||
A tuple of extra keys and the next multi-modal index.
|
||||
|
||||
"""
|
||||
extra_keys: list[Any] = []
|
||||
|
||||
@@ -565,6 +573,7 @@ def _gen_lora_extra_hash_keys(request: Request) -> list[str]:
|
||||
Returns:
|
||||
Return LoRA name of the request if it is a LoRA request. Return empty
|
||||
list otherwise.
|
||||
|
||||
"""
|
||||
if not request.lora_request:
|
||||
return []
|
||||
@@ -584,6 +593,7 @@ def _gen_prompt_embeds_extra_hash_keys(
|
||||
Returns:
|
||||
Return a stable hash of the block prompt embeddings if prompt embeds
|
||||
are present. Return empty list otherwise.
|
||||
|
||||
"""
|
||||
if request.prompt_embeds is None:
|
||||
return []
|
||||
@@ -612,6 +622,7 @@ def generate_block_hash_extra_keys(
|
||||
|
||||
Returns:
|
||||
A tuple of extra keys and the next multi-modal index.
|
||||
|
||||
"""
|
||||
mm_extra_keys: list[Any]
|
||||
mm_extra_keys, new_start_mm_idx = _gen_mm_extra_hash_keys(
|
||||
@@ -645,6 +656,7 @@ def hash_block_tokens(
|
||||
the contents of the preceding block(s). The hash value is used for
|
||||
prefix caching. We use LRU cache for this function to avoid recomputing
|
||||
hash values for the same block contents.
|
||||
|
||||
Args:
|
||||
hash_function: The hash function used to compute block hash.
|
||||
parent_block_hash: The hash of the parent block. None
|
||||
@@ -652,9 +664,11 @@ def hash_block_tokens(
|
||||
curr_block_token_ids: A list of token ids in the current
|
||||
block. The current block is assumed to be full.
|
||||
extra_keys: Extra keys for the block.
|
||||
|
||||
Returns:
|
||||
The hash value of the block and the token ids in the block.
|
||||
The entire tuple is used as the hash key of the block.
|
||||
|
||||
"""
|
||||
if not parent_block_hash:
|
||||
parent_block_hash = NONE_HASH
|
||||
@@ -813,8 +827,7 @@ def get_request_block_hasher(
|
||||
hash_block_size: int,
|
||||
caching_hash_fn: Callable[[Any], bytes],
|
||||
) -> Callable[[Request], list[BlockHash]]:
|
||||
"""
|
||||
Returns a function which computes the list of un-computed block hashes
|
||||
"""Returns a function which computes the list of un-computed block hashes
|
||||
of a request.
|
||||
|
||||
Hashes are computed at ``hash_block_size`` granularity and chained over the
|
||||
@@ -912,9 +925,7 @@ def _check_enough_kv_cache_memory(
|
||||
def max_memory_usage_bytes(
|
||||
vllm_config: VllmConfig, kv_cache_specs: Iterable[KVCacheSpec]
|
||||
) -> int:
|
||||
"""
|
||||
Get the maximum memory usage in bytes for the given KV cache specs.
|
||||
"""
|
||||
"""Get the maximum memory usage in bytes for the given KV cache specs."""
|
||||
return sum(spec.max_memory_usage_bytes(vllm_config) for spec in kv_cache_specs)
|
||||
|
||||
|
||||
@@ -923,8 +934,7 @@ def estimate_max_model_len(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
available_memory: int,
|
||||
) -> int:
|
||||
"""
|
||||
Estimates the maximum model length that can fit in the available memory
|
||||
"""Estimates the maximum model length that can fit in the available memory
|
||||
using binary search.
|
||||
|
||||
This function temporarily modifies max_model_len during estimation but
|
||||
@@ -937,6 +947,7 @@ def estimate_max_model_len(
|
||||
|
||||
Returns:
|
||||
The estimated maximum model length that can fit in the available memory.
|
||||
|
||||
"""
|
||||
# Save the original max_model_len to restore after estimation
|
||||
original_max_model_len = vllm_config.model_config.max_model_len
|
||||
@@ -977,8 +988,7 @@ def check_enough_kv_cache_memory(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
available_memory: int,
|
||||
):
|
||||
"""
|
||||
Checks whether `available_memory` is enough for the KV cache to hold at
|
||||
"""Checks whether `available_memory` is enough for the KV cache to hold at
|
||||
least one request with the model's max_model_len.
|
||||
|
||||
Args:
|
||||
@@ -988,8 +998,8 @@ def check_enough_kv_cache_memory(
|
||||
|
||||
Raises:
|
||||
ValueError: If there is not enough memory available for the KV cache.
|
||||
"""
|
||||
|
||||
"""
|
||||
# No need to check for available memory if the kv_cache_spec is empty
|
||||
if kv_cache_spec:
|
||||
# Reserve the null block BlockPool permanently holds back, so the check
|
||||
@@ -1012,8 +1022,7 @@ def check_enough_kv_cache_memory(
|
||||
def create_kv_cache_group_specs(
|
||||
kv_cache_spec: dict[str, KVCacheSpec], grouped_layer_names: list[list[str]]
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Create KVCacheGroupSpec object for each kv cache group layer.
|
||||
"""Create KVCacheGroupSpec object for each kv cache group layer.
|
||||
The layers in the same group should share the same
|
||||
KVCacheSpec.
|
||||
|
||||
@@ -1024,8 +1033,10 @@ def create_kv_cache_group_specs(
|
||||
A list of kv cache groups, where each element is a list of layer
|
||||
names that belong to the same group and should share the same
|
||||
KVCacheSpec.
|
||||
|
||||
Returns:
|
||||
A list of KVCacheGroupSpec objects, one for each group.
|
||||
|
||||
"""
|
||||
kv_cache_groups = []
|
||||
for layer_names_one_group in grouped_layer_names:
|
||||
@@ -1040,8 +1051,7 @@ def create_kv_cache_group_specs(
|
||||
|
||||
|
||||
def is_kv_cache_spec_uniform(kv_cache_spec: dict[str, KVCacheSpec]) -> bool:
|
||||
"""
|
||||
Whether all layers in the given KVCacheSpec have the same KV cache spec.
|
||||
"""Whether all layers in the given KVCacheSpec have the same KV cache spec.
|
||||
Note that we regard FullAttentionSpec with and without sliding window as
|
||||
the same type.
|
||||
|
||||
@@ -1050,8 +1060,8 @@ def is_kv_cache_spec_uniform(kv_cache_spec: dict[str, KVCacheSpec]) -> bool:
|
||||
|
||||
Returns:
|
||||
True if all layers have the same type, False otherwise.
|
||||
"""
|
||||
|
||||
"""
|
||||
if not kv_cache_spec:
|
||||
# Encoder-only models do not have KV cache, kv_cache_type can be
|
||||
# regarded as uniform.
|
||||
@@ -1067,8 +1077,7 @@ def is_kv_cache_spec_uniform(kv_cache_spec: dict[str, KVCacheSpec]) -> bool:
|
||||
def get_max_concurrency_for_kv_cache_config(
|
||||
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
) -> float:
|
||||
"""
|
||||
Get the maximum concurrency for the given KV cache configuration.
|
||||
"""Get the maximum concurrency for the given KV cache configuration.
|
||||
|
||||
A request at max_model_len consumes whole blocks from each group's block
|
||||
table — cdiv(per-request bytes, page bytes) of the group's spec — and all
|
||||
@@ -1101,8 +1110,7 @@ def get_max_concurrency_for_kv_cache_config(
|
||||
|
||||
|
||||
def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
|
||||
"""
|
||||
Override the number of kv cache blocks if `num_gpu_blocks_override` is set.
|
||||
"""Override the number of kv cache blocks if `num_gpu_blocks_override` is set.
|
||||
The override is logged once, at the call site in `get_kv_cache_configs`.
|
||||
"""
|
||||
if vllm_config.cache_config.num_gpu_blocks_override is not None:
|
||||
@@ -1111,8 +1119,7 @@ def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
|
||||
|
||||
|
||||
def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
|
||||
"""
|
||||
Bytes consumed by one block in the worker's shared KV cache pool, mirroring
|
||||
"""Bytes consumed by one block in the worker's shared KV cache pool, mirroring
|
||||
the divisor used by `get_kv_cache_config_from_groups` to convert
|
||||
`available_memory` into `num_blocks`. Used to compute the effective KV cache
|
||||
capacity once `num_gpu_blocks_override` is applied.
|
||||
@@ -1121,9 +1128,7 @@ def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
|
||||
|
||||
|
||||
def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
|
||||
"""
|
||||
Get the page size of the KV cache.
|
||||
"""
|
||||
"""Get the page size of the KV cache."""
|
||||
page_sizes = {layer.page_size_bytes for layer in kv_cache_specs}
|
||||
assert len(page_sizes) == 1
|
||||
return page_sizes.pop()
|
||||
@@ -1132,8 +1137,7 @@ def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
|
||||
def _get_kv_cache_groups_uniform_spec(
|
||||
kv_cache_specs: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Generates the KV cache configuration for a model with the same KV cache
|
||||
"""Generates the KV cache configuration for a model with the same KV cache
|
||||
spec for all layers.
|
||||
|
||||
Args:
|
||||
@@ -1141,16 +1145,15 @@ def _get_kv_cache_groups_uniform_spec(
|
||||
|
||||
Returns:
|
||||
The generated KVCacheGroupSpecs
|
||||
"""
|
||||
|
||||
"""
|
||||
return create_kv_cache_group_specs(kv_cache_specs, [list(kv_cache_specs.keys())])
|
||||
|
||||
|
||||
def _get_kv_cache_groups_uniform_type(
|
||||
spec: UniformTypeKVCacheSpecs,
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Generates the KV cache configuration for a model with one type of KV cache
|
||||
"""Generates the KV cache configuration for a model with one type of KV cache
|
||||
but different hidden sizes. All layers are merged into one group.
|
||||
|
||||
Args:
|
||||
@@ -1158,8 +1161,8 @@ def _get_kv_cache_groups_uniform_type(
|
||||
|
||||
Returns:
|
||||
The generated KVCacheGroupSpecs
|
||||
"""
|
||||
|
||||
"""
|
||||
return [KVCacheGroupSpec(list(spec.kv_cache_specs.keys()), spec)]
|
||||
|
||||
|
||||
@@ -1365,8 +1368,7 @@ def _glm5_next_tensor_layout(
|
||||
def unify_kv_cache_spec_page_size(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> dict[str, KVCacheSpec]:
|
||||
"""
|
||||
Unify the page size of the given KVCacheSpec. If the page size of all layers
|
||||
"""Unify the page size of the given KVCacheSpec. If the page size of all layers
|
||||
are the same, return the original KVCacheSpec. If not same, unify the page
|
||||
size by increasing the block size of layers with smaller page size. Two
|
||||
cases cannot be unified by block size alone and pad their physical page to
|
||||
@@ -1385,6 +1387,7 @@ def unify_kv_cache_spec_page_size(
|
||||
|
||||
Returns:
|
||||
The updated KVCacheSpec with the same page_size_bytes.
|
||||
|
||||
"""
|
||||
page_sizes = {layer.page_size_bytes for layer in kv_cache_spec.values()}
|
||||
if len(page_sizes) <= 1:
|
||||
@@ -1435,8 +1438,7 @@ def is_kv_cache_type_attention_free(kv_cache_spec: dict[str, KVCacheSpec]) -> bo
|
||||
def _get_kv_cache_groups_uniform_page_size(
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Generates the KV cache groups for hybrid models with multiple
|
||||
"""Generates the KV cache groups for hybrid models with multiple
|
||||
attention types but still with a uniform page size (physical memory per
|
||||
block per layer) for all layers.
|
||||
|
||||
@@ -1496,6 +1498,7 @@ def _get_kv_cache_groups_uniform_page_size(
|
||||
kv_cache_spec: The KVCacheSpec of each attention layer in the model
|
||||
Returns:
|
||||
The generated KVCacheGroupSpecs
|
||||
|
||||
"""
|
||||
# Group all layers by kv_cache_spec.
|
||||
# E.g., 2 full attention layers and 3 sliding window attention layers,
|
||||
@@ -1659,8 +1662,7 @@ def get_kv_cache_config_from_groups(
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
available_memory: int,
|
||||
) -> KVCacheConfig:
|
||||
"""
|
||||
Generate the KV cache configuration from the KV cache groups and spec
|
||||
"""Generate the KV cache configuration from the KV cache groups and spec
|
||||
of each layer.
|
||||
|
||||
Args:
|
||||
@@ -1669,6 +1671,7 @@ def get_kv_cache_config_from_groups(
|
||||
available_memory: Memory available for KV cache in bytes
|
||||
Returns:
|
||||
The generated KVCacheConfig
|
||||
|
||||
"""
|
||||
if len(kv_cache_groups) == 0:
|
||||
# Attention free models do not have KV cache.
|
||||
@@ -1926,15 +1929,14 @@ def _try_get_full_allocation_fallback_groups(
|
||||
|
||||
|
||||
def unify_hybrid_kv_cache_specs(kv_cache_spec: dict[str, KVCacheSpec]):
|
||||
"""
|
||||
This function tries to convert the KV cache specs to one type if the model
|
||||
"""This function tries to convert the KV cache specs to one type if the model
|
||||
is a hybrid model with multiple type of KV cache. It will convert all
|
||||
SlidingWindowSpec to FullAttentionSpec if both types are present.
|
||||
|
||||
Args:
|
||||
kv_cache_spec: The kv cache spec of each attention layer in the model
|
||||
"""
|
||||
|
||||
"""
|
||||
if is_kv_cache_spec_uniform(
|
||||
kv_cache_spec
|
||||
) or UniformTypeKVCacheSpecs.is_uniform_type(kv_cache_spec):
|
||||
@@ -2166,6 +2168,7 @@ def _annotate_eagle_groups(
|
||||
kv_cache_groups: Groups to annotate in place.
|
||||
use_deepseek_v4_fallback: Enable rule 2 for a DeepseekV4/V4.1 packed
|
||||
group.
|
||||
|
||||
"""
|
||||
spec_config = vllm_config.speculative_config
|
||||
if spec_config is None or not spec_config.use_eagle_block_drop():
|
||||
@@ -2196,6 +2199,7 @@ def _warn_if_unannotated_eagle_mamba(
|
||||
Args:
|
||||
vllm_config: Config supplying the speculative method, if any.
|
||||
kv_cache_groups: Groups as they will be handed to consumers.
|
||||
|
||||
"""
|
||||
spec_config = vllm_config.speculative_config
|
||||
if spec_config is None or not spec_config.use_eagle():
|
||||
@@ -2262,8 +2266,7 @@ def get_kv_cache_groups(
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Split the layers in the model into groups with the same KV cache spec.
|
||||
"""Split the layers in the model into groups with the same KV cache spec.
|
||||
|
||||
Args:
|
||||
vllm_config: The global VllmConfig
|
||||
@@ -2271,6 +2274,7 @@ def get_kv_cache_groups(
|
||||
|
||||
Returns:
|
||||
The generated KVCacheGroups
|
||||
|
||||
"""
|
||||
if vllm_config.scheduler_config.disable_hybrid_kv_cache_manager:
|
||||
unify_hybrid_kv_cache_specs(kv_cache_spec)
|
||||
@@ -2356,9 +2360,7 @@ def get_kv_cache_groups(
|
||||
def generate_scheduler_kv_cache_config(
|
||||
kv_cache_configs: list[KVCacheConfig],
|
||||
) -> KVCacheConfig:
|
||||
"""
|
||||
Generate the KV cache configuration for the scheduler.
|
||||
"""
|
||||
"""Generate the KV cache configuration for the scheduler."""
|
||||
assert all(
|
||||
[cfg.num_blocks == kv_cache_configs[0].num_blocks for cfg in kv_cache_configs]
|
||||
)
|
||||
@@ -2382,9 +2384,7 @@ def generate_scheduler_kv_cache_config(
|
||||
def get_kv_cache_capacity(
|
||||
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
) -> tuple[int, float]:
|
||||
"""
|
||||
Get the group-aware KV cache token capacity and max concurrency.
|
||||
"""
|
||||
"""Get the group-aware KV cache token capacity and max concurrency."""
|
||||
max_model_len = vllm_config.model_config.max_model_len
|
||||
max_concurrency = get_max_concurrency_for_kv_cache_config(
|
||||
vllm_config, kv_cache_config
|
||||
@@ -2415,8 +2415,7 @@ def _max_memory_usage_bytes_from_groups(
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
) -> int:
|
||||
"""
|
||||
Calculate maximum memory usage in bytes from KV cache groups.
|
||||
"""Calculate maximum memory usage in bytes from KV cache groups.
|
||||
|
||||
This correctly accounts for padding in hybrid models. For example, if a
|
||||
model has 8 full attention layers and 9 sliding window layers, they will
|
||||
@@ -2475,8 +2474,7 @@ def _estimate_max_model_len_from_groups(
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
available_memory: int,
|
||||
) -> int:
|
||||
"""
|
||||
Binary search for the maximum model length that fits in available memory.
|
||||
"""Binary search for the maximum model length that fits in available memory.
|
||||
Returns 0 if even 1 token doesn't fit.
|
||||
"""
|
||||
original_max = vllm_config.model_config.max_model_len
|
||||
@@ -2522,8 +2520,7 @@ def _auto_fit_max_model_len(
|
||||
projected_groups_per_worker: list[list[KVCacheGroupSpec]],
|
||||
available_memory: list[int],
|
||||
) -> None:
|
||||
"""
|
||||
When max_model_len is set to -1, this function estimates the largest
|
||||
"""When max_model_len is set to -1, this function estimates the largest
|
||||
context length that can be supported with the available GPU memory.
|
||||
It uses binary search to find the maximum length that fits across all
|
||||
workers.
|
||||
@@ -2533,6 +2530,7 @@ def _auto_fit_max_model_len(
|
||||
projected_groups_per_worker: KV cache groups projected to each worker.
|
||||
available_memory: Memory available for KV cache in bytes for each
|
||||
worker.
|
||||
|
||||
"""
|
||||
original_max = vllm_config.model_config.max_model_len
|
||||
|
||||
@@ -2585,8 +2583,7 @@ def _project_kv_cache_groups_to_worker(
|
||||
global_kv_cache_groups: list[KVCacheGroupSpec],
|
||||
worker_spec: dict[str, KVCacheSpec],
|
||||
) -> list[KVCacheGroupSpec]:
|
||||
"""
|
||||
Projects global KV cache groups onto a single worker's assigned layers.
|
||||
"""Projects global KV cache groups onto a single worker's assigned layers.
|
||||
|
||||
In pipeline parallelism, each worker only owns a subset of layers. This
|
||||
function filters the global groups to include only layers present on the
|
||||
@@ -2598,6 +2595,7 @@ def _project_kv_cache_groups_to_worker(
|
||||
|
||||
Returns:
|
||||
The projected KV cache groups containing only this worker's layers.
|
||||
|
||||
"""
|
||||
projected_groups: list[KVCacheGroupSpec] = []
|
||||
for group in global_kv_cache_groups:
|
||||
@@ -2628,8 +2626,7 @@ def get_kv_cache_configs(
|
||||
kv_cache_specs: list[dict[str, KVCacheSpec]],
|
||||
available_memory: list[int],
|
||||
) -> list[KVCacheConfig]:
|
||||
"""
|
||||
Generates the KV cache configurations for a model.
|
||||
"""Generates the KV cache configurations for a model.
|
||||
Since we use a shared centralized controller for all workers, we need the
|
||||
`kv_cache_config` to be consistent across all workers to make sure
|
||||
the KV cache allocation can be applied to all workers. However, different
|
||||
@@ -2656,8 +2653,8 @@ def get_kv_cache_configs(
|
||||
|
||||
Returns:
|
||||
The generated KVCacheConfigs for each worker.
|
||||
"""
|
||||
|
||||
"""
|
||||
# Merge the KV cache specs of all workers. Different PP stages may have
|
||||
# different layer names, and different TP ranks of the same PP stage should
|
||||
# have the same KV cache spec.
|
||||
@@ -2778,8 +2775,7 @@ def get_kv_cache_configs(
|
||||
|
||||
|
||||
class BlockHashListWithBlockSize:
|
||||
"""
|
||||
Convert block-hash granularity from `hash_block_size` to `target_block_size`.
|
||||
"""Convert block-hash granularity from `hash_block_size` to `target_block_size`.
|
||||
Used when KV cache groups have different block sizes: `hash_block_size`
|
||||
is the size used to compute the original `block_hashes`; `target_block_size`
|
||||
is the group's actual block size.
|
||||
@@ -2809,6 +2805,7 @@ class BlockHashListWithBlockSize:
|
||||
block_hashes: Block hashes to convert, computed at `hash_block_size`.
|
||||
hash_block_size: Block size at which `block_hashes` were computed.
|
||||
target_block_size: Desired block size; must be a multiple of `hash_block_size`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -79,6 +79,7 @@ class SchedulerInterface(ABC):
|
||||
Returns:
|
||||
A SchedulerOutput object containing information about the scheduled
|
||||
requests.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -105,6 +106,7 @@ class SchedulerInterface(ABC):
|
||||
Returns:
|
||||
A dict of client index to EngineCoreOutputs object containing the
|
||||
outputs for each request originating from that client.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -115,6 +117,7 @@ class SchedulerInterface(ABC):
|
||||
|
||||
Args:
|
||||
draft_token_ids: The input draft token ids for each request.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -129,6 +132,7 @@ class SchedulerInterface(ABC):
|
||||
draft_token_ids: The input draft token ids for each request.
|
||||
scheduler_output: Update the given scheduler_output
|
||||
with the corresponding draft token ids.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -138,6 +142,7 @@ class SchedulerInterface(ABC):
|
||||
|
||||
Args:
|
||||
request: The new request being added.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -162,6 +167,7 @@ class SchedulerInterface(ABC):
|
||||
Returns:
|
||||
List of requests that were aborted. Will not include any that were
|
||||
already finished.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -172,7 +178,8 @@ class SchedulerInterface(ABC):
|
||||
|
||||
def has_unfinished_requests(self) -> bool:
|
||||
"""Returns True if there are unfinished requests in the scheduler's
|
||||
internal queue."""
|
||||
internal queue.
|
||||
"""
|
||||
return self.get_num_unfinished_requests() > 0
|
||||
|
||||
@abstractmethod
|
||||
@@ -192,7 +199,8 @@ class SchedulerInterface(ABC):
|
||||
|
||||
def has_requests(self) -> bool:
|
||||
"""Returns True if there are unfinished requests, or finished requests
|
||||
not yet returned in SchedulerOutputs."""
|
||||
not yet returned in SchedulerOutputs.
|
||||
"""
|
||||
return self.has_unfinished_requests() or self.has_finished_requests()
|
||||
|
||||
@property
|
||||
@@ -218,6 +226,8 @@ class SchedulerInterface(ABC):
|
||||
preempted and moved to the waiting queue. Otherwise, this method
|
||||
will only reset the KV prefix cache when there is no running request
|
||||
taking KV cache.
|
||||
reset_connector: If True, also reset any KV connector state.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ class RequestQueue(ABC):
|
||||
@abstractmethod
|
||||
def prepend_requests(self, requests: "RequestQueue") -> None:
|
||||
"""Prepend all requests from another queue to the front of this
|
||||
queue."""
|
||||
queue.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -129,8 +130,7 @@ class FCFSRequestQueue(deque[Request], RequestQueue):
|
||||
|
||||
|
||||
class PriorityRequestQueue(RequestQueue):
|
||||
"""
|
||||
A priority queue that supports heap operations.
|
||||
"""A priority queue that supports heap operations.
|
||||
|
||||
Respects the ordering defined in the Request class, where
|
||||
requests with a smaller value of `priority` are processed first.
|
||||
@@ -161,14 +161,16 @@ class PriorityRequestQueue(RequestQueue):
|
||||
"""Add a request to the queue according to priority policy.
|
||||
|
||||
Note: In a priority queue, there is no concept of prepending to the
|
||||
front. Requests are ordered by (priority, arrival_time)."""
|
||||
front. Requests are ordered by (priority, arrival_time).
|
||||
"""
|
||||
self.add_request(request)
|
||||
|
||||
def prepend_requests(self, requests: RequestQueue) -> None:
|
||||
"""Add all requests from another queue according to priority policy.
|
||||
|
||||
Note: In a priority queue, there is no concept of prepending to the
|
||||
front. Requests are ordered by (priority, arrival_time)."""
|
||||
front. Requests are ordered by (priority, arrival_time).
|
||||
"""
|
||||
for request in requests:
|
||||
self.add_request(request)
|
||||
|
||||
|
||||
@@ -1558,12 +1558,10 @@ class Scheduler(SchedulerInterface):
|
||||
def _update_request_as_session(
|
||||
self, session: Request, update: StreamingUpdate
|
||||
) -> None:
|
||||
"""
|
||||
Updates the waiting session with the next streaming update.
|
||||
"""Updates the waiting session with the next streaming update.
|
||||
|
||||
Discards the last sampled output token from the prior input chunk.
|
||||
"""
|
||||
|
||||
# Current streaming input behaviour: Keep only computed output tokens
|
||||
# (discard final sampled output token).
|
||||
num_computed_tokens = session.num_computed_tokens
|
||||
@@ -1665,8 +1663,7 @@ class Scheduler(SchedulerInterface):
|
||||
encoder_compute_budget: int,
|
||||
shift_computed_tokens: int = 0,
|
||||
) -> tuple[list[int], int, int, list[int]]:
|
||||
"""
|
||||
Determine which encoder inputs need to be scheduled in the current step,
|
||||
"""Determine which encoder inputs need to be scheduled in the current step,
|
||||
and update `num_new_tokens` and encoder token budget accordingly.
|
||||
|
||||
An encoder input will be scheduled if:
|
||||
@@ -2507,6 +2504,7 @@ class Scheduler(SchedulerInterface):
|
||||
Returns:
|
||||
List of requests that were aborted. Will not include any that were
|
||||
already finished.
|
||||
|
||||
"""
|
||||
assert RequestStatus.is_finished(finished_status)
|
||||
if isinstance(request_ids, str):
|
||||
@@ -2841,8 +2839,7 @@ class Scheduler(SchedulerInterface):
|
||||
def _connector_finished(
|
||||
self, request: Request
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
"""
|
||||
Invoke the KV connector request_finished() method if applicable.
|
||||
"""Invoke the KV connector request_finished() method if applicable.
|
||||
|
||||
Returns optional kv transfer parameters to be included with the
|
||||
request outputs.
|
||||
@@ -2910,14 +2907,12 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
def _inflight_prefill_reserved_blocks(self) -> int:
|
||||
"""Num blocks in-flight prefills still need to finish (their reservation)."""
|
||||
|
||||
return sum(
|
||||
self._request_remaining_blocks(req) for req in self._inflight_prefills
|
||||
)
|
||||
|
||||
def _update_waiting_for_remote_kv(self, request: Request) -> None:
|
||||
"""
|
||||
KV Connector: update request state after async recv is finished.
|
||||
"""KV Connector: update request state after async recv is finished.
|
||||
|
||||
When the kv transfer is ready, we cache the blocks
|
||||
and the request state will be moved back to WAITING from
|
||||
@@ -2959,9 +2954,7 @@ class Scheduler(SchedulerInterface):
|
||||
self.finished_recving_kv_req_ids.remove(request.request_id)
|
||||
|
||||
def _try_promote_blocked_waiting_request(self, request: Request) -> bool:
|
||||
"""
|
||||
Try to promote a blocked waiting request back to schedulable states.
|
||||
"""
|
||||
"""Try to promote a blocked waiting request back to schedulable states."""
|
||||
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
# finished_recving_kv_req_ids is populated during
|
||||
# update_from_output(), based on worker-side connector signals
|
||||
@@ -2995,8 +2988,7 @@ class Scheduler(SchedulerInterface):
|
||||
)
|
||||
|
||||
def _update_from_kv_xfer_finished(self, kv_connector_output: KVConnectorOutput):
|
||||
"""
|
||||
KV Connector: update the scheduler state based on the output.
|
||||
"""KV Connector: update the scheduler state based on the output.
|
||||
|
||||
The Worker side connectors add finished_recving and
|
||||
finished_sending reqs to the output.
|
||||
@@ -3004,7 +2996,6 @@ class Scheduler(SchedulerInterface):
|
||||
# if finished_recving: add to state so we can
|
||||
schedule the request during the next step.
|
||||
"""
|
||||
|
||||
if self.connector is not None:
|
||||
self.connector.update_connector_output(kv_connector_output)
|
||||
|
||||
@@ -3030,8 +3021,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
evict_blocks: bool = True,
|
||||
) -> tuple[set[str], int, set[int]]:
|
||||
"""
|
||||
Identify and update requests affected by invalid KV cache blocks.
|
||||
"""Identify and update requests affected by invalid KV cache blocks.
|
||||
|
||||
This method scans the given requests, detects those with invalid blocks
|
||||
and adjusts their `num_computed_tokens` to the longest valid prefix.
|
||||
@@ -3053,6 +3043,7 @@ class Scheduler(SchedulerInterface):
|
||||
be recomputed across all affected requests.
|
||||
- blocks_to_evict (set[int]): Block IDs to evict from cache,
|
||||
including invalid blocks and downstream dependent blocks.
|
||||
|
||||
"""
|
||||
affected_req_ids: set[str] = set()
|
||||
total_affected_tokens = 0
|
||||
@@ -3145,11 +3136,11 @@ class Scheduler(SchedulerInterface):
|
||||
def _handle_invalid_blocks(
|
||||
self, invalid_block_ids: set[int], num_scheduled_tokens: dict[str, int]
|
||||
) -> set[str]:
|
||||
"""
|
||||
Handle requests affected by invalid KV cache blocks.
|
||||
"""Handle requests affected by invalid KV cache blocks.
|
||||
|
||||
Returns:
|
||||
Set of affected request IDs to skip in update_from_output main loop.
|
||||
|
||||
"""
|
||||
if len(self.kv_cache_config.kv_cache_groups) > 1:
|
||||
# Block IDs are only unique within a group, so a flat set of
|
||||
|
||||
@@ -30,11 +30,14 @@ def check_sequence_repetition(
|
||||
params: RepetitionDetectionParams,
|
||||
) -> bool:
|
||||
"""Check if a sequence of token IDs has a repetition pattern.
|
||||
|
||||
Args:
|
||||
token_ids: List of token IDs
|
||||
params: Repetition detection parameters.
|
||||
|
||||
Returns:
|
||||
True if a repetition pattern is found, False otherwise.
|
||||
|
||||
"""
|
||||
max_pattern_size = params.max_pattern_size
|
||||
min_pattern_size = params.min_pattern_size
|
||||
@@ -77,6 +80,7 @@ def remove_all(lst: list, items_to_remove: set) -> list:
|
||||
Note:
|
||||
For single item removal, this modifies the original list in-place
|
||||
and returns it. For multiple items, it creates and returns a new list.
|
||||
|
||||
"""
|
||||
if not items_to_remove:
|
||||
return lst
|
||||
|
||||
@@ -49,8 +49,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SingleTypeKVCacheManager(ABC):
|
||||
"""
|
||||
An abstract base class for a manager that handle the kv cache management
|
||||
"""An abstract base class for a manager that handle the kv cache management
|
||||
logic of one specific type of attention layer.
|
||||
"""
|
||||
|
||||
@@ -81,14 +80,17 @@ class SingleTypeKVCacheManager(ABC):
|
||||
needs_kv_cache_zeroing: bool = False,
|
||||
max_admission_blocks_per_request: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Initializes the SingleTypeKVCacheManager.
|
||||
"""Initializes the SingleTypeKVCacheManager.
|
||||
|
||||
Args:
|
||||
kv_cache_spec: The kv_cache_spec for this manager.
|
||||
block_pool: The block pool.
|
||||
enable_caching: Whether prefix caching is enabled.
|
||||
kv_cache_group_id: The id of the kv cache group of this manager.
|
||||
scheduler_block_size: The scheduling granularity (LCM of all group
|
||||
block sizes); a multiple of this manager's ``block_size``.
|
||||
dcp_world_size: Decode context parallel world size.
|
||||
pcp_world_size: Prefill context parallel world size.
|
||||
needs_kv_cache_zeroing: Whether worker-side KV cache zeroing needs
|
||||
newly allocated block IDs from this manager.
|
||||
max_admission_blocks_per_request: Recycling-aware per-request
|
||||
@@ -97,6 +99,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
chunked-local); `None` (the default) means no cap, which is
|
||||
correct for full-attention-style specs that hold every
|
||||
block until the request finishes.
|
||||
|
||||
"""
|
||||
self.scheduler_block_size = scheduler_block_size
|
||||
# Hybrid fine-grained lookup may lower this after all participating
|
||||
@@ -184,8 +187,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_tokens_main_model: int,
|
||||
apply_admission_cap: bool = False,
|
||||
) -> int:
|
||||
"""
|
||||
Get the number of blocks needed to be allocated for the request.
|
||||
"""Get the number of blocks needed to be allocated for the request.
|
||||
|
||||
Args:
|
||||
request_id: The request ID.
|
||||
@@ -206,8 +208,8 @@ class SingleTypeKVCacheManager(ABC):
|
||||
|
||||
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:
|
||||
# Recycling-aware specs (SWA, chunked-local) cap the per-request
|
||||
@@ -269,8 +271,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_local_computed_tokens: int,
|
||||
num_external_computed_tokens: int,
|
||||
) -> None:
|
||||
"""
|
||||
Add the locally cached (prefix-hit) blocks to the request:
|
||||
"""Add the locally cached (prefix-hit) blocks to the request:
|
||||
1. Touch the computed blocks (paired with adding them to `req_blocks`)
|
||||
so their ref_cnt exactly tracks the referencing requests.
|
||||
1.5. (Optional) For sliding window, skipped blocks are padded with nulls.
|
||||
@@ -282,6 +283,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
prefix cache.
|
||||
num_local_computed_tokens: The number of local computed tokens.
|
||||
num_external_computed_tokens: The number of external computed tokens.
|
||||
|
||||
"""
|
||||
# The coordinator only calls this for first-time allocations (running
|
||||
# requests are short-circuited there), so the request has no blocks yet.
|
||||
@@ -327,8 +329,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_local_computed_tokens: int,
|
||||
num_external_computed_tokens: int,
|
||||
) -> None:
|
||||
"""
|
||||
Allocate new blocks for external (KV-connector) computed tokens.
|
||||
"""Allocate new blocks for external (KV-connector) computed tokens.
|
||||
|
||||
Must run only after every group's local blocks have been touched via
|
||||
`add_local_computed_blocks`, so this group's `get_new_blocks` cannot
|
||||
@@ -338,6 +339,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
request_id: The request ID.
|
||||
num_local_computed_tokens: The number of local computed tokens.
|
||||
num_external_computed_tokens: The number of external computed tokens.
|
||||
|
||||
"""
|
||||
num_total_computed_tokens = (
|
||||
num_local_computed_tokens + num_external_computed_tokens
|
||||
@@ -364,8 +366,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
def allocate_new_blocks(
|
||||
self, request_id: str, num_tokens: int, num_tokens_main_model: int
|
||||
) -> list[KVCacheBlock]:
|
||||
"""
|
||||
Allocate new blocks for the request to give it at least `num_tokens`
|
||||
"""Allocate new blocks for the request to give it at least `num_tokens`
|
||||
token slots.
|
||||
|
||||
Args:
|
||||
@@ -375,8 +376,10 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_tokens_main_model: The number of tokens for the main model (aka target
|
||||
model in spec decode). w/o spec decode, it is num_tokens;
|
||||
with spec decode, it is num_tokens - num_lookahead_tokens.
|
||||
|
||||
Returns:
|
||||
The new allocated blocks.
|
||||
|
||||
"""
|
||||
cow_blocks: list[KVCacheBlock] = []
|
||||
if request_id in self._partial_hit_reqs:
|
||||
@@ -475,8 +478,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
*,
|
||||
replay_boundaries: Sequence[int],
|
||||
) -> None:
|
||||
"""
|
||||
Cache the blocks for the request.
|
||||
"""Cache the blocks for the request.
|
||||
|
||||
Args:
|
||||
request: The request.
|
||||
@@ -488,6 +490,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
a tail once per that-sized segment. Only SWA acts on it.
|
||||
replay_boundaries: Positions a later request replaying this prompt
|
||||
can resume at, from ``get_replay_boundaries``.
|
||||
|
||||
"""
|
||||
num_cached_blocks = self.num_cached_block.get(request.request_id, 0)
|
||||
num_full_blocks = num_tokens // self.block_size
|
||||
@@ -552,8 +555,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
return None
|
||||
|
||||
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
|
||||
"""
|
||||
Pop the request's bookkeeping and return its blocks without yet
|
||||
"""Pop the request's bookkeeping and return its blocks without yet
|
||||
returning them to the block pool. The caller is responsible for
|
||||
eventually passing the returned blocks to `block_pool.free_blocks`,
|
||||
freeing them in reverse order (so that tail blocks are evicted first).
|
||||
@@ -563,6 +565,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
|
||||
Returns:
|
||||
The request's blocks in allocation order.
|
||||
|
||||
"""
|
||||
# Default to [] in case a request is freed (aborted) before alloc.
|
||||
req_blocks = self.req_to_blocks.pop(request_id, [])
|
||||
@@ -571,19 +574,18 @@ class SingleTypeKVCacheManager(ABC):
|
||||
return req_blocks
|
||||
|
||||
def free(self, request_id: str) -> None:
|
||||
"""
|
||||
Free the blocks for the request.
|
||||
"""Free the blocks for the request.
|
||||
|
||||
Args:
|
||||
request_id: The request ID.
|
||||
|
||||
"""
|
||||
# Free blocks in reverse order so that the tail blocks are freed first.
|
||||
self.block_pool.free_blocks(reversed(self.pop_blocks_for_free(request_id)))
|
||||
|
||||
@abstractmethod
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""
|
||||
Get the number of common prefix blocks for all requests with allocated
|
||||
"""Get the number of common prefix blocks for all requests with allocated
|
||||
KV cache.
|
||||
|
||||
Args:
|
||||
@@ -592,8 +594,8 @@ class SingleTypeKVCacheManager(ABC):
|
||||
Returns:
|
||||
The number of common prefix blocks for all requests with allocated
|
||||
KV cache.
|
||||
"""
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
@@ -610,8 +612,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
dcp_world_size: int = 1,
|
||||
pcp_world_size: int = 1,
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int]:
|
||||
"""
|
||||
Get the longest cache hit prefix of the blocks that is not longer than
|
||||
"""Get the longest cache hit prefix of the blocks that is not longer than
|
||||
`max_length`. The prefix should be a common prefix hit for all the
|
||||
kv cache groups in `kv_cache_group_ids`. If no cache hit is found,
|
||||
return an empty list.
|
||||
@@ -647,8 +648,8 @@ class SingleTypeKVCacheManager(ABC):
|
||||
For example, sliding window manager should return a list like
|
||||
([NULL, NULL, KVCacheBlock(7), KVCacheBlock(8)]) for block size 4
|
||||
and sliding window 8 and len(kv_cache_group_ids) = 1.
|
||||
"""
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _remove_blocks_in_range(
|
||||
@@ -684,8 +685,8 @@ class SingleTypeKVCacheManager(ABC):
|
||||
processed_computed_tokens: int,
|
||||
num_prompt_tokens: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Remove and free the blocks that are no longer needed for attention computation.
|
||||
"""Remove and free blocks no longer needed for attention computation.
|
||||
|
||||
The removed blocks should be replaced by null_block.
|
||||
|
||||
This function depends on `get_num_skipped_tokens`, which need to be implemented
|
||||
@@ -698,6 +699,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
num_prompt_tokens: Optional prompt length for attention types (e.g.
|
||||
R-SWA) that evict a middle gap rather than a head prefix. Ignored
|
||||
by the default implementation.
|
||||
|
||||
"""
|
||||
del num_prompt_tokens
|
||||
# Remove the blocks that will be skipped during attention computation.
|
||||
@@ -718,14 +720,14 @@ class SingleTypeKVCacheManager(ABC):
|
||||
self._remove_blocks_in_range(request_id, 0, num_skipped_blocks)
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
"""
|
||||
Get the number of tokens that will be skipped for attention computation.
|
||||
"""Get the number of tokens that will be skipped for attention computation.
|
||||
|
||||
Args:
|
||||
num_computed_tokens: The number of tokens that have been computed.
|
||||
|
||||
Returns:
|
||||
The number of tokens that will be skipped for attention computation.
|
||||
|
||||
"""
|
||||
# The default behavior is to not skip any tokens.
|
||||
return 0
|
||||
@@ -1144,8 +1146,7 @@ class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
return mask
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
"""
|
||||
Get the number of tokens that will be skipped for attention computation.
|
||||
"""Get the number of tokens that will be skipped for attention computation.
|
||||
|
||||
For sliding window, this corresponds to the tokens that are prior to
|
||||
the current sliding window.
|
||||
@@ -1174,6 +1175,7 @@ class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
|
||||
Returns:
|
||||
The number of tokens that will be skipped for attention computation.
|
||||
|
||||
"""
|
||||
return max(
|
||||
0,
|
||||
@@ -1181,8 +1183,7 @@ class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
)
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""
|
||||
NOTE(Chen): The prefix blocks are null blocks for sliding window layers.
|
||||
"""NOTE(Chen): The prefix blocks are null blocks for sliding window layers.
|
||||
So it's not correct to count ref_cnt like FullAttentionManager. Return
|
||||
0 here for correctness. Need to support cascade attention + sliding
|
||||
window in the future.
|
||||
@@ -1301,8 +1302,7 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
dcp_world_size: int = 1,
|
||||
pcp_world_size: int = 1,
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int]:
|
||||
"""
|
||||
For chunked local attention, we need to find the longest cache hit
|
||||
"""For chunked local attention, we need to find the longest cache hit
|
||||
prefix of the blocks that is not longer than `max_length`. The prefix
|
||||
should be a common prefix hit for all the kv cache groups in
|
||||
`kv_cache_group_ids`. If no cache hit is found, return an empty list.
|
||||
@@ -1335,6 +1335,7 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
|
||||
Returns:
|
||||
A list of cached blocks
|
||||
|
||||
"""
|
||||
assert isinstance(kv_cache_spec, ChunkedLocalAttentionSpec), (
|
||||
"ChunkedLocalAttentionManager can only be used for "
|
||||
@@ -1389,8 +1390,7 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
return computed_blocks, hit_length
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
"""
|
||||
Get the number of tokens that will be skipped for attention computation.
|
||||
"""Get the number of tokens that will be skipped for attention computation.
|
||||
|
||||
For chunked local attention, this corresponds to the tokens that are on
|
||||
the left side of the current chunk.
|
||||
@@ -1428,6 +1428,7 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
|
||||
Returns:
|
||||
The number of tokens that will be skipped for attention computation.
|
||||
|
||||
"""
|
||||
num_skipped_tokens = (
|
||||
num_computed_tokens // self.attention_chunk_size
|
||||
@@ -1435,9 +1436,7 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
return num_skipped_tokens
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""
|
||||
cascade attention is not supported by chunked local attention.
|
||||
"""
|
||||
"""Cascade attention is not supported by chunked local attention."""
|
||||
return 0
|
||||
|
||||
|
||||
@@ -1674,9 +1673,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
blocks[last_state_block_idx] = self._null_block
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""
|
||||
cascade attention is not supported by mamba
|
||||
"""
|
||||
"""Cascade attention is not supported by mamba"""
|
||||
return 0
|
||||
|
||||
def _needs_internal_checkpoint(
|
||||
@@ -1979,8 +1976,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
return super().pop_blocks_for_free(request_id)
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
"""
|
||||
Get the number of tokens whose mamba state are not needed anymore. Mamba only
|
||||
"""Get the number of tokens whose mamba state are not needed anymore. Mamba only
|
||||
need to keep the state of the last computed token, so we return
|
||||
num_computed_tokens - 1.
|
||||
"""
|
||||
@@ -2600,8 +2596,7 @@ def get_manager_for_kv_cache_spec(
|
||||
role: str | None = None,
|
||||
**kwargs,
|
||||
) -> SingleTypeKVCacheManager:
|
||||
"""
|
||||
Get the appropriate manager for a given KVCacheSpec.
|
||||
"""Get the appropriate manager for a given KVCacheSpec.
|
||||
|
||||
Uses the KVCacheSpecRegistry to look up the manager class, supporting
|
||||
both built-in and custom specs registered via @register_kv_cache_spec
|
||||
@@ -2612,8 +2607,11 @@ def get_manager_for_kv_cache_spec(
|
||||
max_in_flight_tokens: The max tokens scheduled but not yet settled
|
||||
(one batch per concurrent step); see `VllmConfig.max_in_flight_tokens`
|
||||
max_model_len: The maximum context length the model could serve
|
||||
role: Optional KV cache group role used to select a role-specific
|
||||
manager
|
||||
Returns:
|
||||
An instance of the appropriate SingleTypeKVCacheManager subclass
|
||||
|
||||
"""
|
||||
manager_class = KVCacheSpecRegistry.get_manager_class(kv_cache_spec, role)
|
||||
assert manager_class is not None, (
|
||||
|
||||
@@ -13,8 +13,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class CudagraphDispatcher:
|
||||
"""
|
||||
Runtime cudagraph dispatcher to dispatch keys for multiple set of
|
||||
"""Runtime cudagraph dispatcher to dispatch keys for multiple set of
|
||||
cudagraphs.
|
||||
|
||||
The dispatcher stores two sets of dispatch keys, one for PIECEWISE and one
|
||||
@@ -109,8 +108,7 @@ class CudagraphDispatcher:
|
||||
)
|
||||
|
||||
def _get_lora_cases(self) -> list[int]:
|
||||
"""
|
||||
Returns list of has_lora values for CUDA graph capture.
|
||||
"""Returns list of has_lora values for CUDA graph capture.
|
||||
This is the single source of truth for LoRA capture cases.
|
||||
"""
|
||||
lora_config = self.vllm_config.lora_config
|
||||
@@ -241,8 +239,7 @@ class CudagraphDispatcher:
|
||||
valid_modes: AbstractSet[CUDAGraphMode] | None = None,
|
||||
invalid_modes: AbstractSet[CUDAGraphMode] | None = None,
|
||||
) -> tuple[CUDAGraphMode, BatchDescriptor]:
|
||||
"""
|
||||
Given conditions(e.g.,batch descriptor and if using piecewise only),
|
||||
"""Given conditions(e.g.,batch descriptor and if using piecewise only),
|
||||
dispatch to a cudagraph runtime mode and the valid batch descriptor.
|
||||
A new batch descriptor is returned as we might dispatch a uniform batch
|
||||
to a graph that supports a more general batch (uniform to non-uniform).
|
||||
@@ -259,6 +256,7 @@ class CudagraphDispatcher:
|
||||
valid_modes to compute allowed modes. (e.g., {FULL} for
|
||||
features like cascade attention not supported by full
|
||||
cudagraphs). None means no modes are excluded.
|
||||
|
||||
"""
|
||||
allowed_modes = valid_modes or CUDAGraphMode.valid_runtime_modes()
|
||||
|
||||
@@ -324,13 +322,13 @@ class CudagraphDispatcher:
|
||||
return CUDAGraphMode.NONE, BatchDescriptor(num_tokens)
|
||||
|
||||
def get_capture_descs(self) -> list[tuple[CUDAGraphMode, list[BatchDescriptor]]]:
|
||||
"""
|
||||
Returns capture descriptors for cudagraph capturing.
|
||||
"""Returns capture descriptors for cudagraph capturing.
|
||||
|
||||
Returns:
|
||||
List of (runtime_mode, batch_descriptors) tuples, ordered PIECEWISE
|
||||
first then FULL. Batch descriptors are sorted largest-first for
|
||||
memory efficiency.
|
||||
|
||||
"""
|
||||
if not self.keys_initialized or self.cudagraph_mode == CUDAGraphMode.NONE:
|
||||
return []
|
||||
|
||||
@@ -45,8 +45,7 @@ class EEPNotificationType(enum.Enum):
|
||||
|
||||
|
||||
class FinishReason(enum.IntEnum):
|
||||
"""
|
||||
Reason a request finished - stop, length, abort, error, or repetition.
|
||||
"""Reason a request finished - stop, length, abort, error, or repetition.
|
||||
|
||||
Int rather than Str for more compact serialization.
|
||||
|
||||
@@ -284,8 +283,7 @@ class EngineCoreOutputs(
|
||||
|
||||
|
||||
class EngineCoreRequestType(enum.Enum):
|
||||
"""
|
||||
Request types defined as hex byte strings, so it can be sent over sockets
|
||||
"""Request types defined as hex byte strings, so it can be sent over sockets
|
||||
without separate encoding step.
|
||||
"""
|
||||
|
||||
@@ -310,9 +308,7 @@ class ReconfigureDistributedRequest(msgspec.Struct):
|
||||
|
||||
|
||||
class ReconfigureRankType(enum.IntEnum):
|
||||
"""
|
||||
Rank type for reconfiguring distributed request.
|
||||
"""
|
||||
"""Rank type for reconfiguring distributed request."""
|
||||
|
||||
KEEP_CURRENT_RANK = -1
|
||||
SHUTDOWN_CURRENT_RANK = -2
|
||||
|
||||
+23
-23
@@ -94,8 +94,7 @@ class AsyncLLM(EngineClient):
|
||||
client_index: int = 0,
|
||||
profiler: TorchProfilerWrapper | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Create an AsyncLLM.
|
||||
"""Create an AsyncLLM.
|
||||
|
||||
Args:
|
||||
vllm_config: global configuration.
|
||||
@@ -105,13 +104,21 @@ class AsyncLLM(EngineClient):
|
||||
mm_registry: Multi-modal registry.
|
||||
log_requests: Whether to log requests.
|
||||
start_engine_loop: Whether to start the engine loop.
|
||||
client_addresses: ZMQ addresses of an externally launched engine,
|
||||
when not launching one in-process.
|
||||
client_count: Number of API-server clients sharing the engine.
|
||||
client_index: Index of this client within ``client_count``.
|
||||
aggregate_engine_logging: Whether to aggregate per-engine logs
|
||||
into a single stat logger.
|
||||
stat_loggers: customized stat loggers for the engine.
|
||||
If not provided, default stat loggers will be used.
|
||||
PLEASE BE AWARE THAT STAT LOGGER IS NOT STABLE
|
||||
IN V1, AND ITS BASE CLASS INTERFACE MIGHT CHANGE.
|
||||
profiler: Torch profiler wrapper used to trace the frontend.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
# Ensure we can serialize custom transformer configs
|
||||
maybe_register_config_serialize_by_value()
|
||||
@@ -255,7 +262,6 @@ class AsyncLLM(EngineClient):
|
||||
stat_loggers: list[StatLoggerFactory] | None = None,
|
||||
) -> "AsyncLLM":
|
||||
"""Create an AsyncLLM from the EngineArgs."""
|
||||
|
||||
# Create the engine configs.
|
||||
vllm_config = engine_args.create_engine_config(usage_context)
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
@@ -319,6 +325,7 @@ class AsyncLLM(EngineClient):
|
||||
Raises:
|
||||
QueueOverflowError: If ``max_num_queued_reqs`` would be exceeded.
|
||||
MaxQueuedTokensError: If ``max_num_queued_tokens`` would be exceeded.
|
||||
|
||||
"""
|
||||
max_num_reqs = self.scheduler_config.max_num_queued_reqs
|
||||
if max_num_reqs is not None:
|
||||
@@ -378,7 +385,6 @@ class AsyncLLM(EngineClient):
|
||||
reasoning_parser_kwargs: dict[str, Any] | None = None,
|
||||
) -> RequestOutputCollector:
|
||||
"""Add new request to the AsyncLLM."""
|
||||
|
||||
if self.errored:
|
||||
raise EngineDeadError()
|
||||
|
||||
@@ -654,8 +660,7 @@ class AsyncLLM(EngineClient):
|
||||
reasoning_ended: bool | None = None,
|
||||
reasoning_parser_kwargs: dict[str, Any] | None = None,
|
||||
) -> AsyncGenerator[RequestOutput, None]:
|
||||
"""
|
||||
Main function called by the API server to kick off a request
|
||||
"""Main function called by the API server to kick off a request
|
||||
* 1) Making an AsyncStream corresponding to the Request.
|
||||
* 2) Processing the Input.
|
||||
* 3) Adding the Request to the Detokenizer.
|
||||
@@ -678,8 +683,8 @@ class AsyncLLM(EngineClient):
|
||||
>>> params = self.renderer.default_cmpl_tok_params
|
||||
>>> (engine_input,) = self.renderer.render_cmpl([parsed], params)
|
||||
>>> gen = self.generate(engine_input, sampling_params, request_id)
|
||||
"""
|
||||
|
||||
"""
|
||||
q: RequestOutputCollector | None = None
|
||||
try:
|
||||
q = await self.add_request(
|
||||
@@ -763,7 +768,6 @@ class AsyncLLM(EngineClient):
|
||||
|
||||
def _run_output_handler(self):
|
||||
"""Background loop: pulls from EngineCore and pushes to AsyncStreams."""
|
||||
|
||||
if self.output_handler is not None:
|
||||
return
|
||||
|
||||
@@ -849,7 +853,6 @@ class AsyncLLM(EngineClient):
|
||||
self, request_id: str | Iterable[str], internal: bool = False
|
||||
) -> None:
|
||||
"""Abort RequestId in OutputProcessor and EngineCore."""
|
||||
|
||||
request_ids = (
|
||||
(request_id,) if isinstance(request_id, str) else as_list(request_id)
|
||||
)
|
||||
@@ -868,7 +871,8 @@ class AsyncLLM(EngineClient):
|
||||
) -> None:
|
||||
"""Submit a pre-aborted request so the connector's request_finished
|
||||
hook runs to free any pre-admission KV-transfer resources (e.g. NIXL
|
||||
prefill blocks pinned on the P node)."""
|
||||
prefill blocks pinned on the P node).
|
||||
"""
|
||||
request = EngineCoreRequest(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=[0],
|
||||
@@ -893,8 +897,7 @@ class AsyncLLM(EngineClient):
|
||||
wait_for_inflight_requests: bool | None = None,
|
||||
clear_cache: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Pause generation to allow model weight updates.
|
||||
"""Pause generation to allow model weight updates.
|
||||
|
||||
All mode handling (abort / wait / keep) and cache clearing is done
|
||||
in the engine. New generation/encoding requests will not be scheduled
|
||||
@@ -910,6 +913,7 @@ class AsyncLLM(EngineClient):
|
||||
wait_for_inflight_requests: DEPRECATED: use mode argument.
|
||||
clear_cache: Whether to clear KV cache and prefix cache after
|
||||
draining. Set to ``False`` to preserve cache for faster resume.
|
||||
|
||||
"""
|
||||
if wait_for_inflight_requests:
|
||||
warnings.warn(
|
||||
@@ -950,8 +954,7 @@ class AsyncLLM(EngineClient):
|
||||
tokenization_kwargs: dict[str, Any] | None = None,
|
||||
reasoning_ended: bool | None = None,
|
||||
) -> AsyncGenerator[PoolingRequestOutput, None]:
|
||||
"""
|
||||
Main function called by the API server to kick off a request
|
||||
"""Main function called by the API server to kick off a request
|
||||
* 1) Making an AsyncStream corresponding to the Request.
|
||||
* 2) Processing the Input.
|
||||
* 3) Adding the Request to the EngineCore (separate process).
|
||||
@@ -963,7 +966,6 @@ class AsyncLLM(EngineClient):
|
||||
The caller of generate() iterates the returned AsyncGenerator,
|
||||
returning the RequestOutput back to the caller.
|
||||
"""
|
||||
|
||||
q: RequestOutputCollector | None = None
|
||||
try:
|
||||
q = await self.add_request(
|
||||
@@ -1116,9 +1118,7 @@ class AsyncLLM(EngineClient):
|
||||
args: tuple = (),
|
||||
kwargs: dict | None = None,
|
||||
):
|
||||
"""
|
||||
Perform a collective RPC call to the given path.
|
||||
"""
|
||||
"""Perform a collective RPC call to the given path."""
|
||||
return await self.engine_core.collective_rpc_async(
|
||||
method, timeout, args, kwargs
|
||||
)
|
||||
@@ -1198,7 +1198,7 @@ class AsyncLLM(EngineClient):
|
||||
async def handle_fault(
|
||||
self, fault_tolerance_request: FaultToleranceRequest
|
||||
) -> FaultToleranceResult:
|
||||
"""send fault tolerance instruction to the engine"""
|
||||
"""Send fault tolerance instruction to the engine."""
|
||||
return await self.engine_core.handle_fault(fault_tolerance_request)
|
||||
|
||||
async def get_status(self):
|
||||
@@ -1224,11 +1224,11 @@ class AsyncLLM(EngineClient):
|
||||
async def init_weight_transfer_engine(
|
||||
self, request: WeightTransferInitRequest
|
||||
) -> None:
|
||||
"""
|
||||
Initialize weight transfer for RL training.
|
||||
"""Initialize weight transfer for RL training.
|
||||
|
||||
Args:
|
||||
request: Weight transfer initialization request with backend-specific info
|
||||
|
||||
"""
|
||||
await self.collective_rpc(
|
||||
"init_weight_transfer_engine", kwargs={"init_info": request.init_info}
|
||||
@@ -1243,11 +1243,11 @@ class AsyncLLM(EngineClient):
|
||||
await self.collective_rpc("start_draft_weight_update")
|
||||
|
||||
async def update_weights(self, request: WeightTransferUpdateRequest) -> None:
|
||||
"""
|
||||
Batched weight update for RL training.
|
||||
"""Batched weight update for RL training.
|
||||
|
||||
Args:
|
||||
request: Weight update request with backend-specific update info
|
||||
|
||||
"""
|
||||
await self.collective_rpc(
|
||||
"update_weights", kwargs={"update_info": request.update_info}
|
||||
|
||||
+14
-29
@@ -505,7 +505,6 @@ class EngineCore:
|
||||
|
||||
def abort_requests(self, request_ids: list[str]):
|
||||
"""Abort requests from the scheduler."""
|
||||
|
||||
# TODO: The scheduler doesn't really need to know the
|
||||
# specific finish reason, TBD whether we propagate that
|
||||
# (i.e. client-aborted vs stop criteria met).
|
||||
@@ -599,7 +598,8 @@ class EngineCore:
|
||||
|
||||
def _should_throttle_prefills(self) -> bool:
|
||||
"""Whether to defer new prefills this step (DP prefill balancing).
|
||||
Overridden by the DP engine core; never throttles otherwise."""
|
||||
Overridden by the DP engine core; never throttles otherwise.
|
||||
"""
|
||||
return False
|
||||
|
||||
def step(self) -> tuple[dict[int, EngineCoreOutputs], bool]:
|
||||
@@ -608,7 +608,6 @@ class EngineCore:
|
||||
Returns tuple of outputs and a flag indicating whether the model
|
||||
was executed.
|
||||
"""
|
||||
|
||||
# Check for any requests remaining in the scheduler - unfinished,
|
||||
# or finished and not yet removed from the batch.
|
||||
if not self.scheduler.has_requests():
|
||||
@@ -659,7 +658,6 @@ class EngineCore:
|
||||
batch in the job queue is finished.
|
||||
3. Update the scheduler from the output.
|
||||
"""
|
||||
|
||||
batch_queue = self.batch_queue
|
||||
assert batch_queue is not None
|
||||
|
||||
@@ -903,8 +901,8 @@ class EngineCore:
|
||||
- Level 2: Discard all GPU memory.
|
||||
mode: Pause mode - how to deal with any existing requests, see
|
||||
documentation of pause_scheduler method.
|
||||
"""
|
||||
|
||||
"""
|
||||
# Pause scheduler before sleeping.
|
||||
clear_prefix_cache = level >= 1
|
||||
pause_future = self.pause_scheduler(mode=mode, clear_cache=clear_prefix_cache)
|
||||
@@ -935,6 +933,7 @@ class EngineCore:
|
||||
|
||||
Args:
|
||||
tags: Tags to wake up. Use ["scheduling"] for level 0 wake up.
|
||||
|
||||
"""
|
||||
if tags is not None and "scheduling" in tags:
|
||||
# Remove "scheduling" from tags if there are other tags to process.
|
||||
@@ -1162,8 +1161,7 @@ class EngineCoreProc(EngineCore):
|
||||
vllm_config: VllmConfig,
|
||||
client_handshake_address: str | None,
|
||||
) -> Generator[EngineZmqAddresses, None, None]:
|
||||
"""
|
||||
Perform startup handshakes.
|
||||
"""Perform startup handshakes.
|
||||
|
||||
For DP=1 or offline mode, this is with the colocated front-end process.
|
||||
|
||||
@@ -1298,7 +1296,6 @@ class EngineCoreProc(EngineCore):
|
||||
@staticmethod
|
||||
def run_engine_core(*args, dp_rank: int = 0, local_dp_rank: int = 0, **kwargs):
|
||||
"""Launch EngineCore busy loop in background process."""
|
||||
|
||||
# Ensure we can serialize transformer config after spawning
|
||||
maybe_register_config_serialize_by_value()
|
||||
|
||||
@@ -1444,7 +1441,6 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
def _process_input_queue(self):
|
||||
"""Exits when an engine step needs to be performed."""
|
||||
|
||||
waited = False
|
||||
while not self.has_work() and self.is_running():
|
||||
# Notify callbacks waiting for engine to become idle.
|
||||
@@ -1475,7 +1471,6 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
def _process_engine_step(self) -> bool:
|
||||
"""Called only when there are unfinished local requests."""
|
||||
|
||||
# Step the engine core.
|
||||
outputs, model_executed = self.step_fn()
|
||||
# Put EngineCoreOutputs into the output queue.
|
||||
@@ -1549,7 +1544,6 @@ class EngineCoreProc(EngineCore):
|
||||
self, request_type: EngineCoreRequestType, request: Any
|
||||
) -> None:
|
||||
"""Dispatch request from client."""
|
||||
|
||||
if request_type == EngineCoreRequestType.WAKEUP:
|
||||
return
|
||||
elif request_type == EngineCoreRequestType.ADD:
|
||||
@@ -1629,7 +1623,8 @@ class EngineCoreProc(EngineCore):
|
||||
@staticmethod
|
||||
def _convert_msgspec_args(method, args):
|
||||
"""If a provided arg type doesn't match corresponding target method
|
||||
arg type, try converting to msgspec object."""
|
||||
arg type, try converting to msgspec object.
|
||||
"""
|
||||
if not args:
|
||||
return args
|
||||
arg_types = signature(method).parameters.values()
|
||||
@@ -1645,7 +1640,6 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
def _send_engine_dead(self):
|
||||
"""Send EngineDead status to the EngineCoreClient."""
|
||||
|
||||
# Put ENGINE_CORE_DEAD in the queue.
|
||||
self.output_queue.put_nowait(EngineCoreProc.ENGINE_CORE_DEAD)
|
||||
|
||||
@@ -1710,7 +1704,6 @@ class EngineCoreProc(EngineCore):
|
||||
ready_event: threading.Event,
|
||||
):
|
||||
"""Input socket IO thread."""
|
||||
|
||||
# Msgpack serialization decoding with optional tensor IPC receiver.
|
||||
add_request_decoder = MsgpackDecoder(
|
||||
EngineCoreRequest, oob_tensor_provider=self.tensor_ipc_receiver
|
||||
@@ -1809,7 +1802,6 @@ class EngineCoreProc(EngineCore):
|
||||
self, output_paths: list[str], coord_output_path: str | None, engine_index: int
|
||||
):
|
||||
"""Output socket IO thread."""
|
||||
|
||||
# Msgpack serialization encoding.
|
||||
encoder = MsgpackEncoder()
|
||||
# Send buffers to reuse.
|
||||
@@ -2014,7 +2006,8 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
class DPEngineCoreProc(EngineCoreProc):
|
||||
"""ZMQ-wrapper for running EngineCore in background process
|
||||
in a data parallel context."""
|
||||
in a data parallel context.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -2199,7 +2192,6 @@ class DPEngineCoreProc(EngineCoreProc):
|
||||
@fault_tolerant_wrapper
|
||||
def run_busy_loop(self):
|
||||
"""Core busy loop of the EngineCore for data parallel case."""
|
||||
|
||||
# Loop until process is sent a SIGINT or SIGTERM
|
||||
while self._handle_shutdown():
|
||||
# 1) Poll the input queue until there is work to do.
|
||||
@@ -2364,8 +2356,7 @@ class DPEngineCoreProc(EngineCoreProc):
|
||||
def _eep_send_engine_core_notification(
|
||||
self, notification_type: EEPNotificationType
|
||||
):
|
||||
"""
|
||||
Send notifications to EngineCoreClient, which can then forward
|
||||
"""Send notifications to EngineCoreClient, which can then forward
|
||||
the notifications to other engine core processes. It is used for:
|
||||
1) In scale down: removing core engines to notify EngineCoreClient
|
||||
so EngineCoreClient can release their ray placement groups;
|
||||
@@ -2415,9 +2406,7 @@ class DPEngineCoreProc(EngineCoreProc):
|
||||
|
||||
|
||||
class EngineCoreActorMixin:
|
||||
"""
|
||||
Ray actor for running EngineCore in a data parallel context
|
||||
"""
|
||||
"""Ray actor for running EngineCore in a data parallel context."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -2510,16 +2499,14 @@ class EngineCoreActorMixin:
|
||||
vllm_config: VllmConfig,
|
||||
client_handshake_address: str | None,
|
||||
):
|
||||
"""
|
||||
For Ray, we don't need to actually perform handshake.
|
||||
"""For Ray, we don't need to actually perform handshake.
|
||||
All addresses information is known before the actor creation.
|
||||
Therefore, we simply yield these addresses.
|
||||
"""
|
||||
yield self.addresses
|
||||
|
||||
def wait_for_init(self):
|
||||
"""
|
||||
Wait until the engine core is initialized.
|
||||
"""Wait until the engine core is initialized.
|
||||
|
||||
This is just an empty method. When ray.get() on this method
|
||||
(or any other method of the actor) returns, it is guaranteed
|
||||
@@ -2528,9 +2515,7 @@ class EngineCoreActorMixin:
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Run the engine core busy loop.
|
||||
"""
|
||||
"""Run the engine core busy loop."""
|
||||
try:
|
||||
self.run_busy_loop() # type: ignore[attr-defined]
|
||||
except SystemExit:
|
||||
|
||||
@@ -77,8 +77,7 @@ EngineIdentity = bytes
|
||||
|
||||
|
||||
class EngineCoreClient(ABC):
|
||||
"""
|
||||
EngineCoreClient: subclasses handle different methods for pushing
|
||||
"""EngineCoreClient: subclasses handle different methods for pushing
|
||||
and pulling from the EngineCore for asyncio / multiprocessing.
|
||||
|
||||
Subclasses:
|
||||
@@ -249,7 +248,8 @@ class EngineCoreClient(ABC):
|
||||
|
||||
def dp_engines_running(self) -> bool:
|
||||
"""Returns True if data parallel engines are collectively in a
|
||||
running state."""
|
||||
running state.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def commit_elastic_ep(self) -> None:
|
||||
@@ -331,8 +331,7 @@ class EngineCoreClient(ABC):
|
||||
|
||||
|
||||
class InprocClient(EngineCoreClient):
|
||||
"""
|
||||
InprocClient: client for in-process EngineCore. Intended
|
||||
"""InprocClient: client for in-process EngineCore. Intended
|
||||
for use in LLMEngine for V0-style add_request() and step()
|
||||
EngineCore setup in this process (no busy loop).
|
||||
|
||||
@@ -447,7 +446,8 @@ class InprocClient(EngineCoreClient):
|
||||
@dataclass
|
||||
class BackgroundResources:
|
||||
"""Used as a finalizer for clean shutdown, avoiding
|
||||
circular reference back to the client object."""
|
||||
circular reference back to the client object.
|
||||
"""
|
||||
|
||||
ctx: zmq.Context
|
||||
# If CoreEngineProcManager, it manages local engines;
|
||||
@@ -469,7 +469,6 @@ class BackgroundResources:
|
||||
|
||||
def __call__(self):
|
||||
"""Clean up background resources."""
|
||||
|
||||
logger.debug_once("[shutdown] MPClient: background resource cleanup start")
|
||||
self.engine_dead = True
|
||||
if self.engine_manager is not None:
|
||||
@@ -543,16 +542,15 @@ class ElasticScalingCache:
|
||||
|
||||
|
||||
class MPClient(EngineCoreClient):
|
||||
"""
|
||||
MPClient: base client for multi-proc EngineCore.
|
||||
EngineCore runs in a background process busy loop, getting
|
||||
new EngineCoreRequests and returning EngineCoreOutputs
|
||||
"""MPClient: base client for multi-proc EngineCore.
|
||||
EngineCore runs in a background process busy loop, getting
|
||||
new EngineCoreRequests and returning EngineCoreOutputs
|
||||
|
||||
* pushes EngineCoreRequests via input_socket
|
||||
* pulls EngineCoreOutputs via output_socket
|
||||
* pushes EngineCoreRequests via input_socket
|
||||
* pulls EngineCoreOutputs via output_socket
|
||||
|
||||
* AsyncMPClient subclass for AsyncLLM usage
|
||||
* SyncMPClient subclass for LLM usage
|
||||
* AsyncMPClient subclass for AsyncLLM usage
|
||||
* SyncMPClient subclass for LLM usage
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -803,7 +801,8 @@ class MPClient(EngineCoreClient):
|
||||
|
||||
def _apply_ready_response(self, payload: bytes) -> None:
|
||||
"""Decode an EngineCoreReadyResponse and sync any post-initialization
|
||||
config changes (e.g. auto-fitted max_model_len) back to the frontend."""
|
||||
config changes (e.g. auto-fitted max_model_len) back to the frontend.
|
||||
"""
|
||||
vllm_config = self.vllm_config
|
||||
response = (
|
||||
msgspec.msgpack.decode(payload, type=EngineCoreReadyResponse)
|
||||
@@ -1334,7 +1333,8 @@ class AsyncMPClient(MPClient):
|
||||
|
||||
class DPAsyncMPClient(AsyncMPClient):
|
||||
"""Asyncio-compatible client for multi-proc, multi-engine (data parallel)
|
||||
EngineCore. Assumes external load-balancing by default."""
|
||||
EngineCore. Assumes external load-balancing by default.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1518,7 +1518,8 @@ class DPAsyncMPClient(AsyncMPClient):
|
||||
|
||||
class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
"""Asyncio-compatible client for multi-proc, multi-engine (data parallel)
|
||||
EngineCore. Load-balances between multiple engine processes."""
|
||||
EngineCore. Load-balances between multiple engine processes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1754,8 +1755,7 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
self._prepared_elastic_ep = new_data_parallel_size, num_redundant_experts
|
||||
|
||||
def _eep_wait_for_setup_switch_complete(self) -> asyncio.Future:
|
||||
"""
|
||||
Wait for core engines to switch to the new setup.
|
||||
"""Wait for core engines to switch to the new setup.
|
||||
|
||||
In eep_process_engine_core_notification(), a dummy UtilityOutput with
|
||||
EEP_NOTIFICATION_CALL_ID will be set when RECONFIGURE_FINISHED
|
||||
@@ -1827,7 +1827,8 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
num_redundant_experts: int,
|
||||
) -> None:
|
||||
"""Prepare scale up by creating new engine cores and reconfiguring
|
||||
existing ones."""
|
||||
existing ones.
|
||||
"""
|
||||
self._setup_elastic_ep_reconfig_bootstrap()
|
||||
|
||||
# Phase 1: Send reconfig messages to existing engines
|
||||
@@ -1919,7 +1920,8 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
|
||||
async def _commit_scale_down_elastic_ep(self, new_data_parallel_size: int) -> None:
|
||||
"""Scale down the data parallel size by shutting down and
|
||||
reconfiguring existing engine cores."""
|
||||
reconfiguring existing engine cores.
|
||||
"""
|
||||
cur_data_parallel_size = len(self.core_engines)
|
||||
|
||||
self.eep_scaling_cache = ElasticScalingCache(
|
||||
|
||||
@@ -94,8 +94,7 @@ class BaseIncrementalDetokenizer(IncrementalDetokenizer, ABC):
|
||||
self.output_text = ""
|
||||
|
||||
def update(self, new_token_ids: list[int], stop_terminated: bool) -> str | None:
|
||||
"""
|
||||
Update RequestState for the request_id by:
|
||||
"""Update RequestState for the request_id by:
|
||||
1) Detokenize the new token ids incrementally.
|
||||
2) Evaluate stop criteria.
|
||||
|
||||
@@ -148,8 +147,8 @@ class BaseIncrementalDetokenizer(IncrementalDetokenizer, ABC):
|
||||
|
||||
def get_next_output_text(self, finished: bool, delta: bool) -> str:
|
||||
"""If delta is True, only new text since the last call to
|
||||
this method is returned"""
|
||||
|
||||
this method is returned
|
||||
"""
|
||||
# We return the full output text if the sequence is finished.
|
||||
buffer_length = 0 if finished else self.stop_buffer_length
|
||||
if not delta:
|
||||
|
||||
@@ -206,8 +206,7 @@ class InputProcessor:
|
||||
mm_hash: str,
|
||||
lora_request: LoRARequest | None,
|
||||
) -> str:
|
||||
"""
|
||||
When enable_tower_connector_lora is True, multi-modal embeddings
|
||||
"""When enable_tower_connector_lora is True, multi-modal embeddings
|
||||
vary depending on the LoRA request. Therefore, the mm_hash must be
|
||||
generated based on the LoRA request to prevent incorrect cache hits.
|
||||
"""
|
||||
|
||||
@@ -171,7 +171,6 @@ class LLMEngine:
|
||||
enable_multiprocessing: bool = False,
|
||||
) -> "LLMEngine":
|
||||
"""Creates an LLM engine from the engine arguments."""
|
||||
|
||||
# Create the engine configs.
|
||||
vllm_config = engine_args.create_engine_config(usage_context)
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
@@ -216,7 +215,6 @@ class LLMEngine:
|
||||
|
||||
def abort_request(self, request_ids: list[str], internal: bool = False) -> None:
|
||||
"""Remove request_ids from EngineCore and Detokenizer."""
|
||||
|
||||
request_ids = self.output_processor.abort_requests(request_ids, internal)
|
||||
self.engine_core.abort_requests(request_ids)
|
||||
|
||||
|
||||
@@ -76,7 +76,6 @@ class LogprobsProcessor:
|
||||
logprobs_lists: the lists of logprob tokens, logprobs, and ranks.
|
||||
|
||||
"""
|
||||
|
||||
assert self.num_logprobs is not None
|
||||
assert self.logprobs is not None
|
||||
assert self.cumulative_logprob is not None
|
||||
@@ -129,7 +128,6 @@ class LogprobsProcessor:
|
||||
tensors.
|
||||
|
||||
"""
|
||||
|
||||
# Prompt logprobs are enabled.
|
||||
assert self.num_prompt_logprobs is not None
|
||||
assert self.prompt_logprobs is not None
|
||||
@@ -187,7 +185,7 @@ class LogprobsProcessor:
|
||||
)
|
||||
|
||||
def pop_prompt_logprobs(self) -> PromptLogprobs | None:
|
||||
"""Pop and return all request prompt logprobs
|
||||
"""Pop and return all request prompt logprobs.
|
||||
|
||||
The logprobs processor aggregates prompt chunk logprobs
|
||||
over one or more prefill chunks. This method returns
|
||||
@@ -199,6 +197,7 @@ class LogprobsProcessor:
|
||||
Returns:
|
||||
None if prompt logprobs are disabled for this request.
|
||||
List of all prompt logprobs, otherwise.
|
||||
|
||||
"""
|
||||
plp = self.prompt_logprobs
|
||||
if plp:
|
||||
@@ -223,6 +222,7 @@ class LogprobsProcessor:
|
||||
|
||||
Returns:
|
||||
List of sampled token IDs, oldest first, most recent last.
|
||||
|
||||
"""
|
||||
if not logprobs_source:
|
||||
return []
|
||||
@@ -265,6 +265,7 @@ class LogprobsProcessor:
|
||||
Returns:
|
||||
The corrected decoded string, or empty string if the byte
|
||||
sequence is genuinely incomplete at this point.
|
||||
|
||||
"""
|
||||
assert self.tokenizer is not None
|
||||
|
||||
@@ -325,6 +326,7 @@ class LogprobsProcessor:
|
||||
context_token_ids: Preceding sampled token IDs providing
|
||||
sequential context. If None, extracted from
|
||||
self.logprobs.
|
||||
|
||||
"""
|
||||
if context_token_ids is None:
|
||||
context_token_ids = self._get_sampled_context_ids(self.logprobs)
|
||||
|
||||
@@ -49,8 +49,7 @@ EMPTY_CPU_TENSOR = torch.empty(0, device="cpu")
|
||||
|
||||
|
||||
class RequestOutputCollector:
|
||||
"""
|
||||
Collects streamed RequestOutputs per individual request,
|
||||
"""Collects streamed RequestOutputs per individual request,
|
||||
for hand-off to the consuming asyncio generate task.
|
||||
|
||||
When streaming deltas, RequestOutputs are merged if the
|
||||
@@ -506,7 +505,6 @@ class OutputProcessor:
|
||||
|
||||
def propagate_error(self, e: Exception):
|
||||
"""Propagate error to all generate() tasks."""
|
||||
|
||||
for _, state in self.request_states.items():
|
||||
assert state.queue is not None
|
||||
state.queue.put(e)
|
||||
@@ -646,8 +644,7 @@ class OutputProcessor:
|
||||
engine_core_timestamp: float | None = None,
|
||||
iteration_stats: IterationStats | None = None,
|
||||
) -> OutputProcessorOutput:
|
||||
"""
|
||||
Process the EngineCoreOutputs:
|
||||
"""Process the EngineCoreOutputs:
|
||||
1) Compute stats for logging
|
||||
2) Detokenize
|
||||
3) Create and handle RequestOutput objects:
|
||||
@@ -667,7 +664,6 @@ class OutputProcessor:
|
||||
If you need to touch every element of the batch, do it from
|
||||
within the loop below.
|
||||
"""
|
||||
|
||||
request_outputs: list[RequestOutput | PoolingRequestOutput] = []
|
||||
reqs_to_abort: list[str] = []
|
||||
for engine_core_output in engine_core_outputs:
|
||||
|
||||
@@ -53,7 +53,7 @@ class ParentRequest:
|
||||
self,
|
||||
index: int,
|
||||
) -> SamplingParams:
|
||||
"""Efficiently obtain child `sampling_params`
|
||||
"""Efficiently obtain child `sampling_params`.
|
||||
|
||||
If `sampling_params.seed` is not `None` then
|
||||
each child request requires a unique clone of
|
||||
@@ -64,6 +64,7 @@ class ParentRequest:
|
||||
|
||||
Returns:
|
||||
Child `sampling_params` instance.
|
||||
|
||||
"""
|
||||
seed = self.sampling_params.seed
|
||||
if self.cached_child_sampling_params:
|
||||
@@ -88,6 +89,7 @@ class ParentRequest:
|
||||
|
||||
Returns:
|
||||
(request ID, sampling_params) tuple
|
||||
|
||||
"""
|
||||
child_req_id = f"{index}_{self.request_id}"
|
||||
self.child_requests.add(child_req_id)
|
||||
|
||||
@@ -29,8 +29,7 @@ TensorIpcQueue = MPQueue
|
||||
|
||||
@dataclasses.dataclass
|
||||
class TensorIpcData:
|
||||
"""
|
||||
Data sent via torch.multiprocessing.Queue for zero-copy IPC.
|
||||
"""Data sent via torch.multiprocessing.Queue for zero-copy IPC.
|
||||
|
||||
Contains the tensor_id and the actual tensor. The tensor is
|
||||
shared in memory (GPU or CPU) for efficient inter-process communication.
|
||||
@@ -130,7 +129,6 @@ class TensorIpcReceiver:
|
||||
the queue, buffering them, until the requested tensor is found.
|
||||
Works for CUDA and CPU.
|
||||
"""
|
||||
|
||||
# Create lookup key from handle
|
||||
sender_id: str = meta["sender_id"]
|
||||
message_id: int = meta["message_id"]
|
||||
|
||||
+8
-18
@@ -142,8 +142,7 @@ def _node_ip_from_resources(node_resources: dict) -> str | None:
|
||||
|
||||
|
||||
class CoreEngineProcManager:
|
||||
"""
|
||||
Utility class to handle creation, readiness, and shutdown
|
||||
"""Utility class to handle creation, readiness, and shutdown
|
||||
of background processes used by the AsyncLLM and LLMEngine.
|
||||
"""
|
||||
|
||||
@@ -255,7 +254,6 @@ class CoreEngineProcManager:
|
||||
|
||||
def monitor_engine_liveness(self) -> None:
|
||||
"""Monitor engine core process liveness."""
|
||||
|
||||
sentinel_to_proc = {proc.sentinel: proc for proc in self.processes}
|
||||
sentinels = set(sentinel_to_proc.keys())
|
||||
|
||||
@@ -316,8 +314,7 @@ def set_assigned_physical_gpu_ids_for_dp_rank(
|
||||
local_dp_rank: int,
|
||||
user_assigned_gpu_ids: list[int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Populate assigned_physical_gpu_ids on the config for the given DP rank.
|
||||
"""Populate assigned_physical_gpu_ids on the config for the given DP rank.
|
||||
|
||||
user_assigned_gpu_ids is the full (un-sharded) --device-ids list, if the
|
||||
user provided one; this DP rank's shard is sliced from it. It is passed
|
||||
@@ -345,8 +342,7 @@ def get_physical_gpu_ids_for_local_dp_rank(
|
||||
local_world_size: int | None = None,
|
||||
user_assigned_gpu_ids: list[int] | None = None,
|
||||
) -> list[int]:
|
||||
"""
|
||||
Returns list of physical GPU IDs for the specified
|
||||
"""Returns list of physical GPU IDs for the specified
|
||||
data parallel rank.
|
||||
|
||||
For example, if world_size=2 and local_dp_rank=1, and there are 4 devices,
|
||||
@@ -399,8 +395,7 @@ def _apply_dp_identity_suffix(dp_vllm_config, dp_rank: int) -> None:
|
||||
|
||||
|
||||
class CoreEngineActorManager:
|
||||
"""
|
||||
Utility class to handle creation, readiness, and shutdown
|
||||
"""Utility class to handle creation, readiness, and shutdown
|
||||
of core engine Ray actors used by the AsyncLLM and LLMEngine.
|
||||
|
||||
Different from CoreEngineProcManager, this class manages
|
||||
@@ -552,10 +547,7 @@ class CoreEngineActorManager:
|
||||
def create_dp_placement_groups(
|
||||
vllm_config: VllmConfig,
|
||||
) -> tuple[list["PlacementGroup"], list[int]]:
|
||||
"""
|
||||
Create placement groups for data parallel.
|
||||
"""
|
||||
|
||||
"""Create placement groups for data parallel."""
|
||||
import ray
|
||||
from ray._private.state import available_resources_per_node
|
||||
|
||||
@@ -769,9 +761,7 @@ class CoreEngineActorManager:
|
||||
def add_dp_placement_groups(
|
||||
old_vllm_config: VllmConfig, new_data_parallel_size: int
|
||||
) -> tuple[list["PlacementGroup"], list[int]]:
|
||||
"""
|
||||
Add placement groups for new data parallel size.
|
||||
"""
|
||||
"""Add placement groups for new data parallel size."""
|
||||
import ray
|
||||
from ray._private.state import (
|
||||
available_resources_per_node,
|
||||
@@ -1051,7 +1041,8 @@ def get_engine_zmq_addresses(
|
||||
|
||||
Set ``defer_api_server_ports=False`` only when the consumer cannot
|
||||
report a bound port back (e.g. the Rust front-end). IPC paths are
|
||||
unaffected."""
|
||||
unaffected.
|
||||
"""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
local_engine_count = parallel_config.data_parallel_size_local
|
||||
local_start_index = parallel_config.data_parallel_rank_local
|
||||
@@ -1108,7 +1099,6 @@ def launch_core_engines(
|
||||
addresses: EngineZmqAddresses,
|
||||
) -> Iterator[CoreEngineLaunch]:
|
||||
"""Launch engine and DP coordinator processes as needed."""
|
||||
|
||||
parallel_config = vllm_config.parallel_config
|
||||
dp_size = parallel_config.data_parallel_size
|
||||
local_engine_count = parallel_config.data_parallel_size_local
|
||||
|
||||
@@ -36,7 +36,7 @@ FailureCallback = Callable[[], None]
|
||||
|
||||
|
||||
class Executor(ABC):
|
||||
"""Abstract base class for vLLM executors."
|
||||
"""Abstract base class for vLLM executors.
|
||||
|
||||
An executor is responsible for executing the model on one device,
|
||||
or it can be a distributed executor that can execute the model on multiple devices.
|
||||
@@ -139,8 +139,7 @@ class Executor(ABC):
|
||||
)
|
||||
|
||||
def register_failure_callback(self, callback: FailureCallback): # noqa: B027
|
||||
"""
|
||||
Register a function to be called if the executor enters a permanent
|
||||
"""Register a function to be called if the executor enters a permanent
|
||||
failed state.
|
||||
"""
|
||||
pass
|
||||
@@ -168,8 +167,29 @@ class Executor(ABC):
|
||||
kwargs: dict | None = None,
|
||||
non_block: Literal[False] = False,
|
||||
) -> list[_R]:
|
||||
"""
|
||||
Execute an RPC call on all workers.
|
||||
pass
|
||||
|
||||
@overload
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[[WorkerBase], _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict | None = None,
|
||||
non_block: Literal[True] = True,
|
||||
) -> Future[list[_R]]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[[WorkerBase], _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict | None = None,
|
||||
non_block: bool = False,
|
||||
) -> list[_R] | Future[list[_R]]:
|
||||
"""Execute an RPC call on all workers.
|
||||
|
||||
Args:
|
||||
method: Name of the worker method to execute, or a callable that
|
||||
@@ -191,24 +211,8 @@ class Executor(ABC):
|
||||
Note:
|
||||
It is recommended to use this API to only pass control messages,
|
||||
and set up data-plane communication to pass data.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@overload
|
||||
def collective_rpc(
|
||||
self,
|
||||
method: str | Callable[[WorkerBase], _R],
|
||||
timeout: float | None = None,
|
||||
args: tuple = (),
|
||||
kwargs: dict | None = None,
|
||||
non_block: Literal[True] = True,
|
||||
) -> Future[list[_R]]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def collective_rpc(
|
||||
self, method, timeout=None, args=(), kwargs=None, non_block: bool = False
|
||||
):
|
||||
raise NotImplementedError
|
||||
|
||||
def get_kv_connector_handshake_metadata(
|
||||
@@ -280,7 +284,8 @@ class Executor(ABC):
|
||||
@abstractmethod
|
||||
def check_health(self) -> None:
|
||||
"""Checks if the executor is healthy. If not, it should raise an
|
||||
exception."""
|
||||
exception.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def shutdown(self) -> None:
|
||||
@@ -288,7 +293,7 @@ class Executor(ABC):
|
||||
self.collective_rpc("shutdown")
|
||||
|
||||
def init_kv_output_aggregator(self, connector: "KVConnectorBase") -> None:
|
||||
"""Init KVOutputAggregator"""
|
||||
"""Init KVOutputAggregator."""
|
||||
self.kv_output_aggregator = KVOutputAggregator.from_connector(
|
||||
connector, self.parallel_config.world_size
|
||||
)
|
||||
@@ -381,9 +386,7 @@ class Executor(ABC):
|
||||
|
||||
@classmethod
|
||||
def supports_async_scheduling(cls) -> bool:
|
||||
"""
|
||||
Whether the executor supports async scheduling.
|
||||
"""
|
||||
"""Whether the executor supports async scheduling."""
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -384,7 +384,8 @@ class MultiprocExecutor(Executor):
|
||||
ec_output_aggregator: ECOutputAggregator | None = None,
|
||||
) -> Any:
|
||||
"""Returns single result if unique_reply_rank and/or an output
|
||||
aggregator is provided, otherwise list."""
|
||||
aggregator is provided, otherwise list.
|
||||
"""
|
||||
assert self.rpc_broadcast_mq is not None, (
|
||||
"collective_rpc should not be called on follower node"
|
||||
)
|
||||
@@ -451,7 +452,8 @@ class MultiprocExecutor(Executor):
|
||||
def _ensure_worker_termination(worker_procs: list[BaseProcess]):
|
||||
"""Ensure that all worker processes are terminated. Assumes workers have
|
||||
received termination requests. Waits for processing, then sends
|
||||
termination and kill signals if needed."""
|
||||
termination and kill signals if needed.
|
||||
"""
|
||||
|
||||
def wait_for_termination(procs, timeout):
|
||||
if not time:
|
||||
@@ -500,7 +502,7 @@ class MultiprocExecutor(Executor):
|
||||
p.kill()
|
||||
|
||||
def shutdown(self):
|
||||
"""Properly shut down the executor and its workers"""
|
||||
"""Properly shut down the executor and its workers."""
|
||||
if not getattr(self, "shutting_down", False):
|
||||
worker_count = len(getattr(self, "workers", None) or [])
|
||||
logger.debug(
|
||||
@@ -852,8 +854,8 @@ class WorkerProc:
|
||||
@staticmethod
|
||||
def worker_main(*args, **kwargs):
|
||||
"""Worker initialization and execution loops.
|
||||
This runs a background process"""
|
||||
|
||||
This runs a background process
|
||||
"""
|
||||
# Signal handler used for graceful termination.
|
||||
# SystemExit exception is only raised once to allow this and worker
|
||||
# processes to terminate without error
|
||||
@@ -1010,7 +1012,6 @@ class WorkerProc:
|
||||
|
||||
def async_output_busy_loop(self):
|
||||
"""Entrypoint for the thread which handles outputs asynchronously."""
|
||||
|
||||
# set device to the worker device for the thread.
|
||||
# a thread will not inherit the context of the main thread.
|
||||
# when calling any cuda runtime functions, it will implicitly
|
||||
@@ -1027,7 +1028,7 @@ class WorkerProc:
|
||||
self.enqueue_output(output)
|
||||
|
||||
def worker_busy_loop(self):
|
||||
"""Main busy loop for Multiprocessing Workers"""
|
||||
"""Main busy loop for Multiprocessing Workers."""
|
||||
assert self.rpc_broadcast_mq is not None
|
||||
while True:
|
||||
self._execute_worker_rpc(self.rpc_broadcast_mq.dequeue(indefinite=True))
|
||||
@@ -1098,8 +1099,8 @@ class WorkerProc:
|
||||
def set_multiprocessing_worker_envs(local_world_size: int = 1):
|
||||
"""Set up environment variables that should be used when there are workers
|
||||
in a multiprocessing environment. This should be called by the parent
|
||||
process before worker processes are created"""
|
||||
|
||||
process before worker processes are created
|
||||
"""
|
||||
_maybe_force_spawn()
|
||||
|
||||
if current_platform.is_cpu() or "OMP_NUM_THREADS" in os.environ:
|
||||
|
||||
@@ -52,8 +52,7 @@ COMPLETED_NONE_FUTURE.set_result(None)
|
||||
|
||||
@dataclass
|
||||
class RayWorkerMetaData:
|
||||
"""
|
||||
Metadata for a Ray worker.
|
||||
"""Metadata for a Ray worker.
|
||||
The order of ray worker creation can be random,
|
||||
and we need to reset the rank after creating all workers.
|
||||
"""
|
||||
@@ -65,7 +64,7 @@ class RayWorkerMetaData:
|
||||
|
||||
|
||||
class RayDistributedExecutor(Executor):
|
||||
"""Ray-based distributed executor"""
|
||||
"""Ray-based distributed executor."""
|
||||
|
||||
uses_ray: bool = True
|
||||
supports_pp: bool = True
|
||||
@@ -249,8 +248,7 @@ class RayDistributedExecutor(Executor):
|
||||
ip_counts[ip] = ip_counts.get(ip, 0) + 1
|
||||
|
||||
def sort_by_driver_then_worker_ip(item: RayWorkerMetaData):
|
||||
"""
|
||||
Sort the workers based on 3 properties:
|
||||
"""Sort the workers based on 3 properties:
|
||||
1. If the worker is on the same node as the driver (vllm engine),
|
||||
it should be placed first.
|
||||
2. Then, if the worker is on a node with fewer workers, it should
|
||||
@@ -439,6 +437,7 @@ class RayDistributedExecutor(Executor):
|
||||
|
||||
Returns:
|
||||
The model runner output.
|
||||
|
||||
"""
|
||||
scheduler_output = self.scheduler_output
|
||||
if scheduler_output is None:
|
||||
|
||||
@@ -72,7 +72,7 @@ class RayWorkerHandle:
|
||||
"""run() ObjectRef used as a sentinel for health monitoring"""
|
||||
|
||||
def run(self):
|
||||
"""Start the worker's busy loop"""
|
||||
"""Start the worker's busy loop."""
|
||||
self.run_ref = self.actor.run.remote()
|
||||
|
||||
|
||||
@@ -190,8 +190,7 @@ class RayWorkerProc(WorkerProc):
|
||||
def _init_message_queues(
|
||||
self, input_shm_handle: Handle, vllm_config: VllmConfig
|
||||
) -> None:
|
||||
"""
|
||||
Workers on the same node as the executor use shared memory for
|
||||
"""Workers on the same node as the executor use shared memory for
|
||||
both the broadcast (input) MQ and the response MQ. Workers on
|
||||
different nodes use TCP (n_local_reader=0).
|
||||
"""
|
||||
|
||||
@@ -55,7 +55,8 @@ try:
|
||||
|
||||
class RayWorkerWrapper(WorkerWrapperBase):
|
||||
"""Ray wrapper for vllm.worker.Worker, allowing Worker to be
|
||||
lazily initialized after Ray sets CUDA_VISIBLE_DEVICES."""
|
||||
lazily initialized after Ray sets CUDA_VISIBLE_DEVICES.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -68,8 +69,7 @@ try:
|
||||
rpc_rank: int
|
||||
|
||||
def adjust_rank(self, rank_mapping: dict[int, int]) -> None:
|
||||
"""
|
||||
Adjust the rpc_rank based on the given mapping.
|
||||
"""Adjust the rpc_rank based on the given mapping.
|
||||
It is only used during the initialization of the executor,
|
||||
to adjust the rpc_rank of workers after we create all workers.
|
||||
"""
|
||||
@@ -363,8 +363,7 @@ def get_bundles_for_indices(
|
||||
bundle_indices: list[int],
|
||||
world_size: int,
|
||||
) -> list[tuple[int, str, str]]:
|
||||
"""
|
||||
Return GPU bundle indices paired with node IDs and node IPs for
|
||||
"""Return GPU bundle indices paired with node IDs and node IPs for
|
||||
explicit bundle indices specified via VLLM_RAY_BUNDLE_INDICES.
|
||||
"""
|
||||
assert len(bundle_indices) == world_size, (
|
||||
@@ -391,8 +390,7 @@ def get_bundles_for_indices(
|
||||
def get_bundles_sorted_by_node(
|
||||
placement_group: "PlacementGroup",
|
||||
) -> list[tuple[int, str, str]]:
|
||||
"""
|
||||
Return GPU bundle indices paired with node IDs and node IPs,
|
||||
"""Return GPU bundle indices paired with node IDs and node IPs,
|
||||
sorted driver-first.
|
||||
|
||||
This utility has to be invoked from the driver node.
|
||||
@@ -533,6 +531,7 @@ def initialize_ray_cluster(
|
||||
on the current (driver) node and pin the first PG bundle to it.
|
||||
Set to False for executors like RayExecutorV2 where all GPU work
|
||||
is delegated to remote Ray actors.
|
||||
|
||||
"""
|
||||
assert_ray_available()
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -154,9 +154,7 @@ class SparseCacheRole(str, Enum):
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KVCacheSpec:
|
||||
"""
|
||||
A base class for specifying the KV cache format of one layer.
|
||||
"""
|
||||
"""A base class for specifying the KV cache format of one layer."""
|
||||
|
||||
# number of tokens in a block
|
||||
block_size: int
|
||||
@@ -180,11 +178,11 @@ class KVCacheSpec:
|
||||
|
||||
@property
|
||||
def page_size_bytes(self) -> int:
|
||||
"""
|
||||
The size of a page with `block_size` tokens in bytes.
|
||||
"""The size of a page with `block_size` tokens in bytes.
|
||||
|
||||
Returns:
|
||||
The page size
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -202,37 +200,33 @@ class KVCacheSpec:
|
||||
return 128
|
||||
|
||||
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
|
||||
"""
|
||||
The maximum possible memory usage of this KV cache in bytes.
|
||||
"""The maximum possible memory usage of this KV cache in bytes.
|
||||
|
||||
Returns:
|
||||
The KV cache size in bytes
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int:
|
||||
"""
|
||||
The number of block table entries needed per request, i.e. the row
|
||||
"""The number of block table entries needed per request, i.e. the row
|
||||
length of the worker-side block table for this cache group.
|
||||
|
||||
Args:
|
||||
vllm_config: The vllm config.
|
||||
max_len: The maximum sequence length to size for, including the
|
||||
encoder length for encoder-decoder models.
|
||||
|
||||
"""
|
||||
return cdiv(max_len, self.block_size)
|
||||
|
||||
def copy_with_new_block_size(self, block_size: int) -> Self:
|
||||
"""
|
||||
Create a new KVCacheSpec from self but replacing the block size.
|
||||
"""
|
||||
"""Create a new KVCacheSpec from self but replacing the block size."""
|
||||
return replace(self, block_size=block_size)
|
||||
|
||||
@classmethod
|
||||
def merge(cls, specs: list[Self]) -> Self:
|
||||
"""
|
||||
Merge a list of KVCacheSpec objects into a single KVCacheSpec object.
|
||||
"""
|
||||
"""Merge a list of KVCacheSpec objects into a single KVCacheSpec object."""
|
||||
if not all(spec == specs[0] for spec in specs[1:]):
|
||||
raise AssertionError(
|
||||
"All layers in the same KV cache group must be the same."
|
||||
@@ -242,9 +236,7 @@ class KVCacheSpec:
|
||||
def is_uniform_with_collection(
|
||||
self, kv_cache_specs: dict[str, KVCacheSpec]
|
||||
) -> bool:
|
||||
"""
|
||||
Whether this KVCacheSpec is uniform with all specs of all layers.
|
||||
"""
|
||||
"""Whether this KVCacheSpec is uniform with all specs of all layers."""
|
||||
uniform_type_base_spec = KVCacheSpecRegistry.get_uniform_type_base_spec(self)
|
||||
assert uniform_type_base_spec is not None, (
|
||||
f"Unsupported KV cache spec type: {type(self)}. "
|
||||
@@ -537,8 +529,7 @@ class AttentionSpec(KVCacheSpec):
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class FullAttentionSpec(AttentionSpec):
|
||||
"""
|
||||
When hybrid allocator is disabled and the model contains both full
|
||||
"""When hybrid allocator is disabled and the model contains both full
|
||||
attention layers and sliding window attention layers, sliding
|
||||
window attention are regarded as full attention in KV cache manager
|
||||
(blocks are allocated for all tokens), while computed as sliding window
|
||||
@@ -582,8 +573,7 @@ class FullAttentionSpec(AttentionSpec):
|
||||
|
||||
@classmethod
|
||||
def merge(cls, specs: list[Self]) -> Self:
|
||||
"""
|
||||
Merge a list of FullAttentionSpec objects into a single
|
||||
"""Merge a list of FullAttentionSpec objects into a single
|
||||
FullAttentionSpec object.
|
||||
"""
|
||||
assert all(isinstance(spec, FullAttentionSpec) for spec in specs), (
|
||||
@@ -1124,9 +1114,7 @@ class EncoderOnlyAttentionSpec(AttentionSpec):
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CrossAttentionSpec(AttentionSpec):
|
||||
"""
|
||||
KV cache spec for cross-attention layers in encoder-decoder models.
|
||||
"""
|
||||
"""KV cache spec for cross-attention layers in encoder-decoder models."""
|
||||
|
||||
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
|
||||
# For cross-attention, we need to cache encoder states
|
||||
@@ -1141,8 +1129,7 @@ class SinkFullAttentionSpec(FullAttentionSpec):
|
||||
|
||||
@classmethod
|
||||
def merge(cls, specs: list[Self]) -> Self:
|
||||
"""
|
||||
Merge a list of FullAttentionSpec objects into a single
|
||||
"""Merge a list of FullAttentionSpec objects into a single
|
||||
FullAttentionSpec object.
|
||||
"""
|
||||
assert all(isinstance(spec, FullAttentionSpec) for spec in specs), (
|
||||
@@ -1192,8 +1179,7 @@ class SinkFullAttentionSpec(FullAttentionSpec):
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
"""
|
||||
A KV cache spec for multiple layers with the same type of attention. Here,
|
||||
"""A KV cache spec for multiple layers with the same type of attention. Here,
|
||||
same types means always need the same number of token slots. For example,
|
||||
sliding window attentions with different window sizes are not the same type
|
||||
and should not be merged into one UniformTypeKVCacheSpecs.
|
||||
@@ -1241,8 +1227,7 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
|
||||
@classmethod
|
||||
def is_uniform_type(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> bool:
|
||||
"""
|
||||
Whether all layers have the same type of KV cache spec.
|
||||
"""Whether all layers have the same type of KV cache spec.
|
||||
|
||||
Uses the registry to determine grouping base classes, so custom specs
|
||||
that inherit from FullAttentionSpec are treated as full attention.
|
||||
@@ -1256,8 +1241,7 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
|
||||
@classmethod
|
||||
def from_specs(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> Self | None:
|
||||
"""
|
||||
Return a SameTypeKVCacheSpecs object if all layers have the same type
|
||||
"""Return a SameTypeKVCacheSpecs object if all layers have the same type
|
||||
of KV cache spec. Return None if not.
|
||||
"""
|
||||
if cls.is_uniform_type(kv_cache_specs):
|
||||
@@ -1268,7 +1252,8 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
|
||||
def get_max_layers_per_page_size(self) -> int:
|
||||
"""Max number of layers sharing a page size. For a balanced bucket
|
||||
this equals the number of repetitions of the layer pattern."""
|
||||
this equals the number of repetitions of the layer pattern.
|
||||
"""
|
||||
return Counter(
|
||||
spec.page_size_bytes for spec in self.kv_cache_specs.values()
|
||||
).most_common(1)[0][1]
|
||||
@@ -1368,8 +1353,7 @@ def get_kv_cache_spec_sliding_window(kv_cache_spec: KVCacheSpec) -> int | None:
|
||||
|
||||
@dataclass
|
||||
class KVCacheTensor:
|
||||
"""
|
||||
A class for specifying how the workers should initialize the KV cache.
|
||||
"""A class for specifying how the workers should initialize the KV cache.
|
||||
|
||||
Placement of a set of same-shaped layers in the KV cache allocation.
|
||||
Layer ``layers[l]``'s page for block ``b`` starts at
|
||||
@@ -1399,8 +1383,7 @@ class KVCacheGroupRole(str, Enum):
|
||||
|
||||
@dataclass
|
||||
class KVCacheGroupSpec:
|
||||
"""
|
||||
Represents a group of model layers that share the same KV cache block table.
|
||||
"""Represents a group of model layers that share the same KV cache block table.
|
||||
These layers are regarded as one layer in the KV cache manager.
|
||||
"""
|
||||
|
||||
@@ -1421,9 +1404,7 @@ class KVCacheGroupSpec:
|
||||
|
||||
@dataclass
|
||||
class KVCacheConfig:
|
||||
"""
|
||||
The KV cache configuration of a model.
|
||||
"""
|
||||
"""The KV cache configuration of a model."""
|
||||
|
||||
num_blocks: int
|
||||
"""The number of KV cache blocks"""
|
||||
|
||||
@@ -49,7 +49,8 @@ class KVCacheLayout(Enum):
|
||||
@property
|
||||
def is_block_compact(self) -> bool:
|
||||
"""True when each page's [H, N, C] bytes form one contiguous run; i.e.
|
||||
the L and B dimensions are outermost."""
|
||||
the L and B dimensions are outermost.
|
||||
"""
|
||||
return set(self.value[:2]) == {_DIM_L, _DIM_B}
|
||||
|
||||
@property
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Registry for KVCacheSpec types and their associated managers.
|
||||
"""Registry for KVCacheSpec types and their associated managers.
|
||||
|
||||
This module provides a pluggable architecture for registering custom KVCacheSpec
|
||||
subclasses without modifying vLLM core code. Out-of-tree platforms can define
|
||||
@@ -42,9 +41,7 @@ class KVCacheSpecRegistry:
|
||||
|
||||
@classmethod
|
||||
def _ensure_registered(cls, vllm_config=None) -> None:
|
||||
"""
|
||||
Run full KVCacheSpec registration if the registration is not done.
|
||||
"""
|
||||
"""Run full KVCacheSpec registration if the registration is not done."""
|
||||
if _REGISTRY_KVCACHESPEC_LIST:
|
||||
return
|
||||
|
||||
@@ -67,8 +64,7 @@ class KVCacheSpecRegistry:
|
||||
manager_class: type["SingleTypeKVCacheManager"] | None = None,
|
||||
uniform_type_base_spec: type["KVCacheSpec"] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Register a KVCacheSpec class with its manager and base spec.
|
||||
"""Register a KVCacheSpec class with its manager and base spec.
|
||||
|
||||
Args:
|
||||
kvcache_spec_cls: The KVCacheSpec subclass to register
|
||||
@@ -77,6 +73,7 @@ class KVCacheSpecRegistry:
|
||||
instead of being grouped to different kvcache group, `kvcache_spec_cls`
|
||||
and `uniform_type_base_spec` will be trated as uniform type.
|
||||
If None, defaults to kvcache_spec_cls itself (for built-in base specs).
|
||||
|
||||
"""
|
||||
assert manager_class is not None, "manager_class is required"
|
||||
if uniform_type_base_spec is None:
|
||||
@@ -118,8 +115,7 @@ class KVCacheSpecRegistry:
|
||||
def get_manager_class(
|
||||
cls, kvcache_spec: "KVCacheSpec", role: str | None = None
|
||||
) -> type["SingleTypeKVCacheManager"] | None:
|
||||
"""
|
||||
Get the single type kvcache manager class for a given kvcache spec instance.
|
||||
"""Get the single type kvcache manager class for a given kvcache spec instance.
|
||||
|
||||
Args:
|
||||
kvcache_spec: A KVCacheSpec instance
|
||||
@@ -127,6 +123,7 @@ class KVCacheSpecRegistry:
|
||||
|
||||
Returns:
|
||||
The SingleTypeKVCacheManager class to use for this kvcache_spec
|
||||
|
||||
"""
|
||||
cls._ensure_registered()
|
||||
if role is not None and (manager_class := _REGISTRY_ROLE_MANAGERS.get(role)):
|
||||
@@ -144,8 +141,7 @@ class KVCacheSpecRegistry:
|
||||
def get_uniform_type_base_spec(
|
||||
cls, kvcache_spec: "KVCacheSpec"
|
||||
) -> type["KVCacheSpec"] | None:
|
||||
"""
|
||||
Get the base kvcache spec class for grouping compatibility checks.
|
||||
"""Get the base kvcache spec class for grouping compatibility checks.
|
||||
KVCacheSpecs with uniform_type_base_spec will be trated as one group.
|
||||
|
||||
Args:
|
||||
@@ -153,6 +149,7 @@ class KVCacheSpecRegistry:
|
||||
|
||||
Returns:
|
||||
The base KVCacheSpec class for checking uniform type kvcache specs
|
||||
|
||||
"""
|
||||
cls._ensure_registered()
|
||||
kvcache_spec_cls = type(kvcache_spec)
|
||||
@@ -168,9 +165,7 @@ class KVCacheSpecRegistry:
|
||||
def check_kv_cache_spec_registry(
|
||||
cls, kv_cache_spec: dict[str, "KVCacheSpec"]
|
||||
) -> None:
|
||||
"""
|
||||
Check if the KVCacheSpecs of each layer are registered as expected.
|
||||
"""
|
||||
"""Check if the KVCacheSpecs of each layer are registered as expected."""
|
||||
cls._ensure_registered()
|
||||
for layer_name, spec in kv_cache_spec.items():
|
||||
# use raise instead of assert to make it effective in production environment
|
||||
@@ -192,8 +187,7 @@ def register_kv_cache_spec(
|
||||
manager_class: type["SingleTypeKVCacheManager"] | None = None,
|
||||
uniform_type_base_spec: type["KVCacheSpec"] | None = None,
|
||||
):
|
||||
"""
|
||||
Decorator to register a custom KVCacheSpec class.
|
||||
"""Decorator to register a custom KVCacheSpec class.
|
||||
|
||||
Args:
|
||||
manager_class: The SingleTypeKVCacheManager to use for this spec.
|
||||
@@ -211,6 +205,7 @@ def register_kv_cache_spec(
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class CustomFullAttentionSpec(FullAttentionSpec):
|
||||
pass
|
||||
|
||||
"""
|
||||
|
||||
def decorator(kvcache_spec_cls: type["KVCacheSpec"]) -> type["KVCacheSpec"]:
|
||||
|
||||
+32
-39
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Core abstractions for KV cache offloading in vLLM v1.
|
||||
"""
|
||||
"""Core abstractions for KV cache offloading in vLLM v1."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Collection, Iterable, Sequence
|
||||
@@ -149,8 +147,7 @@ class ScheduleEndContext(NamedTuple):
|
||||
|
||||
|
||||
class LoadStoreSpec:
|
||||
"""
|
||||
Metadata that encapsulates information allowing a worker
|
||||
"""Metadata that encapsulates information allowing a worker
|
||||
to load, and optionally also to store, blocks of KV data.
|
||||
"""
|
||||
|
||||
@@ -235,8 +232,7 @@ class OffloadingKVEventsConfig:
|
||||
class OffloadingManager(ABC):
|
||||
@abstractmethod
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Checks whether a single block is offloaded and ready to be read.
|
||||
"""Checks whether a single block is offloaded and ready to be read.
|
||||
|
||||
Args:
|
||||
key: the key identifying the block to lookup.
|
||||
@@ -246,6 +242,7 @@ class OffloadingManager(ABC):
|
||||
HIT if the block is offloaded and ready, MISS if not found,
|
||||
HIT_PENDING if found but not yet readable, or RETRY if the
|
||||
lookup should be retried later.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -255,8 +252,7 @@ class OffloadingManager(ABC):
|
||||
keys: Collection[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
) -> LoadStoreSpec:
|
||||
"""
|
||||
Prepare the given blocks to be read.
|
||||
"""Prepare the given blocks to be read.
|
||||
The given blocks will be protected from eviction until
|
||||
complete_load is called.
|
||||
It assumes all given blocks are offloaded.
|
||||
@@ -268,27 +264,28 @@ class OffloadingManager(ABC):
|
||||
Returns:
|
||||
A LoadStoreSpec that can be used by a worker to locate and load
|
||||
the actual offloaded KV data.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark the given blocks as recently used.
|
||||
"""Mark the given blocks as recently used.
|
||||
This could in practice mean moving them to the end of an LRU list.
|
||||
|
||||
Args:
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
def complete_load(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Marks previous blocks that were prepared to load as done loading.
|
||||
"""Marks previous blocks that were prepared to load as done loading.
|
||||
|
||||
Args:
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@@ -298,8 +295,7 @@ class OffloadingManager(ABC):
|
||||
keys: Collection[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
) -> PrepareStoreOutput | None:
|
||||
"""
|
||||
Prepare the given blocks to be offloaded.
|
||||
"""Prepare the given blocks to be offloaded.
|
||||
The given blocks will be protected from eviction until
|
||||
complete_store is called.
|
||||
|
||||
@@ -312,6 +308,7 @@ class OffloadingManager(ABC):
|
||||
where to store them (LoadStoreSpec), and list of blocks that
|
||||
were evicted as a result.
|
||||
None is returned if the blocks cannot be stored.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -321,8 +318,7 @@ class OffloadingManager(ABC):
|
||||
req_context: ReqContext,
|
||||
success: bool = True,
|
||||
):
|
||||
"""
|
||||
Marks blocks which were previously prepared to be stored, as stored.
|
||||
"""Marks blocks which were previously prepared to be stored, as stored.
|
||||
Following this call, the blocks become loadable.
|
||||
If success is False, blocks that were not marked as stored will be
|
||||
removed.
|
||||
@@ -331,25 +327,25 @@ class OffloadingManager(ABC):
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
success: whether the blocks were stored successfully.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
|
||||
"""
|
||||
Called when a new request is first seen by the scheduler.
|
||||
"""Called when a new request is first seen by the scheduler.
|
||||
|
||||
Returns a RequestOffloadingContext indicating how this request's
|
||||
blocks should be offloaded.
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_request_finished(self, req_context: ReqContext) -> None:
|
||||
"""
|
||||
Called when a request has finished.
|
||||
"""Called when a request has finished.
|
||||
|
||||
By the time this is called, the scheduler will issue no more
|
||||
submit-side calls for this request, such as prepare_store() and
|
||||
@@ -364,12 +360,12 @@ class OffloadingManager(ABC):
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
def take_events(self) -> Iterable[OffloadingEvent]:
|
||||
"""
|
||||
Take the offloading events from the manager.
|
||||
"""Take the offloading events from the manager.
|
||||
|
||||
A tier manager emits only events for storage state it owns. A
|
||||
composing manager may aggregate child event streams, but should not
|
||||
@@ -377,6 +373,7 @@ class OffloadingManager(ABC):
|
||||
|
||||
Yields:
|
||||
New OffloadingEvents collected since the last call.
|
||||
|
||||
"""
|
||||
return ()
|
||||
|
||||
@@ -410,8 +407,7 @@ class OffloadingManager(ABC):
|
||||
|
||||
|
||||
class BlockIDsLoadStoreSpec(LoadStoreSpec, ABC):
|
||||
"""
|
||||
Spec for loading/storing KV blocks from given block numbers.
|
||||
"""Spec for loading/storing KV blocks from given block numbers.
|
||||
|
||||
Subclass semantics differ: GPULoadStoreSpec.block_ids are GPU block
|
||||
indices; CPULoadStoreSpec.block_ids are CPU cache chunk indices.
|
||||
@@ -425,8 +421,7 @@ class BlockIDsLoadStoreSpec(LoadStoreSpec, ABC):
|
||||
|
||||
|
||||
class GPULoadStoreSpec(BlockIDsLoadStoreSpec):
|
||||
"""
|
||||
Spec for loading/storing a KV block to GPU memory.
|
||||
"""Spec for loading/storing a KV block to GPU memory.
|
||||
|
||||
If there are multiple KV groups, the blocks are expected to be
|
||||
ordered by the group index.
|
||||
@@ -460,8 +455,7 @@ class GPULoadStoreSpec(BlockIDsLoadStoreSpec):
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCacheTensor:
|
||||
"""
|
||||
A canonicalized KV cache tensor whose first dimension is num_blocks.
|
||||
"""A canonicalized KV cache tensor whose first dimension is num_blocks.
|
||||
|
||||
With standardized layouts (RFC #42082) num_blocks is always the leading
|
||||
logical dimension.
|
||||
@@ -478,7 +472,8 @@ class CopyRun:
|
||||
"""A strided byte correspondence between this worker's physical page and
|
||||
a canonical page: for i in range(num_fragments), fragment i spans
|
||||
[local_offset + i * local_stride, +fragment_size) in the worker's page and
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically."""
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically.
|
||||
"""
|
||||
|
||||
local_offset: int
|
||||
canonical_offset: int
|
||||
@@ -517,8 +512,7 @@ class CanonicalPageMapping:
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCacheRef:
|
||||
"""
|
||||
Per-layer (or group of layers) reference to a specific (by index)
|
||||
"""Per-layer (or group of layers) reference to a specific (by index)
|
||||
CanonicalKVCacheTensor and records the un-padded page size used by that layer.
|
||||
"""
|
||||
|
||||
@@ -532,8 +526,7 @@ class CanonicalKVCacheRef:
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCaches:
|
||||
"""
|
||||
Canonicalized block-level representation of the KV caches.
|
||||
"""Canonicalized block-level representation of the KV caches.
|
||||
|
||||
Composed of:
|
||||
- Unique list of KV cache data tensors,
|
||||
@@ -561,7 +554,8 @@ class TransferResult:
|
||||
class OffloadingWorker(ABC):
|
||||
"""Runs in the worker process. Performs async KV transfers for ONE
|
||||
offloaded medium (e.g. CPU). Direction is explicit via submit_store /
|
||||
submit_load, so there is no (src_medium, dst_medium) routing."""
|
||||
submit_load, so there is no (src_medium, dst_medium) routing.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def submit_store(
|
||||
@@ -620,8 +614,7 @@ class OffloadingSpec(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
"""
|
||||
Get an OffloadingManager that will be used
|
||||
"""Get an OffloadingManager that will be used
|
||||
by the scheduler-side offloading connector to track
|
||||
offloaded blocks and manage evictions.
|
||||
"""
|
||||
@@ -629,13 +622,13 @@ class OffloadingSpec(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def get_worker(self, kv_caches: CanonicalKVCaches) -> OffloadingWorker:
|
||||
"""
|
||||
Get an OffloadingWorker that handles async KV transfers for this spec.
|
||||
"""Get an OffloadingWorker that handles async KV transfers for this spec.
|
||||
|
||||
Args:
|
||||
kv_caches: Canonicalized KV caches.
|
||||
|
||||
Returns:
|
||||
An OffloadingWorker instance for this medium.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -80,8 +80,7 @@ def compute_sub_block_ptrs(
|
||||
tensor: torch.Tensor,
|
||||
skip_count: int = 0,
|
||||
):
|
||||
"""
|
||||
Compute byte pointers for sub-blocks of the given block IDs.
|
||||
"""Compute byte pointers for sub-blocks of the given block IDs.
|
||||
|
||||
Each block in block_ids contains blocks_per_chunk sub-blocks.
|
||||
The pointer for sub-block j of block b is:
|
||||
@@ -98,6 +97,7 @@ def compute_sub_block_ptrs(
|
||||
output: pre-allocated pointer array to write pointers into.
|
||||
tensor: the source or destination tensor.
|
||||
skip_count: sub-blocks to skip in the first block.
|
||||
|
||||
"""
|
||||
assert skip_count < blocks_per_chunk
|
||||
|
||||
@@ -126,7 +126,8 @@ def compute_sub_block_ptrs(
|
||||
class CopyPlan(NamedTuple):
|
||||
"""Precomputed fragment-copy template for one data ref under the canonical
|
||||
CPU layout, unrolled from the ref's mapped runs. Offsets are relative to
|
||||
the per-block base pointers on each side."""
|
||||
the per-block base pointers on each side.
|
||||
"""
|
||||
|
||||
frag_offsets_src: np.ndarray
|
||||
frag_offsets_dst: np.ndarray
|
||||
@@ -164,7 +165,8 @@ def _canonical_page_ids(
|
||||
) -> np.ndarray:
|
||||
"""Global canonical page ids matching compute_sub_block_ptrs' enumeration.
|
||||
These identify canonical pages consistently across ranks, so they key
|
||||
CanonicalPageMapping.is_writer rotation."""
|
||||
CanonicalPageMapping.is_writer rotation.
|
||||
"""
|
||||
if blocks_per_chunk == 1:
|
||||
return block_ids[:count]
|
||||
flat = (
|
||||
@@ -177,7 +179,8 @@ def _canonical_block_sizes(
|
||||
layer_refs_per_group: list[list[CanonicalKVCacheRef]], num_tensors: int
|
||||
) -> list[int]:
|
||||
"""Canonical CPU bytes per GPU block for each tensor, taken from the refs'
|
||||
mappings. Requires every ref to carry a mapping."""
|
||||
mappings. Requires every ref to carry a mapping.
|
||||
"""
|
||||
canonical_bytes_per_block = [0] * num_tensors
|
||||
for layer_refs in layer_refs_per_group:
|
||||
for ref in layer_refs:
|
||||
@@ -234,8 +237,7 @@ def _new_descriptor_buffers(
|
||||
|
||||
|
||||
class SingleDirectionOffloadingHandler:
|
||||
"""
|
||||
Handles transfers for a single direction, either CPU->GPU or GPU->CPU.
|
||||
"""Handles transfers for a single direction, either CPU->GPU or GPU->CPU.
|
||||
Transfers are guaranteed to be executed in order of their submission.
|
||||
Each transfer uses a unique CUDA stream, and its stream will start
|
||||
executing only after the streams of previous transfers have finished.
|
||||
@@ -250,8 +252,7 @@ class SingleDirectionOffloadingHandler:
|
||||
gpu_to_cpu: bool,
|
||||
canonical_layout: bool = False,
|
||||
):
|
||||
"""
|
||||
Initialize a SingleDirectionOffloadingHandler.
|
||||
"""Initialize a SingleDirectionOffloadingHandler.
|
||||
|
||||
Args:
|
||||
gpu_tensors: list of GPU KV cache tensors.
|
||||
@@ -259,10 +260,12 @@ class SingleDirectionOffloadingHandler:
|
||||
cpu_tensors: list of CPU KV cache tensors.
|
||||
Each of shape (num_cpu_chunks, cpu_page_size_bytes) with dtype int8.
|
||||
Order should match gpu_tensors.
|
||||
blocks_per_chunk: number of blocks transferred per chunk.
|
||||
layer_refs_per_group: list of CanonicalKVCacheRef per group.
|
||||
gpu_to_cpu: if True, transfer from GPU to CPU; otherwise CPU to GPU.
|
||||
canonical_layout: if True, CPU pages use the canonical layout
|
||||
described by the refs' mappings.
|
||||
|
||||
"""
|
||||
assert len(gpu_tensors) == len(cpu_tensors)
|
||||
assert len(gpu_tensors) > 0
|
||||
@@ -340,7 +343,8 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Upper bound on the number of copy descriptors for a transfer.
|
||||
|
||||
Exact for the direct layout. The canonical path may fill fewer:
|
||||
writer rotation later drops the blocks this rank does not write."""
|
||||
writer rotation later drops the blocks this rank does not write.
|
||||
"""
|
||||
num_copy_ops = 0
|
||||
for g_idx, (group_size, layer_refs) in enumerate(
|
||||
zip(group_sizes, self.layer_refs_per_group)
|
||||
@@ -369,7 +373,8 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Fill one group's copy descriptors for the direct (worker-private)
|
||||
layout: one whole-page copy per (block, ref).
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
num_bytes = 0
|
||||
for data_ref in self.layer_refs_per_group[g_idx]:
|
||||
t_idx = data_ref.tensor_idx
|
||||
@@ -412,7 +417,8 @@ class SingleDirectionOffloadingHandler:
|
||||
scatter each block through the ref's precomputed CopyPlan, keeping
|
||||
only the blocks this rank writes.
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
assert self._canonical_copy_plans is not None
|
||||
# Zero-copy reinterpretation for pointer arithmetic: uint64 and the
|
||||
# buffers' int64 are bit-equivalent for addresses
|
||||
@@ -499,7 +505,8 @@ class SingleDirectionOffloadingHandler:
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Keep only the blocks this rank writes: replicated ranks take turns
|
||||
writing shared canonical pages, keyed by the rank-consistent CPU-side
|
||||
canonical page id."""
|
||||
canonical page id.
|
||||
"""
|
||||
cpu_page_ids = _canonical_page_ids(
|
||||
group_dst,
|
||||
self.dst_blocks_per_chunk,
|
||||
|
||||
@@ -44,8 +44,7 @@ class _RequestCacheAccess:
|
||||
|
||||
|
||||
class CPUOffloadingManager(OffloadingManager):
|
||||
"""
|
||||
An OffloadingManager with a pluggable CachePolicy, resolved by name via
|
||||
"""An OffloadingManager with a pluggable CachePolicy, resolved by name via
|
||||
CachePolicyFactory (built in: "lru", "arc"; external policies can either
|
||||
register their own or be loaded out-of-tree via cache_policy_module_path).
|
||||
|
||||
|
||||
@@ -14,8 +14,7 @@ from vllm.v1.kv_offload.cpu.policies.base import (
|
||||
|
||||
|
||||
class ARCCachePolicy(CachePolicy):
|
||||
"""
|
||||
ARC (Adaptive Replacement Cache) cache policy.
|
||||
"""ARC (Adaptive Replacement Cache) cache policy.
|
||||
|
||||
Data Structures:
|
||||
T1: Recent cache containing chunks accessed once.
|
||||
|
||||
@@ -23,8 +23,7 @@ def order_request_keys(
|
||||
|
||||
|
||||
class ChunkStatus(ctypes.Structure):
|
||||
"""
|
||||
Offloading status for a single chunk of KV data.
|
||||
"""Offloading status for a single chunk of KV data.
|
||||
Holds the following information:
|
||||
|
||||
ref_cnt - the current number of transfers using this chunk as a source.
|
||||
@@ -42,15 +41,12 @@ class ChunkStatus(ctypes.Structure):
|
||||
|
||||
@property
|
||||
def is_ready(self) -> bool:
|
||||
"""
|
||||
Returns whether the chunk is ready to be read.
|
||||
"""
|
||||
"""Returns whether the chunk is ready to be read."""
|
||||
return self.ref_cnt >= 0
|
||||
|
||||
|
||||
class CachePolicy(ABC):
|
||||
"""
|
||||
Encapsulates both chunk organization (data structures) and replacement
|
||||
"""Encapsulates both chunk organization (data structures) and replacement
|
||||
decisions (which chunk to evict). LRU and ARC differ in both dimensions —
|
||||
ARC's ghost lists and target_t1_size live at the intersection of storage
|
||||
and eviction, so they cannot be separated cleanly.
|
||||
@@ -73,12 +69,12 @@ class CachePolicy(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
|
||||
"""
|
||||
Mark chunks as recently used.
|
||||
"""Mark chunks as recently used.
|
||||
|
||||
Args:
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context for the request touching these chunks.
|
||||
|
||||
"""
|
||||
|
||||
def on_store_miss(
|
||||
@@ -120,8 +116,7 @@ class CachePolicy(ABC):
|
||||
def evict(
|
||||
self, n: int, protected: set[OffloadKey]
|
||||
) -> list[tuple[OffloadKey, ChunkStatus]] | None:
|
||||
"""
|
||||
Evict exactly n chunks, skipping any in protected.
|
||||
"""Evict exactly n chunks, skipping any in protected.
|
||||
|
||||
Returns a list of (key, chunk) for the evicted chunks,
|
||||
or None if n evictions cannot be satisfied. The operation is atomic:
|
||||
@@ -133,8 +128,7 @@ class CachePolicy(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def clear(self) -> None:
|
||||
"""
|
||||
Remove ALL chunks regardless of ref_cnt.
|
||||
"""Remove ALL chunks regardless of ref_cnt.
|
||||
|
||||
Ghost lists and adaptive state are also reset.
|
||||
"""
|
||||
|
||||
@@ -57,6 +57,7 @@ class CachePolicyFactory:
|
||||
|
||||
Raises ValueError if the cache policy is neither registered nor
|
||||
resolvable via `module_path`.
|
||||
|
||||
"""
|
||||
if name in cls._registry:
|
||||
return cls._registry[name]()
|
||||
|
||||
@@ -14,8 +14,7 @@ from vllm.v1.kv_offload.cpu.policies.base import (
|
||||
|
||||
|
||||
class LRUCachePolicy(CachePolicy):
|
||||
"""
|
||||
LRU caching policy with logical recency independent of transfer pinning.
|
||||
"""LRU caching policy with logical recency independent of transfer pinning.
|
||||
|
||||
Evictable chunks live in a lazy-invalidating min-heap. A chunk's recency
|
||||
can therefore be updated while it is pinned; when it later becomes
|
||||
|
||||
@@ -69,8 +69,7 @@ def _get_populate_write_fn(
|
||||
|
||||
|
||||
class SharedOffloadRegion:
|
||||
"""
|
||||
Single mmap-backed memory region shared across all workers for a
|
||||
"""Single mmap-backed memory region shared across all workers for a
|
||||
vLLM instance. Workers coordinate via the filesystem: the first worker
|
||||
to open the file with O_EXCL becomes the creator and calls ftruncate;
|
||||
the rest open the existing file and wait until it reaches the expected
|
||||
@@ -264,6 +263,7 @@ class SharedOffloadRegion:
|
||||
|
||||
Args:
|
||||
tensor_page_size: Bytes per chunk for this tensor.
|
||||
|
||||
"""
|
||||
assert self.rank is not None
|
||||
new_offset = self._worker_offset + tensor_page_size
|
||||
@@ -313,6 +313,7 @@ class SharedOffloadRegion:
|
||||
|
||||
Args:
|
||||
tensor_page_size: Canonical bytes per chunk for this tensor.
|
||||
|
||||
"""
|
||||
new_offset = self._canonical_offset + tensor_page_size
|
||||
assert new_offset <= self._row_stride
|
||||
|
||||
@@ -28,7 +28,8 @@ def _all_workers_barrier() -> None:
|
||||
"""Block until every worker rank has reached this point (gloo cpu group).
|
||||
|
||||
A superset of the node-local mmap openers suffices: once the barrier
|
||||
releases, every worker sharing the region file has mapped it."""
|
||||
releases, every worker sharing the region file has mapped it.
|
||||
"""
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_inner_dp_world_group,
|
||||
get_world_group,
|
||||
@@ -161,7 +162,8 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
|
||||
def _uses_shared_region(self) -> bool:
|
||||
"""Whether the worker CPU buffer is the shared mmap region (vs a private
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True."""
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True.
|
||||
"""
|
||||
return current_platform.is_cuda_alike()
|
||||
|
||||
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
|
||||
|
||||
@@ -19,9 +19,7 @@ _CONFIG_FILENAME = "config.json"
|
||||
|
||||
|
||||
class FileMapper:
|
||||
"""
|
||||
FileMapper maps KV blocks (given by their hash) to file names.
|
||||
"""
|
||||
"""FileMapper maps KV blocks (given by their hash) to file names."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -41,8 +39,7 @@ class FileMapper:
|
||||
replicated_layout: bool = False,
|
||||
canonical_format: str | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the file mapper. Each worker constructs its own, but
|
||||
"""Initialize the file mapper. Each worker constructs its own, but
|
||||
`config.json` is shared across workers since rank lives outside the hash.
|
||||
When `parallel_agnostic=True`, tp/pp/pcp/dcp are forced to 1 and rank
|
||||
to 0 so multiple parallelism layouts collapse into the same folder.
|
||||
@@ -136,8 +133,7 @@ class FileMapper:
|
||||
|
||||
@staticmethod
|
||||
def _compute_base_path(root_dir: str, fields: dict) -> str:
|
||||
"""
|
||||
Layout: <root_dir>/<safe_model_name>_<sha256-prefix>/.
|
||||
"""Layout: <root_dir>/<safe_model_name>_<sha256-prefix>/.
|
||||
safe_model_name replaces '/' with '_' so HuggingFace IDs don't nest.
|
||||
"""
|
||||
canonical = json.dumps(fields, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
AsyncLookupManager: per-tier async lookup manager for secondary tier
|
||||
"""AsyncLookupManager: per-tier async lookup manager for secondary tier
|
||||
existence checks.
|
||||
|
||||
Each secondary tier that wants non-blocking lookups composes its own
|
||||
@@ -65,8 +64,7 @@ class LookupState:
|
||||
|
||||
|
||||
class AsyncLookupManager(ABC):
|
||||
"""
|
||||
Per-tier async lookup manager for secondary tier existence checks.
|
||||
"""Per-tier async lookup manager for secondary tier existence checks.
|
||||
|
||||
Each secondary tier that wants non-blocking lookups composes its own
|
||||
AsyncLookupManager instance internally. The manager maintains lookup
|
||||
@@ -126,8 +124,7 @@ class AsyncLookupManager(ABC):
|
||||
def batch_lookup(
|
||||
self, keys: list[OffloadKey], req_context: ReqContext
|
||||
) -> Iterable[bool]:
|
||||
"""
|
||||
Check whether a batch of blocks exist in this tier.
|
||||
"""Check whether a batch of blocks exist in this tier.
|
||||
|
||||
Called from the worker thread — must be synchronous and must not
|
||||
touch the primary tier or scheduler state.
|
||||
@@ -141,13 +138,13 @@ class AsyncLookupManager(ABC):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> bool | None:
|
||||
"""
|
||||
Non-blocking lookup called from the scheduler thread.
|
||||
"""Non-blocking lookup called from the scheduler thread.
|
||||
|
||||
Returns:
|
||||
True — block is present in this tier.
|
||||
False — block is not present in this tier.
|
||||
None — result not yet available; retry next step.
|
||||
|
||||
"""
|
||||
if self._need_to_drain:
|
||||
self.drain_results()
|
||||
@@ -219,7 +216,8 @@ class AsyncLookupManager(ABC):
|
||||
def mark_miss(self, keys: Collection[OffloadKey]) -> None:
|
||||
"""Force the cached verdict for ``keys`` to False after a failed load, so
|
||||
the scheduler stops re-issuing the doomed promotion (livelock, #49176).
|
||||
Keys with no cached entry are skipped."""
|
||||
Keys with no cached entry are skipped.
|
||||
"""
|
||||
for key in keys:
|
||||
state = self._lookup_state.get(key)
|
||||
if state is not None:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Abstract interfaces and data types for the secondary tiering layer.
|
||||
"""
|
||||
"""Abstract interfaces and data types for the secondary tiering layer."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Collection, Iterable
|
||||
@@ -119,8 +117,7 @@ class ParentManager(ABC):
|
||||
|
||||
|
||||
class SecondaryTierManager(ABC):
|
||||
"""
|
||||
Abstract interface for managing a single non-primary offloading tier.
|
||||
"""Abstract interface for managing a single non-primary offloading tier.
|
||||
|
||||
Secondary tiers cannot directly access GPU memory. All data transfers
|
||||
must go through the CPU (primary) tier:
|
||||
@@ -140,12 +137,12 @@ class SecondaryTierManager(ABC):
|
||||
primary_kv_view: memoryview,
|
||||
tier_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory
|
||||
from the registered tier type.
|
||||
"""Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory
|
||||
from the registered tier type.
|
||||
|
||||
"""
|
||||
self._offloading_spec = offloading_spec
|
||||
self._primary_kv_view: memoryview = primary_kv_view
|
||||
@@ -154,8 +151,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
"""Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
@@ -165,13 +161,13 @@ class SecondaryTierManager(ABC):
|
||||
HIT if the chunk is present and ready,
|
||||
MISS if not found,
|
||||
or RETRY if the chunk is being transferred (retry later).
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def submit_store(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit an async job to store chunks from the primary tier to this
|
||||
"""Submit an async job to store chunks from the primary tier to this
|
||||
secondary tier.
|
||||
|
||||
This method must be lightweight and non-blocking: allocate metadata
|
||||
@@ -193,13 +189,13 @@ class SecondaryTierManager(ABC):
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to read from.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit an async job to load chunks from this secondary tier to the
|
||||
"""Submit an async job to load chunks from this secondary tier to the
|
||||
primary tier.
|
||||
|
||||
This method must be lightweight and non-blocking: mark chunks as
|
||||
@@ -218,13 +214,13 @@ class SecondaryTierManager(ABC):
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to write into.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""
|
||||
Return all jobs (loads and stores) that completed since the last call.
|
||||
"""Return all jobs (loads and stores) that completed since the last call.
|
||||
|
||||
The framework uses these results to release resources and finalize
|
||||
transfers.
|
||||
@@ -232,6 +228,7 @@ class SecondaryTierManager(ABC):
|
||||
Returns:
|
||||
Iterable of JobResult objects for jobs finished since the
|
||||
last call.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -248,31 +245,30 @@ class SecondaryTierManager(ABC):
|
||||
return ()
|
||||
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as recently used for eviction policy.
|
||||
"""Mark chunks as recently used for eviction policy.
|
||||
|
||||
Args:
|
||||
keys: Offload keys to mark as recently used.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
|
||||
"""
|
||||
Called when a new request is first seen by the scheduler.
|
||||
"""Called when a new request is first seen by the scheduler.
|
||||
|
||||
Returns a RequestOffloadingContext expressing this tier's preference
|
||||
for how chunks should be offloaded for this request.
|
||||
|
||||
Args:
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_request_finished(self, req_context: ReqContext) -> None:
|
||||
"""
|
||||
Called when a request has finished.
|
||||
"""Called when a request has finished.
|
||||
|
||||
By the time this is called, all per-request calls for this request
|
||||
(submit_store, submit_load, touch) have already been issued, and none
|
||||
@@ -283,6 +279,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@@ -300,6 +297,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
Args:
|
||||
context: Per-step context from the scheduler.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
ExampleSecondaryTierManager: A simple in-memory secondary tier.
|
||||
"""ExampleSecondaryTierManager: A simple in-memory secondary tier.
|
||||
|
||||
This implementation provides a minimal secondary tier that stores chunks
|
||||
in memory (using a dictionary) with immediate completion. It serves as a
|
||||
@@ -35,8 +34,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
"""
|
||||
A simple in-memory secondary tier.
|
||||
"""A simple in-memory secondary tier.
|
||||
|
||||
This implementation:
|
||||
- Stores chunks in a dictionary (key -> True)
|
||||
@@ -52,11 +50,14 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
tier_type: str,
|
||||
custom_param: int = 0,
|
||||
):
|
||||
"""
|
||||
Initialize the example secondary tier.
|
||||
"""Initialize the example secondary tier.
|
||||
|
||||
Args:
|
||||
offloading_spec: The offloading spec this tier belongs to.
|
||||
primary_kv_view: Memoryview over the primary tier's KV buffer.
|
||||
tier_type: Name identifying this tier type.
|
||||
custom_param: Dummy parameter demonstrating custom args.
|
||||
|
||||
"""
|
||||
super().__init__(
|
||||
offloading_spec=offloading_spec,
|
||||
@@ -78,8 +79,7 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
"""Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
@@ -87,17 +87,18 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
Returns:
|
||||
HIT if the chunk is present, MISS if not found.
|
||||
|
||||
"""
|
||||
return LookupResult.HIT if key in self.chunks else LookupResult.MISS
|
||||
|
||||
@override
|
||||
def submit_store(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit a job to store chunks from primary tier to this tier.
|
||||
"""Submit a job to store chunks from primary tier to this tier.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and
|
||||
spec for reading chunks from the primary tier.
|
||||
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
@@ -118,12 +119,12 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit a job to load chunks from this tier to primary tier.
|
||||
"""Submit a job to load chunks from this tier to primary tier.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and
|
||||
spec for writing chunks into the primary tier.
|
||||
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
@@ -149,12 +150,12 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""
|
||||
Poll for finished jobs.
|
||||
"""Poll for finished jobs.
|
||||
|
||||
Returns:
|
||||
Iterable of JobResult objects for all jobs that have
|
||||
finished since the last call.
|
||||
|
||||
"""
|
||||
result = self.completed_jobs
|
||||
self.completed_jobs = []
|
||||
@@ -167,7 +168,8 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def drain_jobs(self) -> None:
|
||||
"""Synchronous tier — submit_*() returns only after the operation
|
||||
completes, so there is nothing to wait for."""
|
||||
completes, so there is nothing to wait for.
|
||||
"""
|
||||
return
|
||||
|
||||
def get_num_chunks(self) -> int:
|
||||
|
||||
@@ -71,6 +71,7 @@ class SecondaryTierFactory:
|
||||
Raises:
|
||||
ValueError: If 'type' is missing, or is neither registered nor
|
||||
resolvable via module_path.
|
||||
|
||||
"""
|
||||
tier_type = tier_config.get("type")
|
||||
if not tier_type:
|
||||
|
||||
@@ -94,9 +94,7 @@ def _store_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Store callback: Writes to a temp file then atomically replaces the destination.
|
||||
"""
|
||||
"""Store callback: write to a temp file then atomically replace the target."""
|
||||
# Check if block already exists to avoid redundant writes
|
||||
if os.path.exists(dest_path):
|
||||
return
|
||||
@@ -141,7 +139,8 @@ def _load_block(
|
||||
) -> None:
|
||||
"""Read one KV block from disk; remove the file only on a provable short
|
||||
read (a too-short file is genuine corruption) and leave it untouched on any
|
||||
other error."""
|
||||
other error.
|
||||
"""
|
||||
fd: int | None = None
|
||||
view_slice = view.cast("B")[offset : offset + block_size]
|
||||
o_direct = O_DIRECT if use_o_direct else 0
|
||||
@@ -172,8 +171,7 @@ def batch_store_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Store a batch of KV blocks from a shared buffer to disk in one call.
|
||||
"""Store a batch of KV blocks from a shared buffer to disk in one call.
|
||||
|
||||
Each block buffer[offsets[i] : offsets[i]+block_size] is written atomically
|
||||
to dest_paths[i] via a temp-file rename. Raises on first error.
|
||||
@@ -197,8 +195,7 @@ def batch_load_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Load a batch of KV blocks from disk into a shared buffer in one call.
|
||||
"""Load a batch of KV blocks from disk into a shared buffer in one call.
|
||||
|
||||
Block i is read from source_paths[i] into view[offsets[i] : offsets[i]+block_size].
|
||||
Raises on first error (see _load_block for the delete-on-short-read policy).
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
FileSystemTierManager: Pure-Python file system secondary tier for KV cache offloading.
|
||||
"""FileSystemTierManager: pure-Python filesystem tier for KV cache offloading.
|
||||
|
||||
Store path:
|
||||
Data is written to a temp file (<dest_path.tmp>) via os.write,
|
||||
@@ -84,8 +83,7 @@ class FsAsyncLookupManager(AsyncLookupManager):
|
||||
|
||||
|
||||
class FileSystemTierManager(SecondaryTierManager):
|
||||
"""
|
||||
Pure-Python disk-backed secondary tier.
|
||||
"""Pure-Python disk-backed secondary tier.
|
||||
|
||||
Read-priority threads service load jobs preferentially; write-priority
|
||||
threads service store jobs preferentially. Both groups can drain either
|
||||
@@ -118,20 +116,20 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
enable_kv_events: bool = False,
|
||||
locality: str | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Contains normalized offloading configuration and
|
||||
blocks_per_chunk.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
root_dir: Root directory for block files.
|
||||
n_read_threads: Number of read-priority I/O threads.
|
||||
n_write_threads: Number of write-priority I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
"""Args:
|
||||
offloading_spec: Contains normalized offloading configuration and
|
||||
blocks_per_chunk.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
root_dir: Root directory for block files.
|
||||
n_read_threads: Number of read-priority I/O threads.
|
||||
n_write_threads: Number of write-priority I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
self.locality = Locality(locality) if locality is not None else None
|
||||
@@ -271,7 +269,8 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Collect finished jobs; a failed promotion marks only its failed keys
|
||||
as a miss here (scheduler thread)."""
|
||||
as a miss here (scheduler thread).
|
||||
"""
|
||||
results = []
|
||||
for job_id, success, transfer_time in self._pool.get_finished():
|
||||
if self.events is not None:
|
||||
@@ -333,8 +332,7 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def shutdown(self) -> None:
|
||||
"""
|
||||
Release resources held by this tier.
|
||||
"""Release resources held by this tier.
|
||||
|
||||
Shuts down the lookup manager and the thread pool,
|
||||
clearing pending tasks and waiting for active threads to complete.
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Thread pool:
|
||||
Two queues (load, store) and two sets of threads:
|
||||
- Load-priority threads: drain the load queue first, then the store queue.
|
||||
- Store-priority threads: drain the store queue first, then the load queue.
|
||||
Load jobs are enqueued to the load queue; store jobs to the store queue.
|
||||
"""Thread pool:
|
||||
Two queues (load, store) and two sets of threads:
|
||||
- Load-priority threads: drain the load queue first, then the store queue.
|
||||
- Store-priority threads: drain the store queue first, then the load queue.
|
||||
Load jobs are enqueued to the load queue; store jobs to the store queue.
|
||||
"""
|
||||
|
||||
import threading
|
||||
@@ -20,8 +19,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class JobState:
|
||||
"""
|
||||
Thread-safe completion tracker for a set of per-block I/O tasks.
|
||||
"""Thread-safe completion tracker for a set of per-block I/O tasks.
|
||||
|
||||
Each task calls task_done(success) when it finishes.
|
||||
"""
|
||||
@@ -50,7 +48,7 @@ class JobState:
|
||||
def task_done(
|
||||
self, success: bool, transfer_time: float
|
||||
) -> tuple[bool, bool, float]:
|
||||
"""Returns if job completed and success flag"""
|
||||
"""Returns if job completed and success flag."""
|
||||
with self._lock:
|
||||
self._completed += 1
|
||||
self._transfer_time += transfer_time
|
||||
@@ -60,8 +58,7 @@ class JobState:
|
||||
|
||||
|
||||
class DualQueueThreadPool:
|
||||
"""
|
||||
Thread pool with two task queues (load and store) and two thread groups.
|
||||
"""Thread pool with two task queues (load and store) and two thread groups.
|
||||
|
||||
Load-priority threads drain the load queue first, then fall back to the
|
||||
store queue. Store-priority threads do the reverse. Both queues share
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
TieringOffloadingManager: Multi-tier KV cache offloading orchestrator.
|
||||
"""TieringOffloadingManager: Multi-tier KV cache offloading orchestrator.
|
||||
|
||||
This manager coordinates between a CPU primary tier (with direct GPU access)
|
||||
and zero or more secondary tiers (Storage, Network, etc.) to provide
|
||||
@@ -144,7 +143,8 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
|
||||
|
||||
class _SecondaryTierFacingParent(ParentManager):
|
||||
"""Wrapper that implements ParentManager by delegating to the
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier."""
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier.
|
||||
"""
|
||||
|
||||
__slots__ = ("_m", "_origin_idx")
|
||||
|
||||
@@ -174,8 +174,7 @@ class _SecondaryTierFacingParent(ParentManager):
|
||||
|
||||
|
||||
class TieringOffloadingManager(OffloadingManager):
|
||||
"""
|
||||
Orchestrates multi-tier KV cache offloading.
|
||||
"""Orchestrates multi-tier KV cache offloading.
|
||||
|
||||
This manager coordinates between a CPU primary tier (with direct GPU access)
|
||||
and zero or more secondary tiers (Storage, Network, etc.) to provide
|
||||
@@ -194,13 +193,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
primary_tier: CPUPrimaryTierOffloadingManager,
|
||||
secondary_tiers: list[SecondaryTierManager] | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the TieringOffloadingManager.
|
||||
"""Initialize the TieringOffloadingManager.
|
||||
|
||||
Args:
|
||||
primary_tier: The primary tier manager (CPU-based).
|
||||
secondary_tiers: List of secondary tier managers (e.g., Storage,
|
||||
Network). Can be None or empty list.
|
||||
|
||||
"""
|
||||
self.primary_tier: CPUPrimaryTierOffloadingManager = primary_tier
|
||||
self.secondary_tiers = secondary_tiers or []
|
||||
@@ -259,8 +258,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
return self._jobs.pop(job_id, None)
|
||||
|
||||
def _maybe_process_finished_jobs(self):
|
||||
"""
|
||||
Poll secondary tiers for completed jobs (at most once per step).
|
||||
"""Poll secondary tiers for completed jobs (at most once per step).
|
||||
|
||||
Guarded by _processed_jobs_this_step: the first call in an engine step
|
||||
does the actual polling; subsequent calls are no-ops. The flag is reset
|
||||
@@ -306,8 +304,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
)
|
||||
|
||||
def _process_finished_jobs(self):
|
||||
"""
|
||||
Unconditionally poll all secondary tiers for completed jobs.
|
||||
"""Unconditionally poll all secondary tiers for completed jobs.
|
||||
|
||||
This method:
|
||||
1. Calls get_finished_jobs() on each secondary tier
|
||||
@@ -350,8 +347,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
*,
|
||||
exclude_tier_idx: int | None = None,
|
||||
) -> LookupResult:
|
||||
"""
|
||||
Check whether a single chunk is offloaded and ready.
|
||||
"""Check whether a single chunk is offloaded and ready.
|
||||
|
||||
Algorithm:
|
||||
1. Process any completed async jobs first.
|
||||
@@ -362,6 +358,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Args:
|
||||
key: Chunk hash to look up.
|
||||
req_context: Per-request context.
|
||||
exclude_tier_idx: Skip this tier index during the lookup.
|
||||
|
||||
Returns:
|
||||
HIT — chunk is ready in the primary tier.
|
||||
@@ -370,6 +367,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
RETRY — promotion started or a secondary tier is busy.
|
||||
MISS — chunk not found in any tier, or primary is full
|
||||
and cannot accept a promotion.
|
||||
|
||||
"""
|
||||
# Poll first so a promotion that finished since the last call is
|
||||
# already reflected as HIT (not stale HIT_PENDING/MISS) below, and
|
||||
@@ -432,8 +430,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
key: OffloadKey,
|
||||
req_context: ReqContext,
|
||||
) -> bool:
|
||||
"""
|
||||
Queue a chunk for promotion from a secondary tier to the primary tier.
|
||||
"""Queue a chunk for promotion from a secondary tier to the primary tier.
|
||||
|
||||
Allocates space in the primary tier immediately (sets ref_cnt=-1 so
|
||||
subsequent lookups within the same step see the slot as in-flight),
|
||||
@@ -448,6 +445,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Returns:
|
||||
True if promotion was initiated, False if primary tier is full.
|
||||
|
||||
"""
|
||||
# Allocate space in primary tier for promoted chunk.
|
||||
# Must happen immediately so primary.lookup() returns None (in-flight)
|
||||
@@ -505,8 +503,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
def prepare_load(
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> LoadStoreSpec:
|
||||
"""
|
||||
Prepare chunks to be loaded from primary tier to GPU.
|
||||
"""Prepare chunks to be loaded from primary tier to GPU.
|
||||
|
||||
Callers only pass keys already confirmed HIT by lookup() earlier this
|
||||
step.
|
||||
@@ -520,17 +517,18 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Returns:
|
||||
LoadStoreSpec for reading from primary tier.
|
||||
|
||||
"""
|
||||
return self.primary_tier.prepare_load(keys, req_context)
|
||||
|
||||
@override
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as recently used in all tiers.
|
||||
"""Mark chunks as recently used in all tiers.
|
||||
|
||||
Args:
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
self.primary_tier.touch(keys, req_context)
|
||||
for tier in self.secondary_tiers:
|
||||
@@ -538,8 +536,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
@override
|
||||
def complete_load(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as done loading from primary tier to GPU.
|
||||
"""Mark chunks as done loading from primary tier to GPU.
|
||||
|
||||
This decrements ref_cnt on the chunks in the primary tier, allowing
|
||||
them to be evicted again.
|
||||
@@ -547,6 +544,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Args:
|
||||
keys: Chunks that finished loading.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
self.primary_tier.complete_load(keys, req_context)
|
||||
|
||||
@@ -554,8 +552,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
def prepare_store(
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> PrepareStoreOutput | None:
|
||||
"""
|
||||
Prepare chunks to be stored from GPU to primary tier.
|
||||
"""Prepare chunks to be stored from GPU to primary tier.
|
||||
|
||||
CRITICAL: This method calls _maybe_process_finished_jobs() FIRST to ensure
|
||||
that any completed async transfers have their ref_cnt decremented
|
||||
@@ -571,6 +568,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Returns:
|
||||
PrepareStoreOutput describing where to store chunks and what was
|
||||
evicted, or None if store cannot proceed.
|
||||
|
||||
"""
|
||||
# Step 1: Poll for completed async jobs FIRST
|
||||
# _process_finished_jobs() handles two kinds of completions here:
|
||||
@@ -617,8 +615,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
request_level_tiers: set[int],
|
||||
) -> None:
|
||||
"""
|
||||
For tiers that requested request-level policy, submit_store() for
|
||||
"""For tiers that requested request-level policy, submit_store() for
|
||||
chunks that are already present in the primary tier.
|
||||
|
||||
A key whose primary write is still in flight (HIT_PENDING) cannot be
|
||||
@@ -674,8 +671,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
success: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Mark chunks as done storing from GPU to primary tier.
|
||||
"""Mark chunks as done storing from GPU to primary tier.
|
||||
|
||||
This is where secondary tier cascading happens — after chunks are
|
||||
confirmed to be in the primary tier, they are cascaded to ALL
|
||||
@@ -691,6 +687,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
keys: Chunks that finished storing.
|
||||
success: Whether the GPU→primary transfer succeeded.
|
||||
req_context: Per-request context forwarded to primary.prepare_read().
|
||||
|
||||
"""
|
||||
# Step 1: Complete store in primary tier (makes chunks loadable)
|
||||
self.primary_tier.complete_store(keys, req_context, success)
|
||||
@@ -748,8 +745,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
*,
|
||||
exclude_tier_idx: int | None = None,
|
||||
) -> RequestOffloadingContext:
|
||||
"""
|
||||
Query each secondary tier for its offload policy preference.
|
||||
"""Query each secondary tier for its offload policy preference.
|
||||
|
||||
Returns REQUEST_LEVEL if ANY secondary tier wants request-level.
|
||||
Only stores REQUEST_LEVEL tier decisions for use in prepare_store.
|
||||
@@ -858,6 +854,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Yields:
|
||||
New OffloadingEvents collected by each tier since the last call.
|
||||
|
||||
"""
|
||||
yield from self.primary_tier.take_events()
|
||||
for tier in self.secondary_tiers:
|
||||
|
||||
@@ -113,19 +113,19 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
enable_kv_events: bool = False,
|
||||
locality: str | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
store_config: Object store connection parameters (see ObjStoreConfig).
|
||||
prefix: Key prefix prepended to all object keys.
|
||||
io_threads: Number of NIXL I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
"""Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
store_config: Object store connection parameters (see ObjStoreConfig).
|
||||
prefix: Key prefix prepended to all object keys.
|
||||
io_threads: Number of NIXL I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
self.locality = Locality(locality) if locality is not None else None
|
||||
@@ -308,7 +308,8 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def _poll_active_transfers(self) -> None:
|
||||
"""Poll all in-flight transfers once; move newly-completed (success or
|
||||
failure) into ``_pending_results`` and release their NIXL handles."""
|
||||
failure) into ``_pending_results`` and release their NIXL handles.
|
||||
"""
|
||||
for job_id, entry in list(self._transfers.items()):
|
||||
try:
|
||||
state = self._agent.check_xfer_state(entry.xfer_handle)
|
||||
@@ -363,7 +364,8 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Poll transfers; a failed promotion marks its cached verdicts False
|
||||
here (scheduler thread)."""
|
||||
here (scheduler thread).
|
||||
"""
|
||||
self._poll_active_transfers()
|
||||
results = self._pending_results
|
||||
self._pending_results = []
|
||||
|
||||
@@ -139,6 +139,7 @@ class ControlTransport(ABC):
|
||||
A connection to peer_id that is registered but no longer alive is
|
||||
retired and replaced; a live one is a duplicate and must not be
|
||||
replaced.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -158,6 +159,7 @@ class ControlTransport(ABC):
|
||||
The returned sequence is read-only — callers must not mutate
|
||||
it. The caller is responsible for creating sessions for
|
||||
these connections.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
ZMQ-based transport layer for P2P KV cache sharing.
|
||||
"""ZMQ-based transport layer for P2P KV cache sharing.
|
||||
|
||||
Provides ZmqConnection (per-peer messaging) and ZmqTransport (connection
|
||||
management). Message-content agnostic.
|
||||
|
||||
@@ -87,6 +87,7 @@ class PollResult(NamedTuple):
|
||||
Attributes:
|
||||
done: Transfer IDs that completed successfully.
|
||||
failed: Transfer IDs that failed (error, timeout, etc.).
|
||||
|
||||
"""
|
||||
|
||||
done: Sequence[int]
|
||||
@@ -174,6 +175,7 @@ class DataTransport(ABC):
|
||||
base_addr: Base address of the peer's block memory region.
|
||||
num_blocks: Number of blocks in the peer's region.
|
||||
block_len: Size of each block (must match local block_len).
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -203,6 +205,7 @@ class DataTransport(ABC):
|
||||
Returns:
|
||||
A unique transfer_id (int) to track this transfer, or
|
||||
None if the peer is not registered or submission failed.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -224,6 +227,7 @@ class DataTransport(ABC):
|
||||
Completed/failed transfers are removed from the inflight set.
|
||||
|
||||
Must be called periodically to drive progress checking.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -255,6 +259,7 @@ class DataTransport(ABC):
|
||||
For mode="wait", the subset of *transfer_ids* still
|
||||
tracked as inflight after the cancel attempt. For
|
||||
mode="immediate", always [].
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL.
|
||||
"""
|
||||
"""NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2PSecondaryTierManager: Secondary tier for P2P KV cache sharing.
|
||||
"""P2PSecondaryTierManager: Secondary tier for P2P KV cache sharing.
|
||||
|
||||
Owns transports and a single bidirectional P2PSession per remote peer.
|
||||
"""
|
||||
@@ -135,7 +134,8 @@ class P2PDestInfo:
|
||||
|
||||
def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
"""Parse the consumer sub-dict (PD ``remote_prefiller`` or symmetric
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete."""
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete.
|
||||
"""
|
||||
role = _remote_prefiller_params(kv_params)
|
||||
do_probe = False
|
||||
if role is None:
|
||||
@@ -156,7 +156,8 @@ def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
|
||||
def _parse_dest(kv_params: dict | None) -> P2PDestInfo | None:
|
||||
"""Parse the producer ``remote_decoder`` sub-dict into a ``P2PDestInfo``,
|
||||
or None if the block is absent (not a remote-decode request)."""
|
||||
or None if the block is absent (not a remote-decode request).
|
||||
"""
|
||||
role = _remote_decoder_params(kv_params)
|
||||
if role is None:
|
||||
return None
|
||||
@@ -264,6 +265,7 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
Raises:
|
||||
ValueError: If ``unbound_store_timeout_s`` is not a positive
|
||||
number, or anything convertible to one.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
try:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2P KV cache sharing protocol constants and documentation.
|
||||
"""P2P KV cache sharing protocol constants and documentation.
|
||||
|
||||
Protocol Overview
|
||||
=================
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2PSession — bidirectional session combining client + server roles.
|
||||
"""P2PSession — bidirectional session combining client + server roles.
|
||||
|
||||
A single P2PSession per remote peer handles BOTH directions of the P2P
|
||||
protocol on one ControlConnection: it can request blocks from the peer
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
TieringOffloadingSpec: Spec for multi-tier KV cache offloading.
|
||||
"""TieringOffloadingSpec: Spec for multi-tier KV cache offloading.
|
||||
|
||||
This spec creates a TieringOffloadingManager with a CPU primary tier
|
||||
and configurable secondary tiers (e.g., Storage, Network).
|
||||
@@ -82,8 +81,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
"""
|
||||
Spec for multi-tier KV cache offloading.
|
||||
"""Spec for multi-tier KV cache offloading.
|
||||
|
||||
Creates a TieringOffloadingManager with:
|
||||
- Primary tier: CPU (LRU or ARC eviction policy)
|
||||
@@ -276,8 +274,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
|
||||
@override
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
"""
|
||||
Get the TieringOffloadingManager.
|
||||
"""Get the TieringOffloadingManager.
|
||||
|
||||
Creates a TieringOffloadingManager with:
|
||||
- Primary tier: CPU (LRU or ARC)
|
||||
@@ -285,6 +282,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
|
||||
Returns:
|
||||
TieringOffloadingManager instance
|
||||
|
||||
"""
|
||||
if not self._manager:
|
||||
if int(self.extra_config.get("store_threshold", 0)) >= 2:
|
||||
@@ -416,7 +414,8 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
"""Require a mapping on every ref and record layer portability.
|
||||
|
||||
Fails loudly rather than persist direct-layout bytes under a
|
||||
canonical format identity."""
|
||||
canonical format identity.
|
||||
"""
|
||||
all_refs = [
|
||||
ref for group_refs in kv_caches.group_data_refs for ref in group_refs
|
||||
]
|
||||
|
||||
@@ -177,6 +177,7 @@ def build_buckets(mantissa_lst: list[int], max_value: int) -> list[float]:
|
||||
|
||||
Returns:
|
||||
Bucket values in increasing order, capped at `max_value`.
|
||||
|
||||
"""
|
||||
exponent = 0
|
||||
buckets: list[float] = []
|
||||
@@ -196,6 +197,7 @@ def build_1_2_5_buckets(max_value: int) -> list[float]:
|
||||
Example:
|
||||
>>> build_1_2_5_buckets(100)
|
||||
[1, 2, 5, 10, 20, 50, 100]
|
||||
|
||||
"""
|
||||
return build_buckets([1, 2, 5], max_value)
|
||||
|
||||
@@ -218,6 +220,7 @@ def histogram_buckets(
|
||||
Raises:
|
||||
ValueError: If `family` is `request_tokens` and `max_model_len`
|
||||
is None.
|
||||
|
||||
"""
|
||||
if family == "request_tokens":
|
||||
if max_model_len is None:
|
||||
|
||||
+10
-10
@@ -91,7 +91,8 @@ def load_stat_logger_plugin_factories() -> list[StatLoggerFactory]:
|
||||
|
||||
class AggregateStatLoggerBase(StatLoggerBase):
|
||||
"""Abstract base class for loggers that
|
||||
aggregate across multiple DP engines."""
|
||||
aggregate across multiple DP engines.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, vllm_config: VllmConfig, engine_indexes: list[int]): ...
|
||||
@@ -1202,16 +1203,15 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
|
||||
|
||||
class StatLoggerManager:
|
||||
"""
|
||||
StatLoggerManager:
|
||||
Logging happens at the level of the EngineCore (per scheduler).
|
||||
* DP: >1 EngineCore per AsyncLLM - loggers for each EngineCore.
|
||||
* With Local Logger, just make N copies for N EngineCores.
|
||||
* With Prometheus, we need a single logger with N "labels"
|
||||
"""StatLoggerManager:
|
||||
Logging happens at the level of the EngineCore (per scheduler).
|
||||
* DP: >1 EngineCore per AsyncLLM - loggers for each EngineCore.
|
||||
* With Local Logger, just make N copies for N EngineCores.
|
||||
* With Prometheus, we need a single logger with N "labels"
|
||||
|
||||
This class abstracts away this implementation detail from
|
||||
the AsyncLLM, allowing the AsyncLLM to just call .record()
|
||||
and .log() to a simple interface.
|
||||
This class abstracts away this implementation detail from
|
||||
the AsyncLLM, allowing the AsyncLLM to just call .record()
|
||||
and .log() to a simple interface.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
+28
-53
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Analytic flops/memory estimation module for transformer components,
|
||||
"""Analytic flops/memory estimation module for transformer components,
|
||||
to help derive MFU (Model Flops Utilization) stats for a running model.
|
||||
"""
|
||||
|
||||
@@ -33,8 +32,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class InvalidComponent(Exception):
|
||||
"""
|
||||
Custom exception to indicate that a certain ComponentMetric is not
|
||||
"""Custom exception to indicate that a certain ComponentMetric is not
|
||||
applicable to the given VllmConfig.
|
||||
"""
|
||||
|
||||
@@ -99,8 +97,7 @@ class PerfStats:
|
||||
|
||||
@dataclass
|
||||
class ExecutionContext:
|
||||
"""
|
||||
Represents an execution context for a batch of requests.
|
||||
"""Represents an execution context for a batch of requests.
|
||||
|
||||
This class aggregates statistics across multiple requests in a batch,
|
||||
separately tracking prefill and decode phases.
|
||||
@@ -202,8 +199,7 @@ class ExecutionContext:
|
||||
|
||||
|
||||
class ParsedArgs:
|
||||
"""
|
||||
Syntactic sugar so that Parsers can use dot notations
|
||||
"""Syntactic sugar so that Parsers can use dot notations
|
||||
to access/update the parsed arguments.
|
||||
|
||||
e.g.)
|
||||
@@ -227,16 +223,14 @@ class ParsedArgs:
|
||||
|
||||
class Parser(Protocol):
|
||||
def parse(self, args: ParsedArgs, vllm_config: VllmConfig) -> ParsedArgs:
|
||||
"""
|
||||
Parse the vllm config and update the current ParsedArgs and pass it on.
|
||||
"""Parse the vllm config and update the current ParsedArgs and pass it on.
|
||||
If the parser isn't applicable to the vllm_config, it will do nothing.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class ParserChain:
|
||||
"""
|
||||
Applies chain of parser in a sequential order.
|
||||
"""Applies chain of parser in a sequential order.
|
||||
Later parsers might overwrite results from previous parsers,
|
||||
so parsers should be chained in the appropriate order if they
|
||||
are not mutually exclusive.
|
||||
@@ -260,8 +254,7 @@ _COMPONENT_METRICS_REGISTRY: dict[str, type["ComponentMetrics"]] = {}
|
||||
|
||||
|
||||
class ComponentMetrics(BaseModel, ABC):
|
||||
"""
|
||||
Each concrete ComponentMetrics class is associated with:
|
||||
"""Each concrete ComponentMetrics class is associated with:
|
||||
- fields that are required for metric derivation
|
||||
(fields are specified/validated through pydantic model)
|
||||
- parser to parse VllmConfig into fields
|
||||
@@ -277,8 +270,7 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def get_parser(cls) -> ParserChain:
|
||||
"""
|
||||
Return a ParserChain that provides values for all required fields.
|
||||
"""Return a ParserChain that provides values for all required fields.
|
||||
The returned parser chain must populate ParsedArgs with values for every
|
||||
field defined on this ComponentMetrics class. Missing fields will cause
|
||||
a ValidationError when from_vllm_config() is called.
|
||||
@@ -292,11 +284,9 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(cls, vllm_config: VllmConfig) -> Self:
|
||||
"""
|
||||
Instantiate this class from VllmConfig.
|
||||
"""Instantiate this class from VllmConfig.
|
||||
Raises ValidationError if parsing fails.
|
||||
"""
|
||||
|
||||
parser = cls.get_parser()
|
||||
parsed_args = parser.parse(vllm_config)
|
||||
try:
|
||||
@@ -343,8 +333,7 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
|
||||
|
||||
class BaseConfigParser(Parser):
|
||||
"""
|
||||
Parses base model configuration.
|
||||
"""Parses base model configuration.
|
||||
Provides: vocab_size, hidden_size, num_attention_heads, num_hidden_layers,
|
||||
weight_byte_size, activation_byte_size, dp_size, tp_size, pp_size, enable_ep
|
||||
"""
|
||||
@@ -396,8 +385,7 @@ class BaseConfigParser(Parser):
|
||||
|
||||
|
||||
class BaseAttentionConfigParser(Parser):
|
||||
"""
|
||||
Parses attention-specific configuration.
|
||||
"""Parses attention-specific configuration.
|
||||
Provides: num_key_value_heads, head_dim, cache_byte_size
|
||||
"""
|
||||
|
||||
@@ -418,8 +406,7 @@ class BaseAttentionConfigParser(Parser):
|
||||
|
||||
|
||||
class SlidingWindowAttentionParser(Parser):
|
||||
"""
|
||||
Parses sliding window attention configuration and layer breakdown.
|
||||
"""Parses sliding window attention configuration and layer breakdown.
|
||||
Provides: sliding_window, num_swa_layers
|
||||
"""
|
||||
|
||||
@@ -466,8 +453,7 @@ class SlidingWindowAttentionParser(Parser):
|
||||
|
||||
|
||||
class AttentionQuantizationConfigParser(Parser):
|
||||
"""
|
||||
Parses quantization configuration for attention layers.
|
||||
"""Parses quantization configuration for attention layers.
|
||||
Overrides: weight_byte_size
|
||||
"""
|
||||
|
||||
@@ -490,8 +476,7 @@ class AttentionQuantizationConfigParser(Parser):
|
||||
|
||||
|
||||
class AttentionDetectionParser(Parser):
|
||||
"""
|
||||
Prevents standard AttentionMetrics from being instantiated for MLA models.
|
||||
"""Prevents standard AttentionMetrics from being instantiated for MLA models.
|
||||
MLA models should use MLAAttentionMetrics instead.
|
||||
"""
|
||||
|
||||
@@ -589,6 +574,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
|
||||
Returns:
|
||||
Dict with keys: qkv_proj, out_proj, attn_qk, attn_av.
|
||||
|
||||
"""
|
||||
D, q, kv, d = (
|
||||
self.hidden_size,
|
||||
@@ -642,6 +628,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
Returns:
|
||||
Dict with keys: qkv_input, qkv_weight, attn_input (conditional),
|
||||
out_input, out_weight.
|
||||
|
||||
"""
|
||||
D, q, kv, d = (
|
||||
self.hidden_size,
|
||||
@@ -747,8 +734,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
|
||||
|
||||
class MLADetectionParser(Parser):
|
||||
"""
|
||||
Validates that the model uses MLA attention.
|
||||
"""Validates that the model uses MLA attention.
|
||||
Raises InvalidComponent if the model does not use MLA,
|
||||
so MLAAttentionMetrics is silently skipped for non-MLA models.
|
||||
"""
|
||||
@@ -761,8 +747,7 @@ class MLADetectionParser(Parser):
|
||||
|
||||
|
||||
class MLAConfigParser(Parser):
|
||||
"""
|
||||
Parses MLA-specific configuration fields.
|
||||
"""Parses MLA-specific configuration fields.
|
||||
Provides: kv_lora_rank, qk_nope_head_dim, qk_rope_head_dim,
|
||||
v_head_dim, q_lora_rank
|
||||
"""
|
||||
@@ -787,8 +772,7 @@ class MLAConfigParser(Parser):
|
||||
|
||||
|
||||
class MLAAttentionMetrics(ComponentMetrics):
|
||||
"""
|
||||
Performance metrics for Multi-Latent Attention (MLA) layers.
|
||||
"""Performance metrics for Multi-Latent Attention (MLA) layers.
|
||||
|
||||
MLA uses a compressed latent representation for KV cache:
|
||||
- KV cache stores a single compressed vector of size
|
||||
@@ -1025,8 +1009,7 @@ class MLAAttentionMetrics(ComponentMetrics):
|
||||
|
||||
|
||||
class BaseFfnConfigParser(Parser):
|
||||
"""
|
||||
Parses FFN and MoE configuration.
|
||||
"""Parses FFN and MoE configuration.
|
||||
Provides: intermediate_size, num_experts, num_experts_per_tok,
|
||||
moe_intermediate_size, num_shared_experts, num_moe_layers
|
||||
"""
|
||||
@@ -1056,8 +1039,7 @@ class BaseFfnConfigParser(Parser):
|
||||
|
||||
|
||||
class FfnParallelParser(Parser):
|
||||
"""
|
||||
Parses FFN parallelism configuration.
|
||||
"""Parses FFN parallelism configuration.
|
||||
|
||||
Provides: ffn_tp_size, ffn_ep_size
|
||||
"""
|
||||
@@ -1077,8 +1059,7 @@ class FfnParallelParser(Parser):
|
||||
|
||||
|
||||
class InterleaveMoeLayerStepParser(Parser):
|
||||
"""
|
||||
Parses interleave_moe_layer_step field for models like Llama4.
|
||||
"""Parses interleave_moe_layer_step field for models like Llama4.
|
||||
|
||||
Overrides: num_moe_layers
|
||||
"""
|
||||
@@ -1104,8 +1085,7 @@ class InterleaveMoeLayerStepParser(Parser):
|
||||
|
||||
|
||||
class MoeLayerFreqParser(Parser):
|
||||
"""
|
||||
Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
|
||||
"""Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
|
||||
|
||||
Overrides: num_moe_layers
|
||||
"""
|
||||
@@ -1129,8 +1109,7 @@ class MoeLayerFreqParser(Parser):
|
||||
|
||||
|
||||
class FfnQuantizationConfigParser(Parser):
|
||||
"""
|
||||
Parses quantization configuration for FFN layers.
|
||||
"""Parses quantization configuration for FFN layers.
|
||||
|
||||
Overrides: weight_byte_size
|
||||
"""
|
||||
@@ -1486,11 +1465,9 @@ class UnembedMetrics(ComponentMetrics):
|
||||
|
||||
class ModelMetrics:
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
"""
|
||||
Parse vllm_config to instantiate metrics for each component.
|
||||
"""Parse vllm_config to instantiate metrics for each component.
|
||||
is_enabled() will return False if no component metrics could be instantiated.
|
||||
"""
|
||||
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
self.metrics: list[ComponentMetrics] = []
|
||||
@@ -1558,10 +1535,7 @@ class ModelMetrics:
|
||||
def get_step_perf_stats_per_gpu(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> PerfStats:
|
||||
"""
|
||||
Calculate perf stats for the current step based on scheduled tokens.
|
||||
"""
|
||||
|
||||
"""Calculate perf stats for the current step based on scheduled tokens."""
|
||||
t0 = time.monotonic()
|
||||
|
||||
# Build a single batch context
|
||||
@@ -1846,7 +1820,8 @@ def get_required(obj: object, attr: str):
|
||||
|
||||
def getattr_from_list(obj: object, attrs: list[str], default: object = None):
|
||||
"""Try to get the first attr that exists in the object
|
||||
from a list of attrs. Otherwise return None."""
|
||||
from a list of attrs. Otherwise return None.
|
||||
"""
|
||||
for attr in attrs:
|
||||
if hasattr(obj, attr):
|
||||
return getattr(obj, attr)
|
||||
|
||||
@@ -42,6 +42,7 @@ def get_prometheus_registry() -> CollectorRegistry:
|
||||
|
||||
Returns:
|
||||
Registry: A prometheus registry
|
||||
|
||||
"""
|
||||
if os.getenv("PROMETHEUS_MULTIPROC_DIR") is not None:
|
||||
logger.debug("Using multiprocess registry for prometheus metrics")
|
||||
@@ -70,7 +71,6 @@ def unregister_vllm_metrics():
|
||||
|
||||
def shutdown_prometheus():
|
||||
"""Shutdown prometheus metrics."""
|
||||
|
||||
path = _prometheus_multiproc_dir
|
||||
if path is None:
|
||||
return
|
||||
|
||||
@@ -68,8 +68,7 @@ class RayPrometheusMetric:
|
||||
|
||||
@staticmethod
|
||||
def _get_sanitized_opentelemetry_name(name: str) -> str:
|
||||
"""
|
||||
For compatibility with Ray + OpenTelemetry, the metric name must be
|
||||
"""For compatibility with Ray + OpenTelemetry, the metric name must be
|
||||
sanitized. In particular, this replaces disallowed character (e.g., ':')
|
||||
with '_' in the metric name.
|
||||
Allowed characters: a-z, A-Z, 0-9, _
|
||||
@@ -78,13 +77,13 @@ class RayPrometheusMetric:
|
||||
Ref: https://github.com/open-telemetry/opentelemetry-cpp/blob/main/sdk/src/metrics/instrument_metadata_validator.cc#L22-L23
|
||||
Ref: https://github.com/ray-project/ray/blob/master/src/ray/stats/metric.cc#L107
|
||||
"""
|
||||
|
||||
return re.sub(r"[^a-zA-Z0-9_]", "_", name)
|
||||
|
||||
|
||||
class RayGaugeWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Gauge to provide same API as
|
||||
prometheus_client.Gauge"""
|
||||
prometheus_client.Gauge
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -118,7 +117,8 @@ class RayGaugeWrapper(RayPrometheusMetric):
|
||||
|
||||
class RayCounterWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Counter to provide same API as
|
||||
prometheus_client.Counter"""
|
||||
prometheus_client.Counter
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -143,7 +143,8 @@ class RayCounterWrapper(RayPrometheusMetric):
|
||||
|
||||
class RayHistogramWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Histogram to provide same API as
|
||||
prometheus_client.Histogram"""
|
||||
prometheus_client.Histogram
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -169,8 +170,7 @@ class RayHistogramWrapper(RayPrometheusMetric):
|
||||
|
||||
|
||||
class RaySpecDecodingProm(SpecDecodingProm):
|
||||
"""
|
||||
RaySpecDecodingProm is used by RayMetrics to log to Ray metrics.
|
||||
"""RaySpecDecodingProm is used by RayMetrics to log to Ray metrics.
|
||||
Provides the same metrics as SpecDecodingProm but uses Ray's
|
||||
util.metrics library.
|
||||
"""
|
||||
@@ -179,8 +179,7 @@ class RaySpecDecodingProm(SpecDecodingProm):
|
||||
|
||||
|
||||
class RayKVConnectorProm(KVConnectorProm):
|
||||
"""
|
||||
RayKVConnectorProm is used by RayMetrics to log Ray
|
||||
"""RayKVConnectorProm is used by RayMetrics to log Ray
|
||||
metrics. Provides the same metrics as KV connectors but
|
||||
uses Ray's util.metrics library.
|
||||
"""
|
||||
@@ -191,8 +190,7 @@ class RayKVConnectorProm(KVConnectorProm):
|
||||
|
||||
|
||||
class RayPerfMetricsProm(PerfMetricsProm):
|
||||
"""
|
||||
RayPerfMetricsProm is used by RayMetrics to log Ray
|
||||
"""RayPerfMetricsProm is used by RayMetrics to log Ray
|
||||
metrics. Provides the same MFU metrics as PerfMetricsProm
|
||||
uses Ray's util.metrics library.
|
||||
"""
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user