This document is relevant for: Trn2, Trn3

Tutorial: Configure disaggregated encoder inference with 1E1PD and xEyPD#

This topic guides you through configuring encoder-disaggregated inference (EPD) with vLLM Neuron using a simple 1E1PD (one vision encoder, one prefill+decode engine) example and scaling up to a general xEyPD topology. When you have completed it, you will have a working EPD deployment for a multimodal model and will understand the control and data flow between the vision encoder pool, the prefill+decode pool, and the router.

Overview#

For a vision-language model, each request first runs the prompt’s images (or video) through a vision encoder to produce embeddings, then runs the language model (prefill + decode) over the text tokens with those embeddings spliced in. These two stages bottleneck on different resources, and their cost scales with different properties of the request. The encoder is compute-bound, and its cost tracks image count and resolution — the prompt’s text length and the number of tokens generated do not affect it. The PD stage combines a compute-bound prefill over the prompt with memory-bandwidth-bound token generation, which loads the model weights from HBM once per token.

Encoder-disaggregated inference (EPD) separates the vision encoder from the language model across different servers. This separation lets you:

  • Scale the vision encoder pool and the prefill+decode pool independently based on how image-heavy your traffic is.

  • Use different parallelism for each stage. This tutorial gives the encoder a few cores for throughput (TP=4, running DP=4 within them) and the language model a wider tensor-parallel group (TP=8). For how the encoder’s tp_size trades multi-image throughput against single-image latency, see Vision parallelism.

  • Keep expensive vision encoding off the critical path of the language model, and reuse encoded embeddings across the pool via a content-addressed cache.

A single multimodal server remains simpler and is the better default: EPD adds a router, an RDMA transport, and per-pool core-placement constraints. Reach for it when you have measured that one stage is the bottleneck.

Note

EPD splits the vision Encoder from the language model. Steps 1 to 5 run the language model in one combined Prefill+Decode engine: the two-way (E + PD) shape. Disaggregated inference (DI) is a different setup: it splits prefill from decode and has no encoder pool. Step 6 does both: it splits the PD engine into a P pool and a D pool, the three-way (E + P + D) shape.

The two-way architecture of Steps 1 to 5 has three components:

  1. Vision Encoder (VE) pool — runs the vision tower only (launched with --mm-encoder-only), encodes each image/video into embeddings, and writes them into an on-device encoder cache. VE engines act as the EC producer.

  2. Prefill+Decode (PD) pool — runs the language model only (launched with "mm_language_model_only": true inside --additional-config), pulls the vision embeddings it needs, runs prefill over the prompt, and generates tokens. PD engines act as the EC consumer.

  3. Router — preprocesses each request once, routes each media item to a VE, collects the embedding locators, then drives a PD engine to generate the response. It exposes an OpenAI-compatible /v1/chat/completions endpoint. This repository ships a minimal reference router; the VE/PD contract it implements is what any replacement has to reproduce (see Router arguments).

In the three-way shape of Step 6, a P pool and a D pool take the place of the PD pool.

Note

The two build-role switches are set differently. --mm-encoder-only is an upstream vLLM CLI flag, so you pass it directly. mm_language_model_only is a vllm-neuron plugin field with no upstream CLI equivalent — upstream’s disaggregated-encoder consumer loads the full model including the vision tower — so it must be set inside the --additional-config JSON object. There is no --mm-language-model-only flag.

Embedding transfer between VE and PD uses the NeuronNixlECConnector over NIXL / LIBFABRIC (EFA on AWS). The transfer is an HBM→HBM RDMA READ: the PD engine pulls each vision embedding directly from the producing VE’s device-side encoder cache.

Request flow:

  1. Client sends an OpenAI chat-completions request (text + one or more images) to the router.

  2. The router preprocesses the request once, computing a content hash (mm_hash) and placeholder token positions for each media item.

  3. The router routes each media item to a VE using rendezvous (highest-random-weight) hashing on its mm_hash, so the same image consistently lands on the same VE and can hit the warm encoder cache.

  4. Each chosen VE encodes its items, writes the embeddings into its on-device encoder cache, and returns a per-mm_hash EC locator (where the embedding lives).

  5. The router picks a PD engine (round-robin) and calls its /inference/v1/generate with the prompt token ids, the placeholder positions, and the EC locators.

  6. The PD engine pulls each embedding from the owning VE via a NIXL RDMA READ over LIBFABRIC, splices them into the token embedding sequence, runs prefill, and generates the output tokens.

  7. The router detokenizes the PD’s token stream and returns an OpenAI ChatCompletion response (streamed when stream=True).

For more detail on the on-device encoder cache that VE writes and PD reads, see the On-device encoder cache design document.

Before you start#

This tutorial assumes that you have experience in the following areas:

  • Serving a multimodal model on vLLM Neuron on a single instance. See Deploy Qwen3-VL-32B.

  • Running vLLM Neuron online serving. See online serving quickstart.

  • Familiarity with vision encoders and how embeddings are spliced into the language-model prompt.

  • Understanding of tensor parallelism and data parallelism concepts.

Prerequisites#

  • Neuron instance: A supported Trainium instance with enough NeuronCores for both pools. A trn2.48xlarge (64 NeuronCores) comfortably fits the 1E1PD example (12 cores) and scales up to the 2E7PD reference topology (64 cores).

  • vLLM Neuron environment: Installed and verified. See setup guide.

  • NIXL and its runtime libraries: The NIXL EC transfer library. Install with:

    pip install nixl
    

    NIXL’s LIBFABRIC backend also loads the libcuda.so.1 and libfabric.so.1 shared libraries at runtime. If your environment does not already ship them (some container images do not), follow Install dependencies for disaggregated inference before you start. Otherwise the servers fail at startup with unsupported backend 'LIBFABRIC'.

  • Model access: A multimodal model that vLLM Neuron supports. This tutorial uses Qwen3-VL-32B-Instruct.

  • llm-d EPP and Envoy (only for Run EPD with llm-d EPP): see Install the EPP and Envoy.

Prepare your environment#

Important

Run this whole section in every terminal you launch a component from. The three components each run in the foreground, so they each need their own shell — and source / export do not cross shells. Skipping the exports below in the VE or PD terminal is the single most common way to break an otherwise correct deployment: startup and compilation succeed, and the first multimodal request then fails with ECLoadFailure (see Common issues).

Activate the vLLM virtual environment:

source /opt/aws_neuronx_venv_pytorch_inference_vllm_*/bin/activate

Note

This is the pre-built environment shipped by the Neuron DLAMI. The glob avoids pinning a vLLM version, since the directory name embeds one (..._vllm_0_24_0_1_0_0) that changes between DLAMI releases. It assumes exactly one such environment — check with ls -d /opt/aws_neuronx_venv* and activate the one you want by full path if there are several. If you installed via pip or use the container image, the path differs; see the setup guide for the other install options.

The EC connector’s LIBFABRIC/EFA path expects device RDMA and no shared-memory transport. Export these in every VE and PD terminal — these two are required, not tuning knobs:

export FI_EFA_ENABLE_SHM_TRANSFER=0
export FI_EFA_USE_DEVICE_RDMA=1

Without them, LIBFABRIC may select the shared-memory transport instead of device RDMA. Nothing fails at startup, so both engines come up healthy; the first multimodal request is where it breaks, because the READ of the VE’s on-device encoder cache never completes and PD raises ECLoadFailure. Verify with env | grep FI_EFA in each engine’s terminal before launching it.

First-time Neuron compilation of a 32B engine can take several minutes. If your servers time out during compilation, raise the compile timeout:

export VLLM_NEURON_COMPILATION_TIMEOUT=6000

Set your model path — either a Hugging Face model id or a local checkpoint directory:

MODEL="Qwen/Qwen3-VL-32B-Instruct"

# Fail fast if MODEL is unset or empty, rather than silently serving the wrong model.
MODEL="${MODEL:?set MODEL to a Hugging Face model id or checkpoint path first}"

Tip

Prefer a local checkpoint directory over a hub id. Every engine resolves the model id against the Hugging Face API before its engine is built, so bringing up a pool multiplies those calls — and unauthenticated requests are rate-limited per IP, which is shared on NAT’d or multi-tenant hosts. When the quota is exhausted, each affected engine dies at startup with HfHubHTTPError: 429 Too Many Requests: you have reached your 'api' rate limit raised from create_model_config, well before any Neuron work happens. Point MODEL at an already-downloaded checkpoint and pin the hub offline:

MODEL=/path/to/Qwen3-VL-32B-Instruct
export HF_HUB_OFFLINE=1

A local path alone skips the API lookup; HF_HUB_OFFLINE=1 additionally guarantees no other component reaches for the hub mid-launch. If you do use a hub id, export an HF_TOKEN — authenticated requests get a far higher quota — and stagger engine startups as described below.

Warning

Every command below passes "$MODEL" quoted, and the guard above aborts on an empty value. Both matter: vllm serve’s model argument is positional and optional, so if MODEL is empty and unquoted the shell drops the argument entirely and vLLM silently falls back to its built-in default (Qwen/Qwen3-0.6B) — a text-only model. Because that model has no vision tower, the VE then fails deep in model loading with a confusing TypeError: Qwen3ForCausalLM.from_configs() got an unexpected keyword argument 'text_neuron_config' rather than a clear “no model specified” error.

This example places all three components on one instance, so we pin each pool to a disjoint slice of NeuronCores with NEURON_VISIBLE_DEVICES and give each server a distinct port. The layout is:

Component

Role

Cores

HTTP port

NIXL side-channel

PD-0

prefill+decode (TP=8)

0-7

18100

— (consumer)

VE-0

encoder (DP=4)

8-11

18300

14600

Router

OpenAI front end

—

18800

—

The larger pool comes first here. On trn2, each engine’s core slice must start on a boundary that is a multiple of its own TP degree, so the TP=8 PD engine must start at core 0, 8, 16, … while the TP=4 VE only needs a multiple of 4. Placing PD at 0-7 and VE at 8-11 satisfies both and packs the two pools into 12 contiguous cores with nothing stranded; leading with the TP=4 VE would push PD to core 8 and leave cores 4-7 idle. A misaligned slice loads and compiles fine and only fails later, during prefill warmup, when the TP group’s reduce_scatter cannot be mapped onto the hardware collective — see Common issues.

The core IDs in this tutorial count LNC 2 logical NeuronCores, so each engine sets "logical_nc_config": 2 in its --additional-config.

Note

The NEURON_VISIBLE_DEVICES slices above (0-7, 8-11) assume direct host execution and host-level NeuronCore numbering. With EKS and Kubernetes Dynamic Resource Allocation (DRA), a pod can expose its allocation under different, pod-local NeuronCore IDs. Under DRA, leave NEURON_VISIBLE_DEVICES unset and size the DRA resource claim to cover the NeuronCores each engine needs instead.

Each of the three commands below runs in the foreground, so run each one in its own terminal (or under tmux) — and re-run “Prepare your environment” in each of those terminals first, so the venv, the EFA variables, and MODEL are all set.

Note

Prefix caching has not been validated in EPD set up. Therefore each command below passes --no-enable-prefix-caching. Prefix caching is on by default upstream, so this is an opt-out.

Tip

Start the VE and PD in parallel, but the router last. Because the two pools own disjoint core slices and do not talk to each other at startup, they can compile concurrently — which roughly halves cold-start wall clock, and cold compile of a 32B engine can exceed 10 minutes. Two rules of thumb, both taken from the reference launcher (run_epd_single_node in epd_common.py):

  • Stagger the launches by ~10 seconds rather than starting them at the same instant. The launcher sleeps startup_delay_s = 10.0 between engines to avoid a thundering-herd race on NEURON_VISIBLE_DEVICES binding and on the shared compile cache.

  • Start the router only after every engine reports healthy (curl http://127.0.0.1:<port>/health). The launcher health-checks all engines concurrently and starts the router afterward. An early router will not crash, but requests fail until the pools are ready.

Step 1: Launch the vision encoder (VE)#

In this step, you will start a vision-encoder-only server in the ec_producer role. It runs the vision tower, writes embeddings into its on-device encoder cache, and serves their locators to PD engines over NIXL.

NEURON_VISIBLE_DEVICES=8,9,10,11 vllm serve "$MODEL" \
    --tensor-parallel-size 4 \
    --host 127.0.0.1 \
    --port 18300 \
    --max-model-len 8192 \
    --max-num-batched-tokens 8192 \
    --max-num-seqs 1 \
    --dtype bfloat16 \
    --limit-mm-per-prompt '{"image": 30}' \
    --no-enable-prefix-caching \
    --enable-scale-out \
    --mm-encoder-only \
    --no-async-scheduling \
    --additional-config '{"logical_nc_config": 2, "neuron_config": {"quantization": "bf16", "num_batched_tokens_buckets": [8192], "on_device_sampling_config": {"all_greedy": true}, "num_seqs_buckets": [1]}, "encoder_neuron_config": {"encoder_graph_shapes": [[1024, 32]], "dp_size": 4, "encoder_cache_block_size": 16, "encoder_cache_num_blocks": 2049}}' \
    --ec-transfer-config '{"ec_connector": "NeuronNixlECConnector", "ec_role": "ec_producer", "engine_id": "epd-ve-0", "ec_connector_extra_config": {"backends": ["LIBFABRIC"], "side_channel_host": "127.0.0.1", "side_channel_port": 14600}}'

Key parameters:

  • NEURON_VISIBLE_DEVICES=8,9,10,11 — restricts this VE to NeuronCores 8–11 (TP=4). The worker asserts that TP equals the number of visible devices.

  • --mm-encoder-only — build and run only the vision tower. The language model is dropped, so no prefill/decode warmup runs on this engine. This one is an upstream vLLM CLI flag, so it is passed directly (unlike PD’s mm_language_model_only, which goes inside --additional-config).

  • encoder_neuron_config.dp_size: 4 — the vision encoder runs data-parallel across its 4 cores for encoder throughput. DP replicas favor multi-image throughput; shard the encoder weights instead (raise tp_size, which derives DP as world_size / tp_size) when single-image latency matters more — see Vision parallelism.

  • encoder_neuron_config.encoder_cache_block_size: 16 and encoder_cache_num_blocks: 2049 — the layout of the on-device encoder cache. See Encoder cache block size below.

  • --ec-transfer-config with ec_role: "ec_producer" — this engine produces embeddings. engine_id must be unique per VE; side_channel_host / side_channel_port is where PD engines fetch NIXL transfer metadata.

  • encoder_graph_shapes: [[1024, 32]] — one vision encoder graph of 32 blocks of 1024 vision tokens, sized to the example workload. The block size must hold the largest image: (resolution / patch_size)² = (512 / 16)² = 1024. The workload needs num_images blocks of 1024 (30 blocks, 30 × 1024 = 30720 tokens). num_blocks counts the blocks of all vision DP ranks, so it must be a multiple of dp_size (4). So 30 rounds up to 32, and the graph holds 32 × 1024 = 32768 tokens. Recompute it for your own images: resolution is the (square) input edge length in pixels after preprocessing, patch_size is the vision tower’s patch edge (16 for Qwen3-VL), and num_images should match --limit-mm-per-prompt. Non-square images use (width / patch_size) × (height / patch_size) per image. The PD sets the same list.

Wait for the server to print Uvicorn running on http://127.0.0.1:18300.

Step 2: Launch the prefill+decode engine (PD)#

In this step, you will start a language-model-only server in the ec_consumer role. It pulls vision embeddings from the VE, runs prefill, and generates tokens.

NEURON_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 vllm serve "$MODEL" \
    --tensor-parallel-size 8 \
    --host 127.0.0.1 \
    --port 18100 \
    --max-model-len 8192 \
    --max-num-batched-tokens 8192 \
    --max-num-seqs 8 \
    --dtype bfloat16 \
    --limit-mm-per-prompt '{"image": 30}' \
    --no-enable-prefix-caching \
    --enable-scale-out \
    --mm-processor-cache-gb 0 \
    --additional-config '{"logical_nc_config": 2, "neuron_config": {"quantization": "bf16", "num_batched_tokens_buckets": [8192], "on_device_sampling_config": {"all_greedy": true}}, "encoder_neuron_config": {"encoder_graph_shapes": [[1024, 32]], "dp_size": 1, "encoder_cache_block_size": 16}, "mm_language_model_only": true}' \
    --ec-transfer-config '{"ec_connector": "NeuronNixlECConnector", "ec_role": "ec_consumer", "engine_id": "epd-pd-0", "ec_connector_extra_config": {"backends": ["LIBFABRIC"]}}'

Key parameters:

  • NEURON_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 — uses NeuronCores 0–7 (TP=8), disjoint from the VE’s cores. On trn2, a TP=8 engine must start on a multiple of 8, so it takes the bottom of the range and the VE follows at core 8 (see the layout table above).

  • "mm_language_model_only": true — build and run only the language model. The vision tower is dropped, so no encoder warmup runs on this engine. Note this goes inside --additional-config, not as a CLI flag (see the note in the Overview). mm_encoder_only and mm_language_model_only are mutually exclusive — setting both raises at startup.

  • ec_role: "ec_consumer" — this engine consumes embeddings produced by the VE. A consumer does not need a side-channel port; it uses the locator handed to it by the router to reach the producing VE.

  • encoder_cache_block_size: 16 — the same encoder cache block size as the VE. The two pools must use the same value, because the PD reads the VE’s cache blocks directly. A mismatch fails at the first transfer handshake. The PD does not set encoder_cache_num_blocks. It derives the count from --max-num-batched-tokens, because it reads each image in the prefill step that uses it.

  • --mm-processor-cache-gb 0 — the multimodal processor cache is unused on PD because images never reach it (the VE encodes them).

  • --enable-scale-out — registers /inference/v1/generate, which the router uses to drive both VE and PD. vLLM 0.30 and later do not expose it without this flag (the VE command above passes it too).

Encoder cache block size#

The encoder cache stores the merged vision embeddings (one per 2x2 patch group) in fixed blocks of encoder_cache_block_size tokens. Each image fills whole blocks, so the block size must divide the merged-token count of every image you send. The server rejects a request whose image does not fit whole blocks.

The merged-token count of an image is (H / 32) × (W / 32), after the Qwen3-VL processor rounds each side to a multiple of 32. The two image sizes in this tutorial give:

Image

Merged tokens

Divided by 16

The sample photo, downscaled to 512×352

16 × 11 = 176

11 blocks

A 512×512 image (the benchmark)

16 × 16 = 256

16 blocks

A block size of 16 divides both counts. A larger block size puts each image in fewer blocks: one 512×512 image is 16 blocks at a block size of 16, and 256 blocks at a block size of 1. The VE and the PD do a fixed amount of host-side work for each block. A block size of 1 is the default and accepts every image. Use the largest block size that divides the merged-token count of every image in your workload.

encoder_cache_num_blocks counts blocks, not images. Set it on the VE only. The value 2049 holds 128 images of 512×512 (128 × 256 / 16 = 2048 blocks), plus one scratch block. A VE keeps each image until a PD reads it, so the VE needs more cache than one prefill step uses. This count also sets the number of images that the VE scheduler keeps. Without it, the VE derives its cache from --max-num-batched-tokens (8192 merged tokens, 32 images of 512×512), and at high concurrency it can drop images before a PD reads them. If you change the block size, change the block count to keep the same capacity.

Note

Prefix caching is disabled (--no-enable-prefix-caching) on both pools because it has not been validated in an EPD set up yet. Prefix cache is stored on the PD pool so the VE pool doesn’t need it. On a PD node, a KV prefix hit will skip firing the EC connector to pull the embedding because it has already been pulled and merged when generating the prefix cache in a previous prefill run.

Wait for the server to print Uvicorn running on http://127.0.0.1:18100.

Step 3: Launch the router#

In this step, you will start the router that fronts the pools with an OpenAI-compatible API and orchestrates the VE → PD flow.

python3 examples/vllm_neuron/vllm/disaggregated_encoder/server.py \
    --model "$MODEL" \
    --host 127.0.0.1 \
    --port 18800 \
    --ve-timeout-s 600 \
    --pd-timeout-s 600 \
    --ve-endpoint 127.0.0.1:18300 \
    --pd-endpoint 127.0.0.1:18100

The router listens on port 18800 and coordinates the request lifecycle: it preprocesses the request, routes each image to a VE with --ve-endpoint, and drives a PD engine from --pd-endpoint to generate the response.

Router arguments#

These are the router’s arguments for the two-way shape. The three-way shape replaces --pd-endpoint with --prefill-endpoint and --decode-endpoint (see Router arguments for P and D pools):

Argument

Default

Description

--model

required

HF model id or local path. Must be the same checkpoint the VE and PD engines were launched with — the router tokenizes and detokenizes with it.

--ve-endpoint

required

host:port of a Vision Encoder engine. Repeat once per VE; media items are spread over the pool by rendezvous hashing.

--pd-endpoint

none

host:port of a Prefill+Decode engine. Repeat once per PD; requests are assigned round-robin. Required in the two-way shape.

--host

127.0.0.1

Bind host for the router’s own HTTP server.

--port

8000

Bind port for the router’s own HTTP server.

--ve-timeout-s

120.0

Per-VE encode request timeout, in seconds. Raise it if a cold VE is still compiling vision buckets.

--pd-timeout-s

600.0

Per-PD generate request timeout, in seconds. Must cover the full generation, not just time-to-first-token.

--quantization

none

Neuron quantization of the checkpoint, for example mxfp8. Required for a quantized checkpoint.

--metrics-file

none

JSONL file for the per-request phase records. Omit it to write nothing.

--placement-policy

the reference policy

package.module:factory of a placement policy. See Plug in a placement policy.

--placement-gateway

none

NAME=http://host:port of a gateway that a policy may send calls through. Repeat once per gateway. See Run EPD with llm-d EPP.

--decode-slots

0 (no limit)

Hold a PD call while this many are in flight. The two-way shape only. See Run EPD with llm-d EPP.

Important

Pass --quantization whenever the checkpoint is quantized, even though the router loads no weights. The router builds a renderer, which constructs a VllmConfig, and the Neuron platform rejects the checkpoint’s HF quantization_config unless the CPU-dequant quantization is declared. An MXFP8 deployment therefore needs --quantization mxfp8 on the router in addition to "quantization": "mxfp8" in each engine’s neuron_config. The value must match what the engines use. Omitting it fails at router startup, before any request is served. This tutorial’s checkpoint is bf16, so the command above does not set it.

Note

The router (server.py) and the reusable single-node launcher (epd_common.py) are included in the vLLM Neuron repository under examples/vllm_neuron/vllm/disaggregated_encoder/ as reference examples. They are deliberately minimal: both pools are a static list of endpoints, PD selection is plain round-robin unless a placement policy picks, and there is no retry, failover, or autoscaling. The only backpressure is the optional --decode-slots gate. For production deployments, consider an orchestrator for routing, health checking, and autoscaling.

If you bring your own router, it still has to reproduce the same contract with the two pools. The arguments above are not only CLI conveniences:

  • Load the same checkpoint, and declare its quantization. The router tokenizes and detokenizes, so it needs the tokenizer and processor for the exact checkpoint the engines run, and it must declare a quantized checkpoint’s quantization even though it loads no weights (see the admonition above).

  • Preprocess once, on the router. Compute each media item’s content hash (mm_hash) and its placeholder offset/length in the prompt, then send PD the prompt token ids plus those placeholders — not the raw chat messages. Preprocessing again on PD would recompute work and can desynchronize the hashes the locators are keyed on.

  • Send only the LM-relevant mm kwargs. Strip encoder-only tensors such as pixel_values — PD pulls those over NIXL, not over HTTP. For Qwen3-VL, only image_grid_thw needs to travel with the request, for M-RoPE; see get_epd_kwargs in vllm_neuron/model/qwen3_vl/factory.py.

  • Forward the EC locators. Each VE returns one locator per mm_hash, and the PD request must carry them under sampling_params.extra_args.kv_transfer_params.ec_locator. Without them PD cannot find the embeddings, and the request fails with ECLoadFailure.

  • Encode before you generate. Wait for every VE to acknowledge a request’s items before calling PD’s /inference/v1/generate (note PD is driven through that endpoint, not /v1/chat/completions). PD’s RDMA read assumes the embedding already sits in the VE’s on-device cache.

  • Route media items by content, not round-robin. Hashing each item to a VE by its mm_hash — the example uses rendezvous hashing — is what lets a repeated image land on the VE that already has it encoded. Spraying items across the pool instead costs you every encoder-cache hit. PD needs no such affinity, since any PD can pull any embedding.

Step 4: Validate the 1E1PD deployment#

In this step, you will send a multimodal request through the router and confirm it completes end-to-end. The router speaks the OpenAI chat-completions protocol, so any OpenAI client works against it.

The one thing to get right is image size. Both pools above set encoder_graph_shapes: [[1024, 32]]. Its block size of 1024 bounds a single image to 1024 patches — at Qwen3-VL’s patch size of 16, a 512×512 budget. An oversized image is rejected in the encoder, so the script below downscales before sending and inlines the result as base64 rather than depending on the server being able to reach an external URL:

import base64
import io
import urllib.request

from openai import OpenAI
from PIL import Image

MODEL = "Qwen/Qwen3-VL-32B-Instruct"   # must match what the servers loaded
IMAGE_URL = (
    "https://vllm-public-assets.s3.us-west-2.amazonaws.com/"
    "vision_model_images/cherry_blossom.jpg"
)

# The block size 1024 of encoder_graph_shapes bounds one image to 1024 patches;
# at Qwen3-VL's patch size of 16 that is a 512x512 budget.
PATCH_SIZE = 16
MAX_PATCHES = 1024
MAX_EDGE = PATCH_SIZE * int(MAX_PATCHES**0.5)   # 512
# The processor rounds each side to a multiple of 32 (a 2x2 patch group), and
# each group is one merged token. The encoder cache stores the merged tokens in
# blocks of encoder_cache_block_size.
FACTOR = 2 * PATCH_SIZE
CACHE_BLOCK_SIZE = 16

req = urllib.request.Request(IMAGE_URL, headers={"User-Agent": "vllm-neuron-epd"})
with urllib.request.urlopen(req, timeout=60) as resp:
    image = Image.open(io.BytesIO(resp.read()))

image = image.convert("RGB")
print(f"source image: {image.width}x{image.height}")
image.thumbnail((MAX_EDGE, MAX_EDGE), Image.LANCZOS)   # preserves aspect ratio
# Round each side to a multiple of 32 here, so the counts below match the server.
width = max(FACTOR, round(image.width / FACTOR) * FACTOR)
height = max(FACTOR, round(image.height / FACTOR) * FACTOR)
image = image.resize((width, height), Image.LANCZOS)
patches = (width // PATCH_SIZE) * (height // PATCH_SIZE)
merged_tokens = patches // 4
print(f"resized to:   {width}x{height} ({patches} patches, {merged_tokens} merged tokens)")
assert patches <= MAX_PATCHES, f"{patches} patches exceeds block size {MAX_PATCHES}"
assert merged_tokens % CACHE_BLOCK_SIZE == 0, (
    f"{merged_tokens} merged tokens do not fill whole cache blocks of "
    f"{CACHE_BLOCK_SIZE}"
)

buf = io.BytesIO()
image.save(buf, format="JPEG", quality=90)
image_b64 = base64.b64encode(buf.getvalue()).decode()

client = OpenAI(api_key="EMPTY", base_url="http://localhost:18800/v1")
response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"},
                },
                {"type": "text", "text": "Describe this image."},
            ],
        }
    ],
    max_tokens=128,
    temperature=0,
)
print(response.choices[0].message.content)

Save it as validate_epd.py and run it (pip install openai pillow first if needed):

python3 validate_epd.py

The source image is 1770×1180. The script downscales it to 512×341, then rounds each side to a multiple of 32, as the processor does: 512×352, which is 704 patches and 176 merged tokens. Then the request goes out:

source image: 1770x1180
resized to:   512x352 (704 patches, 176 merged tokens)
The image shows a tall tower ... with cherry blossoms in the foreground ...

Tip

To use a larger image at full resolution instead of downscaling, raise the block size in encoder_graph_shapes on both the VE and PD so the block covers your largest input. The list must match across the two pools. To keep the small block for small images, add a graph with the larger block instead, for example [[1024, 32], [8192, 4]], with the same list on both pools.

A generated description of the image confirms:

  1. The router preprocessed the request and routed the image to VE-0 (port 18300).

  2. VE-0 encoded the image and produced an embedding in its encoder cache.

  3. PD-0 (port 18100) pulled the embedding via NIXL over LIBFABRIC and ran prefill.

  4. PD-0 generated tokens, which the router detokenized and returned.

You can confirm the router sees both pools with a health check:

curl -s http://localhost:18800/healthcheck
# {"status":"ok","ve_instances":1,"pd_instances":1}

Step 5: Scale to xEyPD#

In this step, you will generalize the topology to multiple VE and PD engines. As with DI’s xPyD, the two pools scale independently: the router routes each image to a VE by content hash and picks a PD round-robin, so the pools need not be the same size.

A 2E7PD topology fills a trn2.48xlarge: 2 × VE(DP=4) = 8 cores, plus 7 × PD(TP=8) = 56 cores, for 64 cores total.

To run xEyPD on a single node, launch each engine on a disjoint core slice with its own port and (for VEs) a distinct engine_id and side-channel port, then list every endpoint on the router. The core budget must satisfy num_ve × ve_tp + num_pd × pd_tp ≤ node core count.

For example, to add a second VE (VE-1 on cores 12–15, port 18301, side-channel 14604, engine_id epd-ve-1) and a second PD (PD-1 on cores 16–23, port 18101, engine_id epd-pd-1), launch them exactly like Steps 1–2 but with those values, then start the router with all four endpoints:

python3 examples/vllm_neuron/vllm/disaggregated_encoder/server.py \
    --model "$MODEL" \
    --host 127.0.0.1 \
    --port 18800 \
    --ve-timeout-s 600 \
    --pd-timeout-s 600 \
    --ve-endpoint 127.0.0.1:18300 \
    --ve-endpoint 127.0.0.1:18301 \
    --pd-endpoint 127.0.0.1:18100 \
    --pd-endpoint 127.0.0.1:18101

Repeat --ve-endpoint / --pd-endpoint once per engine. The router consistent-hashes each image’s mm_hash across the VE list (so a repeated image reuses the same VE’s warm encoder cache) and round-robins across the PD list. The two selections are decoupled, so any VE’s embedding can be consumed by any PD.

Launch a whole stack programmatically#

Rather than launching each engine by hand, you can derive and bring up a full single-node topology with the EPDTopology / run_epd_single_node helpers in examples/vllm_neuron/vllm/disaggregated_encoder/epd_common.py. build() derives the disjoint device slices, ports, side-channel ports, and unique engine ids from the pool counts:

from examples.vllm_neuron.vllm.disaggregated_encoder.epd_common import (
    EPDTopology,
    run_epd_single_node,
)

topo = EPDTopology.build(
    model="Qwen/Qwen3-VL-32B-Instruct",
    num_ve=2, ve_dp=4,      # 2 vision encoders, DP=4 each
    num_pd=7, pd_tp=8,      # 7 prefill+decode engines, TP=8 each
    ve_logical_nc_config=2, pd_logical_nc_config=2,  # LNC 2 for each engine
    max_model_len=8192,
    max_num_seqs=8,
    encoder_seq_len=30720,   # num_images × (resolution/patch_size)² = 30 × (512/16)²
    num_images=30,
    quantization="bf16",
    # Same cache block size as the commands above. The launcher derives the VE
    # encoder_cache_num_blocks from it (2049 blocks, 128 images of 512x512).
    # Each PD derives its count from --max-num-batched-tokens.
    encoder_neuron_config={"encoder_cache_block_size": 16},
)

with run_epd_single_node(topo, artifacts_dir="/tmp/epd") as stack:
    print(stack.base_url)   # http://127.0.0.1:18800 — send requests here

The context manager brings up every engine and the router, waits for them to report healthy, and tears the stack down on exit. The 2E7PD topology above needs all 64 cores of a trn2.48xlarge.

Overriding the device slices#

build() lays the pools out contiguously from base_device, so it cannot express a gap. To skip specific cores — a faulted device, or cores another job owns — build the topology and then rewrite each engine’s device_slice. It is only ever iterated into that engine’s NEURON_VISIBLE_DEVICES, so any set of cores works, and EngineSpec is frozen, hence dataclasses.replace:

from dataclasses import replace

# Skip cores 20-23. Every PD start stays a multiple of pd_tp (trn2).
VE_STARTS = [0, 4]
PD_STARTS = [8, 24, 32, 40, 48, 56]

topo = EPDTopology.build(..., num_pd=len(PD_STARTS), pd_tp=8,
                         ve_logical_nc_config=2, pd_logical_nc_config=2, ...)
topo = replace(
    topo,
    ve=[replace(e, device_slice=range(s, s + e.tp))
        for e, s in zip(topo.ve, VE_STARTS, strict=True)],
    pd=[replace(e, device_slice=range(s, s + e.tp))
        for e, s in zip(topo.pd, PD_STARTS, strict=True)],
)

for e in topo.ve + topo.pd:                      # fail fast, not 20 min into compile
    cores = list(e.device_slice)
    assert cores[0] % e.tp == 0, f"{e.label} start {cores[0]} not aligned to tp={e.tp}"

Two constraints still apply, and neither is checked for you: each slice must avoid the excluded cores, and on trn2 each must start on a multiple of its own TP degree. Assert both before launching — a misaligned slice compiles fine and only fails in prefill warmup minutes later. Excluding cores also shrinks the budget, so a pool may need to lose an engine: dropping one device from a 64-core node leaves 60 cores, which no longer fits 2E7PD (64) but does fit 2E6PD (56). Reduce num_pd rather than pd_tp — changing TP invalidates the compile cache. Cores that cannot form an aligned slice of the required width are simply left idle.

Note

The example router and launcher target a single node — all endpoints default to 127.0.0.1, and EPDTopology partitions the cores of one instance. The router’s --ve-endpoint / --pd-endpoint flags accept an arbitrary host:port, so a multi-node layout is possible in principle, but it is not covered by the reference launcher. A multi-node deployment additionally requires EFA connectivity and security-group rules between instances (see the DI tutorial’s multi-node section).

Step 6: Split prefill from decode (xEyPzD)#

In this step, you will split the PD pool into a prefill pool (P) and a decode pool (D). The VE pool does not change. The request goes from a VE to a P, and then to a D (VE → P → D).

When to use xEyPzD#

A PD engine runs prefill and decode on the same cores. During a long multimodal prefill on a PD engine, the other requests on that engine do not decode. In xEyPzD, a P engine runs only prefill, and a D engine runs only decode. The time per output token then does not change with the prefill load.

Use xEyPzD when you measure that prefill on the PD pool increases the time per output token above your target. Start with xEyPD in other cases, because it has fewer engines and no KV transfer.

Request flow#

  1. The router preprocesses the request and sends each media item to a VE, as in xEyPD.

  2. After the VE gather, the router picks a P engine: round-robin, unless the placement policy picks it with select_prefill. It sends the request to that P with max_tokens=1 and no streaming.

  3. The P engine reads the embeddings from the VE and runs prefill. It keeps the KV cache of the prompt and returns kv_transfer_params that identify the KV cache.

  4. After the P returns, the router picks a D engine. The placement policy makes this pick with select_pd (round-robin by default, see Plug in a placement policy). The router sends the request with the kv_transfer_params of the P.

  5. The D engine reads the KV cache from the P with a NIXL RDMA READ (NeuronNixlConnector over LIBFABRIC). Then it generates the output tokens, and the router returns them to the client.

The D engine does not read embeddings. The KV cache from the P holds the full prompt. The router sends only the M-RoPE inputs (image_grid_thw) to the D.

Rules#

  • VE pool. Give one or more --ve-endpoint. Each P engine is language-model only and reads the embeddings from a VE.

  • TP degree. Use the same TP degree on P and on D. The validated shapes use TP=8.

  • Model runner. P and D run on Neuron Model Runner V2. On Model Runner V1, a multimodal D stops at its first request. vLLM Neuron selects V2 for a P or D only with these roles, and with VLLM_USE_V2_MODEL_RUNNER unset:

    • P: "mm_language_model_only": true, kv_role kv_producer (not kv_both), and ec_role ec_consumer.

    • D: "mm_language_model_only": true, kv_role kv_consumer, and no --ec-transfer-config.

    With other roles the engine starts on V1 and logs Neuron Model Runner V2 does not yet support multimodal model with KV transfer; using V1. Check that the log of each P and D has Using the standalone V2 Neuron model runner.

  • P request body. Send each P the /inference/v1/generate body that a PD gets in xEyPD (prompt token ids, features, EC locators), with max_tokens=1, min_tokens=0, and no stream or stream_options, so a P engine does not decode. Merge the P handoff keys into sampling_params.extra_args.kv_transfer_params, next to the ec_locator: do_remote_decode: true, do_remote_prefill: false, and remote_engine_id, remote_block_ids, remote_host, remote_port set to null. Do not send them in the top-level kv_transfer_params field, as a DI proxy does: generate serving replaces extra_args.kv_transfer_params with that field, the ec_locator is lost, and the P fails with ECLoadFailure.

  • D request body. Send each D the same prompt token ids and features (the LM-only kwargs, for M-RoPE) with the client’s sampling and stream flags. Put the kv_transfer_params that the P returned into sampling_params.extra_args.kv_transfer_params, without the ec_locator: a D reads no embeddings. Treat a P response without kv_transfer_params as a failed request. The router returns HTTP 502 for a non-streaming request, and an in-band error frame with code 502 followed by data: [DONE] for a streaming one.

  • Sampling parameters. The router rejects a request with n other than 1, or with prompt_logprobs, with HTTP 400. With prompt logprobs, a D engine does not load the KV cache and runs the multimodal prefill itself, but it has no vision tower, so its engine stops. With n above 1, the P returns the KV cache of one sequence only.

  • Prefix caching. Keep --no-enable-prefix-caching on each engine. Prefix caching is not validated with xEyPzD.

  • KV load failure. Keep the upstream kv_load_failure_policy default (fail) on each D engine. A D engine cannot recompute a prompt, because it has no vision tower and no embeddings.

  • EFA variables. Export FI_EFA_ENABLE_SHM_TRANSFER=0 and FI_EFA_USE_DEVICE_RDMA=1 in each engine terminal. The KV transfer and the embedding transfer both use LIBFABRIC.

  • KV side channel. Give each P and D engine its own VLLM_NIXL_SIDE_CHANNEL_PORT, and set VLLM_NIXL_SIDE_CHANNEL_HOST=127.0.0.1. The default port is the same on each engine, so two engines on one node use the same port.

  • No fixed KV engine_id. Do not set engine_id in --kv-transfer-config. vLLM gives each engine a new id at each start. With a fixed id, a D engine uses the old handshake after a P restart. Its requests then stop until the router timeout.

  • Core alignment. Start each slice at a multiple of its TP degree, as in xEyPD.

  • VE cache. A VE keeps each item until a P reads it. Set encoder_cache_num_blocks on each VE for the worst case, in which each request in flight is encoded, no P read any of them yet, and all of their items are on one VE: C × blocks_per_request + 1, for C requests in flight. The last block is the scratch block. blocks_per_request is the merged-token count of one request divided by encoder_cache_block_size (see Encoder cache block size), so it depends on the block size. For 30 images of 512×512 (256 merged tokens each), it is 30 × 256 / 16 = 480 at the block size of 16 that the VE of this tutorial uses, and 30 at a block size of 256, which the EPD perf tests use. So C=32 needs 15361 blocks at a block size of 16, or 961 blocks at 256. Both hold the same 245,760 merged tokens, about 9.4 GiB on each VE rank for Qwen3-VL-32B. If the VE frees an item before a P reads it, the P logs EC receipt validation failed, and the P engine stops with ECLoadFailure.

  • D batch. Set --max-num-seqs on each D to ceil(C / num_d). The router gives the D engines the requests round-robin, so each D has about C / num_d of the C requests in flight, and this batch runs them all at once. The count on one D can drift above its share when requests end at different times. With this batch, the extra requests wait in the D queue. With a larger batch, that D runs them in its batch, which can slow each of its steps: on Trn3 with MXFP8, a D step above 8 running sequences is about 3.4x slower. That slowdown was measured on Trn3. On trn2 with BF16, the 2E·4P3D runs at C=32 use a D batch of 11.

Note

The router sends no abort. If a request stops after its P returns and before the D reads the KV cache, for example at a client disconnect or a D error, the P keeps the KV cache until its lease ends (30 s by default). Then the P frees it and logs the lease expiry.

Example: 1E1P1D on one instance#

This example serves up to 4 requests in flight (C = 4), each with 30 images of 512×512. The VE cache and the D batch below are sized for C = 4 by the rules above. Keep the client at 4 requests in flight or fewer, for example with vllm bench serve --max-concurrency 4.

The layout is:

Component

Role

Cores

HTTP port

KV side channel

EC side channel

P-0

prefill (TP=8), KV producer, EC consumer

0-7

18100

5600

—

D-0

decode (TP=8), KV consumer

8-15

18101

5700

—

VE-0

encoder (TP=4, DP=4), EC producer

16-19

18300

—

14600

Router

OpenAI front end

—

18800

—

—

Each listener binds 127.0.0.1. Run each command in its own terminal. Do “Prepare your environment” in each terminal first.

Launch the P engine. It is language-model only, an EC consumer, and a KV producer:

NEURON_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
VLLM_NIXL_SIDE_CHANNEL_HOST=127.0.0.1 \
VLLM_NIXL_SIDE_CHANNEL_PORT=5600 \
vllm serve "$MODEL" \
    --tensor-parallel-size 8 \
    --host 127.0.0.1 \
    --port 18100 \
    --max-model-len 8192 \
    --max-num-batched-tokens 8192 \
    --max-num-seqs 1 \
    --dtype bfloat16 \
    --limit-mm-per-prompt '{"image": 30}' \
    --no-enable-prefix-caching \
    --enable-scale-out \
    --mm-processor-cache-gb 0 \
    --additional-config '{"logical_nc_config": 2, "neuron_config": {"quantization": "bf16", "num_batched_tokens_buckets": [8192], "on_device_sampling_config": {"all_greedy": true}}, "encoder_neuron_config": {"num_encoder_input_buckets": [30720], "encoder_attention_block_size": 1024, "dp_size": 1, "encoder_cache_block_size": 16}, "mm_language_model_only": true}' \
    --ec-transfer-config '{"ec_connector": "NeuronNixlECConnector", "ec_role": "ec_consumer", "engine_id": "epd-p-0", "ec_connector_extra_config": {"backends": ["LIBFABRIC"]}}' \
    --kv-transfer-config '{"kv_connector": "NeuronNixlConnector", "kv_role": "kv_producer", "kv_buffer_device": "cuda", "kv_connector_extra_config": {"backends": ["LIBFABRIC"]}}'

The P engine runs one request at a time (--max-num-seqs 1). It does not decode, so a larger batch only makes each prefill wait longer.

Launch the D engine. It is language-model only and a KV consumer. It has no --ec-transfer-config:

NEURON_VISIBLE_DEVICES=8,9,10,11,12,13,14,15 \
VLLM_NIXL_SIDE_CHANNEL_HOST=127.0.0.1 \
VLLM_NIXL_SIDE_CHANNEL_PORT=5700 \
vllm serve "$MODEL" \
    --tensor-parallel-size 8 \
    --host 127.0.0.1 \
    --port 18101 \
    --max-model-len 8192 \
    --max-num-batched-tokens 8192 \
    --max-num-seqs 4 \
    --dtype bfloat16 \
    --limit-mm-per-prompt '{"image": 30}' \
    --no-enable-prefix-caching \
    --enable-scale-out \
    --mm-processor-cache-gb 0 \
    --additional-config '{"logical_nc_config": 2, "neuron_config": {"quantization": "bf16", "num_batched_tokens_buckets": [8192], "on_device_sampling_config": {"all_greedy": true}}, "encoder_neuron_config": {"num_encoder_input_buckets": [30720], "encoder_attention_block_size": 1024, "dp_size": 1, "encoder_cache_block_size": 16}, "mm_language_model_only": true}' \
    --kv-transfer-config '{"kv_connector": "NeuronNixlConnector", "kv_role": "kv_consumer", "kv_buffer_device": "cuda", "kv_connector_extra_config": {"backends": ["LIBFABRIC"]}}'

The D batch is ceil(C / num_d) = 4 (--max-num-seqs 4).

Launch the VE engine with the command of Step 1, on cores 16-19 (NEURON_VISIBLE_DEVICES=16,17,18,19). The VE does not use the KV side channel, so it needs no VLLM_NIXL_SIDE_CHANNEL_* variable. Its cache of 2049 blocks covers C = 4: at encoder_cache_block_size 16, one 512×512 image is 256 / 16 = 16 blocks, so a request of 30 images is 480 blocks, and C × 480 + 1 = 1921 blocks fit in 2049. For more requests in flight, set encoder_cache_num_blocks on the VE to C × 480 + 1 and --max-num-seqs on the D to C. With a smaller cache, the VE can free an item before the P reads it. The P then logs EC receipt validation failed, and the P engine stops with ECLoadFailure.

When each engine prints Uvicorn running, start the router with the P and D pools:

python3 examples/vllm_neuron/vllm/disaggregated_encoder/server.py \
    --model "$MODEL" \
    --host 127.0.0.1 \
    --port 18800 \
    --ve-timeout-s 600 \
    --pd-timeout-s 600 \
    --ve-endpoint 127.0.0.1:18300 \
    --prefill-endpoint 127.0.0.1:18100 \
    --decode-endpoint 127.0.0.1:18101

Check that the router sees the pools:

curl -s http://localhost:18800/healthcheck
# {"status":"ok","ve_instances":1,"pd_instances":1}

In this shape, pd_instances is the number of D engines. Then run validate_epd.py from Step 4. The router port is the same, so the script does not change.

With --metrics-file, each phase record of a 3-way request holds p_ms (the P round trip) and d_first_token_ms in place of pd_first_token_ms. As with pd_first_token_ms, the router sets d_first_token_ms for a streaming request only. validate_epd.py sends a non-streaming request, so its record has d_first_token_ms: null.

Router arguments for P and D pools#

Argument

Default

Description

--prefill-endpoint

none

host:port of a P engine. Repeat once per P. Use it with --decode-endpoint, in place of --pd-endpoint.

--decode-endpoint

none

host:port of a D engine. Repeat once per D.

--pd-timeout-s

600

In the 3-way shape, the timeout of one P request and of one D request, in seconds. It must cover the full generation.

The router raises at startup unless it gets --pd-endpoint only, or --prefill-endpoint and --decode-endpoint together.

Scale to 2E·4P3D#

A 2E·4P3D topology fills a trn2.48xlarge: 2 × VE(TP=4) = 8 cores, plus 4 × P(TP=8) = 32 cores, plus 3 × D(TP=8) = 24 cores, for 64 cores total.

Pool

Engines

TP

Cores

HTTP ports

KV side channel

EC side channel

VE

2

4 (DP=4)

0-3, 4-7

18300, 18301

—

14600, 14604

P

4

8

8-15, 16-23, 24-31, 32-39

18100–18103

5600, 5700, 5800, 5900

—

D

3

8

40-47, 48-55, 56-63

18104–18106

6000, 6100, 6200

—

Router

—

—

—

18800

—

—

Each VE rank listens on its EC side-channel port plus its rank, so VE-0 uses 14600–14603. Launch each engine like the 1E1P1D commands, with the values of the table. Give each P its own engine_id (epd-p-0 to epd-p-3). Set the VE cache and the D batch for the concurrency, as in the rules above. With the block size of 16 of the 1E1P1D commands, C=32 needs encoder_cache_num_blocks of 32 × 480 + 1 = 15361 on each VE, and --max-num-seqs 11 on each D (ceil(32 / 3)). Then give the router each endpoint:

python3 examples/vllm_neuron/vllm/disaggregated_encoder/server.py \
    --model "$MODEL" \
    --host 127.0.0.1 \
    --port 18800 \
    --ve-timeout-s 600 \
    --pd-timeout-s 600 \
    --ve-endpoint 127.0.0.1:18300 --ve-endpoint 127.0.0.1:18301 \
    --prefill-endpoint 127.0.0.1:18100 --prefill-endpoint 127.0.0.1:18101 \
    --prefill-endpoint 127.0.0.1:18102 --prefill-endpoint 127.0.0.1:18103 \
    --decode-endpoint 127.0.0.1:18104 --decode-endpoint 127.0.0.1:18105 \
    --decode-endpoint 127.0.0.1:18106

The reference launcher builds the same stack. Set num_p and num_d in place of num_pd. In this shape, max_num_seqs is the D batch, and each P runs one sequence. For C=32, 30 images of 512×512 and a block size of 256:

from examples.vllm_neuron.vllm.disaggregated_encoder.epd_common import (
    EPDTopology,
    run_epd_single_node,
)

topo = EPDTopology.build(
    model="Qwen/Qwen3-VL-32B-Instruct",   # or a local checkpoint directory
    num_ve=2, ve_dp=4,      # 2 vision encoders, DP=4 each
    num_p=4, num_d=3,       # 4 prefill and 3 decode engines, TP=8 each
    ve_logical_nc_config=2, pd_logical_nc_config=2,  # LNC 2 for each engine
    max_model_len=8192,
    max_num_seqs=11,        # the D batch: ceil(32 / 3)
    encoder_seq_len=30720,
    num_images=30,
    encoder_neuron_config={"encoder_cache_block_size": 256},
    # 32 requests of 30 blocks on one VE, plus the scratch block.
    ve_encoder_neuron_config={"encoder_cache_num_blocks": 961},
)

with run_epd_single_node(topo, artifacts_dir="/tmp/epd") as stack:
    print(stack.base_url)   # http://127.0.0.1:18800 — send requests here

A block size of 256 accepts only images whose merged-token count is a multiple of 256, such as 512×512 (256 merged tokens). The server rejects the 512×352 sample image of validate_epd.py (176 merged tokens) on this stack. To run the script against it, set CACHE_BLOCK_SIZE = 256 and replace the thumbnail call with image = image.resize((MAX_EDGE, MAX_EDGE), Image.LANCZOS). Or launch the VEs with a block size of 16 and 15361 blocks.

build() raises when a slice of the 3-way shape does not start at a multiple of its TP degree, for example for 1E1P1D with a TP=4 VE at core 0, which puts the TP=8 P at core 4. Set base_device=4 in that case.

Plug in a placement policy#

The router separates mechanism from policy. The router keeps the mechanism: HTTP, the /encode POSTs (one for the non-video items of each VE, and one for each video item, with a /v{k} request-id suffix), the EC locators, the PD request body, and the stream. A placement policy decides which VE encodes each distinct media item, and which PD (in the 3-way shape, which D) serves the request. In the 3-way shape, it may also pick the P. A policy answers with ids only. It gets no endpoint or transport handle, so it cannot move data. Without --placement-policy, the router uses its reference policy: rendezvous hashing on each item’s mm_hash for VEs, and round-robin for PDs, Ds and Ps.

A policy is any object with these three methods (see vllm_neuron/vllm/disaggregated_encoder/placement.py):

Method

Returns

Reference policy

place_encode(items, ctx)

{Target(ve_id): [mm_hash, ...]}

Rendezvous hashing of each mm_hash over ctx.ve_ids

select_pd(ctx)

Target(pd_id)

Round-robin over ctx.pd_ids, one cursor for the streaming and non-streaming paths. In the 3-way shape, ctx.pd_ids are the D ids and the answer is the D

select_prefill(ctx)

None, or Target(p_id) in the 3-way shape

None: the router walks the P pool round-robin

items holds one PlacementItem per distinct mm_hash in the request, with its modality, its num_tokens and its video: for a shard of a long video that the router split (video_sharding), the mm_hash of the first shard of that video, and None for other items. ctx is a PlacementContext with the request_id, the live ve_ids and pd_ids in registration order, the request’s mm_hashes in prompt order, and the live p_ids of the 3-way shape (empty in the 2-way shape). In the 3-way shape, pd_ids holds the D ids.

The router asks place_encode before any VE call, and select_pd and select_prefill after the VEs have encoded the items, just before the PD call. In the 2-way shape, select_prefill must return None. In the 3-way shape, the router asks select_prefill just before the P call, and select_pd (a D id) after P returns. It checks each answer before the call that the answer governs. A rejected answer, or a method that raises, fails the request with error type placement_error (code 500): HTTP 500 for a non-streaming request, and an in-band error frame followed by data: [DONE] for a streaming one. The placement.py module docstring lists the rules, and the router log holds the reason for each rejection.

The methods run synchronously in the router’s event loop on every request, so keep them cheap and never block in them. Each request’s phase record (--metrics-file) holds the time spent in place_encode as place_encode_ms.

For an example, see OneEncoderPolicy in examples/vllm_neuron/vllm/disaggregated_encoder/placement_policy.py. It sends every item to the first VE and picks the PD by hashing the request’s first media item. Do not use it with video_sharding: it puts all the shards of a long video on one VE (29 shards, so 29 concurrent POSTs, for a 1-hour video). That VE must hold all the shards in its encoder cache, and --ve-timeout-s (default 120 s) applies to each POST.

Name the policy with --placement-policy package.module:factory. The module must be importable, and the router calls the factory once with no arguments, so a class works. From the repository root:

PYTHONPATH=$PWD:$PYTHONPATH \
python3 examples/vllm_neuron/vllm/disaggregated_encoder/server.py \
    --model "$MODEL" \
    --port 18800 \
    --ve-endpoint 127.0.0.1:18300 \
    --ve-endpoint 127.0.0.1:18301 \
    --pd-endpoint 127.0.0.1:18100 \
    --pd-endpoint 127.0.0.1:18101 \
    --placement-policy examples.vllm_neuron.vllm.disaggregated_encoder.placement_policy:OneEncoderPolicy

A policy that cannot be imported, or that lacks one of the three methods, stops the router before it serves a request.

Note

The single-node EPD perf tests size each VE’s encoder cache for the even spread that rendezvous hashing gives (concurrency × items per request / VE count). A policy that concentrates items on fewer VEs can overflow one VE’s cache.

Run EPD with llm-d EPP#

Instead of placing calls itself, the router can hand every placement to llm-d’s Endpoint Picker (EPP). The router sends each /inference/v1/generate call to a local Envoy and tags it with an x-llm-d-epp-profile header, as llm-d’s Coordinator does. Envoy asks the EPP over ext_proc which engine serves the call, and forwards the call there. Only placement changes: the VE still returns its own EC locator, and P still returns the KV handoff for D, so the request bodies and the NIXL pulls are the same as with the reference policy.

client → router ──(encode)──────► Envoy ──► VE picked by the EPP
                ├─(prefill, 3-way)─► Envoy ──► P picked by the EPP
                └─(decode)──────► Envoy ──► PD (or D) picked by the EPP
                                    │
                                    └─ ext_proc ─► EPP (file discovery, no Kubernetes)

Profile

Candidates (llm-d.ai/role)

Scorers (weight)

encode

the VEs (encode)

mm-embeddings-cache-scorer (3), header-label-affinity-scorer on the placement hint (1.2), active-request-scorer (1)

decode

the PDs, or the Ds of the 3-way shape (decode)

active-request-scorer (1), token-load-scorer (1)

prefill

the Ps of the 3-way shape (prefill)

active-request-scorer (1), token-load-scorer (1)

The EPP scrapes no engine /metrics: every score comes from its own count of in-flight calls, and mm-embeddings-cache-scorer keeps its own model of each VE’s encoder cache (an LRU of the items it sent there, sized in merged tokens).

The policy, EppPolicy in examples/vllm_neuron/vllm/disaggregated_encoder/llmd_epp_policy.py, splits a request’s items in prompt order into one contiguous chunk per VE (fewer when the request has fewer items than there are VEs) and sends one encode call per chunk. Each chunk carries a VE’s router id as its placement hint (x-vllm-neuron-epd-hint), and the launcher labels each engine with its router id. Chunk k hints VE (r + k) mod n, where r advances by one per request, so a request with fewer chunks than VEs leaves a different VE out each time. The hint outweighs load (at most 1). A cache hit scores 3 times the share of the chunk that a VE holds, so a VE that holds the whole chunk wins it even from an idle VE that the hint names (3 > 1.2 + 1). So each request with at least as many items as VEs keeps one chunk on each VE, as with rendezvous hashing: both VE queues then hold the same requests in the same order, and a request’s chunks finish together. Without the hint, the EPP put both chunks of 21–24% of the requests on the less loaded VE, and every request’s gather slowed down. A one-item request (a video) is one chunk with no hint, placed by load and cache.

Install the EPP and Envoy#

The gateway runs two stock x86_64 Linux binaries: the EPP of llm-d-router v1.0.0 and Envoy 1.40.2. By default, the launcher runs /usr/local/bin/epp and /usr/local/bin/envoy; if both exist, skip this step.

Before the engines start, the launcher checks both versions: the build stamp that epp --help logs, and envoy --version. It refuses any other version, and an EPP built without llm-d’s release ldflags, whose build stamp is empty.

Envoy is a release binary:

mkdir -p ~/llmd-bin
curl -fsSL -o ~/llmd-bin/envoy \
    https://github.com/envoyproxy/envoy/releases/download/v1.40.2/envoy-1.40.2-linux-x86_64
echo "1d64506e25c1844f146162ddb2ece7010fa4e784faddb40a079021491f1f03cc  $HOME/llmd-bin/envoy" \
    | sha256sum -c -
chmod +x ~/llmd-bin/envoy
~/llmd-bin/envoy --version   # .../1.40.2/Clean/RELEASE/BoringSSL

The EPP is the statically linked /app/epp of llm-d-router’s v1.0.0 linux/amd64 release image. With Docker, copy it out of the image:

EPP_IMAGE=ghcr.io/llm-d/llm-d-router-endpoint-picker:v1.0.0@sha256:8c6b24302ed21a1c4aa6ba2306187236519a8fdc92282998b33e65c6a446c516
id=$(docker create "$EPP_IMAGE") && docker cp "$id:/app/epp" ~/llmd-bin/epp && docker rm "$id"

Without Docker (for example, inside a container), download the image layer that holds /app/epp. The image is public:

IMG=llm-d/llm-d-router-endpoint-picker
LAYER=sha256:4d7213119ef32ce421109a79434f2868463122f84a04e8e7ce831c0b121516af
TOKEN=$(curl -fsSL "https://ghcr.io/token?scope=repository:$IMG:pull" \
    | python3 -c 'import json, sys; print(json.load(sys.stdin)["token"])')
curl -fsSL -H "Authorization: Bearer $TOKEN" "https://ghcr.io/v2/$IMG/blobs/$LAYER" \
    | tar -xz -C ~/llmd-bin --strip-components=1 app/epp

Either way, the file is the same:

echo "b3744c05d56f234ce694e06df19d4bae26a448e1d1ef8b8717e5e23b119b87ae  $HOME/llmd-bin/epp" \
    | sha256sum -c -
~/llmd-bin/epp --help 2>&1 | grep -o '"build-ref":"[^"]*"'   # "build-ref":"v1.0.0"

To run binaries from somewhere other than /usr/local/bin, pass their paths in LLMD_EPP_BIN and LLMD_ENVOY_BIN. Set them before you start the stack:

export LLMD_EPP_BIN=$HOME/llmd-bin/epp
export LLMD_ENVOY_BIN=$HOME/llmd-bin/envoy

If a binary is missing or not executable, the launcher stops before it starts the engines, and names the path it looked for.

Run it#

Launch a stack as in Step 5 or Step 6, with placement="epp":

from examples.vllm_neuron.vllm.disaggregated_encoder.epd_common import (
    EPDTopology,
    run_epd_single_node,
)

topo = EPDTopology.build(
    ...,               # the 2E7PD arguments of Step 5, or the 2E·4P3D ones of Step 6
    ve_logical_nc_config=2, pd_logical_nc_config=2,
    placement="epp",
)

with run_epd_single_node(topo, artifacts_dir="/tmp/epd-epp") as stack:
    print(stack.base_url)   # http://127.0.0.1:18800
    input("The stack is up. Press Enter to stop it.\n")

The launcher writes the endpoints file and both configs from the topology. It starts the EPP and Envoy after the engines and before the router, passes --placement-gateway and --placement-policy to the router, and stops the gateway with the stack. Envoy listens on 127.0.0.1:18900, with its admin port on 18901. The EPP has no bind flag, so its listeners (18902–18904) bind every interface. Keep these ports closed to other hosts, for example with the instance’s security group or a host firewall: they have no TLS or authentication, and a host that reaches them can skew the EPP’s load counts and its model of the VE caches.

From another terminal, send the request of Step 4. Then check that every call went through the gateway (Envoy writes its access log to the file once a second):

python3 - <<'EOF'
import collections, json
log = "/tmp/epd-epp/llmd/envoy_access.jsonl"
rows = [json.loads(line) for line in open(log)]
for key, n in sorted(collections.Counter(
        (r["profile"], r["upstream"], r["code"]) for r in rows).items()):
    print(*key, n)
EOF
# decode 127.0.0.1:18104 200 1
# encode 127.0.0.1:18300 200 1

Expect encode calls on VE ports, decode calls on PD (or D) ports, prefill calls on P ports in the 3-way shape, and only code 200. With 2E·4P3D, for example, encode calls land on 18300–18301, prefill calls on 18100–18103, and decode calls on 18104–18106.

A gateway call also carries the router’s --model name in its body, because the EPP rejects a body without one, and an x-request-id equal to the body’s request_id. Everything goes to llmd/ under the run’s artifacts directory: endpoints.json, epp_config.json, envoy.json, epp.log, envoy.log, and envoy_access.jsonl, one line per call with its profile, request id, the engine that served it and the time the gateway added.

In the 2-way shape, the launcher also passes --decode-slots: the PDs’ count times their --max-num-seqs. The router then holds a PD call while that many are in flight, and sends it when one finishes. When more requests arrive than the PDs have slots, the EPP could otherwise only pick among full PDs, and a request might wait behind one that frees its slot late; with the gate, the pick always finds a free PD. The record’s decode_wait_ms holds the wait, inside pd_first_token_ms. The 3-way shape has no such gate, and the router rejects --decode-slots with P engines: the wait would come after P, and P keeps a request’s KV cache only for its kv_lease_duration (30 s by default) unless a D renews it. A D renews it once the request is in that D’s queue.

If a run is killed before it stops the gateway, the EPP and Envoy keep their ports. The next run then stops before it starts the gateway, with The gateway ports [...] already accept connections. Stop them as in Clean up.

When the gateway fails#

Nothing falls back to the reference policy. If Envoy is unreachable, or if the EPP is down or finds no engine (Envoy then answers 500, 503 or 429), the call fails, and the request fails with error type upstream_error (code 502), as for any engine failure. A call without the profile header gets a 404 from Envoy and never reaches an engine.

Note

The EPP models each VE’s encoder cache from the calls it routed; it does not read the VE’s cache. After a VE restarts, the EPP still believes the VE holds its old items until they age out of its LRU, so the first repeats miss.

Confirmation#

You have a working EPD deployment that:

  • Separates the vision encoder from the prefill+decode language model across different NeuronCore slices.

  • Transfers vision embeddings from VE to PD via the NeuronNixlECConnector over NIXL / LIBFABRIC (HBM→HBM RDMA READ).

  • Routes each image to a VE by content hash (warm-cache affinity) and each request to a PD round-robin, through an OpenAI-compatible router.

  • Supports asymmetric scaling (different numbers of VE and PD engines, and different DP/TP per pool).

  • In the three-way shape of Step 6, runs prefill on a P pool and decode on a D pool, and moves the KV cache from P to D with NeuronNixlConnector.

Common issues#

  • TypeError: Qwen3ForCausalLM.from_configs() got an unexpected keyword argument 'text_neuron_config': The server is loading a text-only model while encoder_neuron_config is set, so the runner builds a multimodal model from a text-only architecture. The usual cause is an empty or unset MODEL: vllm serve’s model argument is positional and optional, so an unquoted empty $MODEL disappears from the command line and vLLM falls back to its default Qwen/Qwen3-0.6B. Check the startup banner’s model line — it shows what was actually loaded — and confirm your checkpoint’s config.json lists "architectures": ["Qwen3VLForConditionalGeneration"].

  • HfHubHTTPError: 429 Too Many Requests: you have reached your 'api' rate limit: Not an EPD problem — vLLM resolves the model id against the Hugging Face API in create_model_config, before the engine is built, and unauthenticated requests are rate-limited per IP (shared on NAT’d or multi-tenant hosts). Launching a pool multiplies those calls, so a programmatic bring-up trips the limit more easily than a single server. Serve from a local checkpoint directory with HF_HUB_OFFLINE=1, or export an HF_TOKEN for the higher authenticated quota (see the tip in Prepare your environment). The error message states how many seconds to wait before retrying.

  • Server fails at startup with unsupported backend 'LIBFABRIC': NIXL’s LIBFABRIC backend can’t load libcuda.so.1 / libfabric.so.1. Install the DI dependencies (see Prerequisites) and confirm python -c "import nixl" works.

  • No CUDA runtime is found, using CUDA_HOME='/usr/local/cuda': Benign on Neuron. PyTorch’s cpp_extension probes for CUDA at import; nothing in the EPD path uses it, and NIXL transfers ride LIBFABRIC/EFA. The same applies to Failed to import from vllm._C warnings.

  • Connection refused from the router: Both the VE and PD servers must be fully started before the router can serve requests. First-time Neuron compilation can take several minutes — wait for the Uvicorn running message on each server, and confirm /healthcheck reports the expected VE and PD counts.

  • Embedding transfer stalls or times out: Ensure LIBFABRIC/EFA is available (fi_info -p efa) and that FI_EFA_ENABLE_SHM_TRANSFER=0 and FI_EFA_USE_DEVICE_RDMA=1 are set on both pools. Confirm each VE has a unique engine_id and a reachable side_channel_port.

  • TP != len(NEURON_VISIBLE_DEVICES) assertion: The tensor-parallel size must equal the number of cores in that engine’s NEURON_VISIBLE_DEVICES slice. For a VE, --tensor-parallel-size is the core count; dp_size is a separate vision data-parallel degree inside encoder_neuron_config.

  • Collective operation REDUCE_SCATTER ... is currently not supported, followed by Failed to schedule neff execution. status=2 message=Invalid and Model warmup failed for prefill bucket ...: On trn2, the engine’s core slice is misaligned. A slice must start on a multiple of its own TP degree, so a TP=8 engine must start at core 0, 8, 16, …; a slice like 4-11 has the right core count but the wrong offset, and the TP group’s sequence-parallel reduce_scatter cannot be mapped onto a hardware collective. This is a property of the trn2 device interconnect, whose cores form a 2D torus that the runtime matches against a fixed set of collective algorithms; a slice that straddles the torus rows the algorithms expect falls through to no algorithm at all. Nothing catches this at startup — the engine loads and compiles normally, then fails during prefill warmup. Note the error names the collective and not the core layout, so it is easy to misread as a size or bucket problem: shrinking num_batched_tokens_buckets (or enabling segmented prefill with kv_segment_size_buckets) changes the reported total_size but reproduces the same failure. Fix the offset instead — move the engine to an aligned slice such as 0-7, 8-15, or 56-63.

    This also applies to EPDTopology.build in epd_common.py, which lays the VE pool out first and gives the PD pool whatever follows. That is aligned when the VE pool’s total width is a multiple of the PD’s TP degree — as in 2E7PD, where 2 × VE(TP=4) = 8 cores puts PD-0 at core 8 — but a 1E1PD built the same way yields VE 0-3 and PD 4-11, which is exactly the misaligned case above. When a topology has a single small VE pool ahead of a wider PD pool, pass base_device or lay the pools out by hand so each PD slice starts on a multiple of pd_tp.

    Later platforms whose cores are connected through a switch rather than a torus may not need the offset to be aligned, since any set of cores can form a collective group. That has not been verified for EPD — the topologies exercised in CI are aligned on every platform — so keep the slices aligned unless you have measured otherwise.

  • ECLoadFailure: Encoder-cache load failed for mm_hashes: [...], and the PD engine core dies: PD could not read a vision embedding out of the VE’s on-device encoder cache. The failure always surfaces on the consumer side as a cache-load error and takes the engine core down with it, but the cause is usually upstream of PD. In order of likelihood:

    1. The EFA environment variables are missing on one of the engines. Check FI_EFA_ENABLE_SHM_TRANSFER=0 and FI_EFA_USE_DEVICE_RDMA=1 in the VE and PD terminals — env | grep FI_EFA in each. This is easy to miss because the exports are set once in “Prepare your environment” while each engine runs in its own shell, and because nothing complains until the first request. If the PD log shows EC wait_for_load timed out after ..., the READ was issued and never landed, which points here.

    2. An oversized image. One image exceeding the largest block size of encoder_graph_shapes (1024 patches in this tutorial, a 512×512 budget at patch size 16) fails to encode on the VE, so there is nothing for PD to read. Check the VE’s log for the encode error, then downscale the image (see Step 4) or add a graph with a larger block to encoder_graph_shapes on both pools.

    3. A VE↔PD (model_id, dtype) mismatch. The NIXL handshake rejects a PD pool pointed at a VE serving a different model or dtype, before any bytes move — look for a ValueError naming model_id or dtype in the log. Launch both pools from the same checkpoint (see the --model note) with matching dtype.

    4. A per-embedding content-validation failure. Each block carries an mm_hash fingerprint. The VE writes the tag before the embedding. The PD reads the embedding first, then reads the tag on a second RDMA READ, and compares it to the fingerprint it expects. A mismatch (EC receipt validation failed for mm_hash ...) means the block PD read no longer held the item it expected — a stale, reused, or wrong block. The PD reports it as a load failure, not a wrong answer.

  • One engine hangs for minutes, then TDRV:tdrv_init_wait_ncs_ready Failed to reset nd <N> nc_map 0x… timeout (result=-110) → RuntimeError: Engine core initialization failed: A Neuron device is in a faulted state and is not responding to reset (-110 is ETIMEDOUT from the driver). This is a hardware problem, not a configuration one — restarting the stack will not clear it. Confirm which device by comparing reset counters across devices:

    B=/sys/devices/virtual/neuron_device
    # Neuron Driver 2.31+. On earlier drivers, replace stats/application/other_info with stats/other_info
    for d in $(seq 0 15); do for c in 0 1 2 3; do
      printf "nd%s nc%s req=%s fail=%s\n" $d $c \
        "$(cat $B/neuron$d/neuron_core$c/stats/application/other_info/reset_req_count/total 2>/dev/null)" \
        "$(cat $B/neuron$d/neuron_core$c/stats/application/other_info/reset_fail_count/total 2>/dev/null)"
    done; done
    

    A healthy device reports fail=0 on every core; a faulted one reports a nonzero fail on all of them. Note the failure takes down the whole stack, not just the affected engine: run_epd_single_node health-checks engines concurrently and the first exception unwinds the ExitStack, which terminates every other engine. So a clean SIGTERM/shutdown log on a healthy engine is a symptom, not the cause — find the one engine whose log ends in a traceback. Until the device is reset or the instance replaced, route around it by assigning explicit device slices (see Step 5), keeping every slice free of the faulted device and still aligned to its own TP degree.

  • Core-slice binding race on single node: Launch engines a few seconds apart (the run_epd_single_node launcher staggers Popens by 10 s) so they don’t race on NEURON_VISIBLE_DEVICES binding and the shared compile cache.

Clean up#

Stop all processes:

pkill -f "vllm serve"
pkill -f "disaggregated_encoder/server.py"
# The llm-d gateway, if a run was killed before it stopped it. The patterns
# match only an EPP and an Envoy that the launcher started.
pkill -f "llmd/epp_config.json"
pkill -f "llmd/envoy.json"

If you launched EC2 instances specifically for this tutorial, terminate them to avoid ongoing charges.

Next steps#

This document is relevant for: Trn2, Trn3