[Mini-VLLM] Cut non-OpenAI surfaces, dead kernels, Mistral stack

- Remove Anthropic, Cohere, SageMaker, decisions, structured-decisions,
  rl, render-launcher and batch entrypoints; keep scale-out token routes
- Drop the Swagger static bundle and the /docs, /redoc routes
- Delete device-keyed tuning configs for fused_moe, quant utils, mamba
  select-state and helion; no sm86 entry ever existed for any of them
- Remove ten unused rope variants plus the fbgemm_fp8 and fp_quant
  quantizers and their config, metrics and loader plumbing
- Cut the CPU device build: csrc/cpu, cpu_extension.cmake, cpu
  requirements and the setup.py cpu target path
- Delete 29 environment variables nothing reads and 14 chat-template
  fallbacks for models this fork no longer registers
- Remove nine dead CUDA ops (deepseek_v4, kimi_k3, minimax, muse_spark,
  dsv3 gemm) with their kernels, bindings, wrappers and CMake entries
- Delete the connector test suites that targeted removed connectors
- Cut the Mistral tokenizer and parser stack, its tests, and the
  mistral_common and ijson dependency pins
- Restore the Qwen4Exp registry rows and nvidia/mtp.py that an earlier
  cut deleted while keeping the model tree

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 17:10:56 +07:00
co-authored by Hinata
parent bd70a61c20
commit 2066d3143f
1086 changed files with 122 additions and 291919 deletions
-53
View File
@@ -1,53 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.platforms import current_platform
if current_platform.is_cuda_alike():
from vllm import _custom_ops as ops
elif current_platform.is_xpu():
from vllm._xpu_ops import xpu_ops as ops # type: ignore[no-redef]
class PagedAttention:
@staticmethod
def split_kv_cache(
kv_cache: torch.Tensor,
num_kv_heads: int,
head_size: int,
) -> tuple[torch.Tensor, torch.Tensor]:
x = 16 // kv_cache.element_size()
num_blocks = kv_cache.shape[1]
key_cache = kv_cache[0]
key_cache = key_cache.view(num_blocks, num_kv_heads, head_size // x, -1, x)
value_cache = kv_cache[1]
value_cache = value_cache.view(num_blocks, num_kv_heads, head_size, -1)
return key_cache, value_cache
@staticmethod
def write_to_paged_cache(
key: torch.Tensor,
value: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
slot_mapping: torch.Tensor,
kv_cache_dtype: str,
k_scale: torch.Tensor,
v_scale: torch.Tensor,
interleaved_v: bool,
) -> None:
ops.reshape_and_cache(
key,
value,
key_cache,
value_cache,
slot_mapping.flatten(),
kv_cache_dtype,
k_scale,
v_scale,
interleaved_v,
)
-144
View File
@@ -1,144 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import hashlib
import json
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.canonical_mapping import (
canonical_format_id,
)
from vllm.v1.kv_offload.base import (
OffloadingSpec,
OffloadKey,
get_offload_block_hash,
get_offload_group_idx,
)
_BASE_PATH_HASH_LEN = 12
_CONFIG_FILENAME = "config.json"
class FileMapper:
"""FileMapper maps KV blocks (given by their hash) to file names."""
def __init__(
self,
root_dir: str,
model_name: str,
tokens_per_hash: int,
blocks_per_file: int,
tp_size: int,
pp_size: int,
pcp_size: int,
dcp_size: int,
rank: int,
dtype: str,
kv_cache_groups: list[dict] | None = None,
inference_engine: str = "vllm",
parallel_agnostic: bool = False,
replicated_layout: bool = False,
canonical_format: str | None = None,
):
"""Initialize the file mapper. Each worker constructs its own, but
`config.json` is shared across workers since rank lives outside the hash.
When `parallel_agnostic=True`, tp/pp/pcp/dcp are forced to 1 and rank
to 0 so multiple parallelism layouts collapse into the same folder.
"""
if parallel_agnostic:
tp_size = pp_size = pcp_size = dcp_size = 1
rank = 0
self.rank: int = rank
self.fields: dict = {
"model_name": model_name,
"tokens_per_hash": tokens_per_hash,
"blocks_per_file": blocks_per_file,
"tp_size": tp_size,
"pp_size": pp_size,
"pcp_size": pcp_size,
"dcp_size": dcp_size,
"dtype": str(dtype),
"kv_cache_groups": kv_cache_groups or [],
"inference_engine": inference_engine,
}
if not parallel_agnostic:
self.fields["parallel_agnostic"] = False
# Only written when True so existing deployments' hashed fields are
# unchanged (False is the historical default and must not appear).
if replicated_layout:
self.fields["replicated_layout"] = True
# The canonical byte format is not interchangeable with the direct
# layout (or with other canonical format versions/families), so its
# identity participates in the storage namespace.
if canonical_format is not None:
self.fields["canonical_format"] = canonical_format
self.base_path: str = self._compute_base_path(root_dir, self.fields)
@classmethod
def from_offloading_spec(
cls,
root_dir: str,
offloading_spec: OffloadingSpec,
blocks_per_file: int = 1,
parallel_agnostic: bool = False,
) -> "FileMapper":
"""Build a FileMapper from an OffloadingSpec."""
config = offloading_spec.config
kv_cache_groups = [
{
"tokens_per_block": group.tokens_per_block,
"layer_names": list(group.layer_names),
}
for group in config.groups
]
parallel = config.parallel
canonical_format = None
if config.canonical_layout:
assert config.kv_cache_layout is not None
canonical_format = canonical_format_id(config.kv_cache_layout)
return cls(
root_dir=root_dir,
model_name=config.model.name,
tokens_per_hash=config.cache.tokens_per_hash,
blocks_per_file=blocks_per_file,
tp_size=parallel.tp_size,
pp_size=parallel.pp_size,
pcp_size=parallel.pcp_size,
dcp_size=parallel.dcp_size,
rank=parallel.rank,
dtype=config.model.dtype,
kv_cache_groups=kv_cache_groups,
parallel_agnostic=(
parallel_agnostic
and (parallel.is_parallelism_agnostic or config.replicated_layout)
),
replicated_layout=(parallel_agnostic and config.replicated_layout),
canonical_format=canonical_format,
)
def get_file_name(self, key: OffloadKey) -> str:
"""Map an OffloadKey to <base>_r<rank>/<hhh>/<hh>_g<group_idx>/<hash>.bin."""
hash_hex = get_offload_block_hash(key).hex()
group_idx = get_offload_group_idx(key)
subfolder1, subfolder2 = hash_hex[:3], hash_hex[3:5]
return (
f"{self.base_path}_r{self.rank}"
f"/{subfolder1}/{subfolder2}_g{group_idx}/{hash_hex}.bin"
)
def get_run_config(self) -> dict:
return dict(self.fields)
def get_config_file_path(self) -> str:
return f"{self.base_path}/{_CONFIG_FILENAME}"
@staticmethod
def _compute_base_path(root_dir: str, fields: dict) -> str:
"""Layout: <root_dir>/<safe_model_name>_<sha256-prefix>/.
safe_model_name replaces '/' with '_' so HuggingFace IDs don't nest.
"""
canonical = json.dumps(fields, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[
:_BASE_PATH_HASH_LEN
]
safe_model_name = fields["model_name"].replace("/", "_")
return f"{root_dir}/{safe_model_name}_{digest}"
-290
View File
@@ -1,290 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""AsyncLookupManager: per-tier async lookup manager for secondary tier
existence checks.
Each secondary tier that wants non-blocking lookups composes its own
AsyncLookupManager instance internally. The manager maintains lookup
state and uses a background thread to execute batch_lookup() calls.
Locking design
--------------
There is no explicit lock. Thread safety is achieved by ownership:
* _lookup_state and _lookup_batch are owned by whichever thread holds the
OffloadingManager lock. lookup(), flush(), and cleanup() read and write
them directly. That is usually the scheduler thread, but a tier reached
through ParentManager -- a peer lookup fanning out from another tier, say --
can arrive on the tiering manager's tier-poll thread instead. Both hold
the manager lock, so the accesses stay serialized.
* _lookup_queue is written by the scheduler (flush → put_nowait, one item
per step) and read by the background thread (get). queue.Queue is
thread-safe.
* _pending_results is written by the background thread (put) and read by
the scheduler (get_nowait inside drain_results). queue.SimpleQueue is
thread-safe by design.
lookup() accumulates new keys in _lookup_batch without touching the queue.
flush() is called once per step from the tier's on_schedule_end(), posting
the entire batch as a single queue item so the background thread sees one
batch per step.
Results are drained on the first lookup after each flush, at flush(), and
after worker shutdown. In-flight lookups with no remaining request references
are retained until their results are drained, allowing new requests to share
the same probe.
"""
import queue
import threading
from abc import ABC, abstractmethod
from collections.abc import Collection, Iterable
from dataclasses import dataclass, field
from enum import Enum, auto
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
logger = init_logger(__name__)
class LookupPhase(Enum):
"""Lifecycle phase of a lookup probe."""
PENDING = auto() # Accumulated in _lookup_batch, but not yet submitted.
IN_FLIGHT = auto() # Submitted to the worker, but not yet resolved.
RESOLVED = auto() # A final verdict has been applied to the state.
@dataclass(slots=True)
class LookupState:
generation: int
phase: LookupPhase = LookupPhase.PENDING
# None while pending/in flight; True if the key exists; False if absent or
# explicitly marked missing after a failed load.
result: bool | None = None
request_ids: set[str] = field(default_factory=set) # requests asking for the lookup
class AsyncLookupManager(ABC):
"""Per-tier async lookup manager for secondary tier existence checks.
Each secondary tier that wants non-blocking lookups composes its own
AsyncLookupManager instance internally. The manager maintains lookup
state (cache, queue) and uses a background thread to execute the actual
batch_lookup() calls.
Subclasses implement only batch_lookup() — all queue management,
state tracking, and result delivery is provided by this base class.
The owning tier delegates its lookup(), on_schedule_end(), and
on_request_finished() to this manager:
- lookup() → drain_results() + lookup state check
- on_schedule_end() → flush()
- on_request_finished() → cleanup()
"""
def __init__(
self,
tier_type: str,
) -> None:
self._tier_type = tier_type
# key → LookupState; scheduler-owned, no lock needed.
self._lookup_state: dict[OffloadKey, LookupState] = {}
# req_id → keys looked up by that request (reverse index for cleanup).
self._req_keys: dict[str, set[OffloadKey]] = {}
# Results from an older state must not be applied after cleanup removes
# and recreates a key.
self._next_generation = 0
# Accumulates (key, req_context, generation) triples during lookup().
# Flushed as one queue item per step by flush().
self._lookup_batch: list[tuple[OffloadKey, ReqContext, int]] = []
# Scheduler → worker: one full step's batch per item.
# None is used as a shutdown sentinel.
self._lookup_queue: queue.SimpleQueue[
list[tuple[OffloadKey, ReqContext, int]] | None
] = queue.SimpleQueue()
# Worker → scheduler: completed result batches.
# Each item is a list of (key, generation, found) triples.
# SimpleQueue is explicitly thread-safe for one writer / one reader.
self._pending_results: queue.SimpleQueue[list[tuple[OffloadKey, int, bool]]] = (
queue.SimpleQueue()
)
self._need_to_drain: bool = False
self._thread = threading.Thread(
target=self._worker,
name=f"vllm_offloading_lookup_{tier_type}",
daemon=True,
)
self._thread.start()
@abstractmethod
def batch_lookup(
self, keys: list[OffloadKey], req_context: ReqContext
) -> Iterable[bool]:
"""Check whether a batch of blocks exist in this tier.
Called from the worker thread — must be synchronous and must not
touch the primary tier or scheduler state.
Returns a list parallel to keys: True if present, False if not.
"""
...
# ------------------------------------------------------------------
# Scheduler-thread API
# ------------------------------------------------------------------
def lookup(self, key: OffloadKey, req_context: ReqContext) -> bool | None:
"""Non-blocking lookup called from the scheduler thread.
Returns:
True — block is present in this tier.
False — block is not present in this tier.
None — result not yet available; retry next step.
"""
if self._need_to_drain:
self.drain_results()
self._need_to_drain = False
req_id = req_context.req_id
state = self._lookup_state.get(key)
if state is None:
state = LookupState(generation=self._next_generation)
self._next_generation += 1
self._lookup_state[key] = state
self._lookup_batch.append((key, req_context, state.generation))
state.request_ids.add(req_id)
self._req_keys.setdefault(req_id, set()).add(key)
return state.result
def flush(self) -> None:
"""Post this step's accumulated keys to the worker thread.
Called once per step from on_schedule_end() after all lookup() calls
are done. The worker receives the full batch and processes it during
the model-execution window, maximising time available before the next
step's drain_results(). Also drains completed lookups when there
are no new keys to submit.
"""
self.drain_results()
self._need_to_drain = True
batch = self._lookup_batch
self._lookup_batch = []
in_flight_batch = []
for key, req_context, generation in batch:
state = self._lookup_state.get(key)
if state is None or state.generation != generation:
continue
assert state.phase is LookupPhase.PENDING
state.phase = LookupPhase.IN_FLIGHT
in_flight_batch.append((key, req_context, generation))
if in_flight_batch:
self._lookup_queue.put(in_flight_batch)
def drain_results(self) -> None:
"""Apply pending worker results to _lookup_state.
Called from lookup(), flush(), and shutdown() on the scheduler thread.
"""
while True:
try:
batch = self._pending_results.get_nowait()
except queue.Empty:
break
for key, generation, result in batch:
state = self._lookup_state.get(key)
if state is None or state.generation != generation:
continue
if not state.request_ids:
del self._lookup_state[key]
continue
assert state.phase is LookupPhase.IN_FLIGHT
# Each lookup generation is enqueued exactly once. A matching
# generation must not receive a second result; stale
# generations were discarded above.
assert state.result is None, (
"cached key received a second lookup result; the "
"enqueue-once invariant is broken and could reopen the "
"failed-load livelock"
)
state.result = result
state.phase = LookupPhase.RESOLVED
def mark_miss(self, keys: Collection[OffloadKey]) -> None:
"""Force the cached verdict for ``keys`` to False after a failed load, so
the scheduler stops re-issuing the doomed promotion (livelock, #49176).
Keys with no cached entry are skipped, and so are keys whose entry is
a newer probe still PENDING or IN_FLIGHT: its own result will land,
and forcing it to RESOLVED here would trip the phase asserts in
flush() / drain_results() on the scheduler thread."""
for key in keys:
state = self._lookup_state.get(key)
if state is not None and state.phase is LookupPhase.RESOLVED:
state.result = False
def cleanup(self, req_id: str) -> None:
"""Release request references, retaining in-flight lookups.
Called from the tier's on_request_finished(). Uses the reverse
index to visit only keys associated with this request.
"""
for key in self._req_keys.pop(req_id, ()):
state = self._lookup_state[key]
state.request_ids.discard(req_id)
if not state.request_ids and state.phase is not LookupPhase.IN_FLIGHT:
del self._lookup_state[key]
def shutdown(self) -> None:
"""Stop the worker thread and drain completed lookups."""
self._lookup_queue.put(None) # unblock _worker from _lookup_queue.get()
self._thread.join()
self.drain_results()
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _worker(self) -> None:
while True:
pending = self._lookup_queue.get()
if pending is None:
break
# Group by req_id.
batches: dict[str, tuple[ReqContext, list[tuple[OffloadKey, int]]]] = {}
for key, req_context, generation in pending:
req_id = req_context.req_id
if req_id not in batches:
batches[req_id] = (req_context, [])
batches[req_id][1].append((key, generation))
if not batches:
continue
results: list[tuple[OffloadKey, int, bool]] = []
for req_context, entries in batches.values():
keys = [key for key, _ in entries]
try:
hits = self.batch_lookup(keys, req_context)
except Exception as exc:
logger.warning(
"batch_lookup failed on tier %s for %d keys: %s",
self._tier_type,
len(keys),
exc,
)
hits = (False for _ in keys)
for (key, generation), hit in zip(entries, hits):
results.append((key, generation, hit))
# Post the entire batch as one item — no lock needed.
if results:
self._pending_results.put(results)
-393
View File
@@ -1,393 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import time
from abc import ABC, abstractmethod
class BackpressurePolicy(ABC):
"""Decides what action to take when a detector signals pressure."""
@abstractmethod
def should_store(self, detector: BackpressureDetector) -> bool: ...
@abstractmethod
def on_store_skipped(self, num_blocks: int) -> None: ...
@abstractmethod
def pop_stores_dropped(self) -> tuple[int, int]:
"""Return and reset (stores_dropped, blocks_dropped)."""
...
@abstractmethod
def reset(self) -> None: ...
class DropAccountingPolicy(BackpressurePolicy):
"""Base policy that tracks dropped store/block counters.
Subclasses implement ``should_store``; the shared drop accounting
(``on_store_skipped``/``pop_stores_dropped``/``reset``) lives here so
every policy reports these counters identically. Subclasses that add
their own state override ``reset`` and call ``super().reset()``.
"""
def __init__(self):
self._stores_dropped: int = 0
self._blocks_dropped: int = 0
def on_store_skipped(self, num_blocks: int) -> None:
self._stores_dropped += 1
self._blocks_dropped += num_blocks
def pop_stores_dropped(self) -> tuple[int, int]:
stores, blocks = self._stores_dropped, self._blocks_dropped
self._stores_dropped = 0
self._blocks_dropped = 0
return stores, blocks
def reset(self) -> None:
self._stores_dropped = 0
self._blocks_dropped = 0
class DropStorePolicy(DropAccountingPolicy):
"""Silently drop stores to pressured tiers."""
def should_store(self, detector) -> bool:
return not detector.is_under_pressure()
class ThrottledDropPolicy(DropAccountingPolicy):
"""Drop stores proportionally to pressure severity.
Instead of dropping all stores when pressure is detected, the drop
rate scales with how far the EMA exceeds the high watermark::
overshoot = (ema - high_water) / high_water
drop_rate = min(1.0, overshoot / ramp_factor)
With the default ``ramp_factor=2.0``, stores ramp from 0% drop at
the high watermark to 100% drop at 3x the high watermark. This
keeps secondary tiers populated under moderate pressure, reducing
cache misses (and therefore recomputation / ITL regression) while
still protecting TTFT under severe congestion.
Accumulate ``drop_rate`` across store decisions. When the accumulator
reaches one, drop the store and subtract one from the accumulator,
carrying the remaining fraction into the next decision.
"""
def __init__(self, ramp_factor: float = 2.0):
"""Initialize the drop accumulator and severity ramp."""
super().__init__()
self._drop_accumulator: float = 0.0
self._ramp_factor = ramp_factor
def should_store(self, detector: BackpressureDetector) -> bool:
"""Return whether to allow the store."""
# Proportional throttling needs the EMA and high watermark, which
# only the EMA detector exposes.
assert isinstance(detector, EMABackpressureDetector), (
"ThrottledDropPolicy requires an EMABackpressureDetector"
)
if not detector.is_under_pressure():
return True
ema = detector.store_latency_ema
high = detector._high
if high <= 0:
return False
overshoot = max(0.0, ema - high) / high
drop_rate = min(1.0, overshoot / self._ramp_factor)
if drop_rate <= 0:
return True
if drop_rate >= 1.0:
return False
self._drop_accumulator += drop_rate
if self._drop_accumulator >= 1.0:
self._drop_accumulator -= 1.0
return False
return True
def reset(self) -> None:
"""Clear the drop accumulator and dropped store and block counts."""
super().reset()
self._drop_accumulator = 0.0
class BackpressureDetector(ABC):
"""Observes store completion signals and determines pressure state."""
def __init__(
self,
policy: BackpressurePolicy | None = None,
):
self._policy = policy or ThrottledDropPolicy()
@property
def policy(self) -> BackpressurePolicy:
return self._policy
@abstractmethod
def on_store_completed(self, elapsed_s: float, num_bytes: int) -> None: ...
@abstractmethod
def is_under_pressure(self) -> bool: ...
@abstractmethod
def reset(self) -> None: ...
def update(self, submit_time: float, num_bytes: int) -> None:
"""Update pressure state from a completed store job.
Args:
submit_time: ``time.monotonic()`` when the job was submitted.
num_bytes: Total bytes written (num_blocks * block_size_bytes).
"""
if num_bytes <= 0:
return
elapsed = time.monotonic() - submit_time
self.on_store_completed(elapsed, num_bytes)
def should_store(self, num_blocks: int) -> bool:
"""Check policy and record skip if rejected."""
if not self._policy.should_store(self):
self._policy.on_store_skipped(num_blocks)
return False
return True
@classmethod
def default_config(
cls, tier_type: str, *, locality: str | None = None
) -> dict | None:
"""Return default constructor kwargs for ``tier_type``, or None.
Args:
tier_type: The tier type string (e.g. ``"fs"``, ``"obj"``).
locality: Optional locality hint from the tier config
(``"LOCAL"`` or ``"REMOTE"``). When ``"REMOTE"``, tiers
that would normally get local-storage watermarks (e.g.
``"fs"``) receive network watermarks instead.
"""
return None
@property
def stats(self) -> dict[str, float]:
return {}
class EMABackpressureDetector(BackpressureDetector):
"""EMA of store latency normalized by transfer size.
The EMA tracks seconds per megabyte (s/MiB) so that the metric is
comparable regardless of how many blocks are in a job or how large
each block is. Water marks are in the same unit.
Default water marks are derived from fio benchmarks on the WDC H100
cluster. Two presets are provided:
LOCAL (NVMe/SSD): NVMe sustains ~5 GB/s writes.
high=0.005 s/MiB (~200 MB/s) catches severe congestion;
low=0.001 s/MiB (~1 GB/s) requires meaningful recovery.
NETWORK (CephFS, object store, ``obj``tiers, or any tier
with ``"locality": "REMOTE"``): CephFS sustains ~1.5 GB/s.
high=0.020 s/MiB (~50 MB/s); low=0.005 s/MiB (~200 MB/s).
``obj`` tiers get NETWORK defaults automatically. An
``fs`` tier defaults to LOCAL (appropriate for NVMe/SSD); set
``"locality": "REMOTE"`` in the tier config for network-backed
filesystems like CephFS.
"""
_MIB = 1 << 20
# EMA smoothing factor: higher values (→1) react faster to latency
# spikes but are noisier; lower values (→0) smooth more but lag.
DEFAULT_ALPHA = 0.15
# Number of store completions to collect before seeding the EMA.
# During warmup, pressure is never signalled; the EMA is initialized
# to the mean of the warmup samples to avoid cold-start false positives.
DEFAULT_WARMUP_COMPLETIONS = 10
# When under pressure and no completions arrive, the EMA decays
# toward zero so the detector can eventually recover. The half-life
# controls how quickly: after this many seconds of silence the EMA
# halves. With a 2 s half-life and high_water=0.005, an EMA frozen
# at 0.010 reaches low_water=0.001 in ~6.6 s.
DEFAULT_DECAY_HALF_LIFE_S = 2.0
# After pressure clears, stores are throttled to 50% for this many
# seconds to prevent a burst of stores from re-overwhelming the tier.
DEFAULT_COOLDOWN_S = 1.0
# Number of consecutive sub-low-watermark completions before the
# detector enters a "healthy" fast-path that bypasses policy checks.
_HEALTHY_THRESHOLD = 10
LOCAL_HIGH_WATER_S = 0.010
LOCAL_LOW_WATER_S = 0.002
NETWORK_HIGH_WATER_S = 0.050
NETWORK_LOW_WATER_S = 0.010
_NETWORK_TIER_TYPES = frozenset({"obj"})
@classmethod
def default_config(
cls, tier_type: str, *, locality: str | None = None
) -> dict | None:
is_remote = locality is not None and locality.upper() == "REMOTE"
if is_remote or tier_type in cls._NETWORK_TIER_TYPES:
return {
"high_water_s": cls.NETWORK_HIGH_WATER_S,
"low_water_s": cls.NETWORK_LOW_WATER_S,
}
return {
"high_water_s": cls.LOCAL_HIGH_WATER_S,
"low_water_s": cls.LOCAL_LOW_WATER_S,
}
def __init__(
self,
high_water_s: float,
low_water_s: float,
alpha: float = DEFAULT_ALPHA,
warmup_completions: int = DEFAULT_WARMUP_COMPLETIONS,
decay_half_life_s: float = DEFAULT_DECAY_HALF_LIFE_S,
cooldown_s: float = DEFAULT_COOLDOWN_S,
policy: BackpressurePolicy | None = None,
):
super().__init__(policy=policy)
if not (0 < alpha <= 1):
raise ValueError(f"alpha must be in (0, 1], got {alpha}")
if low_water_s > high_water_s:
raise ValueError(
f"low_water_s ({low_water_s}) must be <= high_water_s ({high_water_s})"
)
self._alpha = alpha
self._high = high_water_s
self._low = low_water_s
self._warmup_completions = warmup_completions
self._decay_half_life_s = decay_half_life_s
self._cooldown_s = cooldown_s
# Exponential moving average of store latency in seconds.
self._ema: float = 0.0
# Whether the tier is currently considered under pressure.
self._under_pressure: bool = False
# Number of store completions observed (for warmup gating).
self._completions: int = 0
# Samples collected during warmup; used to seed the EMA.
self._warmup_samples: list[float] = []
# Monotonic timestamp of the last EMA update; used for idle decay.
self._last_update: float = 0.0
# Consecutive completions with EMA below low watermark.
self._healthy_streak: int = 0
# Monotonic timestamp when pressure was last cleared (for cooldown).
self._pressure_cleared_at: float = 0.0
self._cooldown_count: int = 0
def _apply_idle_decay(self) -> None:
"""Decay the EMA toward zero based on elapsed idle time.
Uses the formula ``ema * 0.5^(dt / half_life)`` so the EMA
halves every ``decay_half_life_s`` seconds of silence. This
lets the detector recover from pressure when no stores are
attempted (and therefore no completions arrive to update the
EMA organically).
"""
now = time.monotonic()
dt = now - self._last_update
if dt <= 0 or self._decay_half_life_s <= 0:
return
self._ema *= 0.5 ** (dt / self._decay_half_life_s)
self._last_update = now
def on_store_completed(self, elapsed_s: float, num_bytes: int) -> None:
now = time.monotonic()
s_per_mib = elapsed_s / (num_bytes / self._MIB)
self._completions += 1
if self._completions <= self._warmup_completions:
self._warmup_samples.append(s_per_mib)
if self._completions == self._warmup_completions:
self._ema = sum(self._warmup_samples) / len(self._warmup_samples)
self._last_update = now
return
self._ema = self._alpha * s_per_mib + (1 - self._alpha) * self._ema
self._last_update = now
if self._ema > self._high:
self._under_pressure = True
self._pressure_cleared_at = 0.0
self._healthy_streak = 0
elif self._ema < self._low:
if self._under_pressure:
self._pressure_cleared_at = now
self._cooldown_count = 0
self._under_pressure = False
self._healthy_streak += 1
else:
self._healthy_streak = 0
def is_under_pressure(self) -> bool:
if self._under_pressure and self._completions >= self._warmup_completions:
self._apply_idle_decay()
if self._ema < self._low:
self._under_pressure = False
self._pressure_cleared_at = time.monotonic()
self._cooldown_count = 0
return self._under_pressure
def is_healthy(self) -> bool:
"""True when the tier has been consistently fast.
After ``_HEALTHY_THRESHOLD`` consecutive store completions with
EMA below the low watermark (and no active pressure), the
detector enters a healthy fast-path: ``should_store()`` returns
``True`` immediately, skipping the policy check entirely.
"""
return (
not self._under_pressure and self._healthy_streak >= self._HEALTHY_THRESHOLD
)
def should_store(self, num_blocks: int) -> bool:
under_pressure = self.is_under_pressure()
if self.is_healthy():
return True
if (
not under_pressure
and self._pressure_cleared_at > 0
and time.monotonic() - self._pressure_cleared_at < self._cooldown_s
):
self._cooldown_count += 1
if self._cooldown_count % 2 == 0:
self._policy.on_store_skipped(num_blocks)
return False
return super().should_store(num_blocks)
def reset(self) -> None:
self._ema = 0.0
self._under_pressure = False
self._completions = 0
self._warmup_samples.clear()
self._last_update = 0.0
self._healthy_streak = 0
self._pressure_cleared_at = 0.0
self._cooldown_count = 0
self._policy.reset()
@property
def store_latency_ema(self) -> float:
return self._ema
@store_latency_ema.setter
def store_latency_ema(self, value: float) -> None:
self._ema = value
@property
def stats(self) -> dict[str, float]:
return {"store_latency_ema": self._ema}
-423
View File
@@ -1,423 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Abstract interfaces and data types for the secondary tiering layer."""
import time
from abc import ABC, abstractmethod
from collections.abc import Collection, Iterable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar
import numpy as np
from vllm.v1.kv_offload.base import (
ConfigInfoMapping,
Locality,
LookupResult,
Medium,
OffloadingEvent,
OffloadingMetricMetadata,
OffloadKey,
ReqContext,
RequestOffloadingContext,
ScheduleEndContext,
)
from vllm.v1.kv_offload.tiering.backpressure import (
BackpressureDetector,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
if TYPE_CHECKING:
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.metrics import (
OffloadingConnectorStats,
)
from vllm.v1.kv_offload.base import OffloadingSpec
# Type alias for job IDs used in async transfer tracking
JobId = int
TIER_LABEL = "tier"
class TieringOffloadingMetrics:
"""Metric names for TieringOffloadingManager."""
LOOKUP_SYNC_DELAY = "vllm:kv_offload_tiering_lookup_sync_delay_seconds"
LOOKUP_ASYNC_DELAY = "vllm:kv_offload_tiering_lookup_async_delay_seconds"
READ_BYTES = "vllm:kv_offload_tiering_read_bytes"
READ_TIME = "vllm:kv_offload_tiering_read_time"
WRITE_BYTES = "vllm:kv_offload_tiering_write_bytes"
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"
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 = (
"vllm:kv_offload_tiering_promotion_allocation_failures"
)
ACTIVE_PROMOTION_JOBS = "vllm:kv_offload_tiering_active_promotion_jobs"
ACTIVE_CASCADE_JOBS = "vllm:kv_offload_tiering_active_cascade_jobs"
BACKPRESSURE_STORE_LATENCY_EMA = (
"vllm:kv_offload_tiering_backpressure_store_latency_ema"
)
BACKPRESSURE_STORES_DROPPED = "vllm:kv_offload_tiering_backpressure_stores_dropped"
BACKPRESSURE_BLOCKS_DROPPED = "vllm:kv_offload_tiering_backpressure_blocks_dropped"
PROMOTION_LATENCY = "vllm:kv_offload_tiering_promotion_latency_seconds"
@dataclass
class TransferJob:
"""Metadata for an in-flight async transfer job."""
job_id: JobId
keys: Collection[OffloadKey]
chunk_ids: np.ndarray
is_promotion: bool
req_context: ReqContext
submit_time: float = field(default_factory=time.monotonic)
@dataclass
class JobResult:
"""Result of an async transfer job."""
job_id: JobId
# True if all keys succeeded; False if all or some failed.
success: bool
# Only applicable to promotion jobs. On partial failure, identifies the
# keys that were successfully loaded. None means all keys share the fate
# indicated by `success`. Must be a subset of the job's original keys.
successful_keys: Collection[OffloadKey] | None = None
transfer_time: float | None = None
transfer_bytes: int | None = None
class ParentManager(ABC):
"""Interface for secondary tiers to call back into the tiering manager.
Passed to secondary tiers via serve_external_requests() each step.
The _SecondaryTierFacingParent wrapper implements this, automatically
excluding the calling tier from fan-out operations.
Required call sequence for each remote request:
1. on_new_request(req_context) — set up per-request state
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
chunks were found, to avoid leaking async lookup state (e.g. in
the fs tier's AsyncLookupManager).
"""
@abstractmethod
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext: ...
@abstractmethod
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult: ...
@abstractmethod
def create_store_job(
self,
keys: Collection[OffloadKey],
req_context: ReqContext,
) -> TransferJob: ...
@abstractmethod
def on_request_finished(self, req_context: ReqContext) -> None: ...
class SecondaryTierManager(ABC):
"""Abstract interface for managing a single non-primary offloading tier.
Secondary tiers cannot directly access GPU memory. All data transfers
must go through the CPU (primary) tier:
- Store: GPU → CPU (primary) → secondary (cascade)
- Load: secondary → CPU (primary) → GPU (promotion)
IMPORTANT: All methods run in the Scheduler process and must be
lightweight and non-blocking. submit_load() and submit_store() submit
async jobs; get_finished_jobs() polls for completion.
Methods are called under the tiering manager's lock, so they are never
entered concurrently -- but not always from the same thread. A tier that
sets tolerates_off_thread_polling is also serviced from the manager's
tier-poll thread, and any tier can be reached from there via
ParentManager fan-out. Keep per-thread assumptions out of tier state.
"""
medium: ClassVar[Medium | None] = None
# Cache tier reported for hits served from this tier. Derived from
# ``medium`` unless a subclass sets it; ``None`` medium means unknown.
cache_hit_source: ClassVar[CacheHitSource] = CacheHitSource.EXTERNAL_UNSPECIFIED
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
if "cache_hit_source" not in cls.__dict__ and cls.medium is not None:
cls.cache_hit_source = {
Medium.CPU: CacheHitSource.HOST,
Medium.STORAGE: CacheHitSource.DISK,
}[cls.medium]
# Whether the tiering manager may also service this tier from its
# tier-poll thread, between engine steps, rather than only from
# on_schedule_end(). That thread calls both get_finished_jobs() and
# serve_external_requests(); see poll_tiers(). Set it on a tier that
# answers a counterpart the engine does not drive -- a remote peer, say --
# whose requests would otherwise wait for a step boundary. Overriding
# serve_external_requests() alone does not opt in: setting this asserts
# the tier tolerates those calls off the scheduler thread.
tolerates_off_thread_polling: ClassVar[bool] = False
def __init__(
self,
offloading_spec: "OffloadingSpec",
primary_kv_view: memoryview,
tier_type: str,
backpressure_detector: BackpressureDetector | None = None,
) -> None:
"""Args:
offloading_spec: Offloading configuration.
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
tier_type: Tier type identifier, set by SecondaryTierFactory
from the registered tier type.
backpressure_detector: Optional `BackpressureDetector`.
"""
self._offloading_spec = offloading_spec
self._primary_kv_view: memoryview = primary_kv_view
assert primary_kv_view.strides is not None, (
"primary_kv_view.strides cannot be None"
)
self._block_size_bytes: int = primary_kv_view.strides[0]
self.tier_type = tier_type
self.locality: Locality | None = None
self._bp_detector = backpressure_detector
@property
def block_size_bytes(self) -> int:
return self._block_size_bytes
@property
def bp_detector(self) -> BackpressureDetector | None:
return self._bp_detector
@abstractmethod
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
"""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 chunk is present and ready,
MISS if not found,
or RETRY if the chunk is being transferred (retry later).
"""
pass
@abstractmethod
def submit_store(self, job_metadata: TransferJob) -> None:
"""Submit an async job to store chunks from the primary tier to this
secondary tier.
This method must be lightweight and non-blocking: allocate metadata
and submit the transfer, but do NOT perform the data copy on the
calling thread.
Preconditions (guaranteed by the framework):
- ``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 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 chunk_ids)
Report completion via ``get_finished_jobs()``.
Args:
job_metadata: Job metadata including job_id, keys, and chunk_ids
identifying the primary-tier slots to read from.
"""
pass
@abstractmethod
def submit_load(self, job_metadata: TransferJob) -> None:
"""Submit an async job to load chunks from this secondary tier to the
primary tier.
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.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 ``chunk_ids``.
Report completion via ``get_finished_jobs()``.
Args:
job_metadata: Job metadata including job_id, keys, and chunk_ids
identifying the primary-tier slots to write into.
"""
pass
@abstractmethod
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Return all jobs (loads and stores) that completed since the last call.
The framework uses these results to release resources and finalize
transfers.
Returns:
Iterable of JobResult objects for jobs finished since the
last call.
"""
pass
def has_pending_work(self) -> bool:
"""Whether this tier needs the engine to keep stepping.
While True, on_schedule_end() and get_finished_jobs() continue
to be called even when no requests are scheduled.
"""
return False
def take_events(self) -> Iterable[OffloadingEvent]:
"""Take KV events for storage state owned by this tier."""
return ()
def touch(self, keys: Collection[OffloadKey], req_context: ReqContext):
"""Mark chunks as recently used for eviction policy.
Args:
keys: Offload keys to mark as recently used.
req_context: Per-request context.
"""
return
@abstractmethod
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
"""Called when a new request is first seen by the scheduler.
Returns a RequestOffloadingContext expressing this tier's preference
for how chunks should be offloaded for this request.
Args:
req_context: Per-request context.
"""
pass
def on_request_finished(self, req_context: ReqContext) -> None:
"""Called when a request has finished.
By the time this is called, all per-request calls for this request
(submit_store, submit_load, touch) have already been issued, and none
will follow. Note this does NOT imply the tier's transfers have
completed: jobs already submitted may still be in flight and will
report via get_finished_jobs(). This is the right place to release
per-request bookkeeping.
Args:
req_context: per-request context.
"""
return
def serve_external_requests(self, parent: ParentManager) -> None:
"""Process remotely-originated requests using the parent manager.
Called once per scheduler step, BEFORE _flush_pending_promotions(), and
additionally once per tier-poll round for tiers that set
tolerates_off_thread_polling. The _flush_pending_promotions() ordering
holds only for the per-step call: a promotion this method initiates from
a tier-poll round is submitted at the next on_schedule_end().
The parent handle is valid only for the duration of this call, and the
caller holds the manager lock throughout it -- so a lookup() HIT taken
here stays valid until this call pins it. An implementation must not
release that lock partway through.
Tiers that don't serve external requests leave this as a no-op. A tier
that overrides it without setting tolerates_off_thread_polling is served
once per step only.
"""
return
def on_schedule_end(self, context: ScheduleEndContext) -> None:
"""Called once at the end of each scheduler step.
Args:
context: Per-step context from the scheduler.
"""
return
@abstractmethod
def drain_jobs(self) -> None:
"""Block until every submitted load/store job has completed or failed.
After this returns, no tier I/O is touching the primary memoryview,
and every submitted job's result is available from `get_finished_jobs()`
(yielded by a prior call or queued for the next one). Used by
`TieringOffloadingManager.reset_cache` to release primary slots
without racing with in-flight transfers.
Implementations must not abort a mid-flight transfer: a partial copy
would corrupt either the primary memoryview or the secondary backing
store. Queued (not-yet-started) transfers may be cancelled, but their
failure result must still appear in `get_finished_jobs()`.
"""
pass
def shutdown(self) -> None:
"""Release resources held by this tier (threads, connections, etc.)."""
return
@classmethod
def build_metric_definitions(
cls, extra_config: dict[str, Any]
) -> dict[str, OffloadingMetricMetadata]:
"""Return Prometheus metric definitions emitted by this tier."""
return {}
def get_stats(self) -> "OffloadingConnectorStats | None":
"""Return and reset metric observations collected by this tier."""
return None
@classmethod
def config_info_keys(cls, tier_config: dict[str, Any]) -> tuple[str, ...]:
"""Return the info metric label names of this tier.
TieringOffloadingSpec merges the names of all tiers and adds
TIER_LABEL, so a tier must not declare it. See ConfigInfo.
Args:
tier_config: Configuration dict of this tier.
"""
return ()
def config_info(self) -> ConfigInfoMapping:
"""Return the info metric labels of this tier, for its one series.
TieringOffloadingManager adds TIER_LABEL. See ConfigInfo.
"""
return {}
@@ -1,205 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ExampleSecondaryTierManager: A simple in-memory secondary tier.
This implementation provides a minimal secondary tier that stores chunks
in memory (using a dictionary) with immediate completion. It serves as a
reference for writing new tiers and is useful for testing the
TieringOffloadingManager without requiring actual storage or network backends.
"""
import logging
from collections.abc import Iterable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, ClassVar
from typing_extensions import override
from vllm.v1.kv_offload.base import (
ConfigInfo,
ConfigInfoMapping,
LookupResult,
Medium,
OffloadKey,
ReqContext,
RequestOffloadingContext,
)
from vllm.v1.kv_offload.tiering.base import (
JobResult,
SecondaryTierManager,
TransferJob,
)
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from vllm.v1.kv_offload.base import OffloadingSpec
from vllm.v1.kv_offload.tiering.backpressure import BackpressureDetector
@dataclass(frozen=True)
class ExampleTierInfo(ConfigInfo):
"""Config facts of one ExampleSecondaryTierManager.
A field name is the label name. A secondary tier needs no name of its own
for the tier, because the tier label tells the series of the tiers apart.
"""
example_info: int
class ExampleSecondaryTierManager(SecondaryTierManager):
"""A simple in-memory secondary tier.
This implementation:
- Stores chunks in a dictionary (key -> True)
- Completes transfers immediately (synchronous)
"""
medium: ClassVar[Medium] = Medium.CPU
def __init__(
self,
offloading_spec: "OffloadingSpec",
primary_kv_view: memoryview,
tier_type: str,
custom_param: int = 0,
backpressure_detector: "BackpressureDetector | None" = None,
):
"""Initialize the example secondary tier.
Args:
offloading_spec: The offloading spec this tier belongs to.
primary_kv_view: Memoryview over the primary tier's KV buffer.
tier_type: Name identifying this tier type.
custom_param: Dummy parameter demonstrating custom args.
backpressure_detector: Optional backpressure detector.
"""
super().__init__(
offloading_spec=offloading_spec,
primary_kv_view=primary_kv_view,
tier_type=tier_type,
backpressure_detector=backpressure_detector,
)
self._config_info = ExampleTierInfo(example_info=custom_param)
logger.info(
"ExampleSecondaryTierManager initialized with custom_param=%d", custom_param
)
# key -> True (only care about presence)
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._chunk_size = primary_kv_view.strides[0]
@classmethod
@override
def config_info_keys(cls, tier_config: dict[str, Any]) -> tuple[str, ...]:
return ExampleTierInfo.config_info_keys()
@override
def config_info(self) -> ConfigInfoMapping:
return self._config_info.as_config_info()
@override
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
"""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 chunk is present, MISS if not found.
"""
return LookupResult.HIT if key in self.chunks else LookupResult.MISS
@override
def submit_store(self, job_metadata: TransferJob) -> None:
"""Submit a job to store chunks from primary tier to this tier.
Args:
job_metadata: Job metadata including job_id, keys, and
spec for reading chunks from the primary tier.
"""
keys = job_metadata.keys
chunk_ids = job_metadata.chunk_ids
assert len(keys) == len(chunk_ids), (
f"Length mismatch: {len(keys)} keys but {len(chunk_ids)} chunk_ids"
)
for key in keys:
self.chunks[key] = True
self.completed_jobs.append(
JobResult(
job_id=job_metadata.job_id,
success=True,
transfer_time=0.0,
)
)
@override
def submit_load(self, job_metadata: TransferJob) -> None:
"""Submit a job to load chunks from this tier to primary tier.
Args:
job_metadata: Job metadata including job_id, keys, and
spec for writing chunks into the primary tier.
"""
keys = job_metadata.keys
chunk_ids = job_metadata.chunk_ids
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.chunks:
self.completed_jobs.append(
JobResult(job_id=job_metadata.job_id, success=False)
)
return
self.completed_jobs.append(
JobResult(
job_id=job_metadata.job_id,
success=True,
transfer_time=0.0,
)
)
@override
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Poll for finished jobs.
Returns:
Iterable of JobResult objects for all jobs that have
finished since the last call.
"""
result = self.completed_jobs
self.completed_jobs = []
return result
@override
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
return RequestOffloadingContext()
@override
def drain_jobs(self) -> None:
"""Synchronous tier — submit_*() returns only after the operation
completes, so there is nothing to wait for."""
return
def get_num_chunks(self) -> int:
"""Get the number of chunks currently stored in this tier."""
return len(self.chunks)
-174
View File
@@ -1,174 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import importlib
from collections.abc import Callable
from typing import TYPE_CHECKING
from vllm.logger import init_logger
from vllm.v1.kv_offload.tiering.base import SecondaryTierManager
if TYPE_CHECKING:
from vllm.v1.kv_offload.backpressure import BackpressureDetector
from vllm.v1.kv_offload.base import OffloadingSpec
logger = init_logger(__name__)
_DEFAULT_PACKAGE = "vllm.v1.kv_offload.tiering.backpressure"
def _import_class(name: str) -> type:
"""Import a class by name.
If ``name`` contains a dot it is treated as a fully qualified path
(e.g. ``'my_package.MyDetector'``). Otherwise it is looked up in
the default backpressure module
(``vllm.v1.kv_offload.tiering.backpressure``), so short names like
``'DropStorePolicy'`` or ``'EMABackpressureDetector'`` work out of
the box.
"""
if "." in name:
module_path, _, class_name = name.rpartition(".")
else:
module_path, class_name = _DEFAULT_PACKAGE, name
module = importlib.import_module(module_path)
return getattr(module, class_name)
class SecondaryTierFactory:
"""Registry for SecondaryTierManager implementations, resolved by type.
Mirrors OffloadingSpecFactory (vllm/v1/kv_offload/factory.py): built-in
tiers are pre-registered below. External tiers can either
register_tier() a friendly short name up front, or skip registration
entirely and pass a module_path at lookup time (out-of-tree, no vLLM
fork/patch required) -- see get_tier_class.
"""
_registry: dict[str, Callable[[], type[SecondaryTierManager]]] = {}
@classmethod
def register_tier(cls, tier_type: str, module_path: str, class_name: str) -> None:
if tier_type in cls._registry:
raise ValueError(f"Tier '{tier_type}' is already registered.")
def loader() -> type[SecondaryTierManager]:
module = importlib.import_module(module_path)
return getattr(module, class_name)
cls._registry[tier_type] = loader
@classmethod
def create_secondary_tier(
cls,
tier_config: dict,
primary_kv_view: memoryview,
offloading_spec: "OffloadingSpec",
) -> SecondaryTierManager:
tier_cls = cls.get_tier_class(tier_config)
config = tier_config.copy()
tier_type = config.pop("type")
config.pop("module_path", None)
locality = config.get("locality")
bp_config = config.pop("backpressure", None)
bp_detector = None
if bp_config is not None:
bp_config = bp_config.copy()
bp_cls_name = bp_config.pop("backpressure_cls", None)
if bp_cls_name is None:
raise ValueError(
"backpressure config must include 'backpressure_cls' "
"(e.g. 'EMABackpressureDetector')"
)
policy_cls_name = bp_config.pop("policy_cls", None)
policy = _import_class(policy_cls_name)() if policy_cls_name else None
detector_cls: type[BackpressureDetector] = _import_class(bp_cls_name)
defaults = detector_cls.default_config(tier_type, locality=locality)
if defaults:
for k, v in defaults.items():
bp_config.setdefault(k, v)
bp_detector = detector_cls(policy=policy, **bp_config)
return tier_cls(
offloading_spec=offloading_spec,
primary_kv_view=primary_kv_view,
tier_type=tier_type,
backpressure_detector=bp_detector,
**config,
)
@classmethod
def get_tier_class(cls, tier_config: dict) -> type[SecondaryTierManager]:
"""Get a secondary tier class by type.
Args:
tier_config: Tier configuration dict. Must contain 'type' (the
tier name or out-of-tree class name). If 'type' is not a
registered tier and 'module_path' is given, the class is
imported from there -- an out-of-tree tier needs no
register_tier() call, just this module path in the config.
Returns:
The secondary tier manager class.
Raises:
ValueError: If 'type' is missing, or is neither registered nor
resolvable via module_path.
"""
tier_type = tier_config.get("type")
if not tier_type:
raise ValueError("Secondary tier configuration must include 'type'")
if tier_type in cls._registry:
return cls._registry[tier_type]()
module_path = tier_config.get("module_path")
if module_path is None:
raise ValueError(
f"Unknown secondary tier type: {tier_type!r}. "
f"Supported types: {list(cls._registry)}. "
"For an out-of-tree tier, also set 'module_path'."
)
logger.warning_once(
"Loading out-of-tree secondary tier. This API is "
"experimental and subject to change in the future "
"as we iterate the design."
)
logger.info(
"Loading out-of-tree secondary tier '%s' from '%s'.",
tier_type,
module_path,
)
module = importlib.import_module(module_path)
tier_cls = getattr(module, tier_type)
assert issubclass(tier_cls, SecondaryTierManager)
return tier_cls
SecondaryTierFactory.register_tier(
"example",
"vllm.v1.kv_offload.tiering.example.manager",
"ExampleSecondaryTierManager",
)
SecondaryTierFactory.register_tier(
"fs",
"vllm.v1.kv_offload.tiering.fs.manager",
"FileSystemTierManager",
)
SecondaryTierFactory.register_tier(
"p2p",
"vllm.v1.kv_offload.tiering.p2p.manager",
"P2PSecondaryTierManager",
)
SecondaryTierFactory.register_tier(
"obj",
"vllm.v1.kv_offload.tiering.obj.manager",
"ObjectStoreSecondaryTierManager",
)
SecondaryTierFactory.register_tier(
"kvcr",
"vllm.v1.kv_offload.tiering.kvcr.manager",
"KVCRSecondaryTierManager",
)
-218
View File
@@ -1,218 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
import logging
import mmap
import os
import random
import threading
try:
from vllm.fs_io_C import ( # pyright: ignore[reportMissingImports]
batch_load_block as batch_load_block_C,
)
from vllm.fs_io_C import (
batch_store_block as batch_store_block_C,
)
_HAS_FSIO_C = True
except ImportError:
_HAS_FSIO_C = False
logger = logging.getLogger(__name__)
# O_DIRECT is Linux-specific and not available on macOS
O_DIRECT = getattr(os, "O_DIRECT", 0)
# Thread-local storage for unique temporary file suffixes
_thread_local = threading.local()
def _get_tmp_suffix() -> str:
"""Generate a thread-local unique suffix for temporary files."""
try:
return _thread_local.tmp_suffix
except AttributeError:
_thread_local.tmp_suffix = f"_{random.randint(0, 2**63 - 1)}.tmp"
return _thread_local.tmp_suffix
def probe_o_direct(directory: str) -> bool:
"""Return whether ``O_DIRECT`` I/O works in *directory*.
``O_DIRECT`` is unsupported on some filesystems (e.g. the overlayfs backing
a container ``/tmp``, older tmpfs, or some NFS mounts), where opening or
writing a file with it fails with ``EINVAL``. Probe once with an aligned
single-page write so callers can fall back to buffered I/O instead of
failing on every block.
"""
if not O_DIRECT:
return False
path = os.path.join(directory, f".o_direct_probe{_get_tmp_suffix()}")
page = mmap.mmap(-1, mmap.PAGESIZE)
try:
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC | O_DIRECT, 0o644)
try:
os.write(fd, page)
finally:
os.close(fd)
return True
except OSError:
return False
finally:
page.close()
with contextlib.suppress(OSError):
os.remove(path)
def _ensure_dirs(path: str) -> None:
"""Create parent directories of *path* if they don't exist."""
os.makedirs(os.path.dirname(path), exist_ok=True)
def _validate_offsets(view: memoryview, offsets: list[int], block_size: int) -> None:
"""Raise if any block would read/write past the bounds of `view`.
Without this, an out-of-range offset silently clips to a shorter (or
empty) slice instead of failing, since memoryview slicing follows
Python's slice-clamping semantics rather than raising.
"""
total_len = len(view.cast("B"))
for offset in offsets:
if offset < 0 or offset + block_size > total_len:
raise ValueError(
f"block offset {offset} (block_size {block_size}) is out of "
f"bounds for a buffer of size {total_len}"
)
def _store_block(
dest_path: str,
buffer: memoryview,
offset: int,
block_size: int,
use_o_direct: bool = True,
) -> None:
"""Store callback: write to a temp file then atomically replace the target."""
# Check if block already exists to avoid redundant writes
if os.path.exists(dest_path):
return
tmp_path = dest_path + _get_tmp_suffix()
# Ensure parent directories exist
_ensure_dirs(dest_path)
# Write block atomically. Cast to a flat byte view so the slice uses byte
# indices; the raw memoryview may be multi-dimensional with itemsize > 1.
view_slice = buffer.cast("B")[offset : offset + block_size]
o_direct = O_DIRECT if use_o_direct else 0
try:
fd = os.open(
tmp_path,
os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_TRUNC | o_direct,
0o644,
)
try:
written = os.write(fd, view_slice)
if written < len(view_slice):
raise OSError(
f"Short write: expected {len(view_slice)} bytes, wrote {written}"
)
finally:
os.close(fd)
os.replace(tmp_path, dest_path)
except Exception:
try:
os.remove(tmp_path)
except OSError as cleanup_exc:
logger.warning("Failed to remove temp file %s: %s", tmp_path, cleanup_exc)
raise
def _load_block(
source_path: str,
view: memoryview,
offset: int,
block_size: int,
use_o_direct: bool = True,
) -> None:
"""Read one KV block from disk; remove the file only on a provable short
read (a too-short file is genuine corruption) and leave it untouched on any
other error."""
fd: int | None = None
view_slice = view.cast("B")[offset : offset + block_size]
o_direct = O_DIRECT if use_o_direct else 0
try:
fd = os.open(source_path, os.O_RDONLY | o_direct)
bytes_read = os.readv(fd, [view_slice])
if bytes_read < block_size:
# A failure to remove must not mask the short-read error below.
try:
os.remove(source_path)
except OSError as cleanup_exc:
logger.warning(
"Failed to remove short-read file %s: %s",
source_path,
cleanup_exc,
)
raise OSError(f"Short read: expected {block_size} bytes, read {bytes_read}")
finally:
if fd is not None:
os.close(fd)
def batch_store_block(
paths: list[str],
view: memoryview,
offsets: list[int],
block_size: int,
use_o_direct: bool = True,
) -> None:
"""Store a batch of KV blocks from a shared buffer to disk in one call.
Each block buffer[offsets[i] : offsets[i]+block_size] is written atomically
to dest_paths[i] via a temp-file rename. Raises on first error.
"""
_validate_offsets(view, offsets, block_size)
if _HAS_FSIO_C:
view_B = view.cast("B")
view_slices = [view_B[x : x + block_size] for x in offsets]
tmp_paths = [p + _get_tmp_suffix() for p in paths]
return batch_store_block_C(tmp_paths, paths, view_slices, use_o_direct)
else:
for path, offset in zip(paths, offsets):
_store_block(path, view, offset, block_size, use_o_direct)
def batch_load_block(
paths: list[str],
view: memoryview,
offsets: list[int],
block_size: int,
use_o_direct: bool = True,
) -> None:
"""Load a batch of KV blocks from disk into a shared buffer in one call.
Block i is read from source_paths[i] into view[offsets[i] : offsets[i]+block_size].
Raises on first error (see _load_block for the delete-on-short-read policy).
On failure the raised OSError carries ``num_succeeded`` = the number of
blocks loaded before the failing one, so the tier can keep them.
"""
_validate_offsets(view, offsets, block_size)
if _HAS_FSIO_C:
view_B = view.cast("B")
view_slices = [view_B[x : x + block_size] for x in offsets]
return batch_load_block_C(paths, view_slices, use_o_direct)
else:
for i, (path, offset) in enumerate(zip(paths, offsets)):
try:
_load_block(path, view, offset, block_size, use_o_direct)
except OSError as exc:
# Blocks 0..i-1 loaded fine; record the count for partial keep.
# The C path sets the same attribute via PyObject_SetAttrString.
exc.num_succeeded = i # type: ignore[attr-defined]
raise
-353
View File
@@ -1,353 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FileSystemTierManager: pure-Python filesystem tier for KV cache offloading.
Store path:
Data is written to a temp file (<dest_path.tmp>) via os.write,
then os.replace'd to the final path (without .tmp).
Load path:
Data is read from the block file directly via os.readv into the
provided memoryview slice.
File naming: <base_path>_r<rank>/<hhh>/<hh>_g<group_idx>/<hash_hex>.bin
(hash-based subdirectories to limit directory fan-out)
"""
import functools
import json
import os
from collections.abc import Iterable
from typing import TYPE_CHECKING, ClassVar
try:
from vllm.fs_io_C import batch_lookup as batch_lookup_C
_HAS_BATCH_LOOKUP_C = True
except ImportError:
_HAS_BATCH_LOOKUP_C = False
from typing_extensions import override
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import (
Locality,
LookupResult,
Medium,
OffloadingEvent,
OffloadKey,
ReqContext,
)
from vllm.v1.kv_offload.file_mapper import FileMapper
from vllm.v1.kv_offload.tiering.async_lookup import AsyncLookupManager
from vllm.v1.kv_offload.tiering.backpressure import BackpressureDetector
from vllm.v1.kv_offload.tiering.base import (
JobId,
JobResult,
RequestOffloadingContext,
ScheduleEndContext,
SecondaryTierManager,
TransferJob,
)
from vllm.v1.kv_offload.tiering.fs.io import (
batch_load_block,
batch_store_block,
probe_o_direct,
)
from vllm.v1.kv_offload.tiering.fs.thread_pool import DualQueueThreadPool
if TYPE_CHECKING:
from vllm.v1.kv_offload.base import OffloadingSpec
logger = init_logger(__name__)
class FsAsyncLookupManager(AsyncLookupManager):
"""Async lookup manager for FileSystemTierManager."""
def __init__(
self,
tier: "FileSystemTierManager",
tier_type: str,
) -> None:
super().__init__(tier_type=tier_type)
self._tier = tier
def batch_lookup(
self, keys: list[OffloadKey], req_context: ReqContext
) -> Iterable[bool]:
paths = [self._tier.file_mapper.get_file_name(k) for k in keys]
if _HAS_BATCH_LOOKUP_C:
# C extension: GIL released for the entire faccessat() batch.
return batch_lookup_C(paths)
return (os.path.exists(p) for p in paths)
class FileSystemTierManager(SecondaryTierManager):
"""Pure-Python disk-backed secondary tier.
Read-priority threads service load jobs preferentially; write-priority
threads service store jobs preferentially. Both groups can drain either
queue, so neither starves.
submit_store / submit_load are non-blocking: they enqueue tasks and return.
get_finished_jobs() polls job completion and returns completed JobResults.
Cross-process sharing:
KV cache sharing between multiple vLLM instances using the same
``root_dir`` (e.g., via a shared PVC) works by default: ``NONE_HASH``
(the chain-hash seed for block content hashes) is derived from a fixed
default seed, so identical token content produces identical block
filenames across instances. Setting the ``PYTHONHASHSEED`` environment
variable to the same value on all instances overrides the default seed,
and is required to share a cache when using a non-cryptographic
prefix-caching hash algorithm, which seeds ``NONE_HASH`` randomly.
"""
medium: ClassVar[Medium] = Medium.STORAGE
def __init__(
self,
offloading_spec: "OffloadingSpec",
primary_kv_view: memoryview,
tier_type: str,
root_dir: str,
n_read_threads: int = 16,
n_write_threads: int = 16,
enable_kv_events: bool = False,
locality: str | None = None,
backpressure_detector: BackpressureDetector | None = None,
):
"""Args:
offloading_spec: Contains normalized offloading configuration and
blocks_per_chunk.
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
tier_type: Tier type identifier, set by SecondaryTierFactory.
root_dir: Root directory for block files.
n_read_threads: Number of read-priority I/O threads.
n_write_threads: Number of write-priority I/O threads.
enable_kv_events: Emit BlockStored KV events for blocks
successfully stored to this tier. Effective only when KV
cache events are enabled globally (kv_events_config).
locality: Whether this tier's storage is LOCAL or REMOTE relative
to the publishing vLLM instance.
backpressure_detector: Optional backpressure detector.
"""
super().__init__(
offloading_spec, primary_kv_view, tier_type, backpressure_detector
)
self.locality = Locality(locality) if locality is not None else None
self.events: list[OffloadingEvent] | None = None
if enable_kv_events:
if offloading_spec.kv_events_config.enable_kv_cache_events:
self.events = []
else:
logger.warning(
"enable_kv_events is set on secondary tier '%s' but KV "
"cache events are disabled globally; the tier will not "
"emit events.",
tier_type,
)
# Keys of in-flight store jobs, tracked only when events are enabled.
self._store_job_keys: dict[JobId, list[OffloadKey]] = {}
# Keys of in-flight load (promotion) jobs, so a failed load can mark
# its own cached lookup verdicts False (see get_finished_jobs).
self._load_job_keys: dict[JobId, list[OffloadKey]] = {}
# Block count per in-flight job, used to report transfer_bytes.
self._job_block_counts: dict[JobId, int] = {}
# Per load job: how many blocks loaded before a failure (partial keep).
# Written by the pool worker inside the load task before it raises (so
# before task_done publishes the job); read on the scheduler thread in
# get_finished_jobs only for job ids the finished queue returned. Under
# the GIL that read cannot observe the finished job without the prior
# write, so no extra lock is needed (get_finished is itself lock-free).
self._load_progress: dict[JobId, int] = {}
# Extract block size from primary view
assert primary_kv_view.strides is not None, (
"primary_kv_view.strides cannot be None"
)
self._block_size: int = primary_kv_view.strides[0]
# Opt in; FileMapper enables it only for a parallelism-invariant block.
self.file_mapper = FileMapper.from_offloading_spec(
root_dir=root_dir,
offloading_spec=offloading_spec,
blocks_per_file=offloading_spec.blocks_per_chunk,
parallel_agnostic=True,
)
# Write config file
config_path = self.file_mapper.get_config_file_path()
os.makedirs(os.path.dirname(config_path), exist_ok=True)
if not os.path.exists(config_path):
with open(config_path, "w") as f:
json.dump(
self.file_mapper.get_run_config(), f, indent=2, sort_keys=True
)
# Prefer O_DIRECT to bypass the page cache, but fall back to buffered
# I/O on filesystems that reject it (e.g. overlayfs, some NFS mounts)
# rather than failing every block.
self._use_o_direct = probe_o_direct(os.path.dirname(config_path))
if not self._use_o_direct:
logger.warning(
"O_DIRECT is not supported at '%s'; falling back to buffered "
"I/O for the '%s' KV offload tier.",
root_dir,
tier_type,
)
self._pool = DualQueueThreadPool(
n_read_threads,
n_write_threads,
thread_name_prefix="vllm_kv_py_fs",
)
self._lookup_manager = FsAsyncLookupManager(tier=self, tier_type=self.tier_type)
@override
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
return RequestOffloadingContext()
@override
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
result = self._lookup_manager.lookup(key, req_context)
if result is None:
return LookupResult.RETRY
return LookupResult.HIT if result else LookupResult.MISS
@override
def submit_store(self, job_metadata: TransferJob) -> None:
keys = list(job_metadata.keys)
if self.events is not None:
self._store_job_keys[job_metadata.job_id] = keys
task = functools.partial(
batch_store_block,
[self.file_mapper.get_file_name(key) for key in keys],
self._primary_kv_view,
[int(cid) * self._block_size for cid in job_metadata.chunk_ids],
self._block_size,
self._use_o_direct,
)
self._job_block_counts[job_metadata.job_id] = len(keys)
self._pool.enqueue_store(job_metadata.job_id, 1, [task])
@override
def submit_load(self, job_metadata: TransferJob) -> None:
job_id = job_metadata.job_id
# Track this load's keys so a failed promotion can mark only its failed
# keys as a miss (see get_finished_jobs).
keys = list(job_metadata.keys)
self._load_job_keys[job_id] = keys
self._job_block_counts[job_id] = len(keys)
paths = [self.file_mapper.get_file_name(key) for key in keys]
offsets = [int(cid) * self._block_size for cid in job_metadata.chunk_ids]
def load_task() -> None:
try:
batch_load_block(
paths,
self._primary_kv_view,
offsets,
self._block_size,
self._use_o_direct,
)
except OSError as exc:
# Runs on the pool worker thread. Record how many blocks loaded
# before the failure so get_finished_jobs can keep them; this
# write precedes task_done, so the scheduler reads it safely
# under the GIL once the finished queue hands back this job.
num_succeeded = getattr(exc, "num_succeeded", 0)
self._load_progress[job_id] = num_succeeded
# Surfaces errno (e.g. EMFILE "Too many open files") for both
# the C and Python load paths.
logger.debug(
"Load of %d blocks for job %s failed at block %d: %s",
len(paths),
job_id,
num_succeeded,
exc,
)
raise
self._pool.enqueue_load(job_id, 1, [load_task])
@override
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Collect finished jobs; a failed promotion marks only its failed keys
as a miss here (scheduler thread)."""
results = []
for job_id, success, transfer_time in self._pool.get_finished():
block_count = self._job_block_counts.pop(job_id, 0)
transfer_bytes = block_count * self._block_size if block_count else None
if self.events is not None:
keys = self._store_job_keys.pop(job_id, None)
if success and keys:
self.events.append(
OffloadingEvent(
keys=keys,
medium=self.medium,
removed=False,
locality=self.locality,
)
)
load_keys = self._load_job_keys.pop(job_id, None)
num_succeeded = self._load_progress.pop(job_id, 0)
if load_keys is not None and not success:
# A batched load stops at the first bad block and reports how
# many loaded before it. Those earlier blocks are kept in the
# primary tier (reported via successful_keys); only this block
# and the ones after it are marked a miss and recomputed.
successful = load_keys[:num_succeeded]
failed = load_keys[num_succeeded:]
self._lookup_manager.mark_miss(failed)
results.append(
JobResult(
job_id=job_id,
success=False,
successful_keys=tuple(successful) if successful else None,
transfer_time=transfer_time,
transfer_bytes=transfer_bytes,
)
)
continue
results.append(
JobResult(
job_id=job_id,
success=success,
transfer_time=transfer_time,
transfer_bytes=transfer_bytes,
)
)
return results
@override
def take_events(self) -> Iterable[OffloadingEvent]:
if self.events is not None:
yield from self.events
self.events.clear()
@override
def drain_jobs(self) -> None:
"""Block until all in-flight transfers in the threadpool finish."""
self._pool.wait_idle()
def on_request_finished(self, req_context: ReqContext) -> None:
self._lookup_manager.cleanup(req_context.req_id)
@override
def on_schedule_end(self, context: ScheduleEndContext) -> None:
self._lookup_manager.flush()
@override
def shutdown(self) -> None:
"""Release resources held by this tier.
Shuts down the lookup manager and the thread pool,
clearing pending tasks and waiting for active threads to complete.
"""
self._lookup_manager.shutdown()
self._pool.shutdown(wait=True)
@@ -1,194 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Thread pool:
Two queues (load, store) and two sets of threads:
- Load-priority threads: drain the load queue first, then the store queue.
- Store-priority threads: drain the store queue first, then the load queue.
Load jobs are enqueued to the load queue; store jobs to the store queue.
"""
import threading
import time
from collections import deque
from collections.abc import Callable, Iterable
from vllm.logger import init_logger
from vllm.v1.kv_offload.tiering.base import JobId
logger = init_logger(__name__)
class JobState:
"""Thread-safe completion tracker for a set of per-block I/O tasks.
Each task calls task_done(success) when it finishes.
"""
__slots__ = (
"_job_id",
"_n_tasks",
"_completed",
"_success",
"_transfer_time",
"_lock",
)
def __init__(self, job_id: JobId, n_tasks: int) -> None:
self._job_id: JobId = job_id
self._n_tasks = n_tasks
self._completed = 0
self._success = True
self._transfer_time = 0.0
self._lock = threading.Lock()
@property
def job_id(self) -> JobId:
return self._job_id
def task_done(
self, success: bool, transfer_time: float
) -> tuple[bool, bool, float]:
"""Returns if job completed and success flag."""
with self._lock:
self._completed += 1
self._transfer_time += transfer_time
if not success:
self._success = False
return self._completed == self._n_tasks, self._success, self._transfer_time
class DualQueueThreadPool:
"""Thread pool with two task queues (load and store) and two thread groups.
Load-priority threads drain the load queue first, then fall back to the
store queue. Store-priority threads do the reverse. Both queues share
a single condition variable.
"""
def __init__(
self,
n_read_threads: int,
n_write_threads: int,
thread_name_prefix: str = "fs_secondary_tier",
) -> None:
self._load_q: deque = deque()
self._store_q: deque = deque()
self._condition = threading.Condition(threading.Lock())
self._stop = False
self._threads: list[threading.Thread] = []
self._finished_q: deque[tuple[JobId, bool, float]] = deque()
self._inflight_jobs = 0 # guarded by _condition
for i in range(n_read_threads):
t = threading.Thread(
target=self._worker,
args=(True,),
name=f"{thread_name_prefix}_l{i}",
daemon=True,
)
t.start()
self._threads.append(t)
for i in range(n_write_threads):
t = threading.Thread(
target=self._worker,
args=(False,),
name=f"{thread_name_prefix}_s{i}",
daemon=True,
)
t.start()
self._threads.append(t)
def enqueue_load(
self,
job_id: JobId,
n_tasks: int,
tasks: Iterable[Callable],
) -> None:
"""Enqueue load tasks for a job (high-priority for load-priority threads)."""
state = JobState(job_id, n_tasks)
with self._condition:
self._inflight_jobs += 1
for fn in tasks:
self._load_q.append((fn, state))
self._condition.notify(n_tasks)
def enqueue_store(
self,
job_id: JobId,
n_tasks: int,
tasks: Iterable[Callable],
) -> None:
"""Enqueue store tasks for a job (high-priority for store-priority threads)."""
state = JobState(job_id, n_tasks)
with self._condition:
self._inflight_jobs += 1
for fn in tasks:
self._store_q.append((fn, state))
self._condition.notify(n_tasks)
def get_finished(self) -> list[tuple[JobId, bool, float]]:
# No lock needed: deque is thread-safe for concurrent append/popleft,
# and the manager is the sole popper.
jobs = []
while self._finished_q:
jobs.append(self._finished_q.popleft())
return jobs
def wait_idle(self) -> None:
"""Block until there are no in-flight jobs.
After this returns, every submitted job has had its last task
finish, so no worker thread is still copying data. Note:
completed jobs may still be sitting in ``_finished_q`` waiting
for ``get_finished()`` to drain them.
"""
with self._condition:
self._condition.wait_for(lambda: self._inflight_jobs == 0)
def shutdown(self, wait: bool = True) -> None:
with self._condition:
self._stop = True
self._load_q.clear()
self._store_q.clear()
# Cancelled tasks will not decrement _inflight_jobs; reset it so a
# subsequent wait_idle() returns instead of hanging.
self._inflight_jobs = 0
self._condition.notify_all()
if wait:
for t in self._threads:
t.join()
def _worker(self, load_priority: bool) -> None:
# Wait for tasks, process from primary queue first, fall back to secondary.
while True:
with self._condition:
self._condition.wait_for(
lambda: self._stop or self._load_q or self._store_q
)
if self._stop:
return
primary = self._load_q if load_priority else self._store_q
secondary = self._store_q if load_priority else self._load_q
task, state = primary.popleft() if primary else secondary.popleft()
try:
start_time = time.monotonic()
task()
transfer_time = time.monotonic() - start_time
job_finished, success, total_time = state.task_done(True, transfer_time)
except Exception as exc:
transfer_time = time.monotonic() - start_time
logger.error(
"Job %s block I/O failed: %s",
state.job_id,
exc,
)
job_finished, success, total_time = state.task_done(
False, transfer_time
)
if job_finished:
with self._condition:
self._finished_q.append((state.job_id, success, total_time))
self._inflight_jobs -= 1
self._condition.notify_all()
@@ -1,2 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
-655
View File
@@ -1,655 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""vLLM secondary-tier adapter for KVCR."""
import ctypes
import mmap
import socket
import time
import uuid
from collections.abc import Collection, Iterable
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar, cast
import msgspec
from kvcr import (
DURATION_METRIC,
KVCR,
ROUTER_HINT_CAPABILITIES,
STATE_METRIC,
TRANSFER_BLOCKS_METRIC,
TRANSFER_BYTES_METRIC,
KVCRBindings,
)
from kvcr.config import (
G3Options,
KeyAdapter,
KVCRBackendConfigs,
KVCRConfig,
KVCRGuardConfig,
LocalDramOptions,
RemoteFWDramOptions,
)
from kvcr.control_channels import ZmqPeerControlChannel
from kvcr.policy import (
FIFOPolicy,
G3FIFOPolicy,
G3LRUPolicy,
KVCachePolicy,
LRUPolicy,
)
from kvcr.types import (
BlockKey,
CacheTier,
InventoryEvent,
KVCRStartupError,
MemoryRef,
OpHandle,
PinRequestId,
PinResult,
QueryStatus,
RegionDescriptor,
)
from typing_extensions import override
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.metrics import (
OffloadingConnectorStats,
)
from vllm.logger import init_logger
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.v1.core.kv_cache_utils import (
BlockHash,
maybe_convert_block_hash,
)
from vllm.v1.kv_offload.base import (
LookupResult,
Medium,
OffloadingCounterMetadata,
OffloadingEvent,
OffloadingGaugeMetadata,
OffloadingHistogramMetadata,
OffloadingMetricMetadata,
OffloadKey,
ReqContext,
RequestOffloadingContext,
get_offload_block_hash,
)
from vllm.v1.kv_offload.tiering.base import (
JobResult,
ParentManager,
SecondaryTierManager,
TransferJob,
)
if TYPE_CHECKING:
from vllm.v1.kv_offload.base import OffloadingSpec
from vllm.v1.kv_offload.tiering.backpressure import BackpressureDetector
_REQUIRED_ROUTER_CAPABILITIES = ROUTER_HINT_CAPABILITIES
logger = init_logger(__name__)
_BUILTIN_POLICIES: dict[str, type[KVCachePolicy]] = {
"fifo": FIFOPolicy,
"lru": LRUPolicy,
"g3_fifo": G3FIFOPolicy,
"g3_lru": G3LRUPolicy,
}
def _resolve_policy(name: str | None) -> KVCachePolicy | None:
if name is None:
return None
policy_type = _BUILTIN_POLICIES.get(name)
if policy_type is None:
if "." not in name:
raise ValueError(
f"Unknown KVCR policy: {name!r}. "
f"Supported: {list(_BUILTIN_POLICIES)}; external policies "
"must use a fully qualified module.Class path."
)
policy_type = resolve_obj_by_qualname(name)
if not isinstance(policy_type, type) or not issubclass(
policy_type, KVCachePolicy
):
raise TypeError(f"{name} is not a KVCachePolicy")
return policy_type()
def _vllm_metric_name(name: str) -> str:
return f"vllm:{name}"
def _kvcr_metric_definitions() -> dict[str, OffloadingMetricMetadata]:
return {
_vllm_metric_name(DURATION_METRIC): OffloadingHistogramMetadata(
documentation="KVCR operation and stage duration in seconds.",
labelnames=("scope", "result"),
),
_vllm_metric_name(TRANSFER_BYTES_METRIC): OffloadingCounterMetadata(
documentation="Bytes transferred by KVCR operations.",
labelnames=("operation",),
),
_vllm_metric_name(TRANSFER_BLOCKS_METRIC): OffloadingCounterMetadata(
documentation="KV blocks transferred by successful KVCR operations.",
labelnames=("operation",),
),
_vllm_metric_name(STATE_METRIC): OffloadingGaugeMetadata(
documentation="Current KVCR metadata and operation counts.",
labelnames=("resource",),
),
}
class _FrameworkPinAdapter:
"""Adapt KVCR framework pin callbacks to primary-tier store jobs."""
def __init__(self, tier: "KVCRSecondaryTierManager") -> None:
self._tier = tier
self._next_request_id = 0
self._next_pin_request_id = 0
self._pending_pins: dict[PinRequestId, tuple[BlockKey, ...]] = {}
self._completed_pins: list[tuple[PinRequestId, PinResult]] = []
self._pin_jobs: dict[str, int] = {}
self._pin_job_results: list[JobResult] = []
def request_pin(self, keys: Collection[BlockKey]) -> PinRequestId:
# The parent callback is valid only from serve_external_requests().
request = PinRequestId(self._next_pin_request_id)
self._next_pin_request_id += 1
self._pending_pins[request] = tuple(keys)
return request
def process_pending(self, parent: ParentManager) -> None:
pending = self._pending_pins
self._pending_pins = {}
self._completed_pins.extend(
(request, self._resolve_pin(parent, keys))
for request, keys in pending.items()
)
def poll_pin_results(self) -> list[tuple[PinRequestId, PinResult]]:
completed = self._completed_pins
self._completed_pins = []
return completed
def cancel_pin_request(self, request: PinRequestId) -> None:
self._pending_pins.pop(request, None)
def _resolve_pin(
self, parent: ParentManager, keys: Collection[BlockKey]
) -> tuple[str, dict[BlockKey, list[MemoryRef] | None]] | None:
offload_keys = tuple(OffloadKey(bytes(key)) for key in keys)
request_id = f"kvcr-source:{self._next_request_id}"
self._next_request_id += 1
req_context = ReqContext(req_id=request_id)
started = False
job: TransferJob | None = None
pin_handle: str | None = None
try:
parent.on_new_request(req_context)
started = True
hit_keys = tuple(
key
for key in offload_keys
if parent.lookup(key, req_context) is LookupResult.HIT
)
if not hit_keys:
return None
job = parent.create_store_job(hit_keys, req_context)
job_keys = tuple(job.keys)
chunk_ids = tuple(int(chunk_id) for chunk_id in job.chunk_ids)
if len(job_keys) != len(chunk_ids) or set(job_keys) != set(hit_keys):
return None
descriptors: dict[BlockKey, list[MemoryRef] | None] = {
BlockKey(bytes(key)): None for key in offload_keys
}
descriptors.update(
(
BlockKey(bytes(key)),
[self._tier._make_descriptor(chunk_id)],
)
for key, chunk_id in zip(job_keys, chunk_ids)
)
pin_handle = f"kvcr-job-{job.job_id}"
self._pin_jobs[pin_handle] = job.job_id
return pin_handle, descriptors
except Exception:
logger.warning("KVCR source acquisition failed", exc_info=True)
return None
finally:
if started:
try:
parent.on_request_finished(req_context)
except Exception:
logger.warning("KVCR source request cleanup failed", exc_info=True)
if job is not None and pin_handle is None:
self._pin_job_results.append(
JobResult(job_id=job.job_id, success=False)
)
def release_pin(self, pin_handle: str) -> bool:
job_id = self._pin_jobs.pop(pin_handle, None)
if job_id is not None:
self._pin_job_results.append(JobResult(job_id=job_id, success=True))
return True
def has_active_pins(self) -> bool:
return bool(self._pin_jobs)
def take_pin_job_results(self) -> list[JobResult]:
results = self._pin_job_results
self._pin_job_results = []
return results
class _VllmKeyAdapter:
"""Adapt vLLM's local key format to KVCR."""
def encode(self, framework_key: object) -> BlockKey:
if not isinstance(framework_key, bytes):
raise TypeError("vLLM offload keys must be bytes")
return BlockKey(framework_key)
def decode(self, key: BlockKey) -> int | bytes:
block_hash = BlockHash(get_offload_block_hash(OffloadKey(key)))
return maybe_convert_block_hash(block_hash)
# Job ID, remaining blocks, aggregate success, and successful load keys.
_JobState = tuple[int, int, bool, set[OffloadKey] | None]
# Held for the process lifetime after a startup failure that could not stop
# native work: an export blocks close() and keeps the mapping alive against GC,
# so nothing can unmap memory NIXL may still be writing into.
_RETAINED_NATIVE_BUFFERS: list[object] = []
class KVCRSecondaryTierManager(SecondaryTierManager):
"""Secondary tier wrapper around the KVCR KV P2P API."""
# Serves framework pin requests from serve_external_requests(), but only
# once per step for now: opting in would also poll the KVCR library from
# the tiering manager's polling thread, which it is not yet verified to
# tolerate.
tolerates_off_thread_polling: ClassVar[bool] = False
@classmethod
@override
def build_metric_definitions(
cls, extra_config: dict[str, Any]
) -> dict[str, OffloadingMetricMetadata]:
if not extra_config.get("enable_telemetry", False):
return {}
return _kvcr_metric_definitions()
def __init__(
self,
offloading_spec: "OffloadingSpec",
primary_kv_view: memoryview,
tier_type: str,
router_capabilities: Iterable[str] | None = None,
control_host: str = "0.0.0.0",
control_ports: list[int] | None = None,
control_advertise_host: str | None = None,
eager_ctrl_connect: bool = True,
opportunistic_query: bool = True,
enable_telemetry: bool = False,
operation_timeout_ms: int = 1000,
abandon_timeout_ms: int = 5000,
metadata_retry_interval_ms: int = 100,
secondary_g2_slots: int = 0,
kvcr_service_socket_path: str | None = None,
compatibility_digest: str | None = None,
policy: str | None = None,
g3: dict[str, Any] | None = None,
local_dram_backend: str = "UCX",
remote_fw_dram_backend: str = "UCX",
backpressure_detector: "BackpressureDetector | None" = None,
) -> None:
super().__init__(
offloading_spec, primary_kv_view, tier_type, backpressure_detector
)
selected_policy = _resolve_policy(policy)
if (kvcr_service_socket_path is None) != (compatibility_digest is None):
raise ValueError(
"kvcr_service_socket_path and compatibility_digest must be "
"configured together"
)
missing = _REQUIRED_ROUTER_CAPABILITIES - set(router_capabilities or ())
if missing:
raise ValueError(
f"KVCR secondary tier requires router capabilities: {sorted(missing)}"
)
events_enabled = offloading_spec.kv_events_config.enable_kv_cache_events
self_describing_events = (
offloading_spec.kv_events_config.self_describing_kv_events
)
if (
events_enabled
and (
secondary_g2_slots > 0
or kvcr_service_socket_path is not None
or g3 is not None
)
and not self_describing_events
):
raise ValueError(
"KVCR local G2/G3 inventory requires self_describing_kv_events"
)
self._key_adapter: KeyAdapter = _VllmKeyAdapter()
advertise_host = control_advertise_host or socket.gethostname()
dp_local_rank = offloading_spec.config.parallel.data_parallel_rank_local
if dp_local_rank is None:
if control_ports is None or len(control_ports) != 1:
raise ValueError(
"control_ports must contain exactly one port when "
"data_parallel_rank_local is unset"
)
dp_local_rank = 0
if control_ports is None or not 0 <= dp_local_rank < len(control_ports):
raise ValueError(
"control_ports must contain a port for "
f"local data-parallel rank {dp_local_rank}"
)
if any(not 1 <= port <= 65535 for port in control_ports):
raise ValueError("control_ports must be between 1 and 65535")
control = ZmqPeerControlChannel(
control_host,
control_ports[dp_local_rank],
advertise_host,
)
# Give colocated workers distinct transport listen ports.
with socket.socket() as _s:
_s.bind(("", 0))
_nixl_listen_port = _s.getsockname()[1]
if secondary_g2_slots < 0:
raise ValueError("secondary_g2_slots must be non-negative")
if (
secondary_g2_slots or kvcr_service_socket_path is not None
) and not events_enabled:
logger.warning(
"KVCR local DRAM is enabled, but KV cache events are disabled; "
"local DRAM inventory will not be published"
)
local_mapping: mmap.mmap | None = None
local_dram: LocalDramOptions | None = None
if secondary_g2_slots:
if kvcr_service_socket_path is not None:
logger.warning(
"secondary_g2_slots is ignored when "
"kvcr_service_socket_path is configured"
)
else:
local_mapping = mmap.mmap(
-1, secondary_g2_slots * self.block_size_bytes
)
local_dram = LocalDramOptions(
pools=[
(
"",
ctypes.addressof(ctypes.c_char.from_buffer(local_mapping)),
len(local_mapping),
)
],
backend=local_dram_backend,
)
guard_config = (
KVCRGuardConfig(
kvcr_service_socket_path=kvcr_service_socket_path,
guard_index=dp_local_rank,
compatibility_digest=compatibility_digest,
)
if kvcr_service_socket_path is not None and compatibility_digest is not None
else None
)
g3_config = None
if g3 is not None:
g3_values = dict(g3)
g3_values["paths"] = tuple(Path(path) for path in g3_values["paths"])
g3_config = G3Options(**g3_values)
nixl_agent_name = f"KVCR-{uuid.uuid4()}"
self._framework_pin_adapter = _FrameworkPinAdapter(self)
self._inventory_events: list[OffloadingEvent] = []
try:
self._kvcr = KVCR(
KVCRConfig(
pool_layouts=[("", self.block_size_bytes)],
enable_telemetry=enable_telemetry,
operation_timeout_ms=operation_timeout_ms,
abandon_timeout_ms=abandon_timeout_ms,
nixl_agent_name=nixl_agent_name,
nixl_listen_port=_nixl_listen_port,
),
KVCRBindings(
request_pin=self._framework_pin_adapter.request_pin,
poll_pin_results=self._framework_pin_adapter.poll_pin_results,
release_pin=self._framework_pin_adapter.release_pin,
cancel_pin_request=(self._framework_pin_adapter.cancel_pin_request),
framework_control=control,
key_adapter=self._key_adapter,
inventory_sink=(self._record_inventory if events_enabled else None),
stats_factory=(
OffloadingConnectorStats if enable_telemetry else None
),
policy=selected_policy,
),
KVCRBackendConfigs(
framework_regions=[
RegionDescriptor(
addr=ctypes.addressof(
ctypes.c_char.from_buffer(primary_kv_view)
),
size=self.block_size_bytes,
count=len(primary_kv_view),
)
],
local_dram=local_dram,
g3=g3_config,
remote_fw_dram=RemoteFWDramOptions(
eager_ctrl_connect=eager_ctrl_connect,
opportunistic_query=opportunistic_query,
metadata_retry_interval_ms=metadata_retry_interval_ms,
backend=remote_fw_dram_backend,
),
),
guard_config,
)
except BaseException as exc:
if not isinstance(exc, Exception) or isinstance(exc, KVCRStartupError):
# Native work may still touch these.
_RETAINED_NATIVE_BUFFERS.append(
ctypes.c_char.from_buffer(primary_kv_view)
)
if local_mapping is not None:
_RETAINED_NATIVE_BUFFERS.append(
ctypes.c_char.from_buffer(local_mapping)
)
raise
control.close()
if local_mapping is not None:
local_mapping.close()
raise
self._local_dram_mmap = local_mapping
self._finished_jobs: list[JobResult] = []
self._jobs_by_op: dict[OpHandle, _JobState] = {}
@override
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
block_key = self._key_adapter.encode(key)
status, _ = self._kvcr.query((block_key,), req_context.req_id)[0]
if status is QueryStatus.FETCHING:
return LookupResult.RETRY
if status in (QueryStatus.HIT, QueryStatus.FETCHABLE):
return LookupResult.HIT
return LookupResult.MISS
@override
def submit_load(self, job_metadata: TransferJob) -> None:
blocks = {
self._key_adapter.encode(key): [self._make_descriptor(int(chunk_id))]
for key, chunk_id in zip(
job_metadata.keys, job_metadata.chunk_ids, strict=True
)
}
if not blocks:
self._finished_jobs.append(
JobResult(job_id=job_metadata.job_id, success=True)
)
return
op_handle = self._kvcr.deliver(
blocks, request_id=job_metadata.req_context.req_id
)
self._jobs_by_op[op_handle] = (
job_metadata.job_id,
len(blocks),
True,
set(),
)
@override
def submit_store(self, job_metadata: TransferJob) -> None:
blocks = {
self._key_adapter.encode(key): [self._make_descriptor(int(chunk_id))]
for key, chunk_id in zip(
job_metadata.keys, job_metadata.chunk_ids, strict=True
)
}
if not blocks:
self._finished_jobs.append(
JobResult(job_id=job_metadata.job_id, success=True)
)
return
op_handle = self._kvcr.deposit(blocks)
self._jobs_by_op[op_handle] = (
job_metadata.job_id,
len(blocks),
True,
None,
)
@override
def get_finished_jobs(self) -> Iterable[JobResult]:
results = self._finished_jobs
self._finished_jobs = []
results.extend(self._poll_finished_jobs())
return results
@override
def get_stats(self) -> OffloadingConnectorStats | None:
stats = cast(OffloadingConnectorStats | None, self._kvcr.get_stats())
if stats is not None:
# Add the framework namespace only at the vLLM boundary.
for metrics in stats.metric_sections():
for name in tuple(metrics):
metrics[_vllm_metric_name(name)] = metrics.pop(name)
return stats
@override
def serve_external_requests(self, parent: ParentManager) -> None:
self._framework_pin_adapter.process_pending(parent)
def _poll_finished_jobs(self) -> list[JobResult]:
results: list[JobResult] = []
for op_handle, entries in self._kvcr.poll_completed():
job_state = self._jobs_by_op.get(op_handle)
if job_state is None:
continue
job_id, remaining, success, successful_keys = job_state
remaining -= len(entries)
success = success and all(entry.success for entry in entries.values())
if successful_keys is not None:
successful_keys.update(
OffloadKey(bytes(key))
for key, entry in entries.items()
if entry.success
)
if remaining > 0:
self._jobs_by_op[op_handle] = (
job_id,
remaining,
success,
successful_keys,
)
continue
self._jobs_by_op.pop(op_handle, None)
results.append(
JobResult(
job_id=job_id,
success=success,
successful_keys=successful_keys if not success else None,
)
)
results.extend(self._framework_pin_adapter.take_pin_job_results())
return results
@override
def has_pending_work(self) -> bool:
# Keep scheduler polling: control messages may arrive without a load job.
return True
@override
def take_events(self) -> Iterable[OffloadingEvent]:
events = self._inventory_events
self._inventory_events = []
return events
@override
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
if (hint := req_context.kv_hints) is not None:
self._kvcr.submit_hint(
request_id=req_context.req_id,
hints=msgspec.to_builtins(hint),
)
return RequestOffloadingContext()
@override
def on_request_finished(self, req_context: ReqContext) -> None:
self._kvcr.discard_hint(req_context.req_id)
@override
def drain_jobs(self) -> None:
while self._jobs_by_op or self._framework_pin_adapter.has_active_pins():
drained = self._poll_finished_jobs()
if drained:
self._finished_jobs.extend(drained)
else:
time.sleep(0.001)
@override
def shutdown(self) -> None:
self.drain_jobs()
# TODO: Keep registered buffers alive if KVCR.close() fails.
self._kvcr.close()
if self._local_dram_mmap is not None:
self._local_dram_mmap.close()
self._local_dram_mmap = None
def _record_inventory(self, event: InventoryEvent) -> None:
if event.tier is CacheTier.LOCAL_G2:
medium = Medium.CPU
elif event.tier is CacheTier.G3:
medium = Medium.STORAGE
else:
raise ValueError(f"unsupported KVCR inventory tier: {event.tier}")
self._inventory_events.append(
OffloadingEvent(
keys=[OffloadKey(bytes(key)) for key in event.keys],
medium=medium,
removed=event.removed,
ownership="kvcr",
removal_expected=True,
)
)
def _make_descriptor(self, chunk_id: int) -> MemoryRef:
return MemoryRef(
end_point_name=self._kvcr.config.nixl_agent_name,
element_index=chunk_id,
)
File diff suppressed because it is too large Load Diff
-320
View File
@@ -1,320 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
import time
from dataclasses import dataclass, field
from typing import Protocol
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.metrics import (
OffloadingConnectorStats,
)
from vllm.v1.kv_offload.base import LookupResult, OffloadKey, ReqContext
from vllm.v1.kv_offload.tiering.base import (
JobResult,
SecondaryTierManager,
TieringOffloadingMetrics,
TransferJob,
)
TierLabel = tuple[str]
PRIMARY_TIER_LABEL: TierLabel = ("0:primary",)
class _JobMetadataLike(Protocol):
@property
def transfer_job(self) -> TransferJob: ...
@property
def tier_idx(self) -> int: ...
@dataclass(slots=True)
class _RequestMetricsState:
observed_lookups: dict[TierLabel, dict[OffloadKey, float | None]] | None = field(
default_factory=dict
)
@dataclass
class _TierState:
active_promotion_count: int = 0
active_cascade_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_chunks: int,
primary_chunk_size: int,
) -> None:
self._tier_types = tier_types
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()
@functools.cache # noqa: B019
def tier_label(self, tier_idx: int) -> TierLabel:
return (f"{tier_idx + 1}:{self._tier_types[tier_idx]}",)
@property
def primary_tier_label(self) -> TierLabel:
return PRIMARY_TIER_LABEL
def on_new_request(self, req_context: ReqContext) -> None:
self._request_states[req_context.req_id] = _RequestMetricsState()
def on_request_allocated(self, req_context: ReqContext) -> None:
state = self._request_states.get(req_context.req_id)
if state is None:
return
state.observed_lookups = None
def on_request_finished(self, req_context: ReqContext) -> None:
self._request_states.pop(req_context.req_id, None)
def on_lookup(
self,
req_context: ReqContext,
key: OffloadKey,
tier_label: TierLabel,
result: LookupResult,
lookup_duration: float,
) -> None:
state = self._request_states.get(req_context.req_id)
if state is None:
state = _RequestMetricsState()
self._request_states[req_context.req_id] = state
if state.observed_lookups is not None and result in (
LookupResult.HIT,
LookupResult.MISS,
):
observed = state.observed_lookups.setdefault(tier_label, {})
start_time = observed.get(key)
if key not in observed or start_time is not None:
observed[key] = None
self._observe_resolved_lookup(
tier_label,
result,
lookup_duration,
start_time,
)
elif result is LookupResult.RETRY and state.observed_lookups is not None:
observed = state.observed_lookups.setdefault(tier_label, {})
observed.setdefault(key, time.monotonic() - lookup_duration)
def on_job_registered(self, job_metadata: _JobMetadataLike) -> None:
transfer_job = job_metadata.transfer_job
state = self._tier_states[job_metadata.tier_idx]
chunk_count = len(transfer_job.chunk_ids)
if transfer_job.is_promotion:
state.active_promotion_count += 1
state.primary_write_chunk_count += chunk_count
else:
state.active_cascade_count += 1
state.primary_read_chunk_count += chunk_count
def on_job_finished(
self, job_metadata: _JobMetadataLike, result: JobResult
) -> None:
self._observe_finished_job_stats(job_metadata, result)
if job_metadata.transfer_job.is_promotion:
self._observe_promotion_latency(job_metadata, result)
self._decrement_tier_state(job_metadata)
def on_promotion_allocation_failure(self) -> None:
self._stats.increase_counter(
TieringOffloadingMetrics.PROMOTION_ALLOCATION_FAILURES
)
def record_backpressure(
self,
tiers: list[SecondaryTierManager],
) -> None:
for i, tier in enumerate(tiers):
detector = tier.bp_detector
if detector is None:
continue
label = self.tier_label(i)
ema = detector.stats.get("store_latency_ema")
if ema is not None:
self._stats.set_gauge(
TieringOffloadingMetrics.BACKPRESSURE_STORE_LATENCY_EMA,
ema,
labelvalues=label,
)
stores_dropped, blocks_dropped = detector.policy.pop_stores_dropped()
if stores_dropped > 0:
self._stats.increase_counter(
TieringOffloadingMetrics.BACKPRESSURE_STORES_DROPPED,
stores_dropped,
labelvalues=label,
)
if blocks_dropped > 0:
self._stats.increase_counter(
TieringOffloadingMetrics.BACKPRESSURE_BLOCKS_DROPPED,
blocks_dropped,
labelvalues=label,
)
def take_stats(self) -> OffloadingConnectorStats | None:
active_transfer_stats = OffloadingConnectorStats()
self._observe_active_transfer_stats(active_transfer_stats)
stats = None
if not active_transfer_stats.is_empty():
stats = active_transfer_stats
if not self._stats.is_empty():
if stats is None:
stats = self._stats
else:
stats.aggregate(self._stats)
self._stats = OffloadingConnectorStats()
return stats
def assert_idle(self) -> None:
assert all(
state.active_promotion_count == 0
and state.active_cascade_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]
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_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_chunk_count -= chunk_count
assert state.primary_read_chunk_count >= 0
def _observe_finished_job_stats(
self,
job_metadata: _JobMetadataLike,
completed_job: JobResult,
) -> None:
transfer_job = job_metadata.transfer_job
labelvalues = self.tier_label(job_metadata.tier_idx)
completed_key_count = len(transfer_job.keys)
if not completed_job.success:
failure_metric = (
TieringOffloadingMetrics.PROMOTION_JOB_FAILURES
if transfer_job.is_promotion
else TieringOffloadingMetrics.CASCADE_JOB_FAILURES
)
self._stats.increase_counter(failure_metric, labelvalues=labelvalues)
if transfer_job.is_promotion and completed_job.successful_keys:
completed_key_count = len(completed_job.successful_keys)
else:
return
bytes_metric = (
TieringOffloadingMetrics.READ_BYTES
if transfer_job.is_promotion
else TieringOffloadingMetrics.WRITE_BYTES
)
time_metric = (
TieringOffloadingMetrics.READ_TIME
if transfer_job.is_promotion
else TieringOffloadingMetrics.WRITE_TIME
)
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(
time_metric, completed_job.transfer_time, labelvalues
)
def _observe_promotion_latency(
self, job_metadata: _JobMetadataLike, result: JobResult
) -> None:
"""Record promotion time from job creation to reported completion.
This is broader than the tier-reported `JobResult.transfer_time`, which
covers only the active data movement, and so includes tier queueing.
Failed promotions are observed too; PROMOTION_JOB_FAILURES counts them.
"""
self._stats.observe_histogram(
TieringOffloadingMetrics.PROMOTION_LATENCY,
time.monotonic() - job_metadata.transfer_job.submit_time,
(
*self.tier_label(job_metadata.tier_idx),
"success" if result.success else "failure",
),
)
def _observe_active_transfer_stats(self, stats: OffloadingConnectorStats) -> None:
for tier_idx, state in enumerate(self._tier_states):
labelvalues = self.tier_label(tier_idx)
write_usage = (
state.primary_write_chunk_count / self._num_primary_chunks
if self._num_primary_chunks > 0
else 0.0
)
read_usage = (
state.primary_read_chunk_count / self._num_primary_chunks
if self._num_primary_chunks > 0
else 0.0
)
stats.set_gauge(
TieringOffloadingMetrics.PRIMARY_WRITE_USAGE_PERC,
write_usage,
labelvalues,
)
stats.set_gauge(
TieringOffloadingMetrics.PRIMARY_READ_USAGE_PERC,
read_usage,
labelvalues,
)
stats.set_gauge(
TieringOffloadingMetrics.ACTIVE_PROMOTION_JOBS,
state.active_promotion_count,
labelvalues,
)
stats.set_gauge(
TieringOffloadingMetrics.ACTIVE_CASCADE_JOBS,
state.active_cascade_count,
labelvalues,
)
def _observe_resolved_lookup(
self,
tier_label: TierLabel,
result: LookupResult,
lookup_duration: float,
async_start_time: float | None,
) -> None:
self._stats.increase_counter(
TieringOffloadingMetrics.CHUNK_QUERIES,
labelvalues=tier_label,
)
if result is LookupResult.HIT:
self._stats.increase_counter(
TieringOffloadingMetrics.CHUNK_HITS,
labelvalues=tier_label,
)
self._stats.observe_histogram(
TieringOffloadingMetrics.LOOKUP_SYNC_DELAY,
lookup_duration,
tier_label,
)
if async_start_time is not None:
self._stats.observe_histogram(
TieringOffloadingMetrics.LOOKUP_ASYNC_DELAY,
time.monotonic() - async_start_time,
tier_label,
)
-46
View File
@@ -1,46 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Connection configuration for the object store secondary tier."""
from dataclasses import dataclass, field
@dataclass
class ObjStoreConfig:
"""Connection parameters for an object store backend.
When ``access_key`` and ``secret_key`` are left empty the NIXL OBJ
plugin falls back to the AWS SDK default credential provider chain
(IAM roles, environment variables, credential files, etc.), which
enables workload-identity based auth on Kubernetes.
"""
bucket: str
endpoint_override: str
access_key: str = field(default="", repr=False)
secret_key: str = field(default="", repr=False)
session_token: str = field(default="", repr=False)
region: str = ""
scheme: str = "http"
ca_bundle: str = ""
def to_nixl_params(self) -> dict[str, str]:
"""Build the NIXL backend params dict.
Credential and optional fields are only included when non-empty
so that the AWS SDK default credential chain can activate.
"""
params: dict[str, str] = {
"bucket": self.bucket,
"endpoint_override": self.endpoint_override,
"scheme": self.scheme,
}
# Omit empty optional fields so the NIXL OBJ plugin's underlying
# AWS SDK can fall back to its default credential provider chain
# (IAM roles, env vars, credential files, etc.).
# https://github.com/ai-dynamo/nixl/blob/main/src/plugins/obj/README.md
for key in ("access_key", "secret_key", "session_token", "region", "ca_bundle"):
value = getattr(self, key)
if value:
params[key] = value
return params
-461
View File
@@ -1,461 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Object store secondary tier implementation."""
import ctypes
import time
from collections.abc import Iterable
from typing import TYPE_CHECKING, ClassVar, NamedTuple
import numpy as np
from vllm.distributed.nixl_utils import NixlWrapper as nixl_agent
from vllm.distributed.nixl_utils import nixl_agent_config
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import (
Locality,
LookupResult,
Medium,
OffloadingEvent,
OffloadKey,
ReqContext,
)
from vllm.v1.kv_offload.file_mapper import FileMapper
from vllm.v1.kv_offload.tiering.async_lookup import AsyncLookupManager
from vllm.v1.kv_offload.tiering.backpressure import BackpressureDetector
from vllm.v1.kv_offload.tiering.base import (
JobId,
JobResult,
RequestOffloadingContext,
ScheduleEndContext,
SecondaryTierManager,
TransferJob,
)
from vllm.v1.kv_offload.tiering.obj.config import ObjStoreConfig
if TYPE_CHECKING:
from nixl._api import nixl_prepped_dlist_handle, nixl_xfer_handle
from vllm.v1.kv_offload.base import OffloadingSpec
logger = init_logger(__name__)
NIXL_WRITE = "WRITE"
NIXL_READ = "READ"
NIXL_PROC = "PROC"
NIXL_DONE = "DONE"
# Device ID for CPU DRAM descriptors. DRAM is not a multi-device resource so
# the device ID is always 0.
NIXL_DEV_ID: int = 0
# Fields for NIXL OBJ descriptors: (addr, len, dev_id, obj_key).
# For existence probes addr and len are placeholders — no data is read.
# dev_id=0 is reserved for probes; transfers start from 1.
_PROBE_ADDR: int = 0
_PROBE_LEN: int = 1
_PROBE_DEV_ID: int = 0
class TransferEntry(NamedTuple):
xfer_handle: "nixl_xfer_handle"
files_desc: object
obj_handle: "nixl_prepped_dlist_handle"
class ObjAsyncLookupManager(AsyncLookupManager):
"""Async lookup manager for ObjectStoreSecondaryTierManager.
Batches existence probes into a single query_memory() call so the
background thread issues one round-trip per step instead of one per key.
"""
def __init__(
self,
tier: "ObjectStoreSecondaryTierManager",
tier_type: str,
) -> None:
super().__init__(tier_type=tier_type)
self._tier = tier
def batch_lookup(
self, keys: list[OffloadKey], req_context: ReqContext
) -> Iterable[bool]:
descriptors = [
(
_PROBE_ADDR,
_PROBE_LEN,
_PROBE_DEV_ID,
self._tier._file_mapper.get_file_name(k),
)
for k in keys
]
results = self._tier._agent.query_memory(descriptors, "OBJ", "OBJ")
return (r is not None for r in results)
class ObjectStoreSecondaryTierManager(SecondaryTierManager):
"""Secondary tier that offloads KV cache blocks to an S3-compatible store.
Handles CPU DRAM <-> S3 transfers only. GPU <-> CPU is managed by the
primary tier. Object keys are formed as ``{prefix}/{hash_shard}/{hash}.bin``.
"""
medium: ClassVar[Medium] = Medium.STORAGE
def __init__(
self,
offloading_spec: "OffloadingSpec",
primary_kv_view: memoryview,
tier_type: str,
store_config: dict,
prefix: str = "",
io_threads: int = 4,
enable_kv_events: bool = False,
locality: str | None = None,
backpressure_detector: BackpressureDetector | None = None,
):
"""Args:
offloading_spec: Offloading configuration.
primary_kv_view: Memoryview of the primary tier's CPU KV cache.
tier_type: Tier type identifier, set by SecondaryTierFactory.
store_config: Object store connection parameters (see ObjStoreConfig).
prefix: Key prefix prepended to all object keys.
io_threads: Number of NIXL I/O threads.
enable_kv_events: Emit BlockStored KV events for blocks
successfully stored to this tier. Effective only when KV
cache events are enabled globally (kv_events_config).
locality: Whether this tier's storage is LOCAL or REMOTE relative
to the publishing vLLM instance.
backpressure_detector: Optional backpressure detector.
"""
super().__init__(
offloading_spec,
primary_kv_view,
tier_type,
backpressure_detector,
)
self.locality = Locality(locality) if locality is not None else None
self.events: list[OffloadingEvent] | None = None
if enable_kv_events:
if offloading_spec.kv_events_config.enable_kv_cache_events:
self.events = []
else:
logger.warning(
"enable_kv_events is set on secondary tier '%s' but KV "
"cache events are disabled globally; the tier will not "
"emit events.",
tier_type,
)
# Keys of in-flight store jobs, tracked only when events are enabled.
self._store_job_keys: dict[JobId, list[OffloadKey]] = {}
# Keys of in-flight load (promotion) jobs, so a failed download can
# mark its own cached lookup verdicts False (see get_finished_jobs).
self._load_job_keys: dict[JobId, list[OffloadKey]] = {}
agent_config = nixl_agent_config(backends=[])
self._agent = nixl_agent("ObjAgent", agent_config)
obj_config = ObjStoreConfig(**store_config)
params = {**obj_config.to_nixl_params(), "num_threads": str(io_threads)}
self._agent.create_backend("OBJ", params)
self._transfers: dict[int, TransferEntry] = {}
# Buffered results awaiting the next get_finished_jobs() call:
# submission-time failures + poll-time completions accumulated
# during drain_jobs().
self._pending_results: list[JobResult] = []
self._primary_reg = None
self._block_size_bytes: int = 0
root_dir = f"{prefix}/" if prefix else ""
# Opt in; FileMapper enables it only for a parallelism-invariant block.
self._file_mapper = FileMapper.from_offloading_spec(
root_dir, offloading_spec, parallel_agnostic=True
)
self._next_obj_dev_id: int = 1 # dev_id=0 is reserved for _exists() probes
self._probe_connectivity()
base_addr = ctypes.addressof(ctypes.c_char.from_buffer(primary_kv_view))
assert primary_kv_view.strides is not None
stride = primary_kv_view.strides[0]
self._primary_reg = self._agent.register_memory(
[(base_addr, primary_kv_view.nbytes, NIXL_DEV_ID, "")], "DRAM"
)
self._block_size_bytes = stride
all_blocks = [
(base_addr + i * stride, stride, NIXL_DEV_ID)
for i in range(len(primary_kv_view))
]
# NIXL_INIT_AGENT marks this as the local side; make_prepped_xfer requires
# local_xfer_side tagged with NIXL_INIT_AGENT and remote_xfer_side tagged
# with the peer agent name ("ObjAgent").
self._dram_prepped_handle: nixl_prepped_dlist_handle = (
self._agent.prep_xfer_dlist("NIXL_INIT_AGENT", all_blocks, "DRAM")
)
self._lookup_manager = ObjAsyncLookupManager(
tier=self, tier_type=self.tier_type
)
def _probe_connectivity(self) -> None:
"""Verify object store connectivity at startup via a NIXL lookup probe.
Performs a single exists() check against a synthetic key that will
never exist. A True/False result confirms the bucket is reachable;
an exception indicates misconfigured obj store params and raises RuntimeError.
"""
probe_key = "__nixl_probe__/connectivity_test"
try:
self._exists(probe_key)
logger.info("Object store tier connectivity probe succeeded")
except Exception as e:
raise RuntimeError(
f"Object store tier connectivity probe failed — check bucket, "
f"endpoint_override, and scheme. If using explicit credentials "
f"verify access_key and secret_key; otherwise ensure the AWS "
f"SDK default credential chain is configured (IAM role, env "
f"vars, credential file). Error: {e}"
) from e
def _exists(self, obj_key: str) -> bool:
results = self._agent.query_memory(
[(_PROBE_ADDR, _PROBE_LEN, _PROBE_DEV_ID, obj_key)], "OBJ", "OBJ"
)
return results[0] is not None
def _submit_transfer(
self,
job_id: int,
block_ids: np.ndarray,
obj_keys: Iterable[str],
op: str,
) -> None:
"""Submit an async transfer. op is 'WRITE' (store) or 'READ' (load)."""
# NIXL takes indices as int32; a wider dtype silently costs a conversion.
assert block_ids.dtype == np.int32
# The OBJ backend maps devId -> obj_key. All descriptors must have
# unique devIds or later registrations overwrite earlier ones.
nixl_files = [
(0, self._block_size_bytes, dev_id, key)
for dev_id, key in enumerate(obj_keys, self._next_obj_dev_id)
]
self._next_obj_dev_id += len(nixl_files)
files_desc = self._agent.register_memory(nixl_files, "OBJ")
if files_desc is None:
logger.warning("register_memory (OBJ) failed for job %d", job_id)
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
obj_handle = self._agent.prep_xfer_dlist("ObjAgent", files_desc.trim())
if not obj_handle:
logger.warning("prep_xfer_dlist (OBJ) failed for job %d", job_id)
self._agent.deregister_memory(files_desc)
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
xfer_handle = self._agent.make_prepped_xfer(
op,
self._dram_prepped_handle,
block_ids,
obj_handle,
np.arange(len(nixl_files), dtype=np.int32),
)
if not xfer_handle:
logger.warning("make_prepped_xfer failed for job %d", job_id)
self._agent.release_dlist_handle(obj_handle)
self._agent.deregister_memory(files_desc)
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
state = self._agent.transfer(xfer_handle)
if state == "ERR":
logger.warning("agent.transfer failed for job %d", job_id)
self._agent.release_dlist_handle(obj_handle)
self._agent.deregister_memory(files_desc)
self._agent.release_xfer_handle(xfer_handle)
self._pending_results.append(JobResult(job_id=job_id, success=False))
return
self._transfers[job_id] = TransferEntry(
xfer_handle=xfer_handle,
files_desc=files_desc,
obj_handle=obj_handle,
)
def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:
result = self._lookup_manager.lookup(key, req_context)
if result is None:
return LookupResult.RETRY
return LookupResult.HIT if result else LookupResult.MISS
def submit_store(self, job_metadata: TransferJob) -> None:
if self.events is not None:
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.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.chunk_ids, obj_keys, NIXL_READ
)
def on_request_finished(self, req_context: ReqContext) -> None:
self._lookup_manager.cleanup(req_context.req_id)
def on_schedule_end(self, context: ScheduleEndContext) -> None:
self._lookup_manager.flush()
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
return RequestOffloadingContext()
def _poll_active_transfers(self) -> None:
"""Poll all in-flight transfers once; move newly-completed (success or
failure) into ``_pending_results`` and release their NIXL handles."""
for job_id, entry in list(self._transfers.items()):
try:
state = self._agent.check_xfer_state(entry.xfer_handle)
except Exception as exc:
success = False
logger.warning("check_xfer_state raised for job %d: %s", job_id, exc)
else:
if state == NIXL_PROC:
continue
if state == NIXL_DONE:
success = True
else:
success = False
logger.warning("transfer failed job=%d state=%s", job_id, state)
transfer_time = None
if success:
telemetry = self._agent.get_xfer_telemetry(entry.xfer_handle)
transfer_time = telemetry.xferDuration / 1e6
try:
self._agent.release_xfer_handle(entry.xfer_handle)
except Exception as exc:
# Keep the entry until NIXL confirms that the transfer handle
# can be released. The transfer may still access primary-tier
# memory, so publishing its result would allow unsafe reuse.
logger.warning("release_xfer_handle failed for job %d: %s", job_id, exc)
continue
# Once the transfer handle is released, these remaining cleanup
# failures must not suppress the job completion. They can leak
# NIXL metadata, but cannot leave an active data transfer behind.
try:
self._agent.release_dlist_handle(entry.obj_handle)
except Exception as exc:
logger.warning(
"release_dlist_handle failed for job %d: %s", job_id, exc
)
try:
self._agent.deregister_memory(entry.files_desc)
except Exception as exc:
logger.warning("deregister_memory failed for job %d: %s", job_id, exc)
del self._transfers[job_id]
self._pending_results.append(
JobResult(
job_id=job_id,
success=success,
transfer_time=transfer_time,
)
)
def get_finished_jobs(self) -> Iterable[JobResult]:
"""Poll transfers; a failed promotion marks its cached verdicts False
here (scheduler thread)."""
self._poll_active_transfers()
results = self._pending_results
self._pending_results = []
for result in results:
if self.events is not None:
keys = self._store_job_keys.pop(result.job_id, None)
if result.success and keys:
self.events.append(
OffloadingEvent(
keys=keys,
medium=self.medium,
removed=False,
locality=self.locality,
)
)
# Mark only the keys that did not load as a miss; the request
# recomputes them. The miss is per-request (cleared when the request
# finishes), so other requests still HIT the blocks that loaded
# fine. nixl reports the batch as a whole (successful_keys is None),
# so today this marks all keys; the subtraction keeps it correct if
# partial results are ever reported.
load_keys = self._load_job_keys.pop(result.job_id, None)
if load_keys is not None and not result.success:
successful = set(result.successful_keys or ())
failed = [k for k in load_keys if k not in successful]
self._lookup_manager.mark_miss(failed)
return results
def take_events(self) -> Iterable[OffloadingEvent]:
if self.events is not None:
yield from self.events
self.events.clear()
def drain_jobs(self) -> None:
"""Block until every submitted transfer has completed or failed.
nixl exposes only ``check_xfer_state`` (poll-based), so this loops
until ``_transfers`` is empty. Results accumulate in
``_pending_results`` and are surfaced by the next
``get_finished_jobs()`` call.
"""
start = time.monotonic()
warned = False
while self._transfers:
self._poll_active_transfers()
if not self._transfers:
break
if not warned and time.monotonic() - start > 5.0:
logger.warning(
"ObjectStoreSecondaryTierManager.drain_jobs: still "
"draining after 5s (%d transfers in flight); a stuck "
"transfer will block the engine.",
len(self._transfers),
)
warned = True
time.sleep(0.001)
def shutdown(self) -> None:
self._lookup_manager.shutdown()
for job_id, entry in self._transfers.items():
try:
self._agent.release_xfer_handle(entry.xfer_handle)
except Exception as exc:
logger.warning("release_xfer_handle failed for job %d: %s", job_id, exc)
try:
self._agent.release_dlist_handle(entry.obj_handle)
except Exception as exc:
logger.warning(
"release_dlist_handle failed for job %d: %s", job_id, exc
)
try:
self._agent.deregister_memory(entry.files_desc)
except Exception as exc:
logger.warning("deregister_memory failed for job %d: %s", job_id, exc)
self._transfers.clear()
if self._dram_prepped_handle is not None:
try:
self._agent.release_dlist_handle(self._dram_prepped_handle)
except Exception as exc:
logger.warning("failed to release DRAM prepped handle: %s", exc)
self._dram_prepped_handle = None
if self._primary_reg is not None:
try:
self._agent.deregister_memory(self._primary_reg)
except Exception as exc:
logger.warning("failed to deregister primary buffer: %s", exc)
self._primary_reg = None
@@ -1,17 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.v1.kv_offload.tiering.p2p.control.base import (
ControlConnection,
ControlTransport,
)
from vllm.v1.kv_offload.tiering.p2p.control.zmq import (
ZmqConnection,
ZmqTransport,
)
__all__ = [
"ControlConnection",
"ControlTransport",
"ZmqConnection",
"ZmqTransport",
]
@@ -1,176 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Abstract base classes for the P2P control-plane transport.
The control plane handles peer discovery, connection lifecycle, and
message routing. It is message-content agnostic — it moves opaque
dicts between peers without interpreting them.
Architecture
------------
ControlTransport (one per node)
├── listen for inbound connections
├── connect() to outbound peers
└── poll() → new ControlConnections
ControlConnection (one per peer)
├── send(msg) — enqueue a message to the peer
├── recv() — drain buffered inbound messages
├── mark_dead() — signal that the peer is gone
└── close() — tear down the connection
Threading model: all I/O is driven by the caller invoking poll(). No background
threads of its own. More than one caller thread may drive poll() over a
transport's lifetime, but never concurrently -- callers serialize themselves
(the tiering manager does so with its lock), because sockets here are not
thread-safe. poll() must be called periodically to:
- receive messages (buffered per-connection)
- accept new inbound peers
- detect disconnections
Implementor contracts
---------------------
- ControlConnection.send() must not block. Messages are serialized
and queued for the next I/O pass.
- ControlConnection.recv() returns all messages received since the
last call (may be empty). Messages are dicts (already deserialized).
- ControlConnection.alive returns False after mark_dead() or close().
- ControlTransport.poll() returns newly accepted connections only —
not previously returned ones. Each connection appears exactly once.
- ControlTransport.connect() creates an outbound connection to a peer
identified by peer_id (format: "host:port"). Raises on failure.
- Messages may arrive from unknown peers (new inbound connections).
The transport creates a ControlConnection and returns it from poll()
with the first message(s) already in its recv() buffer.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence
class ControlConnection(ABC):
"""Bidirectional message channel to a single remote peer.
Lifecycle:
1. Created by ControlTransport (connect() or poll())
2. Used for send/recv by sessions
3. Marked dead on disconnect (mark_dead())
4. Cleaned up with close()
Once mark_dead() is called, alive becomes False and the owning
session should stop using this connection. close() releases
underlying resources (sockets, monitors).
"""
def __init__(self, peer_id: str) -> None:
self.peer_id = peer_id
@property
@abstractmethod
def alive(self) -> bool:
"""True if the connection is usable. False after mark_dead/close."""
...
@abstractmethod
def send(self, msg: dict) -> None:
"""Enqueue a message for delivery to the peer.
Must not block. Serialization happens internally.
Raises on closed connection.
"""
...
@abstractmethod
def recv(self) -> Sequence[dict]:
"""Drain and return all messages received since the last call.
Returns an empty sequence if no messages are pending.
The returned sequence is read-only — callers must not mutate it.
Messages are dicts deserialized from the wire format.
"""
...
@abstractmethod
def mark_dead(self) -> None:
"""Mark this connection as dead (peer disconnected).
After this call, alive returns False. The session should
stop using this connection and the transport will clean it up.
Resources are not released here — close() must still run.
"""
...
@abstractmethod
def close(self) -> None:
"""Release all resources (sockets, monitors).
Idempotent. After close(), alive returns False.
"""
...
class ControlTransport(ABC):
"""Manages peer connections and drives all control-plane I/O.
Owns the listening socket and all active connections.
The caller must invoke poll() periodically to process I/O.
Lifecycle:
1. Constructed with a local identity and listen address
2. connect() to reach remote peers
3. poll() to accept inbound peers and process messages
4. close() to shut down
"""
@abstractmethod
def connect(self, peer_id: str) -> ControlConnection:
"""Create an outbound connection to a remote peer.
Args:
peer_id: Remote peer identity (format: "host:port").
Returns:
A new ControlConnection ready for send/recv.
The connection's send queue is live immediately — messages
sent before the remote peer's poll() will be buffered.
A connection to peer_id that is registered but no longer alive is
retired and replaced; a live one is a duplicate and must not be
replaced.
"""
...
@abstractmethod
def poll(self) -> Sequence[ControlConnection]:
"""Process all pending I/O and return newly accepted connections.
This is the main I/O driver. Each call:
- Receives messages from all connected peers (buffered in
each connection's recv() queue)
- Accepts new inbound peers and creates connections for them
(first message already in recv() buffer)
- Detects disconnections and marks connections dead
Returns:
Newly accepted inbound connections (not previously returned).
The returned sequence is read-only — callers must not mutate
it. The caller is responsible for creating sessions for
these connections.
"""
...
@abstractmethod
def close(self) -> None:
"""Shut down the transport and all connections.
Closes the listening socket and all active connections.
Idempotent.
"""
...
@@ -1,375 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ZMQ-based transport layer for P2P KV cache sharing.
Provides ZmqConnection (per-peer messaging) and ZmqTransport (connection
management). Message-content agnostic.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
import msgspec
import zmq
import zmq.utils.monitor
from vllm.logger import init_logger
from vllm.v1.kv_offload.tiering.p2p.control.base import (
ControlConnection,
ControlTransport,
)
logger = init_logger(__name__)
_HEARTBEAT_IVL_MS = 2000
_HEARTBEAT_TIMEOUT_MS = 10000
_HEARTBEAT_TTL_MS = 10000
# Events that indicate a fatal connection failure — the peer will never
# become reachable through this socket.
_FATAL_MONITOR_EVENTS: frozenset[int] = frozenset() # populated after import
# Shared sentinels returned when there is nothing to report.
_EMPTY_INBOX: tuple[dict, ...] = ()
_EMPTY_NEW_CONNECTIONS: tuple[ControlConnection, ...] = ()
def _build_fatal_events() -> frozenset[int]:
events = {zmq.EVENT_DISCONNECTED, zmq.EVENT_CLOSED}
for attr in (
"EVENT_HANDSHAKE_FAILED_AUTH",
"EVENT_HANDSHAKE_FAILED_PROTOCOL",
"EVENT_HANDSHAKE_FAILED_NO_DETAIL",
):
val = getattr(zmq, attr, None)
if val is not None:
events.add(val)
return frozenset(events)
_FATAL_MONITOR_EVENTS = _build_fatal_events()
_MONITOR_EVENT_MASK: int = 0
for _ev in _FATAL_MONITOR_EVENTS:
_MONITOR_EVENT_MASK |= _ev
def _tcp_addr(host: str, port: int | str) -> str:
return f"tcp://{host}:{port}"
def _apply_heartbeat(sock: zmq.Socket) -> None:
sock.setsockopt(zmq.HEARTBEAT_IVL, _HEARTBEAT_IVL_MS)
sock.setsockopt(zmq.HEARTBEAT_TIMEOUT, _HEARTBEAT_TIMEOUT_MS)
sock.setsockopt(zmq.HEARTBEAT_TTL, _HEARTBEAT_TTL_MS)
@dataclass
class _Sockets:
dealer: zmq.Socket
monitor: zmq.Socket
class ZmqConnection(ControlConnection):
"""Bidirectional message channel to a single remote peer."""
def __init__(self, peer_id: str, sockets: _Sockets) -> None:
super().__init__(peer_id)
self._sockets = sockets
# _dead: the peer is gone. _closed: the sockets have been released.
# Distinct, so mark_dead() cannot turn close() into a no-op and leak
# the DEALER and its monitor socket.
self._dead = False
self._closed = False
self._inbox: list[dict] = []
def send(self, msg: dict) -> None:
"""Send a msgpack-encoded message to this peer."""
if not self.alive:
raise RuntimeError(
f"ZmqConnection: send on closed connection to {self.peer_id}"
)
data = msgspec.msgpack.encode(msg)
self._sockets.dealer.send(data)
def recv(self) -> Sequence[dict]:
"""Drain and return all buffered incoming messages."""
if not self._inbox:
return _EMPTY_INBOX
msgs = self._inbox
self._inbox = []
return msgs
@property
def alive(self) -> bool:
return not (self._dead or self._closed)
def close(self) -> None:
if self._closed:
return
self._closed = True
self._dead = True
logger.info("ZmqConnection: closing connection to %s", self.peer_id)
self._sockets.monitor.close()
self._sockets.dealer.close()
def enqueue(self, msg: dict) -> None:
"""Buffer an incoming message."""
self._inbox.append(msg)
def mark_dead(self) -> None:
"""Mark connection as disconnected.
Only flips liveness: the sockets stay open until close() releases
them, so the owner can still drain recv() before tearing down.
"""
self._dead = True
@property
def monitor_socket(self) -> zmq.Socket:
"""Monitor socket for disconnect detection (used by ZmqTransport)."""
return self._sockets.monitor
class ZmqTransport(ControlTransport):
"""ZMQ implementation of ControlTransport.
Manages a ROUTER socket for accepting connections and DEALER sockets
for outbound connections. Message-content agnostic.
"""
def __init__(self, local_id: str, host: str, port: int) -> None:
self._local_id = local_id
self._closed = False
self._connections: dict[str, ZmqConnection] = {}
self._pending_inbound: list[tuple[str, dict]] = []
# Monotonic suffix for inproc monitor endpoints — see
# _open_connection() for why peer_id alone is not enough.
self._monitor_seq = 0
self._zmq_ctx = zmq.Context()
self._router: zmq.Socket = self._zmq_ctx.socket(zmq.ROUTER)
_apply_heartbeat(self._router)
bind_addr = _tcp_addr(host, port)
self._router.bind(bind_addr)
logger.info("ZmqTransport %s: ROUTER bound on %s", self._local_id, bind_addr)
# ------------------------------------------------------------------
# ZmqConnection lifecycle
# ------------------------------------------------------------------
def connect(self, peer_id: str) -> ZmqConnection:
"""Open an outbound connection to a remote peer.
A dead connection can still be registered: its owning session may mark
it dead after this tick's sweep already ran, and poll() only
unregisters it on the next pass. Retire such an entry instead of
asserting, so a reconnect landing in that window succeeds. A live
entry is still a genuine duplicate.
"""
existing = self._connections.get(peer_id)
if existing is not None:
assert not existing.alive, f"ZmqConnection to {peer_id} already exists"
logger.info(
"ZmqTransport %s: retiring dead connection to %s before reconnect",
self._local_id,
peer_id,
)
self._connections.pop(peer_id).close()
logger.info(
"ZmqTransport %s: opening OUTBOUND connection to %s",
self._local_id,
peer_id,
)
return self._open_connection(peer_id, direction="outbound")
def poll(self) -> Sequence[ControlConnection]:
"""Process all pending I/O. Returns newly accepted connections.
- Receives messages (buffered in each connection's inbox)
- Creates connections for new inbound peers (connect msg in inbox)
- Checks monitors for disconnections
- Removes and closes dead connections
"""
# Retire connections a session killed since the last poll() before
# routing traffic: otherwise a reconnecting peer's first message is
# enqueued into the dead connection and discarded along with it.
# This closes only that between-polls window. A peer that dies while
# poll() is running is not seen until the next _check_monitors(), and
# one that dies silently not until the ZMQ heartbeat expires; both
# still take a message into a doomed connection and are out of scope.
self._sweep_dead_connections()
self._recv_router()
self._check_monitors()
self._sweep_dead_connections()
# Create connections for new inbound peers
new_connections: list[ControlConnection] | None = None
for sender_id, msg in self._pending_inbound:
conn = self._connections.get(sender_id)
if conn is None:
logger.info(
"ZmqTransport %s: accepting INBOUND connection from %s",
self._local_id,
sender_id,
)
conn = self._open_connection(sender_id, direction="inbound")
if new_connections is None:
new_connections = []
new_connections.append(conn)
conn.enqueue(msg)
self._pending_inbound.clear()
return (
new_connections if new_connections is not None else _EMPTY_NEW_CONNECTIONS
)
def close(self) -> None:
if self._closed:
return
self._closed = True
for conn in self._connections.values():
conn.close()
self._connections.clear()
self._router.setsockopt(zmq.LINGER, 0)
self._router.close()
self._zmq_ctx.destroy(linger=0)
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
def _open_connection(
self, peer_id: str, direction: str = "outbound"
) -> ZmqConnection:
"""Create a DEALER socket + monitor and register the connection."""
host, port_str = peer_id.rsplit(":", 1)
dealer_addr = _tcp_addr(host, port_str)
logger.debug(
"ZmqTransport %s: creating DEALER for %s peer %s -> %s",
self._local_id,
direction,
peer_id,
dealer_addr,
)
dealer = self._zmq_ctx.socket(zmq.DEALER)
_apply_heartbeat(dealer)
dealer.identity = self._local_id.encode()
# Unique per connection, not per peer: libzmq releases an inproc
# endpoint on its reaper thread after the DEALER's close() has already
# returned, so reusing the peer-derived address on a reconnect races
# that teardown and fails with EADDRINUSE.
safe_id = peer_id.replace(":", "-").replace("/", "-")
monitor_addr = f"inproc://p2p-monitor-{safe_id}-{self._monitor_seq}"
self._monitor_seq += 1
dealer.monitor(monitor_addr, _MONITOR_EVENT_MASK)
monitor_sock = self._zmq_ctx.socket(zmq.PAIR)
monitor_sock.connect(monitor_addr)
dealer.connect(dealer_addr)
sockets = _Sockets(dealer=dealer, monitor=monitor_sock)
conn = ZmqConnection(peer_id, sockets)
self._connections[peer_id] = conn
logger.info(
"ZmqTransport %s: %s connection established to %s (active connections: %d)",
self._local_id,
direction,
peer_id,
len(self._connections),
)
return conn
def _sweep_dead_connections(self) -> None:
"""Unregister and release every connection that is no longer alive."""
for pid in [p for p, c in self._connections.items() if not c.alive]:
self._connections.pop(pid).close()
def _recv_router(self) -> None:
"""Non-blocking: receive all pending messages from ROUTER."""
while True:
try:
frames = self._router.recv_multipart(zmq.NOBLOCK)
except zmq.Again:
break
except zmq.ZMQError as exc:
logger.warning("ZmqTransport %s: recv error: %s", self._local_id, exc)
break
if len(frames) != 2:
logger.warning(
"ZmqTransport %s: dropping message with %d frames (expected 2)",
self._local_id,
len(frames),
)
continue
identity, data = frames
sender_id = identity.decode()
logger.debug(
"ZmqTransport %s: ROUTER recv from %s (%d bytes)",
self._local_id,
sender_id,
len(data),
)
try:
msg = msgspec.msgpack.decode(data)
except Exception as exc:
logger.warning(
"ZmqTransport %s: failed to decode message from %s: %s",
self._local_id,
sender_id,
exc,
)
continue
conn = self._connections.get(sender_id)
if conn is not None:
conn.enqueue(msg)
else:
self._pending_inbound.append((sender_id, msg))
def _check_monitors(self) -> None:
"""Non-blocking: check all monitor sockets for fatal events."""
for conn in self._connections.values():
if not conn.alive:
continue
while True:
try:
event = zmq.utils.monitor.recv_monitor_message(
conn.monitor_socket, zmq.NOBLOCK
)
except zmq.Again:
break
except zmq.ZMQError as exc:
logger.warning(
"ZmqTransport %s: monitor error for peer %s: %s",
self._local_id,
conn.peer_id,
exc,
)
break
ev = event["event"]
if ev in _FATAL_MONITOR_EVENTS:
logger.debug(
"ZmqTransport %s: peer %s fatal event 0x%x",
self._local_id,
conn.peer_id,
ev,
)
conn.mark_dead()
break
@@ -1,10 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.v1.kv_offload.tiering.p2p.data.base import DataTransport, PollResult
from vllm.v1.kv_offload.tiering.p2p.data.nixl import NixlTransport
__all__ = [
"DataTransport",
"NixlTransport",
"PollResult",
]
-325
View File
@@ -1,325 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Abstract base class for the P2P data-plane transport.
The data plane handles RDMA (or similar) block transfers between peers.
It is independent of the control plane — the control plane establishes
who can talk to whom, then the data plane moves blocks at wire speed.
Architecture
------------
DataTransport (one per node)
├── owns the local KV block memory region
├── registers remote peers (add_remote_peer / remove_remote_peer)
├── submits block writes (write_blocks → transfer_id)
├── polls for completion (poll → done/failed IDs)
└── cancels inflight transfers (cancel)
Memory model
------------
The local node exposes a contiguous block region:
base_addr ──► ┌─────────────┐ block 0
├─────────────┤ block 1
├─────────────┤ ...
└─────────────┘ block (num_blocks - 1)
Each block is block_len bytes.
Remote peers expose the same layout. write_blocks() copies local
blocks to a remote peer's block region by index:
write_blocks("peer:1", local_idxs=[0, 3], remote_idxs=[5, 7])
→ writes local block 0 → remote block 5
local block 3 → remote block 7
Transfer lifecycle
------------------
1. Register remote peer: add_remote_peer(peer_id, metadata, ...)
- Provides the remote memory layout so transfers can target it
2. Submit: write_blocks(peer_id, local_idxs, remote_idxs) → int
- Returns a transfer_id (opaque int) for tracking
- Returns None if peer not registered or submission fails
3. Poll: poll() → PollResult(done=[...], failed=[...])
- Returns transfer_ids that completed or failed since last poll
- Completed transfers are automatically cleaned up
4. Cancel: cancel(transfer_ids, mode="immediate" | "wait")
- Best-effort cancellation of inflight transfers
- mode="wait" returns ids still in PROC/PEND so the caller can poll
them to completion
Implementor contracts
---------------------
- write_blocks() must not block. The transfer runs asynchronously.
- poll() must be called periodically. It drives completion checking.
- transfer_ids are unique across the lifetime of the transport.
- add_remote_peer() must be called before write_blocks() to that peer.
- get_agent_metadata() returns opaque bytes that the remote peer
needs to call add_remote_peer() (e.g., RDMA connection info).
- config_fingerprint is a content hash of the model configuration.
Peers with different fingerprints are incompatible and must not
exchange blocks (validated during the control-plane handshake).
- close() releases all resources (memory registrations, handles).
After close(), no other methods may be called.
Threading model: no background Python threads. All I/O driven by poll(). More
than one caller thread may drive a transport over its lifetime, but never
concurrently -- callers serialize themselves (the tiering manager does so with
its lock). Note that serialization alone is not obviously sufficient for a
backend that binds state to the thread that created it; see NixlTransport.
"""
from __future__ import annotations
import ctypes
import hashlib
import json
from abc import ABC, abstractmethod
from collections.abc import Iterable, Sequence
from concurrent.futures import Future
from typing import Literal, NamedTuple
CancelMode = Literal["immediate", "wait"]
class PollResult(NamedTuple):
"""Result of polling inflight transfers.
Attributes:
done: Transfer IDs that completed successfully.
failed: Transfer IDs that failed (error, timeout, etc.).
"""
done: Sequence[int]
failed: Sequence[int]
class DataTransport(ABC):
"""Abstract data-plane transport for RDMA-style block transfers.
Owns the local KV block memory region and manages transfers to/from
registered remote peers.
Construction:
view: A 2D memoryview (num_blocks × block_len bytes) over the
local KV cache block storage.
config_fields: Dict of model config values used to compute the
compatibility fingerprint. None → empty fingerprint
(compatible with any peer).
"""
def __init__(self, view: memoryview, config_fields: dict | None = None) -> None:
assert view.shape is not None
self._view = view
self._base_addr = ctypes.addressof(ctypes.c_char.from_buffer(view))
self._num_blocks = view.shape[0]
self._block_len = view.shape[1]
self._config_fingerprint = self._compute_fingerprint(config_fields)
@property
def base_addr(self) -> int:
"""Base address of the local block memory region."""
return self._base_addr
@property
def num_blocks(self) -> int:
"""Number of blocks in the local region."""
return self._num_blocks
@property
def block_len(self) -> int:
"""Size of each block in bytes."""
return self._block_len
@property
def config_fingerprint(self) -> str:
"""Content-hash of the model configuration (hex string).
Peers must have matching fingerprints to exchange blocks.
Empty string means no fingerprint (always compatible).
"""
return self._config_fingerprint
@staticmethod
def _compute_fingerprint(config_fields: dict | None) -> str:
if not config_fields:
return ""
canonical = json.dumps(config_fields, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()[:16]
@abstractmethod
def get_agent_metadata(self) -> bytes:
"""Return opaque metadata needed by remote peers to connect.
The returned bytes are sent during the control-plane handshake
and passed to the remote peer's add_remote_peer().
"""
...
@abstractmethod
def add_remote_peer(
self,
peer_id: str,
agent_metadata: bytes,
base_addr: int,
num_blocks: int,
block_len: int,
) -> None:
"""Register a remote peer for block transfers.
Must be called before write_blocks() to this peer.
Args:
peer_id: Unique identifier for the remote peer.
agent_metadata: Opaque bytes from the peer's get_agent_metadata().
base_addr: Base address of the peer's block memory region.
num_blocks: Number of blocks in the peer's region.
block_len: Size of each block (must match local block_len).
"""
...
def add_remote_peer_async(
self,
peer_id: str,
agent_metadata: bytes,
base_addr: int,
num_blocks: int,
block_len: int,
) -> Future[None]:
"""Register a remote peer without blocking the caller.
Registration is O(num_blocks) and can take seconds for a large
secondary tier, so the session starts it here and sends
``ConnectAckMsg`` only once the returned future resolves. The
acknowledgement is therefore the peer's guarantee that this side
is ready to serve, and no ``write_blocks`` can arrive before it.
The default implementation runs ``add_remote_peer`` inline and
returns an already-resolved future; transports whose registration
is cheap need not override it.
Args:
peer_id: Unique identifier for the remote peer.
agent_metadata: Opaque bytes from the peer's get_agent_metadata().
base_addr: Base address of the peer's block memory region.
num_blocks: Number of blocks in the peer's region.
block_len: Size of each block (must match local block_len).
Returns:
A future resolving to None on success. A failed future means
the peer must be rejected rather than acknowledged.
"""
future: Future[None] = Future()
try:
self.add_remote_peer(
peer_id,
agent_metadata=agent_metadata,
base_addr=base_addr,
num_blocks=num_blocks,
block_len=block_len,
)
except Exception as exc:
future.set_exception(exc)
else:
future.set_result(None)
return future
@abstractmethod
def remove_remote_peer(self, peer_id: str) -> None:
"""Unregister a remote peer and release associated resources.
Inflight transfers to this peer should be cancelled first.
"""
...
@abstractmethod
def write_blocks(
self,
peer_id: str,
local_idxs: list[int],
remote_idxs: list[int],
) -> int | None:
"""Submit a WRITE transfer: local blocks → remote peer's blocks.
Args:
peer_id: Target peer (must be registered via add_remote_peer).
local_idxs: Indexes of local blocks to read from.
remote_idxs: Indexes of remote blocks to write to.
Must be same length as local_idxs.
Returns:
A unique transfer_id (int) to track this transfer, or
None if the peer is not registered or submission failed.
"""
...
@abstractmethod
def poll(self, peer_id: str | None = None) -> PollResult:
"""Poll inflight transfers for completion.
Args:
peer_id: If given, only poll (and drain) transfers submitted for
this peer_id — the value passed to ``write_blocks``. This is
required when a single transport is shared across multiple
peer sessions: ``poll()`` pops completed handles, so an
unscoped poll by one session would consume and discard the
completions of its siblings, starving them. ``None`` polls
every peer's transfers (used only for the shutdown drain).
Returns:
PollResult with lists of completed and failed transfer_ids.
Completed/failed transfers are removed from the inflight set.
Must be called periodically to drive progress checking.
"""
...
@abstractmethod
def cancel(
self,
transfer_ids: Iterable[int],
mode: CancelMode = "immediate",
) -> list[int]:
"""Cancel inflight transfers by their IDs.
Best-effort: transfers that already completed are ignored.
Args:
transfer_ids: IDs to cancel. Unknown IDs are ignored.
mode:
"immediate" (default): pop and release each handle and
return []. Matches the legacy fire-and-forget
behavior — the caller does not wait for the
underlying transfer to drain.
"wait": release only transfers that have stopped. A
transfer still PROC/PEND (or whose release fails)
stays in the inflight set and its id is included in
the returned list. The caller is expected to keep
calling poll() until every returned id surfaces in
done/failed.
Returns:
For mode="wait", the subset of *transfer_ids* still
tracked as inflight after the cancel attempt. For
mode="immediate", always [].
"""
...
@abstractmethod
def close(self) -> None:
"""Release all resources (registrations, handles, memory).
Cancels any remaining inflight transfers. Idempotent.
After close(), no other methods may be called.
"""
...
-523
View File
@@ -1,523 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""NixlTransport: Data-plane transport for RDMA-based KV block transfers via NIXL.
Threading: the agent is reached from the scheduler thread and, when the tiering
manager runs one, from its tier-poll thread. The manager's lock serializes
them strictly -- one Python thread inside any agent call at a time, with a full
memory barrier between.
That lock is the only protection, not a belt over NIXL's own. nixl_agent picks
NIXL_THREAD_SYNC_STRICT only when ``enable_listen`` is set, which this transport
does not set, so the agent runs with NIXL_THREAD_SYNC_NONE -- under which NIXL's
internal agent lock compiles down to no-ops, leaving every agent entry point
unguarded. So the manager lock must cover all of them, and the lifetime of every
handle passed between calls. The exception is peer registration moved onto a
worker thread, as NixlConnector's handshake executor does: it runs outside the
lock and relies, like that connector, on NIXL tolerating it beside transfers.
Serialized use from a second thread is supported (checked against NIXL 1.4.1
sources): NIXL never creates its UCX worker in UCS_THREAD_MODE_SINGLE, the only
creator-thread-affine mode. The weakest mode it ever requests is
UCS_THREAD_MODE_SERIALIZED, documented as "multiple threads can access, but only
one at a time", and because ``enable_prog_thread`` defaults on here it actually
requests UCS_THREAD_MODE_MULTI and fails construction if the UCX build cannot
provide it.
Two caveats. NIXL binds a shared UCX worker per calling thread
(``tlsSharedWorkerMap``), which is harmless only while there is exactly one
shared worker -- true here, but it would stop being true if a ``num_workers``
UCX backend param were ever set. And NIXL 1.4.1 does accept an explicit
``sync_mode`` (including NIXL_THREAD_SYNC_RW), which would make its own locking
real; that parameter does not exist before 1.x, so passing it would need a
version gate, the way ``capture_telemetry`` does.
"""
from __future__ import annotations
import itertools
import threading
from collections.abc import Iterable
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, NamedTuple
import numpy as np
from vllm.distributed.nixl_utils import NixlWrapper as _NixlAgent
from vllm.distributed.nixl_utils import nixl_agent_config as _NixlAgentConfig
from vllm.logger import init_logger
from vllm.v1.kv_offload.tiering.p2p.data.base import (
CancelMode,
DataTransport,
PollResult,
)
logger = init_logger(__name__)
# Shared sentinel returned by poll() in the steady state (no inflight, or
# no transfer changed state since the last poll). Tuples make it immutable;
# callers only iterate / membership-test / equality-check.
_EMPTY_POLL_RESULT: PollResult = PollResult(done=(), failed=())
def _is_remote_disconnect(exc: Exception) -> bool:
"""True if a NIXL state check failed because the peer disconnected.
NIXL raises ``nixlRemoteDisconnectError`` (NIXL_ERR_REMOTE_DISCONNECT)
from ``check_xfer_state`` once the target endpoint is gone, e.g. after
the peer process died, instead of reporting an ``"ERR"`` state. Matched
by name and status code so the bindings need not be imported here; an
unrecognized error keeps the transfer inflight, the conservative side.
"""
return type(
exc
).__name__ == "nixlRemoteDisconnectError" or "NIXL_ERR_REMOTE_DISCONNECT" in str(
exc
)
class _Inflight(NamedTuple):
"""A submitted-but-not-yet-drained transfer.
``peer_id`` lets poll() scope to a single owning session, since the
transport is shared across all peer sessions of the engine.
"""
peer_id: str
handle: object
class NixlTransport(DataTransport):
"""Manages a NIXL agent, memory registration, and block transfers.
Wraps the NIXL C library behind a Python interface so the rest of the
P2P tier code never touches NIXL types directly. Tracks inflight
handles internally and returns completed/failed tags on poll.
"""
def __init__(
self,
agent_name: str,
view: memoryview,
config_fields: dict | None = None,
backends: list[str] | None = None,
num_threads: int = 4,
) -> None:
super().__init__(view, config_fields=config_fields)
self._agent_name = agent_name
self._backends = list(backends) if backends else ["UCX"]
self._num_threads = num_threads
self._agent: Any = None
self._reg: Any = None
self._local_dlist: Any = None
self._remote_dlists: dict[str, object] = {}
self._peer_nixl_names: dict[str, str] = {}
# transfer_id → _Inflight(peer_id, handle).
self._inflight: dict[int, _Inflight] = {}
self._next_id = itertools.count()
# Registration is O(num_blocks) NIXL work — add_remote_agent plus a
# prep_xfer_dlist over every block of the peer's region — so it runs
# off the scheduler thread, mirroring the NIXL connector's
# _handshake_initiation_executor. One worker only: NIXL is not
# guaranteed to be thread-safe, so registrations stay serialized
# against each other.
self._reg_executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix="vllm-p2p-nixl-reg"
)
# peer_id → registration generation, bumped on every add and remove.
# A worker that finishes building handles under a stale generation
# releases them instead of publishing, so a late completion cannot
# revive a peer that was reaped or superseded meanwhile.
self._peer_gen: dict[str, int] = {}
# Guards _peer_gen together with _peer_nixl_names/_remote_dlists so
# the generation check and the publish are one atomic step.
self._peer_lock = threading.Lock()
self._init(view)
@property
def available(self) -> bool:
return self._agent is not None
def _init(self, view: memoryview) -> None:
if _NixlAgent is None:
return
non_ucx_backends = [b for b in self._backends if b != "UCX"]
if non_ucx_backends:
cfg = _NixlAgentConfig(backends=self._backends, capture_telemetry=True)
logger.info(
"NixlTransport %s: NIXL backends=%s",
self._agent_name,
self._backends,
)
else:
cfg = _NixlAgentConfig(
num_threads=self._num_threads, capture_telemetry=True
)
logger.info(
"NixlTransport %s: NIXL backends=[UCX] num_threads=%d",
self._agent_name,
self._num_threads,
)
self._agent = _NixlAgent(self._agent_name, cfg)
total_size = self._num_blocks * self._block_len
reg_descs = [(self._base_addr, total_size, 0, "")]
self._reg = self._agent.register_memory(reg_descs, mem_type="DRAM")
block_tuples = [
(self._base_addr + i * self._block_len, self._block_len, 0)
for i in range(self._num_blocks)
]
xfer_dlist = self._agent.get_xfer_descs(block_tuples, mem_type="DRAM")
self._local_dlist = self._agent.prep_xfer_dlist("NIXL_INIT_AGENT", xfer_dlist)
logger.info(
"NixlTransport %s: registered %d blocks", self._agent_name, self._num_blocks
)
def get_agent_metadata(self) -> bytes:
assert self._agent is not None
return self._agent.get_agent_metadata()
# ------------------------------------------------------------------
# Peer management
# ------------------------------------------------------------------
def add_remote_peer(
self,
peer_id: str,
agent_metadata: bytes,
base_addr: int,
num_blocks: int,
block_len: int,
) -> None:
gen = self._begin_registration(peer_id)
nixl_name, remote_dlist = self._build_peer_handles(
agent_metadata, base_addr, num_blocks, block_len
)
self._publish_peer(peer_id, gen, nixl_name, remote_dlist)
def add_remote_peer_async(
self,
peer_id: str,
agent_metadata: bytes,
base_addr: int,
num_blocks: int,
block_len: int,
) -> Future[None]:
gen = self._begin_registration(peer_id)
def register() -> None:
nixl_name, remote_dlist = self._build_peer_handles(
agent_metadata, base_addr, num_blocks, block_len
)
if not self._publish_peer(peer_id, gen, nixl_name, remote_dlist):
raise RuntimeError(
f"registration for peer {peer_id} was superseded "
"(peer removed or re-registered while registering)"
)
return self._reg_executor.submit(register)
def remove_remote_peer(self, peer_id: str) -> None:
with self._peer_lock:
# Invalidate any registration still being built for this peer so
# its worker releases the handles instead of publishing them.
self._peer_gen[peer_id] = self._peer_gen.get(peer_id, 0) + 1
nixl_name = self._peer_nixl_names.pop(peer_id, None)
dlist = self._remote_dlists.pop(peer_id, None)
if self._agent is not None:
self._release_remote_handles(peer_id, dlist, nixl_name)
def _begin_registration(self, peer_id: str) -> int:
"""Claim the next registration generation for *peer_id*."""
with self._peer_lock:
gen = self._peer_gen.get(peer_id, 0) + 1
self._peer_gen[peer_id] = gen
return gen
def _build_peer_handles(
self,
agent_metadata: bytes,
base_addr: int,
num_blocks: int,
block_len: int,
) -> tuple[str, Any]:
"""The expensive half: agent wireup plus one descriptor per block.
Touches no shared state, so it runs unlocked — holding the peer
lock across it would stall the scheduler thread for exactly as
long as the registration it is meant to move off that thread.
"""
nixl_name = self._agent.add_remote_agent(agent_metadata)
block_descs = [
(base_addr + i * block_len, block_len, 0) for i in range(num_blocks)
]
xfer_dlist = self._agent.get_xfer_descs(block_descs, mem_type="DRAM")
remote_dlist = self._agent.prep_xfer_dlist(nixl_name, xfer_dlist)
return nixl_name, remote_dlist
def _publish_peer(
self,
peer_id: str,
gen: int,
nixl_name: str,
remote_dlist: Any,
) -> bool:
"""Install freshly built handles, unless *gen* is stale.
Returns False when the peer was removed or re-registered while the
handles were being built; the handles are released here since
nothing else ever saw them.
"""
with self._peer_lock:
fresh = self._peer_gen.get(peer_id) == gen
if fresh:
self._peer_nixl_names[peer_id] = nixl_name
self._remote_dlists[peer_id] = remote_dlist
if fresh:
return True
logger.info(
"NixlTransport %s: discarding superseded registration for peer=%s",
self._agent_name,
peer_id,
)
if self._agent is not None:
self._release_remote_handles(peer_id, remote_dlist, nixl_name)
return False
def _release_remote_handles(
self, peer_id: str, dlist: object | None, nixl_name: str | None
) -> None:
"""Release a peer's descriptor list and remote agent independently.
The two teardown operations are independent: NIXL may reject one
after a transport failure, and a ``release_dlist_handle`` that
raises must not skip ``remove_remote_agent``. Skipping it would
leave a stale remote registration behind after the peer is gone
(peer removal) or after its registration was superseded.
"""
if dlist is not None:
try:
self._agent.release_dlist_handle(dlist)
except Exception as exc:
logger.warning(
"NixlTransport %s: releasing dlist handle for peer=%s failed: %s",
self._agent_name,
peer_id,
exc,
)
if nixl_name:
try:
self._agent.remove_remote_agent(nixl_name)
except Exception as exc:
logger.warning(
"NixlTransport %s: removing remote agent for peer=%s failed: %s",
self._agent_name,
peer_id,
exc,
)
# ------------------------------------------------------------------
# Transfer submission and polling
# ------------------------------------------------------------------
def write_blocks(
self,
peer_id: str,
local_idxs: list[int],
remote_idxs: list[int],
) -> int | None:
"""Submit a WRITE transfer to *peer_id*.
Returns a transfer ID, or None if the peer is not registered.
The ID is returned via poll() when the transfer completes or fails.
"""
remote_dlist = self._remote_dlists.get(peer_id)
if remote_dlist is None:
logger.warning(
"NixlTransport %s: write_blocks NO REMOTE DLIST for peer=%s "
"(known peers=%s)",
self._agent_name,
peer_id,
list(self._remote_dlists.keys()),
)
return None
logger.debug(
"NixlTransport %s: write_blocks NIXL.transfer peer=%s blocks=%d",
self._agent_name,
peer_id,
len(local_idxs),
)
handle = self._agent.make_prepped_xfer(
"WRITE",
self._local_dlist,
np.asarray(local_idxs, dtype=np.int32),
remote_dlist,
np.asarray(remote_idxs, dtype=np.int32),
)
self._agent.transfer(handle)
transfer_id = next(self._next_id)
self._inflight[transfer_id] = _Inflight(peer_id, handle)
return transfer_id
def poll(self, peer_id: str | None = None) -> PollResult:
"""Poll inflight transfers.
When *peer_id* is given, only transfers submitted for that peer_id are
checked and drained — the transport is shared across peer sessions, so
an unscoped poll by one session would consume and discard siblings'
completions. *peer_id* None polls every peer (shutdown drain only).
Returns PollResult(done=..., failed=...) with transfer IDs.
Completed handles are released automatically.
"""
if not self._inflight:
return _EMPTY_POLL_RESULT
done_ids: list[int] | None = None
failed_ids: list[int] | None = None
for transfer_id, entry in self._inflight.items():
if peer_id is not None and entry.peer_id != peer_id:
continue
try:
state = self._agent.check_xfer_state(entry.handle)
except Exception as exc:
logger.warning(
"NixlTransport %s: check_xfer_state failed for transfer_id=%d: %s",
self._agent_name,
transfer_id,
exc,
)
if not _is_remote_disconnect(exc):
continue
state = "ERR"
if state == "DONE":
if done_ids is None:
done_ids = []
done_ids.append(transfer_id)
elif state not in ("PROC", "PEND"):
if failed_ids is None:
failed_ids = []
failed_ids.append(transfer_id)
if done_ids is None and failed_ids is None:
return _EMPTY_POLL_RESULT
handles_to_release = []
for tid in done_ids or ():
handles_to_release.append(self._inflight.pop(tid).handle)
for tid in failed_ids or ():
handles_to_release.append(self._inflight.pop(tid).handle)
self._release_handles(handles_to_release)
return PollResult(
done=done_ids if done_ids is not None else _EMPTY_POLL_RESULT.done,
failed=failed_ids if failed_ids is not None else _EMPTY_POLL_RESULT.failed,
)
def cancel(
self,
transfer_ids: Iterable[int],
mode: CancelMode = "immediate",
) -> list[int]:
"""Cancel inflight transfers by their IDs.
See ``DataTransport.cancel`` for the contract. In "wait" mode, a
transfer is released only once NIXL reports it terminal. Releasing
a PROC/PEND handle does not stop the WRITE: the UCX backend frees
the request without cancelling RMA, and the bytes keep landing. So
PROC/PEND transfers, and those whose state check or
``release_xfer_handle`` raises, stay in ``self._inflight`` for a
later ``poll()`` to observe. A state check that fails because the
peer disconnected counts as terminal.
"""
if mode == "immediate":
handles = [
self._inflight.pop(tid).handle
for tid in transfer_ids
if tid in self._inflight
]
self._release_handles(handles)
return []
still_inflight: list[int] = []
for tid in transfer_ids:
entry = self._inflight.get(tid)
if entry is None:
continue
try:
state = self._agent.check_xfer_state(entry.handle)
except Exception as exc:
logger.debug(
"NixlTransport %s: cancel state check failed for "
"transfer_id=%d: %s",
self._agent_name,
tid,
exc,
)
if not _is_remote_disconnect(exc):
still_inflight.append(tid)
continue
# The handle may no longer be releasable; it is terminal
# either way, so drop it instead of retrying forever.
self._release_handles([entry.handle])
del self._inflight[tid]
continue
if state in ("PROC", "PEND"):
still_inflight.append(tid)
continue
try:
self._agent.release_xfer_handle(entry.handle)
except Exception as exc:
logger.debug(
"NixlTransport %s: cancel pending for transfer_id=%d: %s",
self._agent_name,
tid,
exc,
)
still_inflight.append(tid)
continue
del self._inflight[tid]
return still_inflight
# ------------------------------------------------------------------
# Lifecycle
# ------------------------------------------------------------------
def close(self) -> None:
# Stop accepting registrations and let any in-flight one finish
# before the agent goes away underneath it.
self._reg_executor.shutdown(wait=True)
if self._agent is None:
return
self._release_handles([entry.handle for entry in self._inflight.values()])
self._inflight.clear()
for peer_id in list(self._remote_dlists):
self.remove_remote_peer(peer_id)
if self._local_dlist is not None:
self._agent.release_dlist_handle(self._local_dlist)
self._local_dlist = None
if self._reg is not None:
self._agent.deregister_memory(self._reg)
self._reg = None
self._agent = None
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
def _release_handles(self, handles: list[object]) -> None:
if self._agent is None:
return
for handle in handles:
try:
self._agent.release_xfer_handle(handle)
except Exception as exc:
logger.warning(
"NixlTransport %s: release_xfer_handle failed: %s",
self._agent_name,
exc,
)
File diff suppressed because it is too large Load Diff
@@ -1,17 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.v1.kv_offload.tiering.p2p.session.session import (
LoadResult,
P2PSession,
SessionCloseResult,
SessionPollResult,
StoreResult,
)
__all__ = [
"LoadResult",
"P2PSession",
"SessionCloseResult",
"SessionPollResult",
"StoreResult",
]
@@ -1,548 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Client-role state machine for a single peer session.
Handles outgoing fetch requests, abort-on-timeout, abort-ack timeout,
and produces ``LoadResult`` for completed loads. The session coordinator
parses wire messages and dispatches typed arguments here; this module
never touches ``ControlConnection`` directly — it emits via the ``send``
callback injected by the coordinator (which gates on ConnectAck).
"""
from __future__ import annotations
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, NamedTuple
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import OffloadKey
from vllm.v1.kv_offload.tiering.p2p.session.protocol import (
TYPE_KEY,
AbortFetchMsg,
FetchMsg,
LookupMsg,
)
if TYPE_CHECKING:
from vllm.v1.kv_offload.tiering.base import JobId
logger = init_logger(__name__)
_LOAD_TIMEOUT_S = 30.0
_ABORT_ACK_TIMEOUT_S = 10.0
_LOOKUP_TIMEOUT_S = 30.0
@dataclass
class _InboundLoadState:
"""Client-role state for a single in-flight load request.
Lives in ``_ClientRequestState.loads`` keyed by round_seq for the
duration of a fetch; the owning kv_request_id is the outer dict key.
"""
job_id: int # opaque ID assigned by the manager to this load request
submitted_at: float
aborted_at: float | None = None
@dataclass
class _ClientRequestState:
"""Per-kv_request_id client-side state.
One entry per kv_request_id we're driving. Lookup-phase fields are
used only by symmetric P2P (``do_p2p_fetch``); PD-only loads leave
``probes``/``unsent`` empty and drive just ``phase`` and ``loads``. An
entry is dropped once every field is idle — see ``ClientRole._maybe_prune``.
"""
# -- Lookup phase (symmetric P2P only; untouched for PD) --
# Probe outcome per OffloadKey: None while in-flight (registered/sent
# but unresolved), True/False once a LookupRespMsg lands. Unanswered
# probes expire the session so the manager can fall back to local compute.
probes: dict[OffloadKey, bool | None] = field(default_factory=dict)
# OffloadKeys registered but not yet flushed onto the wire. Drained and
# cleared by the next flush_pending_lookups.
unsent: list[OffloadKey] = field(default_factory=list)
# Current lookup round. LookupMsgs carry it, each fetch closes it and
# advances it, so every round's supply/demand/completion is isolated
# on the wire. PD clients never probe and stay on round 0.
round_seq: int = 0
# This id ran the symmetric lookup phase (register_lookup); a fetch
# with keys then requires every key to be a confirmed probe. PD
# loads never probe.
probed: bool = False
# The peer holds lookup state no FetchMsg has closed: a LookupMsg
# was flushed since the last fetch. finish owes a terminal empty
# FetchMsg while set, so the peer releases parked supply.
peer_lookup_open: bool = False
# In-flight loads keyed by the round their fetch carried. The
# scheduler submits loads incrementally as chunks resolve, so several
# can be in flight at once; TransferDone/AbortAck match by round.
loads: dict[int, _InboundLoadState] = field(default_factory=dict)
class LoadResult(NamedTuple):
"""Result from a session poll, client side."""
job_id: int
kv_request_id: str
success: bool
class ClientCloseResult(NamedTuple):
"""What the manager must fail when a peer session is torn down.
``failed_jobs`` is the ``job_id`` of every load still in flight; each
becomes a ``JobResult(success=False)``. ``failed_req_ids`` is every
kv_request_id whose lookup() would otherwise defer forever on the dead
peer — the in-flight loads plus any request holding an unresolved
symmetric-P2P probe. ``failed_jobs`` is the subset of ``failed_req_ids``
that had a load job.
"""
failed_jobs: list[int]
failed_req_ids: list[str]
class ClientRole:
"""Client-side load state machine for one peer session.
The coordinator owns the connection and the send-gating; this role
is given a ``send`` callback and a ``peer_id`` for log messages and
is otherwise self-contained.
"""
def __init__(self, peer_id: str, send: Callable[[dict], None]) -> None:
self._peer_id = peer_id
self._send = send
# All per-kv_request_id state lives here. Entries are created
# lazily by request_blocks / register_lookup and dropped by
# _maybe_prune once every field is idle.
self._requests: dict[str, _ClientRequestState] = {}
# kv_request_ids with unsent lookup keys for the next flush to
# visit — the work-list that keeps flush_pending_lookups from
# scanning every request each scheduler step. Mirrors the server's
# _serve_pending. Populated by register_lookup, drained by
# flush_pending_lookups, and discarded on finish/close.
self._flush_pending: set[str] = set()
# kv_request_ids with at least one fetch in flight or aborting — the
# work-list collect_results walks for timeouts, and the
# has_active_loads predicate, instead of scanning every request.
# Kept in exact sync with ``st.loads``.
self._active_loads: set[str] = set()
self._completed_loads: list[LoadResult] = []
# Per-request progress deadlines. Only newly resolved probes extend
# them; additional keys and repeated scheduler polls do not.
self._lookup_deadlines: dict[str, float] = {}
# ------------------------------------------------------------------
# State helpers
# ------------------------------------------------------------------
def _get_or_create_request(self, kv_request_id: str) -> _ClientRequestState:
"""Get or create the state entry for a kv_request_id."""
st = self._requests.get(kv_request_id)
if st is None:
st = _ClientRequestState()
self._requests[kv_request_id] = st
return st
def _maybe_prune(self, kv_request_id: str) -> None:
"""Drop the entry once it holds no live load or lookup state.
``peer_lookup_open`` is only read by ``finish``, and every path
that clears the last probe (fetch / finish / close) also settles
it, so dropping on emptiness never loses a flag still in use.
"""
st = self._requests.get(kv_request_id)
if st is not None and not st.loads and not st.probes and not st.unsent:
del self._requests[kv_request_id]
def _on_load_terminal(self, kv_request_id: str, st: _ClientRequestState) -> None:
"""Wind down id-level state once no load remains in flight."""
if st.loads:
return
self._active_loads.discard(kv_request_id)
self._maybe_prune(kv_request_id)
@property
def has_active_loads(self) -> bool:
"""True if any kv_request_id has a fetch in flight."""
return bool(self._active_loads)
def get_expired_lookup(self) -> tuple[str, float] | None:
"""Return an expired request and seconds without progress, if any."""
now = time.monotonic()
for req_id, deadline in self._lookup_deadlines.items():
if now >= deadline:
return req_id, now - deadline + _LOOKUP_TIMEOUT_S
return None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def request_blocks(
self,
job_id: JobId,
kv_request_id: str,
keys: Sequence[OffloadKey],
block_ids: Sequence[int],
send_ready: bool,
) -> None:
"""Send the FetchMsg closing the current lookup round.
The scheduler may submit several loads per kv_request_id as its
matched prefix resolves incrementally; each fetch carries the
round it closes so the loads stay independent on the wire.
"""
logger.debug(
"P2PSession %s: request_blocks job_id=%d kv_request_id=%s "
"blocks=%d ready=%s",
self._peer_id,
job_id,
kv_request_id,
len(block_ids),
send_ready,
)
st = self._get_or_create_request(kv_request_id)
round_seq = st.round_seq
st.round_seq += 1
st.loads[round_seq] = _InboundLoadState(
job_id=job_id,
submitted_at=time.monotonic(),
)
self._active_loads.add(kv_request_id)
st.peer_lookup_open = False
self._send(
{
TYPE_KEY: FetchMsg.TYPE,
FetchMsg.KV_REQUEST_ID: kv_request_id,
FetchMsg.KEYS: list(keys),
FetchMsg.BLOCK_INDEXES: [int(idx) for idx in block_ids],
FetchMsg.ROUND_SEQ: round_seq,
}
)
# Issuing the fetch closes this lookup round, so drop all probe
# state. Once the peer serves the fetch both sides unpin, so a
# stale cached True would let a later lookup() return HIT for a
# block the producer may have evicted; clearing forces a fresh
# probe under the next round.
if st.probed and keys:
assert st.probes, (
f"symmetric fetch for {kv_request_id} has keys but no probes"
)
assert all(st.probes.get(key) is True for key in keys)
st.probes.clear()
self._lookup_deadlines.pop(kv_request_id, None)
def finish(self, kv_request_id: str) -> None:
"""Finish a request: abort in-flight loads and release lookup state.
Called from the session's ``finish_request``. Sends an
AbortFetchMsg per load not already aborting, and — independently —
the terminal empty FetchMsg when the peer still holds lookup
state no fetch has closed (its "request finished" signal: it
releases lookup state, drains parked supply, and fires
``cb.finish_request``). A later round's supply can be parked
while an earlier round's load is still in flight, so both can be
owed at once.
Then drop all probe/lookup state. Keep aborted loads until their abort
acknowledgement or timeout produces a terminal result.
"""
st = self._requests.get(kv_request_id)
if st is None:
return
if st.loads:
for round_seq, load in st.loads.items():
if load.aborted_at is not None:
continue
self._send(
{
TYPE_KEY: AbortFetchMsg.TYPE,
AbortFetchMsg.KV_REQUEST_ID: kv_request_id,
AbortFetchMsg.ROUND_SEQ: round_seq,
}
)
load.aborted_at = time.monotonic()
if st.peer_lookup_open:
st.peer_lookup_open = False
self._send(
{
TYPE_KEY: FetchMsg.TYPE,
FetchMsg.KV_REQUEST_ID: kv_request_id,
FetchMsg.KEYS: [],
FetchMsg.BLOCK_INDEXES: [],
FetchMsg.ROUND_SEQ: st.round_seq,
}
)
st.probes.clear()
st.unsent.clear()
self._lookup_deadlines.pop(kv_request_id, None)
self._flush_pending.discard(kv_request_id)
self._maybe_prune(kv_request_id)
def on_transfer_done(
self, kv_request_id: str, success: bool, round_seq: int
) -> None:
"""Handle a TransferDoneMsg from the peer."""
st = self._requests.get(kv_request_id)
load = st.loads.pop(round_seq, None) if st is not None else None
if st is not None and load is not None:
self._completed_loads.append(
LoadResult(
job_id=load.job_id,
kv_request_id=kv_request_id,
success=success,
)
)
self._on_load_terminal(kv_request_id, st)
else:
# No matching in-flight load: either a duplicate
# transfer_done from the peer (protocol violation) or a
# benign race with a local cancel/abort/timeout that
# already popped the entry. We don't track terminated ids,
# so we can't tell — log so it's findable.
logger.warning(
"P2PSession %s: transfer_done for unknown kv_request_id=%s "
"round=%s (duplicate from peer, or raced with local "
"cancel/timeout)",
self._peer_id,
kv_request_id,
round_seq,
)
def on_abort_ack(self, kv_request_id: str, round_seq: int) -> None:
"""Handle an AbortAckMsg from the peer."""
st = self._requests.get(kv_request_id)
load = st.loads.pop(round_seq, None) if st is not None else None
if st is not None and load is not None:
logger.warning(
"P2PSession %s: load request %s (job_id=%d) "
"completed with failure after abort",
self._peer_id,
kv_request_id,
load.job_id,
)
self._completed_loads.append(
LoadResult(
job_id=load.job_id,
kv_request_id=kv_request_id,
success=False,
)
)
self._on_load_terminal(kv_request_id, st)
else:
# See on_transfer_done: same ambiguity (duplicate ack
# vs. raced with local cancel/timeout that already popped).
logger.warning(
"P2PSession %s: abort_ack for unknown kv_request_id=%s "
"round=%s (duplicate from peer, or raced with local "
"cancel/timeout)",
self._peer_id,
kv_request_id,
round_seq,
)
# ------------------------------------------------------------------
# Symmetric-P2P lookup (do_p2p_fetch=true)
# ------------------------------------------------------------------
def register_lookup(self, kv_request_id: str, key: bytes) -> bool | None:
"""Register or resolve one (kv_request_id, key) probe.
Idempotent across scheduler steps:
- First call: creates a pending entry, returns None.
- Subsequent calls while in-flight: returns None.
- Once a LookupRespMsg has resolved the entry: returns the cached
bool result on every call without popping it.
A resolved entry is retained until a fetch closes the round
(``request_blocks`` clears all probes) or the request finishes
(``finish`` clears all entries for the id). A request's
block set can be re-probed across steps, so popping on read would
make a repeat probe of an already-resolved key look brand-new and
re-queue it, emitting a redundant LookupMsg for an answer we
already hold. Keeping the entry until fetch makes repeat probes
free; clearing at fetch forces a fresh probe under the next
round, since the block is unpinned once served.
"""
st = self._get_or_create_request(kv_request_id)
st.probed = True
okey = OffloadKey(key)
if okey in st.probes:
return st.probes[okey]
st.probes[okey] = None
st.unsent.append(okey)
self._flush_pending.add(kv_request_id)
logger.debug(
"P2P LOOKUP client %s: REGISTER kv_request_id=%s key=%s (unsent=%d)",
self._peer_id,
kv_request_id,
key.hex()[:16],
len(st.unsent),
)
return None
def flush_pending_lookups(self, send_ready: bool) -> None:
"""Send a LookupMsg for each kv_request_id with unsent entries.
Called once per scheduler step from the manager's
``on_schedule_end()``. A request's block set may be discovered
across several scheduler steps, so more than one LookupMsg can
go out per kv_request_id — one per step that registered new
keys, all tagged with the current round. register_lookup()
de-dups in-flight and already-resolved (req_id, key) pairs, so
each LookupMsg carries only the keys first probed in that step.
Wait for ConnectAckMsg before sending or starting the response deadline.
Only requests that registered new keys since the last flush are
visited — the ``_flush_pending`` work-list avoids scanning every
live request each scheduler step.
"""
if not send_ready:
return
for req_id in self._flush_pending:
st = self._requests.get(req_id)
if st is None or not st.unsent:
continue
# The peer now holds lookup state for this id; finish owes a
# terminal empty FetchMsg until a fetch closes it.
st.peer_lookup_open = True
self._lookup_deadlines.setdefault(
req_id, time.monotonic() + _LOOKUP_TIMEOUT_S
)
logger.debug(
"P2P LOOKUP client %s: SEND LookupMsg kv_request_id=%s keys=%d",
self._peer_id,
req_id,
len(st.unsent),
)
self._send(
{
TYPE_KEY: LookupMsg.TYPE,
LookupMsg.KV_REQUEST_ID: req_id,
LookupMsg.KEYS: list(st.unsent),
LookupMsg.ROUND_SEQ: st.round_seq,
}
)
st.unsent = []
self._flush_pending.clear()
def on_lookup_resp(
self,
kv_request_id: str,
keys: Sequence[bytes],
hits: Sequence[bool],
) -> None:
"""Apply per-pair hit/miss results from a peer.
Pairs that don't match a known entry (already cancelled or
never asked) are silently dropped — the producer is free to
split or coalesce responses.
"""
n_hit = sum(1 for hit in hits if hit)
logger.debug(
"P2P LOOKUP client %s: RECV LookupRespMsg kv_request_id=%s "
"keys=%d hits=%d misses=%d",
self._peer_id,
kv_request_id,
len(keys),
n_hit,
len(hits) - n_hit,
)
st = self._requests.get(kv_request_id)
if st is None:
return
progressed = False
for h, hit in zip(keys, hits):
key = OffloadKey(h)
if key in st.probes:
progressed |= st.probes[key] is None
st.probes[key] = hit
if all(hit is not None for hit in st.probes.values()):
self._lookup_deadlines.pop(kv_request_id, None)
elif progressed:
self._lookup_deadlines[kv_request_id] = time.monotonic() + _LOOKUP_TIMEOUT_S
def collect_results(self) -> list[LoadResult]:
"""Walk load timeouts and drain completed loads.
Loads past ``_LOAD_TIMEOUT_S`` get an AbortFetchMsg sent and
enter the aborting phase. Aborting loads past
``_ABORT_ACK_TIMEOUT_S`` are surfaced as failed.
"""
now = time.monotonic()
to_remove: list[tuple[str, int]] = []
for req_id in self._active_loads:
st = self._requests[req_id]
assert st.loads
for round_seq, load in st.loads.items():
if load.aborted_at is None:
if now - load.submitted_at >= _LOAD_TIMEOUT_S:
load.aborted_at = now
logger.warning(
"P2PSession %s: %s round=%s timed out, sending abort",
self._peer_id,
req_id,
round_seq,
)
self._send(
{
TYPE_KEY: AbortFetchMsg.TYPE,
AbortFetchMsg.KV_REQUEST_ID: req_id,
AbortFetchMsg.ROUND_SEQ: round_seq,
}
)
else:
if now - load.aborted_at >= _ABORT_ACK_TIMEOUT_S:
to_remove.append((req_id, round_seq))
self._completed_loads.append(
LoadResult(
job_id=load.job_id,
kv_request_id=req_id,
success=False,
)
)
logger.warning(
"P2PSession %s: abort_ack timed out for "
"kv_request_id=%s round=%s",
self._peer_id,
req_id,
round_seq,
)
for req_id, round_seq in to_remove:
st = self._requests[req_id]
st.loads.pop(round_seq)
self._on_load_terminal(req_id, st)
results = self._completed_loads
self._completed_loads = []
return results
def close(self) -> ClientCloseResult:
"""Tear down, reporting work the dead peer can no longer complete.
A request is failed if it has a load in flight (its job fails) or
holds an unresolved symmetric-P2P probe (its lookup() would defer
forever on an answer that can never arrive). See ``ClientCloseResult``.
"""
failed_jobs = [
load.job_id for st in self._requests.values() for load in st.loads.values()
]
failed_req_ids = [
req_id
for req_id, st in self._requests.items()
if st.loads or any(hit is None for hit in st.probes.values())
]
self._requests.clear()
self._flush_pending.clear()
self._active_loads.clear()
self._completed_loads.clear()
self._lookup_deadlines.clear()
return ClientCloseResult(failed_jobs=failed_jobs, failed_req_ids=failed_req_ids)
@@ -1,341 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""P2P KV cache sharing protocol constants and documentation.
Protocol Overview
=================
Two session types communicate over a bidirectional message channel:
- P2PClientSession (requests blocks from a server)
- P2PServerSession (serves blocks to a client)
Connection Lifecycle
--------------------
1. Client opens a connection and sends ConnectMsg with its identity,
RDMA metadata, memory layout, and config fingerprint.
2. Server validates block_len and config_fingerprint, registers the
RDMA peer, and replies with ConnectAckMsg.
3. Client receives ConnectAckMsg and transitions to ready state
(flushes any queued messages).
4. Either side may send DisconnectMsg to gracefully close.
Block Transfer Flow (happy path)
---------------------------------
1. Client sends FetchMsg with a kv_request_id and lists of
block keys + remote indexes where it wants the data written.
A request may run several lookup→fetch rounds; symmetric-P2P
messages carry ROUND_SEQ so each round's supply, demand, and
completion stay isolated. The terminal empty FetchMsg is the
server-side "request finished" signal for the id: parked
LookupMsg batches are popped and ``cb.finish_request`` fires on
each.
2. Server matches requested blocks against locally stored blocks:
- Blocks already available are transferred immediately via RDMA.
- Blocks not yet available are recorded as "demanded" and
transferred when the server later stores them.
3. When all blocks for a kv_request_id are transferred, the server
sends TransferDoneMsg (success=True) to the client.
4. Client reports the load job as complete.
Abort Flow (timeout path)
--------------------------
1. If the client times out waiting for TransferDoneMsg, it sends
AbortFetchMsg to cancel the request.
2. Server cancels inflight transfers for that kv_request_id and
replies with AbortAckMsg.
3. Client receives AbortAckMsg and reports the load job as failed.
4. If AbortAckMsg itself times out, the client fails the job anyway.
Message Format
--------------
All messages are dicts serialized with msgpack. Every message has a
TYPE_KEY key identifying its type. Additional fields depend on the
message type (see per-message class docstrings below).
Security
--------
Sessions wrap all incoming message handling in try/except to guard
against malformed messages from adversarial or buggy peers. Invalid
messages are logged and dropped without crashing the session.
The config_fingerprint field in ConnectMsg ensures peers have
compatible model configurations (model, dtype, block sizes). Mismatches
are rejected during the handshake.
"""
TYPE_KEY = "type"
# ---------------------------------------------------------------------------
# Validation helpers
# ---------------------------------------------------------------------------
def _require(msg: dict, key: str, typ: type, *, name: str = "") -> None:
"""Raise ValueError if msg[key] is missing or not isinstance(typ)."""
val = msg.get(key)
if not isinstance(val, typ):
label = name or key
raise ValueError(f"{label}: expected {typ.__name__}, got {type(val).__name__}")
def _require_pos_int(msg: dict, key: str, *, name: str = "") -> None:
"""Raise ValueError if msg[key] is not a positive int."""
val = msg.get(key)
if not isinstance(val, int) or val <= 0:
label = name or key
raise ValueError(f"{label}: expected positive int, got {val!r}")
def _require_non_neg_int(msg: dict, key: str, *, name: str = "") -> None:
"""Raise ValueError if msg[key] is not a non-negative int."""
val = msg.get(key)
if not isinstance(val, int) or val < 0:
label = name or key
raise ValueError(f"{label}: expected non-negative int, got {val!r}")
def _require_list(msg: dict, key: str, *, name: str = "") -> None:
"""Raise ValueError if msg[key] is not a list."""
val = msg.get(key)
if not isinstance(val, list):
label = name or key
raise ValueError(f"{label}: expected list, got {type(val).__name__}")
# ---------------------------------------------------------------------------
# Message classes
# ---------------------------------------------------------------------------
class ConnectMsg:
"""Client → Server: initial handshake request.
Fields:
PEER_ID: Local peer identity string.
AGENT_METADATA: RDMA agent metadata (opaque bytes).
BASE_ADDR: Base memory address of the KV block region.
NUM_BLOCKS: Number of blocks in the KV block region.
BLOCK_LEN: Size in bytes of each block (must match between peers).
CONFIG_FINGERPRINT: SHA-256 prefix of the model configuration.
Peers with different fingerprints are incompatible.
HASH_SEED: The peer's effective prefix-cache hash seed (PYTHONHASHSEED
if set, otherwise the built-in default). Block hashes chain from a
seed derived from it, so peers with different values compute
different hashes for identical content and must not exchange blocks.
"""
TYPE = "connect"
PEER_ID = "peer_id"
AGENT_METADATA = "agent_metadata"
BASE_ADDR = "base_addr"
NUM_BLOCKS = "num_blocks"
BLOCK_LEN = "block_len"
CONFIG_FINGERPRINT = "config_fingerprint"
HASH_SEED = "hash_seed"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, ConnectMsg.PEER_ID, str)
_require(msg, ConnectMsg.AGENT_METADATA, bytes)
_require_non_neg_int(msg, ConnectMsg.BASE_ADDR)
_require_pos_int(msg, ConnectMsg.NUM_BLOCKS)
_require_pos_int(msg, ConnectMsg.BLOCK_LEN)
_require(msg, ConnectMsg.HASH_SEED, str)
class ConnectAckMsg:
"""Server → Client: handshake acknowledgement.
Fields:
PEER_ID: Server's peer identity string.
"""
TYPE = "connect_ack"
PEER_ID = "peer_id"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, ConnectAckMsg.PEER_ID, str)
class DisconnectMsg:
"""Either → Either: graceful connection close.
No additional fields beyond TYPE_KEY.
"""
TYPE = "disconnect"
class FetchMsg:
"""Client → Server: request blocks for one lookup round.
A non-empty fetch closes only its round. The terminal empty FetchMsg
(``KEYS`` and ``BLOCK_INDEXES`` both empty) is the "request
finished" signal: the server pops parked LookupMsg batches, calls
``cb.finish_request`` on each, and drains any leftover supply.
Fields:
KV_REQUEST_ID: Identifies this block transfer request.
KEYS: List of block keys (OffloadKey bytes). May be empty.
BLOCK_INDEXES: List of remote block indexes (same length as KEYS).
ROUND_SEQ: Lookup round this fetch closes. PD clients never probe
and stay on their single round 0.
"""
TYPE = "fetch"
KV_REQUEST_ID = "kv_request_id"
KEYS = "keys"
BLOCK_INDEXES = "block_indexes"
ROUND_SEQ = "round_seq"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, FetchMsg.KV_REQUEST_ID, str)
_require_non_neg_int(msg, FetchMsg.ROUND_SEQ)
_require_list(msg, FetchMsg.KEYS)
_require_list(msg, FetchMsg.BLOCK_INDEXES)
keys = msg[FetchMsg.KEYS]
indexes = msg[FetchMsg.BLOCK_INDEXES]
if len(keys) != len(indexes):
raise ValueError(
f"keys/block_indexes length mismatch: {len(keys)} vs {len(indexes)}"
)
for idx in indexes:
if not isinstance(idx, int) or idx < 0:
raise ValueError(f"block_indexes: invalid index {idx!r}")
class LookupMsg:
"""Client → Server: probe which block keys the peer holds.
Sent on the consumer side under symmetric P2P (do_p2p_fetch=true)
after the consumer has aggregated per-block lookups across a
scheduler step. The producer replies with one or more LookupRespMsg
covering the requested keys.
Fields:
KV_REQUEST_ID: Identifies this lookup transaction.
KEYS: List of block keys (OffloadKey bytes) to probe.
ROUND_SEQ: Lookup round these probes belong to; pinned supply is
parked under it for that round's fetch.
"""
TYPE = "lookup"
KV_REQUEST_ID = "kv_request_id"
KEYS = "keys"
ROUND_SEQ = "round_seq"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, LookupMsg.KV_REQUEST_ID, str)
_require_list(msg, LookupMsg.KEYS)
_require_non_neg_int(msg, LookupMsg.ROUND_SEQ)
class LookupRespMsg:
"""Server → Client: per-key hit/miss answer for a prior LookupMsg.
Carries two parallel arrays of equal length so each (key,
hit) pair is self-describing. The producer is free to split or
coalesce responses across multiple LookupMsgs for the same
KV_REQUEST_ID — the consumer matches each pair back to its
pending entry by (KV_REQUEST_ID, key).
Fields:
KV_REQUEST_ID: The lookup transaction this responds to.
KEYS: List of block keys answered by this message.
HITS: Parallel list of bools — True if the producer holds the
corresponding block, False otherwise.
"""
TYPE = "lookup_resp"
KV_REQUEST_ID = "kv_request_id"
KEYS = "keys"
HITS = "hits"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, LookupRespMsg.KV_REQUEST_ID, str)
_require_list(msg, LookupRespMsg.KEYS)
_require_list(msg, LookupRespMsg.HITS)
keys = msg[LookupRespMsg.KEYS]
hits = msg[LookupRespMsg.HITS]
if len(keys) != len(hits):
raise ValueError(f"keys/hits length mismatch: {len(keys)} vs {len(hits)}")
for hit in hits:
if not isinstance(hit, bool):
raise ValueError(f"hits: invalid value {hit!r}")
class TransferDoneMsg:
"""Server → Client: all blocks transferred for a request.
Fields:
KV_REQUEST_ID: The request that completed.
SUCCESS: Whether the transfer completed successfully.
ROUND_SEQ: The fetch round that completed. Several loads can be
in flight per id (the scheduler submits loads incrementally),
so completions are matched by round.
"""
TYPE = "transfer_done"
KV_REQUEST_ID = "kv_request_id"
SUCCESS = "success"
ROUND_SEQ = "round_seq"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, TransferDoneMsg.KV_REQUEST_ID, str)
_require(msg, TransferDoneMsg.SUCCESS, bool)
_require_non_neg_int(msg, TransferDoneMsg.ROUND_SEQ)
class AbortFetchMsg:
"""Client → Server: cancel a pending request.
Fields:
KV_REQUEST_ID: The request to cancel.
ROUND_SEQ: The fetch round to cancel.
"""
TYPE = "abort_fetch"
KV_REQUEST_ID = "kv_request_id"
ROUND_SEQ = "round_seq"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, AbortFetchMsg.KV_REQUEST_ID, str)
_require_non_neg_int(msg, AbortFetchMsg.ROUND_SEQ)
class AbortAckMsg:
"""Server → Client: acknowledge cancellation.
Fields:
KV_REQUEST_ID: The request that was cancelled.
ROUND_SEQ: The round that was cancelled; echoes AbortFetchMsg.
"""
TYPE = "abort_ack"
KV_REQUEST_ID = "kv_request_id"
ROUND_SEQ = "round_seq"
@staticmethod
def validate(msg: dict) -> None:
"""Raise ValueError if any field has an invalid type or value."""
_require(msg, AbortAckMsg.KV_REQUEST_ID, str)
_require_non_neg_int(msg, AbortAckMsg.ROUND_SEQ)
File diff suppressed because it is too large Load Diff
@@ -1,666 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""P2PSession — bidirectional session combining client + server roles.
A single P2PSession per remote peer handles BOTH directions of the P2P
protocol on one ControlConnection: it can request blocks from the peer
("client" role, in :mod:`.client`) AND serve blocks to the peer
("server" role, in :mod:`.server`). This module is the thin coordinator
that owns the connection, the handshake, send-gating, and the message
dispatch — each parsed message is forwarded to the corresponding role.
Wire protocol is unchanged. Both sides advertise their NIXL metadata
via ConnectMsg when their session is connected; the peer's ConnectMsg
starts transport.add_remote_peer_async off the scheduler thread, and
ConnectAckMsg is sent only once that registration lands. ConnectAckMsg
confirms the peer received our ConnectMsg, after which queued outgoing
messages are flushed — so a peer that may send is a peer we have already
registered.
"""
from __future__ import annotations
import contextlib
import time
from collections.abc import Sequence
from concurrent.futures import Future
from typing import TYPE_CHECKING, NamedTuple
import vllm.envs as envs
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import OffloadKey
from vllm.v1.kv_offload.tiering.p2p.control.base import ControlConnection
from vllm.v1.kv_offload.tiering.p2p.session.client import ClientRole, LoadResult
from vllm.v1.kv_offload.tiering.p2p.session.protocol import (
TYPE_KEY,
AbortAckMsg,
AbortFetchMsg,
ConnectAckMsg,
ConnectMsg,
DisconnectMsg,
FetchMsg,
LookupMsg,
LookupRespMsg,
TransferDoneMsg,
)
from vllm.v1.kv_offload.tiering.p2p.session.server import (
ServerRole,
StoreResult,
)
if TYPE_CHECKING:
from vllm.v1.kv_offload.base import ReqContext
from vllm.v1.kv_offload.tiering.base import JobId, ParentManager
from vllm.v1.kv_offload.tiering.p2p.data import DataTransport
logger = init_logger(__name__)
# Cap on consecutive non-protocol dispatch exceptions before we tear
# down the session. Protocol violations (ValueError) disconnect on the
# first occurrence; this threshold protects against repeated internal
# bugs that may indicate a peer-induced bad state. Reset on any
# successful dispatch.
_MAX_CONSECUTIVE_DISPATCH_ERRORS = 5
class SessionPollResult(NamedTuple):
"""Result of one P2PSession.poll() tick.
`loads`/`stores` are the same per-role results the manager has always
consumed. `new_fetch_ids` reports kv_request_ids whose FetchMsg
arrived this tick — the manager uses them to bind kv_request_id →
session and replay any submit_store batches parked while no peer had
asked yet. Reporting (rather than calling back into the manager
mid-dispatch) keeps the dependency strictly top-down.
"""
loads: list[LoadResult]
stores: list[StoreResult]
new_fetch_ids: list[str]
class SessionCloseResult(NamedTuple):
"""Result of tearing down a P2PSession.
`failed_jobs`/`failed_stores` are the in-flight jobs (client loads /
server stores) the manager must mark failed. `failed_req_ids` is every
client-side kv_request_id whose lookup() must fail (in-flight loads plus
unresolved probes); `failed_serves` is the server-side lookup state the
dead peer can no longer resolve.
"""
failed_jobs: list[int] # client load job_ids
failed_req_ids: list[str] # client kv_request_ids (loads + probes)
failed_stores: list[int] # server store job_ids
failed_serves: list[ReqContext] # server-side lookup ctxs needing release
class P2PSession:
"""Bidirectional session — coordinator over ClientRole + ServerRole.
Lifecycle:
- Constructor with conn=None ⇒ pending. Accepts add_stored_blocks
but cannot send (used by the prefiller to buffer blocks before
the decoder connects).
- Constructor with conn != None ⇒ connected. Sends our own ConnectMsg
immediately; the peer's ConnectMsg arrives in poll() and is
dispatched to _on_connect, which starts
transport.add_remote_peer_async. A later poll() sees the
registration land and replies with ConnectAckMsg; a failed
registration marks the connection dead instead. Outgoing sends are
queued until ConnectAckMsg confirms our metadata reached the peer.
- attach_connection(conn) on a pending session ⇒ same as above,
starting from pending.
"""
def __init__(
self,
peer_id: str,
local_id: str,
transport: DataTransport,
local_block_len: int,
local_hash_seed: str,
conn: ControlConnection | None = None,
) -> None:
self.peer_id = peer_id
self._local_id = local_id
self._transport = transport
self._local_block_len = local_block_len
self._local_hash_seed = local_hash_seed
self._conn: ControlConnection | None = None
self._send_ready = False # True after the peer acked our ConnectMsg
# Msgs waiting to be sent on connection establishment
self._queued: list[dict] = []
# Consecutive non-protocol dispatch errors. Reset on success.
self._dispatch_error_count: int = 0
now = time.monotonic()
self._connected_at: float | None = None
self._last_activity_at: float = now
# kv_request_ids whose FetchMsg arrived during the current poll
# tick. Drained and returned in the next poll() result so the
# manager can bind kv_request_id → session and replay any
# submit_store batches parked before the binding existed.
self._new_fetch_ids: list[str] = []
# In-flight peer registration started by _on_connect. Registration
# is O(num_blocks) and runs off this thread, so ConnectAckMsg is
# held back until the future resolves — the ack is what tells the
# peer it may start sending, and nothing may be served before the
# peer's blocks are registered here.
self._pending_registration: Future[None] | None = None
self._client = ClientRole(peer_id=peer_id, send=self._send)
self._server = ServerRole(
peer_id=peer_id,
transport=transport,
send=self._send,
)
if conn is not None:
self.attach_connection(conn)
# ------------------------------------------------------------------
# Properties
# ------------------------------------------------------------------
@property
def alive(self) -> bool:
# Pending sessions (awaiting connection) are alive — only a
# closed real connection counts as dead.
return self._conn is None or self._conn.alive
@property
def connected(self) -> bool:
return self._conn is not None
@property
def ready(self) -> bool:
"""True after the peer acked our ConnectMsg (we may send freely)."""
return self._send_ready
@property
def has_pending_work(self) -> bool:
"""True while inbound loads or outbound transfers are outstanding."""
return (
self._pending_registration is not None
or self._client.has_active_loads
or self._server.has_inflight_transfers
)
@property
def last_activity_at(self) -> float:
"""Monotonic timestamp of the last meaningful session activity."""
return self._last_activity_at
# ------------------------------------------------------------------
# Connection lifecycle
# ------------------------------------------------------------------
def attach_connection(self, conn: ControlConnection) -> None:
"""Attach a connection to a pending session and announce ourselves.
Symmetric: every side advertises its NIXL metadata on connect, so
whichever peer receives a session first can register the other.
"""
if self._conn is not None:
raise ValueError(f"P2PSession {self.peer_id}: already connected")
self._conn = conn
now = time.monotonic()
self._connected_at = now
self._last_activity_at = now
self._send_connect()
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def request_blocks(
self,
job_id: JobId,
kv_request_id: str,
keys: Sequence[OffloadKey],
block_ids: Sequence[int],
) -> None:
"""Send fetch to the peer."""
self._client.request_blocks(
job_id, kv_request_id, keys, block_ids, send_ready=self._send_ready
)
def add_stored_blocks(
self,
kv_request_id: str,
keys: Sequence[OffloadKey],
block_ids: Sequence[int],
job_id: JobId,
) -> None:
"""New blocks stored locally — match against pending fetch demand."""
self._server.add_stored_blocks(kv_request_id, keys, block_ids, job_id)
def finish_request(self, kv_request_id: str) -> None:
"""Called when the request is finishing locally.
Finishes the client role (aborts any inbound load and drops any
pending symmetric-P2P lookup state) and finalizes any outbound
serving (server role) for this id. Roles that aren't active for
this id are silent no-ops.
"""
self._client.finish(kv_request_id)
self._server.finish(kv_request_id)
def register_lookup(self, kv_request_id: str, key: bytes) -> bool | None:
"""Register or resolve one (kv_request_id, key) probe.
Called from the manager's lookup() for symmetric-P2P consumers
(``remote_kv_source`` sub-dict in kv_transfer_params). See
``ClientRole.register_lookup`` for the state-machine contract.
"""
return self._client.register_lookup(kv_request_id, key)
def flush_pending_lookups(self) -> None:
"""Flush any aggregated symmetric-P2P lookups for this peer.
Called once per scheduler step from the manager's
``on_schedule_end()``. Probes wait for ConnectAckMsg before sending.
"""
self._client.flush_pending_lookups(send_ready=self._send_ready)
def serve_external_requests(self, parent: ParentManager) -> None:
"""Resolve inbound peer lookups against the tiering manager.
Delegates to the server role; the ``parent`` handle is valid
only for the duration of this call.
"""
self._server.serve_external_requests(parent)
def poll(self) -> SessionPollResult:
"""Process incoming messages, drive transfers, apply timeouts."""
if self._conn is None:
return SessionPollResult(
loads=[],
stores=self._server.collect_idle_timeouts(),
new_fetch_ids=[],
)
# Drain the inbox first so a ConnectAck already buffered at the
# deadline (e.g. after a scheduler stall) can complete the
# handshake instead of being discarded by mark_dead.
messages = self._conn.recv()
if messages:
self._last_activity_at = time.monotonic()
for msg in messages:
self._on_message(msg)
# After dispatch: a ConnectMsg handled just above may already have a
# resolved registration (transports that register inline ack in the
# same tick), and a registration started on an earlier tick may have
# landed while the engine was busy elsewhere. This runs before the
# handshake deadline below so a registration that just resolved gets
# its ConnectAckMsg out rather than being judged as timed out, and so
# a failed registration's mark_dead() short-circuits that check.
self._poll_registration()
# Handshake deadline: a peer that never completes the handshake
# is stuck in connected-but-not-ready state. Mark it dead so the
# manager reaps it instead of accumulating sockets indefinitely.
# Note this also covers the peer registering *our* region before it
# acks, so the deadline must exceed remote registration time; the
# 30s default leaves ample room for the descriptor build.
if (
not self._send_ready
and self._conn.alive
and self._connected_at is not None
and time.monotonic() - self._connected_at
> envs.VLLM_P2P_HANDSHAKE_TIMEOUT_S
):
logger.warning(
"P2PSession %s: handshake timed out after %ds "
"— marking connection dead",
self.peer_id,
envs.VLLM_P2P_HANDSHAKE_TIMEOUT_S,
)
self._conn.mark_dead()
loads = self._client.collect_results()
stores = self._server.collect_results()
self._server.drain_pending_aborts()
# Drain buffered replies and completed transfers before expiring a peer.
expired_lookup = self._client.get_expired_lookup()
if expired_lookup is not None:
req_id, elapsed = expired_lookup
logger.warning(
"P2PSession %s: lookup response timed out for kv_request_id=%s "
"after %.1fs without progress; disconnecting peer session",
self.peer_id,
req_id,
elapsed,
)
with contextlib.suppress(Exception):
self._conn.send({TYPE_KEY: DisconnectMsg.TYPE})
self._conn.mark_dead()
new_fetch_ids = self._new_fetch_ids
self._new_fetch_ids = []
return SessionPollResult(
loads=loads, stores=stores, new_fetch_ids=new_fetch_ids
)
def close(self) -> SessionCloseResult:
"""Shut down.
failed_jobs: client load job_ids to fail.
failed_req_ids: client kv_request_ids to fail — in-flight loads plus
requests with an unresolved symmetric-P2P probe toward the
now-dead peer. The manager fails these so the consumer's lookup()
falls back to local prefill instead of deferring forever on an
answer that can never arrive.
failed_stores: server store job_ids to fail.
failed_serves: synthetic lookup ctxs still owing
``parent.on_request_finished`` (the manager flushes these on
its next ``serve_external_requests``).
"""
# Abandon any in-flight registration: nothing will ack this peer
# now. The manager's remove_remote_peer bumps the transport's
# generation for this peer, so a worker already past cancellation
# releases its handles instead of publishing them.
if self._pending_registration is not None:
self._pending_registration.cancel()
self._pending_registration = None
client_result = self._client.close()
failed_stores, failed_serves = self._server.close()
if self._conn is not None:
with contextlib.suppress(Exception):
self._conn.send({TYPE_KEY: DisconnectMsg.TYPE})
self._conn.close()
self._conn = None
return SessionCloseResult(
failed_jobs=client_result.failed_jobs,
failed_req_ids=client_result.failed_req_ids,
failed_stores=failed_stores,
failed_serves=failed_serves,
)
# ------------------------------------------------------------------
# Message dispatch
# ------------------------------------------------------------------
def _on_message(self, msg: dict) -> None:
msg_type = msg.get(TYPE_KEY) if isinstance(msg, dict) else msg
try:
self._dispatch_message(msg)
except ValueError as exc:
# Protocol contract violation from the peer — *Msg.validate()
# and handler-level checks raise ValueError. Retrying won't
# help and may corrupt session state, so disconnect now.
self._protocol_error(f"malformed {msg_type!r}: {exc}")
return
except Exception as exc:
# Anything else is most likely an internal bug rather than a
# peer fault. Log loudly with a traceback so it doesn't
# disappear, but don't kill the session on a single hiccup.
# Disconnect only if errors keep arriving — that pattern is
# consistent with a peer wedging us into a broken state.
self._dispatch_error_count += 1
logger.exception(
"P2PSession %s: error handling message %r (count=%d): %s",
self.peer_id,
msg_type,
self._dispatch_error_count,
exc,
)
if self._dispatch_error_count >= _MAX_CONSECUTIVE_DISPATCH_ERRORS:
self._protocol_error(
f"too many consecutive dispatch errors "
f"({self._dispatch_error_count})"
)
return
self._dispatch_error_count = 0
def _protocol_error(self, reason: str) -> None:
"""Log a protocol violation and disconnect.
Best-effort sends ``DisconnectMsg`` so the peer learns why we're
going away, then marks the connection dead. The manager reaps
the session on the next poll via ``alive``.
"""
logger.error(
"P2PSession %s: protocol error: %s — disconnecting",
self.peer_id,
reason,
)
if self._conn is not None:
with contextlib.suppress(Exception):
self._conn.send({TYPE_KEY: DisconnectMsg.TYPE})
self._conn.mark_dead()
def _dispatch_message(self, msg: dict) -> None:
# Drop messages buffered before disconnect: a poll batch can
# contain msg-after-DisconnectMsg, and dispatching them would
# mutate state on a dead session.
if self._conn is not None and not self._conn.alive:
return
msg_type = msg.get(TYPE_KEY) if isinstance(msg, dict) else None
if msg_type == ConnectMsg.TYPE:
self._on_connect(msg)
elif msg_type == ConnectAckMsg.TYPE:
ConnectAckMsg.validate(msg)
self._on_connect_ack()
elif msg_type == FetchMsg.TYPE:
FetchMsg.validate(msg)
kv_request_id = msg[FetchMsg.KV_REQUEST_ID]
keys = [
OffloadKey(bh if isinstance(bh, bytes) else bytes(bh))
for bh in msg[FetchMsg.KEYS]
]
block_indexes = msg[FetchMsg.BLOCK_INDEXES]
round_seq = msg[FetchMsg.ROUND_SEQ]
# Run the server-role state machine inline as today —
# add_fetch_demand records demand against any blocks we've
# already seen in `available`. Report the kv_request_id so
# the manager (after poll() returns) can replay any parked
# submit_store batches; their add_stored_blocks calls hit
# the demand recorded here and submit transfers immediately.
self._server.on_fetch(kv_request_id, keys, block_indexes, round_seq)
self._new_fetch_ids.append(kv_request_id)
elif msg_type == AbortFetchMsg.TYPE:
AbortFetchMsg.validate(msg)
self._server.on_abort_fetch(
msg[AbortFetchMsg.KV_REQUEST_ID],
msg[AbortFetchMsg.ROUND_SEQ],
)
elif msg_type == TransferDoneMsg.TYPE:
TransferDoneMsg.validate(msg)
self._client.on_transfer_done(
msg[TransferDoneMsg.KV_REQUEST_ID],
msg[TransferDoneMsg.SUCCESS],
msg[TransferDoneMsg.ROUND_SEQ],
)
elif msg_type == AbortAckMsg.TYPE:
AbortAckMsg.validate(msg)
self._client.on_abort_ack(
msg[AbortAckMsg.KV_REQUEST_ID],
msg[AbortAckMsg.ROUND_SEQ],
)
elif msg_type == LookupMsg.TYPE:
LookupMsg.validate(msg)
kv_request_id = msg[LookupMsg.KV_REQUEST_ID]
keys = [
OffloadKey(bh if isinstance(bh, bytes) else bytes(bh))
for bh in msg[LookupMsg.KEYS]
]
self._server.on_lookup(kv_request_id, keys, msg[LookupMsg.ROUND_SEQ])
elif msg_type == LookupRespMsg.TYPE:
LookupRespMsg.validate(msg)
kv_request_id = msg[LookupRespMsg.KV_REQUEST_ID]
keys = [
OffloadKey(bh if isinstance(bh, bytes) else bytes(bh))
for bh in msg[LookupRespMsg.KEYS]
]
hits = msg[LookupRespMsg.HITS]
self._client.on_lookup_resp(kv_request_id, keys, hits)
elif msg_type == DisconnectMsg.TYPE:
if self._conn is not None:
self._conn.mark_dead()
else:
logger.warning(
"P2PSession %s: unknown message type %r", self.peer_id, msg_type
)
# ------------------------------------------------------------------
# Handshake
# ------------------------------------------------------------------
def _on_connect(self, msg: dict) -> None:
# Validation failures here mean an incompatible or malicious peer.
# Mark the connection dead so the manager reaps the session;
# don't call add_remote_peer or send connect_ack.
if self._send_ready or self._pending_registration is not None:
# Either the handshake completed (we hold the peer's ack) or a
# registration for this peer is already in flight. A second
# connect either way is a protocol violation — re-registering
# would corrupt transport state.
self._protocol_error("duplicate connect after handshake")
return
try:
ConnectMsg.validate(msg)
if msg[ConnectMsg.BLOCK_LEN] != self._local_block_len:
raise ValueError(
f"block_len mismatch from {self.peer_id}: "
f"remote={msg[ConnectMsg.BLOCK_LEN]}, "
f"local={self._local_block_len}"
)
remote_fp = msg.get(ConnectMsg.CONFIG_FINGERPRINT, "")
local_fp = self._transport.config_fingerprint
if local_fp and remote_fp and remote_fp != local_fp:
raise ValueError(
f"config fingerprint mismatch from {self.peer_id}: "
f"remote={remote_fp!r}, local={local_fp!r}"
)
if msg[ConnectMsg.HASH_SEED] != self._local_hash_seed:
raise ValueError(
f"hash seed mismatch from {self.peer_id}: "
f"remote={msg[ConnectMsg.HASH_SEED]!r}, "
f"local={self._local_hash_seed!r}. Ensure PYTHONHASHSEED "
"(if set) matches on all P2P peers."
)
registration = self._transport.add_remote_peer_async(
self.peer_id,
agent_metadata=msg[ConnectMsg.AGENT_METADATA],
base_addr=msg[ConnectMsg.BASE_ADDR],
num_blocks=msg[ConnectMsg.NUM_BLOCKS],
block_len=msg[ConnectMsg.BLOCK_LEN],
)
except ValueError as exc:
logger.error("P2PSession %s: rejecting peer connect: %s", self.peer_id, exc)
if self._conn is not None:
self._conn.mark_dead()
return
# ConnectAckMsg is deferred to _poll_registration once the
# registration lands; sending it now would let the peer fetch
# against blocks this side has not registered yet.
self._pending_registration = registration
def _poll_registration(self) -> None:
"""Ack or reject the peer once its registration resolves.
Called from poll() after message dispatch. A successful
registration releases ConnectAckMsg — the peer treats that as
permission to send, so it must not go out earlier. A failed one
marks the connection dead so the manager reaps the session.
"""
registration = self._pending_registration
if registration is None or not registration.done():
return
self._pending_registration = None
try:
registration.result()
except Exception as exc:
logger.error(
"P2PSession %s: peer registration failed, rejecting peer: %s",
self.peer_id,
exc,
)
if self._conn is not None:
self._conn.mark_dead()
return
if self._conn is not None and self._conn.alive:
self._conn.send(
{
TYPE_KEY: ConnectAckMsg.TYPE,
ConnectAckMsg.PEER_ID: self._local_id,
}
)
def _on_connect_ack(self) -> None:
if self._queued:
logger.debug(
"P2PSession %s: connect_ack received, flushing %d queued msg(s)",
self.peer_id,
len(self._queued),
)
self._send_ready = True
for queued in self._queued:
self._do_send(queued)
self._queued.clear()
# ------------------------------------------------------------------
# Send helpers
# ------------------------------------------------------------------
def _send_connect(self) -> None:
"""Send our ConnectMsg announcing local NIXL metadata."""
assert self._conn is not None
self._conn.send(
{
TYPE_KEY: ConnectMsg.TYPE,
ConnectMsg.PEER_ID: self._local_id,
ConnectMsg.AGENT_METADATA: self._transport.get_agent_metadata(),
ConnectMsg.BASE_ADDR: self._transport.base_addr,
ConnectMsg.NUM_BLOCKS: self._transport.num_blocks,
ConnectMsg.BLOCK_LEN: self._transport.block_len,
ConnectMsg.CONFIG_FINGERPRINT: self._transport.config_fingerprint,
ConnectMsg.HASH_SEED: self._local_hash_seed,
}
)
def _send(self, msg: dict) -> None:
if self._conn is None or not self._send_ready:
logger.debug(
"P2PSession %s: queueing %s (ready=%s queue_depth=%d)",
self.peer_id,
msg.get(TYPE_KEY),
self._send_ready,
len(self._queued) + 1,
)
self._queued.append(msg)
return
self._do_send(msg)
def _do_send(self, msg: dict) -> None:
if self._conn is None:
return
try:
self._conn.send(msg)
self._last_activity_at = time.monotonic()
logger.debug("P2PSession %s: sent %s", self.peer_id, msg.get(TYPE_KEY))
except Exception:
# A send failure means the connection is broken. Swallowing it
# silently strands every in-flight lookup/load toward this peer:
# the session stays alive, is never reaped, and the consumer's
# lookup() keeps returning RETRY until the HTTP client times out.
# Mark the connection dead so the manager reaps the session on
# its next poll and surfaces the stranded work as failures.
logger.warning(
"P2PSession %s: send of %s failed — marking connection dead",
self.peer_id,
msg.get(TYPE_KEY),
)
self._conn.mark_dead()
-579
View File
@@ -1,579 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TieringOffloadingSpec: Spec for multi-tier KV cache offloading.
This spec creates a TieringOffloadingManager with a CPU primary tier
and configurable secondary tiers (e.g., Storage, Network).
Configuration via kv_connector_extra_config:
- cpu_bytes_to_use: (required) Bytes to allocate for CPU primary tier
- 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
(default: "lru")
- cache_policy_module_path: (optional) Python import path to load
eviction_policy from when it names an out-of-tree CachePolicy not
registered via CachePolicyFactory
- secondary_tiers: (optional) List of secondary tier configurations
Each secondary tier config is a dict with:
- type: (required) Type of secondary tier (e.g., "example", "fs",
"p2p", "obj"), or the class name of an out-of-tree
SecondaryTierManager paired with module_path.
- module_path: (optional) Python import path to load 'type' from
when it names an out-of-tree SecondaryTierManager not registered
via SecondaryTierFactory.register_tier()
- Additional tier-specific parameters are passed directly to the tier
constructor. See each tier's documentation for supported parameters.
Example configuration:
{
"cpu_bytes_to_use": 10737418240, # 10 GB
"block_size": 16,
"eviction_policy": "lru",
"secondary_tiers": [
{
"type": "example",
"custom_param": 67
}
]
}
Example out-of-tree tier configuration:
{
"cpu_bytes_to_use": 10737418240,
"secondary_tiers": [
{
"type": "MyCustomTier",
"module_path": "my_package.my_module",
"custom_param": "value"
}
]
}
"""
from typing import Any
from typing_extensions import override
from vllm.logger import init_logger
from vllm.v1.kv_offload.base import (
CanonicalKVCaches,
OffloadingCounterMetadata,
OffloadingGaugeMetadata,
OffloadingHistogramMetadata,
OffloadingManager,
OffloadingMetricMetadata,
)
from vllm.v1.kv_offload.config import OffloadingConfig
from vllm.v1.kv_offload.cpu.gpu_worker import CPUOffloadingWorker
from vllm.v1.kv_offload.cpu.shared_offload_region import SharedOffloadRegion
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
from vllm.v1.kv_offload.tiering.base import (
TIER_LABEL,
SecondaryTierManager,
TieringOffloadingMetrics,
)
from vllm.v1.kv_offload.tiering.factory import SecondaryTierFactory
from vllm.v1.kv_offload.tiering.manager import (
DEFAULT_TIER_POLL_INTERVAL_S,
CPUPrimaryTierOffloadingManager,
TieringOffloadingManager,
)
logger = init_logger(__name__)
class TieringOffloadingSpec(CPUOffloadingSpec):
"""Spec for multi-tier KV cache offloading.
Creates a TieringOffloadingManager with:
- Primary tier: CPU (LRU or ARC eviction policy)
- Secondary tiers: Configurable via extra_config
The CPU primary tier has direct GPU access and serves as the gateway for
all GPU↔offload operations. Secondary tiers cannot directly access GPU
memory and must transfer data through the primary tier.
"""
BLOCK_SIZE_ALIGNMENT = SharedOffloadRegion.BLOCK_SIZE_ALIGNMENT
@classmethod
@override
def build_metric_definitions(
cls, extra_config: dict[str, Any]
) -> dict[str, OffloadingMetricMetadata]:
metrics = super().build_metric_definitions(extra_config)
metrics[TieringOffloadingMetrics.LOOKUP_SYNC_DELAY] = (
OffloadingHistogramMetadata(
documentation=(
"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_LABEL,),
buckets=(
0.00001,
0.00005,
0.0001,
0.0005,
0.001,
0.005,
0.01,
0.05,
0.1,
0.5,
1,
),
)
)
metrics[TieringOffloadingMetrics.LOOKUP_ASYNC_DELAY] = (
OffloadingHistogramMetadata(
documentation=(
"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."
),
labelnames=(TIER_LABEL,),
buckets=(
0.0001,
0.0005,
0.001,
0.005,
0.01,
0.05,
0.1,
0.5,
1,
5,
10,
),
)
)
metrics[TieringOffloadingMetrics.READ_BYTES] = OffloadingCounterMetadata(
documentation=(
"Total bytes read from secondary tiers into the primary tier, "
"labeled by tier."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.READ_TIME] = OffloadingCounterMetadata(
documentation=(
"Total time spent reading from secondary tiers into the primary "
"tier, in seconds, labeled by tier. Tiers that do not report "
"per-job transfer time have no series here. Use "
"vllm:kv_offload_tiering_promotion_latency_seconds for "
"tier-independent promotion timing."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.WRITE_BYTES] = OffloadingCounterMetadata(
documentation=(
"Total bytes written from the primary tier to secondary tiers, "
"labeled by tier."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.WRITE_TIME] = OffloadingCounterMetadata(
documentation=(
"Total time spent writing from the primary tier to secondary "
"tiers, in seconds, labeled by tier. Tiers that do not report "
"per-job transfer time have no series here."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.PROMOTION_JOB_FAILURES] = (
OffloadingCounterMetadata(
documentation=(
"Number of failed secondary-tier promotion jobs, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.CASCADE_JOB_FAILURES] = (
OffloadingCounterMetadata(
documentation=(
"Number of failed secondary-tier cascade jobs, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.CHUNK_QUERIES] = OffloadingCounterMetadata(
documentation=(
"Number of chunk lookup queries sent to a tier, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.CHUNK_HITS] = OffloadingCounterMetadata(
documentation="Number of chunk lookup hits in a tier, labeled by tier.",
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.PROMOTION_ALLOCATION_FAILURES] = (
OffloadingCounterMetadata(
documentation=(
"Number of promotion attempts that failed because the "
"primary tier could not allocate space."
),
)
)
metrics[TieringOffloadingMetrics.PRIMARY_WRITE_USAGE_PERC] = (
OffloadingGaugeMetadata(
documentation=(
"Current fraction of primary-tier space used by writes from "
"secondary tiers, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.PRIMARY_READ_USAGE_PERC] = (
OffloadingGaugeMetadata(
documentation=(
"Current fraction of primary-tier space used by reads to "
"secondary tiers, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.ACTIVE_PROMOTION_JOBS] = (
OffloadingGaugeMetadata(
documentation=(
"Number of active secondary-tier promotion jobs, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.ACTIVE_CASCADE_JOBS] = OffloadingGaugeMetadata(
documentation=(
"Number of active secondary-tier cascade jobs, labeled by tier."
),
labelnames=(TIER_LABEL,),
)
metrics[TieringOffloadingMetrics.PROMOTION_LATENCY] = (
OffloadingHistogramMetadata(
documentation=(
"Histogram of per-job latency for secondary-tier promotion "
"attempts, measured from job creation until the tiering "
"manager observes completion so that tier queueing is "
"included, labeled by tier and result, in seconds. Includes "
"failed attempts."
),
labelnames=(TIER_LABEL, "result"),
buckets=(
0.005,
0.01,
0.025,
0.05,
0.1,
0.25,
0.5,
1,
2.5,
5,
10,
30,
60,
),
)
)
for tier_config, tier_cls in cls._get_secondary_tiers(extra_config):
metrics.update(tier_cls.build_metric_definitions(tier_config))
metrics[TieringOffloadingMetrics.BACKPRESSURE_STORE_LATENCY_EMA] = (
OffloadingGaugeMetadata(
documentation=(
"Exponential moving average of store latency "
"for back-pressure detection, in s/MiB."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.BACKPRESSURE_STORES_DROPPED] = (
OffloadingCounterMetadata(
documentation=(
"Number of store operations dropped due to "
"back-pressure on a secondary tier."
),
labelnames=(TIER_LABEL,),
)
)
metrics[TieringOffloadingMetrics.BACKPRESSURE_BLOCKS_DROPPED] = (
OffloadingCounterMetadata(
documentation=(
"Number of blocks dropped due to back-pressure on a secondary tier."
),
labelnames=(TIER_LABEL,),
)
)
return metrics
def __init__(self, config: OffloadingConfig):
super().__init__(config)
# Redeclare for mypy: parent sets this but `--follow-imports skip` hides it
self._manager: OffloadingManager | None = None
# Parse secondary tier configurations
self.secondary_tier_configs = self.extra_config.get("secondary_tiers", [])
if not isinstance(self.secondary_tier_configs, list):
raise ValueError("secondary_tiers must be a list of tier configurations")
# Pause between tier-poll rounds for tiers that need servicing
# between engine steps. Zero or negative disables the thread, which
# restores per-step servicing.
self.tier_poll_interval_s = float(
self.extra_config.get("tier_poll_interval_s", DEFAULT_TIER_POLL_INTERVAL_S)
)
# Backpressure config is merged field-by-field in priority order
# (highest first):
# 1. Per-tier ``backpressure`` dict in the tier config
# 2. Top-level ``backpressure`` in kv_connector_extra_config
# Merging per field (rather than per whole dict) means a partial
# tier override still inherits missing fields from the top-level
# default, so the resolved dict reaching the factory is complete.
# Within each tier's resolved dict, tier-type-aware water marks
# are filled in last so a bare ``"backpressure": {}`` picks up
# sensible thresholds for the storage medium.
bp_defaults = self.extra_config.get("backpressure")
for tier_cfg in self.secondary_tier_configs:
tier_override = tier_cfg.get("backpressure")
# Overlay from lowest to highest precedence so higher-precedence
# fields win while lower-precedence ones fill in the gaps.
merged: dict[str, Any] = {}
for source in (bp_defaults, tier_override):
if source:
merged.update(source)
# Only set a resolved dict when at least one source contributed
# (or an explicit ``backpressure`` key was present, e.g. ``{}``),
# so tiers without any backpressure config stay unconfigured.
if merged or "backpressure" in tier_cfg:
tier_cfg["backpressure"] = merged
# Scheduler-side mmap (rank=None); kept for cleanup
self._scheduler_mmap: SharedOffloadRegion | None = None
# Set by create_worker when canonical_layout is enabled: True when
# every layer's canonical bytes are parallelism-agnostic (portable),
# False when some layers use the opaque fallback (exact-topology only)
self.all_layers_portable: bool | None = None
# engine_id is unique per DP replica (suffixed with _dp{rank} in both
# the Ray and multiprocessing paths), so it names a per-replica offload
# region.
self._engine_id = config.engine_id
@override
def get_manager(self) -> OffloadingManager:
"""Get the TieringOffloadingManager.
Creates a TieringOffloadingManager with:
- Primary tier: CPU (LRU or ARC)
- Secondary tiers: As configured in extra_config
Returns:
TieringOffloadingManager instance
"""
if not self._manager:
if int(self.extra_config.get("store_threshold", 0)) >= 2:
raise ValueError(
"store_threshold is not supported for TieringOffloadingSpec"
)
scheduler_mmap: SharedOffloadRegion | None = None
primary_tier: CPUPrimaryTierOffloadingManager | None = None
secondary_tiers = []
try:
# Create scheduler-side SharedOffloadRegion (rank=None) so the
# primary tier can eagerly create a memoryview over _base.
scheduler_mmap = SharedOffloadRegion(
engine_id=self._engine_id,
num_chunks=self.num_chunks,
rank=None,
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_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,
mmap_region=scheduler_mmap,
)
# Create secondary tiers
primary_kv_view = primary_tier.get_kv_memoryview()
for i, tier_config in enumerate(self.secondary_tier_configs):
tier = SecondaryTierFactory.create_secondary_tier(
tier_config, primary_kv_view, self
)
secondary_tiers.append(tier)
logger.info(
"Created secondary tier #%d (%s)",
i,
tier.tier_type,
)
# Create TieringOffloadingManager. GPU↔CPU transfers use the inherited
# get_worker(). Secondary tier transfers are handled by the
# secondary tier managers and need no additional workers here.
tiering_manager = TieringOffloadingManager(
primary_tier=primary_tier,
secondary_tiers=secondary_tiers,
tier_poll_interval_s=self.tier_poll_interval_s,
)
self._manager = tiering_manager
except Exception:
for tier in reversed(secondary_tiers):
try:
tier.shutdown()
except Exception:
logger.exception(
"Failed to shut down secondary tier during "
"initialization cleanup"
)
if primary_tier is not None:
try:
primary_tier.shutdown()
except Exception:
logger.exception(
"Failed to shut down primary tier during "
"initialization cleanup"
)
elif scheduler_mmap is not None:
try:
scheduler_mmap.cleanup()
except Exception:
logger.exception(
"Failed to clean up scheduler mmap during "
"initialization cleanup"
)
self._scheduler_mmap = None
raise
logger.info(
"Created TieringOffloadingManager with primary tier "
"(%s, %s chunks) and %s secondary tier(s)",
self.eviction_policy,
self.num_chunks,
len(secondary_tiers),
)
return self._manager
@classmethod
@override
def config_info_keys(cls, extra_config: dict[str, Any]) -> tuple[str, ...]:
"""Return TIER_LABEL and the label names of all tiers, with no repeat."""
# dict.fromkeys() keeps one copy of a name that two tier types share.
keys = dict.fromkeys(super().config_info_keys(extra_config))
keys[TIER_LABEL] = None
for tier_config, tier_cls in cls._get_secondary_tiers(extra_config):
tier_keys = tier_cls.config_info_keys(tier_config)
assert TIER_LABEL not in tier_keys, (
f"{tier_cls.__name__} must not declare the reserved label "
f"{TIER_LABEL!r}"
)
keys.update(dict.fromkeys(tier_keys))
return tuple(keys)
@classmethod
def _get_secondary_tiers(
cls, extra_config: dict[str, Any]
) -> list[tuple[dict[str, Any], type[SecondaryTierManager]]]:
"""Resolve every configured secondary tier to its manager class.
Args:
extra_config: kv_connector_extra_config of this instance.
Returns:
One (tier config, tier class) pair for each secondary tier, in
configuration order. That order sets the tier index.
Raises:
ValueError: If secondary_tiers is not a list.
"""
secondary_tier_configs = extra_config.get("secondary_tiers", [])
if not isinstance(secondary_tier_configs, list):
raise ValueError("secondary_tiers must be a list of tier configurations")
tiers = []
for tier_config in secondary_tier_configs:
assert isinstance(tier_config, dict)
tier_cls = SecondaryTierFactory.get_tier_class(tier_config)
tiers.append((tier_config, tier_cls))
return tiers
@override
def _uses_shared_region(self) -> bool:
# Tiering always allocates on the shared region (every platform), so the
# replicated-layout gate must not be narrowed by the CPU spec's
# CUDA-alike check.
return True
@override
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
rank = 0 if self.replicated_layout else self.config.parallel.rank
worker_mmap = SharedOffloadRegion(
engine_id=self._engine_id,
num_chunks=self.num_chunks,
rank=rank,
kv_bytes_per_chunk=self.kv_bytes_per_chunk,
cpu_page_size=self.cpu_page_size_per_worker,
)
try:
if self.config.canonical_layout:
self._validate_canonical_refs(kv_caches)
return CPUOffloadingWorker(
kv_caches=kv_caches,
blocks_per_chunk=self.blocks_per_chunk,
num_cpu_chunks=self.num_chunks,
mmap_region=worker_mmap,
canonical_layout=self.config.canonical_layout,
)
except Exception:
worker_mmap.cleanup()
raise
def _validate_canonical_refs(self, kv_caches: CanonicalKVCaches) -> None:
"""Require a mapping on every ref and record layer portability.
Fails loudly rather than persist direct-layout bytes under a
canonical format identity."""
all_refs = [
ref for group_refs in kv_caches.group_data_refs for ref in group_refs
]
if any(ref.mapping is None for ref in all_refs):
raise RuntimeError(
"canonical_layout was requested but the KV cache layout "
"could not be certified for canonical offload (offload "
"workers must be exactly the TP group, and packed / "
"cross-layer KV layouts are not supported). Remove "
"canonical_layout from kv_connector_extra_config."
)
self.all_layers_portable = all(
ref.mapping is not None and ref.mapping.parallelism_agnostic
for ref in all_refs
)
if self.config.parallel.is_parallelism_agnostic and not (
self.all_layers_portable
):
# The scheduler-side storage namespace was already collapsed on
# the static portability claim; opaque per-topology bytes must
# not land in it.
raise RuntimeError(
"canonical_layout could not certify every layer as "
"parallelism-agnostic, but the storage namespace is shared "
"across topologies. Remove canonical_layout from "
"kv_connector_extra_config or disable parallel-agnostic "
"secondary tiers."
)
logger.info(
"Canonical KV layout enabled (all_layers_portable=%s)",
self.all_layers_portable,
)
-6
View File
@@ -49,9 +49,6 @@ class InvalidComponent(Exception):
_QUANT_WEIGHT_BYTE_SIZE: dict[str, float] = {
# FP8 methods (1 byte per weight)
"fp8": 1,
"fbgemm_fp8": 1,
"ptpc_fp8": 1,
"fp_quant": 1,
"modelopt": 1,
"modelopt_mxfp8": 1,
# FP4 / INT4 methods (0.5 bytes per weight)
@@ -61,12 +58,9 @@ _QUANT_WEIGHT_BYTE_SIZE: dict[str, float] = {
"gptq": 0.5,
"gptq_marlin": 0.5,
"modelopt_fp4": 0.5,
"petit_nvfp4": 0.5,
"compressed-tensors": 0.5,
"torchao": 0.5,
"quark": 0.5,
"moe_wna16": 0.5,
"inc": 0.5,
"experts_int8": 1,
}
@@ -15,7 +15,6 @@ from vllm.logger import init_logger
from vllm.sampling_params import SamplingParams
from vllm.tokenizers import TokenizerLike
from vllm.utils.import_utils import LazyLoader
from vllm.utils.mistral import is_mistral_tokenizer
from vllm.v1.structured_output.backend_types import (
StructuredOutputBackend,
StructuredOutputGrammar,
@@ -150,15 +149,12 @@ class GuidanceBackend(StructuredOutputBackend):
In that case we will remove this check from vLLM.
That kind of work is really appreciated!
"""
if is_mistral_tokenizer(tokenizer):
return tokenizer.is_tekken
# PreTrainedTokenizerFast is the same as TokenizersBackend
return isinstance(tokenizer, TokenizersBackend)
@staticmethod
def _build_ll_tokenizer(tokenizer: TokenizerLike, vocab_size: int) -> Any:
if is_mistral_tokenizer(tokenizer):
return tokenizer.llg_tokenizer
return llguidance_hf.from_tokenizer(tokenizer, max(vocab_size, len(tokenizer)))
def __post_init__(self):
+1 -20
View File
@@ -12,7 +12,6 @@ from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.sampling_params import SamplingParams, check_json_nesting
from vllm.utils.import_utils import LazyLoader
from vllm.utils.mistral import is_mistral_tokenizer
from vllm.v1.structured_output.backend_types import (
StructuredOutputBackend,
StructuredOutputGrammar,
@@ -46,25 +45,7 @@ class XgrammarBackend(StructuredOutputBackend):
)
full_vocab_tokenizer_info = None
if is_mistral_tokenizer(self.tokenizer):
# NOTE: ideally, xgrammar should handle this accordingly.
# refer to https://github.com/mlc-ai/xgrammar/blob/d77c0a0173ef14779c918e3be7966ba852f7910f/python/xgrammar/tokenizer_info.py#L98
stop_token_ids = [self.tokenizer.eos_token_id]
# not self.tokenizer.vocab_size as self.tokenizer.vocab
# collapses all decoded errors into a single token.
self.vocab_size = len(self.tokenizer.vocab)
tokenizer_info = xgr.TokenizerInfo( # type: ignore
encoded_vocab=self.tokenizer.vocab,
# NOTE: https://github.com/mlc-ai/xgrammar/blob/5e141f6ff1ca02bc31f9e512e68b61f2a8ae88e5/tests/python/test_tokenizer_info.py#L43 # noqa: E501
vocab_type=xgr.VocabType.RAW
if self.tokenizer.is_tekken
else xgr.VocabType.BYTE_FALLBACK,
vocab_size=self.vocab_size,
stop_token_ids=stop_token_ids,
add_prefix_space=True,
)
elif is_plamo3 and callable(
if is_plamo3 and callable(
init_xgrammar := getattr(self.tokenizer, "init_xgrammar", None)
):
tokenizer_info, _ = init_xgrammar()
-6
View File
@@ -283,12 +283,6 @@ class WorkerWrapperBase:
load_general_plugins()
# Let the platform replace core Triton kernels (e.g. CPU fallback
# implementations) before any worker or model code can launch them.
from vllm.platforms import current_platform
current_platform.register_triton_kernel_overrides()
parallel_config = vllm_config.parallel_config
if isinstance(parallel_config.worker_cls, str):
worker_class: type[WorkerBase] = resolve_obj_by_qualname(