Vision Module Breakdown: How to Calculate Token Counts and Parameter Size

    This article explains how a vision encoder converts images into visual tokens, including padding, patch extraction, 2×2 token merging, token-budget control, tensor shape changes, and parameter estimation. It also highlights why a reported 0.56B total may not match the listed architecture and outlines key deployment checks for precision, latency, and context-length limits.

    Key Takeaways

    A vision encoder divides an image into small patches and merges every 2×2 group of adjacent patches into one visual token. The number of tokens depends only on the padded image width and height.

    With the representative configuration discussed here, the vision backbone has approximately 0.30B parameters. However, the reported total of 0.56B cannot be explained by the components listed in the architecture. The counting methodology should therefore be verified before quoting that figure.

    Vision Module Architecture and Parameter Estimates

    Lightweight multimodal models often use a reduced Vision Transformer (ViT) as the visual backbone. The representative configuration includes:

    • 24 layers
    • Hidden dimension: d = 1024
    • 16 attention heads
    • Head dimension: 64 (1024 / 16 = 64)
    • Output dimension: 4096, matching the language model hidden size

    This configuration does not use grouped-query attention (GQA). GQA primarily reduces the size of the key-value cache during autoregressive decoding. Because a ViT performs a single forward pass rather than step-by-step decoding, the benefit of GQA is limited in this part of the model.

    The parameter estimate can be broken down as follows:

    Component Calculation Approximate size
    Patch embedding 14 × 14 × 3 × 1024, plus 1,024 bias terms 0.60M
    Attention per layer 4d² (3d² for QKV plus d² for the output projection) 4.19M/layer, approximately 100.7M for 24 layers
    MLP per layer Expansion ratio of 4: 2 × 4d² = 8d² 8.39M/layer, approximately 201.3M for 24 layers
    Backbone total 12d² × 24 Approximately 0.30B
    Projection layer One 1024 × 4096 linear layer Approximately 4.2M
    Positional encoding Depends on the maximum resolution, which is not specified Unknown

    The listed components total approximately 0.31B parameters. The reported overall size of approximately 0.56B leaves a gap of about 0.25B parameters.

    No component in the table can account for this difference. Even if the entire gap were assigned to the MLP, the expansion ratio would need to be approximately 9, contradicting the stated ratio of 4. The discrepancy is more likely caused by differences in layer count, hidden width, additional modules, or parameter-counting conventions. Before citing the 0.56B figure, verify exactly which components it includes.

    A useful approximation for checking the parameter scale is:

    1. Parameter count ≈ number of layers × (4 + 2r) × d²
    2. + embedding parameters
    3. + projection parameters

    Here, r is the MLP expansion ratio. Substituting the stated configuration with r = 4 gives approximately 0.30B parameters for the backbone and approximately 0.31B after adding the embedding and projection layers.

    The visual module’s share of the full model depends on the language model size. If the language component has 7B parameters:

    1. 0.56 / (7 + 0.56) ≈ 7.4%

    If the 7B language component alone is used as the denominator, the ratio is approximately 8.0%. When reporting this percentage, always state which denominator was used.

    How an Image Becomes Visual Tokens

    Step 1: Resize and Zero-Pad

    The image is first resized as required. Zero padding is then added to the right and bottom so that both dimensions are multiples of 28.

    The value 28 comes from the 14-pixel base patch size and the 2×2 merging window:

    1. 14 × 2 = 28

    Padding ensures that every merge window is complete and that the merging operation does not cross image boundaries.

    The padded dimensions are:

    1. H_pad = ceil(H / 28) × 28
    2. W_pad = ceil(W / 28) × 28

    Consider an image with dimensions 500 × 300 pixels. Along the width:

    1. 500 / 28 ≈ 17.86
    2. ceil(500 / 28) = 18
    3. 18 × 28 = 504

    Along the height:

    1. 300 / 28 ≈ 10.71
    2. ceil(300 / 28) = 11
    3. 11 × 28 = 308

    The padded image is therefore 504 × 308 pixels. The padded area accounts for approximately 3.4% of the total padded image area:

    1. (155,232 − 150,000) / 155,232

    Step 2: Split into Patches and Merge 2×2 Groups

    The padded image is divided into 14 × 14 base patches. A 504 × 308 image produces:

    1. 36 × 22 = 792 base patches

    Every four adjacent patches are then merged into one visual token:

    1. 18 × 11 = 198 visual tokens

    The token-count formula is:

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

    Therefore, the 500 × 300 image produces 198 visual tokens. Even if either image dimension is smaller than 28 pixels, the padded image still produces at least one token.

    Controlling the Visual Token Budget

    The number of visual tokens is approximately proportional to the total number of pixels. Ignoring padding, each token represents:

    1. 28 × 28 = 784 pixels

    Given a maximum token budget T_max, the corresponding pixel budget is approximately:

    1. T_max × 784
    Target token limit Pixel limit Equivalent square image
    256 200,704 448 × 448
    1,280 1,003,520 Approximately 1,000 × 1,000

    A practical budgeting procedure is:

    1. If the image exceeds the token limit, resize it proportionally.
    2. Round the resulting height and width down to multiples of 28.
    3. Apply the minimum dimension of 28 pixels.

    Rounding down helps prevent padding from pushing the final token count beyond the budget.

    1. def fit_budget(H, W, max_tokens):
    2. max_pixels = max_tokens * 28 * 28
    3. if H * W > max_pixels:
    4. s = (max_pixels / (H * W)) ** 0.5
    5. H, W = int(H * s), int(W * s)
    6. H = max(28, H // 28 * 28)
    7. W = max(28, W // 28 * 28)
    8. return H, W, (H // 28) * (W // 28)

    The visual token budget must also be considered together with the text budget. Visual tokens plus text tokens must remain within the language model’s context length. More visual tokens preserve more image detail, but they also increase language-model forward-pass computation and KV-cache usage.

    Tensor Shape Changes During Inference

    The following pseudocode illustrates a general processing flow. It does not correspond to a specific product. The input image is the padded 504 × 308 image, with batch size B = 1.

    1. # Input: pixel [1, 3, 308, 504]
    2. x = patch_embed(pixel) # Conv2d(3, 1024, k=14, s=14) -> [1, 1024, 22, 36]
    3. x = x.flatten(2).transpose(1, 2) # -> [1, 792, 1024]
    4. for blk in vit_blocks: # 24 layers; input and output are [1, 792, 1024]
    5. x = blk(x)
    6. # 2x2 merging: divide the 22x36 grid into 11x18 groups
    7. grid = x.view(1, 22, 36, 1024) # [1, 22, 36, 1024]
    8. grid = grid.view(1, 11, 2, 18, 2, 1024) # [1, 11, 2, 18, 2, 1024]
    9. grid = grid.permute(0, 1, 3, 2, 4, 5) # [1, 11, 18, 2, 2, 1024]
    10. vis = grid.reshape(1, 198, 4096) # [1, 198, 4096]
    11. vis = proj(vis) # Optional Linear(4096, 4096); shape unchanged
    12. text_emb = embed(input_ids) # [1, L, 4096]
    13. seq = concat(text_before, vis, text_after) # [1, L + 198, 4096]
    14. logits = llm(seq) # [1, L + 198, vocab_size]

    After 2×2 merging, the feature dimension is:

    1. 1024 × 4 = 4096

    This matches the language model hidden size, so no additional dimension conversion is required. If a projection layer is added after merging, the tensor shape remains unchanged, but the parameter count increases.

    Deployment Risks and Validation Checklist

    Matching Dimensions Does Not Guarantee Semantic Alignment

    Matching tensor shapes only means that the tensors can be concatenated. It does not guarantee that visual and language features occupy compatible semantic spaces.

    Alignment must be learned during training through mechanisms such as projection-layer training, image-text alignment data, and special image-boundary tokens. Whether visual features can be passed directly to the language model depends on the specific architecture and must be confirmed by inspecting its implementation.

    BF16 and FP8

    BF16 and FP32 both use 8 exponent bits, so they have the same dynamic range. BF16 can therefore reduce memory usage while retaining a similar numerical range.

    Whether FP8 is suitable must be validated with representative data. The validation checklist should include:

    1. Calibration data: Cover the image types and resolutions expected in the target workload.
    2. Error metrics: Compare visual-feature cosine similarity or downstream task accuracy.
    3. Acceptance thresholds: Derive thresholds from business or application requirements rather than directly reusing values from another system.
    4. Fallback strategy: Switch back to BF16 when results do not meet the target, and keep the fallback configurable.

    Latency and Resolution

    Self-attention in the vision encoder scales quadratically with the number of patches. In this example, the encoder processes 792 patches, which is substantially more than the 198 tokens produced after merging.

    Increasing the input resolution raises both the patch count and the computational cost. Measure end-to-end latency at the target resolutions before deployment.

    Input Validation

    Images with zero, extremely small, or excessively large dimensions should be rejected or resized before processing. This helps prevent invalid operations and excessive memory consumption.

    Final Checklist

    Before deployment, verify the following:

    • The padded height and width are multiples of 28.
    • The visual token count matches the token-count formula.
    • The parameter-counting scope is clearly defined.
    • Tensor shapes at each processing stage match the expected values.
    • The combined visual-token and text-token count fits within the context length.