KV Cache VRAM Explosion When Deploying Multimodal LLMs
KV Cache VRAM Explosion When Deploying Multimodal LLMs
Search
Ask the AI

KV Cache VRAM Explosion When Deploying Multimodal LLMs

Calculate the cache before choosing an optimisation

High-resolution images and video can produce long prompts in Multimodal Large Language Models (MLLMs), including LLaVA, Qwen-VL and InternVL. The actual token count depends on the model’s image processor, tiling rules and token compression. Start with that count, calculate KV Cache memory, then measure prefill and decode separately.

KV Cache memory: one sequence and one token

During autoregressive inference, the decoder stores previous Keys and Values so that it can reuse them. For one sequence, assume that every decoder layer uses full attention, the same KV head count and head dimension, and a fixed number of stored bytes per cache element. Count element data here and quantisation metadata separately. The raw cache payload is:

Formula: \(VRAM_{KV} = 2 \times layers \times kv\_heads \times head\_dim \times seq\_len \times bytes\)

The formula above covers the whole sequence. Set seq_len to 1 for one token. The factors are:

  • 2: Key and Value tensors.
  • layers: Number of decoder layers; Llama-3-8B has 32.
  • kv_heads: Number of KV heads, which can differ from the query-head count.
  • head_dim: Dimension of each head.
  • seq_len: Number of cached tokens in this sequence.
  • bytes: Bytes per cache element, such as 2 for FP16/BF16 or 1 for the INT8 payload before quantisation metadata.

For B independent sequences of equal length, multiply the result by B. With different lengths, add each sequence’s payload. Physical allocation also depends on page rounding, reserved capacity, prefix sharing and quantisation metadata. Model weights, the vision encoder, the projector, activations and workspace require additional memory. Sliding-window layers retain only their active window; hybrid models therefore need a sum over the layers’ actual cache lengths. See the Transformers cache documentation.

Use KV heads, not query heads

In grouped-query attention (GQA), several query heads share Key/Value heads. The official Llama model registry gives Llama-3-8B 32 query heads and 8 KV heads, with a head dimension of 128. Substituting 32 for 8 overstates its raw cache payload by 4×.

seq, layers, head_dim, byt = 8000, 32, 128, 2
kv = lambda h: 2 * layers * h * head_dim * seq * byt / 2**30

kv(32)   # 3.91 GiB  -- attention heads, wrong
kv(8)    # 0.98 GiB  -- KV heads, correct

This example uses FP16 and 8,000 tokens. With 8 KV heads, one token occupies 131,072 bytes, or 128 KiB; the whole sequence occupies 0.9765625 GiB. Four independent sequences occupy 3.90625 GiB. Under the same numerical assumptions, MHA with 32 KV heads uses 3.90625 GiB per sequence, while MQA with one KV head uses 0.1220703125 GiB.

The config field is usually num_key_value_heads. Read its effective value and the model implementation: an absent field alone does not establish MHA. In MHA it equals num_attention_heads; in MQA it is 1; in GQA the query heads share groups of KV heads.

Separate cache growth from attention compute

For the full-attention cache defined above, seq_len appears to the first power: double the cached tokens, double the raw payload. Dense attention has a quadratic number of positions in its score matrix \(QK^T\). A naive implementation can also allocate that quadratic matrix in memory. FlashAttention processes tiles without storing the full score matrix, while retaining the quadratic arithmetic of dense attention.

Count the tokens after image preprocessing

For a toy patchifier with 14×14 patches, no resizing, no padding and no extra tokens, use integer patch counts. A 1024×1024 image gives \(\lfloor1024/14\rfloor^2 = 73^2 = 5329\) patches. The original 4K calculation is retained below; its intermediate values use integer truncation:

(3840 ÷ 14) × (2160 ÷ 14) = 274 × 154 ≈ 42,196 tokens

The corresponding calculation is \(\lfloor3840/14\rfloor \times \lfloor2160/14\rfloor = 274 \times 154 = 42196\). This is a patch-count illustration, not the output of a specific MLLM processor. For example, a 336×336 crop with 14×14 patches has 576 patches. Real processors resize, pad, tile, select features and add model-specific tokens; the LLaVA-NeXT documentation explains why token counts must match those settings.

At 42,196 tokens, the 32-layer, 8-KV-head, 128-dimension FP16 fixture above needs 5.15087890625 GiB of raw KV payload. This fixture does not describe every LLaVA checkpoint. Compare the actual image tokens plus text and planned output with the configured context limit, then add the other memory terms before deciding whether the full workload fits an A100 or another GPU.

AnyRes preserves detail; compression needs its own mechanism

LLaVA’s AnyRes implementation selects a resolution, pads and slices the image, and includes a resized global view. Multiple crops can produce more tokens than a single resized image. The diagram below is retained from the original article; its projector label needs correction.


graph TD
    A[Original High-Res Image 4K] --> B{AnyRes Dynamic Slicing}
    B --> C[Global View 
Resized to 336x336] B --> D[Local Patches
Sliced into NxM 336x336 grids] C --> E(ViT Vision Encoder) D --> E E --> F[Feature Concatenation] F --> G[Projector
MLP Downsampling/Compression] G --> H[LLM Backbone]

In the standard LLaVA linear/MLP projector, the projection changes feature width while preserving the number of tokens. The diagram’s “MLP Downsampling/Compression” label therefore does not establish token compression. Pooling, token selection or another compatible resampler must reduce the sequence explicitly. The relevant implementations are AnyRes preprocessing and the projector builder.

LLaVA inference: historical code and a versioned correction

Quantising decoder weights to 4 bits can reduce their storage and memory traffic. GGUF is a container format that supports multiple quantisation types; the vision encoder, projector and KV Cache have their own precision and memory requirements. The following original script is retained as a historical example. Its unpinned clone, make LLAMA_CUDA=1 build and llava-cli path require an older matching checkout.


#!/bin/bash
# Clone and build llama.cpp with CUDA hardware acceleration support
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
make LLAMA_CUDA=1

# Download quantized multimodal model (LLaVA-1.5-7b) and vision projector (mmproj)
wget https://huggingface.co/mys/ggml_llava-v1.5-7b/resolve/main/ggml-model-q4_k.gguf
wget https://huggingface.co/mys/ggml_llava-v1.5-7b/resolve/main/mmproj-model-f16.gguf

# Run llava-cli for multimodal image-text inference
./llava-cli \
  -m ggml-model-q4_k.gguf \
  --mmproj mmproj-model-f16.gguf \
  --image /path/to/high_res_input.jpg \
  -p "Describe the image in detail, paying attention to the intricate textures." \
  -c 4096 \
  -ngl 35 # Offload specific layers to GPU VRAM

Corrected example for b10216: this version uses CMake with GGML_CUDA=ON and llama-mtmd-cli. These names and arguments were checked against the versioned build instructions and multimodal CLI documentation. The model and projector must be a matching pair. The example was syntax-checked; GPU build and inference were not rerun for this correction.

# Corrected example: llama.cpp b10216; source-checked, not a new GPU benchmark
set -eu
git clone --branch b10216 --depth 1 https://github.com/ggml-org/llama.cpp.git llama-cpp-b10216
cmake -S llama-cpp-b10216 -B llama-cpp-b10216/build -DGGML_CUDA=ON
cmake --build llama-cpp-b10216/build --config Release -j

# Use the matching LLaVA model and mmproj downloaded in the historical example.
llama-cpp-b10216/build/bin/llama-mtmd-cli \
  -m ggml-model-q4_k.gguf \
  --mmproj mmproj-model-f16.gguf \
  --image /path/to/high_res_input.jpg \
  -p "Describe the image in detail." \
  -c 4096 \
  -ngl 35

Measure prefill and decode separately

A long visual prompt can make prefill dominate time-to-first-token. Long outputs, large batches or a slow cache-reading kernel can make decode significant too. Record image preprocessing and encoding time, queue time, prefill time, time-to-first-token and the mean interval between output tokens.

  • Prefill: dense attention scales with \(n^2\): it has 25 million score positions per head per layer at n = 5,000, and 1.764 billion at n = 42,000, a ratio of 70.56× (about 70×). These are matrix-position counts, not total model FLOPs or a measured runtime ratio. Causal masking and the kernel affect the operations performed.
  • Decode: each new token attends to the retained cache. For full attention, the attention work grows with \(n\), and the raw cache payload also grows with \(n\), where n is the retained sequence length. Other layers, batching and the memory backend also affect runtime.

Choose the optimisation from those measurements:

  1. Reduce visual tokens when the task permits it. With dense attention, reducing 42,000 tokens to 3,000 reduces the quadratic attention term to 1/196 and the raw cache term to 1/14. End-to-end prefill includes other work, so its runtime need not fall by 196×. AnyRes tiling alone does not provide this reduction; use a compression mechanism that the model supports and check detail-sensitive tasks.
  2. Reduce cache precision when cache memory binds. INT8 halves the element payload relative to FP16 before metadata. Accuracy, kernel support and latency require validation. Quantisation does not change the quadratic dependence of dense attention, but it can affect time-to-first-token through bandwidth, conversion and scheduling.
  3. Use paged management when fragmentation or concurrency binds. PagedAttention limits allocation waste and supports cache sharing. It can improve throughput and latency; it does not remove the attention operations required by a sequence or guarantee that every workload fits.

For the weights, cache and fixed-overhead terms, see Turning Three Known VRAM Traps Into a Working Estimator. Tensor-parallel KV placement is implementation-specific: vLLM v0.19.0 can replicate KV heads when the parallel degree is at least the KV-head count, so simple divisibility by GPU count is not a universal requirement. The site’s VRAM calculator covers the Gemma 4 variants under its stated assumptions.

Two deployment checks

1. Diagnose OOM from the allocation terms

FlashAttention’s tile or block size is not a maximum sequence length: the kernel processes multiple tiles. For an OOM, inspect weights, KV allocation, temporary workspace, batching and backend limits. Paging reduces fragmentation and improves sharing; physical memory still sets a capacity limit.

2. Keep the visual history that the next question needs

Repeated images and frames consume context and cache capacity. Keep the images needed for follow-up questions, remove redundant frames, and reserve room for output. Replacing an image with a text summary trades visual detail for a shorter context. Token Merging (ToMe) was developed for vision transformers; using it after an arbitrary MLLM projector requires a compatible integration and task-level validation.

Leave a Reply

Scroll down