Visual Encoders in Multimodal Models: Patch Merging and Token Budgeting

    Visual encoding in lightweight multimodal models directly impacts image comprehension, inference latency, and VRAM usage. Unlike traditional approaches that treat the vision module as a standalone preprocessor, native integration allows the model to engage visual capabilities dynamically during internal reasoning. This article breaks down the visual encoding pipeline of a lightweight flagship model, covering image preprocessing, patch splitting and merging, and token budget control, while providing practical deployment guidelines.

    Visual encoding in lightweight multimodal models determines the quality of image comprehension and directly impacts inference latency and VRAM usage. Traditional approaches treat the vision module as a standalone preprocessor, computing image features before feeding them to the language model. Native integration takes a different approach: visual capabilities participate in the model’s internal reasoning process, allowing the model to decide when to process images based on context and incorporating visual information into subsequent reasoning steps.

    This article uses the vision module of a lightweight flagship model as an example to deconstruct three key stages: image preprocessing, patch splitting and merging, and token budget control. It also provides deployment checkpoints. Note that the architectural parameters mentioned are example configurations; always refer to the official documentation of the specific model for actual use.

    1. Image Preprocessing: Why Align to Multiples of 28

    To put it simply, padding image dimensions to multiples of 28 ensures that patch splitting does not result in boundary truncation.

    The process involves three steps. First, the image is proportionally scaled to an appropriate size while maintaining its aspect ratio. Second, zero-padding is applied to make both width and height multiples of 28. Third, the image is divided into 14×14 pixel base patches.

    The choice of 28 is straightforward. The base patch size is 14, and a subsequent 2×2 merging operation is applied (14×2=28). As long as the dimensions are multiples of 28, every merged region remains complete without truncated edge patches, preserving the spatial structure of visual features.

    2. Patch Splitting and 2×2 Merging: Reducing Tokens to a Quarter

    After base patch splitting, adjacent 4 patches are merged into a larger region. Each 28×28 pixel region corresponds to a single visual token.

    This step acts as spatial down-sampling. The token count is reduced to a quarter of the original, significantly decreasing subsequent computational overhead since Transformer attention scales with sequence length. The trade-off is that fine textures may be compressed, which heavily impacts images with dense text. Whether this is acceptable must be tested with your specific data.

    3. Token Budget Control: How to Tune min_image_tokens and max_image_tokens

    Two parameters are crucial here: min_image_tokens sets the lower bound of tokens for a single image, while max_image_tokens sets the upper bound. You can adjust them following these steps:

    1. Categorize by task: Icons and simple graphics can use a lower upper bound. High-density documents, tables, and complex scenes require a higher upper bound.
    2. Set the lower bound: This ensures small images have enough tokens to express basic structures, preventing complete information loss.
    3. Set the upper bound: This determines the maximum visual tokens per image, directly impacting VRAM usage and Time-To-First-Token (TTFT) latency.
    4. Check the total volume: When a request contains multiple images or video frames, the total token count grows rapidly and may squeeze the text context. In such cases, lower the per-image upper bound or limit the number of images per request.

    The default lower bound mentioned in the source material is 16, and the upper bound is 8000. These values lack specified measurement conditions, so it is recommended to verify them on your model version before adoption.

    4. Visual Encoder Parameters (Example Configuration)

    Here is an example configuration:

    • Depth: 24
    • Hidden Size: 1024
    • Attention Heads: 16, with a dimension of 64 per head (1024÷16)
    • Patch Size & Merge: 14, 2×2
    • Output Dimension: 4096, consistent with the language model’s hidden size
    • Parameters: ~0.56B

    This configuration uses standard Multi-Head Attention (MHA). The main benefit of Grouped-Query Attention (GQA) is reducing the KV cache. Since visual encoders typically perform only one forward pass without autoregressive decoding, whether to adopt GQA depends on the specific implementation and precision requirements; it cannot be generalized.

    With about 0.56B parameters, it accounts for a small portion compared to a 10-billion-scale language model. However, a small proportion does not mean the overhead can be ignored; actual latency depends on batch size, image resolution, and hardware bandwidth. For inference precision, the example uses BF16. If considering FP8 quantization, you must weigh the precision loss against the speed gain.

    5. Forward Propagation Flow (Illustrative)

    The following pseudocode illustrates the main steps of visual encoding. It omits details and is not directly runnable.

    1. def forward(self, hidden_states, grid_thw, **kwargs):
    2. # hidden_states: patch pixels after splitting, dtype is bfloat16
    3. # grid_thw: shape [num_images, 3], recording time, height, and width grid counts for each image
    4. position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size)
    5. cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config)
    6. hidden_states = self.patch_embed(hidden_states) # Conv3d patch embedding
    7. position_embeddings = self.rotary_pos_emb(position_ids) # Inject RoPE
    8. # Subsequently, multiple Transformer Blocks are executed

    grid_thw determines position encoding and attention segmentation. cu_seqlens records the start and end positions of each image in the concatenated sequence, allowing variable-length images to be processed in the same batch. patch_embed uses 3D convolution to map pixel blocks to initial hidden states, while RoPE injects spatial position information into the sequence.

    Before running, confirm the framework version, input shapes, and data types. The original material does not provide these details.

    6. Deployment Checkpoints

    • VRAM: Estimate peak VRAM based on the maximum tokens per image and maximum batch size, leaving a margin to prevent Out-Of-Memory (OOM) errors.
    • Latency: Dynamic batching can improve throughput but increases tail latency. Set timeouts and maximum wait times.
    • Monitoring: Log the visual token count, encoding time, and VRAM usage for each request to determine if the budget parameters are appropriate.
    • Rollback: Retain the previous model weights and parameter configurations. Canary release new parameters so you can quickly switch back if anomalies occur.

    Conclusion

    Native visual encoding integrates visual capabilities inside the model. 28-pixel alignment, 2×2 merging, and token budgeting collectively determine the precision and cost of the vision module. These mechanisms achieve a compromise under given parameters and input distributions and are not universally applicable. When tuning parameters, test with your own business images first before deciding on the upper and lower limits.