The Cost of Visual Tokens in Multimodal LLMs and How to Optimize It

    This article breaks down why image inputs increase inference cost in multimodal large language models, provides a simple script to estimate KV cache memory from image resolution and model configuration, and outlines practical optimization paths—including resolution selection, token compression, sparse attention, structured coordinate output, and result caching. It also covers engineering considerations for data pipelines, inference chain changes, evaluation metrics, and the role of visual signals in AI agents, ending with a scenario-based selection guide.

    1. Why Visual Input Is Expensive

    When large language models process text, cost scales mainly with sequence length. Adding images changes the picture. An image is first divided into patches by a vision encoder; each patch corresponds to one or more visual tokens, which are fed into the model together with text tokens. The higher the image resolution, the finer the patches and the greater the number of visual tokens.

    For a common patch-based approach, a 1024×1024 image split into 16×16 patches yields 64×64 = 4096 visual tokens. If a single request contains multiple images, or the user keeps referring to the same image in follow-up turns, these tokens remain in the context window.

    The cost comes from two main sources. First, attention computation during the prefill phase. Standard attention has computational complexity proportional to the square of the sequence length, so longer sequences increase the per-token cost. Second, KV cache. Each token must store keys and values for every layer, so memory usage grows linearly with token count. Combined, visual input often multiplies the inference cost of a single request.

    2. Estimating Visual Cost with a Script

    Before making architecture decisions, you can write a rough estimation script that converts image size, patch settings, and model structure into token counts and memory usage. The example below only demonstrates the calculation method; parameters should be replaced with your actual model configuration.

    1. function visual_token_count(width, height, patch_size=16, merge_factor=1):
    2. cols = width // (patch_size * merge_factor)
    3. rows = height // (patch_size * merge_factor)
    4. return cols * rows
    5. function kv_cache_bytes(token_count, num_layers, num_kv_heads, head_dim, bytes_per_element=2):
    6. # formula: 2 (key and value) × layers × KV heads × head dim × tokens × bytes per element
    7. return 2 * num_layers * num_kv_heads * head_dim * token_count * bytes_per_element
    8. token_count = visual_token_count(1024, 1024, patch_size=16) # result: 4096
    9. memory_bytes = kv_cache_bytes(token_count, num_layers=32, num_kv_heads=8, head_dim=128)
    10. print("KV cache for one image: ~", memory_bytes / 1024**2, "MiB") # result: ~512 MiB

    This result shows that a single medium-resolution image can occupy hundreds of MiB of KV cache. As concurrent requests increase, memory quickly becomes the bottleneck.

    3. Common Strategies to Reduce Visual Token Cost

    1. Choose Resolution Based on the Task

    Most tasks do not require full resolution. Document recognition, UI screenshot verification, and small-field reading need high resolution. Scene classification and coarse description can use lower resolution. At the request entry point, decide the patch parameters based on the task type instead of always using the maximum size.

    2. Compress Visual Tokens

    Common methods include merging adjacent patches, using a small number of learnable query vectors to resample visual features, and merging redundant tokens in intermediate network layers. Compression reduces token count at the cost of potential detail loss. Teams must run evaluations to confirm whether the accuracy drop is acceptable for the business.

    3. Sparse Attention and Cache Compression

    Standard attention computes pairwise interactions between all tokens. Sparse attention keeps only a subset of connections, reducing computation. KV cache compression reduces memory usage via quantization or pruning. These methods change the model’s attention behavior and usually need adaptation during training or fine-tuning.

    4. Bring Structured Coordinates into the Reasoning Chain

    Let the model output structured information such as point coordinates and bounding boxes during reasoning, then use that to revisit local regions of the image. The model only reads details when needed; most image areas do not enter the context at high resolution. This approach lets the model decide where to focus, making it suitable for localization, counting, and reading charts.

    5. Reuse Computed Results

    When the same image is referenced repeatedly in multi-turn dialogue, cache the visual encoding output and the corresponding KV cache, then reuse them in subsequent turns. The server needs to set expiration policies and capacity limits for the cache, and isolate it per session to prevent data leakage between users.

    4. Engineering Costs in Practice

    Data Pipeline

    Visual capabilities rely on annotated data. A common workflow includes image collection and labeling, removal of duplicates and low-quality samples, stratified sampling by category and difficulty, and manual or rule-based spot checks of annotation quality. Each filtering round reduces the available sample size, so teams need to reserve enough data volume and time.

    Inference Chain Modifications

    If you introduce coordinate or region outputs, the training data must include the corresponding reasoning process, not just the final answer. Prompt templates, output formats, and parsing logic all need to be updated. Fallback strategies for parse failures, such as retry or degradation to full-image input, are required.

    Evaluation System

    It is recommended to establish at least three categories of metrics: task accuracy, per-request token count and latency, and memory usage. Focusing only on accuracy ignores cost; focusing only on cost may hide functional regression. The evaluation set should cover typical business images, including hard cases like blur, low light, and dense text.

    5. Vision in Agent Workflows

    When an agent executes a task, it often needs to verify whether the previous action took effect. For example, automated testing confirms page navigation, an operations assistant reads monitoring dashboard screenshots, and office automation checks form results. In these cases, visual information serves as a verification signal for execution results.

    When incorporating vision into the execution loop, two points deserve attention. First, control the frequency of screenshots. Taking full snapshots at every step quickly consumes the inference budget. Second, combine visual signals with text signals such as API return codes, logs, and page structure data. Vision should only supplement what text cannot cover.

    If you build such a service on Baidu AI Cloud, you can use object storage to save screenshots, a message queue to decouple collection from inference, and logging and monitoring alerts to track token consumption and latency for each request.

    6. Selection Guide by Scenario

    Scenario Recommended Approach Key Focus
    Document and table recognition High-resolution patch splitting, keep details Recognition accuracy, token count per page
    UI screenshot verification Local cropping, on-demand screenshots Screenshot frequency, end-to-end latency
    Coarse image classification Low resolution, token compression Throughput, unit cost
    Multi-turn image Q&A Cache visual output and KV cache Cache hit rate, session isolation

    A suggested implementation order is as follows. First, use an estimation script to evaluate the budget. Then, run small-scale real-world tests to measure both accuracy and cost. Finally, scale up gradually and set alert thresholds for unit cost.