Image Encoding and Token Budgets in Lightweight Vision-Language Models

    Learn how image preprocessing, patch embedding, and 2×2 spatial merging turn pixels into visual tokens in lightweight vision-language models. A worked example and illustrative pseudocode explain how image dimensions affect token counts and how resolution limits help manage context usage and computational cost.

    1. Why Visual Inputs Need a Separate Encoding Path

    Language models process sequences of discrete tokens, while images are continuous, two-dimensional pixel arrays. To make images usable by a language model, the system must first convert pixels into a sequence of vectors with dimensions compatible with text-token representations. A visual encoder typically performs this conversion, forming a multimodal model together with the language backbone.

    Visual inputs incur two main costs: computation within the visual encoder and the context length occupied by visual tokens. Higher image resolutions produce more visual tokens, increasing attention computation and GPU memory usage. In practice, image processing must balance information retention against resource consumption.

    2. Image Preprocessing: Dimension Alignment and Zero Padding

    Visual encoders impose structural requirements on input dimensions. A common approach is to resize an image to a suitable range, then pad its width and height with zero-valued pixels to multiples of a specified factor. This ensures that subsequent patching and merging operations divide the image evenly, without incomplete units at the boundaries.

    Suppose the base patch size is 14 pixels and each group of 2×2 neighboring patches is merged into one unit. Each merged unit then covers a 28×28-pixel region. Padding both dimensions to multiples of 28 ensures divisibility. This alignment factor follows from the patch size and merging factor; it is not an arbitrary choice.

    Zero padding also has a cost. Padded regions contain no useful image information but still generate tokens and consume computation. Images with extreme aspect ratios can have a high proportion of padding. Preprocessing should monitor this proportion, preserve the aspect ratio during resizing, and apply reasonable dimension limits to reduce uninformative regions.

    3. Patch Embedding and 2×2 Merging: From Pixels to Visual Tokens

    Patch embedding is the first step in the visual encoder. The image is divided into non-overlapping square patches, each mapped to a vector through a linear projection of its flattened pixels or through a convolution. Smaller patches retain more detail but produce longer sequences.

    Merging shortens the sequence by concatenating spatially adjacent patch representations and projecting them into output vectors. With 2×2 merging, the sequence length becomes one-quarter of its original length, and each output vector represents a larger local region. The language backbone therefore processes a shorter visual sequence, reducing its computational load.

    Consider an input image that is 1,024 pixels wide and 768 pixels high:

    • Padded dimensions: 1,036 pixels wide (37 × 28) and 784 pixels high (28 × 28).
    • Number of 14×14 patches: 74 columns × 56 rows = 4,144 patches.
    • Visual tokens after 2×2 merging: 4,144 ÷ 4 = 1,036 tokens.
    • Cross-check: The padded image contains 37 × 28 regions of 28×28 pixels. Each region corresponds to one token, giving the same total of 1,036 tokens.

    Video can also be processed along the temporal dimension. One common approach groups adjacent frames along the time axis, uses a 3D convolution to create spatiotemporal patches, and then applies the same merging operation across the spatial dimensions.

    4. Controlling the Visual Token Budget

    The same image can occupy very different amounts of context depending on the task. Everyday conversation often requires only a broad understanding of an image, while document recognition requires higher resolution. A practical approach is to define lower and upper visual-token limits for each image. The upper limit prevents large images from crowding out text context, while the lower limit gives small images sufficient representation capacity.

    The following illustrative pseudocode shows how to apply an upper token-budget constraint when calculating image dimensions. It demonstrates the logic only and does not correspond to any specific API.

    1. def ceil_div(a, b):
    2. return (a + b - 1) // b
    3. def fit_to_budget(width, height, factor=28, max_tokens=8000):
    4. # Estimate the token count before resizing
    5. tokens = ceil_div(width, factor) * ceil_div(height, factor)
    6. if tokens > max_tokens:
    7. # Reduce the area proportionally to approach the token limit
    8. scale = (max_tokens / tokens) ** 0.5
    9. width = int(width * scale)
    10. height = int(height * scale)
    11. # Round down to multiples of factor to ensure divisibility
    12. w = max(factor, (width // factor) * factor)
    13. h = max(factor, (height // factor) * factor)
    14. return w, h, (w // factor) * (h // factor)