How Vision Encoders Convert Images into Tokens for Large Language Models

    This article explains how vision encoders are integrated into large language models to process images, covering preprocessing steps, token budget control, encoder architecture parameters, and the inference pipeline, with a practical token estimation example.

    Why Vision Capabilities Are Built into the Model

    Early multimodal approaches often handed images to a separate recognition module, which first converted them into text descriptions before passing them to a language model for reasoning. The problem with this approach is that the language model cannot decide when to look at an image, which region to examine, or re-inspect the image based on intermediate reasoning results.

    By placing a vision encoder and a language model in the same training and inference pipeline, the model can treat images as actively callable inputs. This capability is especially important in tasks such as writing code, reading interface screenshots, and diagnosing chart issues. Visual information is not just a one-time input; it can also serve as feedback signals for subsequent actions.

    Understanding this helps define the design goals of the vision module. It needs to compress images and videos of arbitrary resolution into a token sequence that the language model can directly read, while keeping the sequence length controlled so the context budget remains manageable.

    Standard Preprocessing Before Images Enter the Model

    Before an image enters the vision encoder, it usually goes through several preprocessing steps: resizing, zero-padding, and patch merging.

    Resizing and Zero-Padding

    Preprocessing scales the image to a suitable size and then pads it with zeros up to a multiple of 28. The number 28 comes from subsequent operations: the patch size is 14 pixels, and the merging window is 2×2, which multiply to 28. If the dimensions are not a multiple of 28, the boundary regions will be incomplete during merging.

    Zero-padding introduces areas with no information, and these areas still consume token budget. Therefore, scaling should preserve the aspect ratio as much as possible to reduce padding area.

    Patch Splitting and 2×2 Merging

    The image is first cut into 14×14 pixel base patches. Then, adjacent 2×2 patches are merged into one visual unit, so each 28×28 pixel region corresponds to one visual token. The merging operation shortens the sequence and also lets each token carry more complete local information.

    A Calculation Example

    Suppose the input image size is 1000×600 pixels. Width is padded to 1008 pixels (36×28), and height to 616 pixels (22×28). After splitting, there are 72×44 base patches. After 2×2 merging, the result is 36×22 visual tokens, for a total of 792.

    This calculation can be written as a simple function to estimate cost before sending a request:

    1. import math
    2. def estimate_visual_tokens(width: int, height: int, factor: int = 28) -> int:
    3. """Estimate visual token count after 28-pixel alignment"""
    4. aligned_w = math.ceil(width / factor) * factor
    5. aligned_h = math.ceil(height / factor) * factor
    6. return (aligned_w // factor) * (aligned_h // factor)
    7. print(estimate_visual_tokens(1000, 600)) # Output: 792

    Token Budget Control

    The image sizes processed by the same model can vary greatly. A thumbnail may require only a few dozen tokens, while a high-definition screenshot may need thousands. Without limits, a single image could consume the entire context window.

    Therefore, implementations typically set two boundaries: the minimum and maximum number of image tokens. The lower bound ensures that small images still have sufficient expressive power, while the upper bound prevents large images from crowding out other content. In some implementations, the default range is set from 16 to 8000 tokens.

    When the upper bound is exceeded, the processing logic usually scales the image down proportionally. Token count is proportional to image area, so the scaling factor is the square root of the area ratio. When below the lower bound, the image is scaled up in the same manner.

    The choice of budget depends on the task:

    • Optical character recognition, table parsing, and detailed UI inspection: higher resolution is needed, so the budget should be near the upper bound.
    • Scene overview and object classification: lower resolution is usually sufficient, saving context space.
    • Multi-image conversations: the budget should be allocated across the number of images to prevent a single image from dominating the context.

    Architecture Parameters of the Vision Encoder

    The following is a typical lightweight vision encoder configuration, useful for understanding the relationships between parameters:

    Item Value Description
    Number of layers 24 Number of Transformer blocks
    Hidden dimension 1024 Width of the internal representation per patch
    Number of attention heads 16 Parallel branches of multi-head attention
    Head dimension 64 1024 divided by 16
    Patch size 14 Side length of the base patch
    Merging method 2×2 Adjacent 4 patches merged into 1
    Output dimension 4096 Matches the hidden dimension of the language model

    A few notes:

    • The head dimension equals the hidden dimension divided by the number of heads, which is the standard convention for multi-head attention. This configuration does not use grouped-query attention; each head has its own keys and values.
    • The output dimension must match the hidden dimension of the language model; otherwise visual tokens cannot be concatenated with text tokens into the same sequence. A projection layer handles this alignment.
    • Taking a vision encoder with roughly 0.56B parameters as an example, its share of the overall model is typically small. This means the visual branch has relatively manageable overhead in GPU memory and computation, and its precision choice has limited impact on overall resources.

    Inference Pipeline Breakdown

    A single forward pass generally includes the following steps:

    1. Positional encoding: Position IDs are generated based on the image grid dimensions (time, height, width), allowing the model to distinguish the 2D spatial position of each token.
    2. Attention segmentation: Multiple images may be packed in the same batch. An array of cumulative lengths defines the attention scope for each image, preventing cross-image attention.
    3. Patch encoding: The preprocessed image patches are passed through the vision encoder layers to produce visual token embeddings.
    4. Projection: The visual tokens are projected to the language model’s hidden dimension and concatenated with text token embeddings.
    5. Language model forward pass: The combined token sequence is fed into the language model, which performs autoregressive generation or reasoning.