Add pydocstyle to the ruff rules (#52136)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com> Signed-off-by: Harry Mellor <hej.mellor@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
804e5377aa
commit
8c1557a79c
+32
-39
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Core abstractions for KV cache offloading in vLLM v1.
|
||||
"""
|
||||
"""Core abstractions for KV cache offloading in vLLM v1."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Collection, Iterable, Sequence
|
||||
@@ -149,8 +147,7 @@ class ScheduleEndContext(NamedTuple):
|
||||
|
||||
|
||||
class LoadStoreSpec:
|
||||
"""
|
||||
Metadata that encapsulates information allowing a worker
|
||||
"""Metadata that encapsulates information allowing a worker
|
||||
to load, and optionally also to store, blocks of KV data.
|
||||
"""
|
||||
|
||||
@@ -235,8 +232,7 @@ class OffloadingKVEventsConfig:
|
||||
class OffloadingManager(ABC):
|
||||
@abstractmethod
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Checks whether a single block is offloaded and ready to be read.
|
||||
"""Checks whether a single block is offloaded and ready to be read.
|
||||
|
||||
Args:
|
||||
key: the key identifying the block to lookup.
|
||||
@@ -246,6 +242,7 @@ class OffloadingManager(ABC):
|
||||
HIT if the block is offloaded and ready, MISS if not found,
|
||||
HIT_PENDING if found but not yet readable, or RETRY if the
|
||||
lookup should be retried later.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -255,8 +252,7 @@ class OffloadingManager(ABC):
|
||||
keys: Collection[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
) -> LoadStoreSpec:
|
||||
"""
|
||||
Prepare the given blocks to be read.
|
||||
"""Prepare the given blocks to be read.
|
||||
The given blocks will be protected from eviction until
|
||||
complete_load is called.
|
||||
It assumes all given blocks are offloaded.
|
||||
@@ -268,27 +264,28 @@ class OffloadingManager(ABC):
|
||||
Returns:
|
||||
A LoadStoreSpec that can be used by a worker to locate and load
|
||||
the actual offloaded KV data.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark the given blocks as recently used.
|
||||
"""Mark the given blocks as recently used.
|
||||
This could in practice mean moving them to the end of an LRU list.
|
||||
|
||||
Args:
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
def complete_load(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Marks previous blocks that were prepared to load as done loading.
|
||||
"""Marks previous blocks that were prepared to load as done loading.
|
||||
|
||||
Args:
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@@ -298,8 +295,7 @@ class OffloadingManager(ABC):
|
||||
keys: Collection[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
) -> PrepareStoreOutput | None:
|
||||
"""
|
||||
Prepare the given blocks to be offloaded.
|
||||
"""Prepare the given blocks to be offloaded.
|
||||
The given blocks will be protected from eviction until
|
||||
complete_store is called.
|
||||
|
||||
@@ -312,6 +308,7 @@ class OffloadingManager(ABC):
|
||||
where to store them (LoadStoreSpec), and list of blocks that
|
||||
were evicted as a result.
|
||||
None is returned if the blocks cannot be stored.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -321,8 +318,7 @@ class OffloadingManager(ABC):
|
||||
req_context: ReqContext,
|
||||
success: bool = True,
|
||||
):
|
||||
"""
|
||||
Marks blocks which were previously prepared to be stored, as stored.
|
||||
"""Marks blocks which were previously prepared to be stored, as stored.
|
||||
Following this call, the blocks become loadable.
|
||||
If success is False, blocks that were not marked as stored will be
|
||||
removed.
|
||||
@@ -331,25 +327,25 @@ class OffloadingManager(ABC):
|
||||
keys: the keys identifying the blocks.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
success: whether the blocks were stored successfully.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
|
||||
"""
|
||||
Called when a new request is first seen by the scheduler.
|
||||
"""Called when a new request is first seen by the scheduler.
|
||||
|
||||
Returns a RequestOffloadingContext indicating how this request's
|
||||
blocks should be offloaded.
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_request_finished(self, req_context: ReqContext) -> None:
|
||||
"""
|
||||
Called when a request has finished.
|
||||
"""Called when a request has finished.
|
||||
|
||||
By the time this is called, the scheduler will issue no more
|
||||
submit-side calls for this request, such as prepare_store() and
|
||||
@@ -364,12 +360,12 @@ class OffloadingManager(ABC):
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
def take_events(self) -> Iterable[OffloadingEvent]:
|
||||
"""
|
||||
Take the offloading events from the manager.
|
||||
"""Take the offloading events from the manager.
|
||||
|
||||
A tier manager emits only events for storage state it owns. A
|
||||
composing manager may aggregate child event streams, but should not
|
||||
@@ -377,6 +373,7 @@ class OffloadingManager(ABC):
|
||||
|
||||
Yields:
|
||||
New OffloadingEvents collected since the last call.
|
||||
|
||||
"""
|
||||
return ()
|
||||
|
||||
@@ -410,8 +407,7 @@ class OffloadingManager(ABC):
|
||||
|
||||
|
||||
class BlockIDsLoadStoreSpec(LoadStoreSpec, ABC):
|
||||
"""
|
||||
Spec for loading/storing KV blocks from given block numbers.
|
||||
"""Spec for loading/storing KV blocks from given block numbers.
|
||||
|
||||
Subclass semantics differ: GPULoadStoreSpec.block_ids are GPU block
|
||||
indices; CPULoadStoreSpec.block_ids are CPU cache chunk indices.
|
||||
@@ -425,8 +421,7 @@ class BlockIDsLoadStoreSpec(LoadStoreSpec, ABC):
|
||||
|
||||
|
||||
class GPULoadStoreSpec(BlockIDsLoadStoreSpec):
|
||||
"""
|
||||
Spec for loading/storing a KV block to GPU memory.
|
||||
"""Spec for loading/storing a KV block to GPU memory.
|
||||
|
||||
If there are multiple KV groups, the blocks are expected to be
|
||||
ordered by the group index.
|
||||
@@ -460,8 +455,7 @@ class GPULoadStoreSpec(BlockIDsLoadStoreSpec):
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCacheTensor:
|
||||
"""
|
||||
A canonicalized KV cache tensor whose first dimension is num_blocks.
|
||||
"""A canonicalized KV cache tensor whose first dimension is num_blocks.
|
||||
|
||||
With standardized layouts (RFC #42082) num_blocks is always the leading
|
||||
logical dimension.
|
||||
@@ -478,7 +472,8 @@ class CopyRun:
|
||||
"""A strided byte correspondence between this worker's physical page and
|
||||
a canonical page: for i in range(num_fragments), fragment i spans
|
||||
[local_offset + i * local_stride, +fragment_size) in the worker's page and
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically."""
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically.
|
||||
"""
|
||||
|
||||
local_offset: int
|
||||
canonical_offset: int
|
||||
@@ -517,8 +512,7 @@ class CanonicalPageMapping:
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCacheRef:
|
||||
"""
|
||||
Per-layer (or group of layers) reference to a specific (by index)
|
||||
"""Per-layer (or group of layers) reference to a specific (by index)
|
||||
CanonicalKVCacheTensor and records the un-padded page size used by that layer.
|
||||
"""
|
||||
|
||||
@@ -532,8 +526,7 @@ class CanonicalKVCacheRef:
|
||||
|
||||
@dataclass
|
||||
class CanonicalKVCaches:
|
||||
"""
|
||||
Canonicalized block-level representation of the KV caches.
|
||||
"""Canonicalized block-level representation of the KV caches.
|
||||
|
||||
Composed of:
|
||||
- Unique list of KV cache data tensors,
|
||||
@@ -561,7 +554,8 @@ class TransferResult:
|
||||
class OffloadingWorker(ABC):
|
||||
"""Runs in the worker process. Performs async KV transfers for ONE
|
||||
offloaded medium (e.g. CPU). Direction is explicit via submit_store /
|
||||
submit_load, so there is no (src_medium, dst_medium) routing."""
|
||||
submit_load, so there is no (src_medium, dst_medium) routing.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def submit_store(
|
||||
@@ -620,8 +614,7 @@ class OffloadingSpec(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
"""
|
||||
Get an OffloadingManager that will be used
|
||||
"""Get an OffloadingManager that will be used
|
||||
by the scheduler-side offloading connector to track
|
||||
offloaded blocks and manage evictions.
|
||||
"""
|
||||
@@ -629,13 +622,13 @@ class OffloadingSpec(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def get_worker(self, kv_caches: CanonicalKVCaches) -> OffloadingWorker:
|
||||
"""
|
||||
Get an OffloadingWorker that handles async KV transfers for this spec.
|
||||
"""Get an OffloadingWorker that handles async KV transfers for this spec.
|
||||
|
||||
Args:
|
||||
kv_caches: Canonicalized KV caches.
|
||||
|
||||
Returns:
|
||||
An OffloadingWorker instance for this medium.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -80,8 +80,7 @@ def compute_sub_block_ptrs(
|
||||
tensor: torch.Tensor,
|
||||
skip_count: int = 0,
|
||||
):
|
||||
"""
|
||||
Compute byte pointers for sub-blocks of the given block IDs.
|
||||
"""Compute byte pointers for sub-blocks of the given block IDs.
|
||||
|
||||
Each block in block_ids contains blocks_per_chunk sub-blocks.
|
||||
The pointer for sub-block j of block b is:
|
||||
@@ -98,6 +97,7 @@ def compute_sub_block_ptrs(
|
||||
output: pre-allocated pointer array to write pointers into.
|
||||
tensor: the source or destination tensor.
|
||||
skip_count: sub-blocks to skip in the first block.
|
||||
|
||||
"""
|
||||
assert skip_count < blocks_per_chunk
|
||||
|
||||
@@ -126,7 +126,8 @@ def compute_sub_block_ptrs(
|
||||
class CopyPlan(NamedTuple):
|
||||
"""Precomputed fragment-copy template for one data ref under the canonical
|
||||
CPU layout, unrolled from the ref's mapped runs. Offsets are relative to
|
||||
the per-block base pointers on each side."""
|
||||
the per-block base pointers on each side.
|
||||
"""
|
||||
|
||||
frag_offsets_src: np.ndarray
|
||||
frag_offsets_dst: np.ndarray
|
||||
@@ -164,7 +165,8 @@ def _canonical_page_ids(
|
||||
) -> np.ndarray:
|
||||
"""Global canonical page ids matching compute_sub_block_ptrs' enumeration.
|
||||
These identify canonical pages consistently across ranks, so they key
|
||||
CanonicalPageMapping.is_writer rotation."""
|
||||
CanonicalPageMapping.is_writer rotation.
|
||||
"""
|
||||
if blocks_per_chunk == 1:
|
||||
return block_ids[:count]
|
||||
flat = (
|
||||
@@ -177,7 +179,8 @@ def _canonical_block_sizes(
|
||||
layer_refs_per_group: list[list[CanonicalKVCacheRef]], num_tensors: int
|
||||
) -> list[int]:
|
||||
"""Canonical CPU bytes per GPU block for each tensor, taken from the refs'
|
||||
mappings. Requires every ref to carry a mapping."""
|
||||
mappings. Requires every ref to carry a mapping.
|
||||
"""
|
||||
canonical_bytes_per_block = [0] * num_tensors
|
||||
for layer_refs in layer_refs_per_group:
|
||||
for ref in layer_refs:
|
||||
@@ -234,8 +237,7 @@ def _new_descriptor_buffers(
|
||||
|
||||
|
||||
class SingleDirectionOffloadingHandler:
|
||||
"""
|
||||
Handles transfers for a single direction, either CPU->GPU or GPU->CPU.
|
||||
"""Handles transfers for a single direction, either CPU->GPU or GPU->CPU.
|
||||
Transfers are guaranteed to be executed in order of their submission.
|
||||
Each transfer uses a unique CUDA stream, and its stream will start
|
||||
executing only after the streams of previous transfers have finished.
|
||||
@@ -250,8 +252,7 @@ class SingleDirectionOffloadingHandler:
|
||||
gpu_to_cpu: bool,
|
||||
canonical_layout: bool = False,
|
||||
):
|
||||
"""
|
||||
Initialize a SingleDirectionOffloadingHandler.
|
||||
"""Initialize a SingleDirectionOffloadingHandler.
|
||||
|
||||
Args:
|
||||
gpu_tensors: list of GPU KV cache tensors.
|
||||
@@ -259,10 +260,12 @@ class SingleDirectionOffloadingHandler:
|
||||
cpu_tensors: list of CPU KV cache tensors.
|
||||
Each of shape (num_cpu_chunks, cpu_page_size_bytes) with dtype int8.
|
||||
Order should match gpu_tensors.
|
||||
blocks_per_chunk: number of blocks transferred per chunk.
|
||||
layer_refs_per_group: list of CanonicalKVCacheRef per group.
|
||||
gpu_to_cpu: if True, transfer from GPU to CPU; otherwise CPU to GPU.
|
||||
canonical_layout: if True, CPU pages use the canonical layout
|
||||
described by the refs' mappings.
|
||||
|
||||
"""
|
||||
assert len(gpu_tensors) == len(cpu_tensors)
|
||||
assert len(gpu_tensors) > 0
|
||||
@@ -340,7 +343,8 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Upper bound on the number of copy descriptors for a transfer.
|
||||
|
||||
Exact for the direct layout. The canonical path may fill fewer:
|
||||
writer rotation later drops the blocks this rank does not write."""
|
||||
writer rotation later drops the blocks this rank does not write.
|
||||
"""
|
||||
num_copy_ops = 0
|
||||
for g_idx, (group_size, layer_refs) in enumerate(
|
||||
zip(group_sizes, self.layer_refs_per_group)
|
||||
@@ -369,7 +373,8 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Fill one group's copy descriptors for the direct (worker-private)
|
||||
layout: one whole-page copy per (block, ref).
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
num_bytes = 0
|
||||
for data_ref in self.layer_refs_per_group[g_idx]:
|
||||
t_idx = data_ref.tensor_idx
|
||||
@@ -412,7 +417,8 @@ class SingleDirectionOffloadingHandler:
|
||||
scatter each block through the ref's precomputed CopyPlan, keeping
|
||||
only the blocks this rank writes.
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
assert self._canonical_copy_plans is not None
|
||||
# Zero-copy reinterpretation for pointer arithmetic: uint64 and the
|
||||
# buffers' int64 are bit-equivalent for addresses
|
||||
@@ -499,7 +505,8 @@ class SingleDirectionOffloadingHandler:
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Keep only the blocks this rank writes: replicated ranks take turns
|
||||
writing shared canonical pages, keyed by the rank-consistent CPU-side
|
||||
canonical page id."""
|
||||
canonical page id.
|
||||
"""
|
||||
cpu_page_ids = _canonical_page_ids(
|
||||
group_dst,
|
||||
self.dst_blocks_per_chunk,
|
||||
|
||||
@@ -44,8 +44,7 @@ class _RequestCacheAccess:
|
||||
|
||||
|
||||
class CPUOffloadingManager(OffloadingManager):
|
||||
"""
|
||||
An OffloadingManager with a pluggable CachePolicy, resolved by name via
|
||||
"""An OffloadingManager with a pluggable CachePolicy, resolved by name via
|
||||
CachePolicyFactory (built in: "lru", "arc"; external policies can either
|
||||
register their own or be loaded out-of-tree via cache_policy_module_path).
|
||||
|
||||
|
||||
@@ -14,8 +14,7 @@ from vllm.v1.kv_offload.cpu.policies.base import (
|
||||
|
||||
|
||||
class ARCCachePolicy(CachePolicy):
|
||||
"""
|
||||
ARC (Adaptive Replacement Cache) cache policy.
|
||||
"""ARC (Adaptive Replacement Cache) cache policy.
|
||||
|
||||
Data Structures:
|
||||
T1: Recent cache containing chunks accessed once.
|
||||
|
||||
@@ -23,8 +23,7 @@ def order_request_keys(
|
||||
|
||||
|
||||
class ChunkStatus(ctypes.Structure):
|
||||
"""
|
||||
Offloading status for a single chunk of KV data.
|
||||
"""Offloading status for a single chunk of KV data.
|
||||
Holds the following information:
|
||||
|
||||
ref_cnt - the current number of transfers using this chunk as a source.
|
||||
@@ -42,15 +41,12 @@ class ChunkStatus(ctypes.Structure):
|
||||
|
||||
@property
|
||||
def is_ready(self) -> bool:
|
||||
"""
|
||||
Returns whether the chunk is ready to be read.
|
||||
"""
|
||||
"""Returns whether the chunk is ready to be read."""
|
||||
return self.ref_cnt >= 0
|
||||
|
||||
|
||||
class CachePolicy(ABC):
|
||||
"""
|
||||
Encapsulates both chunk organization (data structures) and replacement
|
||||
"""Encapsulates both chunk organization (data structures) and replacement
|
||||
decisions (which chunk to evict). LRU and ARC differ in both dimensions —
|
||||
ARC's ghost lists and target_t1_size live at the intersection of storage
|
||||
and eviction, so they cannot be separated cleanly.
|
||||
@@ -73,12 +69,12 @@ class CachePolicy(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
|
||||
"""
|
||||
Mark chunks as recently used.
|
||||
"""Mark chunks as recently used.
|
||||
|
||||
Args:
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context for the request touching these chunks.
|
||||
|
||||
"""
|
||||
|
||||
def on_store_miss(
|
||||
@@ -120,8 +116,7 @@ class CachePolicy(ABC):
|
||||
def evict(
|
||||
self, n: int, protected: set[OffloadKey]
|
||||
) -> list[tuple[OffloadKey, ChunkStatus]] | None:
|
||||
"""
|
||||
Evict exactly n chunks, skipping any in protected.
|
||||
"""Evict exactly n chunks, skipping any in protected.
|
||||
|
||||
Returns a list of (key, chunk) for the evicted chunks,
|
||||
or None if n evictions cannot be satisfied. The operation is atomic:
|
||||
@@ -133,8 +128,7 @@ class CachePolicy(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def clear(self) -> None:
|
||||
"""
|
||||
Remove ALL chunks regardless of ref_cnt.
|
||||
"""Remove ALL chunks regardless of ref_cnt.
|
||||
|
||||
Ghost lists and adaptive state are also reset.
|
||||
"""
|
||||
|
||||
@@ -57,6 +57,7 @@ class CachePolicyFactory:
|
||||
|
||||
Raises ValueError if the cache policy is neither registered nor
|
||||
resolvable via `module_path`.
|
||||
|
||||
"""
|
||||
if name in cls._registry:
|
||||
return cls._registry[name]()
|
||||
|
||||
@@ -14,8 +14,7 @@ from vllm.v1.kv_offload.cpu.policies.base import (
|
||||
|
||||
|
||||
class LRUCachePolicy(CachePolicy):
|
||||
"""
|
||||
LRU caching policy with logical recency independent of transfer pinning.
|
||||
"""LRU caching policy with logical recency independent of transfer pinning.
|
||||
|
||||
Evictable chunks live in a lazy-invalidating min-heap. A chunk's recency
|
||||
can therefore be updated while it is pinned; when it later becomes
|
||||
|
||||
@@ -69,8 +69,7 @@ def _get_populate_write_fn(
|
||||
|
||||
|
||||
class SharedOffloadRegion:
|
||||
"""
|
||||
Single mmap-backed memory region shared across all workers for a
|
||||
"""Single mmap-backed memory region shared across all workers for a
|
||||
vLLM instance. Workers coordinate via the filesystem: the first worker
|
||||
to open the file with O_EXCL becomes the creator and calls ftruncate;
|
||||
the rest open the existing file and wait until it reaches the expected
|
||||
@@ -264,6 +263,7 @@ class SharedOffloadRegion:
|
||||
|
||||
Args:
|
||||
tensor_page_size: Bytes per chunk for this tensor.
|
||||
|
||||
"""
|
||||
assert self.rank is not None
|
||||
new_offset = self._worker_offset + tensor_page_size
|
||||
@@ -313,6 +313,7 @@ class SharedOffloadRegion:
|
||||
|
||||
Args:
|
||||
tensor_page_size: Canonical bytes per chunk for this tensor.
|
||||
|
||||
"""
|
||||
new_offset = self._canonical_offset + tensor_page_size
|
||||
assert new_offset <= self._row_stride
|
||||
|
||||
@@ -28,7 +28,8 @@ def _all_workers_barrier() -> None:
|
||||
"""Block until every worker rank has reached this point (gloo cpu group).
|
||||
|
||||
A superset of the node-local mmap openers suffices: once the barrier
|
||||
releases, every worker sharing the region file has mapped it."""
|
||||
releases, every worker sharing the region file has mapped it.
|
||||
"""
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_inner_dp_world_group,
|
||||
get_world_group,
|
||||
@@ -161,7 +162,8 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
|
||||
def _uses_shared_region(self) -> bool:
|
||||
"""Whether the worker CPU buffer is the shared mmap region (vs a private
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True."""
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True.
|
||||
"""
|
||||
return current_platform.is_cuda_alike()
|
||||
|
||||
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
|
||||
|
||||
@@ -19,9 +19,7 @@ _CONFIG_FILENAME = "config.json"
|
||||
|
||||
|
||||
class FileMapper:
|
||||
"""
|
||||
FileMapper maps KV blocks (given by their hash) to file names.
|
||||
"""
|
||||
"""FileMapper maps KV blocks (given by their hash) to file names."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -41,8 +39,7 @@ class FileMapper:
|
||||
replicated_layout: bool = False,
|
||||
canonical_format: str | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the file mapper. Each worker constructs its own, but
|
||||
"""Initialize the file mapper. Each worker constructs its own, but
|
||||
`config.json` is shared across workers since rank lives outside the hash.
|
||||
When `parallel_agnostic=True`, tp/pp/pcp/dcp are forced to 1 and rank
|
||||
to 0 so multiple parallelism layouts collapse into the same folder.
|
||||
@@ -136,8 +133,7 @@ class FileMapper:
|
||||
|
||||
@staticmethod
|
||||
def _compute_base_path(root_dir: str, fields: dict) -> str:
|
||||
"""
|
||||
Layout: <root_dir>/<safe_model_name>_<sha256-prefix>/.
|
||||
"""Layout: <root_dir>/<safe_model_name>_<sha256-prefix>/.
|
||||
safe_model_name replaces '/' with '_' so HuggingFace IDs don't nest.
|
||||
"""
|
||||
canonical = json.dumps(fields, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
AsyncLookupManager: per-tier async lookup manager for secondary tier
|
||||
"""AsyncLookupManager: per-tier async lookup manager for secondary tier
|
||||
existence checks.
|
||||
|
||||
Each secondary tier that wants non-blocking lookups composes its own
|
||||
@@ -65,8 +64,7 @@ class LookupState:
|
||||
|
||||
|
||||
class AsyncLookupManager(ABC):
|
||||
"""
|
||||
Per-tier async lookup manager for secondary tier existence checks.
|
||||
"""Per-tier async lookup manager for secondary tier existence checks.
|
||||
|
||||
Each secondary tier that wants non-blocking lookups composes its own
|
||||
AsyncLookupManager instance internally. The manager maintains lookup
|
||||
@@ -126,8 +124,7 @@ class AsyncLookupManager(ABC):
|
||||
def batch_lookup(
|
||||
self, keys: list[OffloadKey], req_context: ReqContext
|
||||
) -> Iterable[bool]:
|
||||
"""
|
||||
Check whether a batch of blocks exist in this tier.
|
||||
"""Check whether a batch of blocks exist in this tier.
|
||||
|
||||
Called from the worker thread — must be synchronous and must not
|
||||
touch the primary tier or scheduler state.
|
||||
@@ -141,13 +138,13 @@ class AsyncLookupManager(ABC):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> bool | None:
|
||||
"""
|
||||
Non-blocking lookup called from the scheduler thread.
|
||||
"""Non-blocking lookup called from the scheduler thread.
|
||||
|
||||
Returns:
|
||||
True — block is present in this tier.
|
||||
False — block is not present in this tier.
|
||||
None — result not yet available; retry next step.
|
||||
|
||||
"""
|
||||
if self._need_to_drain:
|
||||
self.drain_results()
|
||||
@@ -219,7 +216,8 @@ class AsyncLookupManager(ABC):
|
||||
def mark_miss(self, keys: Collection[OffloadKey]) -> None:
|
||||
"""Force the cached verdict for ``keys`` to False after a failed load, so
|
||||
the scheduler stops re-issuing the doomed promotion (livelock, #49176).
|
||||
Keys with no cached entry are skipped."""
|
||||
Keys with no cached entry are skipped.
|
||||
"""
|
||||
for key in keys:
|
||||
state = self._lookup_state.get(key)
|
||||
if state is not None:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Abstract interfaces and data types for the secondary tiering layer.
|
||||
"""
|
||||
"""Abstract interfaces and data types for the secondary tiering layer."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Collection, Iterable
|
||||
@@ -119,8 +117,7 @@ class ParentManager(ABC):
|
||||
|
||||
|
||||
class SecondaryTierManager(ABC):
|
||||
"""
|
||||
Abstract interface for managing a single non-primary offloading tier.
|
||||
"""Abstract interface for managing a single non-primary offloading tier.
|
||||
|
||||
Secondary tiers cannot directly access GPU memory. All data transfers
|
||||
must go through the CPU (primary) tier:
|
||||
@@ -140,12 +137,12 @@ class SecondaryTierManager(ABC):
|
||||
primary_kv_view: memoryview,
|
||||
tier_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory
|
||||
from the registered tier type.
|
||||
"""Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory
|
||||
from the registered tier type.
|
||||
|
||||
"""
|
||||
self._offloading_spec = offloading_spec
|
||||
self._primary_kv_view: memoryview = primary_kv_view
|
||||
@@ -154,8 +151,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
"""Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
@@ -165,13 +161,13 @@ class SecondaryTierManager(ABC):
|
||||
HIT if the chunk is present and ready,
|
||||
MISS if not found,
|
||||
or RETRY if the chunk is being transferred (retry later).
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def submit_store(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit an async job to store chunks from the primary tier to this
|
||||
"""Submit an async job to store chunks from the primary tier to this
|
||||
secondary tier.
|
||||
|
||||
This method must be lightweight and non-blocking: allocate metadata
|
||||
@@ -193,13 +189,13 @@ class SecondaryTierManager(ABC):
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to read from.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit an async job to load chunks from this secondary tier to the
|
||||
"""Submit an async job to load chunks from this secondary tier to the
|
||||
primary tier.
|
||||
|
||||
This method must be lightweight and non-blocking: mark chunks as
|
||||
@@ -218,13 +214,13 @@ class SecondaryTierManager(ABC):
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to write into.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""
|
||||
Return all jobs (loads and stores) that completed since the last call.
|
||||
"""Return all jobs (loads and stores) that completed since the last call.
|
||||
|
||||
The framework uses these results to release resources and finalize
|
||||
transfers.
|
||||
@@ -232,6 +228,7 @@ class SecondaryTierManager(ABC):
|
||||
Returns:
|
||||
Iterable of JobResult objects for jobs finished since the
|
||||
last call.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -248,31 +245,30 @@ class SecondaryTierManager(ABC):
|
||||
return ()
|
||||
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as recently used for eviction policy.
|
||||
"""Mark chunks as recently used for eviction policy.
|
||||
|
||||
Args:
|
||||
keys: Offload keys to mark as recently used.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@abstractmethod
|
||||
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
|
||||
"""
|
||||
Called when a new request is first seen by the scheduler.
|
||||
"""Called when a new request is first seen by the scheduler.
|
||||
|
||||
Returns a RequestOffloadingContext expressing this tier's preference
|
||||
for how chunks should be offloaded for this request.
|
||||
|
||||
Args:
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_request_finished(self, req_context: ReqContext) -> None:
|
||||
"""
|
||||
Called when a request has finished.
|
||||
"""Called when a request has finished.
|
||||
|
||||
By the time this is called, all per-request calls for this request
|
||||
(submit_store, submit_load, touch) have already been issued, and none
|
||||
@@ -283,6 +279,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
Args:
|
||||
req_context: per-request context.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
@@ -300,6 +297,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
Args:
|
||||
context: Per-step context from the scheduler.
|
||||
|
||||
"""
|
||||
return
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
ExampleSecondaryTierManager: A simple in-memory secondary tier.
|
||||
"""ExampleSecondaryTierManager: A simple in-memory secondary tier.
|
||||
|
||||
This implementation provides a minimal secondary tier that stores chunks
|
||||
in memory (using a dictionary) with immediate completion. It serves as a
|
||||
@@ -35,8 +34,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
"""
|
||||
A simple in-memory secondary tier.
|
||||
"""A simple in-memory secondary tier.
|
||||
|
||||
This implementation:
|
||||
- Stores chunks in a dictionary (key -> True)
|
||||
@@ -52,11 +50,14 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
tier_type: str,
|
||||
custom_param: int = 0,
|
||||
):
|
||||
"""
|
||||
Initialize the example secondary tier.
|
||||
"""Initialize the example secondary tier.
|
||||
|
||||
Args:
|
||||
offloading_spec: The offloading spec this tier belongs to.
|
||||
primary_kv_view: Memoryview over the primary tier's KV buffer.
|
||||
tier_type: Name identifying this tier type.
|
||||
custom_param: Dummy parameter demonstrating custom args.
|
||||
|
||||
"""
|
||||
super().__init__(
|
||||
offloading_spec=offloading_spec,
|
||||
@@ -78,8 +79,7 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
"""Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
@@ -87,17 +87,18 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
Returns:
|
||||
HIT if the chunk is present, MISS if not found.
|
||||
|
||||
"""
|
||||
return LookupResult.HIT if key in self.chunks else LookupResult.MISS
|
||||
|
||||
@override
|
||||
def submit_store(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit a job to store chunks from primary tier to this tier.
|
||||
"""Submit a job to store chunks from primary tier to this tier.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and
|
||||
spec for reading chunks from the primary tier.
|
||||
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
@@ -118,12 +119,12 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit a job to load chunks from this tier to primary tier.
|
||||
"""Submit a job to load chunks from this tier to primary tier.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and
|
||||
spec for writing chunks into the primary tier.
|
||||
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
@@ -149,12 +150,12 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""
|
||||
Poll for finished jobs.
|
||||
"""Poll for finished jobs.
|
||||
|
||||
Returns:
|
||||
Iterable of JobResult objects for all jobs that have
|
||||
finished since the last call.
|
||||
|
||||
"""
|
||||
result = self.completed_jobs
|
||||
self.completed_jobs = []
|
||||
@@ -167,7 +168,8 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def drain_jobs(self) -> None:
|
||||
"""Synchronous tier — submit_*() returns only after the operation
|
||||
completes, so there is nothing to wait for."""
|
||||
completes, so there is nothing to wait for.
|
||||
"""
|
||||
return
|
||||
|
||||
def get_num_chunks(self) -> int:
|
||||
|
||||
@@ -71,6 +71,7 @@ class SecondaryTierFactory:
|
||||
Raises:
|
||||
ValueError: If 'type' is missing, or is neither registered nor
|
||||
resolvable via module_path.
|
||||
|
||||
"""
|
||||
tier_type = tier_config.get("type")
|
||||
if not tier_type:
|
||||
|
||||
@@ -94,9 +94,7 @@ def _store_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Store callback: Writes to a temp file then atomically replaces the destination.
|
||||
"""
|
||||
"""Store callback: write to a temp file then atomically replace the target."""
|
||||
# Check if block already exists to avoid redundant writes
|
||||
if os.path.exists(dest_path):
|
||||
return
|
||||
@@ -141,7 +139,8 @@ def _load_block(
|
||||
) -> None:
|
||||
"""Read one KV block from disk; remove the file only on a provable short
|
||||
read (a too-short file is genuine corruption) and leave it untouched on any
|
||||
other error."""
|
||||
other error.
|
||||
"""
|
||||
fd: int | None = None
|
||||
view_slice = view.cast("B")[offset : offset + block_size]
|
||||
o_direct = O_DIRECT if use_o_direct else 0
|
||||
@@ -172,8 +171,7 @@ def batch_store_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Store a batch of KV blocks from a shared buffer to disk in one call.
|
||||
"""Store a batch of KV blocks from a shared buffer to disk in one call.
|
||||
|
||||
Each block buffer[offsets[i] : offsets[i]+block_size] is written atomically
|
||||
to dest_paths[i] via a temp-file rename. Raises on first error.
|
||||
@@ -197,8 +195,7 @@ def batch_load_block(
|
||||
block_size: int,
|
||||
use_o_direct: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Load a batch of KV blocks from disk into a shared buffer in one call.
|
||||
"""Load a batch of KV blocks from disk into a shared buffer in one call.
|
||||
|
||||
Block i is read from source_paths[i] into view[offsets[i] : offsets[i]+block_size].
|
||||
Raises on first error (see _load_block for the delete-on-short-read policy).
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
FileSystemTierManager: Pure-Python file system secondary tier for KV cache offloading.
|
||||
"""FileSystemTierManager: pure-Python filesystem tier for KV cache offloading.
|
||||
|
||||
Store path:
|
||||
Data is written to a temp file (<dest_path.tmp>) via os.write,
|
||||
@@ -84,8 +83,7 @@ class FsAsyncLookupManager(AsyncLookupManager):
|
||||
|
||||
|
||||
class FileSystemTierManager(SecondaryTierManager):
|
||||
"""
|
||||
Pure-Python disk-backed secondary tier.
|
||||
"""Pure-Python disk-backed secondary tier.
|
||||
|
||||
Read-priority threads service load jobs preferentially; write-priority
|
||||
threads service store jobs preferentially. Both groups can drain either
|
||||
@@ -118,20 +116,20 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
enable_kv_events: bool = False,
|
||||
locality: str | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Contains normalized offloading configuration and
|
||||
blocks_per_chunk.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
root_dir: Root directory for block files.
|
||||
n_read_threads: Number of read-priority I/O threads.
|
||||
n_write_threads: Number of write-priority I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
"""Args:
|
||||
offloading_spec: Contains normalized offloading configuration and
|
||||
blocks_per_chunk.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
root_dir: Root directory for block files.
|
||||
n_read_threads: Number of read-priority I/O threads.
|
||||
n_write_threads: Number of write-priority I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
self.locality = Locality(locality) if locality is not None else None
|
||||
@@ -271,7 +269,8 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Collect finished jobs; a failed promotion marks only its failed keys
|
||||
as a miss here (scheduler thread)."""
|
||||
as a miss here (scheduler thread).
|
||||
"""
|
||||
results = []
|
||||
for job_id, success, transfer_time in self._pool.get_finished():
|
||||
if self.events is not None:
|
||||
@@ -333,8 +332,7 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
|
||||
@override
|
||||
def shutdown(self) -> None:
|
||||
"""
|
||||
Release resources held by this tier.
|
||||
"""Release resources held by this tier.
|
||||
|
||||
Shuts down the lookup manager and the thread pool,
|
||||
clearing pending tasks and waiting for active threads to complete.
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Thread pool:
|
||||
Two queues (load, store) and two sets of threads:
|
||||
- Load-priority threads: drain the load queue first, then the store queue.
|
||||
- Store-priority threads: drain the store queue first, then the load queue.
|
||||
Load jobs are enqueued to the load queue; store jobs to the store queue.
|
||||
"""Thread pool:
|
||||
Two queues (load, store) and two sets of threads:
|
||||
- Load-priority threads: drain the load queue first, then the store queue.
|
||||
- Store-priority threads: drain the store queue first, then the load queue.
|
||||
Load jobs are enqueued to the load queue; store jobs to the store queue.
|
||||
"""
|
||||
|
||||
import threading
|
||||
@@ -20,8 +19,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class JobState:
|
||||
"""
|
||||
Thread-safe completion tracker for a set of per-block I/O tasks.
|
||||
"""Thread-safe completion tracker for a set of per-block I/O tasks.
|
||||
|
||||
Each task calls task_done(success) when it finishes.
|
||||
"""
|
||||
@@ -50,7 +48,7 @@ class JobState:
|
||||
def task_done(
|
||||
self, success: bool, transfer_time: float
|
||||
) -> tuple[bool, bool, float]:
|
||||
"""Returns if job completed and success flag"""
|
||||
"""Returns if job completed and success flag."""
|
||||
with self._lock:
|
||||
self._completed += 1
|
||||
self._transfer_time += transfer_time
|
||||
@@ -60,8 +58,7 @@ class JobState:
|
||||
|
||||
|
||||
class DualQueueThreadPool:
|
||||
"""
|
||||
Thread pool with two task queues (load and store) and two thread groups.
|
||||
"""Thread pool with two task queues (load and store) and two thread groups.
|
||||
|
||||
Load-priority threads drain the load queue first, then fall back to the
|
||||
store queue. Store-priority threads do the reverse. Both queues share
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
TieringOffloadingManager: Multi-tier KV cache offloading orchestrator.
|
||||
"""TieringOffloadingManager: Multi-tier KV cache offloading orchestrator.
|
||||
|
||||
This manager coordinates between a CPU primary tier (with direct GPU access)
|
||||
and zero or more secondary tiers (Storage, Network, etc.) to provide
|
||||
@@ -144,7 +143,8 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
|
||||
|
||||
class _SecondaryTierFacingParent(ParentManager):
|
||||
"""Wrapper that implements ParentManager by delegating to the
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier."""
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier.
|
||||
"""
|
||||
|
||||
__slots__ = ("_m", "_origin_idx")
|
||||
|
||||
@@ -174,8 +174,7 @@ class _SecondaryTierFacingParent(ParentManager):
|
||||
|
||||
|
||||
class TieringOffloadingManager(OffloadingManager):
|
||||
"""
|
||||
Orchestrates multi-tier KV cache offloading.
|
||||
"""Orchestrates multi-tier KV cache offloading.
|
||||
|
||||
This manager coordinates between a CPU primary tier (with direct GPU access)
|
||||
and zero or more secondary tiers (Storage, Network, etc.) to provide
|
||||
@@ -194,13 +193,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
primary_tier: CPUPrimaryTierOffloadingManager,
|
||||
secondary_tiers: list[SecondaryTierManager] | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the TieringOffloadingManager.
|
||||
"""Initialize the TieringOffloadingManager.
|
||||
|
||||
Args:
|
||||
primary_tier: The primary tier manager (CPU-based).
|
||||
secondary_tiers: List of secondary tier managers (e.g., Storage,
|
||||
Network). Can be None or empty list.
|
||||
|
||||
"""
|
||||
self.primary_tier: CPUPrimaryTierOffloadingManager = primary_tier
|
||||
self.secondary_tiers = secondary_tiers or []
|
||||
@@ -259,8 +258,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
return self._jobs.pop(job_id, None)
|
||||
|
||||
def _maybe_process_finished_jobs(self):
|
||||
"""
|
||||
Poll secondary tiers for completed jobs (at most once per step).
|
||||
"""Poll secondary tiers for completed jobs (at most once per step).
|
||||
|
||||
Guarded by _processed_jobs_this_step: the first call in an engine step
|
||||
does the actual polling; subsequent calls are no-ops. The flag is reset
|
||||
@@ -306,8 +304,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
)
|
||||
|
||||
def _process_finished_jobs(self):
|
||||
"""
|
||||
Unconditionally poll all secondary tiers for completed jobs.
|
||||
"""Unconditionally poll all secondary tiers for completed jobs.
|
||||
|
||||
This method:
|
||||
1. Calls get_finished_jobs() on each secondary tier
|
||||
@@ -350,8 +347,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
*,
|
||||
exclude_tier_idx: int | None = None,
|
||||
) -> LookupResult:
|
||||
"""
|
||||
Check whether a single chunk is offloaded and ready.
|
||||
"""Check whether a single chunk is offloaded and ready.
|
||||
|
||||
Algorithm:
|
||||
1. Process any completed async jobs first.
|
||||
@@ -362,6 +358,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Args:
|
||||
key: Chunk hash to look up.
|
||||
req_context: Per-request context.
|
||||
exclude_tier_idx: Skip this tier index during the lookup.
|
||||
|
||||
Returns:
|
||||
HIT — chunk is ready in the primary tier.
|
||||
@@ -370,6 +367,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
RETRY — promotion started or a secondary tier is busy.
|
||||
MISS — chunk not found in any tier, or primary is full
|
||||
and cannot accept a promotion.
|
||||
|
||||
"""
|
||||
# Poll first so a promotion that finished since the last call is
|
||||
# already reflected as HIT (not stale HIT_PENDING/MISS) below, and
|
||||
@@ -432,8 +430,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
key: OffloadKey,
|
||||
req_context: ReqContext,
|
||||
) -> bool:
|
||||
"""
|
||||
Queue a chunk for promotion from a secondary tier to the primary tier.
|
||||
"""Queue a chunk for promotion from a secondary tier to the primary tier.
|
||||
|
||||
Allocates space in the primary tier immediately (sets ref_cnt=-1 so
|
||||
subsequent lookups within the same step see the slot as in-flight),
|
||||
@@ -448,6 +445,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Returns:
|
||||
True if promotion was initiated, False if primary tier is full.
|
||||
|
||||
"""
|
||||
# Allocate space in primary tier for promoted chunk.
|
||||
# Must happen immediately so primary.lookup() returns None (in-flight)
|
||||
@@ -505,8 +503,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
def prepare_load(
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> LoadStoreSpec:
|
||||
"""
|
||||
Prepare chunks to be loaded from primary tier to GPU.
|
||||
"""Prepare chunks to be loaded from primary tier to GPU.
|
||||
|
||||
Callers only pass keys already confirmed HIT by lookup() earlier this
|
||||
step.
|
||||
@@ -520,17 +517,18 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Returns:
|
||||
LoadStoreSpec for reading from primary tier.
|
||||
|
||||
"""
|
||||
return self.primary_tier.prepare_load(keys, req_context)
|
||||
|
||||
@override
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as recently used in all tiers.
|
||||
"""Mark chunks as recently used in all tiers.
|
||||
|
||||
Args:
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
self.primary_tier.touch(keys, req_context)
|
||||
for tier in self.secondary_tiers:
|
||||
@@ -538,8 +536,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
@override
|
||||
def complete_load(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark chunks as done loading from primary tier to GPU.
|
||||
"""Mark chunks as done loading from primary tier to GPU.
|
||||
|
||||
This decrements ref_cnt on the chunks in the primary tier, allowing
|
||||
them to be evicted again.
|
||||
@@ -547,6 +544,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Args:
|
||||
keys: Chunks that finished loading.
|
||||
req_context: Per-request context.
|
||||
|
||||
"""
|
||||
self.primary_tier.complete_load(keys, req_context)
|
||||
|
||||
@@ -554,8 +552,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
def prepare_store(
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> PrepareStoreOutput | None:
|
||||
"""
|
||||
Prepare chunks to be stored from GPU to primary tier.
|
||||
"""Prepare chunks to be stored from GPU to primary tier.
|
||||
|
||||
CRITICAL: This method calls _maybe_process_finished_jobs() FIRST to ensure
|
||||
that any completed async transfers have their ref_cnt decremented
|
||||
@@ -571,6 +568,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
Returns:
|
||||
PrepareStoreOutput describing where to store chunks and what was
|
||||
evicted, or None if store cannot proceed.
|
||||
|
||||
"""
|
||||
# Step 1: Poll for completed async jobs FIRST
|
||||
# _process_finished_jobs() handles two kinds of completions here:
|
||||
@@ -617,8 +615,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
request_level_tiers: set[int],
|
||||
) -> None:
|
||||
"""
|
||||
For tiers that requested request-level policy, submit_store() for
|
||||
"""For tiers that requested request-level policy, submit_store() for
|
||||
chunks that are already present in the primary tier.
|
||||
|
||||
A key whose primary write is still in flight (HIT_PENDING) cannot be
|
||||
@@ -674,8 +671,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
success: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Mark chunks as done storing from GPU to primary tier.
|
||||
"""Mark chunks as done storing from GPU to primary tier.
|
||||
|
||||
This is where secondary tier cascading happens — after chunks are
|
||||
confirmed to be in the primary tier, they are cascaded to ALL
|
||||
@@ -691,6 +687,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
keys: Chunks that finished storing.
|
||||
success: Whether the GPU→primary transfer succeeded.
|
||||
req_context: Per-request context forwarded to primary.prepare_read().
|
||||
|
||||
"""
|
||||
# Step 1: Complete store in primary tier (makes chunks loadable)
|
||||
self.primary_tier.complete_store(keys, req_context, success)
|
||||
@@ -748,8 +745,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
*,
|
||||
exclude_tier_idx: int | None = None,
|
||||
) -> RequestOffloadingContext:
|
||||
"""
|
||||
Query each secondary tier for its offload policy preference.
|
||||
"""Query each secondary tier for its offload policy preference.
|
||||
|
||||
Returns REQUEST_LEVEL if ANY secondary tier wants request-level.
|
||||
Only stores REQUEST_LEVEL tier decisions for use in prepare_store.
|
||||
@@ -858,6 +854,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
Yields:
|
||||
New OffloadingEvents collected by each tier since the last call.
|
||||
|
||||
"""
|
||||
yield from self.primary_tier.take_events()
|
||||
for tier in self.secondary_tiers:
|
||||
|
||||
@@ -113,19 +113,19 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
enable_kv_events: bool = False,
|
||||
locality: str | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
store_config: Object store connection parameters (see ObjStoreConfig).
|
||||
prefix: Key prefix prepended to all object keys.
|
||||
io_threads: Number of NIXL I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
"""Args:
|
||||
offloading_spec: Offloading configuration.
|
||||
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
|
||||
tier_type: Tier type identifier, set by SecondaryTierFactory.
|
||||
store_config: Object store connection parameters (see ObjStoreConfig).
|
||||
prefix: Key prefix prepended to all object keys.
|
||||
io_threads: Number of NIXL I/O threads.
|
||||
enable_kv_events: Emit BlockStored KV events for blocks
|
||||
successfully stored to this tier. Effective only when KV
|
||||
cache events are enabled globally (kv_events_config).
|
||||
locality: Whether this tier's storage is LOCAL or REMOTE relative
|
||||
to the publishing vLLM instance.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
self.locality = Locality(locality) if locality is not None else None
|
||||
@@ -308,7 +308,8 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def _poll_active_transfers(self) -> None:
|
||||
"""Poll all in-flight transfers once; move newly-completed (success or
|
||||
failure) into ``_pending_results`` and release their NIXL handles."""
|
||||
failure) into ``_pending_results`` and release their NIXL handles.
|
||||
"""
|
||||
for job_id, entry in list(self._transfers.items()):
|
||||
try:
|
||||
state = self._agent.check_xfer_state(entry.xfer_handle)
|
||||
@@ -363,7 +364,8 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Poll transfers; a failed promotion marks its cached verdicts False
|
||||
here (scheduler thread)."""
|
||||
here (scheduler thread).
|
||||
"""
|
||||
self._poll_active_transfers()
|
||||
results = self._pending_results
|
||||
self._pending_results = []
|
||||
|
||||
@@ -139,6 +139,7 @@ class ControlTransport(ABC):
|
||||
A connection to peer_id that is registered but no longer alive is
|
||||
retired and replaced; a live one is a duplicate and must not be
|
||||
replaced.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -158,6 +159,7 @@ class ControlTransport(ABC):
|
||||
The returned sequence is read-only — callers must not mutate
|
||||
it. The caller is responsible for creating sessions for
|
||||
these connections.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
ZMQ-based transport layer for P2P KV cache sharing.
|
||||
"""ZMQ-based transport layer for P2P KV cache sharing.
|
||||
|
||||
Provides ZmqConnection (per-peer messaging) and ZmqTransport (connection
|
||||
management). Message-content agnostic.
|
||||
|
||||
@@ -87,6 +87,7 @@ class PollResult(NamedTuple):
|
||||
Attributes:
|
||||
done: Transfer IDs that completed successfully.
|
||||
failed: Transfer IDs that failed (error, timeout, etc.).
|
||||
|
||||
"""
|
||||
|
||||
done: Sequence[int]
|
||||
@@ -174,6 +175,7 @@ class DataTransport(ABC):
|
||||
base_addr: Base address of the peer's block memory region.
|
||||
num_blocks: Number of blocks in the peer's region.
|
||||
block_len: Size of each block (must match local block_len).
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -203,6 +205,7 @@ class DataTransport(ABC):
|
||||
Returns:
|
||||
A unique transfer_id (int) to track this transfer, or
|
||||
None if the peer is not registered or submission failed.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -224,6 +227,7 @@ class DataTransport(ABC):
|
||||
Completed/failed transfers are removed from the inflight set.
|
||||
|
||||
Must be called periodically to drive progress checking.
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
@@ -255,6 +259,7 @@ class DataTransport(ABC):
|
||||
For mode="wait", the subset of *transfer_ids* still
|
||||
tracked as inflight after the cancel attempt. For
|
||||
mode="immediate", always [].
|
||||
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL.
|
||||
"""
|
||||
"""NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2PSecondaryTierManager: Secondary tier for P2P KV cache sharing.
|
||||
"""P2PSecondaryTierManager: Secondary tier for P2P KV cache sharing.
|
||||
|
||||
Owns transports and a single bidirectional P2PSession per remote peer.
|
||||
"""
|
||||
@@ -135,7 +134,8 @@ class P2PDestInfo:
|
||||
|
||||
def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
"""Parse the consumer sub-dict (PD ``remote_prefiller`` or symmetric
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete."""
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete.
|
||||
"""
|
||||
role = _remote_prefiller_params(kv_params)
|
||||
do_probe = False
|
||||
if role is None:
|
||||
@@ -156,7 +156,8 @@ def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
|
||||
def _parse_dest(kv_params: dict | None) -> P2PDestInfo | None:
|
||||
"""Parse the producer ``remote_decoder`` sub-dict into a ``P2PDestInfo``,
|
||||
or None if the block is absent (not a remote-decode request)."""
|
||||
or None if the block is absent (not a remote-decode request).
|
||||
"""
|
||||
role = _remote_decoder_params(kv_params)
|
||||
if role is None:
|
||||
return None
|
||||
@@ -264,6 +265,7 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
Raises:
|
||||
ValueError: If ``unbound_store_timeout_s`` is not a positive
|
||||
number, or anything convertible to one.
|
||||
|
||||
"""
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
try:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2P KV cache sharing protocol constants and documentation.
|
||||
"""P2P KV cache sharing protocol constants and documentation.
|
||||
|
||||
Protocol Overview
|
||||
=================
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
P2PSession — bidirectional session combining client + server roles.
|
||||
"""P2PSession — bidirectional session combining client + server roles.
|
||||
|
||||
A single P2PSession per remote peer handles BOTH directions of the P2P
|
||||
protocol on one ControlConnection: it can request blocks from the peer
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
TieringOffloadingSpec: Spec for multi-tier KV cache offloading.
|
||||
"""TieringOffloadingSpec: Spec for multi-tier KV cache offloading.
|
||||
|
||||
This spec creates a TieringOffloadingManager with a CPU primary tier
|
||||
and configurable secondary tiers (e.g., Storage, Network).
|
||||
@@ -82,8 +81,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
"""
|
||||
Spec for multi-tier KV cache offloading.
|
||||
"""Spec for multi-tier KV cache offloading.
|
||||
|
||||
Creates a TieringOffloadingManager with:
|
||||
- Primary tier: CPU (LRU or ARC eviction policy)
|
||||
@@ -276,8 +274,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
|
||||
@override
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
"""
|
||||
Get the TieringOffloadingManager.
|
||||
"""Get the TieringOffloadingManager.
|
||||
|
||||
Creates a TieringOffloadingManager with:
|
||||
- Primary tier: CPU (LRU or ARC)
|
||||
@@ -285,6 +282,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
|
||||
Returns:
|
||||
TieringOffloadingManager instance
|
||||
|
||||
"""
|
||||
if not self._manager:
|
||||
if int(self.extra_config.get("store_threshold", 0)) >= 2:
|
||||
@@ -416,7 +414,8 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
"""Require a mapping on every ref and record layer portability.
|
||||
|
||||
Fails loudly rather than persist direct-layout bytes under a
|
||||
canonical format identity."""
|
||||
canonical format identity.
|
||||
"""
|
||||
all_refs = [
|
||||
ref for group_refs in kv_caches.group_data_refs for ref in group_refs
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user