Pidoku

Multimodal Inputs

Module 18 Lesson 18.h 45 min Difficulty 4/5

Prerequisites 16.e, 18.b, 17.f


Before you start: words you need#

WordPlain meaning
Vision-language modelA language model that also takes images (and sometimes video or audio) as input.
EncoderThe part that turns an image into vectors the language model can read, often a vision transformer (ViT).
Placeholder tokensDummy tokens put in the prompt where an image goes, one per vector the encoder will produce.
ProcessorModel-specific code that resizes and tiles an image and decides how many placeholders it needs.
PatchA small square of pixels (often 14 or 16 pixels a side) that the encoder treats as one unit.
Content hashA fingerprint of an image’s bytes; the same image always gets the same hash.
SSRFServer-side request forgery: tricking a server into fetching an internal URL for you.

1. What is it?#

A vision-language model does not read pixels. An encoder turns an image into a few hundred or a few thousand vectors that look, to the language model, like token embeddings. vLLM fits this into its text machinery with one device: in the token list, an image is a run of placeholder tokens, one per vector. Everything built for text (the token budget, chunked prefill, block hashes, the prefix cache) then works on the placeholders unchanged.

Around that sit three pieces of plumbing: fetching and preprocessing media on the CPU, running the encoder on the GPU under its own budget, and three caches so the same image is never processed twice. Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

  • Images are expensive tokens. One high-resolution image can cost as much context and KV cache as several thousand words.
  • The bottleneck moves. Image-heavy traffic is often limited by API-server CPU (decoding, resizing) before the GPU.
  • Security. A server that fetches URLs for clients is an SSRF risk unless restricted.
  • Caching pays. Chat apps resend the same image with every turn; without caches each turn re-runs the processor, the encoder and the language model over it.

3. Simple analogy#

A meeting transcript has a note “[photo, see appendix pages 4–9]”. The note takes up six pages of the binder, so page numbering, binder size and photocopying all work as for text. A separate person (the encoder) produces the appendix pages when the reader reaches them, and a copy is kept so the same photo is never redrawn.


4. Tiny example#

request     "What is in this image?" + cat.jpg (1920 × 1080)
processor   resize/tile, compute: 4,096 vectors          -> 4,096 placeholder tokens
prompt      [text tokens ...] <P> <P> ... <P> (4,096) [text tokens ...]
scheduler   budget 8,192 tokens/step: text + all placeholders fit in one step
worker      run the encoder for cat.jpg, overwrite the 4,096 placeholder embeddings
second turn same image: processor cache hit, prefix cache hit on its KV blocks

5. Technical explanation#

The request#

The OpenAI chat format carries media as content parts:

JSON
{"role": "user", "content": [
  {"type": "text", "text": "What is in this image?"},
  {"type": "image_url", "image_url": {"url": "https://example.com/cat.jpg"}}
]}

video_url, input_audio and audio_url work the same way. A URL may be https:, a base64 data: URL, or, only if you enable it, a local file: path.

Step 1: fetch and decode, in the API server#

The API server (16.e) downloads and decodes media on a thread pool (VLLM_MEDIA_LOADING_THREAD_COUNT, default 8). This is CPU and network work that never touches the engine core.

warning

A server that fetches URLs for clients can be made to fetch internal URLs: cloud metadata endpoints, admin panels, other services. Set --allowed-media-domains. Local file access is off unless you pass --allowed-local-media-path; point it at a directory containing nothing else.

Limits are part of the contract: --limit-mm-per-prompt.image 2 rejects requests with more than two images. Because each image can add thousands of tokens, the limits also bound memory.

Step 2: the processor and the placeholders#

Each model family has a multimodal processor that:

  1. Turns the decoded image into the tensor the encoder expects (resize, tile, normalise).
  2. Works out how many vectors the encoder will produce and replaces the single image marker in the prompt with that many placeholder tokens.
before:  <s>[INST]What is in this image?\n[IMG][/INST]
after:   [1, 3, 7493, 1681, 1294, 1593, 3937, 9551, <P>, <P>, ..., <P>, 4]

The count depends on the model and often on the image’s size and aspect ratio. It is the real cost of an image: each placeholder takes a position in the context window and a slot in the KV cache of every layer, exactly like a word. The processor also records each item’s position (offset and length in the token list) and an identifier, a hash of its content.

Step 3: three caches#

Some Hugging Face processors are, in the design document’s words, “very slow”, so vLLM caches at three levels:

CacheWhereKeyed byHoldsSaves
Processor cacheAPI server and engine coreContent hashThe processed tensorRe-running the processor
Encoder cacheWorker (GPU)Content hashEncoder output embeddingsRe-running the encoder while a request needs it
Prefix cacheEngine core + GPUBlock hash including the content hashThe language model’s KV for placeholder blocksRe-running the language model over the image

The processor cache defaults to 4 GiB per process (--mm-processor-cache-gb; total memory is that times api_server_count + data_parallel_size). The API server keeps the keys, the engine core keeps the values: when an image the engine already holds is sent again, only its hash crosses the socket. If the two fall out of step, the engine reports a retryable multimodal_cache_miss, the API server forgets the stale key, and the retry carries the data.

The prefix cache needed one addition. Placeholder tokens are identical for every image, so two different pictures of the same size would hash the same. Hence the extra key (17.f), from vllm/v1/core/kv_cache_utils.py:

Python
# The block contains the current mm input. Include its offset
# relative to the start of the block so prefix-cache keys stay
# distinct when the same MM item appears at different positions
# within otherwise-identical placeholder blocks.
extra_keys.append(("mm", mm_feature.identifier, offset - start_token_idx))

A second question about the same image reuses its KV blocks and computes only the new text.

Step 4: scheduling the encoder#

The scheduler treats placeholders as tokens but must also decide when the encoder runs. A vision encoder is a sizeable model; running ten in one step would blow the step time. So the encoder has its own budget (encoder_compute_budget = self.max_num_encoder_input_tokens) and cache accounting. Both max_num_encoder_input_tokens and the encoder cache size default to max_num_batched_tokens.

For each request with media, _try_schedule_encoder_inputs checks whether this step’s token range overlaps an item not yet encoded, and whether the encoder budget and cache can take it. If not, the chunk is cut short to end just before the item, and the image waits for a later step.

By default a chunk may end in the middle of an image’s placeholders. For models that need a whole image in one forward pass, --disable-chunked-mm-input forbids that: the config’s example is TTTT in one step and IIIIIIIIII in the next, rather than TTTTIIIII and IIIII.

Step 5: in the model runner#

When the batch reaches the worker (18.b):

  1. For each item scheduled this step and not in the encoder cache, run the encoder and store the embeddings. In Model Runner V2 this is vllm/v1/worker/gpu/mm/encoder_runner.py and encoder_cache.py.
  2. Look up ordinary embeddings for all input_ids, placeholders included.
  3. Overwrite the rows at placeholder positions with the matching slice of encoder output. With chunked prefill this may be only part of an image.
  4. Run the language model as usual. Models with multi-dimensional rotary positions (M-RoPE, as in Qwen-VL) also get special position IDs for the image tokens.

Embeddings leave the encoder cache once the request has consumed all of an item’s placeholders; the scheduler tells the worker which hashes to free (free_encoder_mm_hashes).


6. Under the hood#

Pixels travel as bytes#

Older pipelines normalised on the CPU and shipped 16-bit floats. With mm_device_do_normalize (on by default in v0.32.0, for models that support it) the path keeps uint8 all the way to the device and normalises there in one fused kernel:

Before: CPU decode → CPU resize → CPU rescale (÷255) → CPU normalize
        → cast to bf16 → PCIe (2 B/elem) → GPU
After:  CPU decode → CPU resize → uint8 pixel_values
        → PCIe (1 B/elem) → GPU fused affine (fp32 compute) → bf16

Half the bytes over the socket and the bus, and less CPU.

Encoder CUDA graphs#

Decoder CUDA graphs (18.d) do not cover the vision encoder. -cc.cudagraph_mm_encoder=true captures the encoder too, per token-budget level, for supported models (Qwen3-VL, InternVL, Gemma 3 and 4, GLM-4.xV, DeepSeek-OCR and others listed in the design document). It is off by default.

The encoder can live elsewhere#

A disaggregated-encoder deployment runs vision encoders in separate vLLM instances that publish embeddings through an encoder-cache connector; language-model instances fetch them instead of encoding. It is prefill/decode disaggregation (19.b) applied to a different stage.

What an image costs#

The formula is the common one for patch-based encoders: one vector per patch, optionally merged in small groups.

Go
package main

import "fmt"

type encoder struct {
	name  string
	patch int // pixels per patch side
	merge int // patches merged per side into one token (1 = none)
	tile  int // images larger than this are split into tiles (0 = resize instead)
}

func ceilDiv(a, b int) int { return (a + b - 1) / b }

// tokens returns the number of placeholder tokens for a w x h image.
func (e encoder) tokens(w, h int) int {
	if e.tile == 0 {
		// Fixed-resolution encoder: every image is resized to one size.
		side := 336 / e.patch
		return side * side / (e.merge * e.merge)
	}
	// Tiling encoder: a global thumbnail plus one grid of patches per tile.
	tiles := ceilDiv(w, e.tile) * ceilDiv(h, e.tile)
	perTile := (e.tile / e.patch) * (e.tile / e.patch) / (e.merge * e.merge)
	return (tiles + 1) * perTile
}

func main() {
	encoders := []encoder{
		{"fixed 336px, patch 14", 14, 1, 0},
		{"tiled 448px, patch 14, 2x2 merge", 14, 2, 448},
	}
	images := [][2]int{{336, 336}, {1024, 768}, {1920, 1080}, {3840, 2160}}
	const kvBytesPerToken = 131072 // an 8B-class language model, 16-bit cache
	const budget = 8192            // max_num_batched_tokens

	for _, e := range encoders {
		fmt.Println(e.name)
		fmt.Printf("  %-12s %8s %14s %18s\n", "image", "tokens", "KV cache", "steps to prefill")
		for _, im := range images {
			n := e.tokens(im[0], im[1])
			fmt.Printf("  %4dx%-7d %8d %10.0f MiB %18d\n",
				im[0], im[1], n, float64(n*kvBytesPerToken)/(1<<20), ceilDiv(n, budget))
		}
		fmt.Println()
	}

	n := encoders[1].tokens(1920, 1080)
	fmt.Printf("a 1920x1080 image costs %d tokens: about %d words of English in context,\n", n, n*3/4)
	fmt.Printf("and ten such images in one request need max_model_len of at least %d\n", 10*n)
}

Output:

fixed 336px, patch 14
  image          tokens       KV cache   steps to prefill
   336x336          576         72 MiB                  1
  1024x768          576         72 MiB                  1
  1920x1080         576         72 MiB                  1
  3840x2160         576         72 MiB                  1

tiled 448px, patch 14, 2x2 merge
  image          tokens       KV cache   steps to prefill
   336x336          512         64 MiB                  1
  1024x768         1792        224 MiB                  1
  1920x1080        4096        512 MiB                  1
  3840x2160       11776       1472 MiB                  2

a 1920x1080 image costs 4096 tokens: about 3072 words of English in context,
and ten such images in one request need max_model_len of at least 40960

The fixed-resolution encoder charges the same for a thumbnail and a 4K frame because it shrinks everything. The tiling encoder keeps detail and its cost grows with pixel count. Knowing which kind your model has is the first step in setting --limit-mm-per-prompt and --max-model-len.


7. Performance implications#

  • Placeholder count drives everything: context length, KV cache, prefill time. Resize images on the client if the task does not need full resolution.
  • Encoder budget limits how many images are encoded per step; a burst of image requests can delay the text tokens of others.
  • Caches turn a repeated image into a near-free hash lookup, a skipped encoder run and a prefix-cache hit.
  • CPU in the API server is often the first limit for image traffic. Add API server processes (--api-server-count) and cores.
  • Encoder CUDA graphs help small, frequent images, where encoder launch overhead dominates.

8. Production implications#

  • Restrict fetching: --allowed-media-domains, no --allowed-local-media-path unless needed, and network egress policy.
  • Set --limit-mm-per-prompt for every modality you allow.
  • Size max_model_len for text plus placeholders. The validation error says so: make sure max_model_len covers the “number of text tokens plus multimodal tokens”.
  • Memory: encoder weights and peak activations count as non-KV memory (17.h); the processor cache is per process in CPU memory.
  • Startup: encoders have their own profiling, compilation and (optionally) graph capture.

9. Common mistakes#

  1. Counting an image as one token when sizing context or cost.
  2. Leaving URL fetching unrestricted on a public endpoint.
  3. Scaling GPUs for image traffic when the API server’s CPU is the bottleneck.
  4. Expecting different images of the same size to share cache. The content hash keeps them apart.
  5. Forgetting video: a video is many frames, each with its own placeholders, and can exceed the token budget on its own.

10. Hands-on exercise#

  1. Add an encoder with a 3×3 merge. How much does it save on a 4K image, and what might it cost in fine detail?
  2. Using the tiled encoder, what --limit-mm-per-prompt.image keeps a request within a 32,768-token context if images are at most 1920×1080 and text is at most 2,000 tokens?
  3. On a real multimodal server, send the same image twice with different questions and compare usage.prompt_tokens_details.cached_tokens. Then send a different image of the same size.
  4. Measure API-server CPU while sending 50 concurrent 4K images. Then double --api-server-count.

11. Interview questions#

  1. Why does representing an image as placeholder tokens let the scheduler treat it like text?
  2. Two different images produce identical placeholder tokens. What keeps the prefix cache from confusing them?
  3. Which process downloads an image URL, and what is the security risk of letting it fetch any URL?
  4. Why does the encoder have its own per-step budget?
  5. How does keeping pixels as uint8 until the GPU help?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in