Multimodal LLM Architecture: Aligning Vision Features with Language
Multimodal LLM Architecture: Aligning Vision Features with Language
Search
Ask the AI

Multimodal LLM Architecture: Aligning Vision Features with Language

In Multimodal Large Language Models (MLLMs), Modality Alignment converts visual features into continuous representations that a language model can consume. Text token IDs are discrete; text embeddings and the visual representations supplied to the LLM are continuous vectors.

End-to-End Architecture Overview

LLaVA and BLIP-2 can both be understood in terms of a vision encoder, connector and language model. The diagram is a simplified data flow: models may use visual prefixes or other fusion paths, and BLIP-2 supports both decoder-only and encoder–decoder language models.


graph TD
    A[Image Input] --> B[Vision Encoder ViT]
    B -->|Patch Embeddings| C[Modality Projection / Q-Former]
    C -->|Visual Tokens| D[Large Language Model]
    E[Text Input] -->|Text Tokens| D
    D --> F[Autoregressive Text Output]
    
    classDef encoder fill:#f9f,stroke:#333,stroke-width:2px;
    classDef projection fill:#bbf,stroke:#333,stroke-width:2px;
    classDef llm fill:#bfb,stroke:#333,stroke-width:2px;
    
    class B encoder;
    class C projection;
    class D llm;

The Mathematics of Alignment: Q-Former and Cross-Attention

An MLP maps features position by position. BLIP-2’s Q-Former instead aggregates visual features with learned queries and Cross-Attention. With a fixed query count, the number of output queries does not change with input patch count. These are different connectors, not a simple-to-advanced quality ranking.

Given the learned queries \(Z \in \mathbb{R}^{N \times D_q}\) and the image patch embeddings \(X \in \mathbb{R}^{M \times D_v}\), the cross-attention mechanism operates by projecting these into Query, Key, and Value matrices:

$$ Q = Z W_Q, \quad K = X W_K, \quad V = X W_V $$

Where \(W_Q \in \mathbb{R}^{D_q \times d_k}\), \(W_K \in \mathbb{R}^{D_v \times d_k}\), and \(W_V \in \mathbb{R}^{D_v \times d_v}\) are learnable weight matrices. The attention output is then computed as:

$$ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V $$

In this single-head sketch, softmax normalizes over visual keys and returns an N×dv output, aggregating \(M\) input positions into \(N\) query outputs. A full Q-Former also has self-attention and feed-forward blocks, and its query representations are mapped to the LLM width. The formula alone does not guarantee retention of task-relevant information.

Implementation: MLP Projection Layer in PyTorch

LLaVA-1.5 uses a two-layer GELU MLP to map ViT features to the LLM dimension \(D_{LLM}\). The program below preserves the patch axis and transforms only the last dimension; it does not select, merge or compress patches.


import torch
import torch.nn as nn

class ModalityProjection(nn.Module):
    def __init__(self, vit_dim=1024, llm_dim=4096):
        super().__init__()
        # 2-Layer MLP with GELU activation
        self.proj = nn.Sequential(
            nn.Linear(vit_dim, llm_dim),
            nn.GELU(),
            nn.Linear(llm_dim, llm_dim)
        )
        
    def forward(self, visual_features):
        """
        Args:
            visual_features: Tensor of shape (batch_size, num_patches, vit_dim)
        Returns:
            visual_tokens: Tensor of shape (batch_size, num_patches, llm_dim)
        """
        visual_tokens = self.proj(visual_features)
        return visual_tokens

# Example usage
vit_output = torch.randn(2, 256, 1024) # Batch of 2, 256 patches, 1024 dims
projector = ModalityProjection(vit_dim=1024, llm_dim=4096)
llm_inputs = projector(vit_output) # Shape: (2, 256, 4096)

The connector and processor jointly determine token count

At deployment, how many tokens each emits is a consequential difference between an MLP and a Q-Former. That count affects context usage, time-to-first-token, and VRAM.

This MLP is per-patch, so output and input patch counts match. For one 336×336 grid with 14×14 patches, no CLS and no merging, (336/14)² = 576. Total visual tokens entering the LLM also depend on crops, a global view, merging, unpadding and separators. A larger source image can instead increase the number of fixed-resolution crops.

A Q-Former is fixed-length: no matter how many patches come in, the output token count equals the number of learnable queries. BLIP-2 uses 32.

MLP projection:  576 patches -> 576 tokens   (grows with resolution)
Q-Former:        576 patches ->  32 tokens   (constant)

The 576/32 token-count ratio is 18, and the visual-only position-pair ratio is 324. That is not a 324-fold total-compute or latency ratio: with T text tokens, dense attention compares (T+576)²/(T+32)² pairs. Vision encoding, Q-Former query–image cross-attention, MLP/FFN operations and memory access add costs; kernels also differ in whether they materialize attention matrices.

Compare task information and sequence cost together. A per-patch MLP preserves the number of positions, not every pixel or detail. Fixed queries create an information bottleneck, but whether it loses OCR, counting or localization information requires task-specific evaluation.

Define OCR, counting, localization, description and VQA tests before choosing a connector. Hold the encoders, language model, training data and budget fixed, then record task scores, failures, visual token counts, memory and time to first token. The names MLP and Q-Former alone do not determine task suitability.

For how token count converts into actual VRAM and latency, see KV Cache VRAM Explosion When Deploying Multimodal LLMs.

Check positional-embedding contracts when changing the encoder grid

Changing a fixed absolute-position grid requires checking how the position table matches. A pretrained higher-resolution checkpoint, dynamic positional scheme or fixed-size tiling path can use a different treatment; manual interpolation is not universal.

For a 224×224 CLIP ViT-L/14 with 14×14 patches, the spatial grid has 16×16=256 positions. Directly changing the grid to 336×336 creates 24×24=576 spatial positions, 320 more than the original table, with CLS handled separately. CLIP also provides ViT-L/14@336px; LLaVA-1.5 uses that checkpoint, rather than merely enlarging a 224 checkpoint’s input.

An implementation may reject mismatched inputs or provide an explicit interpolation option; inspect its contract rather than assuming silent truncation or zero-padding. An AnyRes-style processor can divide the image into fixed-size views, each retaining the encoder’s original grid.

For an implementation that uses absolute-position interpolation, reshape the spatial table as a 2D grid and bicubically interpolate it. This teaching function covers batch 1, square grids and one CLS position, using torch imported earlier:

import torch.nn.functional as F

def interpolate_pos_embed(pos_embed, old_grid, new_grid):
    """pos_embed: (1, old_grid*old_grid + 1, dim); index 0 is CLS"""
    cls_tok, grid_tok = pos_embed[:, :1], pos_embed[:, 1:]
    dim = grid_tok.shape[-1]
    grid_tok = grid_tok.reshape(1, old_grid, old_grid, dim).permute(0, 3, 1, 2)
    grid_tok = F.interpolate(grid_tok, size=(new_grid, new_grid),
                             mode='bicubic', align_corners=False)
    grid_tok = grid_tok.permute(0, 2, 3, 1).reshape(1, new_grid * new_grid, dim)
    return torch.cat([cls_tok, grid_tok], dim=1)

Two places this goes wrong: the CLS token’s embedding must be excluded from interpolation — it is not part of the spatial grid, so slice it off and concatenate it back afterwards; and interpolation must happen on the 2D grid shape, because interpolating the flattened sequence directly blends the end of each row into the start of the next.

Interpolation supplies an initial position table for the new grid. The need for additional fine-tuning and the task effect depend on the checkpoint and target resolution; worse results without fine-tuning are not guaranteed.

Visual tokens borrow a one-dimensional positional encoding

Selection also needs to account for positional encoding.

In a decoder that concatenates visual features and retains its ordinary text positional scheme, LLM position indices are one-dimensional. Other MLLMs use multiaxis schemes, such as Qwen2-VL’s M-RoPE, so check the architecture.

With row-major flattening, same-row horizontal neighbors differ by 1 and vertical neighbors differ by a row width. On a 24×24 grid that vertical offset is 24. Sequence distance does not directly encode 2D Euclidean distance, but the original coordinates are recoverable when grid shape is known.

patch grid            flattened sequence index
┌──┬──┬──┐
│ 0│ 1│ 2│           horizontal neighbour: |0-1| = 1
├──┼──┼──┤           vertical neighbour:   |0-3| = 3   (24 with 24 columns)
│ 3│ 4│ 5│
└──┴──┴──┘

The vision encoder can incorporate spatial information into features, and later modules can learn spatial relations. Flattening alone does not explain a model’s spatial-reasoning failures. Check visual features, positional design, training data and task outcomes rather than assigning a single cause from the representation.

Compare row separators, multiaxis rotary positions and training choices. Validate spatial tasks on specified inputs and evaluation sets; larger LLMs, different interfaces and additional training can each matter. A capacity effect cannot be excluded without a controlled comparison.

Production Pitfalls: Linear vs. 2-Layer MLP

Linear and two-layer MLP connectors differ in expressivity, parameters and computation. LLaVA-1.5 reports task improvements in its controlled connector comparison; that does not establish universally faster convergence, lower loss or fewer hallucinations in deployment.

  • Linear Projection (LLaVA-1.0): Uses a single nn.Linear layer.
    • Pros: Fewer parameters and matrix operations than the two-layer MLP here at matched widths.
    • Cons: A single affine layer adds no connector nonlinearity. Whether this limits task quality requires matched encoders, data and training budgets.
  • 2-Layer MLP (LLaVA-1.5+): Uses an MLP with non-linear activation (e.g., GELU).
    • Pros: GELU adds nonlinear expressivity to the connector. Effects on convergence, final loss and hallucination require separate measurements rather than inference from layer count.
    • Cons: The second square layer adds parameters and computation. Including biases, 1024→4096→4096 has 20,979,712 parameters versus 4,198,400 for one 1024→4096 layer. Its fraction of the full model depends on the backbone.

Selection: Check the checkpoint’s actual connector and visual processor, then compare linear, MLP and query-based compression on the same task and budget. Retain training, memory, latency and failure records and choose from those results.

Leave a Reply

Scroll down