vllm.v1.kv_offload.tiering.manager
¶
TieringOffloadingManager: Multi-tier KV cache offloading orchestrator.
This manager coordinates between a CPU primary tier (with direct GPU access) and zero or more secondary tiers (Storage, Network, etc.) to provide hierarchical KV cache offloading.
Key Design Principles: 1. When a chunk is stored to the primary tier, cascade it to secondary tiers that accept stores for the request 2. Primary tier is the gateway — Secondary tiers cannot access GPU memory directly; all data flows through the CPU primary tier 3. Staged promotion — Chunks in secondary tiers must be promoted to the primary tier before GPU can access them 4. Transparent retry mechanism — Return None from lookup() to signal "data is being promoted, try later" 5. ref_cnt as eviction protection — primary.prepare_read() increments ref_cnt, protecting chunks from eviction until complete_read() is called
Classes:
-
CPUPrimaryTierOffloadingManager–CPUOffloadingManager with a primary/secondary transfer interface.
-
PendingPromotion–Accumulator for chunks awaiting submit_load() for one (tier, request).
-
TieringOffloadingManager–Orchestrates multi-tier KV cache offloading.
CPUPrimaryTierOffloadingManager
¶
Bases: CPUOffloadingManager
CPUOffloadingManager with a primary/secondary transfer interface.
The inherited prepare_store/complete_store/prepare_load/complete_load are the GPU-facing OffloadingManager interface. These aliases expose the same operations from the secondary tier perspective, where read/write refers to secondary accessing primary. This avoids confusion when reading TieringOffloadingManager code (e.g. calling prepare_load inside a cascade/store path would be misleading).
Methods:
-
complete_write–Complete a secondary-to-primary write.
-
defer_write_release–Fail pending writes like
complete_write(False), deferring the release. -
get_kv_memoryview–Return the memoryview over the primary tier's KV cache buffer.
-
prepare_read–Pin chunks for a CPU-to-secondary transfer.
-
prepare_write–Prepare a secondary-to-primary write. It has no store trigger.
-
release_deferred_write–Complete a deferred release: return the chunks to the free pool.
complete_write(keys, req_context, success=True)
¶
Complete a secondary-to-primary write.
defer_write_release(keys)
¶
Fail pending writes like complete_write(False), deferring the release.
The keys leave the cache (lookups miss and a later store allocates a
fresh chunk), while the chunks stay counted as write-pending and out
of the free pool. Returns the deferred chunk ids, to be passed to
release_deferred_write once the writer can no longer touch them.
get_kv_memoryview()
¶
Return the memoryview over the primary tier's KV cache buffer.
The view has shape (num_chunks, row_stride_bytes) and is backed by the
SharedOffloadRegion mmap. Secondary tiers address chunk c as
view[c].
prepare_read(keys, req_context)
¶
Pin chunks for a CPU-to-secondary transfer.
Cascade reads are implementation details of tiering, not additional request accesses, so they must not alter request-scoped recency.
prepare_write(keys, req_context)
¶
Prepare a secondary-to-primary write. It has no store trigger.
release_deferred_write(chunk_ids)
¶
Complete a deferred release: return the chunks to the free pool.
PendingPromotion
dataclass
¶
Accumulator for chunks awaiting submit_load() for one (tier, request).
TieringOffloadingManager
¶
Bases: OffloadingManager
Orchestrates multi-tier KV cache offloading.
This manager coordinates between a CPU primary tier (with direct GPU access) and zero or more secondary tiers (Storage, Network, etc.) to provide hierarchical KV cache offloading.
Key internal state
- Minimal state tracking; relies on secondary tiers to report completion via get_finished_jobs()
- Secondary tiers return JobResult objects containing all necessary information
- job_id_counter: monotonically increasing counter for job IDs
Methods:
-
__init__–Initialize the TieringOffloadingManager.
-
complete_load–Mark chunks as done loading from primary tier to GPU.
-
complete_store–Mark chunks as done storing from GPU to primary tier.
-
config_info–Return one mapping for each tier, primary tier first, with TIER_LABEL.
-
create_store_job–Pin chunks in the primary tier and create a tracked store job.
-
has_pending_work–Report whether outstanding work needs an engine step to finish.
-
lookup–Check whether a single chunk is offloaded and ready.
-
on_new_request–Query each secondary tier for its offload policy preference.
-
on_schedule_end–End-of-schedule hook: process finished jobs, flush deferred
-
poll_tiers–Advance the control plane of tiers that cannot wait for a step.
-
prepare_load–Prepare chunks to be loaded from primary tier to GPU.
-
prepare_store–Prepare chunks to be stored from GPU to primary tier.
-
reset_cache–Reset transfer bookkeeping and primary-tier cache.
-
shutdown–Shut down secondary tiers before releasing primary resources.
-
take_events–Yield events owned by the primary and secondary tiers.
__init__(primary_tier, secondary_tiers=None, tier_poll_interval_s=DEFAULT_TIER_POLL_INTERVAL_S)
¶
Initialize the TieringOffloadingManager.
Parameters:
-
(primary_tier¶CPUPrimaryTierOffloadingManager) –The primary tier manager (CPU-based).
-
(secondary_tiers¶list[SecondaryTierManager] | None, default:None) –List of secondary tier managers (e.g., Storage, Network). Can be None or empty list.
-
(tier_poll_interval_s¶float, default:DEFAULT_TIER_POLL_INTERVAL_S) –Pause between tier-poll rounds for tiers that set tolerates_off_thread_polling. Zero or negative disables the thread, leaving those tiers serviced once per engine step as before.
_cascade_existing_chunks_to_request_level_tiers(keys, req_context, request_level_tiers)
¶
For tiers that requested request-level policy, submit_store() for chunks that are already present in the primary tier.
A key whose primary write is still in flight (HIT_PENDING) cannot be dropped: prepare_store already excluded it as present, and the scheduler advances past its chunk, so no path offers it again. Park it instead. MISS keys are dropped, since nothing is there to read.
The primary tier resolves every key it holds, so RETRY cannot reach here. Parking on it would have no guarantee of ever draining, which is what makes parking HIT_PENDING safe, so it is rejected rather than guessed at.
_flush_pending_cascades()
¶
Retry request-level cascades parked on an in-flight primary write.
A parked key always resolves, to HIT or to MISS, so the set drains and a request cannot be held from finalization forever.
_flush_pending_promotions()
¶
Submit one batched submit_load() per (tier, request).
Called from on_schedule_end() at the end of each scheduler step, flushing all promotion requests deferred during lookup().
_initiate_promotion(tier_idx, key, req_context)
¶
Queue a chunk for promotion from a secondary tier to the primary tier.
Allocates space in the primary tier immediately (sets ref_cnt=-1 so subsequent lookups within the same step see the slot as in-flight), then defers the actual submit_load() call to _flush_pending_promotions() so all chunks queued during one engine step are submitted as a single batched job.
Parameters:
-
(tier_idx¶int) –The secondary tier index to promote from
-
(key¶OffloadKey) –Chunk to promote
-
(req_context¶ReqContext) –Per-request context forwarded to primary.prepare_write().
Returns:
-
bool–True if promotion was initiated, False if primary tier is full.
_maybe_finalize_request(req_id, exclude_tier_idx=None)
¶
Finalize secondary tiers once no more cascades can be submitted.
Their finalization is delayed until pending GPU->primary stores finish, since those callbacks may still submit secondary stores.
_maybe_process_finished_jobs()
¶
Poll secondary tiers for completed jobs (at most once per step).
Guarded by _processed_jobs_this_step: the first call in an engine step does the actual polling; subsequent calls are no-ops. The flag is reset in on_schedule_end() at the end of each step.
_next_job_id()
¶
Generate a unique job ID for async transfer tracking.
_process_finished_jobs(tiers=None)
¶
Unconditionally poll secondary tiers for completed jobs.
This method: 1. Calls get_finished_jobs() on each secondary tier 2. For completed stores (primary→secondary): calls primary.complete_read() to decrement ref_cnt 3. For completed loads (secondary→primary): calls primary.complete_write() to make chunks available
Parameters:
-
(tiers¶Sequence[SecondaryTierManager] | None, default:None) –Tiers to poll. Defaults to every secondary tier. Pass a subset to poll only the tiers a caller is responsible for, so a tier that expects to be polled on the scheduler thread is not dragged elsewhere.
_start_tier_poll_thread()
¶
Start the tier-poll thread, if any tier asked for one.
_stop_tier_poll_thread()
¶
Stop and join the tier-poll thread.
Must run before any tier teardown: the thread drives tier transports, and closing one underneath it can crash the process rather than raise.
complete_load(keys, req_context)
¶
Mark chunks as done loading from primary tier to GPU.
This decrements ref_cnt on the chunks in the primary tier, allowing them to be evicted again.
Parameters:
-
(keys¶Collection[OffloadKey]) –Chunks that finished loading.
-
(req_context¶ReqContext) –Per-request context.
complete_store(keys, req_context, *, trigger, success=True)
¶
Mark chunks as done storing from GPU to primary tier.
This is where secondary tier cascading happens — after chunks are confirmed to be in the primary tier, they are cascaded to secondary tiers that accept stores for this request.
For each secondary tier: 1. Call primary.prepare_read() to get LoadStoreSpec AND increment ref_cnt (protecting chunks during async transfer) 2. Call tier.submit_store() to start async transfer: primary→secondary 3. Track the job in _store_jobs dictionary
Parameters:
-
(keys¶Collection[OffloadKey]) –Chunks that finished storing.
-
(req_context¶ReqContext) –Per-request context forwarded to primary.prepare_read().
-
(trigger¶StoreTrigger) –The trigger given to the matching prepare_store().
-
(success¶bool, default:True) –Whether the GPU→primary transfer succeeded.
config_info()
¶
Return one mapping for each tier, primary tier first, with TIER_LABEL.
Raises:
-
ValueError–If the primary tier returns more than one mapping.
create_store_job(keys, req_context, tier_idx=0)
¶
Pin chunks in the primary tier and create a tracked store job.
Calls prepare_read() to increment ref_cnt (protecting chunks from eviction during the async transfer), allocates a job ID, and registers the job in _jobs.
The caller is responsible for the actual data transfer and reporting completion via get_finished_jobs().
has_pending_work()
¶
Report whether outstanding work needs an engine step to finish.
Work a live tier-poll thread finishes on its own is excluded, so an engine that only serves peers can go idle.
lookup(key, req_context, *, exclude_tier_idx=None)
¶
Check whether a single chunk is offloaded and ready.
Algorithm
- Process any completed async jobs first.
- Query primary tier — short-circuit on hit or in-flight.
- On primary miss, query secondary tiers — stop on first hit and initiate promotion.
Parameters:
-
(key¶OffloadKey) –Chunk hash to look up.
-
(req_context¶ReqContext) –Per-request context.
-
(exclude_tier_idx¶int | None, default:None) –Skip this tier index during the lookup.
Returns:
-
LookupResult–HIT — chunk is ready in the primary tier.
-
LookupResult–HIT_PENDING — chunk found but not yet readable (write in-flight on the primary tier).
-
LookupResult–RETRY — promotion started or a secondary tier is busy.
-
LookupResult–MISS — chunk not found in any tier, primary is full and cannot accept a promotion, or promotions are held after a cache reset (see reset_cache()).
on_new_request(req_context, *, exclude_tier_idx=None)
¶
Query each secondary tier for its offload policy preference.
Returns REQUEST_LEVEL if ANY secondary tier wants request-level. Record request-level and cascade opt-out decisions separately.
on_schedule_end(context)
¶
End-of-schedule hook: process finished jobs, flush deferred promotions, and reset the per-step gate.
Called once per scheduler step, as the last manager call of the step, from OffloadingConnectorScheduler.build_connector_meta().
poll_tiers()
¶
Advance the control plane of tiers that cannot wait for a step.
Polls those tiers for finished jobs and lets them serve whatever their counterpart has asked for -- the same two steps on_schedule_end() runs, narrowed to the tiers that opted in.
Excludes _flush_pending_promotions() and _flush_pending_cascades() by design: both are per-step batching points, and running them here would fragment batches the scheduler thread accumulated during schedule(). A promotion that a lookup() from this path initiates therefore waits for the next on_schedule_end() to be submitted.
The caller must hold self.lock for the whole call. serve_external_requests() relies on that: it establishes lookup() HITs and then pins them, and the two must not be separated by an eviction.
Serving can look keys up through the parent, and lookup() runs the step's once-per-step poll. From here that poll would reach every tier off-thread, re-enter the serving tier's get_finished_jobs() from inside its own serve, and leave the gate set so the next step skips its poll. The round has just polled its tiers itself, so it holds the gate shut for its duration and then puts it back untouched.
prepare_load(keys, req_context)
¶
Prepare chunks to be loaded from primary tier to GPU.
Callers only pass keys already confirmed HIT by lookup() earlier this step.
This increments ref_cnt on the chunks in the primary tier, protecting them from eviction during the transfer.
Parameters:
-
(keys¶Collection[OffloadKey]) –Chunks to prepare for loading.
-
(req_context¶ReqContext) –Per-request context.
Returns:
-
LoadStoreSpec–LoadStoreSpec for reading from primary tier.
prepare_store(keys, req_context, *, trigger)
¶
Prepare chunks to be stored from GPU to primary tier.
CRITICAL: This method polls for finished jobs FIRST to ensure that any completed async transfers have their ref_cnt decremented before the primary tier makes eviction decisions.
For request-level tiers, chunks already present in the primary tier are immediately cascaded via submit_store().
Parameters:
-
(keys¶Collection[OffloadKey]) –Chunks to prepare for storing.
-
(req_context¶ReqContext) –Per-request context.
-
(trigger¶StoreTrigger) –Why the connector asks for the store.
Returns:
-
PrepareStoreOutput | None–PrepareStoreOutput describing where to store chunks and what was
-
PrepareStoreOutput | None–evicted, or None if store cannot proceed.
reset_cache()
¶
Reset transfer bookkeeping and primary-tier cache.
Called during sleep, weight update, or resume. Each secondary tier drains its in-flight transfers via drain_jobs() so no tier I/O is touching primary memory before the primary tier is reset. A stuck tier will block here visibly — preferable to silent corruption from reusing primary slots while a transfer is mid-copy.
Secondary tiers are intentionally not reset: persistent stores (FS, network) keep their data across resets. Active request state is retained so those requests can continue after the reset; finished requests are finalized and removed.
Promotions are then held until on_reset_flushed(): a worker may still write a freed primary chunk for a job in flight at the reset (a late DMA), so no promotion may fill one meanwhile. lookup() is also reached from serve_external_requests() through each tier's ParentManager, so the hold sits here rather than in the scheduler. While held, a chunk missing from the primary tier is a MISS, so the request recomputes it and a peer is told it is absent; RETRY would instead stall both until the hold is released.
shutdown()
¶
Shut down secondary tiers before releasing primary resources.
Stops the tier-poll thread first: it drives tier transports, and tearing one down underneath it (closing a socket, destroying a ZMQ context) can take the process down rather than raise. If the thread will not exit, hold the manager lock across tier teardown so it cannot be mid-round, and raise if even that is unavailable -- tearing a tier down under a live round risks a crash, and skipping it silently would leak the primary's shared memory region.
Unlike every other manager method, call this WITHOUT holding self.lock: it takes the lock itself, which is not reentrant, and the tier-poll thread needs the lock free to notice the stop request and exit. A caller that does hold it only gets the RuntimeError above, after waiting out the timeout.
Every secondary tier is given a shutdown attempt. If any shutdown fails, preserve the primary mmap because a failed tier may still use it.
_SecondaryTierFacingParent
¶
Bases: ParentManager
Wrapper that implements ParentManager by delegating to the TieringOffloadingManager with exclude_tier_idx set to the origin tier.