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:
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.
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):1for 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_indicesfor vision,compute_audio_cache_scatter_indicesfor audio. Vision attention still packs multiple items per attention block (theblock_sizeofencoder_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_sizefully-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 inNeuronPlatform.validate_request, and again inembed_multimodal); blocks are therefore always fully packed. The default of1always 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_sizefully packed blocks. The value must divide the chunk length (13 or 1) and the token count of every clip (checked per request inNeuronPlatform.validate_request, and again inallocate_audio_cache_blocks). The default of1always 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 parallelint64[num_blocks]device tensor holdsmm_hash_fingerprint(mm_hash)per block, to note whichmm_hasha 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 inallocate(), 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.EncoderCacheBlocksalso carries amodel_idconstructor 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:
EncoderCacheBlocks.allocate()reserves blocks from the free queue for each mm_item.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.
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:
_gather_mm_embeddings()looks up the block IDs and per-block real token counts of each mm_item in the current request.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. Rowkholds the item’sk-th embedding.The gather keeps only the rows inside the current scheduling window (an image’s overlap span, or a video’s in-window
is_embedrows), and writes each intoencoder_slot_mapping[batch_position].encoder_slot_mappingis one int32 tensor of lengthnum_tokens, like the KV cacheslot_mapping. A text position holdsnum_slots(num_blocks * block_size).The read graph size is
num_tokens, so it does not depend onencoder_cache_block_sizeor 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:
get_local_encoder_slots_and_positions()takes this SP rank’slocal_lenslots 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 positionlocal_len, which the scatter drops.Flatten the buffer to
[num_blocks × block_size, fat_dim]and gather the rows →[local_len, fat_dim].index_put_writes the rows intohidden_statesat 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 |
|---|---|---|
|
Auto-derived |
Cache block count, in blocks of |
|
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). |
|
Model default ( |
Post-merger tokens per cache block, independent of the encoder attention block size ( |
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 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
This document is relevant for: Trn2, Trn3