How a Vision Encoder Turns Images into Tokens: Estimating Memory and Context Budget

    This article explains how a vision encoder converts an image into visual tokens for a multimodal large language model. It covers image preprocessing, patch splitting, 2×2 spatial merging, and projection. It also shows how to estimate token counts, context budget, parameter size, and KV cache memory before deployment.

    In multimodal large language models, images cannot be fed directly into the language model. A vision encoder first converts pixels into a set of continuous features. A spatial merging step and a projection layer then turn these features into visual tokens with the same dimension as the text embeddings. The visual tokens are concatenated with the text tokens, and the language model processes the full sequence through attention. The number of visual tokens determines memory usage, latency, and how many images fit in the context window, so you should calculate these values before deployment.

    1. Two Fusion Approaches and the Pipeline in This Article

    There are two common ways to combine vision and language.

    Approach A is the modular approach. An independent vision model extracts features, and a projection layer connects them to the language model. The two parts are trained separately. The main advantage is that it reuses an existing vision model, so it is quick to build. The drawback is that the visual information enters the model as a single input, so the model has difficulty looking back at the image during generation.

    Approach B is native fusion. The vision encoder is part of the model architecture and is trained jointly with the rest of the model. During generation, the model can decide when to look at the image again. Tasks such as code debugging, interface inspection, and chart analysis depend on repeated visual feedback, so they suit this approach better.

    Dimension Approach A: Modular Approach B: Native Fusion
    Training cost Lower, can be trained in stages Higher, requires joint training
    Deployment complexity Vision and language models can be replaced independently The two parts are coupled, so upgrades require full re-validation
    Suitable tasks Image-text question answering, image captioning Multi-turn visual reasoning, interface and chart understanding

    The pipeline described in this article uses the structure of Approach A. An independent vision encoder extracts features. A 2×2 merge and a projection layer convert them into visual tokens, which are then inserted into the input sequence of the language model. If a task requires the model to look at the image several times during generation, consider Approach B, and verify whether the model actually has this ability.

    Both approaches ultimately feed visual tokens into the language model. As a result, the token counting and memory estimates in this article apply to both. The projection layer aligns visual features with the text representation space, which reduces information loss when data passes between modules. This is an engineering goal. It does not distinguish the two approaches.

    2. Image Preprocessing: Resizing, Normalization, and Zero Padding

    The vision encoder requires input side lengths that are divisible by a specific number. In this pipeline, that key number is 28. The base patch size is 14 pixels, and a 2×2 spatial merge follows. Each visual token therefore covers a 28×28 pixel region. This conclusion holds only for a configuration with a patch size of 14 and a 2×2 merge. If the encoder uses a patch size of 16 with a 2×2 merge, each token covers 32×32 pixels, and all size calculations must be redone.

    Preprocessing runs in the following order.

    1. Proportional resizing. Let the original width be W0 and the original height be H0. The long-side limit is S_max, which this article sets to 980 pixels. The scale factor is s = min(1, S_max / max(W0, H0)). The new size is W = max(1, round(s·W0)) and H = max(1, round(s·H0)). The image is only scaled down, never up, because upscaling adds computation without adding information. When scaling down, use anti-aliased bicubic or bilinear interpolation, and match the interpolation method used during training. For images with extreme aspect ratios, the short side may shrink to very few pixels. In that case, check whether the content remains recognizable.

    2. Normalization. Divide the pixel values by 255 to map them to [0, 1]. Then apply the per-channel mean μ and standard deviation σ used during training: x’ = (x − μ) / σ. The mean and standard deviation must come from the same vision encoder’s training configuration. Replacing them arbitrarily shifts the feature distribution and lowers accuracy. This problem is hard to notice from the outputs alone.

    3. Zero padding for alignment. After normalization, pad the height and width up to the nearest multiple of 28: H_pad = ceil(H/28) × 28 and W_pad = ceil(W/28) × 28. Pad on the right and bottom so that the image content stays at fixed positions, which makes localization easier. In normalized space, 0 corresponds to the mean color of the training data. For this reason, the padding value is 0. Do not pad with pure black pixels before normalization.

    Padded regions must be masked. The self-attention of the vision encoder needs a key padding mask so that valid patches do not attend to padded patches. The exact parameter name depends on the encoder code, so confirm it against the implementation. During the 2×2 merge, one merged cell may contain both image content and padding. That cell still produces one visual token. Confirm that padded patches are masked or zeroed before merging. Padding with zeros without masking causes the model to treat blank areas as part of the image during attention.

    Padding also wastes computation. The padding ratio is r = 1 − (H·W) / (H_pad·W_pad). For W=750 and H=500, H_pad=504 and W_pad=756, so r = 1 − 375000 / 381024 ≈ 1.6%. If the image dimensions are just slightly above a multiple of 28, the padding ratio rises noticeably. In that case, you can resize the image to the nearest multiple of 28 instead. This introduces geometric distortion, so verify the accuracy impact.

    3. Patch Splitting and Spatial Merging

    After padding, the image tensor has shape [3, H_pad, W_pad], with channels first. Next, the pipeline splits the image into patches, encodes them, merges them, and projects them.

    1. Patch splitting. A convolution with stride 14 and kernel size 14 splits the image. Each position of this convolution corresponds to one non-overlapping 14×14 block. The convolution weights are equivalent to applying a linear mapping to each block. This makes it a linear projection of the patches, not a separate encoder. The output feature map has shape [D_v, H_pad/14, W_pad/14]. When flattened, the rows are read first, then the columns, giving P = (H_pad/14) × (W_pad/14) patches with shape [P, D_v].

    2. Visual encoding. The sequence of P patches passes through a vision Transformer. The output keeps the shape [P, D_v]. In this approach, the encoder applies global self-attention across all patches, so the computation grows with P².

    3. 2×2 spatial merging. The feature map is grouped into 2×2 neighborhoods. The features of each group of four patches are concatenated along the channel dimension, producing shape [H_pad/28, W_pad/28, 4·D_v]. Flattening gives [N, 4·D_v]. Merging happens after the encoder, so it does not reduce the encoder’s computation. To lower the encoder cost, you must reduce the number of input patches, which means lowering the resolution.

    4. Projection. A two-layer MLP maps 4·D_v to the hidden dimension of the language model, D_llm. The output shape is [N, D_llm]. These N vectors are the visual tokens.

    Visual tokens are continuous vectors. They are not discrete IDs produced by a tokenizer, and they do not exist in the text vocabulary. They occupy positions in the input sequence and replace the text embeddings at those positions.

    The token count is calculated as follows:

    N = (H_pad / 28) × (W_pad / 28) = ceil(H/28) × ceil(W/28)

    The corresponding patch count is P = 4N. For W=750 and H=500, H_pad=504 and W_pad=756. Therefore N = 18 × 27 = 486 and P = 36 × 54 = 1944, which matches 4N.

    4. Token Budget and Parameter Estimates

    1. Upper limit of visual tokens per image. The long side does not exceed S_max = 980, and the short side does not exceed the long side. Therefore, neither width nor height exceeds 980. Since ceil(980/28) = 35, the maximum N per image is 35 × 35 = 1225.

    2. Context budget. The total input length is L_in = T_text + Σ(N_i + m), where T_text is the number of text tokens and m is the number of boundary tokens per image. This article uses m = 2. The space available for output is T_out = C − L_in, where C is the context window length.

    Example: C = 8192, the text prompt has 600 tokens, and four images are included, each with N = 486. Then L_in = 600 + 4 × (486 + 2) = 2552, and the remaining output space is 8192 − 2552 = 5640 tokens.

    To reserve 1024 tokens for output, with 600 text tokens and 488 tokens per image including boundary tokens, the maximum number of images is floor((8192 − 600 − 1024) / 488) = 13.

    1. Parameter size. Each layer of the vision Transformer has about 12·D_v² parameters. Attention accounts for 4·D_v², and the MLP, with a 4× expansion, accounts for 8·D_v². For L_v layers, the total is about 12·L_v·D_v².

    Example: D_v = 1024 and L_v = 24. The total is about 12 × 24 × 1024² ≈ 3.0 hundred million parameters.

    The projection layer has about 4·D_v·D_llm + D_llm² parameters. For D_llm = 2048, this is about 8.4M + 4.2M ≈ 12.6M.

    These estimates ignore biases, normalization layers, and positional encoding parameters. For actual parameter counts, refer to the model weight files.

    1. KV cache and activation memory. During decoding, each token stores a key and a value. The memory per token is 2 × L × H_kv × d_h × b bytes. Here, L is the number of LLM layers, H_kv is the number of KV heads, d_h is the dimension per head, and b is the number of bytes per value.

    Example: L = 28, H_kv = 4, d_h = 128, and fp16 is used (b = 2). The memory per token is 2 × 28 × 4 × 128 × 2 = 57344 bytes, or 56 KiB. The 486 visual tokens of one image occupy about 486 × 57344 bytes, which is about 26.6 MiB of KV cache.

    The visual encoding stage also uses temporary activations. If the attention does not use a fused kernel, the attention matrix for a single head has P² entries. When P = 1944, each head’s matrix in fp16 is about 1944² × 2 bytes ≈ 7.56 MB, which is about 7.21 MiB. This article uses the binary units KiB and MiB, where 1 KiB equals 1024 bytes. Decimal MB is different, so convert before mixing units.

    1. Latency. Prefill time grows with the total input length, and the visual portion grows with P. During decoding, each generated token reads the entire KV cache. More visual tokens mean more data read at each step.

    2. Trade-offs.

    • Higher resolution: More detail, but N, memory, and latency all increase.
    • More images: Context usage increases, and the available output length decreases.
    • Larger batch size: Throughput increases, but peak memory rises.
    • Lower long-side limit S_max: The maximum tokens per image decrease, and detail loss increases.

    The numbers in this section assume a single request, fp16, and no quantization or inference framework overhead. Actual memory use also includes framework reserved space, temporary tensors, and memory fragmentation.

    5. Inference Pipeline Overview

    Using an input with W=750 and H=500 as an example, the tensor shapes at each step are as follows: