Visual Tokenization in Practice: From Arbitrary-Resolution Images to Language-Model Tokens

    This article explains how visual inputs are transformed from arbitrary-resolution images into token sequences that language models can process. It covers resolution alignment, token-budget scaling, patch extraction, spatial merging, Vision Transformer encoding, projection, parameter estimation, precision choices, and deployment considerations such as memory, batching, caching, and video input.

    1. Why Visual Inputs Require Dedicated Design

    Language models process discrete token sequences, while images are continuous pixel matrices. To enable a language model to understand images, a system must convert pixels into vectors that occupy a semantic space compatible with text tokens. This conversion is typically handled by a dedicated vision encoder connected to the language backbone through a projection layer.

    Visual input design involves three major challenges. First, image resolutions vary significantly. The same model may need to process images that are only a few dozen pixels wide as well as high-resolution screenshots or video frames. Second, the number of visual tokens directly consumes the context window. As resolution increases, token count and inference cost also increase. Third, visual information must preserve spatial structure. The relative positions of text, table lines, and interface elements are essential for fine-grained tasks. If these relationships are lost during encoding, the model becomes less capable of handling such tasks.

    As a result, most visual encoding pipelines focus on three goals:

    • Standardize the input shape.
    • Control the number of visual tokens.
    • Preserve spatial information.

    The following sections describe each stage in the order data flows through the system, along with the key trade-offs involved.

    2. The Overall Visual Encoding Pipeline

    A typical visual encoding pipeline contains four stages:

    1. Image preprocessing: Resize the image and pad it to a required multiple.
    2. Patch extraction: Divide the image into fixed-size patches.
    3. Spatial merging: Combine neighboring patches into larger units to reduce sequence length.
    4. Encoding and projection: Extract features with a Vision Transformer and map them to the language model’s hidden dimension.

    Each stage produces the input for the next one. Changing parameters at any stage affects the final token count and memory usage, so the pipeline should be designed as a whole rather than optimized one component at a time.

    3. Image Preprocessing: Resizing and Zero Padding

    3.1 Aligning Dimensions to the Merging Unit

    Convolution and patch-extraction operations generally require input dimensions to be divisible by a fixed stride. If the base patch size is p and the merging factor is m, the minimum alignment unit is:

    1. p × m

    For example, with a patch size of 14 and a merging factor of 2, the alignment unit is 28. Both the image height and width must be padded to multiples of 28. Otherwise, edge regions may be truncated or produce an invalid tensor shape.

    Two common approaches are used:

    • Zero padding: Add black or neutral-colored pixels to the right and bottom edges. This preserves the original aspect ratio.
    • Direct resizing: Resize the image to the target dimensions. This changes the aspect ratio but may be acceptable when geometric distortion is not important.

    Most general-purpose systems prefer padding because it does not distort text or geometric structures.

    3.2 Scaling According to a Token Budget

    If an image is too large, aligning it directly can produce an excessive number of visual tokens. Preprocessing therefore commonly includes a token budget. The system defines minimum and maximum token counts, estimates the number of tokens corresponding to the original image, and then scales the image proportionally:

    • If the token count exceeds the maximum, the image is scaled down.
    • If the token count is below the minimum, the image is moderately enlarged.

    This approach gives small images enough detail while preventing high-resolution images from consuming the entire context window.

    Illustrative pseudocode:

    1. function preprocess_image(img, patch=14, merge=2, min_tokens=16, max_tokens=8000):
    2. unit = patch * merge # Alignment unit, 28 in this example
    3. h, w = img.height, img.width
    4. # Estimate the token count for the current resolution
    5. tokens = ceil(h / unit) * ceil(w / unit)
    6. # Scale proportionally according to the token budget
    7. scale = budget_scale(tokens, min_tokens, max_tokens)
    8. new_h = ceil(h * scale / unit) * unit
    9. new_w = ceil(w * scale / unit) * unit
    10. img = resize(img, new_h, new_w)
    11. img = pad_to_multiple(img, unit) # Pad the remaining area with zeros
    12. return img

    The min_tokens and max_tokens values above are examples only. In practice, they should be selected based on available memory, context length, and task requirements.

    4. Patch Extraction and Spatial Merging

    4.1 Patch Extraction

    Patch extraction divides an image into equally sized, non-overlapping regions. With a patch size of 14, a 560 × 560 image produces:

    1. 40 × 40 = 1,600 patches

    Each patch is flattened into a one-dimensional vector and projected into the encoder’s hidden dimension through a linear layer. The extraction step itself is relatively inexpensive; most of the computational cost comes from subsequent attention operations.

    Smaller patches preserve more detail but create longer sequences. Because attention cost grows quadratically with sequence length, this can significantly increase computation. Larger patches reduce sequence length but may lose small text and fine edges. A patch size of 14 is a common compromise between detail preservation and efficiency.

    4.2 Spatial Merging

    Spatial merging combines neighboring 2 × 2 patches into a larger unit. The channel dimension increases while the spatial resolution is reduced by half. After merging, each unit represents a 28 × 28 region of the original image.

    This operation acts as a simple form of spatial downsampling. It reduces the sequence length to one quarter of the original size while retaining local spatial arrangement.

    Two common merging strategies are:

    1. Channel concatenation followed by a linear layer: This is simple and generally loses little information.
    2. A strided convolution: This introduces learnable local aggregation but increases the number of parameters.

    General-purpose implementations often favor concatenation followed by linear projection because the structure is straightforward and easier to optimize for inference.

    4.3 Estimating the Number of Visual Tokens

    After merging, each 28 × 28 image region corresponds to one visual token. The token count can therefore be estimated as:

    1. Number of tokens ≈ ⌈H / 28⌉ × ⌈W / 28⌉

    Typical examples include:

    Input Size Aligned Size Number of Visual Tokens
    224 × 224 224 × 224 8 × 8 = 64
    560 × 560 560 × 560 20 × 20 = 400
    1024 × 1024 1036 × 1036 37 × 37 = 1,369

    As the table shows, doubling the resolution causes the token count to approach four times the original value. Estimating token counts before deployment is therefore a basic step in controlling cost and memory usage.

    5. The Vision Encoder: Key Vision Transformer Design Considerations

    5.1 Core Parameters

    The vision backbone generally uses a standard Vision Transformer architecture. Its key hyperparameters include:

    • Depth: Determines how deeply features are abstracted. More layers usually provide greater representational capacity but increase latency.
    • Hidden size: Determines the width of each token vector.
    • Number of attention heads: Allows attention to operate across multiple subspaces in parallel.
    • Head dimension: Usually equals the hidden size divided by the number of heads. For example, with a hidden size of 1,024 and 16 attention heads, the head dimension is 64.
    • Output dimension: Must match the language model’s hidden dimension, or an additional projection layer is required.

    Alignment between the vision encoder and the language model is often one of the performance bottlenecks. When the output dimensions do not match, the quality of the projection layer directly affects how effectively the language model can use visual information.

    5.2 Estimating Parameter Count

    For a standard Transformer layer with hidden dimension d and a feed-forward expansion ratio of 4, the parameter count per layer is approximately:

    1. 12 · d²

    The attention components account for roughly 4 · d², while the feed-forward network accounts for approximately 8 · d². With L layers, the backbone parameter count is approximately:

    1. 12 · L · d²

    The actual value depends on the feed-forward expansion ratio, whether a gated architecture is used, and other design choices. These formulas are therefore intended only for order-of-magnitude estimates.

    Parameter estimation helps determine the visual branch’s share of total memory usage. When the vision branch has relatively few parameters, it may not be the primary memory bottleneck. However, its activations and attention matrices still grow with the number of visual tokens and must be calculated separately.

    5.3 Attention Scope

    Vision encoders commonly use global attention, allowing every token to attend to every other token in the image. This enables long-range spatial relationships, such as identifying a table header that spans multiple rows.

    The cost is that attention computation grows quadratically with the number of tokens. For extremely high-resolution inputs, block attention or window attention may be considered, but their impact on global relationships must be evaluated.

    6. Inference Precision and Deployment Considerations

    Inference precision for the visual branch should be decided independently. A common strategy is to keep the vision encoder at relatively high precision, such as BF16, while using FP8 or INT8 quantization for the language backbone when resources are limited.

    The reason is that numerical errors in visual features are passed directly to the language model after projection. Even small deviations may affect fine-grained tasks such as text recognition.

    Deployment should also account for the following factors:

    1. Peak memory: The attention matrix grows with the square of the token count, so stress testing is required at the maximum supported resolution.
    2. Batching: Different images may produce different token counts. Batches must use padding or grouping by length; otherwise, compute resources are wasted.
    3. Caching: If the same image is provided repeatedly across multiple conversation turns, its visual features can be cached to avoid repeated encoding.
    4. Video input: Video usually requires frame sampling. The frame rate and per-frame token budget should be configured together to control the total context length.

    7. Example: Complete Visual Input Module Pseudocode

    The following pseudocode illustrates the complete path from a raw image to the language model input:

    1. function encode_visual_input(img):
    2. img = preprocess_image(img) # Align dimensions and scale by budget
    3. patches = split_into_patches(img, patch=14) # Split into 14x14 patches
    4. patches = merge_2x2(patches) # Merge 2x2 patches; each unit covers 28x28 pixels
    5. feats = vision_encoder(patches) # Vision Transformer backbone
    6. tokens = projector(feats) # Project to the language model hidden dimension
    7. return tokens # Concatenate with text tokens before inference

    Three implementation details are especially important:

    • The size information used during preprocessing must remain consistent with the encoding stage.
    • The projection layer’s output dimension must match the language model.
    • The positions of visual tokens in the sequence must be distinguished through positional encoding or special markers.

    8. Common Questions and Design Trade-Offs

    Q: Does higher resolution always produce better results?

    Not necessarily. Resolution beyond what the task requires only increases token count and latency. Text recognition benefits from higher resolution, while image classification and coarse scene understanding can often use lower resolution.

    Q: Should the system use a fixed token count or a fixed resolution?

    Fixed resolution is simpler to implement, but input shapes can vary significantly and reduce batching efficiency. Dynamic scaling based on a token budget keeps token counts more stable and is often better suited to production environments, although the system must handle detail loss caused by resizing.

    Q: Does zero padding reduce model quality?

    Padding regions produce meaningless tokens. A reasonable approach is to train or configure the model to recognize padding regions, or to mask those positions during attention.

    9. Conclusion

    The core purpose of a visual input module is to convert images of arbitrary sizes into token sequences with controlled length while preserving spatial structure. Preprocessing aligns dimensions and enforces the token budget. Patch extraction and spatial merging compress the sequence. Encoding and projection align visual features with the language model’s semantic and hidden spaces.

    Every stage involves trade-offs. The design should begin with estimates of token count and memory usage, followed by decisions about resolution, patch size, and numerical precision. Once this pipeline is understood, developers can adjust visual input configurations more systematically and find a practical balance between quality and cost.