This document is relevant for: Trn2, Trn3

On-Device Encoder Cache#

Overview#

The on-device encoder cache stores encoder outputs in a pre-allocated HBM buffer so that a repeated reference to the same item skips the encoder entirely. Embeddings are organized in fixed-size blocks, written by the encoder graph via input-output aliasing, and read by the prefill graph, which is passed a pointer to the whole buffer plus a block-id index tensor and gathers the needed blocks in-graph — no CPU↔device data transfer in either direction.

Background#

Vision-language models (e.g., Qwen3-VL) encode each image/video into a sequence of embedding tokens before the language model’s prefill. Without a cache, the same media would be re-encoded on every request that references it.

The cache read/write paths must handle two forms of dynamism that conflict with Neuron’s static-graph execution model:

  1. Variable-length write path: Each image/video produces a different number of tokens (256 for a 512×512 image, 7680 for a 30-frame video). The encoder output must be sliced into per-item embeddings for individual cache storage and eviction.

  2. Variable-position read path: Each request places cached embeddings at different text-sequence offsets. Before prefill, cached items must be merged into the token embedding sequence at their respective positions.

On GPU, both operations happen eagerly outside the CUDA graph with negligible cost. On Neuron, eager-mode dynamic operations on device are expensive (291–503 ms for 30 512x512 images gather), and running them on CPU instead creates a 354 ms gap from data transfer round-trips. The on-device encoder cache eliminates this gap by keeping all data in HBM and using compile-compatible fixed-size structures.

Architecture#

The diagram below shows the full vision-language data flow and where the encoder cache sits. All heavy data stays on device — only lightweight metadata (block IDs, position maps) crosses the CPU↔device boundary.

PIL Images/Video (variable count, variable resolution)
                │
   CACHE HIT ------- CACHE MISS
       │                 │
       │                 ▼
       │  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
       │    HF Preprocessor (CPU)
       │  │   Resize, patch, normalize → pixel_values                     │
       │      Compute grid_thw per image → tokens_per_image (VARIABLE)
       │  │   Generate mm_hash per item, placeholder token positions      │
       │  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┬─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
       │                                    │ pixel_values + grid_thw
       │                                    ▼
       │  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
       │    Encoder (on device)
       │  │                                                               │
       │      ┌ ─ Shape fixing (CPU) ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐
       │  │     Bucket select: pick smallest bucket ≥ total_tokens        │
       │        Block-packing: pack items into fixed-size blocks
       │  │     Allocate cache blocks: allocate(mm_hash)                  │
       │      └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
       │  │                                                               │
       │      Encoder graph executes (cache buffer as I/O alias)
       │  │        → scatter-writes directly into encoder_cache.buffer    │
       │             at allocated block positions (no CPU copy)
       │  │                                                               │
       │      mark_written(mm_hash) — starts hold-time clock
       │  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
       │                                    │ data in cache buffer (HBM)
       ▼                                    ▼
┌─────────────────────────────────────────────────────────────────────────┐
│ Encoder Cache Buffer (HBM, pre-allocated at startup)                    │
│                                                                         │
│   [num_blocks, block_size, fat_dim]                                     │
│   slot_map: mm_hash → block_ids                                         │
│   On cache hit: skip the encoder entirely, read from buffer             │
│   On eviction: return blocks to free queue (no data movement)           │
└───────────────────────────────────┬─────────────────────────────────────┘
                                    │ buffer pointer + encoder_slot_mapping
                                    │ (one cache slot per batch position)
                                    ▼
┌─────────────────────────────────────────────────────────────────────────┐
│ Prefill (on device)                                                     │
│                                                                         │
│   _gather_mm_embeddings() builds:                                       │
│     buffer (whole) + encoder_slot_mapping = [num_tokens] cache slots    │
│     (like the KV cache slot_mapping; text positions hold num_slots)     │
│                                                                         │
│   Inside prefill graph (merge_multimodal_embeddings):                   │
│     this rank's slots → index_select(flat buffer) → index_put_ hidden   │
│     Sentinel positions write to dummy row (discarded)                   │
│                                                                         │
│   Prefill graph executes → KV cache filled, first token generated       │
└─────────────────────────────────────────────────────────────────────────┘

On cache hit (same mm_hash seen before): the entire HF Preprocessor and Encoder box are skipped — the prefill graph reads directly from the cache buffer (the whole buffer plus a slot mapping is passed in, and the rows are gathered in-graph).

Buffer Layout#

The cache is a pre-allocated contiguous buffer on device with shape [num_blocks, block_size, fat_dim]. Each block holds embeddings from exactly one image / video frame (a frame may span several blocks). The last block is reserved as a scratch block that absorbs padding writes from encoder bucket padding and is never allocated to real items.

buffer: [num_blocks, block_size, fat_dim]

┌──────────────┬──────────────┬──────────────┬───┬──────────────┐
│ block 0      │ block 1      │ block 2      │...│ block N-1    │
│[block_size,D]│[block_size,D]│[block_size,D]│   │ (scratch)    │
└──────────────┴──────────────┴──────────────┴───┴──────────────┘

slot_map (mm_hash → block_ids), with encoder_cache_block_size = 1:
  "img_hash_A" → [0, 1, 2]      (1 image = merged_tokens / block_size blocks)
  "img_hash_B" → [3, 4]         (smaller image = fewer blocks)
  "video_hash" → [5, 6, 7, 8]   (1 video = concatenation of its frames' runs)
  • block_size = encoder_cache_block_size (post-merger tokens per block), an independent config decoupled from the encoder’s attention block size. The model owns the default (SupportsEncoderCacheLayout.get_encoder_cache_block_size): 1 for Qwen3-VL and for Qwen3-ASR. A mapping step at the end of the encoder graph (write_indices) scatters each output row into its cache slot: compute_cache_scatter_indices for vision, compute_audio_cache_scatter_indices for audio. Vision attention still packs multiple items per attention block (the block_size of encoder_graph_shapes); see Block-Packing Attention.

  • fat_dim = out_hidden_size × (1 + num_deepstack_levels). For Qwen3-VL 32B: 5120 × 4 = 20,480.

  • One-frame-per-block-run policy: Each cache block holds embeddings from exactly one image / video frame; an image/frame occupies merged_tokens / encoder_cache_block_size fully-packed blocks (never shared with another frame), and a video spans the concatenation of its frames’ runs. This simplifies eviction (free item = free its blocks), eliminates external fragmentation, and makes cross-request sharing trivial (mm_hash is the sole lookup key).

  • Zero padding waste for vision (divisibility requirement). Each frame’s merged-token count must be divisible by encoder_cache_block_size (checked per request in NeuronPlatform.validate_request, and again in embed_multimodal); blocks are therefore always fully packed. The default of 1 always satisfies this. A larger value that does not divide a frame’s merged-token count fails that request with a clear error.

  • Audio: one chunk per block run. Each 1 s chunk slot owns its own run of chunk_len / encoder_cache_block_size fully packed blocks. The value must divide the chunk length (13 or 1) and the token count of every clip (checked per request in NeuronPlatform.validate_request, and again in allocate_audio_cache_blocks). The default of 1 always satisfies this. A clip’s last chunk is partial unless its length is close to a whole number of seconds, so a value of 13 suits only fixed-length clips.

  • Per-block content tag (mm_hash_tags). A parallel int64[num_blocks] device tensor holds mm_hash_fingerprint(mm_hash) per block, to note which mm_hash a block holds (0 = empty). In EPD the tag is a NIXL-registered region. The consumer compares the pulled tag to the fingerprint it expects; a mismatch is a stale, reused, or wrong block, and the consumer reports a miss. The read order is deliberate. The producer stamps the tag in allocate(), before the encoder writes the embedding. The consumer reads the embedding first, then reads the tag on a second transfer. So a matching tag proves the embedding matches. The tag is unused in the monolithic path. EncoderCacheBlocks also carries a model_id constructor parameter, which the EPD handshake reads to reject a pool serving a different model.

Write Path#

When the scheduler dispatches new multimodal inputs for encoding:

  1. EncoderCacheBlocks.allocate() reserves blocks from the free queue for each mm_item.

  2. The encoder graph executes with the cache buffer as an input-output alias (same pattern as KV cache). It scatter-writes merged embeddings directly into the allocated block positions.

  3. mark_written() records the write timestamp (used by the minimum-hold-time guard).

No device→host transfer occurs. The encoder graph writes directly into the cache buffer.

Read Path#

When prefill needs cached embeddings:

  1. _gather_mm_embeddings() looks up the block IDs and per-block real token counts of each mm_item in the current request.

  2. encoder_cache_item_rows() expands them to the item’s flat buffer rows (block_id * block_size + offset), skipping the pad tail of a partial block. Row k holds the item’s k-th embedding.

  3. The gather keeps only the rows inside the current scheduling window (an image’s overlap span, or a video’s in-window is_embed rows), and writes each into encoder_slot_mapping[batch_position]. encoder_slot_mapping is one int32 tensor of length num_tokens, like the KV cache slot_mapping. A text position holds num_slots (num_blocks * block_size).

  4. The read graph size is num_tokens, so it does not depend on encoder_cache_block_size or on the encoder buckets. The fixed shape is determined per prefill bucket at warmup — variable-position assembly is encoded as data (slots) rather than control flow, satisfying Neuron’s static-graph constraint.

Fail-loud contract. A scheduled, in-window item whose slot is missing or whose stored token count disagrees with the sequence placeholder (check_num_tokens(), backed by a post-gather check that every scheduled encoder position was filled) is never silently skipped. It raises a detectable fault — a hard EncoderCacheReadError in monolithic mode, or a ECLoadFailure on an EPD consumer — instead of leaving placeholders unfilled and running the model as if no image were present.

Merge Inside Compiled Graph#

Inside the prefill graph, merge_multimodal_embeddings() assembles the embeddings:

  1. get_local_encoder_slots_and_positions() takes this SP rank’s local_len slots out of the slot mapping. It gives the slots to gather (local_encoder_slots) and the local positions (local_encoder_embedding_positions). A text position gets position local_len, which the scatter drops.

  2. Flatten the buffer to [num_blocks × block_size, fat_dim] and gather the rows → [local_len, fat_dim].

  3. index_put_ writes the rows into hidden_states at the local positions. Text positions write to a dummy row that is discarded.

On device, an NKI kernel fuses the gather and the scatter in tiles of 128 positions (one indirect DMA per tile). Each SP rank reads only its own positions, so the loop count is ceil(local_len / 128) whatever the cache block size.

Configuration#

The encoder cache is configured through EncoderNeuronConfig in additional_config:

Parameter

Default

Description

encoder_cache_num_blocks

Auto-derived

Cache block count, in blocks of encoder_cache_block_size tokens, including one scratch block. None = derived from the scheduler budget. A set value takes priority on every engine role. A value below the derived count raises an error at startup.

encoder_cache_min_hold_time_ms

Auto (0 or 100)

Minimum time before freed blocks can be reused. 0 for monolithic; 100 ms for EPD (allows remote readers to finish pulling).

encoder_cache_block_size

Model default (None → 1)

Post-merger tokens per cache block, independent of the encoder attention block size (block_size in encoder_graph_shapes). Vision: must divide every image/frame’s merged-token count. Audio: must divide the chunk length and every clip’s token count.

Sizing#

The model converts the scheduler’s encoder_cache_size (embed tokens) to cache blocks with get_encoder_cache_blocks_needed, part of SupportsEncoderCacheLayout:

num_blocks = get_encoder_cache_blocks_needed(encoder_cache_size) + 1   # + 1 scratch block
  vision, audio: ceil(encoder_cache_size / encoder_cache_block_size)

encoder_cache_size = max(max_num_batched_tokens, max_tokens_per_mm_item) is the token budget that the scheduler’s EncoderCacheManager uses to keep and evict items.

A user-set encoder_cache_num_blocks takes priority on every engine role (monolithic, EPD encoder, EPD prefill). Before the scheduler and the runner start, NeuronPlatform._resolve_encoder_cache_size raises encoder_cache_size to the largest budget that encoder_cache_num_blocks - 1 blocks hold (get_encoder_cache_size_for_blocks). The scheduler then keeps as many items as the buffer holds. Use this on an EPD encoder engine, which keeps each item until a remote prefill engine reads it. The runner raises an error if the set value is smaller than the derived count.

Padding#

Each image, video frame and audio clip must have a token count that encoder_cache_block_size divides, so every cache block is full. The token budget and the block budget then agree. The default block size of 1 divides every input. NeuronPlatform.validate_request rejects a request with an item that does not divide the block size. The model step checks it again before it allocates blocks: embed_multimodal for vision, allocate_audio_cache_blocks for audio.

An audio clip of F mel frames (100 per second) has (F // 100) * 13 + tail(F % 100) tokens. The tail is the CNN output of the leftover frames, from 1 to 13 tokens. The processor does not pad audio to whole seconds, so 13 divides the token count only when the leftover is 0 or 97 to 99 frames. For example, a 29.99 s clip has 390 tokens, and a 7.58 s clip has 99 tokens.

Before the block size was decoupled from the encoder attention block size, a small image used a full attention-size block and wasted the remainder. The token-based scheduler did not see that waste.

Key Files#

File

Purpose

vllm_neuron/vllm/worker/encoder_cache_blocks.py

EncoderCacheBlocks class — buffer allocation, free queue, hold-time guard, slot map. create_encoder_cache_blocks() — sizes and creates the cache for the V1 and the V2 model runners

vllm_neuron/functional/merge_multimodal_embeddings.py

merge_multimodal_embeddings() — scatter encoder embeddings into hidden_states inside compiled graph (shared by vision + audio)

vllm_neuron/model/qwen3_vl/utils/vision_block_packing.py

compute_cache_scatter_indices() — maps merged VE rows → encoder cache slots (write_indices)

vllm_neuron/utils/mm_utils.py

get_encoder_cache_block_size() — dispatches to the model’s SupportsEncoderCacheLayout; shared by the platform and the runner

vllm_neuron/model/qwen3_asr/utils/audio_preprocessing.py

allocate_audio_cache_blocks(), compute_audio_cache_scatter_indices() — per-chunk allocation and write_indices for audio

vllm_neuron/model/qwen3_vl/model_common.py

embed_multimodal() — per-frame allocation + divisibility assert + write_indices build

vllm_neuron/vllm/worker/neuron_model_runner.py

_init_encoder_cache() (calls create_encoder_cache_blocks(); the V2 runner calls it from v2/mm/encoder_cache.py::build_encoder_cache()), _execute_mm_encoder(), _gather_mm_embeddings(), encoder_cache_item_rows() — orchestrates write/read paths, builds encoder_slot_mapping

vllm_neuron/vllm/worker/neuron_worker.py

_get_encoder_cache_bytes(), _compute_kv_budget() — subtracts the encoder cache buffer from the KV HBM budget

vllm_neuron/model/neuron_config.py

EncoderNeuronConfig — encoder_cache_num_blocks, encoder_cache_min_hold_time_ms, encoder_cache_block_size

This document is relevant for: Trn2, Trn3