Vision Encoding and Token Budget Design for Lightweight Multimodal Models
Lightweight multimodal models need native visual capabilities without excessive latency or memory overhead. This article explains the vision encoder structure, image preprocessing steps, visual token budget formula, positional encoding, feature alignment, precision strategy, variable-length batching, and evaluation considerations for deploying small multimodal models.
1. Why Small Models Also Need Native Vision
A common earlier approach was to use a separate image-understanding module to convert an image into a text description, then pass that description to a language model. The problem with this cascaded design is that information is lost during conversion. Coordinate relationships in charts, control positions in UI screenshots, and indentation structure in code screenshots are difficult to describe completely in a paragraph of text.
A native vision approach encodes images into token sequences that are structurally compatible with text and feeds them into the same Transformer together with text. The model can therefore decide during inference when to “look” at an image, which region to inspect, and use visual feedback in later steps. For on-device deployment and low-latency scenarios, the key constraints are compute budget and memory footprint, so the vision encoder is usually built as a lightweight structure.
2. Basic Structure of the Vision Encoder
A typical vision encoder has three parts: linear embedding after image patch splitting, several Transformer encoder blocks, and an output layer that projects visual features into the language model’s hidden dimension. The following table gives an illustrative configuration to show how the parameters relate to one another. It does not represent the actual parameters of any specific product.
| Parameter | Illustrative value | Description |
|---|---|---|
| Layers | 24 | Number of encoder blocks; determines the depth of feature abstraction |
| Hidden dimension | 1024 | Intermediate representation width for each visual token |
| Attention heads | 16 | Number of parallel subspaces in multi-head attention |
| Head dimension | 64 | 1024 / 16; this configuration does not use grouped-query attention |
| Base patch size | 14×14 | Pixel area covered by each base block |
| Merging method | 2×2 | Four adjacent base blocks are merged into one visual token |
| Output dimension | 4096 | Aligned with the language model hidden dimension |
With this configuration, the visual backbone is estimated at about 0.5B parameters. If the language model part reaches several billion parameters, the visual portion is usually less than one percent. The vision encoder has modest compute, so its precision and inference-cost design need to be considered separately rather than simply reusing the language model’s quantization strategy.
3. Image Preprocessing Pipeline
The goal of preprocessing is to map images of arbitrary resolution to a deterministic number of visual tokens. The pipeline has four steps.
Step 1: Resize and pad. The image is first scaled to an appropriate size according to the budget, then zero-padded to an integer multiple of 28. Since 28 equals the base patch size 14 multiplied by the merge factor 2, the padded image can be split exactly into 2×2 merge units.
Step 2: Split patches. The image is split into 14×14-pixel base blocks. Each base block is passed through linear embedding to obtain a feature vector.
Step 3: 2×2 merge. The features of four adjacent base blocks are concatenated and projected into one visual token, so each 28×28-pixel region corresponds to one visual token.
Step 4: Token budget control. Context length is limited, so the number of tokens for a single image must be controllable. In practice, a lower bound and an upper bound are usually set, for example 16 and 8000. Below the lower bound, the image is upscaled; above the upper bound, it is downscaled proportionally.
The number of tokens can be estimated directly with the following formula:
Visual tokens = ⌈height / 28⌉ × ⌈width / 28⌉
The following code provides a reproducible draft that shows the budget-constraint logic:
import mathUNIT = 28 # 14-pixel base patch × 2×2 mergedef fit_to_budget(height: int, width: int, max_tokens: int = 8000):"""Return a target size and token count that satisfy the token budget."""gh = math.ceil(height / UNIT)gw = math.ceil(width / UNIT)if gh * gw <= max_tokens:return height, width, gh * gw# Scale down proportionally to fit the budget, then floor to a multiple of UNITscale = math.sqrt(max_tokens / (gh * gw))new_h = max(UNIT, int(height * scale) // UNIT * UNIT)new_w = max(UNIT, int(width * scale) // UNIT * UNIT)return new_h, new_w, (new_h // UNIT) * (new_w // UNIT)# Example: an 896×672 image requires no scalingprint(fit_to_budget(896, 672)) # (896, 672, 768)
In the example, an 896×672 image is exactly 32×24 on the 28-pixel grid, for a total of 768 tokens, far below the upper bound, so no scaling is needed. The higher the resolution, the faster the token count grows, and the more noticeable the impact of budget control on latency becomes.
4. Handling Positional Information
Visual tokens need to preserve two-dimensional spatial position. A common approach is to apply two-dimensional rotary position encoding to the row and column coordinates of each token so that attention can perceive relative position. Compared with one-dimensional text position encoding, the two-dimensional scheme allows the model to distinguish pixel relationships within the same row and the same column, which is especially important for chart and UI understanding.
For video input, adjacent frames can be split and merged in a similar way along the temporal dimension, using spatiotemporal blocks as the base unit. The cost of this approach is that the number of video tokens grows linearly with the number of frames, so an upper limit is usually placed on the sampling frame rate.
5. Aligning Visual Features with the Language Model
The features output by the vision encoder must be mapped to the language model’s hidden dimension before they can be concatenated with text tokens. The projection layer is usually a linear layer or a small multilayer perceptron. During concatenation, special boundary markers are added before and after the visual token segment so that the model can clearly distinguish image regions from text regions.
The core of alignment training is to make visual features and language semantics correspond in the same space. Training data generally includes image-text pairs, document parsing, UI screenshots, and code screenshots. The more scenarios the data covers, the more stable the model is in practical tasks.
6. Precision and Inference Strategy
The vision encoder has few parameters, but it is relatively sensitive to numerical error. Subtle pixel-level differences can be amplified through multiple layers and affect final region judgments. Therefore, a common practice is to keep the vision encoder at higher precision, for example fixed BF16, without low-bit quantization. The language model part can use more aggressive quantization schemes depending on latency and memory requirements.
The benefit of this mixed-precision strategy is that the additional overhead of the vision branch is small, while recognition degradation caused by quantization can be avoided. Whether to adopt it should be based on evaluation results for the task at hand.
7. Batching Variable-Length Inputs
In actual deployment, different images have different resolutions and different token counts. Simply padding them to the same length wastes a large amount of compute. A more reasonable approach is to concatenate the visual tokens of all images into one long sequence and record the cumulative length boundary of each image. Attention computation is then performed only within each boundary, preventing different images from interfering with one another.
This mechanism relies on a variable-length attention operator. It needs to maintain boundary indices and split computation by segment. In engineering terms, as long as the preprocessing stage outputs the correct grid information, this mechanism can be implemented in common inference frameworks.
8. Selection and Evaluation Guidance
When choosing a visual capability solution for a business, it is recommended to evaluate it from the following dimensions:
- Match between resolution and task. Document reading usually requires higher resolution, while simple image classification does not. Excessively high resolution only adds latency.
- Relationship between token budget and latency. It is recommended to measure first-token latency and throughput at different resolutions on the target hardware, and plot the resolution-latency curve as the basis for the budget upper bound.
- Memory footprint. The number of visual tokens directly affects the size of the attention KV cache. The longer the context, the more memory a single inference consumes.
- Accuracy regression testing. For changes such as quantization and resolution adjustment, regression validation should be performed on an in-house image-text evaluation set rather than relying only on general metrics.
9. Summary
The visual capability of lightweight multimodal models comes down to three things: mapping images of arbitrary resolution stably to a controllable number of tokens, aligning visual features with the language space, and making evidence-based tradeoffs between precision and overhead. Mastering the token calculation formula and budget-control logic makes it possible to estimate cost before deployment and continue optimizing after launch.
