Designing and Inference Practices for Lightweight Vision Encoders in Multimodal LLMs

    This article explains how a lightweight vision encoder turns images and video frames into a compact, predictable token stream for a language model. It covers preprocessing with resize and zero-padding to multiples of 28, 14x14 patch embedding, and 2x2 spatial merging with min/max token budgets; a 24-layer, 1024-hidden-dimension backbone without GQA that outputs 4096 dimensions; the six-step forward pass including axial RoPE and variable-length attention; and engineering practices for context budgeting, batching, precision, video frame control, and observability.

    1. Why Vision Encoders Need to Be Lightweight

    In a multimodal large language model, the vision side acts as a translator: it converts an image or video frame of arbitrary resolution into a one-dimensional token sequence that the language model can understand. The challenge is that visual information is inherently two- or even three-dimensional. Without compression, a single high-resolution image can produce tens of thousands of tokens, quickly exhausting the limited context window while making attention computation grow quadratically.

    The common industry approach is to use a vision backbone that accounts for a tiny share of the total parameters (typically less than 1% of the full model) to perform the encoding, then apply spatial merging and projection to align the output dimension with the language model’s hidden dimension. This design delivers three benefits: low memory usage, controllable time-to-first-token latency, and a predictable context budget. The following sections break down the full pipeline using a typical 24-layer vision backbone.

    2. Preprocessing: Turning Arbitrary Inputs into a Regular Grid

    The first step of vision encoding always happens on the data side, not the network side. A robust processor needs to do three things.

    1) Resizing and zero-padding. The input image’s height and width are resized to an appropriate scale and zero-padded to a multiple of 28. The value 28 is not arbitrary: the base patch size is 14, and a subsequent 2x2 spatial merge is applied, so 14 x 2 equals exactly 28. Aligning the boundaries to an integer multiple of the merge unit avoids grid misalignment caused by “half patches” and lets subsequent reshape operations proceed without an extra mask.

    2) Patch splitting. The image is split into 14x14 pixel base blocks, and each block is mapped to a vector through a convolution-style embedding. This step is equivalent to encoding spatial locality into tokens, where the convolution kernel acts as a local receptive field extractor.

    3) Merging and token budget. Every 4 adjacent base patches (2x2) are combined into one vision token, meaning each 28x28 pixel region corresponds to one token. In practice, minimum and maximum token thresholds (for example, 16 to 8000) are usually provided to constrain the output per image: below the lower bound, upsampling adds detail; above the upper bound, further downsampling is applied. This keeps inputs at different resolutions within a predictable context range.

    Illustrative pseudocode:

    1. def preprocess(image, min_tokens=16, max_tokens=8000):
    2. image = resize_and_pad_to_multiple(image, multiple=28)
    3. tokens = (image.height // 28) * (image.width // 28)
    4. tokens = clamp(tokens, min_tokens, max_tokens)
    5. return tile_to_grid(image, target_tokens=tokens) # output grid_thw

    3. Backbone Design: 24 Layers, 1024 Hidden Dimension, No GQA

    A typical lightweight configuration looks like this:

    Item Value
    Layers 24
    Hidden dimension 1024
    Attention heads 16
    Per-head dimension 64 (1024/16, no GQA)
    Patch / merge 14 / 2x2
    Output dimension 4096 (aligned with the language model hidden dimension)
    Backbone parameters ~0.56 B

    A few design trade-offs are worth noting:

    • No GQA. Vision token sequences are usually much shorter than long-context text scenarios, so KV cache pressure is low. Keeping standard multi-head attention reduces implementation complexity and numerical deviation.
    • Hidden dimension 1024, output 4096. The backbone performs feature abstraction in a “narrow and deep” low-dimensional space, then upscales at the end through a projection layer to align with the language model, avoiding a backbone that balloons into a large model just to match the language model’s dimension.
    • Fixed BF16 inference. The vision side is sensitive to numerical stability (especially for position encoding and normalization). Staying in BF16 rather than lower-bit quantization is a common trade-off between accuracy and throughput.

    4. Forward Pass: Six Key Steps

    The inference entry point receives flattened pixel blocks and a grid description grid_thw. The overall flow can be summarized as:

    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) # (1) convolutional patching
    5. position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) # (2) axial rotary position encoding
    6. for blk in self.blocks: # (3) 24 x encoder block
    7. hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens)
    8. hidden_states = self.post_layernorm(hidden_states) # (4) final normalization
    9. hidden_states = hidden_states.view(-1, 2, 2, C) # (5) 2x2 spatial rearrange
    10. hidden_states = hidden_states.permute(0, 3, 1, 2)
    11. hidden_states = self.downsample(hidden_states).view(-1, out_hidden) # convolutional downsampling
    12. merged = self.merger(hidden_states) # (6) SwiGLU projection
    13. return BaseModelOutputWithPooling(last_hidden_state=hidden_states, pooler_output=merged)

    (1) Convolutional patching. A 3D convolution slides over the temporal and spatial dimensions to extract blocks. Video input naturally reuses the same path, with the frame dimension folded into the batch dimension.

    (2) Axial rotary position encoding. RoPE is applied separately to the height and width axes, giving the model 2D spatial extrapolation ability so it does not need retraining when resolution changes.

    (3) Variable-length attention. The cumulative sequence lengths cu_seqlens together with max_seqlen allow images of different sizes to be batched together without cross-contamination. This is the core of throughput optimization.

    (4) Final normalization. Stabilizes the output distribution and prepares for the final downsampling.

    (5)(6) Spatial merging and projection. The tensor is first reshaped into 2x2 neighborhoods and then downsampled by convolution. Finally, a projection layer with SwiGLU upscales the dimension to the language model’s hidden space. Compared with a plain linear layer, SwiGLU typically provides better feature representation at the same parameter count.

    5. Engineering Practices

    1. Plan the context budget up front. Estimate the token range based on the business resolution distribution, then set lower and upper thresholds to avoid long-document scenarios being crowded out by images.
    2. Variable length within a batch is the norm. Using cumulative lengths instead of padding to a uniform length significantly reduces wasted computation.
    3. Be conservative on the vision side, aggressive on the language side. Keep the backbone in BF16, then choose quantization strategies for the projection and language side according to platform capabilities.
    4. Control video frames. Frame count directly multiplies the token count, so the sampling strategy affects cost more than encoding efficiency.
    5. Observability is not optional. It is recommended to use general-purpose cloud logging and monitoring/alerting capabilities to build dashboards for token output volume, time-to-first-token latency, and memory usage, so capacity planning has a basis.

    In summary, the value of a lightweight vision encoder lies not in piling on parameters, but in using the combination of “aligned padding + patch merging + budget constraints + variable-length attention” to compress visual information into a token stream that the language model can handle and predict. Mastering this pipeline lets you quickly implement and tune multimodal capabilities on your own models or on Baidu AI Cloud compute and inference platforms.