[Refactor][kv_offload]: rename block→chunk (#52615)
Signed-off-by: Ronen Schaffer <ronen.schaffer@ibm.com>
This commit is contained in:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user