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
+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
+5 -5
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import defaultdict
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING
import torch
@@ -193,7 +193,7 @@ def sanity_check_mm_encoder_outputs(
def scatter_mm_placeholders(
embeds: torch.Tensor,
is_embed: Optional[torch.Tensor],
is_embed: torch.Tensor | None,
) -> torch.Tensor:
"""
Scatter the multimodal embeddings into a contiguous tensor that represents
@@ -221,7 +221,7 @@ def scatter_mm_placeholders(
def gather_mm_placeholders(
placeholders: torch.Tensor,
is_embed: Optional[torch.Tensor],
is_embed: torch.Tensor | None,
) -> torch.Tensor:
"""
Reconstructs the embeddings from the placeholder tokens.
@@ -238,7 +238,7 @@ def gather_mm_placeholders(
def add_kv_sharing_layers_to_kv_cache_groups(
shared_kv_cache_layers: dict[str, str],
kv_cache_groups: list[KVCacheGroupSpec],
runner_only_attn_layers: Optional[set[str]] = None,
runner_only_attn_layers: set[str] | None = None,
) -> None:
"""
Sets up KV cache sharing by reusing the allocated KV caches in `kv_caches`
@@ -270,7 +270,7 @@ def bind_kv_cache(
kv_caches: dict[str, torch.Tensor],
forward_context: dict[str, "Attention"],
runner_kv_caches: list[torch.Tensor],
num_attn_module: Optional[int] = 1,
num_attn_module: int | None = 1,
) -> None:
"""
Bind the allocated KV cache to both ModelRunner and forward context so
+6 -4
View File
@@ -1,10 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, TypeVar
import torch
import torch.nn as nn
@@ -26,6 +25,9 @@ from vllm.v1.kv_cache_interface import KVCacheSpec
if TYPE_CHECKING:
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.outputs import ModelRunnerOutput
else:
SchedulerOutput = object
ModelRunnerOutput = object
logger = init_logger(__name__)
@@ -329,7 +331,7 @@ class WorkerWrapperBase:
# To make vLLM config available during device initialization
self.worker.init_device() # type: ignore
def execute_method(self, method: Union[str, bytes], *args, **kwargs):
def execute_method(self, method: str | bytes, *args, **kwargs):
try:
# method resolution order:
# if a method is defined in this class, it will be called directly.