[Refactor][kv_offload]: rename block→chunk (#52615)
Signed-off-by: Ronen Schaffer <ronen.schaffer@ibm.com>
This commit is contained in:
@@ -114,17 +114,17 @@ class LookupResult(Enum):
|
||||
|
||||
|
||||
class OffloadPolicy(Enum):
|
||||
# Offload only newly-computed blocks as they arrive; prefix-hit
|
||||
# blocks (already offloaded by a prior request) are skipped.
|
||||
BLOCK_LEVEL = "block_level"
|
||||
# Offload all blocks for the request, including prefix hits.
|
||||
# Offload only newly-computed chunks as they arrive; prefix-hit
|
||||
# chunks (already offloaded by a prior request) are skipped.
|
||||
CHUNK_LEVEL = "chunk_level"
|
||||
# Offload all chunks for the request, including prefix hits.
|
||||
# Used by tiers that need the complete KV context for a request.
|
||||
REQUEST_LEVEL = "request_level"
|
||||
|
||||
|
||||
@dataclass
|
||||
class RequestOffloadingContext:
|
||||
policy: OffloadPolicy = OffloadPolicy.BLOCK_LEVEL
|
||||
policy: OffloadPolicy = OffloadPolicy.CHUNK_LEVEL
|
||||
|
||||
|
||||
class ScheduleEndContext(NamedTuple):
|
||||
@@ -400,6 +400,9 @@ class OffloadingManager(ABC):
|
||||
class BlockIDsLoadStoreSpec(LoadStoreSpec, ABC):
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(self, block_ids: list[int]):
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import numpy as np
|
||||
|
||||
from vllm.v1.kv_offload.base import BlockIDsLoadStoreSpec
|
||||
|
||||
|
||||
@@ -12,6 +14,13 @@ class CPUOffloadingMetrics:
|
||||
|
||||
|
||||
class CPULoadStoreSpec(BlockIDsLoadStoreSpec):
|
||||
"""Spec for loading/storing KV chunks to/from CPU memory.
|
||||
|
||||
The inherited block_ids field holds chunk indices into the
|
||||
CPU cache (not GPU block IDs). The chunk_ids alias exposes
|
||||
the same array under the name used by the tiering layer.
|
||||
"""
|
||||
Spec for loading/storing a KV block to CPU memory.
|
||||
"""
|
||||
|
||||
@property
|
||||
def chunk_ids(self) -> np.ndarray:
|
||||
return self.block_ids
|
||||
|
||||
@@ -257,7 +257,7 @@ class SingleDirectionOffloadingHandler:
|
||||
gpu_tensors: list of GPU KV cache tensors.
|
||||
Each of shape (num_gpu_blocks, gpu_page_size_bytes) with dtype int8.
|
||||
cpu_tensors: list of CPU KV cache tensors.
|
||||
Each of shape (num_cpu_blocks, cpu_page_size_bytes) with dtype int8.
|
||||
Each of shape (num_cpu_chunks, cpu_page_size_bytes) with dtype int8.
|
||||
Order should match gpu_tensors.
|
||||
layer_refs_per_group: list of CanonicalKVCacheRef per group.
|
||||
gpu_to_cpu: if True, transfer from GPU to CPU; otherwise CPU to GPU.
|
||||
@@ -527,20 +527,20 @@ class SingleDirectionOffloadingHandler:
|
||||
# 1. GPU -> CPU
|
||||
# 2. CPU -> GPU
|
||||
#
|
||||
# transfers are also to CPU blocks, EXCEPT MAYBE for the first and last block.
|
||||
# i.e. the first and last CPU blocks in src_blocks can match against
|
||||
# transfers are also to CPU chunks, EXCEPT MAYBE for the first and last chunk.
|
||||
# i.e. the first and last CPU chunks in src_blocks can match against
|
||||
# a smaller (byte-wise) set of GPU blocks in dst_blocks.
|
||||
# In such cases, we may need to skip some gpu-sized sub-blocks,
|
||||
# and start reading/writing from the middle of the first CPU block.
|
||||
# and start reading/writing from the middle of the first CPU chunk.
|
||||
# If we have multiple KV cache groups (when using HMA with hybrid models),
|
||||
# we may have a partial first/last CPU block per each group.
|
||||
# we may have a partial first/last CPU chunk per each group.
|
||||
# The group_sizes parameter encodes the size of each group of blocks
|
||||
# in the GPU dst_blocks.
|
||||
# If group_sizes is None, we assume all blocks belong to a single group.
|
||||
# The logical_offset parameter maps each group of blocks to its logical
|
||||
# offset inside the request, counting in GPU blocks.
|
||||
# This allows us to find the correct starting position
|
||||
# in the matching first CPU block.
|
||||
# in the matching first CPU chunk.
|
||||
|
||||
# extract group_sizes from the GPU spec
|
||||
gpu_spec = src_spec if self.gpu_to_cpu else dst_spec
|
||||
@@ -751,7 +751,7 @@ class CPUOffloadingWorker(OffloadingWorker):
|
||||
self,
|
||||
kv_caches: CanonicalKVCaches,
|
||||
blocks_per_chunk: int,
|
||||
num_cpu_blocks: int,
|
||||
num_cpu_chunks: int,
|
||||
mmap_region: SharedOffloadRegion | None = None,
|
||||
canonical_layout: bool = False,
|
||||
):
|
||||
@@ -790,16 +790,16 @@ class CPUOffloadingWorker(OffloadingWorker):
|
||||
else:
|
||||
t0 = time.monotonic()
|
||||
cpu_tensor = torch.zeros(
|
||||
(num_cpu_blocks, cpu_page_size_bytes),
|
||||
(num_cpu_chunks, cpu_page_size_bytes),
|
||||
dtype=torch.int8,
|
||||
device="cpu",
|
||||
pin_memory=pin_memory,
|
||||
)
|
||||
logger.debug(
|
||||
"torch.zeros pinned tensor %d×%d (%.2f GB): %.3f s",
|
||||
num_cpu_blocks,
|
||||
num_cpu_chunks,
|
||||
cpu_page_size_bytes,
|
||||
num_cpu_blocks * cpu_page_size_bytes / 1e9,
|
||||
num_cpu_chunks * cpu_page_size_bytes / 1e9,
|
||||
time.monotonic() - t0,
|
||||
)
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ from vllm.v1.kv_offload.cpu.common import (
|
||||
CPULoadStoreSpec,
|
||||
CPUOffloadingMetrics,
|
||||
)
|
||||
from vllm.v1.kv_offload.cpu.policies.base import BlockStatus, CachePolicy
|
||||
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
|
||||
from vllm.v1.kv_offload.cpu.policies.factory import CachePolicyFactory
|
||||
|
||||
|
||||
@@ -34,14 +34,14 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
register their own or be loaded out-of-tree via cache_policy_module_path).
|
||||
|
||||
The manager owns all shared logic: ref-counting, event emission,
|
||||
block pool management, and the prepare_store/complete_store skeletons.
|
||||
Policy-specific block organization and eviction decisions are delegated
|
||||
chunk pool management, and the prepare_store/complete_store skeletons.
|
||||
Policy-specific chunk organization and eviction decisions are delegated
|
||||
to the CachePolicy implementation.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_blocks: int,
|
||||
num_chunks: int,
|
||||
cache_policy: str = "lru",
|
||||
cache_policy_module_path: str | None = None,
|
||||
enable_events: bool = False,
|
||||
@@ -49,59 +49,59 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
max_tracker_size: int = 64_000,
|
||||
):
|
||||
self.medium: Medium = Medium.CPU
|
||||
self._num_blocks: int = num_blocks
|
||||
self._num_allocated_blocks: int = 0
|
||||
self._num_chunks: int = num_chunks
|
||||
self._num_allocated_chunks: int = 0
|
||||
self._free_list: list[int] = []
|
||||
self.events: list[OffloadingEvent] | None = [] if enable_events else None
|
||||
policy_cls = CachePolicyFactory.get_cache_policy_cls(
|
||||
cache_policy, cache_policy_module_path
|
||||
)
|
||||
self._policy: CachePolicy = policy_cls(cache_capacity=num_blocks)
|
||||
# Track the number of blocks in the cache that are evictable. i.e. ref_cnt 0.
|
||||
self._num_evictable_cache_blocks: int = 0
|
||||
# Track blocks with an in-flight store (ref_cnt -1, not yet completed).
|
||||
self._num_write_pending_blocks: int = 0
|
||||
self._policy: CachePolicy = policy_cls(cache_capacity=num_chunks)
|
||||
# Track the number of chunks in the cache that are evictable. i.e. ref_cnt 0.
|
||||
self._num_evictable_cache_chunks: int = 0
|
||||
# Track chunks with an in-flight store (ref_cnt -1, not yet completed).
|
||||
self._num_write_pending_chunks: int = 0
|
||||
|
||||
self.store_threshold: int = store_threshold
|
||||
self.max_tracker_size: int = max_tracker_size
|
||||
self.stores_skipped_in_current_batch: int = 0
|
||||
self.allocation_sizes_in_current_batch: list[int] = []
|
||||
|
||||
# Number of block references. It is ordered so can evict the LRU entry in O(1).
|
||||
# Number of chunk references. It is ordered so can evict the LRU entry in O(1).
|
||||
self.counts: OrderedDict[OffloadKey, int] | None = (
|
||||
OrderedDict() if store_threshold >= 2 else None
|
||||
)
|
||||
|
||||
# --- block pool ---
|
||||
# --- chunk pool ---
|
||||
|
||||
def _get_num_free_blocks(self) -> int:
|
||||
return len(self._free_list) + self._num_blocks - self._num_allocated_blocks
|
||||
def _get_num_free_chunks(self) -> int:
|
||||
return len(self._free_list) + self._num_chunks - self._num_allocated_chunks
|
||||
|
||||
def _allocate_blocks(self, keys: list[OffloadKey]) -> list[BlockStatus]:
|
||||
num_fresh = min(len(keys), self._num_blocks - self._num_allocated_blocks)
|
||||
def _allocate_chunks(self, keys: list[OffloadKey]) -> list[ChunkStatus]:
|
||||
num_fresh = min(len(keys), self._num_chunks - self._num_allocated_chunks)
|
||||
num_reused = len(keys) - num_fresh
|
||||
assert len(self._free_list) >= num_reused
|
||||
|
||||
# allocate fresh blocks
|
||||
blocks: list[BlockStatus] = []
|
||||
# allocate fresh chunks
|
||||
chunks: list[ChunkStatus] = []
|
||||
for _ in range(num_fresh):
|
||||
blocks.append(BlockStatus(self._num_allocated_blocks))
|
||||
self._num_allocated_blocks += 1
|
||||
chunks.append(ChunkStatus(self._num_allocated_chunks))
|
||||
self._num_allocated_chunks += 1
|
||||
|
||||
# allocate reused blocks
|
||||
# allocate reused chunks
|
||||
for _ in range(num_reused):
|
||||
blocks.append(BlockStatus(self._free_list.pop()))
|
||||
return blocks
|
||||
chunks.append(ChunkStatus(self._free_list.pop()))
|
||||
return chunks
|
||||
|
||||
def _free_block(self, block: BlockStatus) -> None:
|
||||
self._free_list.append(block.block_id)
|
||||
def _free_chunk(self, chunk: ChunkStatus) -> None:
|
||||
self._free_list.append(chunk.chunk_id)
|
||||
|
||||
def _get_load_store_spec(
|
||||
self,
|
||||
keys: Iterable[OffloadKey],
|
||||
blocks: Iterable[BlockStatus],
|
||||
chunks: Iterable[ChunkStatus],
|
||||
) -> CPULoadStoreSpec:
|
||||
return CPULoadStoreSpec([block.block_id for block in blocks])
|
||||
return CPULoadStoreSpec([chunk.chunk_id for chunk in chunks])
|
||||
|
||||
def _record_accesses(self, keys: Collection[OffloadKey]) -> None:
|
||||
"""Record an offer without evicting its tracked candidates."""
|
||||
@@ -132,10 +132,10 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
|
||||
@override
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
block = self._policy.get(key)
|
||||
if block is None:
|
||||
chunk = self._policy.get(key)
|
||||
if chunk is None:
|
||||
return LookupResult.MISS
|
||||
if not block.is_ready:
|
||||
if not chunk.is_ready:
|
||||
return LookupResult.HIT_PENDING
|
||||
return LookupResult.HIT
|
||||
|
||||
@@ -145,18 +145,18 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
keys: Collection[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
) -> LoadStoreSpec:
|
||||
blocks = []
|
||||
chunks = []
|
||||
for key in keys:
|
||||
block = self._policy.get(key)
|
||||
assert block is not None, f"Block {key!r} not found in cache"
|
||||
assert block.is_ready, f"Block {key!r} is not ready for reading"
|
||||
if block.ref_cnt == 0:
|
||||
chunk = self._policy.get(key)
|
||||
assert chunk is not None, f"Chunk {key!r} not found in cache"
|
||||
assert chunk.is_ready, f"Chunk {key!r} is not ready for reading"
|
||||
if chunk.ref_cnt == 0:
|
||||
self._policy.mark_non_evictable(key)
|
||||
self._num_evictable_cache_blocks -= 1 # ref_cnt 0 -> 1
|
||||
assert self._num_evictable_cache_blocks >= 0
|
||||
block.ref_cnt += 1
|
||||
blocks.append(block)
|
||||
return self._get_load_store_spec(keys, blocks)
|
||||
self._num_evictable_cache_chunks -= 1 # ref_cnt 0 -> 1
|
||||
assert self._num_evictable_cache_chunks >= 0
|
||||
chunk.ref_cnt += 1
|
||||
chunks.append(chunk)
|
||||
return self._get_load_store_spec(keys, chunks)
|
||||
|
||||
@override
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext) -> None:
|
||||
@@ -167,12 +167,12 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> None:
|
||||
for key in keys:
|
||||
block = self._policy.get(key)
|
||||
assert block is not None, f"Block {key!r} not found"
|
||||
assert block.ref_cnt > 0, f"Block {key!r} ref_cnt is already 0"
|
||||
block.ref_cnt -= 1
|
||||
if block.ref_cnt == 0:
|
||||
self._num_evictable_cache_blocks += 1 # ref_cnt 1 -> 0
|
||||
chunk = self._policy.get(key)
|
||||
assert chunk is not None, f"Chunk {key!r} not found"
|
||||
assert chunk.ref_cnt > 0, f"Chunk {key!r} ref_cnt is already 0"
|
||||
chunk.ref_cnt -= 1
|
||||
if chunk.ref_cnt == 0:
|
||||
self._num_evictable_cache_chunks += 1 # ref_cnt 1 -> 0
|
||||
self._policy.mark_evictable(key)
|
||||
|
||||
@override
|
||||
@@ -186,7 +186,7 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
self._record_accesses(keys)
|
||||
keys = [k for k in keys if self.counts.get(k, 0) >= self.store_threshold]
|
||||
self.stores_skipped_in_current_batch += num_keys - len(keys)
|
||||
# filter out blocks that are already stored
|
||||
# filter out chunks that are already stored
|
||||
keys_to_store = [k for k in keys if self._policy.get(k) is None]
|
||||
|
||||
if not keys_to_store:
|
||||
@@ -197,29 +197,29 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
)
|
||||
|
||||
self.allocation_sizes_in_current_batch.append(len(keys_to_store))
|
||||
num_blocks_to_evict = len(keys_to_store) - self._get_num_free_blocks()
|
||||
num_chunks_to_evict = len(keys_to_store) - self._get_num_free_chunks()
|
||||
|
||||
to_evict: list[OffloadKey] = []
|
||||
if num_blocks_to_evict > 0:
|
||||
if num_blocks_to_evict > self._num_evictable_cache_blocks:
|
||||
if num_chunks_to_evict > 0:
|
||||
if num_chunks_to_evict > self._num_evictable_cache_chunks:
|
||||
# Eviction will fail.
|
||||
return None
|
||||
# There is a still a chance for eviction failure as some of the
|
||||
# idle blocks might be in the protected list.
|
||||
# idle chunks might be in the protected list.
|
||||
|
||||
# Blocks from the original input are excluded from eviction candidates:
|
||||
# a block that was already stored must remain in the cache after this call.
|
||||
# Chunks from the original input are excluded from eviction candidates:
|
||||
# a chunk that was already stored must remain in the cache after this call.
|
||||
protected = set(keys)
|
||||
evicted = self._policy.evict(num_blocks_to_evict, protected)
|
||||
evicted = self._policy.evict(num_chunks_to_evict, protected)
|
||||
if evicted is None:
|
||||
return None
|
||||
|
||||
# cache-policy removes only idle blocks.
|
||||
self._num_evictable_cache_blocks -= len(evicted)
|
||||
assert self._num_evictable_cache_blocks >= 0
|
||||
# cache-policy removes only idle chunks.
|
||||
self._num_evictable_cache_chunks -= len(evicted)
|
||||
assert self._num_evictable_cache_chunks >= 0
|
||||
|
||||
for key, block in evicted:
|
||||
self._free_block(block)
|
||||
for key, chunk in evicted:
|
||||
self._free_chunk(chunk)
|
||||
to_evict.append(key)
|
||||
|
||||
if to_evict and self.events is not None:
|
||||
@@ -231,17 +231,17 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
)
|
||||
)
|
||||
|
||||
blocks = self._allocate_blocks(keys_to_store)
|
||||
assert len(blocks) == len(keys_to_store), (
|
||||
"Block pool did not allocate the expected number of blocks"
|
||||
chunks = self._allocate_chunks(keys_to_store)
|
||||
assert len(chunks) == len(keys_to_store), (
|
||||
"Chunk pool did not allocate the expected number of chunks"
|
||||
)
|
||||
|
||||
for key, block in zip(keys_to_store, blocks):
|
||||
self._policy.insert(key, block)
|
||||
self._num_write_pending_blocks += len(keys_to_store)
|
||||
for key, chunk in zip(keys_to_store, chunks):
|
||||
self._policy.insert(key, chunk)
|
||||
self._num_write_pending_chunks += len(keys_to_store)
|
||||
|
||||
# build store specs for allocated blocks
|
||||
store_spec = self._get_load_store_spec(keys_to_store, blocks)
|
||||
# build store specs for allocated chunks
|
||||
store_spec = self._get_load_store_spec(keys_to_store, chunks)
|
||||
|
||||
return PrepareStoreOutput(
|
||||
keys_to_store=keys_to_store,
|
||||
@@ -260,20 +260,20 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
|
||||
if success:
|
||||
for key in keys:
|
||||
block = self._policy.get(key)
|
||||
if block is not None and not block.is_ready:
|
||||
block.ref_cnt = 0
|
||||
self._num_write_pending_blocks -= 1
|
||||
self._num_evictable_cache_blocks += 1
|
||||
chunk = self._policy.get(key)
|
||||
if chunk is not None and not chunk.is_ready:
|
||||
chunk.ref_cnt = 0
|
||||
self._num_write_pending_chunks -= 1
|
||||
self._num_evictable_cache_chunks += 1
|
||||
self._policy.mark_evictable(key)
|
||||
stored_keys.append(key)
|
||||
else:
|
||||
for key in keys:
|
||||
block = self._policy.get(key)
|
||||
if block is not None and not block.is_ready:
|
||||
self._num_write_pending_blocks -= 1
|
||||
chunk = self._policy.get(key)
|
||||
if chunk is not None and not chunk.is_ready:
|
||||
self._num_write_pending_chunks -= 1
|
||||
self._policy.remove(key)
|
||||
self._free_block(block)
|
||||
self._free_chunk(chunk)
|
||||
|
||||
if stored_keys and self.events is not None:
|
||||
self.events.append(
|
||||
@@ -286,17 +286,17 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
|
||||
@override
|
||||
def reset_cache(self) -> None:
|
||||
# Clear ALL blocks unconditionally. The scheduler's _stale_job_threshold
|
||||
# Clear ALL chunks unconditionally. The scheduler's _stale_job_threshold
|
||||
# guarantees that complete_load / complete_store are never called for
|
||||
# pre-reset jobs, so no lazy cleanup is needed. The scheduler also
|
||||
# flushes in-flight load job IDs to the workers before any new stores
|
||||
# can begin, preventing a cross-direction data race on reused offload block IDs.
|
||||
# can begin, preventing a cross-direction data race on reused offload chunk IDs.
|
||||
self._policy.clear()
|
||||
self._num_evictable_cache_blocks = 0
|
||||
self._num_write_pending_blocks = 0
|
||||
self._num_evictable_cache_chunks = 0
|
||||
self._num_write_pending_chunks = 0
|
||||
|
||||
self._free_list.clear()
|
||||
self._num_allocated_blocks = 0
|
||||
self._num_allocated_chunks = 0
|
||||
|
||||
@override
|
||||
def take_events(self) -> Iterable[OffloadingEvent]:
|
||||
@@ -309,11 +309,11 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
|
||||
# Compute cache usage.
|
||||
num_used = (
|
||||
self._num_allocated_blocks
|
||||
self._num_allocated_chunks
|
||||
- len(self._free_list)
|
||||
- self._num_evictable_cache_blocks
|
||||
- self._num_evictable_cache_chunks
|
||||
)
|
||||
usage = num_used / self._num_blocks if self._num_blocks > 0 else 0.0
|
||||
usage = num_used / self._num_chunks if self._num_chunks > 0 else 0.0
|
||||
stats.set_gauge(CPUOffloadingMetrics.CPU_CACHE_USAGE_PERC, usage)
|
||||
|
||||
for allocation_size in self.allocation_sizes_in_current_batch:
|
||||
@@ -323,8 +323,8 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
self.allocation_sizes_in_current_batch.clear()
|
||||
|
||||
write_usage = (
|
||||
self._num_write_pending_blocks / self._num_blocks
|
||||
if self._num_blocks > 0
|
||||
self._num_write_pending_chunks / self._num_chunks
|
||||
if self._num_chunks > 0
|
||||
else 0.0
|
||||
)
|
||||
read_usage = max(usage - write_usage, 0.0)
|
||||
|
||||
@@ -6,7 +6,7 @@ from collections.abc import Iterable, Iterator
|
||||
from typing_extensions import override
|
||||
|
||||
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
|
||||
from vllm.v1.kv_offload.cpu.policies.base import BlockStatus, CachePolicy
|
||||
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
|
||||
|
||||
|
||||
class ARCCachePolicy(CachePolicy):
|
||||
@@ -14,15 +14,15 @@ class ARCCachePolicy(CachePolicy):
|
||||
ARC (Adaptive Replacement Cache) cache policy.
|
||||
|
||||
Data Structures:
|
||||
T1: Recent cache containing blocks accessed once.
|
||||
T2: Frequent cache containing blocks accessed multiple times.
|
||||
B1/B2: Ghost lists tracking recently evicted blocks from T1/T2.
|
||||
T1: Recent cache containing chunks accessed once.
|
||||
T2: Frequent cache containing chunks accessed multiple times.
|
||||
B1/B2: Ghost lists tracking recently evicted chunks from T1/T2.
|
||||
target_t1_size: Adaptive target size for the T1 partition.
|
||||
|
||||
Algorithm Flow:
|
||||
1. Cache lookup (lookup):
|
||||
Searches T1 and T2 for block hashes and counts consecutive hits
|
||||
until a miss or non-ready block is encountered.
|
||||
Searches T1 and T2 for chunk hashes and counts consecutive hits
|
||||
until a miss or non-ready chunk is encountered.
|
||||
|
||||
2. Cache touch (touch) - Adaptive Learning:
|
||||
For each key (in reverse order):
|
||||
@@ -31,15 +31,15 @@ class ARCCachePolicy(CachePolicy):
|
||||
- If in B1 ghost list: Increase target_t1_size.
|
||||
- If in B2 ghost list: Decrease target_t1_size.
|
||||
|
||||
3. Block eviction (evict) - Adaptive Replacement:
|
||||
3. Chunk eviction (evict) - Adaptive Replacement:
|
||||
Determines eviction source based on adaptive target:
|
||||
- If T1 size >= target_t1_size: Evict from T1, add to B1.
|
||||
- Otherwise: Evict from T2, add to B2.
|
||||
Finally, bound each ghost list size.
|
||||
|
||||
4. Block insertion (insert):
|
||||
New blocks are always inserted into T1 and removed from B1/B2 if
|
||||
present. Blocks may later be promoted to T2 during touch operations.
|
||||
4. Chunk insertion (insert):
|
||||
New chunks are always inserted into T1 and removed from B1/B2 if
|
||||
present. Chunks may later be promoted to T2 during touch operations.
|
||||
|
||||
Adaptive Behavior:
|
||||
The algorithm self-tunes the recency vs. frequency trade-off:
|
||||
@@ -50,19 +50,19 @@ class ARCCachePolicy(CachePolicy):
|
||||
def __init__(self, cache_capacity: int):
|
||||
super().__init__(cache_capacity)
|
||||
self.target_t1_size: float = 0.0
|
||||
self.t1: OrderedDict[OffloadKey, BlockStatus] = OrderedDict()
|
||||
self.t2: OrderedDict[OffloadKey, BlockStatus] = OrderedDict()
|
||||
self.t1: OrderedDict[OffloadKey, ChunkStatus] = OrderedDict()
|
||||
self.t2: OrderedDict[OffloadKey, ChunkStatus] = OrderedDict()
|
||||
# key -> None (only care about presence)
|
||||
self.b1: OrderedDict[OffloadKey, None] = OrderedDict()
|
||||
self.b2: OrderedDict[OffloadKey, None] = OrderedDict()
|
||||
|
||||
@override
|
||||
def get(self, key: OffloadKey) -> BlockStatus | None:
|
||||
def get(self, key: OffloadKey) -> ChunkStatus | None:
|
||||
return self.t1.get(key) or self.t2.get(key)
|
||||
|
||||
@override
|
||||
def insert(self, key: OffloadKey, block: BlockStatus) -> None:
|
||||
self.t1[key] = block
|
||||
def insert(self, key: OffloadKey, chunk: ChunkStatus) -> None:
|
||||
self.t1[key] = chunk
|
||||
self.b1.pop(key, None)
|
||||
self.b2.pop(key, None)
|
||||
|
||||
@@ -75,13 +75,13 @@ class ARCCachePolicy(CachePolicy):
|
||||
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
|
||||
for key in reversed(list(keys)):
|
||||
if key in self.t1:
|
||||
block = self.t1.pop(key)
|
||||
if not block.is_ready:
|
||||
# block was just prepared to be stored, not really touched
|
||||
chunk = self.t1.pop(key)
|
||||
if not chunk.is_ready:
|
||||
# chunk was just prepared to be stored, not really touched
|
||||
# twice — keep it in T1 and mark as most recently used
|
||||
self.t1[key] = block
|
||||
self.t1[key] = chunk
|
||||
else:
|
||||
self.t2[key] = block
|
||||
self.t2[key] = chunk
|
||||
|
||||
elif key in self.t2:
|
||||
self.t2.move_to_end(key)
|
||||
@@ -111,31 +111,31 @@ class ARCCachePolicy(CachePolicy):
|
||||
@override
|
||||
def evict(
|
||||
self, n: int, protected: set[OffloadKey]
|
||||
) -> list[tuple[OffloadKey, BlockStatus]] | None:
|
||||
) -> list[tuple[OffloadKey, ChunkStatus]] | None:
|
||||
if n == 0:
|
||||
return []
|
||||
|
||||
# Collect candidates atomically: simulate T1 size changes as we select,
|
||||
# but do not modify actual data structures until all n are found.
|
||||
candidates: list[
|
||||
tuple[OffloadKey, BlockStatus, bool]
|
||||
] = [] # (key, block, from_t1)
|
||||
tuple[OffloadKey, ChunkStatus, bool]
|
||||
] = [] # (key, chunk, from_t1)
|
||||
virtual_t1_size = len(self.t1)
|
||||
# Keep the scans monotonic: restarting from the LRU end after every
|
||||
# selection makes a batch eviction quadratic in the number of blocks.
|
||||
# selection makes a batch eviction quadratic in the number of chunks.
|
||||
t1_iter = iter(self.t1.items())
|
||||
t2_iter = iter(self.t2.items())
|
||||
|
||||
def next_candidate(
|
||||
entries: Iterator[tuple[OffloadKey, BlockStatus]],
|
||||
) -> tuple[OffloadKey, BlockStatus] | None:
|
||||
for key, block in entries:
|
||||
if block.ref_cnt == 0 and key not in protected:
|
||||
return key, block
|
||||
entries: Iterator[tuple[OffloadKey, ChunkStatus]],
|
||||
) -> tuple[OffloadKey, ChunkStatus] | None:
|
||||
for key, chunk in entries:
|
||||
if chunk.ref_cnt == 0 and key not in protected:
|
||||
return key, chunk
|
||||
return None
|
||||
|
||||
for _ in range(n):
|
||||
candidate: tuple[OffloadKey, BlockStatus, bool] | None = None
|
||||
candidate: tuple[OffloadKey, ChunkStatus, bool] | None = None
|
||||
|
||||
if virtual_t1_size >= int(self.target_t1_size):
|
||||
entry = next_candidate(t1_iter)
|
||||
@@ -158,15 +158,15 @@ class ARCCachePolicy(CachePolicy):
|
||||
candidates.append(candidate)
|
||||
|
||||
# Apply all evictions now that we know n candidates exist.
|
||||
result: list[tuple[OffloadKey, BlockStatus]] = []
|
||||
for key, block, from_t1 in candidates:
|
||||
result: list[tuple[OffloadKey, ChunkStatus]] = []
|
||||
for key, chunk, from_t1 in candidates:
|
||||
if from_t1:
|
||||
del self.t1[key]
|
||||
self.b1[key] = None
|
||||
else:
|
||||
del self.t2[key]
|
||||
self.b2[key] = None
|
||||
result.append((key, block))
|
||||
result.append((key, chunk))
|
||||
|
||||
# Trim ghost lists to cache_capacity.
|
||||
for ghost in (self.b1, self.b2):
|
||||
|
||||
@@ -7,36 +7,36 @@ from collections.abc import Iterable
|
||||
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
|
||||
|
||||
|
||||
class BlockStatus(ctypes.Structure):
|
||||
class ChunkStatus(ctypes.Structure):
|
||||
"""
|
||||
Offloading status for a single block 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 block as a source.
|
||||
A value of -1 indicates the block is not yet ready to be read.
|
||||
block_id - index of the physical CPU buffer slot.
|
||||
ref_cnt - the current number of transfers using this chunk as a source.
|
||||
A value of -1 indicates the chunk is not yet ready to be read.
|
||||
chunk_id - index of the physical CPU buffer slot.
|
||||
"""
|
||||
|
||||
_fields_ = [("ref_cnt", ctypes.c_int32), ("block_id", ctypes.c_int64)]
|
||||
_fields_ = [("ref_cnt", ctypes.c_int32), ("chunk_id", ctypes.c_int64)]
|
||||
|
||||
def __init__(self, block_id: int):
|
||||
def __init__(self, chunk_id: int):
|
||||
super().__init__()
|
||||
# initialize block as "not ready" (ref_cnt = -1)
|
||||
# initialize chunk as "not ready" (ref_cnt = -1)
|
||||
self.ref_cnt = -1
|
||||
self.block_id = block_id
|
||||
self.chunk_id = chunk_id
|
||||
|
||||
@property
|
||||
def is_ready(self) -> bool:
|
||||
"""
|
||||
Returns whether the block is ready to be read.
|
||||
Returns whether the chunk is ready to be read.
|
||||
"""
|
||||
return self.ref_cnt >= 0
|
||||
|
||||
|
||||
class CachePolicy(ABC):
|
||||
"""
|
||||
Encapsulates both block organization (data structures) and replacement
|
||||
decisions (which block to evict). LRU and ARC differ in both dimensions —
|
||||
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.
|
||||
"""
|
||||
@@ -45,35 +45,35 @@ class CachePolicy(ABC):
|
||||
self.cache_capacity = cache_capacity
|
||||
|
||||
@abstractmethod
|
||||
def get(self, key: OffloadKey) -> BlockStatus | None:
|
||||
"""Find block in data structures. Returns None if not present."""
|
||||
def get(self, key: OffloadKey) -> ChunkStatus | None:
|
||||
"""Find chunk in data structures. Returns None if not present."""
|
||||
|
||||
@abstractmethod
|
||||
def insert(self, key: OffloadKey, block: BlockStatus) -> None:
|
||||
"""Add a newly allocated block. For ARC: also removes from ghost lists."""
|
||||
def insert(self, key: OffloadKey, chunk: ChunkStatus) -> None:
|
||||
"""Add a newly allocated chunk. For ARC: also removes from ghost lists."""
|
||||
|
||||
@abstractmethod
|
||||
def remove(self, key: OffloadKey) -> None:
|
||||
"""Remove a block (used to clean up after a failed store)."""
|
||||
"""Remove a chunk (used to clean up after a failed store)."""
|
||||
|
||||
@abstractmethod
|
||||
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
|
||||
"""
|
||||
Mark blocks as recently used.
|
||||
Mark chunks as recently used.
|
||||
|
||||
Args:
|
||||
keys: Blocks to mark as recently used.
|
||||
req_context: Per-request context for the request touching these blocks.
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context for the request touching these chunks.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def evict(
|
||||
self, n: int, protected: set[OffloadKey]
|
||||
) -> list[tuple[OffloadKey, BlockStatus]] | None:
|
||||
) -> list[tuple[OffloadKey, ChunkStatus]] | None:
|
||||
"""
|
||||
Evict exactly n blocks, skipping any in protected.
|
||||
Evict exactly n chunks, skipping any in protected.
|
||||
|
||||
Returns a list of (key, block) for the evicted blocks,
|
||||
Returns a list of (key, chunk) for the evicted chunks,
|
||||
or None if n evictions cannot be satisfied. The operation is atomic:
|
||||
if None is returned, no state changes are made.
|
||||
|
||||
@@ -84,15 +84,15 @@ class CachePolicy(ABC):
|
||||
@abstractmethod
|
||||
def clear(self) -> None:
|
||||
"""
|
||||
Remove ALL blocks regardless of ref_cnt.
|
||||
Remove ALL chunks regardless of ref_cnt.
|
||||
|
||||
Ghost lists and adaptive state are also reset.
|
||||
"""
|
||||
|
||||
def mark_evictable(self, key: OffloadKey) -> None:
|
||||
"""Called when a block's ref_cnt transitions to 0."""
|
||||
"""Called when a chunk's ref_cnt transitions to 0."""
|
||||
return
|
||||
|
||||
def mark_non_evictable(self, key: OffloadKey) -> None:
|
||||
"""Called when a block's ref_cnt transitions from 0."""
|
||||
"""Called when a chunk's ref_cnt transitions from 0."""
|
||||
return
|
||||
|
||||
@@ -6,7 +6,7 @@ from collections.abc import Iterable
|
||||
from typing_extensions import override
|
||||
|
||||
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
|
||||
from vllm.v1.kv_offload.cpu.policies.base import BlockStatus, CachePolicy
|
||||
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
|
||||
|
||||
|
||||
class LRUCachePolicy(CachePolicy):
|
||||
@@ -20,71 +20,71 @@ class LRUCachePolicy(CachePolicy):
|
||||
|
||||
def __init__(self, cache_capacity: int):
|
||||
super().__init__(cache_capacity)
|
||||
# Blocks with ref_cnt 0 (not participating in any loads/stores) ordered in LRU
|
||||
self.evictable_blocks: OrderedDict[OffloadKey, None] = OrderedDict()
|
||||
self.blocks: dict[OffloadKey, BlockStatus] = {}
|
||||
# Chunks with ref_cnt 0 (not participating in any loads/stores) ordered in LRU
|
||||
self.evictable_chunks: OrderedDict[OffloadKey, None] = OrderedDict()
|
||||
self.chunks: dict[OffloadKey, ChunkStatus] = {}
|
||||
|
||||
@override
|
||||
def get(self, key: OffloadKey) -> BlockStatus | None:
|
||||
return self.blocks.get(key)
|
||||
def get(self, key: OffloadKey) -> ChunkStatus | None:
|
||||
return self.chunks.get(key)
|
||||
|
||||
@override
|
||||
def insert(self, key: OffloadKey, block: BlockStatus) -> None:
|
||||
self.blocks[key] = block
|
||||
if block.ref_cnt == 0:
|
||||
self.evictable_blocks[key] = None
|
||||
def insert(self, key: OffloadKey, chunk: ChunkStatus) -> None:
|
||||
self.chunks[key] = chunk
|
||||
if chunk.ref_cnt == 0:
|
||||
self.evictable_chunks[key] = None
|
||||
|
||||
@override
|
||||
def remove(self, key: OffloadKey) -> None:
|
||||
del self.blocks[key]
|
||||
self.evictable_blocks.pop(key, None)
|
||||
del self.chunks[key]
|
||||
self.evictable_chunks.pop(key, None)
|
||||
|
||||
@override
|
||||
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
|
||||
for key in reversed(list(keys)):
|
||||
if key in self.evictable_blocks:
|
||||
self.evictable_blocks.move_to_end(key)
|
||||
# active blocks are untouched as they are non-evictable now. They
|
||||
# will eventually reach the end of evictable_blocks when they finish.
|
||||
if key in self.evictable_chunks:
|
||||
self.evictable_chunks.move_to_end(key)
|
||||
# active chunks are untouched as they are non-evictable now. They
|
||||
# will eventually reach the end of evictable_chunks when they finish.
|
||||
|
||||
@override
|
||||
def clear(self) -> None:
|
||||
self.evictable_blocks.clear()
|
||||
self.blocks.clear()
|
||||
self.evictable_chunks.clear()
|
||||
self.chunks.clear()
|
||||
|
||||
@override
|
||||
def evict(
|
||||
self, n: int, protected: set[OffloadKey]
|
||||
) -> list[tuple[OffloadKey, BlockStatus]] | None:
|
||||
) -> list[tuple[OffloadKey, ChunkStatus]] | None:
|
||||
if n == 0:
|
||||
return []
|
||||
|
||||
candidates: list[tuple[OffloadKey, BlockStatus]] = []
|
||||
for key, _ in self.evictable_blocks.items():
|
||||
candidates: list[tuple[OffloadKey, ChunkStatus]] = []
|
||||
for key, _ in self.evictable_chunks.items():
|
||||
if key in protected:
|
||||
continue
|
||||
|
||||
block = self.blocks[key]
|
||||
assert block.ref_cnt == 0
|
||||
candidates.append((key, block))
|
||||
chunk = self.chunks[key]
|
||||
assert chunk.ref_cnt == 0
|
||||
candidates.append((key, chunk))
|
||||
if len(candidates) == n:
|
||||
break
|
||||
|
||||
if len(candidates) < n:
|
||||
return None
|
||||
for key, _ in candidates:
|
||||
del self.evictable_blocks[key]
|
||||
del self.blocks[key]
|
||||
del self.evictable_chunks[key]
|
||||
del self.chunks[key]
|
||||
return candidates
|
||||
|
||||
@override
|
||||
def mark_evictable(self, key: OffloadKey) -> None:
|
||||
# blocks can become evictable when,
|
||||
# chunks can become evictable when,
|
||||
# store completes - i.e. ref_cnt -1 -> 0 # not in evictable list
|
||||
# all loads complete - i.e ref_cnt 1 -> 0 # not in evictable list
|
||||
self.evictable_blocks[key] = None
|
||||
self.evictable_chunks[key] = None
|
||||
|
||||
@override
|
||||
def mark_non_evictable(self, key: OffloadKey) -> None:
|
||||
# key must have been in the evictable list.
|
||||
del self.evictable_blocks[key]
|
||||
del self.evictable_chunks[key]
|
||||
|
||||
@@ -82,24 +82,24 @@ class SharedOffloadRegion:
|
||||
def __init__(
|
||||
self,
|
||||
engine_id: str,
|
||||
num_blocks: int,
|
||||
num_chunks: int,
|
||||
rank: int | None,
|
||||
kv_bytes_per_block: int,
|
||||
kv_bytes_per_chunk: int,
|
||||
cpu_page_size: int,
|
||||
barrier: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
self.page_size = mmap.PAGESIZE
|
||||
assert kv_bytes_per_block % self.page_size == 0
|
||||
assert kv_bytes_per_chunk % self.page_size == 0
|
||||
|
||||
self.num_blocks = num_blocks
|
||||
self._row_stride = kv_bytes_per_block
|
||||
self.total_size_bytes = self.num_blocks * self._row_stride
|
||||
self.num_chunks = num_chunks
|
||||
self._row_stride = kv_bytes_per_chunk
|
||||
self.total_size_bytes = self.num_chunks * self._row_stride
|
||||
|
||||
self.mmap_path = f"/dev/shm/vllm_offload_{engine_id}.mmap"
|
||||
self._creator = False # set True only if this worker creates the file
|
||||
self.rank = rank
|
||||
if rank is not None:
|
||||
# byte offset to this worker's first slot within each block row
|
||||
# byte offset to this worker's first slot within each chunk row
|
||||
self._worker_offset = rank * cpu_page_size
|
||||
# exclusive upper bound for this worker's area within each row
|
||||
self._worker_area_end = (rank + 1) * cpu_page_size
|
||||
@@ -182,19 +182,19 @@ class SharedOffloadRegion:
|
||||
populate_write_fn = _get_populate_write_fn(self.mmap_obj)
|
||||
|
||||
if rank is not None:
|
||||
# Populate only this worker's pages (one slot per block row).
|
||||
# Populate only this worker's pages (one slot per chunk row).
|
||||
worker_offset = rank * cpu_page_size
|
||||
_t0 = time.perf_counter()
|
||||
page_size = self.page_size
|
||||
for block in range(num_blocks):
|
||||
raw_offset = block * self._row_stride + worker_offset
|
||||
for chunk in range(num_chunks):
|
||||
raw_offset = chunk * self._row_stride + worker_offset
|
||||
aligned_offset = (raw_offset // page_size) * page_size
|
||||
end = raw_offset + cpu_page_size
|
||||
aligned_length = end - aligned_offset
|
||||
populate_write_fn(self.mmap_obj, aligned_offset, aligned_length)
|
||||
logger.debug(
|
||||
"MADV_POPULATE_WRITE loop: %d blocks in %.3f s",
|
||||
num_blocks,
|
||||
"MADV_POPULATE_WRITE loop: %d chunks in %.3f s",
|
||||
num_chunks,
|
||||
time.perf_counter() - _t0,
|
||||
)
|
||||
else:
|
||||
@@ -215,22 +215,22 @@ class SharedOffloadRegion:
|
||||
|
||||
Must be called once per canonical tensor. The full mmap layout is:
|
||||
|
||||
worker0_block0 | worker1_block0 | ... | worker{M-1}_block0
|
||||
worker0_block1 | worker1_block1 | ... | worker{M-1}_block1
|
||||
worker0_chunk0 | worker1_chunk0 | ... | worker{M-1}_chunk0
|
||||
worker0_chunk1 | worker1_chunk1 | ... | worker{M-1}_chunk1
|
||||
...
|
||||
|
||||
Each worker_block cell is cpu_page_size bytes and holds all canonical
|
||||
tensors for that worker and block concatenated:
|
||||
Each worker_chunk cell is cpu_page_size bytes and holds all canonical
|
||||
tensors for that worker and chunk concatenated:
|
||||
[ tensor0_data | tensor1_data | ... | tensor{L-1}_data ]
|
||||
|
||||
Consecutive rows are separated by row_stride = cpu_page_size * M.
|
||||
|
||||
Returns an int8 tensor of shape (num_blocks, tensor_page_size) with stride
|
||||
Returns an int8 tensor of shape (num_chunks, tensor_page_size) with stride
|
||||
(row_stride, 1). Using int8 keeps stride == bytes, so swap_blocks
|
||||
address arithmetic works without any dtype conversion.
|
||||
|
||||
Args:
|
||||
tensor_page_size: Bytes per block for this tensor.
|
||||
tensor_page_size: Bytes per chunk for this tensor.
|
||||
"""
|
||||
assert self.rank is not None
|
||||
new_offset = self._worker_offset + tensor_page_size
|
||||
@@ -241,7 +241,7 @@ class SharedOffloadRegion:
|
||||
)
|
||||
worker_layer_view = torch.as_strided(
|
||||
self._base,
|
||||
size=(self.num_blocks, tensor_page_size),
|
||||
size=(self.num_chunks, tensor_page_size),
|
||||
stride=(self._row_stride, 1),
|
||||
storage_offset=self._worker_offset,
|
||||
)
|
||||
@@ -266,8 +266,8 @@ class SharedOffloadRegion:
|
||||
_canonical_offset=0, then advances by each tensor's size
|
||||
|
||||
Each canonical_t{i} cell is that tensor's canonical page for the
|
||||
block. Canonical areas are carved consecutively from the start of
|
||||
each block row; consecutive rows are separated by row_stride. Every
|
||||
chunk. Canonical areas are carved consecutively from the start of
|
||||
each chunk row; consecutive rows are separated by row_stride. Every
|
||||
worker gets the identical byte ranges and writes only its disjoint
|
||||
bytes within them, as described by its canonical mappings — unlike
|
||||
create_next_worker_view, which gives each worker a private
|
||||
@@ -279,13 +279,13 @@ class SharedOffloadRegion:
|
||||
where one canonical copy replaces world_size worker copies.
|
||||
|
||||
Args:
|
||||
tensor_page_size: Canonical bytes per block for this tensor.
|
||||
tensor_page_size: Canonical bytes per chunk for this tensor.
|
||||
"""
|
||||
new_offset = self._canonical_offset + tensor_page_size
|
||||
assert new_offset <= self._row_stride
|
||||
view = torch.as_strided(
|
||||
self._base,
|
||||
size=(self.num_blocks, tensor_page_size),
|
||||
size=(self.num_chunks, tensor_page_size),
|
||||
stride=(self._row_stride, 1),
|
||||
storage_offset=self._canonical_offset,
|
||||
)
|
||||
@@ -296,10 +296,10 @@ class SharedOffloadRegion:
|
||||
def create_kv_memoryview(self) -> memoryview:
|
||||
"""Return a zero-copy memoryview over the entire KV buffer.
|
||||
|
||||
Shape: (num_blocks, row_stride_bytes). Secondary tiers address
|
||||
block *b* as ``view[b]``.
|
||||
Shape: (num_chunks, row_stride_bytes). Secondary tiers address
|
||||
chunk *b* as ``view[b]``.
|
||||
"""
|
||||
kv_tensor = self._base.view(self.num_blocks, self._row_stride)
|
||||
kv_tensor = self._base.view(self.num_chunks, self._row_stride)
|
||||
np_arr = kv_tensor.numpy()
|
||||
assert np_arr.ctypes.data == self._base.data_ptr(), (
|
||||
"view()/numpy() created a copy instead of sharing the mmap buffer; "
|
||||
|
||||
@@ -73,7 +73,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
),
|
||||
CPUOffloadingMetrics.CPU_ALLOCATION_SIZE: OffloadingHistogramMetadata(
|
||||
documentation=(
|
||||
"Histogram of the number of CPU blocks requested by each "
|
||||
"Histogram of the number of CPU chunks requested by each "
|
||||
"KV offload prepare_store call."
|
||||
),
|
||||
buckets=(1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144),
|
||||
@@ -101,7 +101,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
)
|
||||
|
||||
world_size = config.parallel.world_size
|
||||
self.num_blocks = 0
|
||||
self.num_chunks = 0
|
||||
self.kv_bytes_per_chunk = 0
|
||||
self.cpu_page_size_per_worker = 0
|
||||
self.replicated_layout = config.replicated_layout and self._uses_shared_region()
|
||||
@@ -113,17 +113,17 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
# calculate cpu_page_size_per_worker
|
||||
self.cpu_page_size_per_worker = kv_bytes_per_chunk // num_copies
|
||||
|
||||
# calculate num_blocks
|
||||
# calculate num_chunks
|
||||
aligned_kv_bytes_per_chunk = round_up(
|
||||
kv_bytes_per_chunk, self.BLOCK_SIZE_ALIGNMENT
|
||||
)
|
||||
self.num_blocks = int(cpu_bytes_to_use) // aligned_kv_bytes_per_chunk
|
||||
self.num_chunks = int(cpu_bytes_to_use) // aligned_kv_bytes_per_chunk
|
||||
|
||||
# Expose aligned_kv_bytes_per_chunk as
|
||||
# kv_bytes_per_chunk. Note that this might contain
|
||||
# some padding. i.e. each offloaded block is of the form,
|
||||
# |--- W0-B0---|---- W1-B0---| ... |---- Wn-B0---| *** maybe-pad *** |
|
||||
# or |--- B0 (single copy) ---| *** maybe-pad *** |
|
||||
# some padding. i.e. each offloaded chunk is of the form,
|
||||
# |--- W0-C0---|---- W1-C0---| ... |---- Wn-C0---| *** maybe-pad *** |
|
||||
# or |--- C0 (single copy) ---| *** maybe-pad *** |
|
||||
self.kv_bytes_per_chunk = aligned_kv_bytes_per_chunk
|
||||
|
||||
# scheduler-side
|
||||
@@ -140,7 +140,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
@override
|
||||
def get_manager(self) -> OffloadingManager:
|
||||
if not self._manager:
|
||||
# store_threshold: how many times a block must be offered for
|
||||
# store_threshold: how many times a chunk must be offered for
|
||||
# storage before it is eligible for CPU offloading. Values < 2
|
||||
# disable filtering (a threshold of 1 equals no filter; 0 is the
|
||||
# default).
|
||||
@@ -150,7 +150,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
max_tracker_size = int(self.extra_config.get("max_tracker_size", 64_000))
|
||||
|
||||
self._manager = CPUOffloadingManager(
|
||||
num_blocks=self.num_blocks,
|
||||
num_chunks=self.num_chunks,
|
||||
cache_policy=self.eviction_policy,
|
||||
cache_policy_module_path=self.cache_policy_module_path,
|
||||
enable_events=self.kv_events_config.enable_kv_cache_events,
|
||||
@@ -166,9 +166,9 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
|
||||
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
|
||||
mmap_region: SharedOffloadRegion | None = None
|
||||
# num_blocks == 0 would size the region to zero bytes, which cannot be
|
||||
# num_chunks == 0 would size the region to zero bytes, which cannot be
|
||||
# mmap'd; fall back to the tensor path (empty tensors) as before.
|
||||
if self._uses_shared_region() and self.num_blocks > 0:
|
||||
if self._uses_shared_region() and self.num_chunks > 0:
|
||||
# Replicated layout puts all ranks on slot 0 (single MLA copy);
|
||||
# otherwise each rank takes its own slot by physical device index.
|
||||
if self.replicated_layout:
|
||||
@@ -178,9 +178,9 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
rank = torch.accelerator.current_device_index() % world_size
|
||||
mmap_region = SharedOffloadRegion(
|
||||
engine_id=self.config.engine_id,
|
||||
num_blocks=self.num_blocks,
|
||||
num_chunks=self.num_chunks,
|
||||
rank=rank,
|
||||
kv_bytes_per_block=self.kv_bytes_per_chunk,
|
||||
kv_bytes_per_chunk=self.kv_bytes_per_chunk,
|
||||
cpu_page_size=self.cpu_page_size_per_worker,
|
||||
barrier=_all_workers_barrier,
|
||||
)
|
||||
@@ -188,7 +188,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
return CPUOffloadingWorker(
|
||||
kv_caches=kv_caches,
|
||||
blocks_per_chunk=self.blocks_per_chunk,
|
||||
num_cpu_blocks=self.num_blocks,
|
||||
num_cpu_chunks=self.num_chunks,
|
||||
mmap_region=mmap_region,
|
||||
)
|
||||
except Exception:
|
||||
|
||||
@@ -45,8 +45,8 @@ class TieringOffloadingMetrics:
|
||||
WRITE_TIME = "vllm:kv_offload_tiering_write_time"
|
||||
PROMOTION_JOB_FAILURES = "vllm:kv_offload_tiering_promotion_job_failures"
|
||||
CASCADE_JOB_FAILURES = "vllm:kv_offload_tiering_cascade_job_failures"
|
||||
BLOCK_QUERIES = "vllm:kv_offload_tiering_chunk_queries"
|
||||
BLOCK_HITS = "vllm:kv_offload_tiering_chunk_hits"
|
||||
CHUNK_QUERIES = "vllm:kv_offload_tiering_chunk_queries"
|
||||
CHUNK_HITS = "vllm:kv_offload_tiering_chunk_hits"
|
||||
PRIMARY_WRITE_USAGE_PERC = "vllm:kv_offload_tiering_primary_write_usage_perc"
|
||||
PRIMARY_READ_USAGE_PERC = "vllm:kv_offload_tiering_primary_read_usage_perc"
|
||||
PROMOTION_ALLOCATION_FAILURES = (
|
||||
@@ -62,7 +62,7 @@ class TransferJob:
|
||||
|
||||
job_id: JobId
|
||||
keys: Collection[OffloadKey]
|
||||
block_ids: np.ndarray
|
||||
chunk_ids: np.ndarray
|
||||
is_promotion: bool
|
||||
req_context: ReqContext
|
||||
|
||||
@@ -90,14 +90,14 @@ class ParentManager(ABC):
|
||||
|
||||
Required call sequence for each remote request:
|
||||
1. on_new_request(req_context) — set up per-request state
|
||||
2. lookup(key, req_context) — check block availability
|
||||
(repeat per block)
|
||||
3. create_store_job(keys, req_context) — pin blocks and get a
|
||||
2. lookup(key, req_context) — check chunk availability
|
||||
(repeat per chunk)
|
||||
3. create_store_job(keys, req_context) — pin chunks and get a
|
||||
job handle
|
||||
4. on_request_finished(req_context) — clean up per-request state
|
||||
|
||||
Steps 2-3 may be interleaved. Step 4 must be called even if no
|
||||
blocks were found, to avoid leaking async lookup state (e.g. in
|
||||
chunks were found, to avoid leaking async lookup state (e.g. in
|
||||
the fs tier's AsyncLookupManager).
|
||||
"""
|
||||
|
||||
@@ -155,23 +155,23 @@ class SecondaryTierManager(ABC):
|
||||
@abstractmethod
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a block exists in this secondary tier.
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
req_context: per-request context (e.g. kv_transfer_params).
|
||||
|
||||
Returns:
|
||||
HIT if the block is present and ready,
|
||||
HIT if the chunk is present and ready,
|
||||
MISS if not found,
|
||||
or RETRY if the block is being transferred (retry later).
|
||||
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 blocks 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
|
||||
@@ -179,19 +179,19 @@ class SecondaryTierManager(ABC):
|
||||
calling thread.
|
||||
|
||||
Preconditions (guaranteed by the framework):
|
||||
- ``job_metadata.block_ids`` are valid primary-tier slots, pinned
|
||||
- ``job_metadata.chunk_ids`` are valid primary-tier slots, pinned
|
||||
(ref-counted) for the duration of the transfer.
|
||||
|
||||
The implementation is responsible for:
|
||||
1. Filtering out blocks already present in this tier
|
||||
2. Evicting blocks if capacity is needed
|
||||
1. Filtering out chunks already present in this tier
|
||||
2. Evicting chunks if capacity is needed
|
||||
3. Allocating space in this tier
|
||||
4. Submitting the async transfer (read from primary via block_ids)
|
||||
4. Submitting the async transfer (read from primary via chunk_ids)
|
||||
|
||||
Report completion via ``get_finished_jobs()``.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and block_ids
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to read from.
|
||||
"""
|
||||
pass
|
||||
@@ -199,24 +199,24 @@ class SecondaryTierManager(ABC):
|
||||
@abstractmethod
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit an async job to load blocks 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 blocks as
|
||||
This method must be lightweight and non-blocking: mark chunks as
|
||||
in-flight and submit the transfer, but do NOT perform the data copy
|
||||
on the calling thread.
|
||||
|
||||
Preconditions (guaranteed by the framework):
|
||||
- ``job_metadata.block_ids`` are allocated primary-tier slots
|
||||
- ``job_metadata.chunk_ids`` are allocated primary-tier slots
|
||||
ready to receive data.
|
||||
|
||||
The implementation must copy data from this tier into the
|
||||
primary-tier slots identified by ``block_ids``.
|
||||
primary-tier slots identified by ``chunk_ids``.
|
||||
|
||||
Report completion via ``get_finished_jobs()``.
|
||||
|
||||
Args:
|
||||
job_metadata: Job metadata including job_id, keys, and block_ids
|
||||
job_metadata: Job metadata including job_id, keys, and chunk_ids
|
||||
identifying the primary-tier slots to write into.
|
||||
"""
|
||||
pass
|
||||
@@ -249,7 +249,7 @@ class SecondaryTierManager(ABC):
|
||||
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark blocks as recently used for eviction policy.
|
||||
Mark chunks as recently used for eviction policy.
|
||||
|
||||
Args:
|
||||
keys: Offload keys to mark as recently used.
|
||||
@@ -263,7 +263,7 @@ class SecondaryTierManager(ABC):
|
||||
Called when a new request is first seen by the scheduler.
|
||||
|
||||
Returns a RequestOffloadingContext expressing this tier's preference
|
||||
for how blocks should be offloaded for this request.
|
||||
for how chunks should be offloaded for this request.
|
||||
|
||||
Args:
|
||||
req_context: Per-request context.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"""
|
||||
ExampleSecondaryTierManager: A simple in-memory secondary tier.
|
||||
|
||||
This implementation provides a minimal secondary tier that stores blocks
|
||||
This implementation provides a minimal secondary tier that stores chunks
|
||||
in memory (using a dictionary) with immediate completion. It serves as a
|
||||
reference for writing new tiers and is useful for testing the
|
||||
TieringOffloadingManager without requiring actual storage or network backends.
|
||||
@@ -39,7 +39,7 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
A simple in-memory secondary tier.
|
||||
|
||||
This implementation:
|
||||
- Stores blocks in a dictionary (key -> True)
|
||||
- Stores chunks in a dictionary (key -> True)
|
||||
- Completes transfers immediately (synchronous)
|
||||
"""
|
||||
|
||||
@@ -69,45 +69,45 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
)
|
||||
|
||||
# key -> True (only care about presence)
|
||||
self.blocks: dict[OffloadKey, bool] = {}
|
||||
self.chunks: dict[OffloadKey, bool] = {}
|
||||
|
||||
# Completed jobs waiting to be retrieved by get_finished_jobs()
|
||||
self.completed_jobs: list[JobResult] = []
|
||||
assert primary_kv_view.strides is not None
|
||||
self._block_size = primary_kv_view.strides[0]
|
||||
self._chunk_size = primary_kv_view.strides[0]
|
||||
|
||||
@override
|
||||
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
|
||||
"""
|
||||
Check whether a block exists in this secondary tier.
|
||||
Check whether a chunk exists in this secondary tier.
|
||||
|
||||
Args:
|
||||
key: Offload key to look up.
|
||||
req_context: Per-request context.
|
||||
|
||||
Returns:
|
||||
HIT if the block is present, MISS if not found.
|
||||
HIT if the chunk is present, MISS if not found.
|
||||
"""
|
||||
return LookupResult.HIT if key in self.blocks else LookupResult.MISS
|
||||
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 blocks 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 blocks from the primary tier.
|
||||
spec for reading chunks from the primary tier.
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
block_ids = job_metadata.block_ids
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
|
||||
assert len(keys) == len(block_ids), (
|
||||
f"Length mismatch: {len(keys)} keys but {len(block_ids)} block_ids"
|
||||
assert len(keys) == len(chunk_ids), (
|
||||
f"Length mismatch: {len(keys)} keys but {len(chunk_ids)} chunk_ids"
|
||||
)
|
||||
|
||||
for key in keys:
|
||||
self.blocks[key] = True
|
||||
self.chunks[key] = True
|
||||
self.completed_jobs.append(
|
||||
JobResult(
|
||||
job_id=job_metadata.job_id,
|
||||
@@ -119,21 +119,21 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
"""
|
||||
Submit a job to load blocks 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 blocks into the primary tier.
|
||||
spec for writing chunks into the primary tier.
|
||||
"""
|
||||
keys = job_metadata.keys
|
||||
block_ids = job_metadata.block_ids
|
||||
chunk_ids = job_metadata.chunk_ids
|
||||
|
||||
assert len(keys) == len(block_ids), (
|
||||
f"Length mismatch: {len(keys)} keys but {len(block_ids)} block_ids"
|
||||
assert len(keys) == len(chunk_ids), (
|
||||
f"Length mismatch: {len(keys)} keys but {len(chunk_ids)} chunk_ids"
|
||||
)
|
||||
|
||||
for key in keys:
|
||||
if key not in self.blocks:
|
||||
if key not in self.chunks:
|
||||
self.completed_jobs.append(
|
||||
JobResult(job_id=job_metadata.job_id, success=False)
|
||||
)
|
||||
@@ -170,6 +170,6 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
completes, so there is nothing to wait for."""
|
||||
return
|
||||
|
||||
def get_num_blocks(self) -> int:
|
||||
"""Get the number of blocks currently stored in this tier."""
|
||||
return len(self.blocks)
|
||||
def get_num_chunks(self) -> int:
|
||||
"""Get the number of chunks currently stored in this tier."""
|
||||
return len(self.chunks)
|
||||
|
||||
@@ -223,7 +223,7 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
batch_store_block,
|
||||
[self.file_mapper.get_file_name(key) for key in keys],
|
||||
self._primary_kv_view,
|
||||
[int(bid) * self._block_size for bid in job_metadata.block_ids],
|
||||
[int(cid) * self._block_size for cid in job_metadata.chunk_ids],
|
||||
self._block_size,
|
||||
self._use_o_direct,
|
||||
)
|
||||
@@ -237,7 +237,7 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
keys = list(job_metadata.keys)
|
||||
self._load_job_keys[job_id] = keys
|
||||
paths = [self.file_mapper.get_file_name(key) for key in keys]
|
||||
offsets = [int(bid) * self._block_size for bid in job_metadata.block_ids]
|
||||
offsets = [int(cid) * self._block_size for cid in job_metadata.chunk_ids]
|
||||
|
||||
def load_task() -> None:
|
||||
try:
|
||||
|
||||
@@ -8,16 +8,16 @@ and zero or more secondary tiers (Storage, Network, etc.) to provide
|
||||
hierarchical KV cache offloading.
|
||||
|
||||
Key Design Principles:
|
||||
1. Always offload to all tiers — When a block is stored to the primary tier,
|
||||
1. Always offload to all tiers — When a chunk is stored to the primary tier,
|
||||
it is cascaded to ALL secondary tiers
|
||||
2. Primary tier is the gateway — Secondary tiers cannot access GPU memory
|
||||
directly; all data flows through the CPU primary tier
|
||||
3. Staged promotion — Blocks in secondary tiers must be promoted to the
|
||||
3. Staged promotion — Chunks in secondary tiers must be promoted to the
|
||||
primary tier before GPU can access them
|
||||
4. Transparent retry mechanism — Return None from lookup() to signal
|
||||
"data is being promoted, try later"
|
||||
5. ref_cnt as eviction protection — primary.prepare_read() increments ref_cnt,
|
||||
protecting blocks from eviction until complete_read() is called
|
||||
protecting chunks from eviction until complete_read() is called
|
||||
"""
|
||||
|
||||
import time
|
||||
@@ -61,11 +61,11 @@ logger = init_logger(__name__)
|
||||
|
||||
@dataclass
|
||||
class PendingPromotion:
|
||||
"""Accumulator for blocks awaiting submit_load() for one (tier, request)."""
|
||||
"""Accumulator for chunks awaiting submit_load() for one (tier, request)."""
|
||||
|
||||
req_context: ReqContext
|
||||
keys: list[OffloadKey] = field(default_factory=list)
|
||||
block_ids: list[int] = field(default_factory=list)
|
||||
chunk_ids: list[int] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -94,14 +94,14 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_blocks: int,
|
||||
num_chunks: int,
|
||||
mmap_region: SharedOffloadRegion,
|
||||
cache_policy: str = "lru",
|
||||
cache_policy_module_path: str | None = None,
|
||||
enable_events: bool = False,
|
||||
):
|
||||
super().__init__(
|
||||
num_blocks=num_blocks,
|
||||
num_chunks=num_chunks,
|
||||
cache_policy=cache_policy,
|
||||
cache_policy_module_path=cache_policy_module_path,
|
||||
enable_events=enable_events,
|
||||
@@ -120,9 +120,9 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
|
||||
def get_kv_memoryview(self) -> memoryview:
|
||||
"""Return the memoryview over the primary tier's KV cache buffer.
|
||||
|
||||
The view has shape (num_blocks, row_stride_bytes) and is backed by the
|
||||
SharedOffloadRegion mmap. Secondary tiers address block *b* as
|
||||
``view[b]``.
|
||||
The view has shape (num_chunks, row_stride_bytes) and is backed by the
|
||||
SharedOffloadRegion mmap. Secondary tiers address chunk *c* as
|
||||
``view[c]``.
|
||||
"""
|
||||
return self._kv_memoryview
|
||||
|
||||
@@ -206,14 +206,14 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
assert primary_view.strides is not None
|
||||
self._metrics = TieringMetricsTracker(
|
||||
tier_types=[tier.tier_type for tier in self.secondary_tiers],
|
||||
num_primary_blocks=self.primary_tier._num_blocks,
|
||||
primary_block_size=primary_view.strides[0],
|
||||
num_primary_chunks=self.primary_tier._num_chunks,
|
||||
primary_chunk_size=primary_view.strides[0],
|
||||
)
|
||||
|
||||
# Pending promotion requests accumulated during lookup() calls; flushed
|
||||
# as one batched submit_load() per (tier, request) in on_schedule_end().
|
||||
# Outer key: tier index. Inner key: req_context.req_id — the same ReqContext
|
||||
# object is reused for all block lookups of a given request per engine step.
|
||||
# object is reused for all chunk lookups of a given request per engine step.
|
||||
self._pending_load_submissions: dict[int, dict[str, PendingPromotion]] = {}
|
||||
|
||||
# Gate for once-per-step execution of _maybe_process_finished_jobs().
|
||||
@@ -305,7 +305,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
2. For completed stores (primary→secondary): calls primary.complete_read()
|
||||
to decrement ref_cnt
|
||||
3. For completed loads (secondary→primary): calls primary.complete_write()
|
||||
to make blocks available
|
||||
to make chunks available
|
||||
"""
|
||||
for i, tier in enumerate(self.secondary_tiers):
|
||||
for completed_job in tier.get_finished_jobs():
|
||||
@@ -324,11 +324,11 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
if transfer_job.is_promotion:
|
||||
# secondary→primary transfer (promotion) completed.
|
||||
# Make blocks available in primary tier.
|
||||
# Make chunks available in primary tier.
|
||||
self._complete_promotion(job_metadata, completed_job)
|
||||
else:
|
||||
# primary→secondary transfer completed.
|
||||
# Decrement ref_cnt on primary blocks.
|
||||
# Decrement ref_cnt on primary chunks.
|
||||
self.primary_tier.complete_read(
|
||||
transfer_job.keys, transfer_job.req_context
|
||||
)
|
||||
@@ -342,7 +342,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
exclude_tier_idx: int | None = None,
|
||||
) -> LookupResult:
|
||||
"""
|
||||
Check whether a single block is offloaded and ready.
|
||||
Check whether a single chunk is offloaded and ready.
|
||||
|
||||
Algorithm:
|
||||
1. Process any completed async jobs first.
|
||||
@@ -351,20 +351,20 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
hit and initiate promotion.
|
||||
|
||||
Args:
|
||||
key: Block hash to look up.
|
||||
key: Chunk hash to look up.
|
||||
req_context: Per-request context.
|
||||
|
||||
Returns:
|
||||
HIT — block is ready in the primary tier.
|
||||
HIT_PENDING — block found but not yet readable (write
|
||||
HIT — chunk is ready in the primary tier.
|
||||
HIT_PENDING — chunk found but not yet readable (write
|
||||
in-flight on the primary tier).
|
||||
RETRY — promotion started or a secondary tier is busy.
|
||||
MISS — block not found in any tier, or primary is full
|
||||
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
|
||||
# so blocks freed by cascade or promotion completions are evictable
|
||||
# so chunks freed by cascade or promotion completions are evictable
|
||||
# in time for a promotion this lookup may initiate.
|
||||
self._maybe_process_finished_jobs()
|
||||
|
||||
@@ -424,30 +424,30 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
) -> bool:
|
||||
"""
|
||||
Queue a block 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),
|
||||
then defers the actual submit_load() call to _flush_pending_promotions()
|
||||
so all blocks queued during one engine step are submitted as a single
|
||||
so all chunks queued during one engine step are submitted as a single
|
||||
batched job.
|
||||
|
||||
Args:
|
||||
tier_idx: The secondary tier index to promote from
|
||||
key: Block to promote
|
||||
key: Chunk to promote
|
||||
req_context: Per-request context forwarded to primary.prepare_write().
|
||||
|
||||
Returns:
|
||||
True if promotion was initiated, False if primary tier is full.
|
||||
"""
|
||||
# Allocate space in primary tier for promoted block.
|
||||
# Allocate space in primary tier for promoted chunk.
|
||||
# Must happen immediately so primary.lookup() returns None (in-flight)
|
||||
# for this key on any subsequent lookup() call within the same step,
|
||||
# preventing duplicate promotion attempts.
|
||||
primary_write_result = self.primary_tier.prepare_write([key], req_context)
|
||||
|
||||
if primary_write_result is None:
|
||||
# Primary tier is full; caller should treat the block as unavailable
|
||||
# Primary tier is full; caller should treat the chunk as unavailable
|
||||
# rather than retrying indefinitely.
|
||||
self._metrics.on_promotion_allocation_failure()
|
||||
return False
|
||||
@@ -455,16 +455,16 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
store_spec = primary_write_result.store_spec
|
||||
assert isinstance(store_spec, CPULoadStoreSpec)
|
||||
# Defer submit_load to on_schedule_end(). Group by (tier, request) so
|
||||
# each request's blocks are submitted as one batched job per tier.
|
||||
# each request's chunks are submitted as one batched job per tier.
|
||||
tier_pending = self._pending_load_submissions.setdefault(tier_idx, {})
|
||||
ctx_id = req_context.req_id
|
||||
if ctx_id not in tier_pending:
|
||||
tier_pending[ctx_id] = PendingPromotion(
|
||||
keys=[], block_ids=[], req_context=req_context
|
||||
keys=[], chunk_ids=[], req_context=req_context
|
||||
)
|
||||
entry = tier_pending[ctx_id]
|
||||
entry.keys.extend(primary_write_result.keys_to_store)
|
||||
entry.block_ids.extend(store_spec.block_ids)
|
||||
entry.chunk_ids.extend(store_spec.chunk_ids)
|
||||
return True
|
||||
|
||||
def _flush_pending_promotions(self) -> None:
|
||||
@@ -483,7 +483,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
job_metadata = TransferJob(
|
||||
job_id=job_id,
|
||||
keys=entry.keys,
|
||||
block_ids=np.array(entry.block_ids, dtype=np.int32),
|
||||
chunk_ids=np.array(entry.chunk_ids, dtype=np.int32),
|
||||
is_promotion=True,
|
||||
req_context=entry.req_context,
|
||||
)
|
||||
@@ -497,16 +497,16 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> LoadStoreSpec:
|
||||
"""
|
||||
Prepare blocks 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.
|
||||
|
||||
This increments ref_cnt on the blocks in the primary tier, protecting
|
||||
This increments ref_cnt on the chunks in the primary tier, protecting
|
||||
them from eviction during the transfer.
|
||||
|
||||
Args:
|
||||
keys: Blocks to prepare for loading.
|
||||
keys: Chunks to prepare for loading.
|
||||
req_context: Per-request context.
|
||||
|
||||
Returns:
|
||||
@@ -517,10 +517,10 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
@override
|
||||
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark blocks as recently used in all tiers.
|
||||
Mark chunks as recently used in all tiers.
|
||||
|
||||
Args:
|
||||
keys: Blocks to mark as recently used.
|
||||
keys: Chunks to mark as recently used.
|
||||
req_context: Per-request context.
|
||||
"""
|
||||
self.primary_tier.touch(keys, req_context)
|
||||
@@ -530,13 +530,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
@override
|
||||
def complete_load(self, keys: Collection[OffloadKey], req_context: ReqContext):
|
||||
"""
|
||||
Mark blocks as done loading from primary tier to GPU.
|
||||
Mark chunks as done loading from primary tier to GPU.
|
||||
|
||||
This decrements ref_cnt on the blocks in the primary tier, allowing
|
||||
This decrements ref_cnt on the chunks in the primary tier, allowing
|
||||
them to be evicted again.
|
||||
|
||||
Args:
|
||||
keys: Blocks that finished loading.
|
||||
keys: Chunks that finished loading.
|
||||
req_context: Per-request context.
|
||||
"""
|
||||
self.primary_tier.complete_load(keys, req_context)
|
||||
@@ -546,37 +546,37 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
self, keys: Collection[OffloadKey], req_context: ReqContext
|
||||
) -> PrepareStoreOutput | None:
|
||||
"""
|
||||
Prepare blocks 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
|
||||
before the primary tier makes eviction decisions.
|
||||
|
||||
For request-level tiers, blocks already present in the primary tier
|
||||
For request-level tiers, chunks already present in the primary tier
|
||||
are immediately cascaded via submit_store().
|
||||
|
||||
Args:
|
||||
keys: Blocks to prepare for storing.
|
||||
keys: Chunks to prepare for storing.
|
||||
req_context: Per-request context.
|
||||
|
||||
Returns:
|
||||
PrepareStoreOutput describing where to store blocks and what was
|
||||
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:
|
||||
# - Cascade completions (store to a secondary tier, either a local
|
||||
# cascade or a store job created for a remote requester via
|
||||
# create_store_job()): decrements ref_cnt on the primary blocks
|
||||
# create_store_job()): decrements ref_cnt on the primary chunks
|
||||
# that were read, making them evictable again once ref_cnt hits 0.
|
||||
# - Promotion completions (secondary->primary loads): sets a
|
||||
# not-yet-ready block's ref_cnt from -1 to 0 via complete_write(),
|
||||
# not-yet-ready chunk's ref_cnt from -1 to 0 via complete_write(),
|
||||
# making it evictable for the first time.
|
||||
# Both must be accounted for before the eviction decision below.
|
||||
self._maybe_process_finished_jobs()
|
||||
|
||||
# Step 2: Store to primary tier (new blocks only).
|
||||
# Cascading of these newly-stored blocks to ALL secondary tiers
|
||||
# Step 2: Store to primary tier (new chunks only).
|
||||
# Cascading of these newly-stored chunks to ALL secondary tiers
|
||||
# happens later in complete_store(), after the GPU→Primary transfer
|
||||
# completes.
|
||||
primary_result = self.primary_tier.prepare_store(keys, req_context)
|
||||
@@ -588,7 +588,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
state = self._req_state[req_context.req_id]
|
||||
state.pending_primary_stores += 1
|
||||
|
||||
# Step 3: For request-level tiers, cascade blocks already in primary
|
||||
# Step 3: For request-level tiers, cascade chunks already in primary
|
||||
request_level_tiers = self._req_state[req_context.req_id].request_level_tiers
|
||||
if request_level_tiers:
|
||||
keys_to_store_set = set(primary_result.keys_to_store)
|
||||
@@ -596,13 +596,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
k for k in keys if k not in keys_to_store_set
|
||||
)
|
||||
if keys_already_in_primary:
|
||||
self._cascade_existing_blocks_to_request_level_tiers(
|
||||
self._cascade_existing_chunks_to_request_level_tiers(
|
||||
keys_already_in_primary, req_context, request_level_tiers
|
||||
)
|
||||
|
||||
return primary_result
|
||||
|
||||
def _cascade_existing_blocks_to_request_level_tiers(
|
||||
def _cascade_existing_chunks_to_request_level_tiers(
|
||||
self,
|
||||
keys: Sequence[OffloadKey],
|
||||
req_context: ReqContext,
|
||||
@@ -610,7 +610,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
) -> None:
|
||||
"""
|
||||
For tiers that requested request-level policy, submit_store() for
|
||||
blocks that are already present in the primary tier.
|
||||
chunks that are already present in the primary tier.
|
||||
|
||||
A key whose primary write is still in flight (HIT_PENDING) cannot be
|
||||
dropped: prepare_store already excluded it as present, and the
|
||||
@@ -653,7 +653,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
continue
|
||||
assert state.request_level_tiers
|
||||
keys, state.pending_cascade_keys = state.pending_cascade_keys, []
|
||||
self._cascade_existing_blocks_to_request_level_tiers(
|
||||
self._cascade_existing_chunks_to_request_level_tiers(
|
||||
keys, state.req_context, state.request_level_tiers
|
||||
)
|
||||
self._maybe_finalize_request(req_id)
|
||||
@@ -666,30 +666,30 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
success: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
Mark blocks 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 blocks are
|
||||
This is where secondary tier cascading happens — after chunks are
|
||||
confirmed to be in the primary tier, they are cascaded to ALL
|
||||
secondary tiers.
|
||||
|
||||
For each secondary tier:
|
||||
1. Call primary.prepare_read() to get LoadStoreSpec AND increment
|
||||
ref_cnt (protecting blocks during async transfer)
|
||||
ref_cnt (protecting chunks during async transfer)
|
||||
2. Call tier.submit_store() to start async transfer: primary→secondary
|
||||
3. Track the job in _store_jobs dictionary
|
||||
|
||||
Args:
|
||||
keys: Blocks that finished storing.
|
||||
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 blocks loadable)
|
||||
# Step 1: Complete store in primary tier (makes chunks loadable)
|
||||
self.primary_tier.complete_store(keys, req_context, success)
|
||||
|
||||
if success:
|
||||
# Step 2: Cascade to ALL secondary tiers
|
||||
# For each secondary tier, call primary.prepare_read() to get the
|
||||
# LoadStoreSpec AND to increment ref_cnt (protecting blocks from
|
||||
# LoadStoreSpec AND to increment ref_cnt (protecting chunks from
|
||||
# eviction during the async transfer). One prepare_read() call per
|
||||
# secondary tier.
|
||||
for tier_idx, tier in enumerate(self.secondary_tiers):
|
||||
@@ -710,22 +710,22 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
req_context: ReqContext,
|
||||
tier_idx: int = 0,
|
||||
) -> TransferJob:
|
||||
"""Pin blocks in the primary tier and create a tracked store job.
|
||||
"""Pin chunks in the primary tier and create a tracked store job.
|
||||
|
||||
Calls prepare_read() to increment ref_cnt (protecting blocks
|
||||
Calls prepare_read() to increment ref_cnt (protecting chunks
|
||||
from eviction during the async transfer), allocates a job ID,
|
||||
and registers the job in _jobs.
|
||||
|
||||
The caller is responsible for the actual data transfer and
|
||||
reporting completion via get_finished_jobs().
|
||||
"""
|
||||
primary_blocks_spec = self.primary_tier.prepare_read(keys, req_context)
|
||||
assert isinstance(primary_blocks_spec, CPULoadStoreSpec)
|
||||
primary_chunks_spec = self.primary_tier.prepare_read(keys, req_context)
|
||||
assert isinstance(primary_chunks_spec, CPULoadStoreSpec)
|
||||
job_id = self._next_job_id()
|
||||
job_metadata = TransferJob(
|
||||
job_id=job_id,
|
||||
keys=keys,
|
||||
block_ids=primary_blocks_spec.block_ids,
|
||||
chunk_ids=primary_chunks_spec.chunk_ids,
|
||||
is_promotion=False,
|
||||
req_context=req_context,
|
||||
)
|
||||
@@ -760,7 +760,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
policy = (
|
||||
OffloadPolicy.REQUEST_LEVEL
|
||||
if state.request_level_tiers
|
||||
else OffloadPolicy.BLOCK_LEVEL
|
||||
else OffloadPolicy.CHUNK_LEVEL
|
||||
)
|
||||
return RequestOffloadingContext(policy=policy)
|
||||
|
||||
|
||||
@@ -39,20 +39,20 @@ class _RequestMetricsState:
|
||||
class _TierState:
|
||||
active_promotion_count: int = 0
|
||||
active_cascade_count: int = 0
|
||||
primary_write_block_count: int = 0
|
||||
primary_read_block_count: int = 0
|
||||
primary_write_chunk_count: int = 0
|
||||
primary_read_chunk_count: int = 0
|
||||
|
||||
|
||||
class TieringMetricsTracker:
|
||||
def __init__(
|
||||
self,
|
||||
tier_types: list[str],
|
||||
num_primary_blocks: int,
|
||||
primary_block_size: int,
|
||||
num_primary_chunks: int,
|
||||
primary_chunk_size: int,
|
||||
) -> None:
|
||||
self._tier_types = tier_types
|
||||
self._num_primary_blocks = num_primary_blocks
|
||||
self._primary_block_size = primary_block_size
|
||||
self._num_primary_chunks = num_primary_chunks
|
||||
self._primary_chunk_size = primary_chunk_size
|
||||
self._request_states: dict[str, _RequestMetricsState] = {}
|
||||
self._tier_states = [_TierState() for _ in tier_types]
|
||||
self._stats = OffloadingConnectorStats()
|
||||
@@ -111,13 +111,13 @@ class TieringMetricsTracker:
|
||||
def on_job_registered(self, job_metadata: _JobMetadataLike) -> None:
|
||||
transfer_job = job_metadata.transfer_job
|
||||
state = self._tier_states[job_metadata.tier_idx]
|
||||
block_count = len(transfer_job.block_ids)
|
||||
chunk_count = len(transfer_job.chunk_ids)
|
||||
if transfer_job.is_promotion:
|
||||
state.active_promotion_count += 1
|
||||
state.primary_write_block_count += block_count
|
||||
state.primary_write_chunk_count += chunk_count
|
||||
else:
|
||||
state.active_cascade_count += 1
|
||||
state.primary_read_block_count += block_count
|
||||
state.primary_read_chunk_count += chunk_count
|
||||
|
||||
def on_job_finished(
|
||||
self, job_metadata: _JobMetadataLike, result: JobResult
|
||||
@@ -149,25 +149,25 @@ class TieringMetricsTracker:
|
||||
assert all(
|
||||
state.active_promotion_count == 0
|
||||
and state.active_cascade_count == 0
|
||||
and state.primary_write_block_count == 0
|
||||
and state.primary_read_block_count == 0
|
||||
and state.primary_write_chunk_count == 0
|
||||
and state.primary_read_chunk_count == 0
|
||||
for state in self._tier_states
|
||||
)
|
||||
|
||||
def _decrement_tier_state(self, job_metadata: _JobMetadataLike) -> None:
|
||||
transfer_job = job_metadata.transfer_job
|
||||
state = self._tier_states[job_metadata.tier_idx]
|
||||
block_count = len(transfer_job.block_ids)
|
||||
chunk_count = len(transfer_job.chunk_ids)
|
||||
if transfer_job.is_promotion:
|
||||
assert state.active_promotion_count > 0
|
||||
state.active_promotion_count -= 1
|
||||
state.primary_write_block_count -= block_count
|
||||
assert state.primary_write_block_count >= 0
|
||||
state.primary_write_chunk_count -= chunk_count
|
||||
assert state.primary_write_chunk_count >= 0
|
||||
else:
|
||||
assert state.active_cascade_count > 0
|
||||
state.active_cascade_count -= 1
|
||||
state.primary_read_block_count -= block_count
|
||||
assert state.primary_read_block_count >= 0
|
||||
state.primary_read_chunk_count -= chunk_count
|
||||
assert state.primary_read_chunk_count >= 0
|
||||
|
||||
def _observe_finished_job_stats(
|
||||
self,
|
||||
@@ -199,7 +199,7 @@ class TieringMetricsTracker:
|
||||
if transfer_job.is_promotion
|
||||
else TieringOffloadingMetrics.WRITE_TIME
|
||||
)
|
||||
transfer_size = completed_key_count * self._primary_block_size
|
||||
transfer_size = completed_key_count * self._primary_chunk_size
|
||||
self._stats.increase_counter(bytes_metric, transfer_size, labelvalues)
|
||||
if completed_job.transfer_time is not None:
|
||||
self._stats.increase_counter(
|
||||
@@ -210,13 +210,13 @@ class TieringMetricsTracker:
|
||||
for tier_idx, state in enumerate(self._tier_states):
|
||||
labelvalues = self.tier_label(tier_idx)
|
||||
write_usage = (
|
||||
state.primary_write_block_count / self._num_primary_blocks
|
||||
if self._num_primary_blocks > 0
|
||||
state.primary_write_chunk_count / self._num_primary_chunks
|
||||
if self._num_primary_chunks > 0
|
||||
else 0.0
|
||||
)
|
||||
read_usage = (
|
||||
state.primary_read_block_count / self._num_primary_blocks
|
||||
if self._num_primary_blocks > 0
|
||||
state.primary_read_chunk_count / self._num_primary_chunks
|
||||
if self._num_primary_chunks > 0
|
||||
else 0.0
|
||||
)
|
||||
stats.set_gauge(
|
||||
@@ -248,12 +248,12 @@ class TieringMetricsTracker:
|
||||
async_start_time: float | None,
|
||||
) -> None:
|
||||
self._stats.increase_counter(
|
||||
TieringOffloadingMetrics.BLOCK_QUERIES,
|
||||
TieringOffloadingMetrics.CHUNK_QUERIES,
|
||||
labelvalues=tier_label,
|
||||
)
|
||||
if result is LookupResult.HIT:
|
||||
self._stats.increase_counter(
|
||||
TieringOffloadingMetrics.BLOCK_HITS,
|
||||
TieringOffloadingMetrics.CHUNK_HITS,
|
||||
labelvalues=tier_label,
|
||||
)
|
||||
self._stats.observe_histogram(
|
||||
|
||||
@@ -287,14 +287,14 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
self._store_job_keys[job_metadata.job_id] = list(job_metadata.keys)
|
||||
obj_keys = (self._file_mapper.get_file_name(k) for k in job_metadata.keys)
|
||||
self._submit_transfer(
|
||||
job_metadata.job_id, job_metadata.block_ids, obj_keys, NIXL_WRITE
|
||||
job_metadata.job_id, job_metadata.chunk_ids, obj_keys, NIXL_WRITE
|
||||
)
|
||||
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
self._load_job_keys[job_metadata.job_id] = list(job_metadata.keys)
|
||||
obj_keys = (self._file_mapper.get_file_name(k) for k in job_metadata.keys)
|
||||
self._submit_transfer(
|
||||
job_metadata.job_id, job_metadata.block_ids, obj_keys, NIXL_READ
|
||||
job_metadata.job_id, job_metadata.chunk_ids, obj_keys, NIXL_READ
|
||||
)
|
||||
|
||||
def on_request_finished(self, req_context: ReqContext) -> None:
|
||||
|
||||
@@ -417,7 +417,7 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
def submit_store(self, job_metadata: TransferJob) -> None:
|
||||
job_id = job_metadata.job_id
|
||||
keys = list(job_metadata.keys)
|
||||
block_ids = job_metadata.block_ids.tolist()
|
||||
block_ids = job_metadata.chunk_ids.tolist()
|
||||
|
||||
assert len(keys) == len(block_ids)
|
||||
|
||||
@@ -476,7 +476,7 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
def submit_load(self, job_metadata: TransferJob) -> None:
|
||||
job_id = job_metadata.job_id
|
||||
keys = list(job_metadata.keys)
|
||||
block_ids = job_metadata.block_ids
|
||||
block_ids = job_metadata.chunk_ids
|
||||
|
||||
source = job_metadata.req_context.get_state(P2PSourceInfo)
|
||||
logger.debug(
|
||||
|
||||
@@ -593,7 +593,7 @@ class ServerRole:
|
||||
self.add_stored_blocks(
|
||||
lookup.kv_request_id,
|
||||
list(meta.keys),
|
||||
meta.block_ids.tolist(),
|
||||
meta.chunk_ids.tolist(),
|
||||
meta.job_id,
|
||||
round_seq=lookup.round_seq,
|
||||
from_lookup=True,
|
||||
|
||||
@@ -8,7 +8,7 @@ and configurable secondary tiers (e.g., Storage, Network).
|
||||
|
||||
Configuration via kv_connector_extra_config:
|
||||
- cpu_bytes_to_use: (required) Bytes to allocate for CPU primary tier
|
||||
- block_size: (optional) Block size for offloaded blocks (default: GPU block size)
|
||||
- block_size: (optional) Tokens per offloaded chunk (default: GPU block size)
|
||||
- eviction_policy: (optional) Primary tier eviction policy: built-in "lru"/
|
||||
"arc", or the name of a policy registered via CachePolicyFactory, or an
|
||||
out-of-tree CachePolicy class name paired with cache_policy_module_path
|
||||
@@ -105,7 +105,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
metrics[TieringOffloadingMetrics.LOOKUP_SYNC_DELAY] = (
|
||||
OffloadingHistogramMetadata(
|
||||
documentation=(
|
||||
"Histogram of blocking time spent in a per-block tier lookup "
|
||||
"Histogram of blocking time spent in a per-chunk tier lookup "
|
||||
"that resolved as a hit or miss, labeled by tier, in seconds."
|
||||
),
|
||||
labelnames=("tier",),
|
||||
@@ -127,7 +127,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
metrics[TieringOffloadingMetrics.LOOKUP_ASYNC_DELAY] = (
|
||||
OffloadingHistogramMetadata(
|
||||
documentation=(
|
||||
"Histogram of wall-clock time from a per-block tier lookup "
|
||||
"Histogram of wall-clock time from a per-chunk tier lookup "
|
||||
"first returning retry until that same tier lookup resolves "
|
||||
"as a hit or miss, labeled by tier, in seconds."
|
||||
),
|
||||
@@ -191,14 +191,14 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
labelnames=("tier",),
|
||||
)
|
||||
)
|
||||
metrics[TieringOffloadingMetrics.BLOCK_QUERIES] = OffloadingCounterMetadata(
|
||||
metrics[TieringOffloadingMetrics.CHUNK_QUERIES] = OffloadingCounterMetadata(
|
||||
documentation=(
|
||||
"Number of block lookup queries sent to a tier, labeled by tier."
|
||||
"Number of chunk lookup queries sent to a tier, labeled by tier."
|
||||
),
|
||||
labelnames=("tier",),
|
||||
)
|
||||
metrics[TieringOffloadingMetrics.BLOCK_HITS] = OffloadingCounterMetadata(
|
||||
documentation="Number of block lookup hits in a tier, labeled by tier.",
|
||||
metrics[TieringOffloadingMetrics.CHUNK_HITS] = OffloadingCounterMetadata(
|
||||
documentation="Number of chunk lookup hits in a tier, labeled by tier.",
|
||||
labelnames=("tier",),
|
||||
)
|
||||
metrics[TieringOffloadingMetrics.PROMOTION_ALLOCATION_FAILURES] = (
|
||||
@@ -300,16 +300,16 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
# primary tier can eagerly create a memoryview over _base.
|
||||
scheduler_mmap = SharedOffloadRegion(
|
||||
engine_id=self._engine_id,
|
||||
num_blocks=self.num_blocks,
|
||||
num_chunks=self.num_chunks,
|
||||
rank=None,
|
||||
kv_bytes_per_block=self.kv_bytes_per_chunk,
|
||||
kv_bytes_per_chunk=self.kv_bytes_per_chunk,
|
||||
cpu_page_size=self.cpu_page_size_per_worker,
|
||||
)
|
||||
self._scheduler_mmap = scheduler_mmap
|
||||
|
||||
# Create primary tier (CPU-based)
|
||||
primary_tier = CPUPrimaryTierOffloadingManager(
|
||||
num_blocks=self.num_blocks,
|
||||
num_chunks=self.num_chunks,
|
||||
cache_policy=self.eviction_policy,
|
||||
cache_policy_module_path=self.cache_policy_module_path,
|
||||
enable_events=self.kv_events_config.enable_kv_cache_events,
|
||||
@@ -367,9 +367,9 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
|
||||
logger.info(
|
||||
"Created TieringOffloadingManager with primary tier "
|
||||
"(%s, %s blocks) and %s secondary tier(s)",
|
||||
"(%s, %s chunks) and %s secondary tier(s)",
|
||||
self.eviction_policy,
|
||||
self.num_blocks,
|
||||
self.num_chunks,
|
||||
len(secondary_tiers),
|
||||
)
|
||||
|
||||
@@ -393,9 +393,9 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
rank = torch.accelerator.current_device_index() % world_size
|
||||
worker_mmap = SharedOffloadRegion(
|
||||
engine_id=self._engine_id,
|
||||
num_blocks=self.num_blocks,
|
||||
num_chunks=self.num_chunks,
|
||||
rank=rank,
|
||||
kv_bytes_per_block=self.kv_bytes_per_chunk,
|
||||
kv_bytes_per_chunk=self.kv_bytes_per_chunk,
|
||||
cpu_page_size=self.cpu_page_size_per_worker,
|
||||
)
|
||||
try:
|
||||
@@ -404,7 +404,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
return CPUOffloadingWorker(
|
||||
kv_caches=kv_caches,
|
||||
blocks_per_chunk=self.blocks_per_chunk,
|
||||
num_cpu_blocks=self.num_blocks,
|
||||
num_cpu_chunks=self.num_chunks,
|
||||
mmap_region=worker_mmap,
|
||||
canonical_layout=self.config.canonical_layout,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user