Understanding Vision Encoder Architecture and Selection in Multimodal Models
This article provides a technical deep dive into the structure and selection of vision encoders for multimodal large language models. It covers image preprocessing, patch embedding and merging, token budget control, parameter estimation, forward inference workflows, precision selection, and practical engineering considerations for deployment and performance tuning.
Why Vision Inputs Need Deep Integration with Language Models
When multimodal models process images, the core challenge is converting pixels into vector sequences that a language model can understand. Early approaches typically fed images to a separate recognition model and then passed the text output to the language model. This design loses information in the intermediate steps—such as coordinate relationships in charts, widget layouts in UI screenshots, and indentation hierarchies in code screenshots.
Architectures where the vision encoder is natively integrated with the language model allow the model to decide during generation when to inspect the image and which regions to focus on, adjusting subsequent actions based on visual feedback. This design is particularly important in scenarios such as vision-assisted programming, UI automation, and document understanding. Understanding these use cases starts with understanding how a vision encoder converts images of arbitrary size into a regularized sequence of tokens.
Preprocessing: Normalizing Arbitrary Resolution Images into a Computable Grid
Size Alignment and Zero Padding
Input images come in vastly different resolutions. Most vision encoders require input dimensions to be a multiple of some base value; otherwise, convolution patching and subsequent merging operations produce incomplete boundaries. A common practice is to resize the image to an appropriate scale, then pad the right and bottom edges with zeros so that width and height are multiples of the target value.
Assuming a patch size of 14 and a merge window of 2×2, one merged unit covers an edge length of 14 × 2 = 28 pixels. Image width and height both need to be padded to a multiple of 28. The padded pixels carry no visual information but ensure every grid cell is complete, avoiding truncated features at boundaries.
Resizing strategy involves a trade-off between fidelity and efficiency. Aspect-ratio-preserving scaling with padding maintains the proportions of objects, which suits tables, charts, and code screenshots. Directly stretching to a fixed size is simpler to implement but distorts text and geometric relationships, typically reducing recognition accuracy.
Patch Splitting and 2×2 Merging
After alignment, images are split into base patches of 14×14 pixels. For a 560×392 image, this yields 40 patches along the width and 28 along the height—1,120 base patches in total.
A 2×2 merge then combines four adjacent base patches into a larger unit. The resulting grid becomes 20×14, with 280 units. Each unit corresponds to a 28×28 pixel region of the original image, which forms the basis for computing vision token counts.
The merge operation serves two purposes. First, it shortens sequence length to one-quarter of the original, significantly reducing computational cost in subsequent attention layers. Second, it aggregates local neighborhood information so the visual representation passed to the language model reflects “region”-level semantics rather than isolated pixel blocks.
Token Budget Control
The same image may have entirely different token budgets in different scenarios. High-resolution screenshots require more tokens to preserve detail, while ordinary images need only a few tokens to describe the main content. In practice, implementations typically define two boundary parameters:
min_image_tokens: the minimum token count per image, preventing small images from losing too much information after scaling;max_image_tokens: the maximum token count per image, preventing large images from filling up the context window.
When the raw grid count of an image exceeds the upper limit, resolution is proportionally reduced until the token count falls within budget. When the result falls below the lower limit, the image is upscaled. The values of these two boundaries should be determined together based on context length, concurrent request volume, and task type. For multi-image conversations, the sum of all image budgets and the text portion must fit within the context window.
Encoder Architecture: An Illustrative Configuration and Parameter Calculation
A vision encoder typically uses a Transformer-based ViT structure. The following configuration is provided as a calculation example to illustrate relationships between parameters. These values are illustrative only and do not represent any specific product’s actual parameters.
| Configuration Item | Illustrative Value | Description |
|---|---|---|
| Depth | 24 | Number of stacked Transformer blocks |
| Hidden size | 1024 | Feature width per token |
| Attention heads | 16 | Number of parallel subspaces in multi-head attention |
| Head dimension | 64 | 1024 / 16 |
| Patch size and merging | 14 / 2×2 | Determines pixel coverage per vision token |
| Output dimension | 4096 | Aligned with language model hidden dimension |
In this example, the head dimension is 64, indicating that no grouped query attention is used—attention heads do not share key/value projections. This choice slightly increases GPU memory usage but simplifies implementation and improves compatibility.
Estimating Parameter Count
To estimate the parameter count of a vision encoder, calculations can be decomposed per block. Let h be the hidden dimension and m the MLP intermediate dimension:
- Self-attention includes four matrices—Q, K, V, and output projection—amounting to approximately 4h² parameters;
- A standard two-layer MLP has approximately 2hm parameters; with a gated linear unit structure (e.g., SwiGLU), this becomes about 3hm;
- Each block’s parameter count is the sum of these two parts, and the total is the per-block count multiplied by the number of layers, plus input and output projection parameters.
With h = 1024 and m = 4h, a standard MLP block has approximately 4.2M (attention) plus 8.4M (MLP) parameters, totaling about 12.6M per block. For 24 layers, this is roughly 302M. Real models with wider gated MLPs or additional projection layers will have larger totals. The purpose of estimation is to assess the vision encoder’s share of total model parameters, informing decisions about inference precision and deployment strategy.
Forward Inference Workflow
The pseudo-code below shows a typical vision encoder execution sequence. Actual implementations may adjust details based on the framework, but the main steps remain consistent.
def encode_image(pixel_values, grid_thw):# 1. Generate 2D position indices based on grid informationpos_ids = build_2d_position_ids(grid_thw)# 2. Compute cumulative lengths of variable-length sequences for attention isolation in multi-image batchingcu_seqlens = build_cumulative_lengths(grid_thw)# 3. Apply convolutional patching to obtain base patch featuresx = patch_embed(pixel_values)# 4. Generate 2D rotary position embeddingsrope = rotary_embed(x, pos_ids)# 5. Pass through all Transformer blocks sequentiallyfor block in blocks:x = block(x, rope, cu_seqlens)# 6. Apply final normalizationx = final_norm(x)# 7. Reshape and merge spatial tokens in 2×2 windowsx = x.reshape(-1, 2, 2, channels)x = downsample(x)# 8. Project to the language model's hidden dimensionreturn mlp_projector(x)
2D Position Encoding
Image positions are two-dimensional—both rows and columns need encoding. A common approach splits rotary position embeddings into row and column axes, applying rotation to different channel groups separately. This allows the model to perceive relative position relationships while adapting to resolutions not seen during training.
Variable-Length Sequences and Attention Isolation
A single batch may contain images of different sizes simultaneously. When concatenated into one long sequence, a cumulative length array (cu_seqlens) marks the start and end of each image so attention is computed only within the same image. Otherwise, tokens from different images interfere with one another, causing feature contamination.
Final Normalization and Downsampling
After the Transformer stack, final normalization stabilizes the numerical distribution of features. A 2×2 reshape then concatenates the channels of four adjacent tokens, followed by a convolution or linear layer to reduce to the dimension required by the language model. The final MLP projection layer handles modality alignment, mapping vision vectors into the same semantic space as text embeddings.
Choosing Inference Precision
Precision selection for vision encoders requires balancing parameter share, numerical sensitivity, and deployment cost.
Low parameter share. In many multimodal models, vision components account for only a small fraction of total parameters, so quantizing them yields limited memory savings.
High numerical sensitivity. Small deviations in visual features directly impact fine-grained recognition, such as small text and similar color distinctions. Many deployments therefore retain higher precision formats (like BF16) for the encoder rather than applying aggressive quantization.
Throughput gains require measurement. The vision encoder’s computation scales with image token count. If the workload is dominated by high-resolution images, encoding can become the latency bottleneck. End-to-end latency and accuracy should be compared across precision options through load testing rather than decided by assumption.
Engineering Practice Considerations
Caching Vision Features
The same image may be referenced repeatedly across multi-turn conversations. Caching encoded visual features by image hash avoids redundant computation. The cache key should include image content, resolution, and preprocessing parameters—any change should be treated as a new input.
Video Frame Sampling
Video can be treated as a sequence of images ordered by time. Sampling frame rate directly determines total token count. Lower frame rates control cost but may miss fast-changing content. In practice, fixed frame counts are set per scenario, with higher sampling density applied at key segments.
GPU Memory Estimation
Activation memory for the vision encoder scales with token count, layer count, and hidden dimension. Before deployment, peak memory should be estimated for the maximum resolution and batch size, reserving additional space for the language model’s decoding cache.
Balancing Budget and Quality
If max_image_tokens is set too low, fine text and table lines are lost. If set too high, both context usage and latency increase per request. It is recommended to build an evaluation set from representative business samples, record accuracy and latency at different budget levels, and then determine default values.
Common Issues and Troubleshooting
Issue one: Increased character recognition errors. First check whether the scaling ratio is too small, then verify that preprocessing has not applied unnecessary compression. If the screenshot itself has low resolution, prioritize raising min_image_tokens.
Issue two: Later images underperform in multi-image conversations. Check whether the context budget is exhausted and whether attention isolation for multi-image batching is correct. Test images individually and compare results to isolate the problem.
Issue three: Inference speed is lower than expected. Check for repeated encoding, confirm caching is active, and measure vision token counts per request. If high-resolution images dominate, consider applying resolution limits on the client side.
Issue four: Results differ across frameworks. Position encoding index rules, padding methods, and normalization details may all cause discrepancies. When migrating models, fix the random seed and compare intermediate features layer by layer to confirm each step produces consistent output.
Summary
The core task of a vision encoder is to convert images of arbitrary resolution into a regularized, controllable token sequence. This process involves alignment and padding, patch splitting, 2×2 merging, variable-length attention, and projection alignment. Understanding the computational relationships between these stages allows you to estimate token counts and GPU memory usage, and design budget strategies accordingly.
For engineering deployment, it is recommended to first establish an evaluation set to clarify the relationship between resolution, token budget, and accuracy, then decide on precision format, caching strategy, and video sampling plan. This produces configurations that are both evidence-based and adaptable as business needs evolve.
