This document is relevant for: Trn2, Trn3

CPU KV offloading design#

This document describes how vLLM Neuron runs vLLM’s OffloadingConnector, which adds a host-memory tier to the prefix cache. It covers the KV cache registration, the host tier, the two copy modes, and how copies are ordered against device executions. Some experience with the vLLM KV connector framework and with async scheduling is required to understand it in full.

What you should know before reading#

Before you start, you must be familiar with the following:

Overview#

vLLM’s OffloadingConnector stores full KV blocks from HBM to host memory. On a prefix hit that HBM no longer holds, it loads the blocks back instead of computing them again. This is the engine side of a tiered prefix cache, such as the llm-d tiered prefix cache.

          scheduler process                          each worker process (one per rank)
+------------------------------------+      +-----------------------------------------------+
| NeuronOffloadingConnector          |      | NeuronOffloadingConnectorWorker               |
|   (scheduler role)                 |      |   registration: K and V slab of each layer    |
|   upstream scheduler and           | meta |   drain decision before each copy             |
|   CPUOffloadingManager (LRU)       | ---> |                                               |
|   hit cap, deferred lookups,       |      | NeuronCPUOffloadingWorker                     |
|   failed stores and loads          | <--- |   sync: Tensor.copy_ on the step thread       |
|                                    | out  |   async: transfer ops on its own thread       |
+------------------------------------+      |   host tier: (num_chunks, page) per region    |
                                            +-----------------------------------------------+
                                                 ^ load (H2D)               | store (D2H)
                                                 |                          v
                                            +-----------------------------------------------+
                                            | HBM KV cache: (2, num_blocks, ...) per layer  |
                                            +-----------------------------------------------+
  • The scheduler side decides what to store and what to load. It is upstream code, with Neuron changes to the hit cap, to failed jobs and to deferred lookups.

  • Each worker copies the blocks of its own shard. A rank holds 1 / world_size of the host tier.

  • The platform resolves the configuration once, before the engines start. Every process then reads the same values.

A request goes through these steps:

  1. The scheduler looks up the request’s prefix in HBM, then in the host tier (get_num_new_matched_tokens).

  2. On a host hit, the scheduler allocates device blocks and queues a load job. The request waits in WAITING_FOR_REMOTE_KVS until the load is reported finished.

  3. The request then computes only the tokens after the hit.

  4. When a block of the request is full, the scheduler queues a store job. The worker copies the block to the host tier. The manager marks the block ready when the store finishes.

Why the upstream connector does not run on Neuron#

The upstream connector fails on Neuron for two reasons:

  1. OffloadingConnectorWorker.register_kv_caches makes one region of each layer, and asserts that its leading dimension is num_blocks. Neuron registers one (2, num_blocks, num_kv_heads, block_size, head_size) tensor for each layer, so the assert fails.

  2. CPUOffloadingSpec.get_worker refuses a platform that is not CUDA-like or XPU. Its worker also needs CUDA streams, swap_blocks_batch and cudaHostRegister.

vLLM Neuron keeps the upstream scheduler side and the upstream manager. It replaces three parts:

  • the registration of the KV cache, because the Neuron cache layout is different;

  • the copy worker, because the upstream worker needs CUDA;

  • the ordering of copies against device executions, because the Neuron runtime allows one waiter for each in-flight execution.

Upstream component

Location

Neuron replacement

OffloadingConnector

vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py

NeuronOffloadingConnector

OffloadingConnectorScheduler

.../offloading/scheduler.py

Kept

OffloadingConnectorWorker

.../offloading/worker.py

NeuronOffloadingConnectorWorker

CPUOffloadingSpec

vllm/v1/kv_offload/cpu/spec.py

NeuronCPUOffloadingSpec

CPUOffloadingManager

vllm/v1/kv_offload/cpu/manager.py

Kept

CUDA copy worker

vllm/v1/kv_offload/cpu/

NeuronCPUOffloadingWorker

Configuration resolution#

NeuronPlatform.check_and_update_config resolves the configuration in the process that starts the engines:

  • --kv-offloading-size is resolved before the model runner decision. Upstream resolves it after this method, so neither the redirect nor the runner decision would see it. The platform builds the KVTransferConfig itself, with kv_load_failure_policy="recompute".

  • OffloadingConnector is redirected to NeuronOffloadingConnector, at the top level and in each child of a MultiConnector. spec_name becomes NeuronCPUOffloadingSpec, unless the user names another spec. A module path that the user set names the upstream module, so the redirect replaces it with the Neuron module path.

  • The copy mode is resolved once (see Copy modes). The result is written to xfer_mode in the extra config of the connector. Each node resolves auto on its own, so the ranks compare their settings later (see Rank agreement).

  • A kv_load_failure_policy that the user sets is kept. With fail, the platform logs a warning that a failed CPU load then fails its request.

  • The data-parallel engines of a host are checked together (see Host memory checks). With several API servers, only the launcher runs this check.

  • The DCP check runs after the redirect. CPU offloading does not support decode-context parallelism, so a DCP server refuses it.

KV cache registration#

NeuronOffloadingConnectorWorker.register_kv_caches turns each layer into two regions, a K slab and a V slab. A region is an int8 (num_blocks, page) view of the storage of the layer. Its block stride is half the page of the layer. The worker then copies blocks by byte ranges, so the KV dtype and the packed-FP8 K layout do not matter.

  • Only the KV cache groups that upstream offloads are registered (get_offloading_group_ids).

  • Layers whose slabs alias the same bytes share one region.

  • The registration refuses a layer that is not an attention layer, or that has a padded page. It also refuses a tensor whose leading dimension is not 2, and a slab that is not contiguous.

Host tier and budget#

cpu_bytes_to_use is all the host memory of the connector on the ranks of one engine. It includes the host tier and the staging memory of each rank. NeuronCPUOffloadingSpec subtracts the staging of every rank before it sizes num_chunks. The scheduler and every worker build the spec from the same configuration, so they get the same num_chunks. Each data-parallel engine takes its own budget.

Mode

Host tier

Staging per rank

sync

Anonymous mapping, MADV_NOHUGEPAGE, populated after warmup (MADV_POPULATE_WRITE)

8 MiB copy buffer (staging_buffer_bytes)

async

Anonymous mapping, MADV_NOHUGEPAGE, page-locked after warmup (mlock)

512 MiB arena (async_staging_bytes), page-locked at the init

In both modes, the host tier is not resident during the compile:

  • Every worker runs with deterministic algorithms on, and torch.empty then fills its memory. An anonymous mapping (_empty_unfilled) avoids that fill.

  • After warmup, NeuronWorker.compile_or_warm_up_model commits the tier. Sync mode populates it with madvise(MADV_POPULATE_WRITE). Async mode locks it with mlock, which also faults every page in. The compile peak and the tier are then never needed at the same time. This matters most for the async tier, because the kernel cannot reclaim locked pages.

  • A host that cannot hold the tier fails at startup, not when the tier fills.

  • The mapping stays in 4 KiB pages. A huge-page fault can stall on direct compaction under THP defrag=madvise.

  • The ranks commit in parallel. In a test on a Trn3 instance, each of 8 ranks committed a 23.99 GiB sync tier in 6.1 s.

Host memory checks#

Four checks refuse a budget that the host cannot back:

  1. At the config. The platform compares data_parallel_size_local × cpu_bytes_to_use with the available memory of the host. Each engine of a dense model starts as an independent DP=1 engine, so only this check sees all the engines of a host. With several API servers, each one builds its own config while the engines already take memory, so only the launcher runs this check.

  2. At the registration. Every rank reads the available memory of its host before any rank allocates. All ranks check the same per-host table. In async mode the check also covers RLIMIT_MEMLOCK, for the tier and the arena of a rank.

  3. After warmup, in both modes. Every rank reads its available memory again before it commits its tier. A commit past the cgroup limit is OOM-killed, not failed, so this check comes first.

  4. At the commit, with a reservation. The checks above count the ranks of one server. Each rank also reserves the memory that it is about to commit, so that other servers on the host count it (see Host memory reservations).

The available memory is the lower of the cgroup headroom and MemAvailable. The cgroup headroom is the memory limit less the memory in use. The memory in use does not include the inactive page cache (inactive_file, or total_inactive_file on cgroup v1), for example of the checkpoint and NEFF files. The kernel reclaims that cache before it OOM-kills, and kubelet’s working set does not count it either.

Each check refuses memory above host_memory_safety_fraction (default 0.8) of the available memory. A fraction of 0 turns the checks and the reservations off, except the lock-limit check.

Rank agreement#

At the registration, before the host memory check, every rank compares three settings with the other ranks in one gather: xfer_mode, the number of host blocks (num_chunks) and host_memory_safety_fraction. All ranks refuse to start when one rank differs.

Each node resolves auto on its own. Two nodes with different lock limits can therefore pick different modes. Ranks in different modes would wait on each other in the host memory gathers, which depend on the mode, until a timeout. Their host tiers would also differ from the block count that the scheduler hands out.

Host memory reservations#

Two servers on one host can start together. An example is the prefill server and the decode server of a single-node disaggregated deployment. Each server can pass its checks before the other commits its tier, and then together they use more memory than the host has. A reservation closes this gap:

  1. The rank takes a host lock: fcntl.flock on a file in /dev/shm/vllm_neuron_cpu_offload.

  2. Under the lock, it reads the available memory, and it subtracts the reservations of other processes.

  3. If its tier fits in host_memory_safety_fraction of what is left, it writes its own reservation. If not, it refuses to start.

  4. It releases the lock, and it commits its tier without the lock.

  5. After the commit, it removes its reservation. The committed memory is then no longer available, so the next check sees it.

Mode

When the rank reserves

What it reserves

sync

During the populate after warmup

The host tier of the rank

async

During the worker init, while the arena is locked

The arena of the rank

async

During the lock after warmup

The host tier of the rank

A reservation does not stay after its process:

  • A reservation of a process that is gone is dropped. In its own PID namespace, a rank compares the PID and the start time of the process.

  • A reservation from another PID namespace is dropped 30 minutes after it was made. A rank commits about 4 GiB/s (23.99 GiB in 6.1 s in the test above), so 30 minutes covers a tier of several TiB.

  • The file name holds the PID namespace and the PID. Ranks of two containers can have the same PID, and they do not overwrite each other’s reservation.

Servers see each other only when they share /dev/shm and run as the same user. The ranks of one container or pod always do. Servers in different containers do so only when the containers share /dev/shm, for example with --ipc=host. Without a usable directory, a rank makes no reservation, and the other checks still run.

Copy modes#

sync

async

API

Tensor.copy_

libtorch-neuronx-lite async_tensor_transfer_* (nrta)

Thread

Engine step thread

A transfer thread on each worker

Blocks the step

Yes, for the copy

No, except a flush

Waits on the device

Yes, through the drain

No

Needs

Nothing

Async scheduling, no speculative decoding, PP = 1, mp, ray or external_launcher executor, the transfer ops, a lock limit that covers the rank’s share of cpu_bytes_to_use and its arena

The user sets the mode in xfer_mode in kv_connector_extra_config. The default is auto. The platform picks async when every condition in the table holds, and sync otherwise. It logs the mode and the reason. An explicit sync or async is kept. The connector refuses an explicit async at startup without async scheduling or with speculative decoding. It also refuses one on another multi-rank executor, or under a low lock limit.

The user-facing name is async, not the name of the API. A later implementation of the async mode can then use another API, and user configurations do not change. The code still names the current implementation nrta (for example _NrtaJob and the nrta-xfer thread).

Sync mode#

A copy moves each run of blocks that are consecutive on the device in one Tensor.copy_ call, through the staging buffer. The bandwidth of a copy depends on its size: about 0.6 GiB/s for one 8 KiB block, and about 12.5 GiB/s for 4 MiB.

Async mode#

The worker queues each job, and its transfer thread submits the job and reaps it. The library merges blocks that are consecutive on both the device and the host into one DMA. The worker sorts the block pairs of a job by device block, because vLLM frees the blocks of a request in reverse order.

Sometimes a device run of at least 4 blocks has host blocks that are not consecutive. That run goes through the staging arena, so it is one DMA for each region.

The library has no thread of its own. It moves DMAs forward only inside a transfer op call. So while a job is in flight, the transfer thread waits in finish on its oldest transfer, for at most 2 ms at a time.

Ordering against device executions#

Each output tensor of one graph execution, the sampled tokens and the KV alike, carries the same completion future. This has two effects:

  • A device-to-host copy_ of KV waits on that future, so a store never reads KV that a graph has not finished writing.

  • A host-to-device copy_ does not wait. A load must first wait for every execution that can still write its destination blocks.

The Neuron runtime keeps one waiter for each in-flight execution. Each waiter registers its own eventfd, and the runtime keeps only the last one. With async scheduling, the output thread of the executor already waits on the in-flight step. An eager copy on the step thread that waits on the same execution would hang one of the two threads.

Sync mode: the drain#

On each step that copies, the runner first reads the in-flight step’s async output back on the step thread. It uses that output’s own lock, so the output thread then reuses the result. No execution is in flight when the copies start.

Some loads start after the step’s graph was submitted (MRv2 starts them in post_forward). They also wait for that graph. The output thread does not wait on it yet, so the load is its only waiter. A copy that needs the drain raises when async scheduling is on and the runner registered no drain.

Async mode: the readback gate#

A job is held until every graph that was submitted before the job was queued is known to be complete (READBACK_GATE). The runner counts each graph submit. A readback of an async output proves that every graph submitted before that output was created has finished. So the async mode needs async scheduling. It also needs no speculative decoding, because the gate does not count the draft graph.

KV writes during a load#

A load can land while later graphs run. Those graphs do not read the blocks of the load, because the request waits for them. They also do not write them, if every KV write touches only its own slots.

A graph that copies a whole KV layer out and writes it back would overwrite such a load. The packed-FP8 prefill K write therefore writes only its own [d_head, 2] pairs (scatter_packed_k). A packed-FP8 decode bucket on the un-swizzled fallback kernel still rewrites the whole K layer. A load that lands during that graph is lost.

An idle data-parallel rank runs a dummy batch when a peer is busy. In both runners, every KV write of that dummy goes to the reserved null block. So the dummy does not overwrite a block that a load fills.

Scheduler integration#

  • Hit cap. A host hit stops at the last block boundary below the last token of the prompt. Segmented prefill needs a block-aligned prior, as for the HBM prefix cache.

  • Finished loads. A request whose load finished schedules prompt tokens, so NeuronScheduler counts it as a waiting prefill. It never joins a decode batch.

  • Deferred lookups. The upstream lookup defers while a chunk that it needs is being loaded or stored. Until a job finishes, the next lookup defers again. So a deferred request forces a prefill step only after a job has finished since its last lookup (lookup_deferred).

Failure handling#

The worker reports a failed job only when none of its DMAs can still write. This is true when the job failed before it issued a DMA, or when every DMA that it issued has ended. The exception is an async load whose completion cannot be observed (the last row of the table). Under kv_load_failure_policy=recompute, vLLM computes the tokens of a failed load instead:

Case

Reported as

What vLLM computes

One KV cache group

Load errors (the failed blocks)

Only the failed blocks

Several KV cache groups

Failed receive

The request from its start

Async load whose completion cannot be observed

Failed receive, and its device blocks are quarantined

The request from its start, in other blocks

  • The next lookup of the request takes no host hit. The retry then computes its tokens, and does not load the same chunks again.

  • A quarantined block keeps a reference for the life of the engine. A DMA that may still write the block then cannot reach another request.

  • The host blocks of a failed store are dropped. A running request stores them again.

  • An async store whose completion cannot be observed stops the worker, because its DMAs write host-tier blocks.

  • A flush that sees no job finish for async_flush_timeout_s (default 10 s) gives up on its jobs. A load is given up when it is not finished async_load_timeout_s (30 s) after it was queued, and a store after async_store_timeout_s (60 s).

  • Failed loads and stores are counted once for each job: vllm:kv_offload_load_failures and vllm:kv_offload_store_failures.

Model runner integration#

Both runners (MRv1 and MRv2) do the same three things:

  • register their async-output drain with the connector, after the connector is created (register_async_output_drain). Each KV cache init path does it, for example both the pooled and the stacked cache of MRv2;

  • count each graph submit for the readback gate (note_graph_submit);

  • report each async output that they create and read back.

The MRv2 policy keeps native CPU offloading on MRv2. LMCache and SimpleCPUOffloadConnector stay on MRv1 and upstream code.

Debug checks#

Two options of kv_connector_extra_config check the copies. Both are for test servers, and both can be on together.

"verify": true reads every copied block back from HBM, once the job has landed. It compares the block byte for byte with its host block. The worker logs the totals as offload verify: device=... totals ..., and a block that differs as offload verify mismatch. A job is reported finished only after its check. The check is slow, and in async mode it drains the in-flight output on every step.

"verify_host_hash": true reads host memory only:

  • When a store completes, the worker records a CRC-32 of each host block that the store wrote.

  • When a load completes, the worker compares each host block that the load read with that record.

  • The worker logs the totals as offload host hash: device=... totals stored=... checked=... (... differ, ... missing). It logs offload host hash mismatch for a block that changed after its store, or that no store wrote.

This check reads no device block and drains nothing, so in async mode the copies keep the order and the timing of production. It does not show a copy that moved the wrong device block. verify shows that.

Limitations#

  • Decode-context parallelism (DCP) is not supported.

  • A chunk is one KV block (blocks_per_chunk is 1).

  • canonical_layout is not supported.

  • Only attention layers with a K/V pair and an unpadded page are registered.

  • The async mode needs PP = 1 and no speculative decoding. auto uses sync for those.

  • In sync mode, every step that copies drains the in-flight output.

  • Servers that do not share /dev/shm do not see each other’s reservations.

  • With the async mode, a packed-FP8 decode graph on the un-swizzled fallback loses a load that lands while it runs.

Source files#

File

Contents

vllm_neuron/vllm/kv_connector/neuron_offloading_connector.py

Connector, spec, workers, readback gate, host memory checks and reservations, rank agreement, debug checks

vllm_neuron/vllm/platform.py

Redirect, --kv-offloading-size, copy mode, policy warning, DP and DCP checks

vllm_neuron/vllm/worker/neuron_worker.py

Host tier commit after warmup

vllm_neuron/vllm/worker/neuron_model_runner.py

MRv1 drain, graph count and DP dummy batch

vllm_neuron/vllm/worker/neuron_model_runner_v2.py

MRv2 drain and graph count

vllm_neuron/vllm/core/scheduler.py

Finished loads and deferred lookups

vllm_neuron/vllm/model_runner_v2_policy.py

Runner selection with offloading

Further reading#

This document is relevant for: Trn2, Trn3