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
+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