Decoding the Vision Encoder Workflow in a Lightweight Multimodal Model

    This article breaks down the internal workflow of a vision encoder in a lightweight multimodal model, covering image preprocessing, the core ViT architecture, token compression, and feature projection. It explains how high-resolution images are resized and padded, split into patches, and processed through 24 transformer blocks before being merged and projected into token embeddings for the language model. Practical considerations such as token budget tuning, precision selection (BF16 vs. FP8), and deployment trade-offs are also discussed based on the original technical documentation.

    Multimodal large models rely on a vision encoder to convert raw pixels into tokens that a language model can process. High-resolution images produce a large number of tokens, which can directly slow down inference. This article uses the vision encoder from a lightweight multimodal model as an example to walk through its preprocessing steps, network architecture, feature compression, and dimension projection. The concrete values referenced here come from the original documentation; in practice, always consult the configuration file of the specific model version you are deploying.

    1. Preprocessing Before the Image Enters the Model

    Before an image is fed into the vision encoder, it undergoes a standardization process consisting of three main steps.

    Resizing and Zero-Padding

    Input images at arbitrary resolutions are first resized to an appropriate size and then zero-padded so that both width and height are multiples of 28. The number 28 is chosen because the network uses 14-pixel patches and subsequently applies a 2×2 merge; 14 multiplied by 2 equals 28. After padding, the patching and merging operations can divide evenly, reducing the risk of edge regions being truncated. However, zero-padding introduces some pixels without actual content, which still incurs a small amount of wasted computation.

    Patch Splitting

    The image is divided into 14×14 pixel base patches. Each patch corresponds to one position in the subsequent token sequence.

    Token Budget Control

    The model limits the number of tokens generated per image through minimum and maximum token counts. The default range given in the original documentation is 16 to 8000. The documentation does not specify the exact counting convention; generally, such a range corresponds to upper and lower bounds on image pixel counts or similar configuration parameters. The exact unit depends on the definition used by the image processor.

    How to set the token budget depends on the task type. The following recommendations are based on common use cases, not on conclusions from the original documentation:

    • For OCR-like tasks or fine-grained visual question answering, small text and fine textures need to be preserved, so the upper budget should be set higher. The trade-off is slower inference and a larger context window footprint.
    • For coarse-grained classification or scene overview tasks, the budget can be set lower in exchange for faster response times.

    2. Core Configuration of the Vision Backbone

    The vision encoder adopts a lightweight Vision Transformer (ViT) structure with the following core configuration:

    • Number of layers: 24 Transformer blocks
    • Hidden dimension: 1024
    • Attention heads: 16, with a head dimension of 64 (1024 ÷ 16)
    • Attention mechanism: Standard multi-head attention, without grouped-query attention (GQA)
    • Patch size: 14 pixels
    • Merge strategy: 2×2
    • Output dimension: 4096

    The output dimension must match the hidden dimension of the backend language model. Different language models have different hidden dimensions, so this value must be updated accordingly when switching to a different language model.

    The vision backbone has approximately 0.56B parameters. The original documentation also claims that this accounts for less than 1% of the total multimodal model, but it does not provide the total parameter count, so this ratio cannot be verified. If the total model size were around 7B, 0.56B would represent approximately 8%, which contradicts the “less than 1%” claim. Before citing this figure, the total parameter count of the model should be confirmed.

    3. Execution Order of the Forward Pass

    The original documentation provides pseudocode that outlines the main steps of the forward pass:

    1. def forward(self, hidden_states, grid_thw, **kwargs):
    2. position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, ...)
    3. cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, ...)
    4. hidden_states = self.patch_embed(hidden_states) # Conv3d patch embed
    5. position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) # Axial RoPE
    6. for blk in self.blocks: # 24 blocks
    7. hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, ...)
    8. hidden_states = self.post_layernorm(hidden_states)
    9. hidden_states = hidden_states.view(-1, 2, 2, C) # 2×2 spatial rearrange
    10. hidden_states = hidden_states.permute(0, 3, 1, 2)
    11. hidden_states = self.downsample(hidden_states).view(-1, out_hidden) # Conv2d downsample
    12. merged = self.merger(hidden_states) # SwiGLU projection

    Note that the division of responsibilities between downsample and merger is not entirely clear from the pseudocode. Refer to the actual source code when reading this part.

    Step 1: Patch Embedding and Position Encoding

    The input is first passed through a Conv3d layer to produce a sequence of patches. Axial rotary position embeddings (RoPE) are then applied, injecting positional information based on the row and column indices of the grid. This design allows the model to adapt to images at different resolutions. The cu_seqlens and max_seqlen values track the boundary of each image within the sequence. With this information, multiple images of different sizes can participate in variable-length attention computation within the same batch, reducing reliance on padding.

    Step 2: 24-Layer Encoding

    The patch sequence passes through 24 Transformer blocks layer by layer, with features being progressively extracted and abstracted.

    Step 3: 2×2 Spatial Merging

    After layer normalization, the features are rearranged into 2×2 spatial blocks, merging four adjacent patches into one. The token count is therefore reduced to one quarter of the original. A subsequent Conv2d downsampling layer mixes the merged features and maps them to the target dimension.

    To illustrate with an example: suppose an image is resized to 1344×1344 pixels. 1344 is a multiple of 28, satisfying the padding requirement. With 14-pixel patches, the image yields 96×96, or 9216 patches. After 2×2 merging, the token count drops to 48×48, or 2304 tokens. This number falls within the default range of 16 to 8000. This example is derived from the workflow described above, not from a measured value in the original documentation.

    Step 4: SwiGLU Projection

    The merger module projects the downsampled features to 4096 dimensions. SwiGLU consists of two linear branches: one passes through a Swish activation and acts as a gate, which is multiplied element-wise with the output of the other branch; the result is then passed through a final linear layer. The projected features serve as the visual tokens fed into the language model.

    4. Precision Selection for Deployment

    According to the original documentation, the vision backbone uses BF16 precision for inference, without introducing FP8 quantization. Two reasons are given. First, the vision module accounts for only a small fraction of the total computation in the multimodal model, so FP8 would offer limited acceleration. Second, keeping BF16 reduces the impact of quantization error on visual features, which benefits accuracy on understanding tasks.

    These reasons are design-level inferences. The original documentation does not include latency, throughput, or accuracy measurements. To make a definitive choice, BF16 and FP8 should be compared on the target hardware in terms of latency, throughput, and task accuracy.

    The original documentation also mentions deployment on a cloud-native container platform, combined with object storage for image reading and elastic scaling. These environmental factors affect actual latency and concurrency capabilities and should be validated through load testing; the original documentation does not provide such data.

    5. Applicability Boundaries and Caveats

    • High-resolution images and video frames rapidly generate a large number of tokens. The upper budget directly affects GPU memory usage and inference latency.
    • Small objects and dense text may suffer detail loss after compression. The budget should be increased and validation should be performed on your own dataset.
    • When switching language models, the output dimension must be updated accordingly, otherwise the projection will not align with the backend.
    • Parameters such as 0.56B, 24 layers, and 4096 dimensions should be confirmed against the configuration file of the specific model version in use.
    • The original documentation does not provide comparative experiments against other vision encoders, so it is not possible to conclude that this design performs better on all tasks.

    6. Summary

    The core idea of this vision encoder is as follows: first, standardize the input by padding to multiples of 28 and splitting into 14-pixel patches; then, reduce the token count to one quarter via 2×2 merging; finally, project the features to the language model’s hidden dimension. Under the configuration described in the article, it effectively reduces the number of visual tokens. The degree of compression, precision loss, and latency benefits all depend on the token budget settings and the deployment environment. Therefore, before putting it into production for a specific use case, testing should be performed on the target task and hardware.