Home / AI & GenAI

AI & GenAITroubleshootingAdvanced

vLLM vision model requests fail or run out of memory: image limits, encoder cache, media fetches and SSRF

Fix vLLM multimodal problems. Covers prompt-length errors from large images, GPU and host memory growth, slow media fetches, cache misses behind load balancers and blocking SSRF.

Deepak Bhardwaj7 min read

Applies tovLLM OpenAI-compatible server with vision-language models; flag names vary by version

A vision model on vLLM passes its smoke test, then production sends phone photos and multi-page scans. Requests return 400, pods are OOMKilled, or TTFT jumps while the GPU looks idle. Text-only tuning doesn't explain these, because images add three stages before prefill: fetch, preprocess on CPU, and encode on GPU.

Find the failing stage

Symptom Stage Likely cause Fix
400 mentioning a limit on images Validation More items than --limit-mm-per-prompt Raise the limit or send fewer images
400 about prompt or context length Preprocess Image expands to thousands of tokens Resize, or cap pixels
4xx naming a media URL Fetch Timeout, blocked domain, no egress Fix egress, or send base64
TTFT high, GPU idle Fetch or preprocess Slow URLs or CPU starved Give CPU, resize at the gateway
Container OOMKilled, GPU fine Preprocess Media decode plus per-process caches Size caches and memory limit
CUDA OOM at startup or on large images Encode Encoder memory, or profiling skipped Cap pixels, restore profiling
Repeated image is slow each time Cache Requests land on different replicas Affinity, or stable UUIDs

Start with the server's own view:

curl -s localhost:8000/metrics | grep -E 'time_to_first_token|num_requests_(running|waiting)|mm_cache'
kubectl top pod -l app=vllm-vision --containers
kubectl describe pod -l app=vllm-vision | grep -A5 'Last State'
nvidia-smi dmon -s um -c 10

Metric names vary by version; check your build's /metrics output. If TTFT is high, waiting is near zero and GPU utilisation is low, the time is going before the scheduler.

Measure image tokens before blaming the model

Image token counts depend on the model's processor and usually on the resolution. Don't estimate them from text. Ask the server:

import base64
import io
import sys
from openai import OpenAI
from PIL import Image

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
model = client.models.list().data[0].id

def prompt_tokens(img: Image.Image) -> int:
    buf = io.BytesIO()
    img.convert("RGB").save(buf, "JPEG", quality=90)
    url = "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
    r = client.chat.completions.create(
        model=model, max_tokens=1,
        messages=[{"role": "user", "content": [
            {"type": "text", "text": "x"},
            {"type": "image_url", "image_url": {"url": url}}]}])
    return r.usage.prompt_tokens

src = Image.open(sys.argv[1])
for side in (512, 1024, 1536, 2048, 4096):
    im = src.copy()
    im.thumbnail((side, side))
    print(im.size, prompt_tokens(im))

The last line tells you what one uncapped phone photo costs. Multiply it by the images per prompt and compare with --max-model-len. The KV cache pays for those tokens too, so ten 4,000-token images use as much cache as a 40,000-token document.

Cap resolution in two places

Resize at the gateway so that bytes never reach the GPU pod, and set a server-side cap for clients that bypass it. The processor option is model-specific. For the Qwen2-VL family the vLLM documentation uses max_pixels:

vllm serve /models/vision-model \
  --limit-mm-per-prompt '{"image": 4, "video": 0}' \
  --mm-processor-kwargs '{"max_pixels": 1003520}' \
  --max-model-len 32768

Re-run the script afterwards. If the numbers don't change, your model's processor ignores that key and you need its own name. Re-run your accuracy tests too: small text in scans is the first thing lost.

Warning

Recent vLLM versions reject per-request mm_processor_kwargs unless the server runs with --trust-request-mm-kwargs. Leave that off for untrusted clients: otherwise one caller can raise the pixel cap for everyone's GPU.

GPU memory: the encoder is part of the budget

At startup vLLM profiles encoder memory, then gives the remainder to KV cache. The largest allowed item and the item limits affect that profile.

  • Unused modality: set its count to 0, for example "video": 0.
  • Text-only use of a multimodal checkpoint: use --language-model-only, which sets every modality limit to 0.
  • --skip-mm-profiling: shortens startup, but you now own the estimate. If OOMs appeared after this flag was added, remove it first.
  • --mm-encoder-tp-mode data: splits the image batch across tensor-parallel ranks, for models that support it. Every rank holds the full encoder weights, so it can OOM a model that barely fitted.

The encoder compute budget and encoder cache are derived from --max-num-batched-tokens by default. A low value chosen for smoother inter-token latency also limits how much encoder work is scheduled per step. If TTFT on image traffic got worse after you lowered it, test a higher value under real image load.

Host memory: caches multiply per process

The multimodal processor cache defaults to 4 GiB, and with the default lru type it is kept per process. Documented total use is:

mm_processor_cache_gb * (api_server_count + data_parallel_size)

With --api-server-count 4 and --data-parallel-size 2, the default becomes 4 × (4 + 2) = 24 GiB of host memory for cache alone. Decode buffers come on top. Options:

# smaller cache
--mm-processor-cache-gb 1
# shared-memory cache for multi-process setups
--mm-processor-cache-type shm

The shm type needs enough /dev/shm. In Kubernetes, mount an emptyDir with medium: Memory, and count it towards the memory limit:

volumes:
  - name: dshm
    emptyDir: {medium: Memory, sizeLimit: 12Gi}
containers:
  - name: vllm
    volumeMounts:
      - {name: dshm, mountPath: /dev/shm}

Adding API servers helps CPU-bound preprocessing, but it also disables multimodal IPC caching, which needs one API process per engine process. Each API server also starts media-loading threads (8 by default, set by VLLM_MEDIA_LOADING_THREAD_COUNT). On a pod limited to 4 CPUs, four API servers oversubscribe badly.

Media fetches: timeouts and SSRF

When the request contains a URL, the vLLM pod fetches it. Two problems follow.

Latency and failures. The default image timeout is short, and video gets longer:

export VLLM_IMAGE_FETCH_TIMEOUT=10
export VLLM_VIDEO_FETCH_TIMEOUT=60

Test from the pod, not from your laptop:

kubectl exec deploy/vllm-vision -- python3 -c "
import time, urllib.request
t=time.time()
d=urllib.request.urlopen('https://media.example.com/test.jpg', timeout=10).read()
print(len(d), round(time.time()-t,2))"

Server-side request forgery. A caller can point the URL at an internal service or the cloud metadata address.

Caution

Never run a multimodal endpoint with unrestricted media URLs inside a trusted network. Restrict domains, disable redirects so an allowed site can't bounce to an internal one, and enforce egress at the network layer too.

export VLLM_MEDIA_URL_ALLOW_REDIRECTS=0
vllm serve /models/vision-model --allowed-media-domains media.example.com
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: vllm-vision-egress}
spec:
  podSelector: {matchLabels: {app: vllm-vision}}
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}
      ports: [{port: 53, protocol: UDP}, {port: 53, protocol: TCP}]
    - to:
        - ipBlock: {cidr: 203.0.113.0/24}   # your media proxy
      ports: [{port: 443, protocol: TCP}]

The safest design has the gateway fetch, scan, resize and send base64, with no egress from the GPU pod. Check the body-size limits on every proxy, because base64 adds about a third. --allowed-local-media-path has a similar risk: it lets API callers read images from a server directory, so leave it unset unless needed.

Repeated images that never hit the cache

Multi-turn chat resends the same image every turn. If the URL is signed, or the client re-encodes it, the bytes or the string differ. Supply a stable ID per item:

{"type": "image_url",
 "image_url": {"url": "https://media.example.com/p.jpg?sig=abc"},
 "uuid": "tenant42:sha256-of-original"}

Derive the UUID from the content plus the tenant, on the server side. If clients choose it, a collision can return the wrong image's features. If both processor caching and prefix caching are off, UUIDs are ignored. A later request may omit the media and send only the UUID, but it fails on a miss, so retry with the bytes. Route by conversation, because caches are per replica.

Prevent it next time

  • Load test with your real resolution distribution, including the 99th percentile image.
  • Record prompt_tokens split by image count, and alert when the average moves: a client SDK change often removes resizing.
  • Set explicit limits for every modality at deploy time instead of relying on defaults.
  • Keep the SSRF test in CI: request http://169.254.169.254/ as an image and require an error, with no outbound connection.
  • Re-run the token script on each model or vLLM upgrade.