How Vision Encoders Turn Images of Any Resolution into Tokens
This article explains how a vision encoder converts images of any resolution into visual tokens for a large language model. It covers the encoder structure, the 28-pixel alignment rule, how token counts are calculated, token budget control, the forward pass, precision trade-offs, video input, and practical engineering recommendations.
1. Background: Why Vision Belongs Inside the Model
Image understanding has moved from a auxiliary feature to a core capability of large models. In programming, a model needs to read error screenshots, interface sketches, and architecture diagrams. In document processing, it needs to parse tables, formulas, and page layouts. In operations, it needs to judge abnormal trends from monitoring charts. These tasks share one requirement: the model should perceive visual information directly, rather than rely on an external recognition module that converts images to text before passing them to the language model.
The traditional cascaded approach first extracts text with a separate OCR or image captioning module, then inserts that text into the prompt. The problem with this approach is information loss. Layout, color, icon semantics, and spatial position are easily lost during conversion, and errors from the two modules compound.
The native multimodal approach works differently. An image first passes through a vision encoder, which converts it into a set of vectors aligned with the dimension of text tokens. These vectors then enter the same Transformer together with the text tokens. During inference, the model can decide for itself when it needs to look at the image and how to adjust its next actions after looking. This design requires the vision encoder to preserve enough detail while keeping computation and context costs under control.
2. Basic Structure of the Vision Encoder
The vision encoder typically uses the Vision Transformer (ViT) architecture. Its core process is to split an image into small patches, map each patch to a vector, model the relationships between patches through multiple layers of self-attention, and finally project the output to the hidden dimension of the language model.
The table below shows a typical configuration and how its parameters relate to each other.
| Parameter | Value | Description |
|---|---|---|
| Depth (depth) | 24 | Stacking depth of Transformer blocks |
| Hidden size (hidden_size) | 1024 | Vector width of each visual token in the backbone |
| Number of attention heads | 16 | Number of parallel subspaces in multi-head attention |
| Dimension per head | 64 | 1024 divided by 16 |
| Patch size | 14 | Side length of a single base patch, in pixels |
| Merge method | 2×2 | Four adjacent patches merged into one visual unit |
| Output dimension | 4096 | Aligned with the hidden dimension of the language model |
| Backbone parameters | About 0.56B | Parameter size of the vision encoder itself |
In this configuration, each attention head has its own key and value projections, which is standard multi-head attention. Grouped-query attention (GQA) lets multiple query heads share key and value heads to reduce memory usage. Because the vision encoder is relatively small, this configuration uses standard multi-head attention for a more direct implementation.
The vision encoder has far fewer parameters than the full model. This means the main cost of vision capability lies in the number of input tokens, not in the computation of the encoder itself. Section 3.4 on budget control covers this in more detail.
3. Preprocessing Images of Arbitrary Resolution
A fixed-resolution approach scales every image to the same size. This causes significant loss of detail and unnecessarily enlarges small images. A dynamic-resolution approach generates a number of visual tokens based on the original image size, which works better for high-information inputs such as documents and screenshots.
3.1 Resizing and Zero Padding
The first preprocessing step is resizing. The image width and height are adjusted to a suitable range, then zero-padded to multiples of 28. The reason for choosing 28 is:
- The base patch side length is 14 pixels.
- The 2×2 merge operation requires each merged unit to cover 2 patches, which is 14 × 2 = 28 pixels.
Only when both width and height are multiples of 28 can the splitting and merging produce no incomplete units.
3.2 Patch Splitting and Merging
The resized image is split into base patches of 14×14 pixels. Adjacent 2×2 patches are then merged into one visual unit and projected to the model dimension. Therefore, each 28×28 pixel region corresponds to exactly one visual token.
3.3 Calculating the Number of Tokens
The number of visual tokens can be calculated directly from the image size. Let W be the padded width and H be the padded height:
Number of visual tokens = (W / 28) × (H / 28)
Take a screenshot that is 1024 pixels wide and 768 pixels high as an example. The width of 1024 is padded to 1036 (37 × 28), and the height of 768 is padded to 784 (28 × 28). The number of visual tokens is therefore 37 × 28 = 1036. This number directly determines how much context space the image occupies.
3.4 Token Budget Control
The best resolution for the same image differs across scenarios. To manage this, preprocessing usually provides two parameters that limit the number of tokens:
- min_image_tokens: the minimum number of tokens for a single image, which ensures that small images still carry enough information.
- max_image_tokens: the maximum number of tokens for a single image, which prevents very large images from crowding out the context.
A common default range is 16 to 8000. When an image exceeds the upper limit, it is scaled down proportionally. When it falls below the lower limit, it is scaled up appropriately. Budget settings should account for both the model’s context length and the application’s concurrency.
The following is example code for the preprocessing logic. The function name is used only to illustrate the process and does not belong to any specific library’s interface.
import mathPATCH = 14MERGE = 2UNIT = PATCH * MERGE # 28def resize_for_budget(w, h, min_tokens=16, max_tokens=8000):"""Resize the image to fit the token budget and align it to multiples of 28."""tokens = math.ceil(w / UNIT) * math.ceil(h / UNIT)if tokens > max_tokens:scale = math.sqrt(max_tokens / tokens)w, h = int(w * scale), int(h * scale)elif tokens < min_tokens:scale = math.sqrt(min_tokens / tokens)w, h = int(w * scale), int(h * scale)new_w = math.ceil(w / UNIT) * UNITnew_h = math.ceil(h / UNIT) * UNITreturn new_w, new_h, (new_w // UNIT) * (new_h // UNIT)
In this logic, the scaling factor is the square root because the token count is roughly proportional to the product of width and height. The alignment step comes after scaling, which ensures that the final dimensions are multiples of 28.
4. The Vision Encoder Forward Pass
After preprocessing, the vision encoder’s forward pass has four stages.
Stage 1: Building position information. For images, positions are two-dimensional, with rows and columns encoded separately. For video, the frame index forms a third dimension. The encoder generates a position index for each patch based on the grid size (time, height, width). These indices are used later by the rotary position encoding.
Stage 2: Attention segmentation. A batch may contain several images of different sizes. To keep images from attending to each other, the encoder computes a cumulative length array (cu_seqlens). This array marks the start and end position of each image in the sequence, and the encoder also records the maximum sequence length. Attention is computed within each segment. This avoids wasted computation on padding and prevents information from mixing between images.
Stage 3: Patch embedding and backbone computation. The raw pixels first pass through a convolution layer with both kernel size and stride set to 14. This completes the patch embedding. The sequence then enters 24 Transformer blocks. Each block contains an attention computation and a feed-forward network, and rotary position encoding is applied inside the attention.
Stage 4: Merging and projection. The backbone output passes through a 2×2 merge layer. This layer concatenates each group of 4 adjacent vectors and projects them to 4096 dimensions to align with the input space of the language model. The projected results are then inserted into the text sequence at their corresponding positions.
Example code:
def vision_forward(patches, grid_thw):pos_ids = build_position_ids(grid_thw, merge=2)cu_seqlens, max_seqlen = build_attention_segments(grid_thw)x = patch_embed(patches) # Patch embedding via convolutionpos_emb = rotary_embedding(pos_ids) # Rotary position embeddingfor block in vision_blocks: # 24 Transformer layersx = block(x, pos_emb, cu_seqlens, max_seqlen)x = merge_2x2(x) # Merge 4 adjacent vectorsreturn project(x, out_dim=4096) # Align with the language model dimension
The key point is that position encoding and attention segmentation must be prepared all at once before the backbone computation. If the segmentation information is missing, attention across different images will mix together and produce incorrect outputs.
5. Engineering Trade-offs in Inference Precision
The vision encoder typically runs in BF16 precision during inference and is not quantized to lower-bit formats such as FP8. This choice is based on three considerations:
- Limited benefit. The vision encoder is relatively small, so the memory and bandwidth savings from quantization are far smaller than those for the language backbone.
- Sensitivity to precision. Fine text, thin lines, and numerical scales in images are sensitive to numerical error, and low-precision quantization can more easily cause recognition errors.
- Maintenance cost. Keeping a single precision reduces the work of quantization calibration and validating multiple versions.
This is an engineering trade-off, not a universal rule. In scenarios with very tight memory or very large image volumes, a team may consider quantizing the vision component after thoroughly evaluating accuracy.
6. Handling Video Input
A video is essentially a sequence of images with a time dimension. A common approach is to sample frames at a fixed frame rate or a fixed number of frames, treat each frame as an image, and add a time dimension to the grid size. Because the number of frames quickly multiplies token consumption, applications usually need to limit both the number of sampled frames and the token budget per frame.
For example, a 30-second video sampled at 1 frame per second produces 30 time steps. If each frame keeps 100 visual tokens, the visual part of the video alone takes 3,000 tokens. In this case, the frame sampling rate and the per-frame budget must be designed together to control the total cost.
7. Engineering Recommendations
Based on the mechanisms above, teams deploying visual input can focus on the following areas.
Set budgets by scenario. Tasks such as document parsing and table recognition need higher resolution, so the budget ceiling can be set higher. Tasks such as thumbnail classification and icon recognition can use a lower ceiling to save context.
Estimate context usage. Before a request reaches the model, calculate the number of visual tokens from the image size, add the text length, and check whether the total exceeds the context window. This step prevents requests from failing during inference.
Use variable-length batching. With cumulative length segmentation, images of different sizes can be concatenated in the same batch, which reduces padding waste. When scheduling batches, requests can be sorted by token count to improve hardware utilization.
Cache encoding results for repeated images. The same image may be referenced repeatedly across multiple conversation turns. Caching the encoding results avoids repeated computation. The cache key should include a digest of the image content and the preprocessing parameters, so results from different configurations are not mixed.
Keep the original size information. Preprocessing changes the image dimensions. If the application needs to map coordinates from the model output back to the original image, it must record the scaling ratio and the padding amount.
8. Summary
Building vision capability into a language model is an important direction for handling complex inputs. The implementation rests on three parts: size alignment in units of 28, which keeps splitting and merging complete; token budget control centered on the number of visual tokens, which balances information content against context cost; and a forward pass built on attention segmentation and position encoding, which supports arbitrary resolutions and video input. With these mechanisms in mind, developers can estimate costs more accurately, configure parameters, and make sound trade-offs between accuracy and efficiency.
