How Images Are Converted into Vision Tokens for Large Language Models

    This article explains how a vision encoder transforms image pixels into a sequence of vision tokens that a large language model can process. It covers preprocessing, patch extraction and merging, token budget control, Transformer-based encoding, two-dimensional positional encoding, and the shape changes that occur throughout the pipeline.

    1. Why Visual Inputs Need a Dedicated Encoding Pipeline

    Large language models process discrete token sequences, while images and videos are continuous pixel matrices. A conversion module is therefore required to map pixels into a sequence of vectors that the language model can read directly. This module is typically called a vision encoder. Its output is concatenated with text tokens and passed together into the language model’s attention layers.

    A vision encoder generally has three design goals:

    1. Support inputs with different resolutions.
    2. Control how much context each image consumes.
    3. Preserve enough spatial structure for the model to identify object locations, text arrangement, and interface layouts.

    These goals directly affect whether the model can reliably read code screenshots, interpret interface controls, or verify chart data.

    2. Overview of the Pipeline

    A typical visual encoding pipeline consists of four stages:

    1. Preprocessing: Resize the image and pad its boundaries so that its dimensions meet the requirements of later partitioning.
    2. Patch extraction and merging: Divide the image into fixed-size patches, then merge neighboring patches.
    3. Encoding: Extract features through multiple Transformer blocks while preserving spatial information with two-dimensional positional encoding.
    4. Projection: Map the resulting features to the language model’s hidden dimension and use them as visual token inputs.

    Each stage changes the shape of the data. Understanding these shape transformations is essential for troubleshooting the pipeline.

    3. Image Preprocessing: Dimension Alignment and Zero Padding

    Vision encoders impose implicit constraints on input dimensions. Consider a configuration with 14 × 14 patches and 2 × 2 patch merging. One visual token then represents a 28 × 28 pixel region, because 14 is multiplied by 2.

    If an image’s width or height is not divisible by 28, it cannot be fully partitioned into visual tokens. Preprocessing therefore usually involves two steps:

    • Resize the image proportionally to an appropriate range to control computational cost.
    • Add zero padding on the right or bottom so that both the width and height become multiples of 28.

    Zero padding introduces a small amount of invalid image area but adds only a limited number of tokens. Compared with forcibly stretching the image, padding preserves the original aspect ratio, preventing distortion in text and visual structures. This generally makes recognition more reliable.

    4. Patch Extraction and 2 × 2 Merging

    The image is first divided into 14 × 14 pixel patches. Each patch is then mapped through a linear transformation into a vector. Next, every spatial group of four neighboring patches is merged into one position.

    After merging:

    • The feature dimension becomes four times larger.
    • The sequence length becomes one-fourth of its original size.

    This operation serves two purposes:

    • It reduces the number of tokens passed to the language model, lowering the cost of attention computation.
    • It aggregates information from four local regions into the same position while retaining local details.

    The following pseudocode illustrates the shape changes:

    1. # Example: patch extraction and merging, showing only shape changes
    2. patches = split_into_patches(image, patch=14) # (H/14, W/14, C)
    3. patches = group_2x2(patches) # (H/28, W/28, 4C)

    5. Controlling the Token Budget

    The number of tokens generated for an image is determined primarily by its pixel area. A rough estimate is:

    1. Number of tokens ≈ (width / 28) × (height / 28)

    To accommodate different use cases and context budgets, implementations usually define two limits:

    • Minimum token count: Ensures that small images still have enough representational capacity.
    • Maximum token count: Prevents a large image from consuming the entire context window.

    With the example configuration, a minimum of 16 tokens corresponds approximately to a 112 × 112 pixel region, while a maximum of 8,000 tokens corresponds to an image on the order of 2,500 × 2,500 pixels.

    Images exceeding the maximum must be proportionally reduced. Images below the minimum can be enlarged as needed.

    Practical guidelines include:

    • Document and table processing usually requires more tokens to keep small text legible.
    • For simple interface screenshots or conversations containing multiple images, the maximum can be reduced to reserve context for text and previous turns.

    6. Encoder Backbone: Transformer Blocks and Two-Dimensional Positional Encoding

    The encoder is built by stacking multiple Transformer blocks. The following parameters are example settings used to illustrate the calculation:

    • 24 layers
    • Hidden dimension: 1,024
    • 16 attention heads
    • Dimension per attention head: 64

    Each layer contains self-attention and a feed-forward network, along with residual connections and normalization.

    A language model processes a one-dimensional sequence, whereas an image has two spatial dimensions: rows and columns. Two-dimensional rotary positional encoding divides positional information into horizontal and vertical components and applies them to different feature subspaces. This allows attention to capture relative relationships such as above, below, left, and right.

    For tasks involving control placement or table rows and columns, this design represents spatial relationships more directly than one-dimensional positional encoding.

    Images can produce different numbers of tokens. In practice, sequences in the same batch are often concatenated into one long sequence, while a cumulative-length array marks the boundaries between images. This avoids padding all images to the same length with invalid tokens and reduces wasted computation.

    A simplified example is shown below:

    1. def encode_image(pixels, grid_thw):
    2. pos_ids = build