Update Optional[x] -> x | None and Union[x, y] to x | y (#26633)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
Harry Mellor
2025-10-12 09:51:31 -07:00
committed by GitHub
parent 9bb38130cb
commit 8fcaaf6a16
944 changed files with 9490 additions and 10121 deletions
+29 -29
View File
@@ -110,7 +110,7 @@ class TorchSDPAMetadata(AttentionMetadata):
"""Metadata for PagedAttention."""
# (batch_size,). The length of sequences (entire tokens seen so far) per
# sequence.
decode_seq_lens_tensor: Optional[torch.Tensor]
decode_seq_lens_tensor: torch.Tensor | None
# Maximum sequence length in the batch. 0 if it is prefill-only batch.
decode_max_seq_len: int
# (batch_size, max_blocks_per_seq).
@@ -119,39 +119,39 @@ class TorchSDPAMetadata(AttentionMetadata):
# in the kv cache. Each block can contain up to block_size tokens.
# 2nd dimensions are padded up to max_blocks_per_seq if it is cuda-graph
# captured.
decode_block_tables: Optional[torch.Tensor]
decode_block_tables: torch.Tensor | None
"""Metadata for TorchSDPABackend.
"""
# Currently, input sequences can only contain all prompts
# or all decoding. True if all sequences are prompts.
chunked_prefill: bool
seq_lens: Optional[list[int]] = None # For non-chunked prefill
seq_lens: list[int] | None = None # For non-chunked prefill
# For chunked prefill only
max_query_len: Optional[int] = None
prefill_max_seq_len: Optional[int] = None
prefill_query_start_loc: Optional[torch.Tensor] = None
prefill_seq_start_loc: Optional[torch.Tensor] = None
prefill_block_tables: Optional[torch.Tensor] = None
max_query_len: int | None = None
prefill_max_seq_len: int | None = None
prefill_query_start_loc: torch.Tensor | None = None
prefill_seq_start_loc: torch.Tensor | None = None
prefill_block_tables: torch.Tensor | None = None
# For V1 logits index only
query_start_loc: Optional[torch.Tensor] = None
query_start_loc: torch.Tensor | None = None
# Begin encoder attn & enc/dec cross-attn fields...
# Encoder sequence lengths representation
encoder_seq_lens: Optional[list[int]] = None
encoder_seq_lens_tensor: Optional[torch.Tensor] = None
encoder_seq_lens: list[int] | None = None
encoder_seq_lens_tensor: torch.Tensor | None = None
# Maximum sequence length among encoder sequences
max_encoder_seq_len: Optional[int] = None
max_encoder_seq_len: int | None = None
# Number of tokens input to encoder
num_encoder_tokens: Optional[int] = None
num_encoder_tokens: int | None = None
# Cross-attention memory-mapping data structures: slot mapping
# and block tables
cross_slot_mapping: Optional[torch.Tensor] = None
cross_block_tables: Optional[torch.Tensor] = None
cross_slot_mapping: torch.Tensor | None = None
cross_block_tables: torch.Tensor | None = None
def __post_init__(self):
# Set during the execution of the first attention op.
@@ -159,9 +159,9 @@ class TorchSDPAMetadata(AttentionMetadata):
# when alibi slopes is used. It is because of the limitation
# from xformer API.
# will not appear in the __repr__ and __init__
self.attn_bias: Optional[list[torch.Tensor]] = None
self.encoder_attn_bias: Optional[list[torch.Tensor]] = None
self.cross_attn_bias: Optional[list[torch.Tensor]] = None
self.attn_bias: list[torch.Tensor] | None = None
self.encoder_attn_bias: list[torch.Tensor] | None = None
self.cross_attn_bias: list[torch.Tensor] | None = None
@property
def is_all_encoder_attn_metadata_set(self):
@@ -237,7 +237,7 @@ class TorchSDPAMetadata(AttentionMetadata):
def get_attn_bias(
self,
attn_type: str,
) -> Optional[list[torch.Tensor]]:
) -> list[torch.Tensor] | None:
"""
Extract appropriate attention bias from attention metadata
according to attention type.
@@ -439,12 +439,12 @@ class TorchSDPABackendImpl(AttentionImpl[TorchSDPAMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
kv_sharing_target_layer_name: str | None = None,
) -> None:
if kv_sharing_target_layer_name is not None:
raise NotImplementedError("KV sharing is not supported in V0.")
@@ -484,9 +484,9 @@ class TorchSDPABackendImpl(AttentionImpl[TorchSDPAMetadata]):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: TorchSDPAMetadata, # type: ignore
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with torch SDPA and PagedAttention.
@@ -737,7 +737,7 @@ def _make_alibi_bias(
def _make_sliding_window_bias(
seq_lens: list[int],
window_size: Optional[int],
window_size: int | None,
dtype: torch.dtype,
) -> list[torch.Tensor]:
attn_biases: list[torch.Tensor] = []
@@ -824,7 +824,7 @@ class _PagedAttention:
kv_cache_dtype: str,
num_kv_heads: int,
scale: float,
alibi_slopes: Optional[torch.Tensor],
alibi_slopes: torch.Tensor | None,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
*args,
@@ -907,7 +907,7 @@ class _IPEXPagedAttention(_PagedAttention):
kv_cache_dtype: str,
num_kv_heads: int,
scale: float,
alibi_slopes: Optional[torch.Tensor],
alibi_slopes: torch.Tensor | None,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
*args,
+24 -25
View File
@@ -3,7 +3,6 @@
"""Attention layer with FlashAttention."""
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
import torch
@@ -59,7 +58,7 @@ class FlashAttentionBackend(AttentionBackend):
return [32, 64, 96, 128, 160, 192, 224, 256]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
@@ -144,13 +143,13 @@ class FlashAttentionMetadata:
# For cascade attention.
use_cascade: bool
common_prefix_len: int
cu_prefix_query_lens: Optional[torch.Tensor]
prefix_kv_lens: Optional[torch.Tensor]
suffix_kv_lens: Optional[torch.Tensor]
cu_prefix_query_lens: torch.Tensor | None
prefix_kv_lens: torch.Tensor | None
suffix_kv_lens: torch.Tensor | None
# Optional aot scheduling
scheduler_metadata: Optional[torch.Tensor] = None
prefix_scheduler_metadata: Optional[torch.Tensor] = None
scheduler_metadata: torch.Tensor | None = None
prefix_scheduler_metadata: torch.Tensor | None = None
max_num_splits: int = 0
causal: bool = True
@@ -158,9 +157,9 @@ class FlashAttentionMetadata:
def _get_sliding_window_configs(
vllm_config: VllmConfig,
) -> set[Optional[tuple[int, int]]]:
) -> set[tuple[int, int] | None]:
"""Get the set of all sliding window configs used in the model."""
sliding_window_configs: set[Optional[tuple[int, int]]] = set()
sliding_window_configs: set[tuple[int, int] | None] = set()
layers = get_layers_from_vllm_config(vllm_config, Attention)
for layer in layers.values():
assert isinstance(layer.impl, FlashAttentionImpl)
@@ -242,7 +241,7 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
# Sliding window size to be used with the AOT scheduler will be
# populated on first build() call.
self.aot_sliding_window: Optional[tuple[int, int]] = None
self.aot_sliding_window: tuple[int, int] | None = None
def build(
self,
@@ -403,13 +402,13 @@ class FlashAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
sinks: Optional[torch.Tensor] = None,
kv_sharing_target_layer_name: str | None = None,
sinks: torch.Tensor | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -460,9 +459,9 @@ class FlashAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: FlashAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FlashAttention.
@@ -762,18 +761,18 @@ def cascade_attention(
suffix_kv_lens: torch.Tensor,
max_kv_len: int,
softmax_scale: float,
alibi_slopes: Optional[torch.Tensor],
alibi_slopes: torch.Tensor | None,
sliding_window: tuple[int, int],
logits_soft_cap: float,
block_table: torch.Tensor,
common_prefix_len: int,
fa_version: int,
prefix_scheduler_metadata: Optional[torch.Tensor] = None,
suffix_scheduler_metadata: Optional[torch.Tensor] = None,
q_descale: Optional[torch.Tensor] = None,
k_descale: Optional[torch.Tensor] = None,
v_descale: Optional[torch.Tensor] = None,
s_aux: Optional[torch.Tensor] = None,
prefix_scheduler_metadata: torch.Tensor | None = None,
suffix_scheduler_metadata: torch.Tensor | None = None,
q_descale: torch.Tensor | None = None,
k_descale: torch.Tensor | None = None,
v_descale: torch.Tensor | None = None,
s_aux: torch.Tensor | None = None,
) -> torch.Tensor:
assert alibi_slopes is None, "Cascade attention does not support ALiBi."
# TODO: Support sliding window.
+8 -10
View File
@@ -2,10 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with FlashInfer."""
from __future__ import annotations
from dataclasses import dataclass
from typing import ClassVar, Union
from typing import ClassVar
import numpy as np
import torch
@@ -167,7 +165,7 @@ class FlashInferBackend(AttentionBackend):
return [64, 128, 256]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
# Note: Not sure for all platforms,
# but on Blackwell, only support a page size of
# 16, 32, 64
@@ -190,15 +188,15 @@ class FlashInferBackend(AttentionBackend):
return "FLASHINFER"
@staticmethod
def get_impl_cls() -> type[FlashInferImpl]:
def get_impl_cls() -> type["FlashInferImpl"]:
return FlashInferImpl
@staticmethod
def get_metadata_cls() -> type[FlashInferMetadata]:
def get_metadata_cls() -> type["FlashInferMetadata"]:
return FlashInferMetadata
@staticmethod
def get_builder_cls() -> type[FlashInferMetadataBuilder]:
def get_builder_cls() -> type["FlashInferMetadataBuilder"]:
return FlashInferMetadataBuilder
@staticmethod
@@ -1116,9 +1114,9 @@ def fast_plan_decode(
pos_encoding_mode: str = "NONE",
window_left: int = -1,
logits_soft_cap: float | None = None,
q_data_type: Union[str, torch.dtype] | None = "float16",
kv_data_type: Union[str, torch.dtype] | None = None,
data_type: Union[str, torch.dtype] | None = None,
q_data_type: str | torch.dtype | None = "float16",
kv_data_type: str | torch.dtype | None = None,
data_type: str | torch.dtype | None = None,
sm_scale: float | None = None,
rope_scale: float | None = None,
rope_theta: float | None = None,
+21 -22
View File
@@ -3,7 +3,6 @@
"""Attention layer with FlexAttention."""
from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch._dynamo.decorators
@@ -282,9 +281,9 @@ class FlexAttentionMetadata:
use_cascade: bool
common_prefix_len: int
cu_prefix_query_lens: Optional[torch.Tensor]
prefix_kv_lens: Optional[torch.Tensor]
suffix_kv_lens: Optional[torch.Tensor]
cu_prefix_query_lens: torch.Tensor | None
prefix_kv_lens: torch.Tensor | None
suffix_kv_lens: torch.Tensor | None
# Block info
total_cache_tokens: int
@@ -300,15 +299,15 @@ class FlexAttentionMetadata:
# Flex Metadata
num_blocks = 0
block_mask: Optional[BlockMask] = None
score_mod: Optional[_score_mod_signature] = None
block_mask: BlockMask | None = None
score_mod: _score_mod_signature | None = None
logical_mask_mod: _mask_mod_signature = causal_mask_mod
doc_ids: Optional[torch.Tensor] = None
doc_ids: torch.Tensor | None = None
direct_build: bool = True
q_block_size: int = 16
kv_block_size: int = 16
transformed_score_mod: Optional[_score_mod_signature] = None
sliding_window: Optional[int] = None
transformed_score_mod: _score_mod_signature | None = None
sliding_window: int | None = None
def _convert_physical_to_logical(
self,
@@ -443,7 +442,7 @@ class FlexAttentionMetadata:
mask_mod = and_masks(mask_mod, sliding_window_mask_mod)
return mask_mod
def get_transformed_score_mod(self) -> Optional[_score_mod_signature]:
def get_transformed_score_mod(self) -> _score_mod_signature | None:
"""Creates the transformed score_mod function for FlexAttention.
This function wraps the user's score_mod to handle physical-to-logical
@@ -669,9 +668,9 @@ class FlexAttentionMetadataBuilder(AttentionMetadataBuilder[FlexAttentionMetadat
class FlexAttentionImpl(AttentionImpl):
sliding_window: Optional[int]
alibi_slopes: Optional[torch.Tensor]
logits_soft_cap: Optional[float]
sliding_window: int | None
alibi_slopes: torch.Tensor | None
logits_soft_cap: float | None
def __init__(
self,
@@ -679,12 +678,12 @@ class FlexAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
kv_sharing_target_layer_name: str | None = None,
**kwargs,
) -> None:
self.num_heads = num_heads
@@ -742,9 +741,9 @@ class FlexAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: FlexAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FLexAttention.
@@ -860,8 +859,8 @@ class FlexAttentionImpl(AttentionImpl):
def get_kernel_options(
query, block_m, block_n, use_direct_build: bool
) -> dict[str, Union[int, bool]]:
kernel_options: dict[str, Union[int, bool]] = {
) -> dict[str, int | bool]:
kernel_options: dict[str, int | bool] = {
"FORCE_USE_FLEX_ATTENTION": True,
}
if vllm_kernel_override_batch_invariant():
+13 -16
View File
@@ -3,7 +3,6 @@
"""Backend for GatedDeltaNet attention."""
from dataclasses import dataclass
from typing import Optional
import torch
@@ -36,29 +35,27 @@ class GDNAttentionMetadata:
num_spec_decode_tokens: int
num_actual_tokens: int
has_initial_state: Optional[torch.Tensor] = None
has_initial_state: torch.Tensor | None = None
spec_query_start_loc: Optional[torch.Tensor] = (
None # shape: [num_spec_decodes + 1,]
)
non_spec_query_start_loc: Optional[torch.Tensor] = (
spec_query_start_loc: torch.Tensor | None = None # shape: [num_spec_decodes + 1,]
non_spec_query_start_loc: torch.Tensor | None = (
None # shape: [batch - num_spec_decodes + 1,]
)
spec_state_indices_tensor: Optional[torch.Tensor] = None # shape: [batch, num_spec]
non_spec_state_indices_tensor: Optional[torch.Tensor] = (
spec_state_indices_tensor: torch.Tensor | None = None # shape: [batch, num_spec]
non_spec_state_indices_tensor: torch.Tensor | None = (
None # shape: [batch - num_spec_decodes,]
)
spec_sequence_masks: Optional[torch.Tensor] = None # shape: [batch,]
spec_token_masks: Optional[torch.Tensor] = (
spec_sequence_masks: torch.Tensor | None = None # shape: [batch,]
spec_token_masks: torch.Tensor | None = (
None # shape: [num_prefill_tokens + num_decode_tokens,]
)
num_accepted_tokens: Optional[torch.Tensor] = None # shape: [batch,]
num_accepted_tokens: torch.Tensor | None = None # shape: [batch,]
# The following attributes are for triton implementation of causal_conv1d
nums_dict: Optional[dict] = None
batch_ptr: Optional[torch.Tensor] = None
token_chunk_offset_ptr: Optional[torch.Tensor] = None
nums_dict: dict | None = None
batch_ptr: torch.Tensor | None = None
token_chunk_offset_ptr: torch.Tensor | None = None
class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]):
@@ -133,8 +130,8 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
self,
common_prefix_len: int,
common_attn_metadata: CommonAttentionMetadata,
num_accepted_tokens: Optional[torch.Tensor] = None,
num_decode_draft_tokens_cpu: Optional[torch.Tensor] = None,
num_accepted_tokens: torch.Tensor | None = None,
num_decode_draft_tokens_cpu: torch.Tensor | None = None,
fast_build: bool = False,
) -> GDNAttentionMetadata:
m = common_attn_metadata
+1 -2
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
import torch
@@ -26,7 +25,7 @@ class Mamba1AttentionMetadata:
query_start_loc: torch.Tensor
context_lens_tensor: torch.Tensor
state_indices_tensor: torch.Tensor
has_initial_states: Optional[torch.Tensor]
has_initial_states: torch.Tensor | None
num_prefills: int
num_prefill_tokens: int
num_decodes: int
+7 -8
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import itertools
from dataclasses import dataclass
from typing import Optional
import torch
@@ -108,18 +107,18 @@ class Mamba2AttentionMetadata:
# The following tensors only contain prefill requests and will be None if
# the batch has no prefill request.
has_initial_states_p: Optional[torch.Tensor]
seq_idx_p: Optional[torch.Tensor]
has_initial_states_p: torch.Tensor | None
seq_idx_p: torch.Tensor | None
# cu_chunk_seqlen_p is a tensor of shape (nchunks+1,) that contains, for
# each chunk, its offests into the varlen sequence dimension. It is defined
# such that the i-th chunk contains tokens from cu_chunk_seqlen_p[i] to
# cu_chunk_seqlen_p[i+1].
cu_chunk_seqlen_p: Optional[torch.Tensor]
cu_chunk_seqlen_p: torch.Tensor | None
# last_chunk_indices_p is a tensor of shape (batch,) that contains the
# index of the last chunk for every sequence in the (prefill) batch.
last_chunk_indices_p: Optional[torch.Tensor]
last_chunk_indices_p: torch.Tensor | None
state_indices_tensor: torch.Tensor # shape: [batch,]
block_idx_last_scheduled_token: torch.Tensor # shape: [batch,]
@@ -128,9 +127,9 @@ class Mamba2AttentionMetadata:
num_computed_tokens_p: torch.Tensor # shape: [batch,]
# The following attributes are for triton implementation of causal_conv1d
nums_dict: Optional[dict] = None
batch_ptr: Optional[torch.Tensor] = None
token_chunk_offset_ptr: Optional[torch.Tensor] = None
nums_dict: dict | None = None
batch_ptr: torch.Tensor | None = None
token_chunk_offset_ptr: torch.Tensor | None = None
class Mamba2AttentionMetadataBuilder(
+37 -32
View File
@@ -190,7 +190,7 @@ return curr_o @ W_O
import functools
from abc import abstractmethod
from dataclasses import dataclass, field
from typing import ClassVar, Generic, Optional, TypeVar, Union
from typing import ClassVar, Generic, TypeVar
import torch
from tqdm import tqdm
@@ -243,6 +243,8 @@ try:
flashinfer_available = True
except ImportError:
BatchPrefillWithRaggedKVCacheWrapper = object
flashinfer_available = False
@@ -337,22 +339,22 @@ class MLACommonPrefillMetadata:
workspace: torch.Tensor
# for mla DCP
cp_chunk_seq_lens: Optional[list[list[int]]] = None
origin_context_lens: Optional[list[int]] = None
cp_cu_seq_lens: Optional[torch.Tensor] = None
chunk_size: Optional[int] = None
cu_seq_lens_lst: Optional[list[list[int]]] = None
cp_chunk_seq_lens: list[list[int]] | None = None
origin_context_lens: list[int] | None = None
cp_cu_seq_lens: torch.Tensor | None = None
chunk_size: int | None = None
cu_seq_lens_lst: list[list[int]] | None = None
block_table: torch.Tensor
query_start_loc: torch.Tensor
max_query_len: int
chunked_context: Optional[ChunkedContextMetadata] = None
chunked_context: ChunkedContextMetadata | None = None
@dataclass
class FlashInferPrefillMetadata(MLACommonPrefillMetadata):
prefill_main: Optional["BatchPrefillWithRaggedKVCacheWrapper"] = None
prefill_chunks: list["BatchPrefillWithRaggedKVCacheWrapper"] = field(
prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = field(
default_factory=list
)
@@ -362,15 +364,15 @@ class CudnnPrefillMetadata(MLACommonPrefillMetadata):
class ChunkedContextMetadata(MLACommonPrefillMetadata.ChunkedContextMetadata):
seq_lens: torch.Tensor
query_seq_lens: Optional[torch.Tensor] = None
cudnn_workspace: Optional[torch.Tensor] = None
query_seq_lens: torch.Tensor | None = None
cudnn_workspace: torch.Tensor | None = None
@dataclass
class MLACommonDecodeMetadata:
block_table: torch.Tensor
seq_lens: torch.Tensor
dcp_tot_seq_lens: Optional[torch.Tensor]
dcp_tot_seq_lens: torch.Tensor | None
D = TypeVar("D", bound=MLACommonDecodeMetadata)
@@ -407,12 +409,15 @@ class MLACommonMetadata(Generic[D]):
num_prefills: int
# The dimension of the attention heads
head_dim: Optional[int] = None
head_dim: int | None = None
decode: Optional[D] = None
prefill: Optional[
Union[MLACommonPrefillMetadata, FlashInferPrefillMetadata, CudnnPrefillMetadata]
] = None
decode: D | None = None
prefill: (
MLACommonPrefillMetadata
| FlashInferPrefillMetadata
| CudnnPrefillMetadata
| None
) = None
def __post_init__(self):
if self.head_dim is not None:
@@ -508,7 +513,7 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
layer_names: list[str],
vllm_config: VllmConfig,
device: torch.device,
metadata_cls: Optional[type[M]] = None,
metadata_cls: type[M] | None = None,
):
self.metadata_cls = (
metadata_cls if metadata_cls is not None else MLACommonMetadata
@@ -580,7 +585,7 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.uint8, device=device
)
self._fi_prefill_main: Optional[BatchPrefillWithRaggedKVCacheWrapper] = None
self._fi_prefill_main: BatchPrefillWithRaggedKVCacheWrapper | None = None
self._fi_prefill_chunks: list[BatchPrefillWithRaggedKVCacheWrapper] = []
self._global_hyperparameters = infer_global_hyperparameters(
@@ -683,7 +688,7 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
dcp_tot_seq_lens_device: Optional[torch.Tensor],
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> MLACommonDecodeMetadata:
return MLACommonDecodeMetadata(
block_table=block_table_tensor,
@@ -1023,14 +1028,14 @@ class MLACommonBaseImpl(MLAAttentionImpl[A], Generic[A]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
q_lora_rank: Optional[int],
q_lora_rank: int | None,
kv_lora_rank: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
@@ -1038,7 +1043,7 @@ class MLACommonBaseImpl(MLAAttentionImpl[A], Generic[A]):
v_head_dim: int,
kv_b_proj: ColumnParallelLinear,
indexer=None,
q_pad_num_heads: Optional[int] = None,
q_pad_num_heads: int | None = None,
) -> None:
if kv_sharing_target_layer_name is not None:
raise NotImplementedError("KV sharing is not supported for MLA")
@@ -1226,7 +1231,7 @@ class MLACommonImpl(MLACommonBaseImpl[M], Generic[M]):
and current_platform.get_device_capability()[0] == 9
)
self.dcp_world_size: Optional[int] = None
self.dcp_world_size: int | None = None
self.chunked_prefill_workspace_size = (
MLACommonMetadataBuilder.determine_chunked_prefill_workspace_size(
@@ -1710,11 +1715,11 @@ class MLACommonImpl(MLACommonBaseImpl[M], Generic[M]):
@abstractmethod
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: M,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
raise NotImplementedError
def forward(
@@ -1725,9 +1730,9 @@ class MLACommonImpl(MLACommonBaseImpl[M], Generic[M]):
k_pe: torch.Tensor, # value in unified attn
kv_cache: torch.Tensor,
attn_metadata: M,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
assert output is not None, "Output tensor must be provided."
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -46,7 +46,7 @@ class CutlassMLABackend(MLACommonBackend):
return CutlassMLAMetadataBuilder
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [128]
@@ -95,12 +95,12 @@ class CutlassMLAImpl(MLACommonImpl[MLACommonMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -232,11 +232,11 @@ class CutlassMLAImpl(MLACommonImpl[MLACommonMetadata]):
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -55,7 +55,7 @@ class FlashAttnMLADecodeMetadata(MLACommonDecodeMetadata):
query_start_loc: torch.Tensor
max_query_len: int
max_seq_len: int
scheduler_metadata: Optional[torch.Tensor] = None
scheduler_metadata: torch.Tensor | None = None
max_num_splits: int = 0
@@ -135,7 +135,7 @@ class FlashAttnMLAMetadataBuilder(MLACommonMetadataBuilder[FlashAttnMLAMetadata]
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
dcp_tot_seq_lens_device: Optional[torch.Tensor],
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> FlashAttnMLADecodeMetadata:
query_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1]
max_query_len = query_lens_cpu.max().item()
@@ -195,12 +195,12 @@ class FlashAttnMLAImpl(MLACommonImpl[FlashAttnMLAMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -242,11 +242,11 @@ class FlashAttnMLAImpl(MLACommonImpl[FlashAttnMLAMetadata]):
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashAttnMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
@@ -57,12 +57,12 @@ class FlashInferMLAImpl(MLACommonImpl[MLACommonMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -96,16 +96,16 @@ class FlashInferMLAImpl(MLACommonImpl[MLACommonMetadata]):
)
self._workspace_buffer = g_fi_workspace
self.bmm1_scale: Optional[float] = None
self.bmm2_scale: Optional[float] = None
self.bmm1_scale: float | None = None
self.bmm2_scale: float | None = None
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
+9 -9
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -45,7 +45,7 @@ class FlashMLABackend(MLACommonBackend):
return FlashMLAImpl
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [64]
@@ -106,7 +106,7 @@ class FlashMLAMetadataBuilder(MLACommonMetadataBuilder[FlashMLAMetadata]):
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
dcp_tot_seq_lens_device: Optional[torch.Tensor],
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> FlashMLADecodeMetadata:
tile_scheduler_metadata, num_splits = get_mla_metadata(
seq_lens_device,
@@ -160,12 +160,12 @@ class FlashMLAImpl(MLACommonImpl[FlashMLAMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -203,11 +203,11 @@ class FlashMLAImpl(MLACommonImpl[FlashMLAMetadata]):
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: FlashMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
# TODO: (zyongye) decode function for mla here
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
@@ -110,12 +110,12 @@ class FlashMLASparseMetadata:
@dataclass
class FP8KernelMetadata:
scheduler_metadata: Optional[torch.Tensor]
scheduler_metadata: torch.Tensor | None
num_splits: torch.Tensor
dummy_block_table: torch.Tensor
cache_lens: torch.Tensor
fp8_extra_metadata: Optional[FP8KernelMetadata] = None
fp8_extra_metadata: FP8KernelMetadata | None = None
@triton.jit
@@ -373,14 +373,14 @@ class FlashMLASparseImpl(MLACommonBaseImpl[FlashMLASparseMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
topk_indice_buffer: Optional[torch.Tensor] = None,
topk_indice_buffer: torch.Tensor | None = None,
indexer: Optional["Indexer"] = None,
**mla_args,
) -> None:
@@ -466,9 +466,9 @@ class FlashMLASparseImpl(MLACommonBaseImpl[FlashMLASparseMetadata]):
k_pe: torch.Tensor, # value in unified attn
kv_cache: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
# NOTE(lucas): for the sparse FlashMLA kernels the kernels want to use
# MQA 576/512 approach for both prefill and decode
+4 -4
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -52,7 +52,7 @@ class DeepseekV32IndexerBackend(AttentionBackend):
return (0, 1, 2)
@classmethod
def get_supported_kernel_block_size(cls) -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size(cls) -> list[int | MultipleOf]:
return [64]
@@ -105,8 +105,8 @@ class DeepseekV32IndexerMetadata:
num_prefills: int
num_prefill_tokens: int
decode: Optional[DeepSeekV32IndexerDecodeMetadata] = None
prefill: Optional[DeepseekV32IndexerPrefillMetadata] = None
decode: DeepSeekV32IndexerDecodeMetadata | None = None
prefill: DeepseekV32IndexerPrefillMetadata | None = None
# TODO (zyongye) optimize this, this is now vibe coded
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -47,14 +47,14 @@ class AiterMLABackend(MLACommonBackend):
@dataclass
class AiterMLADecodeMetadata(MLACommonDecodeMetadata):
# The indptr of the paged kv cache, shape: [batch_size + 1]
paged_kv_indptr: Optional[torch.Tensor] = None
paged_kv_indptr: torch.Tensor | None = None
# The page indices of the paged kv cache
paged_kv_indices: Optional[torch.Tensor] = None
paged_kv_indices: torch.Tensor | None = None
# The number of entries in the last page of each request in
# the paged kv cache, shape: [batch_size]
paged_kv_last_page_len: Optional[torch.Tensor] = None
paged_kv_last_page_len: torch.Tensor | None = None
# The query indptr, shape : [num_decode + 1]
qo_indptr: Optional[torch.Tensor] = None
qo_indptr: torch.Tensor | None = None
class AiterMLAMetadata(MLACommonMetadata[AiterMLADecodeMetadata]):
@@ -116,7 +116,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
dcp_tot_seq_lens_device: Optional[torch.Tensor],
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> AiterMLADecodeMetadata:
page_size = self.kv_cache_spec.block_size
block_table_bounds = (seq_lens_device + page_size - 1) // page_size
@@ -188,12 +188,12 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -242,11 +242,11 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: AiterMLAMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
+6 -7
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Optional, Union
import torch
@@ -44,12 +43,12 @@ class TritonMLAImpl(MLACommonImpl[MLACommonMetadata]):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float],
logits_soft_cap: float | None,
attn_type: str,
kv_sharing_target_layer_name: Optional[str],
kv_sharing_target_layer_name: str | None,
# MLA Specific Arguments
**mla_args,
) -> None:
@@ -138,11 +137,11 @@ class TritonMLAImpl(MLACommonImpl[MLACommonMetadata]):
def _forward_decode(
self,
q: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: MLACommonMetadata,
layer: AttentionLayer,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert kv_c_and_k_pe_cache.numel() > 0
assert attn_metadata.decode is not None
+8 -9
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
import torch
@@ -201,12 +200,12 @@ class PallasAttentionBackendImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: str = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[int] = None,
kv_sharing_target_layer_name: int | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -242,9 +241,9 @@ class PallasAttentionBackendImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: PallasMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with Pallas attention.
@@ -342,7 +341,7 @@ def write_to_kv_cache(
slot_mapping: torch.Tensor,
num_slices_per_kv_cache_update_block: int,
num_kv_update_slices: torch.Tensor,
kv_cache_quantized_dtype: Optional[torch.dtype] = None,
kv_cache_quantized_dtype: torch.dtype | None = None,
k_scale: float = 1.0,
v_scale: float = 1.0,
) -> None:
+14 -15
View File
@@ -3,7 +3,6 @@
"""Attention layer with AiterFlashAttention."""
from dataclasses import dataclass
from typing import Optional, Union
import torch
@@ -160,8 +159,8 @@ if current_platform.is_rocm():
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
window_size: Optional[list[int]], # -1 means infinite context window
alibi_slopes: Optional[list[float]],
window_size: list[int] | None, # -1 means infinite context window
alibi_slopes: list[float] | None,
block_table: torch.Tensor,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
@@ -209,8 +208,8 @@ if current_platform.is_rocm():
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
window_size: Optional[list[int]], # -1 means infinite context window
alibi_slopes: Optional[list[float]],
window_size: list[int] | None, # -1 means infinite context window
alibi_slopes: list[float] | None,
block_table: torch.Tensor,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
@@ -249,7 +248,7 @@ class AiterFlashAttentionMetadata:
seq_lens: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
cu_seq_lens: Optional[torch.Tensor]
cu_seq_lens: torch.Tensor | None
# For cascade attention.
use_cascade: bool
@@ -283,7 +282,7 @@ class AiterFlashAttentionMetadataBuilder(
self.block_size = kv_cache_spec.block_size
# Sliding window size to be used with the AOT scheduler will be
# populated on first build() call.
self.aot_sliding_window: Optional[tuple[int, int]] = None
self.aot_sliding_window: tuple[int, int] | None = None
self.total_tokens: int = 0
def build_for_cudagraph_capture(
@@ -361,7 +360,7 @@ class AiterFlashAttentionBackend(AttentionBackend):
return [64, 128, 256]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
@@ -412,12 +411,12 @@ class AiterFlashAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[int] = None,
kv_sharing_target_layer_name: int | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -458,9 +457,9 @@ class AiterFlashAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: AiterFlashAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with AiterFlashAttention.
@@ -2,8 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention layer with PagedAttention and Triton prefix prefill."""
from typing import Optional
import torch
from vllm import _custom_ops as ops
@@ -70,13 +68,13 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[int] = None,
sinks: Optional[torch.Tensor] = None,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
super().__init__(
num_heads,
@@ -106,9 +104,9 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: FlashAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FlashAttention.
+14 -14
View File
@@ -3,7 +3,7 @@
"""Attention layer with PagedAttention and Triton prefix prefill."""
from dataclasses import dataclass
from typing import ClassVar, Optional
from typing import ClassVar
import torch
@@ -54,13 +54,13 @@ class RocmAttentionMetadata:
# For cascade attention.
use_cascade: bool
common_prefix_len: int
cu_prefix_query_lens: Optional[torch.Tensor]
prefix_kv_lens: Optional[torch.Tensor]
suffix_kv_lens: Optional[torch.Tensor]
cu_prefix_query_lens: torch.Tensor | None
prefix_kv_lens: torch.Tensor | None
suffix_kv_lens: torch.Tensor | None
# Optional aot scheduling
scheduler_metadata: Optional[torch.Tensor] = None
prefix_scheduler_metadata: Optional[torch.Tensor] = None
scheduler_metadata: torch.Tensor | None = None
prefix_scheduler_metadata: torch.Tensor | None = None
class RocmAttentionMetadataBuilder(AttentionMetadataBuilder[RocmAttentionMetadata]):
@@ -217,13 +217,13 @@ class RocmAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[int] = None,
sinks: Optional[torch.Tensor] = None,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -273,9 +273,9 @@ class RocmAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: FlashAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with FlashAttention.
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
import torch
@@ -30,12 +29,12 @@ class ShortConvAttentionMetadata:
query_start_loc: torch.Tensor
state_indices_tensor: torch.Tensor
has_initial_states_p: Optional[torch.Tensor]
has_initial_states_p: torch.Tensor | None
# For causal_conv1d
nums_dict: Optional[dict] = None
batch_ptr: Optional[torch.Tensor] = None
token_chunk_offset_ptr: Optional[torch.Tensor] = None
nums_dict: dict | None = None
batch_ptr: torch.Tensor | None = None
token_chunk_offset_ptr: torch.Tensor | None = None
class ShortConvAttentionMetadataBuilder(
+12 -12
View File
@@ -4,7 +4,7 @@
import ast
from dataclasses import dataclass
from typing import Optional, Union
from typing import Optional
import torch
@@ -41,7 +41,7 @@ class TreeAttentionBackend(AttentionBackend):
return [32, 64, 96, 128, 160, 192, 224, 256]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
@@ -104,7 +104,7 @@ class TreeAttentionMetadata:
num_prefills: int = 0
num_decodes: int = 0
tree_attn_bias: Optional[torch.Tensor] = None
tree_attn_bias: torch.Tensor | None = None
# Cached Prefill/decode metadata.
_cached_prefill_metadata: Optional["TreeAttentionMetadata"] = None
@@ -267,8 +267,8 @@ def _get_depth_counts(sorted_tree_choices: list[tuple[int, ...]]) -> list[int]:
def _prepare_tree_attn_bias(
sorted_tree_choices: list[tuple[int, ...]],
depth_counts: list[int],
dtype: Optional[torch.dtype],
device: Optional[torch.device],
dtype: torch.dtype | None,
device: torch.device | None,
) -> torch.Tensor:
# +1 comes from the additional root node.
tree_len = len(sorted_tree_choices) + 1
@@ -310,12 +310,12 @@ class TreeAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
kv_sharing_target_layer_name: str | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -354,9 +354,9 @@ class TreeAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: TreeAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with TreeAttention.
+15 -15
View File
@@ -3,7 +3,7 @@
"""High-Performance Triton-only Attention layer."""
from dataclasses import dataclass
from typing import ClassVar, Optional, Union
from typing import ClassVar
import torch
@@ -61,13 +61,13 @@ class TritonAttentionMetadata:
# For cascade attention.
use_cascade: bool
common_prefix_len: int
cu_prefix_query_lens: Optional[torch.Tensor]
prefix_kv_lens: Optional[torch.Tensor]
suffix_kv_lens: Optional[torch.Tensor]
cu_prefix_query_lens: torch.Tensor | None
prefix_kv_lens: torch.Tensor | None
suffix_kv_lens: torch.Tensor | None
# Optional aot scheduling
scheduler_metadata: Optional[torch.Tensor] = None
prefix_scheduler_metadata: Optional[torch.Tensor] = None
scheduler_metadata: torch.Tensor | None = None
prefix_scheduler_metadata: torch.Tensor | None = None
class TritonAttentionMetadataBuilder(AttentionMetadataBuilder[TritonAttentionMetadata]):
@@ -159,7 +159,7 @@ class TritonAttentionBackend(AttentionBackend):
return [torch.float16, torch.bfloat16, torch.float32]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
@@ -216,13 +216,13 @@ class TritonAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[int] = None,
sinks: Optional[torch.Tensor] = None,
kv_sharing_target_layer_name: int | None = None,
sinks: torch.Tensor | None = None,
) -> None:
self.num_heads = num_heads
self.head_size = head_size
@@ -272,9 +272,9 @@ class TritonAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: TritonAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with Paged Attention impl. in Triton.
+10 -12
View File
@@ -11,10 +11,8 @@ from typing import (
ClassVar,
Generic,
Literal,
Optional,
Protocol,
TypeVar,
Union,
get_args,
)
@@ -42,7 +40,7 @@ from vllm.v1.worker.ubatch_utils import UBatchSlice
logger = init_logger(__name__)
KVCacheLayoutType = Literal["NHD", "HND"]
_KV_CACHE_LAYOUT_OVERRIDE: Union[KVCacheLayoutType, None] = None
_KV_CACHE_LAYOUT_OVERRIDE: KVCacheLayoutType | None = None
PAD_SLOT_ID = -1
@@ -87,13 +85,13 @@ class CommonAttentionMetadata:
causal: bool = True
# Needed by FastPrefillAttentionBuilder
logits_indices_padded: Optional[torch.Tensor] = None
num_logits_indices: Optional[int] = None
logits_indices_padded: torch.Tensor | None = None
num_logits_indices: int | None = None
# Needed by CrossAttentionBuilder
encoder_seq_lens: Optional[np.ndarray] = None
encoder_seq_lens: np.ndarray | None = None
dcp_local_seq_lens: Optional[torch.Tensor] = None
dcp_local_seq_lens: torch.Tensor | None = None
"""Sequence lengths of the local rank in decode context parallelism world"""
@@ -250,7 +248,7 @@ class AttentionMetadataBuilder(abc.ABC, Generic[M]):
# Does this backend/builder reorder the batch?
# If not, set this to None. Otherwise set it to the query
# length that will be pulled into the front of the batch.
reorder_batch_threshold: Optional[int] = None
reorder_batch_threshold: int | None = None
@abstractmethod
def __init__(
@@ -395,12 +393,12 @@ class PerLayerParameters:
"""
window_left: int
logits_soft_cap: Optional[float]
logits_soft_cap: float | None
sm_scale: float
has_sinks: bool = False
# has same params for all layers
has_same_window_lefts: Optional[bool] = field(default=None, compare=False)
has_same_all_params: Optional[bool] = field(default=None, compare=False)
has_same_window_lefts: bool | None = field(default=None, compare=False)
has_same_all_params: bool | None = field(default=None, compare=False)
def get_per_layer_parameters(
@@ -873,7 +871,7 @@ def reshape_attn_output_for_spec_decode(attn_output: torch.Tensor) -> torch.Tens
KV_SHARING_FAST_PREFILL_METADATA_FIELDS = [
("logits_indices_padded", Optional[torch.Tensor], None),
("logits_indices_padded", torch.Tensor | None, None),
("num_logits_indices", int, 0),
]
+9 -9
View File
@@ -3,7 +3,7 @@
"""Attention layer with XFormersAttention."""
from dataclasses import dataclass
from typing import Optional, Union
from typing import Optional
import torch
@@ -82,7 +82,7 @@ class XFormersAttentionBackend(AttentionBackend):
]
@staticmethod
def get_supported_kernel_block_size() -> list[Union[int, MultipleOf]]:
def get_supported_kernel_block_size() -> list[int | MultipleOf]:
return [MultipleOf(16)]
@classmethod
@@ -280,12 +280,12 @@ class XFormersAttentionImpl(AttentionImpl):
head_size: int,
scale: float,
num_kv_heads: int,
alibi_slopes: Optional[list[float]],
sliding_window: Optional[int],
alibi_slopes: list[float] | None,
sliding_window: int | None,
kv_cache_dtype: str,
logits_soft_cap: Optional[float] = None,
logits_soft_cap: float | None = None,
attn_type: AttentionType = AttentionType.DECODER,
kv_sharing_target_layer_name: Optional[str] = None,
kv_sharing_target_layer_name: str | None = None,
) -> None:
if kv_sharing_target_layer_name is not None:
raise NotImplementedError("KV sharing is not supported in V0.")
@@ -328,9 +328,9 @@ class XFormersAttentionImpl(AttentionImpl):
value: torch.Tensor,
kv_cache: torch.Tensor,
attn_metadata: XFormersAttentionMetadata,
output: Optional[torch.Tensor] = None,
output_scale: Optional[torch.Tensor] = None,
output_block_scale: Optional[torch.Tensor] = None,
output: torch.Tensor | None = None,
output_scale: torch.Tensor | None = None,
output_block_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Forward pass with XFormers.
+7 -7
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable
from typing import Any, Optional, Union
from typing import Any
from vllm.distributed.kv_events import (
MEDIUM_GPU,
@@ -51,10 +51,10 @@ class BlockHashToBlockMap:
def __init__(self):
self._cache: dict[
BlockHashWithGroupId, Union[KVCacheBlock, dict[int, KVCacheBlock]]
BlockHashWithGroupId, KVCacheBlock | dict[int, KVCacheBlock]
] = {}
def get_one_block(self, key: BlockHashWithGroupId) -> Optional[KVCacheBlock]:
def get_one_block(self, key: BlockHashWithGroupId) -> KVCacheBlock | None:
"""
Gets any block with the given block hash key.
"""
@@ -85,7 +85,7 @@ class BlockHashToBlockMap:
else:
self._unexpected_blocks_type(blocks)
def pop(self, key: BlockHashWithGroupId, block_id: int) -> Optional[KVCacheBlock]:
def pop(self, key: BlockHashWithGroupId, block_id: int) -> KVCacheBlock | None:
"""
Checks if block_hash exists and pop block_id from the cache
"""
@@ -168,7 +168,7 @@ class BlockPool:
def get_cached_block(
self, block_hash: BlockHash, kv_cache_group_ids: list[int]
) -> Optional[list[KVCacheBlock]]:
) -> list[KVCacheBlock] | None:
"""Get the cached block by the block hash for each group in
`kv_cache_group_ids`, or None if cache miss for any group.
If there are duplicated blocks, we return the first block in the cache.
@@ -225,7 +225,7 @@ class BlockPool:
assert len(request.block_hashes) >= num_full_blocks
new_block_hashes = request.block_hashes[num_cached_blocks:]
new_hashes: Optional[list[ExternalBlockHash]] = (
new_hashes: list[ExternalBlockHash] | None = (
[] if self.enable_kv_cache_events else None
)
for i, blk in enumerate(new_full_blocks):
@@ -243,7 +243,7 @@ class BlockPool:
if self.enable_kv_cache_events:
if num_cached_blocks == 0:
parent_block_hash: Optional[ExternalBlockHash] = None
parent_block_hash: ExternalBlockHash | None = None
else:
parent_block = blocks[num_cached_blocks - 1]
assert parent_block.block_hash is not None
+2 -3
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from typing import Optional
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.kv_cache_utils import BlockHash, KVCacheBlock
@@ -320,8 +319,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
one of them is full attention. Then, split the kv cache groups into full
attention groups and other groups.
"""
full_attention_spec: Optional[FullAttentionSpec] = None
other_spec: Optional[KVCacheSpec] = None
full_attention_spec: FullAttentionSpec | None = None
other_spec: KVCacheSpec | None = None
self.full_attention_group_ids: list[int] = []
self.other_group_ids: list[int] = []
for i, g in enumerate(self.kv_cache_config.kv_cache_groups):
+7 -7
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Literal, Optional, overload
from typing import Literal, overload
from vllm.distributed.kv_events import KVCacheEvent
from vllm.logger import init_logger
@@ -49,12 +49,12 @@ class KVCacheBlocks:
def get_block_ids(
self,
allow_none: Literal[True] = True,
) -> Optional[tuple[list[int], ...]]: ...
) -> tuple[list[int], ...] | None: ...
def get_block_ids(
self,
allow_none: bool = False,
) -> Optional[tuple[list[int], ...]]:
) -> tuple[list[int], ...] | None:
"""
Converts the KVCacheBlocks instance to block_ids.
@@ -97,7 +97,7 @@ class KVCacheManager:
# FIXME: make prefix cache stats conditional on log_stats
self.prefix_cache_stats = PrefixCacheStats() if log_stats else None
self.block_size: Optional[int] = None
self.block_size: int | None = None
if self.enable_caching:
assert (
len(
@@ -140,7 +140,7 @@ class KVCacheManager:
"""
return self.block_pool.get_usage()
def make_prefix_cache_stats(self) -> Optional[PrefixCacheStats]:
def make_prefix_cache_stats(self) -> PrefixCacheStats | None:
"""Get (and reset) the prefix cache stats.
Returns:
@@ -205,11 +205,11 @@ class KVCacheManager:
request: Request,
num_new_tokens: int,
num_new_computed_tokens: int = 0,
new_computed_blocks: Optional[KVCacheBlocks] = None,
new_computed_blocks: KVCacheBlocks | None = None,
num_lookahead_tokens: int = 0,
delay_cache_blocks: bool = False,
num_encoder_tokens: int = 0,
) -> Optional[KVCacheBlocks]:
) -> KVCacheBlocks | None:
"""Add slots for a request with new tokens to append.
Args:
+10 -10
View File
@@ -5,9 +5,9 @@
import copy
import os
from collections import defaultdict
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from typing import Any, Callable, NewType, Optional, Union
from typing import Any, NewType, TypeAlias
from vllm import envs
from vllm.config import VllmConfig
@@ -38,7 +38,7 @@ BlockHashWithGroupId = NewType("BlockHashWithGroupId", bytes)
# ExternalBlockHash is used for reproducible prefix-cache block hashing.
# It's a union of ``bytes`` and ``int`` to keep backward compatibility
# after we default block hashing to use sha256 bytes.
ExternalBlockHash = Union[bytes, int]
ExternalBlockHash: TypeAlias = bytes | int
def make_block_hash_with_group_id(
@@ -110,18 +110,18 @@ class KVCacheBlock:
ref_cnt: int = 0
# The hash key (block hash + group id) of the block, only available
# when the block is full and cached.
_block_hash: Optional[BlockHashWithGroupId] = None
_block_hash: BlockHashWithGroupId | None = None
# Used to construct a doubly linked list for free blocks.
# These two attributes should only be manipulated by FreeKVCacheBlockQueue.
prev_free_block: Optional["KVCacheBlock"] = None
next_free_block: Optional["KVCacheBlock"] = None
prev_free_block: "KVCacheBlock | None" = None
next_free_block: "KVCacheBlock | None" = None
# Whether the block is a null block that should never be cached.
is_null: bool = False
@property
def block_hash(self) -> Optional[BlockHashWithGroupId]:
def block_hash(self) -> BlockHashWithGroupId | None:
return self._block_hash
@block_hash.setter
@@ -461,7 +461,7 @@ def _gen_lora_extra_hash_keys(request: Request) -> list[int]:
def generate_block_hash_extra_keys(
request: Request, start_token_idx: int, end_token_idx: int, start_mm_idx: int
) -> tuple[Optional[tuple[Any, ...]], int]:
) -> tuple[tuple[Any, ...] | None, int]:
"""Generate extra keys for the block hash. The extra keys can come from
the multi-modal inputs and request specific metadata (e.g., LoRA ID).
@@ -493,9 +493,9 @@ def generate_block_hash_extra_keys(
def hash_block_tokens(
hash_function: Callable[[Any], bytes],
parent_block_hash: Optional[BlockHash],
parent_block_hash: BlockHash | None,
curr_block_token_ids: Sequence[int],
extra_keys: Optional[tuple[Any, ...]] = None,
extra_keys: tuple[Any, ...] | None = None,
) -> BlockHash:
"""Computes a hash value corresponding to the contents of a block and
the contents of the preceding block(s). The hash value is used for
-2
View File
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from vllm.logger import init_logger
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.core.sched.scheduler import Scheduler
+2 -2
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from collections.abc import Iterable
from typing import TYPE_CHECKING, Optional, Union
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorBase_V1
@@ -80,7 +80,7 @@ class SchedulerInterface(ABC):
@abstractmethod
def finish_requests(
self,
request_ids: Union[str, Iterable[str]],
request_ids: str | Iterable[str],
finished_status: "RequestStatus",
) -> None:
"""Finish the requests in the scheduler's internal queue. If the request
+11 -6
View File
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -19,6 +17,13 @@ if TYPE_CHECKING:
from vllm.pooling_params import PoolingParams
from vllm.sampling_params import SamplingParams
from vllm.v1.request import Request
else:
KVConnectorMetadata = object
LoRARequest = object
MultiModalFeatureSpec = object
PoolingParams = object
SamplingParams = object
Request = object
@bc_linter_include
@@ -32,14 +37,14 @@ class NewRequestData:
block_ids: tuple[list[int], ...]
num_computed_tokens: int
lora_request: LoRARequest | None
prompt_embeds: torch.Tensor | None = None
prompt_embeds: "torch.Tensor | None" = None
@classmethod
def from_request(
cls,
request: Request,
block_ids: tuple[list[int], ...],
) -> NewRequestData:
) -> "NewRequestData":
return cls(
req_id=request.request_id,
prompt_token_ids=request.prompt_token_ids,
@@ -110,7 +115,7 @@ class CachedRequestData:
return len(self.req_ids)
@classmethod
def make_empty(cls) -> CachedRequestData:
def make_empty(cls) -> "CachedRequestData":
return cls(
req_ids=[],
resumed_from_preemption=[],
@@ -164,7 +169,7 @@ class SchedulerOutput:
# for filling the next token bitmask
structured_output_request_ids: dict[str, int]
# the bitmask for the whole batch
grammar_bitmask: npt.NDArray[np.int32] | None
grammar_bitmask: "npt.NDArray[np.int32] | None"
# KV Cache Connector metadata.
kv_connector_metadata: KVConnectorMetadata | None = None
+1 -3
View File
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import heapq
from abc import ABC, abstractmethod
from collections import deque
@@ -43,7 +41,7 @@ class RequestQueue(ABC):
pass
@abstractmethod
def prepend_requests(self, requests: RequestQueue) -> None:
def prepend_requests(self, requests: "RequestQueue") -> None:
"""Prepend all requests from another queue to the front of this
queue."""
pass
+2 -4
View File
@@ -1,13 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import itertools
import time
from collections import defaultdict
from collections.abc import Iterable
from typing import Any, Union
from typing import Any
from vllm.config import VllmConfig
from vllm.distributed.kv_events import EventPublisherFactory, KVEventBatch
@@ -1168,7 +1166,7 @@ class Scheduler(SchedulerInterface):
def finish_requests(
self,
request_ids: Union[str, Iterable[str]],
request_ids: str | Iterable[str],
finished_status: RequestStatus,
) -> None:
"""Handles the finish signal from outside the scheduler.
+1 -2
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
from typing import Optional
import torch
@@ -41,7 +40,7 @@ def remove_all(lst: list, items_to_remove: set) -> list:
def check_stop(
request: Request, max_model_len: int, pooler_output: Optional[torch.Tensor] = None
request: Request, max_model_len: int, pooler_output: torch.Tensor | None = None
) -> bool:
if (
request.num_tokens >= max_model_len
+1 -2
View File
@@ -1,6 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Optional
from vllm.config import CUDAGraphMode, VllmConfig
from vllm.forward_context import BatchDescriptor
@@ -102,7 +101,7 @@ class CudagraphDispatcher:
def dispatch(
self, batch_descriptor: BatchDescriptor, use_cascade_attn: bool = False
) -> tuple[CUDAGraphMode, Optional[BatchDescriptor]]:
) -> tuple[CUDAGraphMode, BatchDescriptor | None]:
"""
Given conditions(e.g.,batch descriptor and if using cascade attention),
dispatch to a cudagraph runtime mode and the valid batch descriptor.
+27 -27
View File
@@ -4,7 +4,7 @@
import enum
import time
from collections.abc import Mapping
from typing import Any, Optional, Union
from typing import Any
import msgspec
import torch
@@ -48,16 +48,16 @@ class EngineCoreRequest(
gc=False,
): # type: ignore[call-arg]
request_id: str
prompt_token_ids: Optional[list[int]]
mm_features: Optional[list[MultiModalFeatureSpec]]
sampling_params: Optional[SamplingParams]
pooling_params: Optional[PoolingParams]
eos_token_id: Optional[int]
prompt_token_ids: list[int] | None
mm_features: list[MultiModalFeatureSpec] | None
sampling_params: SamplingParams | None
pooling_params: PoolingParams | None
eos_token_id: int | None
arrival_time: float
lora_request: Optional[LoRARequest]
cache_salt: Optional[str]
data_parallel_rank: Optional[int]
prompt_embeds: Optional[torch.Tensor] = None
lora_request: LoRARequest | None
cache_salt: str | None
data_parallel_rank: int | None
prompt_embeds: torch.Tensor | None = None
# Index of the client, used to ensure outputs are sent back to the same
# client for this request when scaling out the front-end.
@@ -69,7 +69,7 @@ class EngineCoreRequest(
current_wave: int = 0
priority: int = 0
trace_headers: Optional[Mapping[str, str]] = None
trace_headers: Mapping[str, str] | None = None
class EngineCoreEventType(enum.IntEnum):
@@ -93,7 +93,7 @@ class EngineCoreEvent(msgspec.Struct):
@classmethod
def new_event(
cls, event_type: EngineCoreEventType, timestamp: Optional[float] = None
cls, event_type: EngineCoreEventType, timestamp: float | None = None
) -> "EngineCoreEvent":
timestamp = time.monotonic() if timestamp is None else timestamp
return cls(event_type, timestamp)
@@ -108,17 +108,17 @@ class EngineCoreOutput(
request_id: str
new_token_ids: list[int]
new_logprobs: Optional[LogprobsLists] = None
new_prompt_logprobs_tensors: Optional[LogprobsTensors] = None
new_logprobs: LogprobsLists | None = None
new_prompt_logprobs_tensors: LogprobsTensors | None = None
pooling_output: Optional[torch.Tensor] = None
pooling_output: torch.Tensor | None = None
finish_reason: Optional[FinishReason] = None
stop_reason: Union[int, str, None] = None
events: Optional[list[EngineCoreEvent]] = None
kv_transfer_params: Optional[dict[str, Any]] = None
finish_reason: FinishReason | None = None
stop_reason: int | str | None = None
events: list[EngineCoreEvent] | None = None
kv_transfer_params: dict[str, Any] | None = None
trace_headers: Optional[Mapping[str, str]] = None
trace_headers: Mapping[str, str] | None = None
# The number of tokens with prefix cache hits.
num_cached_tokens: int = 0
@@ -142,8 +142,8 @@ class UtilityOutput(
call_id: int
# Non-None implies the call failed, result should be None.
failure_message: Optional[str] = None
result: Optional[UtilityResult] = None
failure_message: str | None = None
result: UtilityResult | None = None
class EngineCoreOutputs(
@@ -159,18 +159,18 @@ class EngineCoreOutputs(
# [num_reqs]
outputs: list[EngineCoreOutput] = []
scheduler_stats: Optional[SchedulerStats] = None
scheduler_stats: SchedulerStats | None = None
timestamp: float = 0.0
utility_output: Optional[UtilityOutput] = None
finished_requests: Optional[set[str]] = None
utility_output: UtilityOutput | None = None
finished_requests: set[str] | None = None
# In DP case, used to signal that the current wave of requests
# has finished and the engines are paused.
wave_complete: Optional[int] = None
wave_complete: int | None = None
# In DP case, used to signal that a request was received for an
# "old" wave, so the next wave needs to be started in other engines.
start_wave: Optional[int] = None
start_wave: int | None = None
def __post_init__(self):
if self.timestamp == 0.0:
+35 -35
View File
@@ -6,7 +6,7 @@ import socket
import time
from collections.abc import AsyncGenerator, Iterable, Mapping
from copy import copy
from typing import Any, Optional, Union
from typing import Any
import numpy as np
import torch
@@ -56,8 +56,8 @@ class AsyncLLM(EngineClient):
use_cached_outputs: bool = False,
log_requests: bool = True,
start_engine_loop: bool = True,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
client_addresses: Optional[dict[str, str]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
) -> None:
@@ -136,7 +136,7 @@ class AsyncLLM(EngineClient):
)
# Loggers.
self.logger_manager: Optional[StatLoggerManager] = None
self.logger_manager: StatLoggerManager | None = None
if self.log_stats:
self.logger_manager = StatLoggerManager(
vllm_config=vllm_config,
@@ -147,7 +147,7 @@ class AsyncLLM(EngineClient):
)
self.logger_manager.log_engine_initialized()
self.output_handler: Optional[asyncio.Task] = None
self.output_handler: asyncio.Task | None = None
try:
# Start output handler eagerly if we are in the asyncio eventloop.
asyncio.get_running_loop()
@@ -185,10 +185,10 @@ class AsyncLLM(EngineClient):
vllm_config: VllmConfig,
start_engine_loop: bool = True,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
enable_log_requests: bool = False,
disable_log_stats: bool = False,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
disable_log_requests: bool = True, # Deprecated, will be removed
@@ -221,7 +221,7 @@ class AsyncLLM(EngineClient):
engine_args: AsyncEngineArgs,
start_engine_loop: bool = True,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
) -> "AsyncLLM":
"""Create an AsyncLLM from the EngineArgs."""
@@ -259,15 +259,15 @@ class AsyncLLM(EngineClient):
async def add_request(
self,
request_id: str,
prompt: Union[EngineCoreRequest, PromptType],
params: Union[SamplingParams, PoolingParams],
arrival_time: Optional[float] = None,
lora_request: Optional[LoRARequest] = None,
tokenization_kwargs: Optional[dict[str, Any]] = None,
trace_headers: Optional[Mapping[str, str]] = None,
prompt: EngineCoreRequest | PromptType,
params: SamplingParams | PoolingParams,
arrival_time: float | None = None,
lora_request: LoRARequest | None = None,
tokenization_kwargs: dict[str, Any] | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
data_parallel_rank: Optional[int] = None,
prompt_text: Optional[str] = None,
data_parallel_rank: int | None = None,
prompt_text: str | None = None,
) -> RequestOutputCollector:
"""Add new request to the AsyncLLM."""
@@ -325,8 +325,8 @@ class AsyncLLM(EngineClient):
async def _add_request(
self,
request: EngineCoreRequest,
prompt: Optional[str],
parent_req: Optional[ParentRequest],
prompt: str | None,
parent_req: ParentRequest | None,
index: int,
queue: RequestOutputCollector,
):
@@ -346,16 +346,16 @@ class AsyncLLM(EngineClient):
# re-multiplexed in the API server anyhow.
async def generate(
self,
prompt: Union[EngineCoreRequest, PromptType],
prompt: EngineCoreRequest | PromptType,
sampling_params: SamplingParams,
request_id: str,
*,
prompt_text: Optional[str] = None,
lora_request: Optional[LoRARequest] = None,
tokenization_kwargs: Optional[dict[str, Any]] = None,
trace_headers: Optional[Mapping[str, str]] = None,
prompt_text: str | None = None,
lora_request: LoRARequest | None = None,
tokenization_kwargs: dict[str, Any] | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
data_parallel_rank: Optional[int] = None,
data_parallel_rank: int | None = None,
) -> AsyncGenerator[RequestOutput, None]:
"""
Main function called by the API server to kick off a request
@@ -520,7 +520,7 @@ class AsyncLLM(EngineClient):
self.output_handler = asyncio.create_task(output_handler())
async def abort(self, request_id: Union[str, Iterable[str]]) -> None:
async def abort(self, request_id: str | Iterable[str]) -> None:
"""Abort RequestId in OutputProcessor and EngineCore."""
request_ids = (
@@ -537,11 +537,11 @@ class AsyncLLM(EngineClient):
prompt: PromptType,
pooling_params: PoolingParams,
request_id: str,
lora_request: Optional[LoRARequest] = None,
trace_headers: Optional[Mapping[str, str]] = None,
lora_request: LoRARequest | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
truncate_prompt_tokens: Optional[int] = None,
tokenization_kwargs: Optional[dict[str, Any]] = None,
truncate_prompt_tokens: int | None = None,
tokenization_kwargs: dict[str, Any] | None = None,
) -> AsyncGenerator[PoolingRequestOutput, None]:
"""
Main function called by the API server to kick off a request
@@ -622,11 +622,11 @@ class AsyncLLM(EngineClient):
raise EngineGenerateError() from e
@property
def tokenizer(self) -> Optional[AnyTokenizer]:
def tokenizer(self) -> AnyTokenizer | None:
return self.processor.tokenizer
@tokenizer.setter
def tokenizer(self, tokenizer: Optional[AnyTokenizer]) -> None:
def tokenizer(self, tokenizer: AnyTokenizer | None) -> None:
self.processor.tokenizer = tokenizer
async def get_tokenizer(self) -> AnyTokenizer:
@@ -665,7 +665,7 @@ class AsyncLLM(EngineClient):
self.processor.clear_mm_cache()
await self.engine_core.reset_mm_cache_async()
async def reset_prefix_cache(self, device: Optional[Device] = None) -> None:
async def reset_prefix_cache(self, device: Device | None = None) -> None:
if device == Device.CPU:
raise ValueError("Not supported on CPU.")
await self.engine_core.reset_prefix_cache_async()
@@ -674,7 +674,7 @@ class AsyncLLM(EngineClient):
await self.reset_prefix_cache()
await self.engine_core.sleep_async(level)
async def wake_up(self, tags: Optional[list[str]] = None) -> None:
async def wake_up(self, tags: list[str] | None = None) -> None:
await self.engine_core.wake_up_async(tags)
async def is_sleeping(self) -> bool:
@@ -699,9 +699,9 @@ class AsyncLLM(EngineClient):
async def collective_rpc(
self,
method: str,
timeout: Optional[float] = None,
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict] = None,
kwargs: dict | None = None,
):
"""
Perform a collective RPC call to the given path.
+2 -3
View File
@@ -4,7 +4,6 @@ import copy
import multiprocessing
import time
import weakref
from typing import Optional
import msgspec.msgpack
import zmq
@@ -155,7 +154,7 @@ class DPCoordinatorProc:
stats_changed = False
last_stats_step = -1
last_stats_wave = -1
last_step_counts: Optional[list[list[int]]] = None
last_step_counts: list[list[int]] | None = None
with (
make_zmq_socket(
@@ -360,7 +359,7 @@ class DPCoordinatorProc:
@staticmethod
def _send_start_wave(
socket: zmq.Socket, wave: int, exclude_engine_index: Optional[int]
socket: zmq.Socket, wave: int, exclude_engine_index: int | None
):
"""Broadcast the START_DP_WAVE message to all the engines.
It includes the current wave number and index of engine which
+24 -24
View File
@@ -7,12 +7,12 @@ import signal
import threading
import time
from collections import deque
from collections.abc import Generator
from collections.abc import Callable, Generator
from concurrent.futures import Future
from contextlib import ExitStack, contextmanager
from inspect import isclass, signature
from logging import DEBUG
from typing import Any, Callable, Optional, TypeVar, Union
from typing import Any, TypeVar
import msgspec
import zmq
@@ -83,7 +83,7 @@ class EngineCore:
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
executor_fail_callback: Optional[Callable] = None,
executor_fail_callback: Callable | None = None,
):
# plugins need to be loaded at the engine/scheduler level too
from vllm.plugins import load_general_plugins
@@ -171,14 +171,14 @@ class EngineCore:
# schedule and execute batches, and is required by pipeline parallelism
# to eliminate pipeline bubbles.
self.batch_queue_size = self.model_executor.max_concurrent_batches
self.batch_queue: Optional[
deque[tuple[Future[ModelRunnerOutput], SchedulerOutput]]
] = None
self.batch_queue: (
deque[tuple[Future[ModelRunnerOutput], SchedulerOutput]] | None
) = None
if self.batch_queue_size > 1:
logger.info("Batch queue is enabled with size %d", self.batch_queue_size)
self.batch_queue = deque(maxlen=self.batch_queue_size)
self.request_block_hasher: Optional[Callable[[Request], list[BlockHash]]] = None
self.request_block_hasher: Callable[[Request], list[BlockHash]] | None = None
if (
self.vllm_config.cache_config.enable_prefix_caching
or self.scheduler.get_kv_connector() is not None
@@ -337,7 +337,7 @@ class EngineCore:
def step_with_batch_queue(
self,
) -> tuple[Optional[dict[int, EngineCoreOutputs]], bool]:
) -> tuple[dict[int, EngineCoreOutputs] | None, bool]:
"""Schedule and execute batches with the batch queue.
Note that if nothing to output in this step, None is returned.
@@ -424,7 +424,7 @@ class EngineCore:
def sleep(self, level: int = 1):
self.model_executor.sleep(level)
def wake_up(self, tags: Optional[list[str]] = None):
def wake_up(self, tags: list[str] | None = None):
self.model_executor.wake_up(tags)
def is_sleeping(self) -> bool:
@@ -448,8 +448,8 @@ class EngineCore:
def save_sharded_state(
self,
path: str,
pattern: Optional[str] = None,
max_size: Optional[int] = None,
pattern: str | None = None,
max_size: int | None = None,
) -> None:
self.model_executor.save_sharded_state(
path=path, pattern=pattern, max_size=max_size
@@ -457,10 +457,10 @@ class EngineCore:
def collective_rpc(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
return self.model_executor.collective_rpc(method, timeout, args, kwargs)
@@ -509,11 +509,11 @@ class EngineCoreProc(EngineCore):
handshake_address: str,
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: Optional[str] = None,
client_handshake_address: str | None = None,
engine_index: int = 0,
):
self.input_queue = queue.Queue[tuple[EngineCoreRequestType, Any]]()
self.output_queue = queue.Queue[Union[tuple[int, EngineCoreOutputs], bytes]]()
self.output_queue = queue.Queue[tuple[int, EngineCoreOutputs] | bytes]()
executor_fail_callback = lambda: self.input_queue.put_nowait(
(EngineCoreRequestType.EXECUTOR_FAILED, b"")
)
@@ -606,7 +606,7 @@ class EngineCoreProc(EngineCore):
identity: bytes,
local_client: bool,
vllm_config: VllmConfig,
client_handshake_address: Optional[str],
client_handshake_address: str | None,
) -> Generator[EngineZmqAddresses, None, None]:
"""
Perform startup handshakes.
@@ -667,7 +667,7 @@ class EngineCoreProc(EngineCore):
local_client: bool,
headless: bool,
vllm_config: VllmConfig,
parallel_config_to_update: Optional[ParallelConfig] = None,
parallel_config_to_update: ParallelConfig | None = None,
) -> Generator[EngineZmqAddresses, None, None]:
with make_zmq_socket(
ctx,
@@ -710,7 +710,7 @@ class EngineCoreProc(EngineCore):
handshake_socket: zmq.Socket,
local_client: bool,
headless: bool,
parallel_config: Optional[ParallelConfig] = None,
parallel_config: ParallelConfig | None = None,
) -> EngineZmqAddresses:
# Send registration message.
handshake_socket.send(
@@ -765,7 +765,7 @@ class EngineCoreProc(EngineCore):
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
engine_core: Optional[EngineCoreProc] = None
engine_core: EngineCoreProc | None = None
try:
parallel_config: ParallelConfig = kwargs["vllm_config"].parallel_config
if parallel_config.data_parallel_size > 1 or dp_rank > 0:
@@ -911,7 +911,7 @@ class EngineCoreProc(EngineCore):
def process_input_sockets(
self,
input_addresses: list[str],
coord_input_address: Optional[str],
coord_input_address: str | None,
identity: bytes,
ready_event: threading.Event,
):
@@ -980,7 +980,7 @@ class EngineCoreProc(EngineCore):
def process_output_sockets(
self,
output_paths: list[str],
coord_output_path: Optional[str],
coord_output_path: str | None,
engine_index: int,
):
"""Output socket IO thread."""
@@ -1059,7 +1059,7 @@ class DPEngineCoreProc(EngineCoreProc):
handshake_address: str,
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: Optional[str] = None,
client_handshake_address: str | None = None,
):
# Counts forward-passes of the model so that we can synchronize
# finished with DP peers every N steps.
@@ -1332,7 +1332,7 @@ class DPEngineCoreActor(DPEngineCoreProc):
identity: bytes,
local_client: bool,
vllm_config: VllmConfig,
client_handshake_address: Optional[str],
client_handshake_address: str | None,
):
"""
For Ray, we don't need to actually perform handshake.
+50 -52
View File
@@ -9,11 +9,11 @@ import uuid
import weakref
from abc import ABC, abstractmethod
from collections import defaultdict, deque
from collections.abc import Awaitable, Sequence
from collections.abc import Awaitable, Callable, Sequence
from concurrent.futures import Future
from dataclasses import dataclass
from threading import Thread
from typing import Any, Callable, Optional, TypeVar, Union
from typing import Any, TypeAlias, TypeVar
import msgspec.msgpack
import zmq
@@ -51,7 +51,7 @@ from vllm.v1.serial_utils import MsgpackDecoder, MsgpackEncoder, bytestr
logger = init_logger(__name__)
AnyFuture = Union[asyncio.Future[Any], Future[Any]]
AnyFuture: TypeAlias = asyncio.Future[Any] | Future[Any]
_R = TypeVar("_R") # Return type for collective_rpc
@@ -99,7 +99,7 @@ class EngineCoreClient(ABC):
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
) -> "MPClient":
@@ -144,7 +144,7 @@ class EngineCoreClient(ABC):
def sleep(self, level: int = 1) -> None:
raise NotImplementedError
def wake_up(self, tags: Optional[list[str]] = None) -> None:
def wake_up(self, tags: list[str] | None = None) -> None:
raise NotImplementedError
def is_sleeping(self) -> bool:
@@ -172,16 +172,16 @@ class EngineCoreClient(ABC):
raise NotImplementedError
def save_sharded_state(
self, path: str, pattern: Optional[str] = None, max_size: Optional[int] = None
self, path: str, pattern: str | None = None, max_size: int | None = None
) -> None:
raise NotImplementedError
def collective_rpc(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
raise NotImplementedError
@@ -214,7 +214,7 @@ class EngineCoreClient(ABC):
async def sleep_async(self, level: int = 1) -> None:
raise NotImplementedError
async def wake_up_async(self, tags: Optional[list[str]] = None) -> None:
async def wake_up_async(self, tags: list[str] | None = None) -> None:
raise NotImplementedError
async def is_sleeping_async(self) -> bool:
@@ -236,16 +236,16 @@ class EngineCoreClient(ABC):
raise NotImplementedError
async def save_sharded_state_async(
self, path: str, pattern: Optional[str] = None, max_size: Optional[int] = None
self, path: str, pattern: str | None = None, max_size: int | None = None
) -> None:
raise NotImplementedError
async def collective_rpc_async(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
raise NotImplementedError
@@ -293,7 +293,7 @@ class InprocClient(EngineCoreClient):
def sleep(self, level: int = 1) -> None:
self.engine_core.sleep(level)
def wake_up(self, tags: Optional[list[str]] = None) -> None:
def wake_up(self, tags: list[str] | None = None) -> None:
self.engine_core.wake_up(tags)
def is_sleeping(self) -> bool:
@@ -315,16 +315,16 @@ class InprocClient(EngineCoreClient):
return self.engine_core.pin_lora(lora_id)
def save_sharded_state(
self, path: str, pattern: Optional[str] = None, max_size: Optional[int] = None
self, path: str, pattern: str | None = None, max_size: int | None = None
) -> None:
self.engine_core.save_sharded_state(path, pattern, max_size)
def collective_rpc(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
return self.engine_core.collective_rpc(method, timeout, args, kwargs)
@@ -340,18 +340,16 @@ class BackgroundResources:
ctx: zmq.Context
# If CoreEngineProcManager, it manages local engines;
# if CoreEngineActorManager, it manages all engines.
engine_manager: Optional[Union[CoreEngineProcManager, CoreEngineActorManager]] = (
None
)
coordinator: Optional[DPCoordinator] = None
output_socket: Optional[Union[zmq.Socket, zmq.asyncio.Socket]] = None
input_socket: Optional[Union[zmq.Socket, zmq.asyncio.Socket]] = None
first_req_send_socket: Optional[zmq.asyncio.Socket] = None
first_req_rcv_socket: Optional[zmq.asyncio.Socket] = None
stats_update_socket: Optional[zmq.asyncio.Socket] = None
output_queue_task: Optional[asyncio.Task] = None
stats_update_task: Optional[asyncio.Task] = None
shutdown_path: Optional[str] = None
engine_manager: CoreEngineProcManager | CoreEngineActorManager | None = None
coordinator: DPCoordinator | None = None
output_socket: zmq.Socket | zmq.asyncio.Socket | None = None
input_socket: zmq.Socket | zmq.asyncio.Socket | None = None
first_req_send_socket: zmq.asyncio.Socket | None = None
first_req_rcv_socket: zmq.asyncio.Socket | None = None
stats_update_socket: zmq.asyncio.Socket | None = None
output_queue_task: asyncio.Task | None = None
stats_update_task: asyncio.Task | None = None
shutdown_path: str | None = None
# Set if any of the engines are dead. Here so that the output
# processing threads can access it without holding a ref to the client.
@@ -438,7 +436,7 @@ class MPClient(EngineCoreClient):
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
):
self.vllm_config = vllm_config
# Serialization setup.
@@ -459,7 +457,7 @@ class MPClient(EngineCoreClient):
# State used for data parallel.
self.engines_running = False
self.stats_update_address: Optional[str] = None
self.stats_update_address: str | None = None
if client_addresses:
# Engines are managed externally to this client.
input_address = client_addresses["input_address"]
@@ -646,7 +644,7 @@ class SyncMPClient(MPClient):
)
self.is_dp = self.vllm_config.parallel_config.data_parallel_size > 1
self.outputs_queue = queue.Queue[Union[EngineCoreOutputs, Exception]]()
self.outputs_queue = queue.Queue[EngineCoreOutputs | Exception]()
# Ensure that the outputs socket processing thread does not have
# a ref to the client which prevents gc.
@@ -770,7 +768,7 @@ class SyncMPClient(MPClient):
def sleep(self, level: int = 1) -> None:
self.call_utility("sleep", level)
def wake_up(self, tags: Optional[list[str]] = None) -> None:
def wake_up(self, tags: list[str] | None = None) -> None:
self.call_utility("wake_up", tags)
def is_sleeping(self) -> bool:
@@ -781,15 +779,15 @@ class SyncMPClient(MPClient):
def collective_rpc(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
return self.call_utility("collective_rpc", method, timeout, args, kwargs)
def save_sharded_state(
self, path: str, pattern: Optional[str] = None, max_size: Optional[int] = None
self, path: str, pattern: str | None = None, max_size: int | None = None
) -> None:
self.call_utility("save_sharded_state", path, pattern, max_size)
@@ -802,7 +800,7 @@ class AsyncMPClient(MPClient):
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
):
@@ -816,7 +814,7 @@ class AsyncMPClient(MPClient):
self.client_count = client_count
self.client_index = client_index
self.outputs_queue = asyncio.Queue[Union[EngineCoreOutputs, Exception]]()
self.outputs_queue = asyncio.Queue[EngineCoreOutputs | Exception]()
try:
# If we are running in an asyncio event loop, start the queue task.
# Otherwise, it will be started lazily. If it is not started here,
@@ -837,9 +835,9 @@ class AsyncMPClient(MPClient):
decoder = self.decoder
utility_results = self.utility_results
outputs_queue = self.outputs_queue
output_handler: Optional[
Callable[[AsyncMPClient, EngineCoreOutputs], Awaitable[None]]
] = getattr(self.__class__, "process_engine_outputs", None)
output_handler: (
Callable[[AsyncMPClient, EngineCoreOutputs], Awaitable[None]] | None
) = getattr(self.__class__, "process_engine_outputs", None)
_self_ref = weakref.ref(self) if output_handler else None
output_socket = resources.output_socket
assert output_socket is not None
@@ -888,7 +886,7 @@ class AsyncMPClient(MPClient):
self,
request_type: EngineCoreRequestType,
request: Any,
engine: Optional[EngineIdentity] = None,
engine: EngineIdentity | None = None,
) -> Awaitable[Any]:
if engine is None:
engine = self.core_engine
@@ -962,7 +960,7 @@ class AsyncMPClient(MPClient):
async def sleep_async(self, level: int = 1) -> None:
await self.call_utility_async("sleep", level)
async def wake_up_async(self, tags: Optional[list[str]] = None) -> None:
async def wake_up_async(self, tags: list[str] | None = None) -> None:
await self.call_utility_async("wake_up", tags)
async def is_sleeping_async(self) -> bool:
@@ -984,16 +982,16 @@ class AsyncMPClient(MPClient):
return await self.call_utility_async("pin_lora", lora_id)
async def save_sharded_state_async(
self, path: str, pattern: Optional[str] = None, max_size: Optional[int] = None
self, path: str, pattern: str | None = None, max_size: int | None = None
) -> None:
await self.call_utility_async("save_sharded_state", path, pattern, max_size)
async def collective_rpc_async(
self,
method: Union[str, Callable[..., _R]],
timeout: Optional[float] = None,
method: str | Callable[..., _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
return await self.call_utility_async(
"collective_rpc", method, timeout, args, kwargs
@@ -1009,7 +1007,7 @@ class DPAsyncMPClient(AsyncMPClient):
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
):
@@ -1166,7 +1164,7 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
vllm_config: VllmConfig,
executor_class: type[Executor],
log_stats: bool,
client_addresses: Optional[dict[str, str]] = None,
client_addresses: dict[str, str] | None = None,
client_count: int = 1,
client_index: int = 0,
):
+5 -6
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from typing import Optional
import tokenizers
from packaging import version
@@ -36,7 +35,7 @@ class IncrementalDetokenizer:
def output_token_ids(self) -> list[int]:
return self.token_ids
def update(self, new_token_ids: list[int], stop_terminated: bool) -> Optional[str]:
def update(self, new_token_ids: list[int], stop_terminated: bool) -> str | None:
self.token_ids.extend(new_token_ids)
return None
@@ -46,7 +45,7 @@ class IncrementalDetokenizer:
@classmethod
def from_new_request(
cls,
tokenizer: Optional[AnyTokenizer],
tokenizer: AnyTokenizer | None,
request: EngineCoreRequest,
) -> "IncrementalDetokenizer":
assert request.sampling_params is not None
@@ -85,7 +84,7 @@ class BaseIncrementalDetokenizer(IncrementalDetokenizer, ABC):
# Generation data
self.output_text = ""
def update(self, new_token_ids: list[int], stop_terminated: bool) -> Optional[str]:
def update(self, new_token_ids: list[int], stop_terminated: bool) -> str | None:
"""
Update RequestState for the request_id by:
1) Detokenize the new token ids incrementally.
@@ -224,7 +223,7 @@ class FastIncrementalDetokenizer(BaseIncrementalDetokenizer):
return token or ""
def _protected_step(self, next_token_id: int) -> Optional[str]:
def _protected_step(self, next_token_id: int) -> str | None:
try:
token = self.stream.step(self.tokenizer, next_token_id)
except (OverflowError, TypeError):
@@ -312,7 +311,7 @@ def check_stop_strings(
new_char_count: int,
stop: list[str],
include_in_output: bool,
) -> Optional[tuple[str, int]]:
) -> tuple[str, int] | None:
"""Check if any stop strings are matched and truncate sequence
output text accordingly.
+21 -21
View File
@@ -2,9 +2,9 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import time
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from copy import copy
from typing import Any, Callable, Optional, Union
from typing import Any
import torch.nn as nn
from typing_extensions import TypeVar
@@ -52,7 +52,7 @@ class LLMEngine:
executor_class: type[Executor],
log_stats: bool,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
use_cached_outputs: bool = False,
multiprocess_mode: bool = False,
@@ -126,7 +126,7 @@ class LLMEngine:
log_stats=self.log_stats,
)
self.logger_manager: Optional[StatLoggerManager] = None
self.logger_manager: StatLoggerManager | None = None
if self.log_stats:
self.logger_manager = StatLoggerManager(
vllm_config=vllm_config,
@@ -152,7 +152,7 @@ class LLMEngine:
cls,
vllm_config: VllmConfig,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
disable_log_stats: bool = False,
) -> "LLMEngine":
return cls(
@@ -169,7 +169,7 @@ class LLMEngine:
cls,
engine_args: EngineArgs,
usage_context: UsageContext = UsageContext.ENGINE_CONTEXT,
stat_loggers: Optional[list[StatLoggerFactory]] = None,
stat_loggers: list[StatLoggerFactory] | None = None,
enable_multiprocessing: bool = False,
) -> "LLMEngine":
"""Creates an LLM engine from the engine arguments."""
@@ -225,14 +225,14 @@ class LLMEngine:
def add_request(
self,
request_id: str,
prompt: Union[EngineCoreRequest, PromptType],
params: Union[SamplingParams, PoolingParams],
arrival_time: Optional[float] = None,
lora_request: Optional[LoRARequest] = None,
tokenization_kwargs: Optional[dict[str, Any]] = None,
trace_headers: Optional[Mapping[str, str]] = None,
prompt: EngineCoreRequest | PromptType,
params: SamplingParams | PoolingParams,
arrival_time: float | None = None,
lora_request: LoRARequest | None = None,
tokenization_kwargs: dict[str, Any] | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
prompt_text: Optional[str] = None,
prompt_text: str | None = None,
) -> None:
# Validate the request_id type.
if not isinstance(request_id, str):
@@ -283,7 +283,7 @@ class LLMEngine:
# Add the request to EngineCore.
self.engine_core.add_request(child_request)
def step(self) -> Union[list[RequestOutput], list[PoolingRequestOutput]]:
def step(self) -> list[RequestOutput] | list[PoolingRequestOutput]:
if self.should_execute_dummy_batch:
self.should_execute_dummy_batch = False
self.engine_core.execute_dummy_batch()
@@ -326,13 +326,13 @@ class LLMEngine:
self.processor.clear_mm_cache()
self.engine_core.reset_mm_cache()
def reset_prefix_cache(self, device: Optional[Device] = None):
def reset_prefix_cache(self, device: Device | None = None):
self.engine_core.reset_prefix_cache()
def sleep(self, level: int = 1):
self.engine_core.sleep(level)
def wake_up(self, tags: Optional[list[str]] = None):
def wake_up(self, tags: list[str] | None = None):
self.engine_core.wake_up(tags)
def is_sleeping(self) -> bool:
@@ -343,11 +343,11 @@ class LLMEngine:
return get_metrics_snapshot()
@property
def tokenizer(self) -> Optional[AnyTokenizer]:
def tokenizer(self) -> AnyTokenizer | None:
return self.processor.tokenizer
@tokenizer.setter
def tokenizer(self, tokenizer: Optional[AnyTokenizer]) -> None:
def tokenizer(self, tokenizer: AnyTokenizer | None) -> None:
self.processor.tokenizer = tokenizer
def get_tokenizer(self) -> AnyTokenizer:
@@ -390,10 +390,10 @@ class LLMEngine:
def collective_rpc(
self,
method: Union[str, Callable[[WorkerBase], _R]],
timeout: Optional[float] = None,
method: str | Callable[[WorkerBase], _R],
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict[str, Any]] = None,
kwargs: dict[str, Any] | None = None,
) -> list[_R]:
return self.engine_core.collective_rpc(method, timeout, args, kwargs)
+9 -10
View File
@@ -4,7 +4,6 @@
import itertools
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Optional
from vllm.logger import init_logger
from vllm.logprobs import Logprob, PromptLogprobs, SampleLogprobs
@@ -24,19 +23,19 @@ NONES = itertools.repeat(None)
class LogprobsProcessor:
# Tokenizer for this request,
# None if detokenization is disabled.
tokenizer: Optional[AnyTokenizer]
tokenizer: AnyTokenizer | None
# Logprobs for this request
logprobs: Optional[SampleLogprobs]
prompt_logprobs: Optional[PromptLogprobs]
cumulative_logprob: Optional[float]
num_logprobs: Optional[int]
num_prompt_logprobs: Optional[int]
logprobs: SampleLogprobs | None
prompt_logprobs: PromptLogprobs | None
cumulative_logprob: float | None
num_logprobs: int | None
num_prompt_logprobs: int | None
@classmethod
def from_new_request(
cls,
tokenizer: Optional[AnyTokenizer],
tokenizer: AnyTokenizer | None,
request: EngineCoreRequest,
) -> "LogprobsProcessor":
assert request.sampling_params is not None
@@ -148,7 +147,7 @@ class LogprobsProcessor:
)
)
def pop_prompt_logprobs(self) -> Optional[PromptLogprobs]:
def pop_prompt_logprobs(self) -> PromptLogprobs | None:
"""Pop and return all request prompt logprobs
The logprobs processor aggregates prompt chunk logprobs
@@ -171,7 +170,7 @@ class LogprobsProcessor:
def _make_logprob_dict(
logprobs: list[float],
logprob_token_ids: list[int],
decoded_tokens: Iterable[Optional[str]],
decoded_tokens: Iterable[str | None],
rank: int,
num_logprobs: int,
) -> dict[int, Logprob]:
+43 -47
View File
@@ -4,7 +4,7 @@
import asyncio
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any, Optional, Union, cast
from typing import Any, cast
import torch
@@ -36,14 +36,10 @@ class RequestOutputCollector:
def __init__(self, output_kind: RequestOutputKind):
self.aggregate = output_kind == RequestOutputKind.DELTA
self.output: Optional[Union[RequestOutput, PoolingRequestOutput, Exception]] = (
None
)
self.output: RequestOutput | PoolingRequestOutput | Exception | None = None
self.ready = asyncio.Event()
def put(
self, output: Union[RequestOutput, PoolingRequestOutput, Exception]
) -> None:
def put(self, output: RequestOutput | PoolingRequestOutput | Exception) -> None:
"""Non-blocking put operation."""
if self.output is None or isinstance(output, Exception):
self.output = output
@@ -53,7 +49,7 @@ class RequestOutputCollector:
# (if n > 1) do not override each other.
self.output.add(output, aggregate=self.aggregate)
async def get(self) -> Union[RequestOutput, PoolingRequestOutput]:
async def get(self) -> RequestOutput | PoolingRequestOutput:
"""Get operation blocks on put event."""
while (output := self.output) is None:
await self.ready.wait()
@@ -63,7 +59,7 @@ class RequestOutputCollector:
raise output
return output
def get_nowait(self) -> Optional[Union[RequestOutput, PoolingRequestOutput]]:
def get_nowait(self) -> RequestOutput | PoolingRequestOutput | None:
"""Non-blocking get operation."""
output = self.output
if output is not None:
@@ -76,7 +72,7 @@ class RequestOutputCollector:
@dataclass
class OutputProcessorOutput:
request_outputs: list[Union[RequestOutput, PoolingRequestOutput]]
request_outputs: list[RequestOutput | PoolingRequestOutput]
reqs_to_abort: list[str]
@@ -84,22 +80,22 @@ class RequestState:
def __init__(
self,
request_id: str,
parent_req: Optional[ParentRequest],
parent_req: ParentRequest | None,
request_index: int,
lora_name: Optional[str],
lora_name: str | None,
output_kind: RequestOutputKind,
prompt: Optional[str],
prompt_token_ids: Optional[list[int]],
prompt_embeds: Optional[torch.Tensor],
logprobs_processor: Optional[LogprobsProcessor],
detokenizer: Optional[IncrementalDetokenizer],
max_tokens_param: Optional[int],
prompt: str | None,
prompt_token_ids: list[int] | None,
prompt_embeds: torch.Tensor | None,
logprobs_processor: LogprobsProcessor | None,
detokenizer: IncrementalDetokenizer | None,
max_tokens_param: int | None,
arrival_time: float,
queue: Optional[RequestOutputCollector],
queue: RequestOutputCollector | None,
log_stats: bool,
top_p: Optional[float] = None,
n: Optional[int] = None,
temperature: Optional[float] = None,
top_p: float | None = None,
n: int | None = None,
temperature: float | None = None,
):
self.request_id = request_id
self.parent_req = parent_req
@@ -129,10 +125,10 @@ class RequestState:
cls,
tokenizer: AnyTokenizer,
request: EngineCoreRequest,
prompt: Optional[str],
parent_req: Optional[ParentRequest],
prompt: str | None,
parent_req: ParentRequest | None,
request_index: int,
queue: Optional[RequestOutputCollector],
queue: RequestOutputCollector | None,
log_stats: bool,
) -> "RequestState":
if sampling_params := request.sampling_params:
@@ -186,11 +182,11 @@ class RequestState:
def make_request_output(
self,
new_token_ids: list[int],
pooling_output: Optional[torch.Tensor],
finish_reason: Optional[FinishReason],
stop_reason: Union[int, str, None],
kv_transfer_params: Optional[dict[str, Any]] = None,
) -> Optional[Union[RequestOutput, PoolingRequestOutput]]:
pooling_output: torch.Tensor | None,
finish_reason: FinishReason | None,
stop_reason: int | str | None,
kv_transfer_params: dict[str, Any] | None = None,
) -> RequestOutput | PoolingRequestOutput | None:
finished = finish_reason is not None
final_only = self.output_kind == RequestOutputKind.FINAL_ONLY
@@ -222,10 +218,10 @@ class RequestState:
def _new_request_output(
self,
request_id: str,
outputs: Union[list[CompletionOutput], list[PoolingOutput]],
outputs: list[CompletionOutput] | list[PoolingOutput],
finished: bool,
kv_transfer_params: Optional[dict[str, Any]] = None,
) -> Union[RequestOutput, PoolingRequestOutput]:
kv_transfer_params: dict[str, Any] | None = None,
) -> RequestOutput | PoolingRequestOutput:
first_output = outputs[0]
if isinstance(first_output, PoolingOutput):
assert len(outputs) == 1
@@ -264,8 +260,8 @@ class RequestState:
def _new_completion_output(
self,
token_ids: list[int],
finish_reason: Optional[FinishReason],
stop_reason: Union[int, str, None],
finish_reason: FinishReason | None,
stop_reason: int | str | None,
) -> CompletionOutput:
assert self.detokenizer is not None
assert self.logprobs_processor is not None
@@ -308,7 +304,7 @@ class OutputProcessor:
self.request_states: dict[str, RequestState] = {}
self.parent_requests: dict[str, ParentRequest] = {}
self.lora_states = LoRARequestStates()
self.tracer: Optional[Tracer] = None
self.tracer: Tracer | None = None
def get_num_unfinished_requests(self):
return len(self.request_states)
@@ -360,10 +356,10 @@ class OutputProcessor:
def add_request(
self,
request: EngineCoreRequest,
prompt: Optional[str],
parent_req: Optional[ParentRequest] = None,
prompt: str | None,
parent_req: ParentRequest | None = None,
request_index: int = 0,
queue: Optional[RequestOutputCollector] = None,
queue: RequestOutputCollector | None = None,
) -> None:
request_id = request.request_id
if request_id in self.request_states:
@@ -386,8 +382,8 @@ class OutputProcessor:
def process_outputs(
self,
engine_core_outputs: list[EngineCoreOutput],
engine_core_timestamp: Optional[float] = None,
iteration_stats: Optional[IterationStats] = None,
engine_core_timestamp: float | None = None,
iteration_stats: IterationStats | None = None,
) -> OutputProcessorOutput:
"""
Process the EngineCoreOutputs:
@@ -411,7 +407,7 @@ class OutputProcessor:
within the loop below.
"""
request_outputs: Union[list[RequestOutput], list[PoolingRequestOutput]] = []
request_outputs: list[RequestOutput] | list[PoolingRequestOutput] = []
reqs_to_abort: list[str] = []
for engine_core_output in engine_core_outputs:
req_id = engine_core_output.request_id
@@ -492,7 +488,7 @@ class OutputProcessor:
self,
engine_core_output: EngineCoreOutput,
req_state: RequestState,
iteration_stats: Optional[IterationStats],
iteration_stats: IterationStats | None,
) -> None:
assert req_state.stats is not None
assert iteration_stats is not None
@@ -555,8 +551,8 @@ class OutputProcessor:
self,
req_state: RequestState,
engine_core_output: EngineCoreOutput,
engine_core_timestamp: Optional[float],
iteration_stats: Optional[IterationStats],
engine_core_timestamp: float | None,
iteration_stats: IterationStats | None,
):
if iteration_stats is None:
return
@@ -577,8 +573,8 @@ class OutputProcessor:
def _update_stats_from_finished(
self,
req_state: RequestState,
finish_reason: Optional[FinishReason],
iteration_stats: Optional[IterationStats],
finish_reason: FinishReason | None,
iteration_stats: IterationStats | None,
):
if iteration_stats is None:
return
+1 -1
View File
@@ -29,7 +29,7 @@ class ParentRequest:
max_num_generation_tokens: int
# To efficiently obtain child sampling params
cached_child_sampling_params: Optional[SamplingParams]
cached_child_sampling_params: SamplingParams | None
def __init__(self, request_id: str, sampling_params: SamplingParams) -> None:
self.request_id = request_id
+17 -17
View File
@@ -3,7 +3,7 @@
import time
from collections.abc import Mapping
from typing import Any, Literal, Optional, Union
from typing import Any, Literal
from vllm.config import VllmConfig
from vllm.inputs import ProcessorInputs, PromptType, SingletonInputs
@@ -38,7 +38,7 @@ class Processor:
def __init__(
self,
vllm_config: VllmConfig,
tokenizer: Optional[AnyTokenizer],
tokenizer: AnyTokenizer | None,
mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
) -> None:
self.vllm_config = vllm_config
@@ -60,11 +60,11 @@ class Processor:
)
@property
def tokenizer(self) -> Optional[AnyTokenizer]:
def tokenizer(self) -> AnyTokenizer | None:
return self.input_preprocessor.tokenizer
@tokenizer.setter
def tokenizer(self, tokenizer: Optional[AnyTokenizer]) -> None:
def tokenizer(self, tokenizer: AnyTokenizer | None) -> None:
self.input_preprocessor.tokenizer = tokenizer
def _validate_logprobs(
@@ -152,7 +152,7 @@ class Processor:
def _validate_params(
self,
params: Union[SamplingParams, PoolingParams],
params: SamplingParams | PoolingParams,
):
"""
Validate supported SamplingParam.
@@ -174,7 +174,7 @@ class Processor:
auto-hashed downstream.
"""
def _validate_single_prompt(single_prompt: Union[dict, str]) -> None:
def _validate_single_prompt(single_prompt: dict | str) -> None:
if not isinstance(single_prompt, dict):
return
mm_data = single_prompt.get("multi_modal_data")
@@ -214,7 +214,7 @@ class Processor:
else:
_validate_single_prompt(prompt) # type: ignore[arg-type]
def _validate_lora(self, lora_request: Optional[LoRARequest]) -> None:
def _validate_lora(self, lora_request: LoRARequest | None) -> None:
if lora_request is None:
return
@@ -309,7 +309,7 @@ class Processor:
self,
request_id: str,
prompt: PromptType,
) -> Optional[MultiModalUUIDDict]:
) -> MultiModalUUIDDict | None:
"""Build per-item multimodal hash overrides when enabled. In this case,
multimodal data items are identified by their request id, modality and
index rather than their content.
@@ -342,13 +342,13 @@ class Processor:
self,
request_id: str,
prompt: PromptType,
params: Union[SamplingParams, PoolingParams],
arrival_time: Optional[float] = None,
lora_request: Optional[LoRARequest] = None,
tokenization_kwargs: Optional[dict[str, Any]] = None,
trace_headers: Optional[Mapping[str, str]] = None,
params: SamplingParams | PoolingParams,
arrival_time: float | None = None,
lora_request: LoRARequest | None = None,
tokenization_kwargs: dict[str, Any] | None = None,
trace_headers: Mapping[str, str] | None = None,
priority: int = 0,
data_parallel_rank: Optional[int] = None,
data_parallel_rank: int | None = None,
) -> EngineCoreRequest:
self._validate_lora(lora_request)
self._validate_params(params)
@@ -445,7 +445,7 @@ class Processor:
pooling_params = params.clone()
# Multimodal related.
mm_features: Optional[list[MultiModalFeatureSpec]] = None
mm_features: list[MultiModalFeatureSpec] | None = None
if decoder_inputs["type"] == "multimodal":
decoder_mm_inputs = decoder_inputs["mm_kwargs"]
@@ -485,7 +485,7 @@ class Processor:
)
def _validate_model_inputs(
self, encoder_inputs: Optional[SingletonInputs], decoder_inputs: SingletonInputs
self, encoder_inputs: SingletonInputs | None, decoder_inputs: SingletonInputs
):
if encoder_inputs is not None:
self._validate_model_input(encoder_inputs, prompt_type="encoder")
@@ -574,7 +574,7 @@ class Processor:
# check that chunked prefill does not truncate them
# max_batch_len = self.scheduler_config.max_num_batched_tokens
def stat_mm_cache(self) -> Optional[MultiModalCacheStats]:
def stat_mm_cache(self) -> MultiModalCacheStats | None:
return self.input_preprocessor.stat_mm_cache()
def clear_mm_cache(self) -> None:
+14 -14
View File
@@ -4,12 +4,12 @@
import contextlib
import os
import weakref
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from enum import Enum, auto
from multiprocessing import Process, connection
from multiprocessing.process import BaseProcess
from typing import TYPE_CHECKING, Callable, Optional, Union
from typing import TYPE_CHECKING
from unittest.mock import patch
import msgspec
@@ -56,13 +56,13 @@ class EngineZmqAddresses:
# ZMQ output socket addresses for each front-end client (responses)
outputs: list[str]
# ZMQ input socket address of DP coordinator if applicable
coordinator_input: Optional[str] = None
coordinator_input: str | None = None
# ZMQ output socket address of DP coordinator if applicable
coordinator_output: Optional[str] = None
coordinator_output: str | None = None
# ZMQ socket for front-end to connect to DP coordinator.
# Not used by engine, just relayed to front-end in handshake response.
# Only required for external DP LB case.
frontend_stats_publish_address: Optional[str] = None
frontend_stats_publish_address: str | None = None
@dataclass
@@ -73,8 +73,8 @@ class EngineHandshakeMetadata:
"""
addresses: EngineZmqAddresses
parallel_config: dict[str, Union[int, str, list[int]]]
parallel_config_hash: Optional[str] = None
parallel_config: dict[str, int | str | list[int]]
parallel_config_hash: str | None = None
class CoreEngineProcManager:
@@ -94,7 +94,7 @@ class CoreEngineProcManager:
handshake_address: str,
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: Optional[str] = None,
client_handshake_address: str | None = None,
):
context = get_mp_context()
common_kwargs = {
@@ -221,8 +221,8 @@ class CoreEngineActorManager:
addresses: EngineZmqAddresses,
executor_class: type[Executor],
log_stats: bool,
placement_groups: Optional[list["PlacementGroup"]] = None,
local_dp_ranks: Optional[list[int]] = None,
placement_groups: list["PlacementGroup"] | None = None,
local_dp_ranks: list[int] | None = None,
):
import copy
@@ -675,8 +675,8 @@ def launch_core_engines(
num_api_servers: int = 1,
) -> Iterator[
tuple[
Optional[Union[CoreEngineProcManager, CoreEngineActorManager]],
Optional[DPCoordinator],
CoreEngineProcManager | CoreEngineActorManager | None,
DPCoordinator | None,
EngineZmqAddresses,
]
]:
@@ -829,8 +829,8 @@ def wait_for_engine_startup(
core_engines: list[CoreEngine],
parallel_config: ParallelConfig,
cache_config: CacheConfig,
proc_manager: Optional[CoreEngineProcManager],
coord_process: Optional[Process],
proc_manager: CoreEngineProcManager | None,
coord_process: Process | None,
):
# Wait for engine core process(es) to send ready messages.
local_count = parallel_config.data_parallel_size_local
+7 -6
View File
@@ -1,8 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from concurrent.futures import Future
from typing import Any, Callable, Optional, Union
from typing import Any
import torch
import torch.distributed as dist
@@ -91,10 +92,10 @@ class Executor(ExecutorBase):
def collective_rpc(
self,
method: Union[str, Callable],
timeout: Optional[float] = None,
method: str | Callable,
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict] = None,
kwargs: dict | None = None,
non_block: bool = False,
) -> list[Any]:
raise NotImplementedError
@@ -103,7 +104,7 @@ class Executor(ExecutorBase):
self,
scheduler_output: SchedulerOutput,
non_block: bool = False,
) -> Union[ModelRunnerOutput, Future[ModelRunnerOutput]]:
) -> ModelRunnerOutput | Future[ModelRunnerOutput]:
output = self.collective_rpc(
"execute_model", args=(scheduler_output,), non_block=non_block
)
@@ -112,7 +113,7 @@ class Executor(ExecutorBase):
def execute_dummy_batch(self) -> None:
self.collective_rpc("execute_dummy_batch")
def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
def take_draft_token_ids(self) -> DraftTokenIds | None:
output = self.collective_rpc("take_draft_token_ids")
return output[0]
+16 -15
View File
@@ -9,6 +9,7 @@ import threading
import time
import traceback
import weakref
from collections.abc import Callable
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
from enum import Enum, auto
@@ -17,7 +18,7 @@ from multiprocessing.connection import Connection
from multiprocessing.process import BaseProcess
from multiprocessing.synchronize import Lock as LockType
from threading import Thread
from typing import Any, Callable, Optional, Union, cast
from typing import Any, cast
import cloudpickle
import torch
@@ -59,8 +60,8 @@ class MultiprocExecutor(Executor):
self._finalizer = weakref.finalize(self, self.shutdown)
self.is_failed = False
self.shutdown_event = threading.Event()
self.failure_callback: Optional[FailureCallback] = None
self.io_thread_pool: Optional[ThreadPoolExecutor] = None
self.failure_callback: FailureCallback | None = None
self.io_thread_pool: ThreadPoolExecutor | None = None
self.world_size = self.parallel_config.world_size
tensor_parallel_size = self.parallel_config.tensor_parallel_size
@@ -179,7 +180,7 @@ class MultiprocExecutor(Executor):
self,
scheduler_output: SchedulerOutput,
non_block: bool = False,
) -> Union[ModelRunnerOutput, Future[ModelRunnerOutput]]:
) -> ModelRunnerOutput | Future[ModelRunnerOutput]:
if not self.has_connector:
# get output only from a single worker (output_rank)
(output,) = self.collective_rpc(
@@ -207,7 +208,7 @@ class MultiprocExecutor(Executor):
def execute_dummy_batch(self) -> None:
self.collective_rpc("execute_dummy_batch", unique_reply_rank=self.output_rank)
def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
def take_draft_token_ids(self) -> DraftTokenIds | None:
# OPTIMIZATION: Get output only from a single worker (output_rank)
outputs = self.collective_rpc(
"take_draft_token_ids", unique_reply_rank=self.output_rank
@@ -216,12 +217,12 @@ class MultiprocExecutor(Executor):
def collective_rpc(
self,
method: Union[str, Callable],
timeout: Optional[float] = None,
method: str | Callable,
timeout: float | None = None,
args: tuple = (),
kwargs: Optional[dict] = None,
kwargs: dict | None = None,
non_block: bool = False,
unique_reply_rank: Optional[int] = None,
unique_reply_rank: int | None = None,
) -> list[Any]:
if self.is_failed:
raise RuntimeError("Executor failed.")
@@ -252,8 +253,8 @@ class MultiprocExecutor(Executor):
def get_response(
w: WorkerProcHandle,
dequeue_timeout: Optional[float] = None,
cancel_event: Optional[threading.Event] = None,
dequeue_timeout: float | None = None,
cancel_event: threading.Event | None = None,
):
status, result = w.worker_response_mq.dequeue(
timeout=dequeue_timeout, cancel=cancel_event
@@ -370,7 +371,7 @@ class UnreadyWorkerProcHandle:
proc: BaseProcess
rank: int
ready_pipe: Connection
death_writer: Optional[Connection] = None
death_writer: Connection | None = None
@dataclass
@@ -378,7 +379,7 @@ class WorkerProcHandle:
proc: BaseProcess
rank: int
worker_response_mq: MessageQueue # The worker process writes to this MQ
death_writer: Optional[Connection] = None
death_writer: Connection | None = None
@classmethod
def from_unready_handle(
@@ -505,7 +506,7 @@ class WorkerProc:
)
pipes = {handle.ready_pipe: handle for handle in unready_proc_handles}
ready_proc_handles: list[Optional[WorkerProcHandle]] = [None] * len(
ready_proc_handles: list[WorkerProcHandle | None] = [None] * len(
unready_proc_handles
)
while pipes:
@@ -674,7 +675,7 @@ class WorkerProc:
output = self.async_output_queue.get()
self.enqueue_output(output)
def worker_busy_loop(self, cancel: Optional[threading.Event] = None):
def worker_busy_loop(self, cancel: threading.Event | None = None):
"""Main busy loop for Multiprocessing Workers"""
while True:
method, args, kwargs, output_rank = self.rpc_broadcast_mq.dequeue(
+2 -3
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from concurrent.futures import Future
from typing import Optional, Union
from vllm.distributed.kv_transfer.kv_connector.utils import KVOutputAggregator
from vllm.executor.ray_distributed_executor import ( # noqa
@@ -26,7 +25,7 @@ class FutureWrapper(Future):
the result() call. If not only the first worker's output is returned.
"""
def __init__(self, refs, aggregator: Optional[KVOutputAggregator] = None):
def __init__(self, refs, aggregator: KVOutputAggregator | None = None):
super().__init__()
self.refs = refs
self.aggregator = aggregator
@@ -66,7 +65,7 @@ class RayDistributedExecutor(RayDistributedExecutorV0, Executor):
self,
scheduler_output: SchedulerOutput,
non_block: bool = False,
) -> Union[ModelRunnerOutput, Future[ModelRunnerOutput]]:
) -> ModelRunnerOutput | Future[ModelRunnerOutput]:
"""Execute the model on the Ray workers.
Args:
+6 -7
View File
@@ -4,7 +4,6 @@
import copy
from dataclasses import dataclass, fields
from math import prod
from typing import Optional
import torch
from typing_extensions import Self
@@ -74,8 +73,8 @@ class AttentionSpec(KVCacheSpec):
@dataclass(frozen=True)
class FullAttentionSpec(AttentionSpec):
sliding_window: Optional[int] = None
attention_chunk_size: Optional[int] = None
sliding_window: int | None = None
attention_chunk_size: int | None = None
"""
When hybrid allocator is disabled and the model contains both full
attention layers and sliding window attention layers, sliding
@@ -96,7 +95,7 @@ class FullAttentionSpec(AttentionSpec):
return cdiv(max_model_len, self.block_size) * self.page_size_bytes
@classmethod
def merge_window_sizes(cls, window_sizes: set[int]) -> Optional[int]:
def merge_window_sizes(cls, window_sizes: set[int]) -> int | None:
if len(window_sizes) == 0:
return None
elif len(window_sizes) == 1:
@@ -154,7 +153,7 @@ class FullAttentionSpec(AttentionSpec):
@dataclass(frozen=True)
class MLAAttentionSpec(FullAttentionSpec):
# TODO(Lucas/Chen): less hacky way to do this
cache_dtype_str: Optional[str] = None
cache_dtype_str: str | None = None
@property
def page_size_bytes(self) -> int:
@@ -237,7 +236,7 @@ class SlidingWindowSpec(AttentionSpec):
class MambaSpec(KVCacheSpec):
shapes: tuple[tuple[int, ...], ...]
dtypes: tuple[torch.dtype]
page_size_padded: Optional[int] = None
page_size_padded: int | None = None
mamba_type: str = "mamba2"
num_speculative_blocks: int = 0
@@ -342,7 +341,7 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
)
@classmethod
def from_specs(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> Optional[Self]:
def from_specs(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> Self | None:
"""
Return a SameTypeKVCacheSpecs object if all layers have the same type
of KV cache spec. Return None if not.
+1 -2
View File
@@ -30,7 +30,6 @@ The class provides the following primitives:
from abc import ABC, abstractmethod
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Optional
from vllm.v1.core.kv_cache_utils import BlockHash
@@ -122,7 +121,7 @@ class OffloadingManager(ABC):
@abstractmethod
def prepare_store(
self, block_hashes: Iterable[BlockHash]
) -> Optional[PrepareStoreOutput]:
) -> PrepareStoreOutput | None:
"""
Prepare the given blocks to be offloaded.
The given blocks will be protected from eviction until
+2 -3
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterator
from typing import Optional
import torch
@@ -29,10 +28,10 @@ class CPUOffloadingSpec(OffloadingSpec):
self.num_cpu_blocks: int = num_cpu_blocks
# scheduler-side
self._manager: Optional[OffloadingManager] = None
self._manager: OffloadingManager | None = None
# worker-side
self._handler: Optional[OffloadingHandler] = None
self._handler: OffloadingHandler | None = None
def get_manager(self) -> OffloadingManager:
if not self._manager:
+2 -1
View File
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import importlib
from typing import TYPE_CHECKING, Callable
from collections.abc import Callable
from typing import TYPE_CHECKING
from vllm.logger import init_logger
from vllm.v1.kv_offload.spec import OffloadingSpec
+2 -3
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import OrderedDict
from collections.abc import Iterable
from typing import Optional
from vllm.v1.core.kv_cache_utils import BlockHash
from vllm.v1.kv_offload.abstract import (
@@ -23,7 +22,7 @@ class LRUOffloadingManager(OffloadingManager):
self.backend: Backend = backend
# block_hash -> BlockStatus
self.blocks: OrderedDict[BlockHash, BlockStatus] = OrderedDict()
self.events: Optional[list[OffloadingEvent]] = [] if enable_events else None
self.events: list[OffloadingEvent] | None = [] if enable_events else None
def lookup(self, block_hashes: Iterable[BlockHash]) -> int:
hit_count = 0
@@ -57,7 +56,7 @@ class LRUOffloadingManager(OffloadingManager):
def prepare_store(
self, block_hashes: Iterable[BlockHash]
) -> Optional[PrepareStoreOutput]:
) -> PrepareStoreOutput | None:
# filter out blocks that are already stored
block_hashes_to_store = [
block_hash for block_hash in block_hashes if block_hash not in self.blocks
+25 -30
View File
@@ -4,9 +4,10 @@
import logging
import time
from abc import ABC, abstractmethod
from typing import Callable, Optional, Union
from collections.abc import Callable
from typing import TypeAlias
import prometheus_client
from prometheus_client import Counter, Gauge, Histogram
from vllm.config import SupportsMetricsInfo, VllmConfig
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorLogging
@@ -40,9 +41,9 @@ class StatLoggerBase(ABC):
@abstractmethod
def record(
self,
scheduler_stats: Optional[SchedulerStats],
iteration_stats: Optional[IterationStats],
mm_cache_stats: Optional[MultiModalCacheStats] = None,
scheduler_stats: SchedulerStats | None,
iteration_stats: IterationStats | None,
mm_cache_stats: MultiModalCacheStats | None = None,
engine_idx: int = 0,
): ...
@@ -93,9 +94,9 @@ class LoggingStatLogger(StatLoggerBase):
def record(
self,
scheduler_stats: Optional[SchedulerStats],
iteration_stats: Optional[IterationStats],
mm_cache_stats: Optional[MultiModalCacheStats] = None,
scheduler_stats: SchedulerStats | None,
iteration_stats: IterationStats | None,
mm_cache_stats: MultiModalCacheStats | None = None,
engine_idx: int = 0,
):
"""Log Stats to standard output."""
@@ -178,13 +179,13 @@ class LoggingStatLogger(StatLoggerBase):
class PrometheusStatLogger(StatLoggerBase):
_gauge_cls = prometheus_client.Gauge
_counter_cls = prometheus_client.Counter
_histogram_cls = prometheus_client.Histogram
_gauge_cls = Gauge
_counter_cls = Counter
_histogram_cls = Histogram
_spec_decoding_cls = SpecDecodingProm
def __init__(
self, vllm_config: VllmConfig, engine_indexes: Optional[list[int]] = None
self, vllm_config: VllmConfig, engine_indexes: list[int] | None = None
):
if engine_indexes is None:
engine_indexes = [0]
@@ -368,9 +369,7 @@ class PrometheusStatLogger(StatLoggerBase):
counter_generation_tokens, engine_indexes, model_name
)
self.counter_request_success: dict[
FinishReason, dict[int, prometheus_client.Counter]
] = {}
self.counter_request_success: dict[FinishReason, dict[int, Counter]] = {}
counter_request_success_base = self._counter_cls(
name="vllm:request_success",
documentation="Count of successfully processed requests.",
@@ -660,7 +659,7 @@ class PrometheusStatLogger(StatLoggerBase):
# TODO: This metric might be incorrect in case of using multiple
# api_server counts which uses prometheus mp.
self.gauge_lora_info: Optional[prometheus_client.Gauge] = None
self.gauge_lora_info: Gauge | None = None
if vllm_config.lora_config is not None:
if len(self.engine_indexes) > 1:
raise NotImplementedError("LoRA in DP mode is not supported yet.")
@@ -705,9 +704,9 @@ class PrometheusStatLogger(StatLoggerBase):
def record(
self,
scheduler_stats: Optional[SchedulerStats],
iteration_stats: Optional[IterationStats],
mm_cache_stats: Optional[MultiModalCacheStats] = None,
scheduler_stats: SchedulerStats | None,
iteration_stats: IterationStats | None,
mm_cache_stats: MultiModalCacheStats | None = None,
engine_idx: int = 0,
):
"""Log to prometheus."""
@@ -826,11 +825,7 @@ class PrometheusStatLogger(StatLoggerBase):
self.log_metrics_info("cache_config", self.vllm_config.cache_config)
PromMetric = Union[
prometheus_client.Gauge,
prometheus_client.Counter,
prometheus_client.Histogram,
]
PromMetric: TypeAlias = Gauge | Counter | Histogram
def make_per_engine(
@@ -882,8 +877,8 @@ class StatLoggerManager:
def __init__(
self,
vllm_config: VllmConfig,
engine_idxs: Optional[list[int]] = None,
custom_stat_loggers: Optional[list[StatLoggerFactory]] = None,
engine_idxs: list[int] | None = None,
custom_stat_loggers: list[StatLoggerFactory] | None = None,
enable_default_loggers: bool = True,
client_count: int = 1,
):
@@ -924,10 +919,10 @@ class StatLoggerManager:
def record(
self,
scheduler_stats: Optional[SchedulerStats],
iteration_stats: Optional[IterationStats],
mm_cache_stats: Optional[MultiModalCacheStats] = None,
engine_idx: Optional[int] = None,
scheduler_stats: SchedulerStats | None,
iteration_stats: IterationStats | None,
mm_cache_stats: MultiModalCacheStats | None = None,
engine_idx: int | None = None,
):
if engine_idx is None:
engine_idx = 0
+1 -2
View File
@@ -3,7 +3,6 @@
import os
import tempfile
from typing import Optional
from prometheus_client import REGISTRY, CollectorRegistry, multiprocess
@@ -12,7 +11,7 @@ from vllm.logger import init_logger
logger = init_logger(__name__)
# Global temporary directory for prometheus multiprocessing
_prometheus_multiproc_dir: Optional[tempfile.TemporaryDirectory] = None
_prometheus_multiproc_dir: tempfile.TemporaryDirectory | None = None
def setup_multiprocess_prometheus():
+11 -12
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import time
from typing import Optional, Union
from vllm.v1.metrics.loggers import PrometheusStatLogger
from vllm.v1.spec_decode.metrics import SpecDecodingProm
@@ -63,9 +62,9 @@ class RayGaugeWrapper(RayPrometheusMetric):
def __init__(
self,
name: str,
documentation: Optional[str] = "",
labelnames: Optional[list[str]] = None,
multiprocess_mode: Optional[str] = "",
documentation: str | None = "",
labelnames: list[str] | None = None,
multiprocess_mode: str | None = "",
):
# All Ray metrics are keyed by WorkerId, so multiprocess modes like
# "mostrecent", "all", "sum" do not apply. This logic can be manually
@@ -77,7 +76,7 @@ class RayGaugeWrapper(RayPrometheusMetric):
name=name, description=documentation, tag_keys=labelnames_tuple
)
def set(self, value: Union[int, float]):
def set(self, value: int | float):
return self.metric.set(value)
def set_to_current_time(self):
@@ -92,8 +91,8 @@ class RayCounterWrapper(RayPrometheusMetric):
def __init__(
self,
name: str,
documentation: Optional[str] = "",
labelnames: Optional[list[str]] = None,
documentation: str | None = "",
labelnames: list[str] | None = None,
):
labelnames_tuple = tuple(labelnames) if labelnames else None
name = self._get_sanitized_opentelemetry_name(name)
@@ -101,7 +100,7 @@ class RayCounterWrapper(RayPrometheusMetric):
name=name, description=documentation, tag_keys=labelnames_tuple
)
def inc(self, value: Union[int, float] = 1.0):
def inc(self, value: int | float = 1.0):
if value == 0:
return
return self.metric.inc(value)
@@ -114,9 +113,9 @@ class RayHistogramWrapper(RayPrometheusMetric):
def __init__(
self,
name: str,
documentation: Optional[str] = "",
labelnames: Optional[list[str]] = None,
buckets: Optional[list[float]] = None,
documentation: str | None = "",
labelnames: list[str] | None = None,
buckets: list[float] | None = None,
):
labelnames_tuple = tuple(labelnames) if labelnames else None
name = self._get_sanitized_opentelemetry_name(name)
@@ -128,7 +127,7 @@ class RayHistogramWrapper(RayPrometheusMetric):
boundaries=boundaries,
)
def observe(self, value: Union[int, float]):
def observe(self, value: int | float):
return self.metric.observe(value)
+1 -2
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
from prometheus_client import REGISTRY
from prometheus_client import Metric as PromMetric
@@ -144,7 +143,7 @@ def get_metrics_snapshot() -> list[Metric]:
return collected
def _get_samples(metric: PromMetric, suffix: Optional[str] = None) -> list[Sample]:
def _get_samples(metric: PromMetric, suffix: str | None = None) -> list[Sample]:
name = (metric.name + suffix) if suffix is not None else metric.name
return [s for s in metric.samples if s.name == name]
+11 -11
View File
@@ -4,7 +4,7 @@
import time
from collections import deque
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any
from vllm.v1.spec_decode.metrics import SpecDecodingStats
@@ -152,8 +152,8 @@ class SchedulerStats:
prefix_cache_stats: PrefixCacheStats = field(default_factory=PrefixCacheStats)
spec_decoding_stats: Optional[SpecDecodingStats] = None
kv_connector_stats: Optional[dict[str, Any]] = None
spec_decoding_stats: SpecDecodingStats | None = None
kv_connector_stats: dict[str, Any] | None = None
num_corrupted_reqs: int = 0
@@ -191,7 +191,7 @@ class FinishedRequestStats:
e2e_latency: float = 0.0
num_prompt_tokens: int = 0
num_generation_tokens: int = 0
max_tokens_param: Optional[int] = None
max_tokens_param: int | None = None
queued_time: float = 0.0
prefill_time: float = 0.0
inference_time: float = 0.0
@@ -230,7 +230,7 @@ class IterationStats:
is_prefilling: bool,
prompt_len: int,
req_stats: RequestStateStats,
lora_stats: Optional[LoRAStats],
lora_stats: LoRAStats | None,
):
num_new_generation_tokens = len(output.new_token_ids)
@@ -265,7 +265,7 @@ class IterationStats:
events: list["EngineCoreEvent"],
is_prefilling: bool,
req_stats: RequestStateStats,
lora_stats: Optional[LoRAStats],
lora_stats: LoRAStats | None,
):
# Avoid circular dependency
from vllm.v1.engine import EngineCoreEventType
@@ -287,7 +287,7 @@ class IterationStats:
self,
finish_reason: "FinishReason",
num_prompt_tokens: int,
max_tokens_param: Optional[int],
max_tokens_param: int | None,
req_stats: RequestStateStats,
):
e2e_latency = self._time_since(req_stats.arrival_time)
@@ -335,7 +335,7 @@ class LoRARequestStates:
def __init__(self):
self.lora_name_to_stats: dict[str, LoRAStats] = {}
def get_stats(self, req_state: "RequestState") -> Optional[LoRAStats]:
def get_stats(self, req_state: "RequestState") -> LoRAStats | None:
if req_state.lora_name is None:
return None
if req_state.lora_name not in self.lora_name_to_stats:
@@ -362,20 +362,20 @@ class LoRARequestStates:
# Break the pattern for this lifecycle methods so we can
# call this from IterationStats.update_from_events()
@staticmethod
def scheduled_request(lora_stats: Optional[LoRAStats], request_id: str):
def scheduled_request(lora_stats: LoRAStats | None, request_id: str):
if lora_stats is None:
return
lora_stats.waiting_requests.remove(request_id)
lora_stats.running_requests.add(request_id)
@staticmethod
def preempted_request(lora_stats: Optional[LoRAStats], request_id: str):
def preempted_request(lora_stats: LoRAStats | None, request_id: str):
if lora_stats is None:
return
lora_stats.running_requests.remove(request_id)
lora_stats.waiting_requests.add(request_id)
def update_iteration_stats(self, iteration_stats: Optional[IterationStats]):
def update_iteration_stats(self, iteration_stats: IterationStats | None):
if iteration_stats is None:
return
for lora_name, stats in self.lora_name_to_stats.items():
+13 -11
View File
@@ -3,12 +3,14 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, NamedTuple, Optional, Union
from typing import TYPE_CHECKING, NamedTuple
import torch
if TYPE_CHECKING:
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats
else:
KVConnectorStats = object
class LogprobsLists(NamedTuple):
@@ -64,7 +66,7 @@ class LogprobsTensors(NamedTuple):
# [num_reqs, <dynamic>]
# The shape of each element depends on the pooler used
PoolerOutput = Union[torch.Tensor, list[torch.Tensor]]
PoolerOutput = torch.Tensor | list[torch.Tensor]
@dataclass
@@ -74,15 +76,15 @@ class SamplerOutput:
# All requests are padded to max_num_generated_tokens.
# PLACEHOLDER_TOKEN_ID (-1 by default) is used for padding.
sampled_token_ids: torch.Tensor
logprobs_tensors: Optional[LogprobsTensors]
logprobs_tensors: LogprobsTensors | None
@dataclass
class KVConnectorOutput:
# [req_ids]
finished_sending: Optional[set[str]] = None
finished_recving: Optional[set[str]] = None
kv_connector_stats: Optional["KVConnectorStats"] = None
finished_sending: set[str] | None = None
finished_recving: set[str] | None = None
kv_connector_stats: KVConnectorStats | None = None
# IDs of externally computed KV blocks that failed to load.
# Requests referencing these blocks should be rescheduled to recompute them.
invalid_block_ids: set[int] = field(default_factory=set)
@@ -114,21 +116,21 @@ class ModelRunnerOutput:
# [num_reqs, max_num_logprobs + 1]
# [num_reqs, max_num_logprobs + 1]
# [num_reqs]
logprobs: Optional[LogprobsLists]
logprobs: LogprobsLists | None
# req_id -> (token_ids, logprobs, ranks)
# [prompt_len, num_prompt_logprobs]
# [prompt_len, num_prompt_logprobs]
# [prompt_len]
prompt_logprobs_dict: dict[str, Optional[LogprobsTensors]]
prompt_logprobs_dict: dict[str, LogprobsTensors | None]
# [num_reqs, hidden_size]
pooler_output: list[Optional[torch.Tensor]]
pooler_output: list[torch.Tensor | None]
kv_connector_output: Optional[KVConnectorOutput] = None
kv_connector_output: KVConnectorOutput | None = None
# req_id -> num_nans_in_logits
num_nans_in_logits: Optional[dict[str, int]] = None
num_nans_in_logits: dict[str, int] | None = None
# ModelRunnerOutput wrapper for async scheduling.
+2 -3
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
import torch
@@ -37,9 +36,9 @@ class PoolingMetadata:
"""Tensors for pooling."""
prompt_lens: torch.Tensor # CPU Tensor
prompt_token_ids: Optional[torch.Tensor]
prompt_token_ids: torch.Tensor | None
pooling_params: list[PoolingParams]
pooling_cursor: Optional[PoolingCursor] = None
pooling_cursor: PoolingCursor | None = None
def __getitem__(self, indices: slice):
return PoolingMetadata(
+22 -22
View File
@@ -3,9 +3,9 @@
import enum
import time
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from functools import partial
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from typing import TYPE_CHECKING, Any, Optional
import torch
@@ -31,20 +31,20 @@ class Request:
def __init__(
self,
request_id: str,
prompt_token_ids: Optional[list[int]],
sampling_params: Optional[SamplingParams],
pooling_params: Optional[PoolingParams],
eos_token_id: Optional[int],
prompt_token_ids: list[int] | None,
sampling_params: SamplingParams | None,
pooling_params: PoolingParams | None,
eos_token_id: int | None,
client_index: int = 0,
arrival_time: Optional[float] = None,
prompt_embeds: Optional[torch.Tensor] = None,
mm_features: Optional[list[MultiModalFeatureSpec]] = None,
arrival_time: float | None = None,
prompt_embeds: torch.Tensor | None = None,
mm_features: list[MultiModalFeatureSpec] | None = None,
lora_request: Optional["LoRARequest"] = None,
structured_output_request: Optional["StructuredOutputRequest"] = None,
cache_salt: Optional[str] = None,
cache_salt: str | None = None,
priority: int = 0,
trace_headers: Optional[Mapping[str, str]] = None,
block_hasher: Optional[Callable[["Request"], list["BlockHash"]]] = None,
trace_headers: Mapping[str, str] | None = None,
block_hasher: Callable[["Request"], list["BlockHash"]] | None = None,
) -> None:
self.request_id = request_id
self.client_index = client_index
@@ -60,10 +60,10 @@ class Request:
self.status = RequestStatus.WAITING
self.use_structured_output = False
self.events: list[EngineCoreEvent] = []
self.stop_reason: Union[int, str, None] = None
self.stop_reason: int | str | None = None
# P/D: Connector-specific KV transfer parameters.
self.kv_transfer_params: Optional[dict[str, Any]] = None
self.kv_transfer_params: dict[str, Any] | None = None
if pooling_params is not None:
# Pooling models.
@@ -97,7 +97,7 @@ class Request:
self.num_output_placeholders = 0 # Used in async scheduling.
self.spec_token_ids: list[int] = []
self.num_computed_tokens = 0
self.cache_salt: Optional[str] = cache_salt
self.cache_salt: str | None = cache_salt
# Multi-modal related
self.mm_features = mm_features or []
@@ -123,7 +123,7 @@ class Request:
self.num_preemptions = 0
self.block_hashes: list[BlockHash] = []
self.get_hash_new_full_blocks: Optional[Callable[[], list[BlockHash]]] = None
self.get_hash_new_full_blocks: Callable[[], list[BlockHash]] | None = None
if block_hasher is not None:
self.get_hash_new_full_blocks = partial(block_hasher, self)
self.block_hashes = self.get_hash_new_full_blocks()
@@ -132,7 +132,7 @@ class Request:
def from_engine_core_request(
cls,
request: EngineCoreRequest,
block_hasher: Optional[Callable[["Request"], list["BlockHash"]]],
block_hasher: Callable[["Request"], list["BlockHash"]] | None,
) -> "Request":
return cls(
request_id=request.request_id,
@@ -158,7 +158,7 @@ class Request:
def append_output_token_ids(
self,
token_ids: Union[int, list[int]],
token_ids: int | list[int],
) -> None:
if isinstance(token_ids, int):
self._output_token_ids.append(token_ids)
@@ -189,7 +189,7 @@ class Request:
def is_finished(self) -> bool:
return RequestStatus.is_finished(self.status)
def get_finished_reason(self) -> Union[FinishReason, None]:
def get_finished_reason(self) -> FinishReason | None:
return RequestStatus.get_finished_reason(self.status)
def get_num_encoder_tokens(self, input_id: int) -> int:
@@ -200,11 +200,11 @@ class Request:
def record_event(
self,
event_type: EngineCoreEventType,
timestamp: Optional[float] = None,
timestamp: float | None = None,
) -> None:
self.events.append(EngineCoreEvent.new_event(event_type, timestamp))
def take_events(self) -> Optional[list[EngineCoreEvent]]:
def take_events(self) -> list[EngineCoreEvent] | None:
if not self.events:
return None
events, self.events = self.events, []
@@ -234,7 +234,7 @@ class RequestStatus(enum.IntEnum):
return status > RequestStatus.PREEMPTED
@staticmethod
def get_finished_reason(status: "RequestStatus") -> Union[FinishReason, None]:
def get_finished_reason(status: "RequestStatus") -> FinishReason | None:
return _FINISHED_REASON_MAP.get(status)
+8 -8
View File
@@ -6,7 +6,7 @@ import itertools
from abc import abstractmethod
from collections.abc import Sequence
from functools import partial
from typing import TYPE_CHECKING, Optional, Union
from typing import TYPE_CHECKING
import torch
@@ -81,7 +81,7 @@ def _load_logitsprocs_plugins() -> list[type[LogitsProcessor]]:
def _load_logitsprocs_by_fqcns(
logits_processors: Optional[Sequence[Union[str, type[LogitsProcessor]]]],
logits_processors: Sequence[str | type[LogitsProcessor]] | None,
) -> list[type[LogitsProcessor]]:
"""Load logit processor types, identifying them by fully-qualified class
names (FQCNs).
@@ -146,7 +146,7 @@ def _load_logitsprocs_by_fqcns(
def _load_custom_logitsprocs(
logits_processors: Optional[Sequence[Union[str, type[LogitsProcessor]]]],
logits_processors: Sequence[str | type[LogitsProcessor]] | None,
) -> list[type[LogitsProcessor]]:
"""Load all custom logits processors.
@@ -176,7 +176,7 @@ def build_logitsprocs(
device: torch.device,
is_pin_memory: bool,
is_pooling_model: bool,
custom_logitsprocs: Sequence[Union[str, type[LogitsProcessor]]] = (),
custom_logitsprocs: Sequence[str | type[LogitsProcessor]] = (),
) -> LogitsProcessors:
if is_pooling_model:
if custom_logitsprocs:
@@ -249,7 +249,7 @@ class AdapterLogitsProcessor(LogitsProcessor):
def new_req_logits_processor(
self,
params: SamplingParams,
) -> Optional[RequestLogitsProcessor]:
) -> RequestLogitsProcessor | None:
"""Consume request info; return a per-request logits processor.
Return None if logits processor does not need to be applied to request
@@ -267,9 +267,9 @@ class AdapterLogitsProcessor(LogitsProcessor):
def _new_state(
self,
params: SamplingParams,
prompt_ids: Optional[list[int]],
prompt_ids: list[int] | None,
output_ids: list[int],
) -> Optional[partial[torch.Tensor]]:
) -> partial[torch.Tensor] | None:
"""Return state representation for new request
Returns None if logits processor is not applicable to request
@@ -292,7 +292,7 @@ class AdapterLogitsProcessor(LogitsProcessor):
return partial(req_lp, *args)
return None
def update_state(self, batch_update: Optional[BatchUpdate]):
def update_state(self, batch_update: BatchUpdate | None):
process_dict_updates(
self.req_info,
batch_update,
+9 -9
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from typing import TYPE_CHECKING, Callable, Optional, TypeVar
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, TypeVar
import torch
@@ -49,7 +49,7 @@ class MinPLogitsProcessor(LogitsProcessor):
def get_min_p_by_index(self, index: int) -> float:
return float(self.min_p_cpu[index])
def update_state(self, batch_update: Optional[BatchUpdate]):
def update_state(self, batch_update: BatchUpdate | None):
if not batch_update:
return
@@ -131,7 +131,7 @@ class LogitBiasLogitsProcessor(LogitsProcessor):
outcome of argmax in greedy sampling."""
return False
def update_state(self, batch_update: Optional[BatchUpdate]):
def update_state(self, batch_update: BatchUpdate | None):
needs_update = process_dict_updates(
self.biases, batch_update, lambda params, _, __: params.logit_bias or None
)
@@ -185,14 +185,14 @@ class MinTokensLogitsProcessor(LogitsProcessor):
@staticmethod
def add_request(
params: SamplingParams, _: Optional[list[int]], output_tok_ids: list[int]
) -> Optional[tuple[int, Sequence[int], set[int]]]:
params: SamplingParams, _: list[int] | None, output_tok_ids: list[int]
) -> tuple[int, Sequence[int], set[int]] | None:
min_tokens = params.min_tokens
if not min_tokens or len(output_tok_ids) >= min_tokens:
return None
return min_tokens, output_tok_ids, params.all_stop_token_ids
def update_state(self, batch_update: Optional[BatchUpdate]):
def update_state(self, batch_update: BatchUpdate | None):
needs_update = process_dict_updates(
self.min_toks, batch_update, self.add_request
)
@@ -235,8 +235,8 @@ class MinTokensLogitsProcessor(LogitsProcessor):
def process_dict_updates(
req_entries: dict[int, T],
batch_update: Optional[BatchUpdate],
new_state: Callable[[SamplingParams, Optional[list[int]], list[int]], Optional[T]],
batch_update: BatchUpdate | None,
new_state: Callable[[SamplingParams, list[int] | None, list[int]], T | None],
) -> bool:
"""Utility function to update dict state for sparse LogitsProcessors."""
+1 -1
View File
@@ -26,7 +26,7 @@ RemovedRequest = int
# (index, params, prompt_tok_ids, output_tok_ids) tuples for new
# requests added to the batch.
AddedRequest = tuple[int, SamplingParams, Optional[list[int]], list[int]]
AddedRequest = tuple[int, SamplingParams, list[int] | None, list[int]]
# (index 1, index 2, directionality) tuples representing
# one-way moves or two-way swaps of requests in batch
+8 -10
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterator
from itertools import chain
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING
from vllm.v1.sample.logits_processor.interface import (
AddedRequest,
@@ -43,9 +43,9 @@ class BatchUpdateBuilder:
def __init__(
self,
removed: Optional[list[RemovedRequest]] = None,
added: Optional[list[AddedRequest]] = None,
moved: Optional[list[MovedRequest]] = None,
removed: list[RemovedRequest] | None = None,
added: list[AddedRequest] | None = None,
moved: list[MovedRequest] | None = None,
) -> None:
self._removed = removed or []
self.added = added or []
@@ -92,14 +92,14 @@ class BatchUpdateBuilder:
def has_removed(self) -> bool:
return bool(self._removed)
def peek_removed(self) -> Optional[int]:
def peek_removed(self) -> int | None:
"""Return lowest removed request index"""
if self.has_removed():
self._ensure_removed_sorted()
return self._removed[-1]
return None
def pop_removed(self) -> Optional[int]:
def pop_removed(self) -> int | None:
"""Pop lowest removed request index"""
if self.has_removed():
self._ensure_removed_sorted()
@@ -116,7 +116,7 @@ class BatchUpdateBuilder:
self.batch_changed = False
return batch_changed
def get_and_reset(self, batch_size: int) -> Optional[BatchUpdate]:
def get_and_reset(self, batch_size: int) -> BatchUpdate | None:
"""Generate a logitsprocs batch update data structure and reset
internal batch update builder state.
@@ -148,9 +148,7 @@ class BatchUpdateBuilder:
class LogitsProcessors:
"""Encapsulates initialized logitsproc objects."""
def __init__(
self, logitsprocs: Optional[Iterator["LogitsProcessor"]] = None
) -> None:
def __init__(self, logitsprocs: Iterator["LogitsProcessor"] | None = None) -> None:
self.argmax_invariant: list[LogitsProcessor] = []
self.non_argmax_invariant: list[LogitsProcessor] = []
if logitsprocs:
+7 -8
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Optional
import torch
@@ -11,20 +10,20 @@ from vllm.v1.sample.logits_processor import LogitsProcessors
@dataclass
class SamplingMetadata:
temperature: Optional[torch.Tensor]
temperature: torch.Tensor | None
all_greedy: bool
all_random: bool
top_p: Optional[torch.Tensor]
top_k: Optional[torch.Tensor]
top_p: torch.Tensor | None
top_k: torch.Tensor | None
generators: dict[int, torch.Generator]
# None means no logprobs, 0 means sampled token logprobs only
max_num_logprobs: Optional[int]
max_num_logprobs: int | None
no_penalties: bool
prompt_token_ids: Optional[torch.Tensor]
prompt_token_ids: torch.Tensor | None
frequency_penalties: torch.Tensor
presence_penalties: torch.Tensor
repetition_penalties: torch.Tensor
@@ -33,7 +32,7 @@ class SamplingMetadata:
# `allowed_token_ids_mask` is a 2D bool tensor of shape (max batch size,
# vocab size).
allowed_token_ids_mask: Optional[torch.Tensor]
allowed_token_ids_mask: torch.Tensor | None
# req_index -> bad_words_token_ids
bad_words_token_ids: dict[int, list[list[int]]]
@@ -42,4 +41,4 @@ class SamplingMetadata:
logitsprocs: LogitsProcessors
# Speculative token ids
spec_token_ids: Optional[list[list[int]]] = None
spec_token_ids: list[list[int]] | None = None
+13 -14
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Optional
import torch
import torch.nn as nn
@@ -84,9 +83,9 @@ class TopKTopPSampler(nn.Module):
self,
logits: torch.Tensor,
generators: dict[int, torch.Generator],
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
PyTorch-native implementation of top-k and top-p sampling.
@@ -105,9 +104,9 @@ class TopKTopPSampler(nn.Module):
self,
logits: torch.Tensor,
generators: dict[int, torch.Generator],
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""More optimized implementation for top-k and top-p sampling."""
# We prefer `random_sample` over `flashinfer_sample` when sorting is
# not needed. This is because `random_sample` does not require
@@ -132,9 +131,9 @@ class TopKTopPSampler(nn.Module):
self,
logits: torch.Tensor,
generators: dict[int, torch.Generator],
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""
PyTorch-native implementation of top-k and top-p sampling for CPU.
@@ -170,8 +169,8 @@ class TopKTopPSampler(nn.Module):
def apply_top_k_top_p(
logits: torch.Tensor,
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> torch.Tensor:
"""Apply top-k and top-p masks to the logits.
@@ -262,8 +261,8 @@ def random_sample(
def flashinfer_sample(
logits: torch.Tensor,
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
k: torch.Tensor | None,
p: torch.Tensor | None,
generators: dict[int, torch.Generator],
) -> torch.Tensor:
"""Sample from the logits using FlashInfer.
+4 -5
View File
@@ -1,6 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Optional
import torch
import torch.nn as nn
@@ -49,7 +48,7 @@ class RejectionSampler(nn.Module):
self,
metadata: SpecDecodeMetadata,
# [num_tokens, vocab_size]
draft_probs: Optional[torch.Tensor],
draft_probs: torch.Tensor | None,
# [num_tokens, vocab_size]
target_logits: torch.Tensor,
# [batch_size, 1]
@@ -216,7 +215,7 @@ class RejectionSampler(nn.Module):
@staticmethod
def _combine_outputs_with_spec_tokens(
output_token_ids: list[list[int]],
spec_token_ids: Optional[list[list[int]]] = None,
spec_token_ids: list[list[int]] | None = None,
) -> list[list[int]]:
if spec_token_ids is None:
return output_token_ids
@@ -240,7 +239,7 @@ def rejection_sample(
# [batch_size]
cu_num_draft_tokens: torch.Tensor,
# [num_tokens, vocab_size]
draft_probs: Optional[torch.Tensor],
draft_probs: torch.Tensor | None,
# [num_tokens, vocab_size]
target_probs: torch.Tensor,
# [batch_size, 1]
@@ -493,7 +492,7 @@ def sample_recovered_tokens(
# [num_tokens]
draft_token_ids: torch.Tensor,
# [num_tokens, vocab_size]
draft_probs: Optional[torch.Tensor],
draft_probs: torch.Tensor | None,
# [num_tokens, vocab_size]
target_probs: torch.Tensor,
sampling_metadata: SamplingMetadata,
+2 -4
View File
@@ -2,8 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""A layer that samples the next tokens from the model's outputs."""
from typing import Optional
import torch
import torch.nn as nn
@@ -140,7 +138,7 @@ class Sampler(nn.Module):
self,
logits: torch.Tensor,
sampling_metadata: SamplingMetadata,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Sample logits based on sampling metadata.
The various logits processing functions called in this method
@@ -243,7 +241,7 @@ class Sampler(nn.Module):
@staticmethod
def _combine_outputs_with_spec_tokens(
output_token_ids: list[list[int]],
spec_token_ids: Optional[list[list[int]]] = None,
spec_token_ids: list[list[int]] | None = None,
) -> list[list[int]]:
if spec_token_ids is None:
return output_token_ids
+1 -2
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass, field
from typing import Optional
import torch
@@ -48,7 +47,7 @@ class TPUSupportedSamplingMetadata:
min_tokens = None # impl is not vectorized
logit_bias: list[Optional[dict[int, float]]] = field(default_factory=lambda: list())
logit_bias: list[dict[int, float] | None] = field(default_factory=lambda: list())
allowed_token_ids_mask = None
bad_words_token_ids = None
+2 -4
View File
@@ -2,8 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Sampler layer implementing TPU supported operations."""
from typing import Optional
import torch
import torch.nn as nn
@@ -166,8 +164,8 @@ class Sampler(nn.Module):
def apply_top_k_top_p(
logits: torch.Tensor,
k: Optional[torch.Tensor],
p: Optional[torch.Tensor],
k: torch.Tensor | None,
p: torch.Tensor | None,
) -> torch.Tensor:
"""
Apply top-k and top-p optimized for TPU.
+10 -10
View File
@@ -4,10 +4,10 @@
import dataclasses
import importlib
import pickle
from collections.abc import Sequence
from collections.abc import Callable, Sequence
from inspect import isclass
from types import FunctionType
from typing import Any, Callable, Optional, Union
from typing import Any, TypeAlias
import cloudpickle
import msgspec
@@ -47,7 +47,7 @@ MMF_CLASS_TO_FACTORY: dict[type[BaseMultiModalField], str] = {
MultiModalBatchedField: "batched",
}
bytestr = Union[bytes, bytearray, memoryview, zmq.Frame]
bytestr: TypeAlias = bytes | bytearray | memoryview | zmq.Frame
def _log_insecure_serialization_warning():
@@ -57,7 +57,7 @@ def _log_insecure_serialization_warning():
)
def _typestr(val: Any) -> Optional[tuple[str, str]]:
def _typestr(val: Any) -> tuple[str, str] | None:
if val is None:
return None
t = type(val)
@@ -111,14 +111,14 @@ class MsgpackEncoder:
via dedicated messages. Note that this is a per-tensor limit.
"""
def __init__(self, size_threshold: Optional[int] = None):
def __init__(self, size_threshold: int | None = None):
if size_threshold is None:
size_threshold = envs.VLLM_MSGPACK_ZERO_COPY_THRESHOLD
self.encoder = msgpack.Encoder(enc_hook=self.enc_hook)
# This is used as a local stash of buffers that we can then access from
# our custom `msgspec` hook, `enc_hook`. We don't have a way to
# pass custom data to the hook otherwise.
self.aux_buffers: Optional[list[bytestr]] = None
self.aux_buffers: list[bytestr] | None = None
self.size_threshold = size_threshold
if envs.VLLM_ALLOW_INSECURE_SERIALIZATION:
_log_insecure_serialization_warning()
@@ -195,7 +195,7 @@ class MsgpackEncoder:
def _encode_ndarray(
self, obj: np.ndarray
) -> tuple[str, tuple[int, ...], Union[int, memoryview]]:
) -> tuple[str, tuple[int, ...], int | memoryview]:
assert self.aux_buffers is not None
# If the array is non-contiguous, we need to copy it first
arr_data = obj.data if obj.flags.c_contiguous else obj.tobytes()
@@ -215,7 +215,7 @@ class MsgpackEncoder:
def _encode_tensor(
self, obj: torch.Tensor
) -> tuple[str, tuple[int, ...], Union[int, memoryview]]:
) -> tuple[str, tuple[int, ...], int | memoryview]:
assert self.aux_buffers is not None
# view the tensor as a contiguous 1D array of bytes
arr = obj.flatten().contiguous().view(torch.uint8).numpy()
@@ -280,7 +280,7 @@ class MsgpackDecoder:
not thread-safe when encoding tensors / numpy arrays.
"""
def __init__(self, t: Optional[Any] = None):
def __init__(self, t: Any | None = None):
args = () if t is None else (t,)
self.decoder = msgpack.Decoder(
*args, ext_hook=self.ext_hook, dec_hook=self.dec_hook
@@ -289,7 +289,7 @@ class MsgpackDecoder:
if envs.VLLM_ALLOW_INSECURE_SERIALIZATION:
_log_insecure_serialization_warning()
def decode(self, bufs: Union[bytestr, Sequence[bytestr]]) -> Any:
def decode(self, bufs: bytestr | Sequence[bytestr]) -> Any:
if isinstance(bufs, bytestr): # type: ignore
return self.decoder.decode(bufs)
+5 -6
View File
@@ -3,7 +3,6 @@
import ast
from dataclasses import replace
from importlib.util import find_spec
from typing import Optional
import numpy as np
import torch
@@ -79,8 +78,8 @@ class EagleProposer:
vllm_config.model_config
)
self.attn_metadata_builder: Optional[AttentionMetadataBuilder] = None
self.draft_indexer_metadata_builder: Optional[AttentionMetadataBuilder] = None
self.attn_metadata_builder: AttentionMetadataBuilder | None = None
self.draft_indexer_metadata_builder: AttentionMetadataBuilder | None = None
self.attn_layer_names: list[str] = []
self.indexer_layer_names: list[str] = []
@@ -149,7 +148,7 @@ class EagleProposer:
)
# Determine allowed attention backends once during initialization.
self.allowed_attn_types: Optional[tuple] = None
self.allowed_attn_types: tuple | None = None
if current_platform.is_rocm():
rocm_types = [TritonAttentionMetadata, FlashAttentionMetadata]
# vllm.v1.attention.backends.rocm_aiter_fa is an optional backend
@@ -207,10 +206,10 @@ class EagleProposer:
target_hidden_states: torch.Tensor,
# [batch_size]
next_token_ids: torch.Tensor,
last_token_indices: Optional[torch.Tensor],
last_token_indices: torch.Tensor | None,
common_attn_metadata: CommonAttentionMetadata,
sampling_metadata: SamplingMetadata,
mm_embed_inputs: Optional[tuple[list[torch.Tensor], torch.Tensor]] = None,
mm_embed_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
) -> torch.Tensor:
num_tokens = target_token_ids.shape[0]
batch_size = next_token_ids.shape[0]
+1 -2
View File
@@ -3,7 +3,6 @@
import time
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
import prometheus_client
@@ -143,7 +142,7 @@ class SpecDecodingProm:
def __init__(
self,
speculative_config: Optional[SpeculativeConfig],
speculative_config: SpeculativeConfig | None,
labelnames: list[str],
per_engine_labelvalues: dict[int, list[str]],
):
+4 -3
View File
@@ -1,7 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import multiprocessing
from concurrent.futures import Future, ThreadPoolExecutor
from typing import TYPE_CHECKING
@@ -28,6 +26,9 @@ if TYPE_CHECKING:
else:
torch = LazyLoader("torch", globals(), "torch")
ReasoningParser = object
Request = object
logger = init_logger(__name__)
@@ -168,7 +169,7 @@ class StructuredOutputManager:
requests: dict[str, Request],
structured_output_request_ids: dict[str, int],
scheduled_spec_decode_tokens: dict[str, list[int]],
) -> npt.NDArray[np.int32] | None:
) -> "npt.NDArray[np.int32] | None":
# Prepare the structured output bitmask for this batch.
if not structured_output_request_ids:
return None
@@ -1,13 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import copy
import json
import os
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Union
from typing import TYPE_CHECKING, Any
import torch
@@ -47,7 +45,7 @@ def _walk_json_for_additional_properties(data: object):
def process_for_additional_properties(
guide_json: Union[str, dict[str, Any]],
guide_json: str | dict[str, Any],
) -> dict[str, Any]:
if isinstance(guide_json, str):
guide_json_obj = json.loads(guide_json)
@@ -184,12 +182,12 @@ class GuidanceGrammar(StructuredOutputGrammar):
def serialize_guidance_grammar(
request_type: StructuredOutputOptions,
grammar_spec: Union[str, dict[str, Any]],
grammar_spec: str | dict[str, Any],
disable_any_whitespace: bool = False,
disable_additional_properties: bool = False,
) -> str:
def _process_schema(
grammar_spec: Union[str, dict[str, Any]],
grammar_spec: str | dict[str, Any],
) -> str:
if disable_additional_properties:
grammar_spec = process_for_additional_properties(grammar_spec)
@@ -1,7 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import ast
import json
from dataclasses import dataclass, field
@@ -34,7 +32,7 @@ else:
@lru_cache
def _cached_build_vllm_token_enforcer_tokenizer_data(
tokenizer: PreTrainedTokenizerBase, vocab_size: int
) -> lmfe_vllm.TokenEnforcerTokenizerData:
) -> "lmfe_vllm.TokenEnforcerTokenizerData":
return lmfe_vllm.build_vllm_token_enforcer_tokenizer_data(
tokenizer, use_bitmask=True, vocab_size=vocab_size
)
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright 2025-present the Outlines developers
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import ast
import importlib
import json
+5 -4
View File
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import enum
from abc import ABC, abstractmethod
from dataclasses import dataclass
@@ -13,6 +11,9 @@ if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.transformers_utils.tokenizer import AnyTokenizer
else:
VllmConfig = object
AnyTokenizer = object
class StructuredOutputOptions(enum.Enum):
@@ -69,7 +70,7 @@ class StructuredOutputGrammar(ABC):
"""
@abstractmethod
def fill_bitmask(self, bitmask: torch.Tensor, batch_index: int) -> None:
def fill_bitmask(self, bitmask: "torch.Tensor", batch_index: int) -> None:
"""
Fills the bitmask for a specific batch index.
@@ -119,7 +120,7 @@ class StructuredOutputBackend(ABC):
"""
@abstractmethod
def allocate_token_bitmask(self, max_num_seqs: int) -> torch.Tensor:
def allocate_token_bitmask(self, max_num_seqs: int) -> "torch.Tensor":
"""
Allocates a token bitmask for the specified maximum number of sequences.
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
+4 -10
View File
@@ -1,13 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import dataclasses
import functools
import json
from concurrent.futures import Future
from concurrent.futures._base import TimeoutError
from typing import Optional, Union, cast
from typing import cast
from vllm.sampling_params import SamplingParams
from vllm.v1.structured_output.backend_types import (
@@ -20,9 +18,7 @@ from vllm.v1.structured_output.backend_types import (
@dataclasses.dataclass
class StructuredOutputRequest:
sampling_params: SamplingParams
_grammar: Union[Future[StructuredOutputGrammar], StructuredOutputGrammar] | None = (
None
)
_grammar: Future[StructuredOutputGrammar] | StructuredOutputGrammar | None = None
reasoning_ended: bool | None = None
def _check_grammar_completion(self) -> bool:
@@ -46,14 +42,12 @@ class StructuredOutputRequest:
def grammar(self) -> StructuredOutputGrammar | None:
completed = self._check_grammar_completion()
return (
cast(Optional[StructuredOutputGrammar], self._grammar)
if completed
else None
cast(StructuredOutputGrammar | None, self._grammar) if completed else None
)
@grammar.setter
def grammar(
self, grammar: Union[StructuredOutputGrammar, Future[StructuredOutputGrammar]]
self, grammar: StructuredOutputGrammar | Future[StructuredOutputGrammar]
) -> None:
self._grammar = grammar
+4 -3
View File
@@ -1,8 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import hashlib
import importlib.metadata
import os
@@ -37,6 +34,10 @@ else:
"transformers.models.gpt2.tokenization_gpt2",
)
AnyTokenizer = object
SchedulerOutput = object
InputBatch = object
logger = init_logger(__name__)
CACHE = None
+10 -12
View File
@@ -5,14 +5,13 @@ import contextlib
import multiprocessing
import time
import weakref
from collections.abc import Sequence
from collections.abc import Callable, Sequence
from contextlib import AbstractContextManager
from multiprocessing import connection
from multiprocessing.process import BaseProcess
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generic,
Optional,
TypeVar,
@@ -66,7 +65,7 @@ class ConstantList(Generic[T], Sequence):
def clear(self):
raise TypeError("Cannot clear a constant list")
def index(self, item: T, start: int = 0, stop: Optional[int] = None) -> int:
def index(self, item: T, start: int = 0, stop: int | None = None) -> int:
return self._x.index(item, start, stop if stop is not None else len(self._x))
@overload
@@ -75,7 +74,7 @@ class ConstantList(Generic[T], Sequence):
@overload
def __getitem__(self, s: slice, /) -> list[T]: ...
def __getitem__(self, item: Union[int, slice]) -> Union[T, list[T]]:
def __getitem__(self, item: int | slice) -> T | list[T]:
return self._x[item]
@overload
@@ -84,7 +83,7 @@ class ConstantList(Generic[T], Sequence):
@overload
def __setitem__(self, s: slice, value: T, /): ...
def __setitem__(self, item: Union[int, slice], value: Union[T, list[T]]):
def __setitem__(self, item: int | slice, value: T | list[T]):
raise TypeError("Cannot set item in a constant list")
def __delitem__(self, item):
@@ -108,7 +107,7 @@ class CpuGpuBuffer:
def __init__(
self,
*size: Union[int, torch.SymInt],
*size: int | torch.SymInt,
dtype: torch.dtype,
device: torch.device,
pin_memory: bool,
@@ -128,12 +127,12 @@ class CpuGpuBuffer:
)
self.np = self.cpu.numpy()
def copy_to_gpu(self, n: Optional[int] = None) -> torch.Tensor:
def copy_to_gpu(self, n: int | None = None) -> torch.Tensor:
if n is None:
return self.gpu.copy_(self.cpu, non_blocking=True)
return self.gpu[:n].copy_(self.cpu[:n], non_blocking=True)
def copy_to_cpu(self, n: Optional[int] = None) -> torch.Tensor:
def copy_to_cpu(self, n: int | None = None) -> torch.Tensor:
"""NOTE: Because this method is non-blocking, explicit synchronization
is needed to ensure the data is copied to CPU."""
if n is None:
@@ -173,7 +172,7 @@ class APIServerProcessManager:
num_servers: int,
input_addresses: list[str],
output_addresses: list[str],
stats_update_address: Optional[str] = None,
stats_update_address: str | None = None,
):
"""Initialize and start API server worker processes.
@@ -227,9 +226,8 @@ class APIServerProcessManager:
def wait_for_completion_or_failure(
api_server_manager: APIServerProcessManager,
engine_manager: Optional[
Union["CoreEngineProcManager", "CoreEngineActorManager"]
] = None,
engine_manager: Union["CoreEngineProcManager", "CoreEngineActorManager"]
| None = None,
coordinator: Optional["DPCoordinator"] = None,
) -> None:
"""Wait for all processes to complete or detect if any fail.
+1 -2
View File
@@ -1,6 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Union
import numpy as np
import torch
@@ -215,7 +214,7 @@ class BlockTable:
return self.block_table.np
def _make_buffer(
self, *size: Union[int, torch.SymInt], dtype: torch.dtype
self, *size: int | torch.SymInt, dtype: torch.dtype
) -> CpuGpuBuffer:
return CpuGpuBuffer(
*size, dtype=dtype, device=self.device, pin_memory=self.pin_memory
+2 -2
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any
import torch
import torch.nn as nn
@@ -95,7 +95,7 @@ class CPUModelRunner(GPUModelRunner):
def _to_list(self, sampled_token_ids: torch.Tensor) -> list[list[int]]:
return sampled_token_ids.tolist()
def get_dp_padding(self, num_tokens: int) -> tuple[int, Optional[torch.Tensor]]:
def get_dp_padding(self, num_tokens: int) -> tuple[int, torch.Tensor | None]:
# Note: For CPU backend, dp padding is not required for now.
return 0, None
+2 -2
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import platform
from typing import Callable, Optional
from collections.abc import Callable
import torch
@@ -91,7 +91,7 @@ class CPUWorker(Worker):
logger.warning("sleep mode is not supported on CPU, ignore it.")
pass
def wake_up(self, tags: Optional[list[str]] = None) -> None:
def wake_up(self, tags: list[str] | None = None) -> None:
logger.warning("sleep mode is not supported on CPU, ignore it.")
pass
+5 -6
View File
@@ -1,6 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Optional
import numpy as np
import torch
@@ -95,7 +94,7 @@ def _synchronize_dp_ranks(
should_attempt_ubatching: bool,
should_attempt_dp_padding: bool,
parallel_config: ParallelConfig,
) -> tuple[bool, Optional[torch.Tensor]]:
) -> tuple[bool, torch.Tensor | None]:
"""
1. Decides if each DP rank is going to microbatch. Either all ranks
run with microbatching or none of them do.
@@ -156,10 +155,10 @@ def coordinate_batch_across_dp(
allow_microbatching: bool,
allow_dp_padding: bool,
parallel_config: ParallelConfig,
num_tokens_padded: Optional[int] = None,
uniform_decode: Optional[bool] = None,
num_scheduled_tokens_per_request: Optional[np.ndarray] = None,
) -> tuple[Optional[UBatchSlices], Optional[torch.Tensor]]:
num_tokens_padded: int | None = None,
uniform_decode: bool | None = None,
num_scheduled_tokens_per_request: np.ndarray | None = None,
) -> tuple[UBatchSlices | None, torch.Tensor | None]:
"""
Coordinates amongst all DP ranks to determine if and how the full batch
should be split into microbatches.
+22 -22
View File
@@ -3,7 +3,7 @@
# Datastructures defining a GPU input batch
from dataclasses import dataclass
from typing import Optional, cast
from typing import cast
import numpy as np
import torch
@@ -29,21 +29,21 @@ from vllm.v1.worker.block_table import MultiGroupBlockTable
@dataclass
class CachedRequestState:
req_id: str
prompt_token_ids: Optional[list[int]]
prompt_token_ids: list[int] | None
mm_features: list[MultiModalFeatureSpec]
sampling_params: Optional[SamplingParams]
pooling_params: Optional[PoolingParams]
generator: Optional[torch.Generator]
sampling_params: SamplingParams | None
pooling_params: PoolingParams | None
generator: torch.Generator | None
block_ids: tuple[list[int], ...]
num_computed_tokens: int
output_token_ids: list[int]
mrope_positions: Optional[torch.Tensor] = None
mrope_position_delta: Optional[int] = None
mrope_positions: torch.Tensor | None = None
mrope_position_delta: int | None = None
lora_request: Optional[LoRARequest] = None
prompt_embeds: Optional[torch.Tensor] = None
lora_request: LoRARequest | None = None
prompt_embeds: torch.Tensor | None = None
def __post_init__(self):
self.num_prompt_tokens = length_from_prompt_token_ids_or_embeds(
@@ -78,7 +78,7 @@ class InputBatch:
vocab_size: int,
block_sizes: list[int], # The block_size of each kv cache group
kernel_block_sizes: list[int],
logitsprocs: Optional[LogitsProcessors] = None,
logitsprocs: LogitsProcessors | None = None,
logitsprocs_need_output_token_ids: bool = False,
is_spec_decode: bool = False,
is_pooling_model: bool = False,
@@ -93,7 +93,7 @@ class InputBatch:
self.pin_memory = pin_memory
self.vocab_size = vocab_size
self._req_ids: list[Optional[str]] = []
self._req_ids: list[str | None] = []
self.req_id_to_index: dict[str, int] = {}
# TODO(woosuk): This buffer could be too large if max_model_len is big.
@@ -228,15 +228,15 @@ class InputBatch:
self.has_allowed_token_ids: set[str] = set()
# NOTE(lufang): In the mask tensor, if the corresponding token allowed,
# the value is False. Since we use masked_fill_ to set -inf.
self.allowed_token_ids_mask: Optional[torch.Tensor] = None
self.allowed_token_ids_mask_cpu_tensor: Optional[torch.Tensor] = None
self.allowed_token_ids_mask: torch.Tensor | None = None
self.allowed_token_ids_mask_cpu_tensor: torch.Tensor | None = None
# req_index -> bad_words_token_ids
self.bad_words_token_ids: dict[int, list[list[int]]] = {}
self.logits_processing_needs_token_ids = np.zeros(max_num_reqs, dtype=bool)
self.req_output_token_ids: list[Optional[list[int]]] = []
self.req_output_token_ids: list[list[int] | None] = []
# Store provided logitsprocs. If none are provided, initialize empty
# data structure
@@ -244,7 +244,7 @@ class InputBatch:
self.logitsprocs_need_output_token_ids = logitsprocs_need_output_token_ids
# Store last speculative tokens for sampler.
self.spec_token_ids: list[Optional[list[int]]] = []
self.spec_token_ids: list[list[int] | None] = []
# This is updated each time the batch constituents change.
self.sampling_metadata = self._make_sampling_metadata()
@@ -252,13 +252,13 @@ class InputBatch:
self.pooling_params: dict[str, PoolingParams] = {}
# Cached reference to the GPU tensor of previously sampled tokens
self.prev_sampled_token_ids: Optional[torch.Tensor] = None
self.prev_req_id_to_index: Optional[dict[str, int]] = None
self.prev_sampled_token_ids: torch.Tensor | None = None
self.prev_req_id_to_index: dict[str, int] | None = None
# These are used to update output_token_ids with real sampled
# ids from prior step, if required by current sampling params
# (e.g. penalties).
self.sampled_token_ids_cpu: Optional[torch.Tensor] = None
self.async_copy_ready_event: Optional[torch.cuda.Event] = None
self.sampled_token_ids_cpu: torch.Tensor | None = None
self.async_copy_ready_event: torch.cuda.Event | None = None
@property
def req_ids(self) -> list[str]:
@@ -438,7 +438,7 @@ class InputBatch:
return req_index
def remove_request(self, req_id: str) -> Optional[int]:
def remove_request(self, req_id: str) -> int | None:
"""This method must always be followed by a call to condense().
Args:
@@ -796,7 +796,7 @@ class InputBatch:
else []
)
allowed_token_ids_mask: Optional[torch.Tensor] = None
allowed_token_ids_mask: torch.Tensor | None = None
if not self.no_allowed_token_ids:
assert self.allowed_token_ids_mask is not None
copy_slice(
@@ -954,7 +954,7 @@ class InputBatch:
)
@property
def max_num_logprobs(self) -> Optional[int]:
def max_num_logprobs(self) -> int | None:
return max(self.num_logprobs.values()) if self.num_logprobs else None
@property
+41 -42
View File
@@ -8,14 +8,13 @@ from collections import defaultdict
from collections.abc import Iterator
from contextlib import contextmanager
from copy import deepcopy
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union, cast
from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias, cast
import numpy as np
import torch
import torch.distributed
import torch.nn as nn
from tqdm import tqdm
from typing_extensions import TypeAlias
import vllm.envs as envs
from vllm.attention import Attention, AttentionType
@@ -162,7 +161,7 @@ logger = init_logger(__name__)
AttnMetadataDict: TypeAlias = dict[str, AttentionMetadata]
# list when ubatching is enabled
PerLayerAttnMetadata: TypeAlias = Union[list[AttnMetadataDict], AttnMetadataDict]
PerLayerAttnMetadata: TypeAlias = list[AttnMetadataDict] | AttnMetadataDict
# Wrapper for ModelRunnerOutput to support overlapped execution.
@@ -295,7 +294,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
# Sampler
self.sampler = Sampler(logprobs_mode=self.model_config.logprobs_mode)
self.eplb_state: Optional[EplbState] = None
self.eplb_state: EplbState | None = None
"""
State of the expert parallelism load balancer.
@@ -447,14 +446,14 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
# CUDA event to synchronize use of reused CPU tensors between steps
# when async scheduling is enabled.
self.prepare_inputs_event: Optional[torch.cuda.Event] = None
self.prepare_inputs_event: torch.cuda.Event | None = None
if self.use_async_scheduling:
self.prepare_inputs_event = torch.cuda.Event()
# Start in a completed state.
self.prepare_inputs_event.record(torch.cuda.default_stream())
# None in the first PP rank. The rest are set after load_model.
self.intermediate_tensors: Optional[IntermediateTensors] = None
self.intermediate_tensors: IntermediateTensors | None = None
# OPTIMIZATION: Cache the tensors rather than creating them every step.
# Keep in int64 to avoid overflow with long context
@@ -495,7 +494,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
else None
)
self.reorder_batch_threshold: Optional[int] = None
self.reorder_batch_threshold: int | None = None
# Attention layers that are only in the KVCacheConfig of the runner
# (e.g., KV sharing, encoder-only attention), but not in the
@@ -503,7 +502,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self.runner_only_attn_layers: set[str] = set()
# Cached outputs.
self._draft_token_ids: Optional[Union[list[list[int]], torch.Tensor]] = None
self._draft_token_ids: list[list[int]] | torch.Tensor | None = None
self.transfer_event = torch.cuda.Event()
self.sampled_token_ids_pinned_cpu = torch.empty(
(self.max_model_len, 1),
@@ -527,7 +526,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
return self.positions.gpu[num_tokens]
def _make_buffer(
self, *size: Union[int, torch.SymInt], dtype: torch.dtype, numpy: bool = True
self, *size: int | torch.SymInt, dtype: torch.dtype, numpy: bool = True
) -> CpuGpuBuffer:
return CpuGpuBuffer(
*size,
@@ -928,7 +927,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _get_cumsum_and_arange(
self,
num_tokens: np.ndarray,
cumsum_dtype: Optional[np.dtype] = None,
cumsum_dtype: np.dtype | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Get the cumulative sum and batched arange of the given array.
# E.g., [2, 5, 3] -> ([2, 7, 10], [0, 1, 0, 1, 2, 3, 4, 0, 1, 2])
@@ -1024,7 +1023,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
scheduler_output: "SchedulerOutput",
kv_cache_spec: KVCacheSpec,
num_reqs: int,
) -> Optional[np.ndarray]:
) -> np.ndarray | None:
if not isinstance(kv_cache_spec, CrossAttentionSpec):
return None
@@ -1042,12 +1041,12 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
) -> tuple[
PerLayerAttnMetadata,
torch.Tensor,
Optional[SpecDecodeMetadata],
SpecDecodeMetadata | None,
np.ndarray,
Optional[CommonAttentionMetadata],
CommonAttentionMetadata | None,
int,
Optional[UBatchSlices],
Optional[torch.Tensor],
UBatchSlices | None,
torch.Tensor | None,
bool,
]:
"""
@@ -2048,7 +2047,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
)
self._sync_device()
pooler_output: list[Optional[torch.Tensor]] = []
pooler_output: list[torch.Tensor | None] = []
for raw_output, seq_len, prompt_len in zip(
raw_pooler_output, seq_lens_cpu, pooling_metadata.prompt_lens
):
@@ -2091,13 +2090,13 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self,
scheduler_output: "SchedulerOutput",
num_input_tokens: int, # Padded
intermediate_tensors: Optional[IntermediateTensors] = None,
intermediate_tensors: IntermediateTensors | None = None,
) -> tuple[
int,
Optional[torch.Tensor],
Optional[torch.Tensor],
torch.Tensor | None,
torch.Tensor | None,
torch.Tensor,
Optional[IntermediateTensors],
IntermediateTensors | None,
dict[str, Any],
]:
num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
@@ -2197,8 +2196,8 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _sample(
self,
logits: Optional[torch.Tensor],
spec_decode_metadata: Optional[SpecDecodeMetadata],
logits: torch.Tensor | None,
spec_decode_metadata: SpecDecodeMetadata | None,
) -> SamplerOutput:
# Sample the next token and get logprobs if needed.
sampling_metadata = self.input_batch.sampling_metadata
@@ -2243,14 +2242,14 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self,
scheduler_output: "SchedulerOutput",
sampler_output: SamplerOutput,
logits: Optional[torch.Tensor],
logits: torch.Tensor | None,
hidden_states: torch.Tensor,
num_scheduled_tokens: int,
) -> tuple[
dict[str, int],
Optional[LogprobsLists],
LogprobsLists | None,
list[list[int]],
dict[str, Optional[LogprobsTensors]],
dict[str, LogprobsTensors | None],
list[str],
dict[str, int],
list[int],
@@ -2377,10 +2376,10 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _model_forward(
self,
input_ids: Optional[torch.Tensor] = None,
positions: Optional[torch.Tensor] = None,
intermediate_tensors: Optional[IntermediateTensors] = None,
inputs_embeds: Optional[torch.Tensor] = None,
input_ids: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
**model_kwargs: dict[str, Any],
) -> Any:
"""Helper method to call the model forward pass.
@@ -2411,8 +2410,8 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def execute_model(
self,
scheduler_output: "SchedulerOutput",
intermediate_tensors: Optional[IntermediateTensors] = None,
) -> Union[ModelRunnerOutput, AsyncModelRunnerOutput, IntermediateTensors]:
intermediate_tensors: IntermediateTensors | None = None,
) -> ModelRunnerOutput | AsyncModelRunnerOutput | IntermediateTensors:
with record_function_or_nullcontext("Preprocess"):
with self.synchronize_input_prep():
# Update persistent batch states.
@@ -2678,7 +2677,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
return async_output
def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
def take_draft_token_ids(self) -> DraftTokenIds | None:
if self._draft_token_ids is None:
return None
req_ids = self.input_batch.req_ids
@@ -2692,14 +2691,14 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def propose_draft_token_ids(
self,
scheduler_output: "SchedulerOutput",
sampled_token_ids: Union[torch.Tensor, list[list[int]]],
sampled_token_ids: torch.Tensor | list[list[int]],
sampling_metadata: SamplingMetadata,
hidden_states: torch.Tensor,
sample_hidden_states: torch.Tensor,
aux_hidden_states: Optional[list[torch.Tensor]],
spec_decode_metadata: Optional[SpecDecodeMetadata],
aux_hidden_states: list[torch.Tensor] | None,
spec_decode_metadata: SpecDecodeMetadata | None,
common_attn_metadata: CommonAttentionMetadata,
) -> Union[list[list[int]], torch.Tensor]:
) -> list[list[int]] | torch.Tensor:
num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
if self.speculative_config.method == "ngram":
assert isinstance(sampled_token_ids, list)
@@ -2961,7 +2960,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self.model, self.vllm_config, CUDAGraphMode.NONE, self.device
)
def _get_eagle3_aux_layers_from_config(self) -> Optional[tuple[int, ...]]:
def _get_eagle3_aux_layers_from_config(self) -> tuple[int, ...] | None:
"""Extract Eagle3 auxiliary layer indices from speculative config.
These indices specify which hidden states from the base model should
@@ -3007,13 +3006,13 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self,
hidden_states: torch.Tensor,
num_scheduled_tokens: dict[str, int],
) -> dict[str, Optional[LogprobsTensors]]:
) -> dict[str, LogprobsTensors | None]:
num_prompt_logprobs_dict = self.input_batch.num_prompt_logprobs
if not num_prompt_logprobs_dict:
return {}
in_progress_dict = self.input_batch.in_progress_prompt_logprobs_cpu
prompt_logprobs_dict: dict[str, Optional[LogprobsTensors]] = {}
prompt_logprobs_dict: dict[str, LogprobsTensors | None] = {}
# Since prompt logprobs are a rare feature, prioritize simple,
# maintainable loop over optimal performance.
@@ -3107,7 +3106,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _get_nans_in_logits(
self,
logits: Optional[torch.Tensor],
logits: torch.Tensor | None,
) -> dict[str, int]:
try:
if logits is None:
@@ -3190,7 +3189,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _dummy_run(
self,
num_tokens: int,
cudagraph_runtime_mode: Optional[CUDAGraphMode] = None,
cudagraph_runtime_mode: CUDAGraphMode | None = None,
force_attention: bool = False,
uniform_decode: bool = False,
allow_microbatching: bool = True,
@@ -3294,7 +3293,7 @@ class GPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
dp_rank = self.parallel_config.data_parallel_rank
num_tokens_after_padding = int(num_tokens_across_dp[dp_rank])
attn_metadata: Optional[PerLayerAttnMetadata] = None
attn_metadata: PerLayerAttnMetadata | None = None
# If force_attention is True, we always capture attention. Otherwise,
# it only happens for cudagraph_runtime_mode=FULL.
+5 -4
View File
@@ -2,8 +2,9 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import threading
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Callable, Optional
from typing import Any
import torch
@@ -32,8 +33,8 @@ class UbatchMetadata:
context: UBatchContext
input_ids: torch.Tensor
positions: torch.Tensor
inputs_embeds: Optional[torch.Tensor]
intermediate_tensors: Optional[IntermediateTensors]
inputs_embeds: torch.Tensor | None
intermediate_tensors: IntermediateTensors | None
num_tokens: int
@@ -41,7 +42,7 @@ class UbatchMetadata:
class CUDAGraphMetaData:
cudagraph: torch.cuda.CUDAGraph
ubatch_metadata: UbatchMetadata
outputs: Optional[Any] = None
outputs: Any | None = None
class SMControlContextManager:
+9 -9
View File
@@ -6,7 +6,7 @@ import copy
import gc
import os
from contextlib import AbstractContextManager, nullcontext
from typing import TYPE_CHECKING, Any, Optional, Union
from typing import TYPE_CHECKING, Any
import torch
import torch.distributed
@@ -132,7 +132,7 @@ class Worker(WorkerBase):
used_bytes / GiB_bytes,
)
def wake_up(self, tags: Optional[list[str]] = None) -> None:
def wake_up(self, tags: list[str] | None = None) -> None:
from vllm.device_allocator.cumem import CuMemAllocator
allocator = CuMemAllocator.get_instance()
@@ -456,7 +456,7 @@ class Worker(WorkerBase):
def execute_model(
self,
scheduler_output: "SchedulerOutput",
) -> Optional[Union[ModelRunnerOutput, AsyncModelRunnerOutput]]:
) -> ModelRunnerOutput | AsyncModelRunnerOutput | None:
intermediate_tensors = None
forward_pass = scheduler_output.total_num_scheduled_tokens > 0
num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
@@ -504,7 +504,7 @@ class Worker(WorkerBase):
output.kv_connector_output = kv_connector_output
return output
def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
def take_draft_token_ids(self) -> DraftTokenIds | None:
return self.model_runner.take_draft_token_ids()
def profile(self, is_start: bool = True):
@@ -565,7 +565,7 @@ class Worker(WorkerBase):
self,
old_ep_size: int,
new_ep_size: int,
global_expert_load: Optional[torch.Tensor],
global_expert_load: torch.Tensor | None,
) -> None:
from vllm.distributed.parallel_state import get_ep_group
@@ -611,7 +611,7 @@ class Worker(WorkerBase):
def _reconfigure_moe(
self, old_ep_size: int, new_ep_size: int
) -> Optional[torch.Tensor]:
) -> torch.Tensor | None:
"""
Reconfigure MoE modules with provided reconfig_request
@@ -730,8 +730,8 @@ class Worker(WorkerBase):
def save_sharded_state(
self,
path: str,
pattern: Optional[str] = None,
max_size: Optional[int] = None,
pattern: str | None = None,
max_size: int | None = None,
) -> None:
from vllm.model_executor.model_loader import ShardedStateLoader
@@ -758,7 +758,7 @@ class Worker(WorkerBase):
def init_worker_distributed_environment(
vllm_config: VllmConfig,
rank: int,
distributed_init_method: Optional[str] = None,
distributed_init_method: str | None = None,
local_rank: int = -1,
backend: str = "nccl",
) -> None:
@@ -9,7 +9,6 @@ from collections.abc import Generator
from contextlib import AbstractContextManager, contextmanager, nullcontext
from typing import (
TYPE_CHECKING, # noqa: UP035
Optional,
)
from vllm.config import VllmConfig
@@ -65,7 +64,7 @@ class KVConnectorModelRunnerMixin:
@staticmethod
def get_finished_kv_transfers(
scheduler_output: "SchedulerOutput",
) -> tuple[Optional[set[str]], Optional[set[str]]]:
) -> tuple[set[str] | None, set[str] | None]:
if has_kv_transfer_group():
return get_kv_transfer_group().get_finished(
scheduler_output.finished_req_ids
@@ -95,7 +94,7 @@ class KVConnectorModelRunnerMixin:
@staticmethod
def maybe_get_kv_connector_output(
scheduler_output: "SchedulerOutput",
) -> AbstractContextManager[Optional[KVConnectorOutput]]:
) -> AbstractContextManager[KVConnectorOutput | None]:
return (
KVConnectorModelRunnerMixin._get_kv_connector_output(scheduler_output)
if has_kv_transfer_group()
@@ -139,7 +138,7 @@ class KVConnectorModelRunnerMixin:
kv_connector.clear_connector_metadata()
@staticmethod
def get_kv_connector_stats() -> Optional[KVConnectorStats]:
def get_kv_connector_stats() -> KVConnectorStats | None:
if has_kv_transfer_group():
return get_kv_transfer_group().get_kv_connector_stats()
return None
+5 -6
View File
@@ -5,7 +5,6 @@ Define LoRA functionality mixin for model runners.
"""
from contextlib import contextmanager
from typing import Optional, Union
import numpy as np
import torch
@@ -21,7 +20,7 @@ from vllm.model_executor.models import supports_lora, supports_multimodal
from vllm.v1.worker.gpu_input_batch import InputBatch as GPUInputBatch
from vllm.v1.worker.tpu_input_batch import InputBatch as TPUInputBatch
InputBatch = Union[TPUInputBatch, GPUInputBatch]
InputBatch = TPUInputBatch | GPUInputBatch
logger = init_logger(__name__)
@@ -85,7 +84,7 @@ class LoRAModelRunnerMixin:
@contextmanager
def maybe_setup_dummy_loras(
self, lora_config: Optional[LoRAConfig], remove_lora: bool = True
self, lora_config: LoRAConfig | None, remove_lora: bool = True
):
if lora_config is None:
yield
@@ -121,7 +120,7 @@ class LoRAModelRunnerMixin:
@contextmanager
def maybe_select_dummy_loras(
self, lora_config: Optional[LoRAConfig], num_scheduled_tokens: np.ndarray
self, lora_config: LoRAConfig | None, num_scheduled_tokens: np.ndarray
):
if lora_config is None:
yield
@@ -158,7 +157,7 @@ class LoRAModelRunnerMixin:
@contextmanager
def maybe_dummy_run_with_lora(
self,
lora_config: Optional[LoRAConfig],
lora_config: LoRAConfig | None,
num_scheduled_tokens: np.ndarray,
remove_lora: bool = True,
):
@@ -168,7 +167,7 @@ class LoRAModelRunnerMixin:
):
yield
def maybe_remove_all_loras(self, lora_config: Optional[LoRAConfig]):
def maybe_remove_all_loras(self, lora_config: LoRAConfig | None):
if lora_config is None:
return
self.lora_manager.remove_all_adapters()
+9 -9
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Datastructures defining a TPU input batch
from typing import Optional, cast
from typing import cast
import numpy as np
import torch
@@ -36,7 +36,7 @@ class InputBatch:
self.pin_memory = pin_memory
self.vocab_size = vocab_size
self._req_ids: list[Optional[str]] = []
self._req_ids: list[str | None] = []
self.req_id_to_index: dict[str, int] = {}
# TODO(woosuk): This buffer could be too large if max_model_len is big.
@@ -155,17 +155,17 @@ class InputBatch:
# To accumulate prompt logprobs tensor chunks across prefill steps.
self.in_progress_prompt_logprobs_cpu: dict[str, LogprobsTensors] = {}
self.logit_bias: list[Optional[dict[int, float]]] = [None] * max_num_reqs
self.logit_bias: list[dict[int, float] | None] = [None] * max_num_reqs
self.has_allowed_token_ids: set[str] = set()
# NOTE(lufang): In the mask tensor, if the corresponding token allowed,
# the value is False. Since we use masked_fill_ to set -inf.
self.allowed_token_ids_mask: Optional[torch.Tensor] = None
self.allowed_token_ids_mask_cpu_tensor: Optional[torch.Tensor] = None
self.allowed_token_ids_mask: torch.Tensor | None = None
self.allowed_token_ids_mask_cpu_tensor: torch.Tensor | None = None
# req_index -> bad_words_token_ids
self.bad_words_token_ids: dict[int, list[list[int]]] = {}
self.req_output_token_ids: list[Optional[list[int]]] = []
self.req_output_token_ids: list[list[int] | None] = []
@property
def req_ids(self) -> list[str]:
@@ -176,7 +176,7 @@ class InputBatch:
def add_request(
self,
request: "CachedRequestState",
req_index: Optional[int] = None,
req_index: int | None = None,
) -> None:
if req_index is None:
req_index = self.num_reqs
@@ -296,7 +296,7 @@ class InputBatch:
# No LoRA
self.request_lora_mapping[req_index] = 0
def remove_request(self, req_id: str) -> Optional[int]:
def remove_request(self, req_id: str) -> int | None:
"""This method must always be followed by a call to condense()."""
req_index = self.req_id_to_index.pop(req_id, None)
@@ -580,7 +580,7 @@ class InputBatch:
)
@property
def max_num_logprobs(self) -> Optional[int]:
def max_num_logprobs(self) -> int | None:
return max(self.num_logprobs.values()) if self.num_logprobs else None
@property
+7 -7
View File
@@ -3,7 +3,7 @@
import bisect
import gc
import time
from typing import TYPE_CHECKING, Any, Optional, cast
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import patch
import numpy as np
@@ -140,7 +140,7 @@ class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
self,
vllm_config: VllmConfig,
device: torch.device,
original_parallel_config: Optional[ParallelConfig] = None,
original_parallel_config: ParallelConfig | None = None,
):
self.vllm_config = vllm_config
self.model_config = vllm_config.model_config
@@ -1050,7 +1050,7 @@ class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def _get_model_inputs(
self,
input_ids: torch.Tensor,
mm_embed_inputs: Optional[tuple[list[torch.Tensor], torch.Tensor]],
mm_embed_inputs: tuple[list[torch.Tensor], torch.Tensor] | None,
):
if self.supports_mm_inputs:
mm_embeds, is_mm_embed = mm_embed_inputs or (None, None)
@@ -1076,7 +1076,7 @@ class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
def execute_model(
self,
scheduler_output: "SchedulerOutput",
intermediate_tensors: Optional[IntermediateTensors] = None,
intermediate_tensors: IntermediateTensors | None = None,
) -> ModelRunnerOutput:
# Update cached state
self._update_states(scheduler_output)
@@ -1220,7 +1220,7 @@ class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin):
), "req_ids contains None"
req_ids = cast(list[str], self.input_batch.req_ids[:num_reqs])
prompt_logprobs_dict: dict[str, Optional[LogprobsTensors]] = {}
prompt_logprobs_dict: dict[str, LogprobsTensors | None] = {}
for req_id in self.input_batch.req_ids[:num_reqs]:
prompt_logprobs_dict[req_id] = None
@@ -2127,8 +2127,8 @@ def replace_set_lora(model):
index: int,
lora_a: torch.Tensor,
lora_b: torch.Tensor,
embeddings_tensor: Optional[torch.Tensor],
bias: Optional[torch.Tensor] = None,
embeddings_tensor: torch.Tensor | None,
bias: torch.Tensor | None = None,
):
# TODO: The integer index leads to a recompilation, but converting it
# to a tensor doesn't seem to work anymore. This might be fixed with a
+4 -3
View File
@@ -3,7 +3,8 @@
"""A TPU worker class."""
import os
from typing import Any, Callable, Optional, TypeVar
from collections.abc import Callable
from typing import Any, TypeVar
import torch
import torch.distributed
@@ -257,7 +258,7 @@ class TPUWorker:
def execute_model(
self,
scheduler_output: "SchedulerOutput",
) -> Optional[ModelRunnerOutput]:
) -> ModelRunnerOutput | None:
output = self.model_runner.execute_model(scheduler_output)
# every worker's output is needed when kv_transfer_group is set up
return output if self.is_driver_worker or has_kv_transfer_group() else None
@@ -317,7 +318,7 @@ class TPUWorker:
self,
vllm_config: VllmConfig,
rank: int,
distributed_init_method: Optional[str] = None,
distributed_init_method: str | None = None,
local_rank: int = -1,
) -> None:
"""Initialize the distributed environment."""
+1 -1
View File
@@ -1,9 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import TypeAlias
import numpy as np
from typing_extensions import TypeAlias
from vllm.config import ParallelConfig

Some files were not shown because too many files have changed in this diff Show More