Vision Encoder Design and Inference Implementation in Lightweight Multimodal Models
This technical breakdown covers the vision encoder in a lightweight multimodal large language model. It explains image preprocessing with 28-pixel alignment, 14×14 patch splitting and 2×2 merging, visual token budget control, the 24-layer ViT configuration, and the forward pass with Axial RoPE and variable-length attention. It closes with engineering takeaways for multimodal inference.
1. Background: Where the Vision Module Fits in a Lightweight Flagship Model
Recently, a class of multimodal large language models has positioned itself as “lightweight flagship” models. These models keep the overall parameter count under control and keep inference costs low. On general conversation, document understanding, and visual question answering, they still perform close to much larger models. For developers, the most useful part to study is not the language backbone, since language-side architectures have largely converged. It is the vision encoder. The question is how a very small ViT turns images of arbitrary resolution, or video frames, into a token sequence that the language model can read directly, while keeping information loss manageable and the context budget adjustable.
This article uses the vision module in a commonly used inference framework as a reference. It walks through the full process from image input to visual token output and analyzes the engineering trade-offs involved.
2. Image Preprocessing: Normalization, Size Alignment, and Patch Splitting
2.1 Resizing and Zero-Padding
Before an image enters the vision encoder, the image processor normalizes it. This involves two core steps.
- Resizing: The image is scaled to an appropriate size based on its original resolution. This balances two concerns. Low resolution loses detail, while high resolution produces too many visual tokens and crowds the context window.
- Zero-padding to a multiple of 28: This is a critical constraint. The number 28 is not arbitrary. It equals the patch size 14 multiplied by the merge factor 2 (14 × 2 = 28). Alignment to 28 is needed because the network’s tail applies a 2×2 spatial merge. Only when both the height and width of the feature map are multiples of 28 does the merge fit cleanly at the boundaries without leaving partial patches.
2.2 Patch Splitting and 2×2 Merging
After alignment, the image is split into base patches of 14×14 pixels. This step usually runs as a convolution layer whose stride equals the patch size. The layer is equivalent to Conv3d when it handles video input with a temporal dimension. The network then performs a 2×2 spatial merge. It concatenates four neighboring base patches along the channel dimension and downsamples them into one merged patch. In other words:
- Each 28×28 pixel image region maps to one visual token.
- The number of visual tokens for an image is approximately (H/28) × (W/28).
This design splits finely and then merges locally, which serves two goals. The first 24 Transformer layers run self-attention at the fine 14×14 granularity, which preserves detail. The output side then compresses by a factor of 4, which substantially shortens the sequence passed to the language model.
2.3 Token Budget Control
Different scenarios need very different visual token budgets. A thumbnail may need only a few dozen tokens, while high-resolution document parsing may need thousands. The module therefore provides minimum and maximum token configuration options, with typical defaults of 16 and 8000. The preprocessor uses these limits to derive a suitable resize target:
- If the token count at the original resolution exceeds the maximum, the image is scaled down proportionally.
- If it falls below the minimum, the image is scaled up moderately so the model can still see basic structure.
This mechanism lets one set of model weights handle a wide range of inputs, from phone screenshots to scanned long documents. It also gives deterministic cost control in context-constrained scenarios, such as multi-image inputs or video frame sampling.
3. ViT Backbone: Configuration and Structure
The vision encoder is a relatively compact 24-layer ViT. Its main configuration is shown below.
| Item | Value |
|---|---|
| Network depth | 24 layers |
| hidden_size | 1024 |
| Attention heads | 16 (head dimension 64, no GQA) |
| Patch size / merge factor | 14 / 2×2 |
| Output dimension | 4096 (aligned with the language model hidden size) |
| Backbone parameters | About 0.56B |
Several design points stand out.
First, the parameter count is very small. About 0.56B parameters account for less than 1% of the full multimodal model. Vision encoding therefore rarely becomes the inference bottleneck, and most of the compute still falls on the language backbone. For inference serving, this asymmetric structure of light vision and heavy language is convenient. The vision part can run its forward pass in BF16 without aggressive quantization such as FP8. This preserves numerical stability and avoids perturbing the visual feature distribution with low precision.
Second, grouped-query attention (GQA) is not used. Unlike a language model, the vision Transformer has no KV cache that grows with sequence length during decoding. It performs a single forward encoding pass. A standard multi-head attention with 16 heads of dimension 64 is therefore a reasonable choice, and it avoids the loss in expressiveness that GQA introduces.
Third, the output dimension aligns with the language side. The 1024-dimensional visual features are projected up to 4096 dimensions, which matches the language model’s hidden size. They can then be concatenated directly into the text token sequence, without an extra adapter layer or normalization bridge.
4. Step-by-Step Walkthrough of the Forward Pass
The forward pass of this vision encoder in the inference framework is clear. It breaks into six stages:
def forward(self, hidden_states, grid_thw, **kwargs):# Compute position IDs and variable-length attention boundaries from the (t, h, w) grid of each image or frameposition_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, ...)cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, ...)hidden_states = self.patch_embed(hidden_states) # ① Split into patches with a convolutionposition_embeddings = self.rotary_pos_emb(hidden_states, position_ids) # ② Axial RoPE position encodingfor blk in self.blocks: # ③ 24 Transformer blockshidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, ...)hidden_states = self.post_layernorm(hidden_states) # ④ Final LayerNormhidden_states = hidden_states.view(-1, 2, 2, C) # ⑤ Rearrange 2×2 spatial neighborshidden_states = hidden_states.permute(0, 3, 1, 2)hidden_states = self.downsample(hidden_states).view(-1, out_hidden)# Downsample and merge with Conv2dmerged = self.merger(hidden_states) # ⑥ Project to LLM dimension with SwiGLU MLPreturn BaseModelOutputWithPooling(last_hidden_state=hidden_states,pooler_output=merged,)
The stages are explained in detail below.
4.1 Variable-Length Sequence Organization: grid_thw and cu_seqlens
Unlike a traditional ViT with fixed resolution, this module natively supports arbitrary resolution and mixed batches. Each image, or each group of video frames, is described by a triplet (t, h, w) that gives its size on the patch grid. The patches from all samples are concatenated into one long sequence. cu_seqlens (cumulative sequence lengths) tells the attention kernel where each sample starts and ends. This is a typical variable-length attention (varlen attention) layout:
- Attention is computed only within each image, which prevents cross-image information leakage.
- Images of different resolutions in a batch pack tightly, which avoids wasted compute on padding.
- It works with high-performance fused attention operators that accept a
cu_seqlensinterface.
4.2 Positional Encoding: Axial RoPE
Stage ② uses axial rotary position embedding (Axial RoPE). It splits 2D spatial coordinates into height and width directions, computes rotation angles for each, and then combines them. Compared with learnable absolute position embeddings, this approach has two direct benefits:
- Native support for arbitrary resolution. Position encodings are computed from coordinates on the fly, so interpolation and extrapolation are not needed.
- Relative position awareness. Rotary encoding lets attention scores carry relative dist
