Skip to content

vllm.v1.kv_offload.base

Core abstractions for KV cache offloading in vLLM v1.

Classes:

  • BlockIDsLoadStoreSpec –

    Spec for loading/storing KV blocks from given block numbers.

  • CanonicalKVCacheRef –

    Per-layer (or group of layers) reference to a specific (by index)

  • CanonicalKVCacheTensor –

    A canonicalized KV cache tensor whose first dimension is num_blocks.

  • CanonicalKVCaches –

    Canonicalized block-level representation of the KV caches.

  • CanonicalPageMapping –

    How this worker's page maps into a canonical (parallelism-free) page.

  • ConfigInfo –

    Static facts that one component publishes on vllm:kv_offload_config_info.

  • CopyRun –

    A strided byte correspondence between this worker's physical page and

  • DevicePointers –

    Pre-resolved device pointers for a transfer.

  • GPULoadStoreSpec –

    Spec for loading/storing a KV block to GPU memory.

  • IOCompletion –

    Completion handle for an async I/O operation.

  • LoadStoreSpec –

    Metadata that encapsulates information allowing a worker

  • Locality –

    Locality of a tier's storage relative to the publishing instance.

  • LookupResult –

    Result of OffloadingManager.lookup().

  • Medium –

    Storage medium of an offloading tier.

  • OffloadingManager –
  • OffloadingSpec –

    Spec for an offloading connector

  • OffloadingWorker –

    Runs in the worker process. Performs async KV transfers for ONE

  • ReqContext –

    Per-request offloading state with optional token counts.

  • ScheduleEndContext –

    Per-step scheduling info passed to on_schedule_end().

  • StoreTrigger –

    Why the connector asks the manager to store the keys.

  • TierFilter –

    Per-request filter controlling which tiers participate.

Functions:

BlockIDsLoadStoreSpec

Bases: LoadStoreSpec, ABC

Spec for loading/storing KV blocks from given block numbers.

Subclass semantics differ: GPULoadStoreSpec.block_ids are GPU block indices; CPULoadStoreSpec.block_ids are CPU cache chunk indices.

CanonicalKVCacheRef dataclass

Per-layer (or group of layers) reference to a specific (by index) CanonicalKVCacheTensor and records the un-padded page size used by that layer.

CanonicalKVCacheTensor dataclass

A canonicalized KV cache tensor whose first dimension is num_blocks.

For attention backends where the raw tensor has num_blocks at a non-leading physical dimension (e.g. FlashAttention's (2, num_blocks, ...) layout), the tensor is split so that each resulting CanonicalKVCacheTensor starts with (num_blocks, ...).

CanonicalKVCaches dataclass

Canonicalized block-level representation of the KV caches.

Composed of
  • Unique list of KV cache data tensors, each with shape (num_blocks, page_size_in_bytes) and int8 dtype.
  • Per-group data references of the tensors. i.e. how each KV cache group maps to the tensors.

CanonicalPageMapping dataclass

How this worker's page maps into a canonical (parallelism-free) page. In-process only, never serialized. Runs cover the full local page in both directions; ranks holding identical bytes take turns writing them.

Methods:

  • is_writer –

    Whether this worker stores the canonical page of the given block.

is_writer(block_id)

Whether this worker stores the canonical page of the given block. Rotating by block spreads writes across ranks holding identical bytes.

ConfigInfo dataclass

Static facts that one component publishes on vllm:kv_offload_config_info.

Each field is one label. The OffloadingSpec declares the names with config_info_keys(), and the OffloadingManager fills the values with as_config_info(). A declared name that the manager does not fill reads empty, and an undeclared name is dropped. The values must stay fixed for the process lifetime. Document each field in docs/features/kv_offloading_usage.md. See CPUOffloadingInfo for an example.

Methods:

  • as_config_info –

    Return the label values. A None value becomes "None", not empty.

  • config_info_keys –

    Return one label name for each field, in field order.

as_config_info()

Return the label values. A None value becomes "None", not empty.

config_info_keys() classmethod

Return one label name for each field, in field order.

CopyRun dataclass

A strided byte correspondence between this worker's physical page and a canonical page: for i in range(num_fragments), fragment i spans [local_offset + i * local_stride, +fragment_size) in the worker's page and [canonical_offset + i * canonical_stride, +fragment_size) canonically.

DevicePointers dataclass

Pre-resolved device pointers for a transfer.

Flat arrays in canonical order

for each group: for each data_ref in group: for each block in group: ptrs[i], sizes[i]

GPULoadStoreSpec

Bases: BlockIDsLoadStoreSpec

Spec for loading/storing a KV block to GPU memory.

If there are multiple KV groups, the blocks are expected to be ordered by the group index. In that case, group_sizes[i] determines the number of blocks per the i-th KV group, and thus sum(group_sizes) == len(block_ids). group_sizes=None indicates a single KV group.

If block_indices is given, each group (determined by group_sizes) of block IDs will correspond to logically contiguous blocks, e.g. blocks 5-10 of a some request. block_indices[i] will represent the block index of the first block in group #i. Thus, len(block_indices) == len(group_sizes) = number of KV cache groups. This information is required in order to support off/loading from offloaded blocks which are larger than GPU blocks. In such cases, the first GPU block per each group may be unaligned to the offloaded block size, and so knowing block_indices[i] allows the worker to correctly skip part of the first matching offloaded block.

IOCompletion

Bases: Protocol

Completion handle for an async I/O operation.

concurrent.futures.Future satisfies this unchanged. Stream-ordered backends can implement this with a CUDA event, avoiding a thread.

LoadStoreSpec

Metadata that encapsulates information allowing a worker to load, and optionally also to store, blocks of KV data.

Locality

Bases: Enum

Locality of a tier's storage relative to the publishing instance.

LookupResult

Bases: Enum

Result of OffloadingManager.lookup().

Medium

Bases: Enum

Storage medium of an offloading tier.

OffloadingManager

Bases: ABC

Methods:

  • complete_load –

    Marks previous blocks that were prepared to load as done loading.

  • complete_store –

    Marks blocks which were previously prepared to be stored, as stored.

  • config_info –

    Return the info metric labels, one mapping for each series.

  • get_load_source –

    Return the cache tier that supplied a successful lookup.

  • get_stats –

    Return collected metrics since last call, or None if disabled.

  • has_pending_work –

    Whether this manager needs the engine to keep stepping.

  • lookup –

    Checks whether a single block is offloaded and ready to be read.

  • on_new_request –

    Called when a new request is first seen by the scheduler.

  • on_request_finished –

    Called when a request has finished.

  • on_reset_flushed –

    Called once workers have reported every job in flight at the last

  • on_schedule_end –

    Called once at the end of each scheduler step.

  • prepare_load –

    Prepare the given blocks to be read.

  • prepare_store –

    Prepare the given blocks to be offloaded.

  • reset_cache –

    Evict all tracked blocks and reset internal state.

  • shutdown –

    Shutdown the manager and release any resources.

  • take_events –

    Take the offloading events from the manager.

Attributes:

lock property

Context manager granting exclusive access to this manager's state.

Scope is the manager, every tier it composes, and any front-end state those tiers own (e.g. a tier's async lookup front end). Every caller of an OffloadingManager method, except shutdown(), must hold it. Manager methods never enter it themselves, so a caller may hold it across an arbitrary sequence of operations -- which is required wherever one call establishes a fact a later call relies on, such as a lookup() HIT followed by the prepare_load() that pins it.

The default is a no-op, for managers that are only ever entered from one thread. A manager that may be entered from another thread -- its own background thread, say -- returns a real lock instead. Callers must not assume either: always enter it, and never re-enter it while held, since a real lock need not be reentrant.

complete_load(keys, req_context)

Marks previous blocks that were prepared to load as done loading.

Parameters:

  • keys

    (Collection[OffloadKey]) –

    the keys identifying the blocks.

  • req_context

    (ReqContext) –

    per-request context (e.g. kv_transfer_params).

complete_store(keys, req_context, *, trigger, success=True)

Marks blocks which were previously prepared to be stored, as stored. Following this call, the blocks become loadable. If success is False, blocks that were not marked as stored will be removed.

Parameters:

  • keys

    (Collection[OffloadKey]) –

    the keys identifying the blocks.

  • req_context

    (ReqContext) –

    per-request context (e.g. kv_transfer_params).

  • trigger

    (StoreTrigger) –

    the trigger given to the matching prepare_store.

  • success

    (bool, default: True ) –

    whether the blocks were stored successfully.

config_info()

Return the info metric labels, one mapping for each series.

The scheduler reads this once. See ConfigInfo.

get_load_source(key, req_context)

Return the cache tier that supplied a successful lookup.

This is queried only after lookup resolves to HIT. Composing managers can override it to retain the origin across asynchronous promotion into a primary tier. The default keeps out-of-tree managers compatible while making unknown provenance explicit.

get_stats()

Return collected metrics since last call, or None if disabled.

has_pending_work()

Whether this manager 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.

lookup(key, req_context) abstractmethod

Checks whether a single block is offloaded and ready to be read.

Parameters:

  • key

    (OffloadKey) –

    the key identifying the block to lookup.

  • req_context

    (ReqContext) –

    per-request context (e.g. kv_transfer_params).

Returns:

  • LookupResult –

    HIT if the block is offloaded and ready, MISS if not found,

  • LookupResult –

    HIT_PENDING if found but not yet readable, or RETRY if the

  • LookupResult –

    lookup should be retried later.

on_new_request(req_context) abstractmethod

Called when a new request is first seen by the scheduler.

Returns a RequestOffloadingContext indicating how this request's blocks should be offloaded.

Parameters:

on_request_finished(req_context)

Called when a request has finished.

By the time this is called, the scheduler will issue no more submit-side calls for this request, such as prepare_store() and prepare_load(). Completion callbacks for already-submitted transfers (complete_store() and complete_load()) may still arrive afterward.

This hook does NOT imply the data has been persisted. Asynchronous transfers already submitted for this request may still be in flight. Managers that cascade to lower tiers should delay those tiers' on_request_finished() calls until no more lower-tier submit calls can be issued for this request.

Parameters:

on_reset_flushed()

Called once workers have reported every job in flight at the last reset_cache(); blocks it freed are no longer written by them.

on_schedule_end(context)

Called once at the end of each scheduler step.

This is the last manager call of a step: every lookup(), prepare_load(), prepare_store() and on_request_finished() for the step has already been issued.

Managers may override this to flush deferred work accumulated during the step (e.g., batched promotions).

prepare_load(keys, req_context) abstractmethod

Prepare the given blocks to be read. The given blocks will be protected from eviction until complete_load is called. It assumes all given blocks are offloaded.

Parameters:

  • keys

    (Collection[OffloadKey]) –

    the keys identifying the blocks.

  • req_context

    (ReqContext) –

    per-request context (e.g. kv_transfer_params).

Returns:

  • LoadStoreSpec –

    A LoadStoreSpec that can be used by a worker to locate and load

  • LoadStoreSpec –

    the actual offloaded KV data.

prepare_store(keys, req_context, *, trigger) abstractmethod

Prepare the given blocks to be offloaded. The given blocks will be protected from eviction until complete_store is called.

Parameters:

  • keys

    (Collection[OffloadKey]) –

    the keys identifying the blocks.

  • req_context

    (ReqContext) –

    per-request context (e.g. kv_transfer_params).

  • trigger

    (StoreTrigger) –

    why the connector asks for the store.

Returns:

  • PrepareStoreOutput | None –

    A PrepareStoreOutput indicating which blocks need storing,

  • PrepareStoreOutput | None –

    where to store them (LoadStoreSpec), and list of blocks that

  • PrepareStoreOutput | None –

    were evicted as a result. A manager short on room may store

  • PrepareStoreOutput | None –

    only some of the keys and report the rest in keys_to_retry,

  • PrepareStoreOutput | None –

    under the constraints documented on that field.

  • PrepareStoreOutput | None –

    None is returned if the blocks cannot be stored.

reset_cache()

Evict all tracked blocks and reset internal state.

shutdown()

Shutdown the manager and release any resources.

The one exception to the rule that callers hold lock: call this without it. A manager with a background thread stops that thread here and may need the lock to do so.

take_events()

Take the offloading events from the manager.

A tier manager emits only events for storage state it owns. A composing manager may aggregate child event streams, but should not synthesize events on behalf of a child tier.

Yields:

  • Iterable[OffloadingEvent] –

    New OffloadingEvents collected since the last call.

OffloadingSpec

Bases: ABC

Spec for an offloading connector

Methods:

  • build_metric_definitions –

    Return Prometheus metric definitions emitted by this spec.

  • config_info_keys –

    Return the info metric label names that the manager fills.

  • get_manager –

    Get an OffloadingManager that will be used

  • get_worker –

    Get an OffloadingWorker that handles async KV transfers for this spec.

build_metric_definitions(extra_config) classmethod

Return Prometheus metric definitions emitted by this spec.

config_info_keys(extra_config) classmethod

Return the info metric label names that the manager fills.

See ConfigInfo.

Parameters:

  • extra_config

    (dict[str, Any]) –

    kv_connector_extra_config of this instance.

get_manager() abstractmethod

Get an OffloadingManager that will be used by the scheduler-side offloading connector to track offloaded blocks and manage evictions.

get_worker(kv_caches) abstractmethod

Get an OffloadingWorker that handles async KV transfers for this spec.

Parameters:

Returns:

OffloadingWorker

Bases: ABC

Runs in the worker process. Performs async KV transfers for ONE offloaded medium (e.g. CPU). Direction is explicit via submit_store / submit_load, so there is no (src_medium, dst_medium) routing.

Methods:

is_ready()

Whether this worker can take transfers.

start_deferred_setup()

Start setup deferred by async_init.

No transfers are submitted until is_ready().

submit_load(job_id, src_spec, device_ptrs, expedited=False) abstractmethod

Async offloaded medium -> device.

An expedited load is waited on within the step, so it should not queue behind regular loads. Submission itself must still not block.

submit_store(job_id, device_ptrs, dst_spec) abstractmethod

Async device -> offloaded medium.

ReqContext dataclass

Per-request offloading state with optional token counts.

Counts are live until the scheduler finishes the request, then frozen.

Attributes:

num_computed_tokens property

Scheduler's computed token count, including in-flight work.

num_in_flight_tokens property

Scheduled tokens whose output has not yet been processed.

num_prompt_tokens property

Number of prompt tokens.

num_tokens property

Number of prompt and output tokens, excluding speculative tokens.

ScheduleEndContext

Bases: NamedTuple

Per-step scheduling info passed to on_schedule_end().

StoreTrigger

Bases: Enum

Why the connector asks the manager to store the keys.

TierFilter dataclass

Per-request filter controlling which tiers participate.

get_offload_block_hash(key)

Extract the block hash from an OffloadKey.

get_offload_group_idx(key)

Extract the group index from an OffloadKey.

make_offload_key(block_hash, group_idx)

Pack a block hash and group index into an OffloadKey.