On this page
A single chart or photograph reveals the core tension in multimodal engineering. Type "line chart showing latency spike" into an image search bar and a dual-encoder index finds matching figures across millions of images in milliseconds. Ask that same 768-number embedding to read a 14:02 axis tick, count three red markers, or reconcile the chart with a 40-second spoken clip, and it goes completely blind.
Pixels, audio spectrograms, and text tokens live in different coordinate systems and arrive at wildly different token rates. Global pooling makes retrieval fast, whereas grounded reasoning demands keeping spatial patch tokens alive and bridging them into a language model without overflowing context windows or KV-cache memory.
Contrastive dual-encoders: CLIP and SigLIP
CLIP (Contrastive Language-Image Pre-training) aligned whole images and captions inside one shared hypersphere from 400 million web (image, text) pairs.[1] It runs an image tower (ResNet or ViT) and a Transformer text tower independently, joining them only at the output via linear projections and L2 normalization. That late-fusion design lets you embed millions of images offline and rank them against any text prompt with a single dot product.
CLIP symmetric InfoNCE loss
For paired L2-normalized image and text embeddings , CLIP builds the scaled cosine logit matrix , where is a learned log-scale (with initialized at , so , and clamped at ).[1] The diagonal pairs are positives and the off-diagonal pairs serve as in-batch negatives under symmetric InfoNCE cross-entropy:
CLIP trained with so every image competed against 32,767 negative captions.[1] Two details trap engineers immediately. First, default CLIP encode_image and encode_text return unnormalized features (with a 77-token text cap);[2] skipping L2 normalization lets high-norm captions beat closer directional matches. Second, when two rows in a large batch depict the same concept, InfoNCE treats their off-diagonal pair as a false negative and pushes matching representations apart.
SigLIP: pairwise sigmoid loss
CLIP's batch-wide softmax forces every GPU to synchronize global normalizers. SigLIP (Sigmoid Loss for Language-Image Pre-training) replaces softmax with independent pairwise binary classification:[3]
Here on the diagonal and off-diagonal, starts at , and learned bias starts at to reflect negative-heavy batches. Crucially, SigLIP sums all pair losses and divides by , not (dividing by shrinks loss and gradients by an extra factor of ). Removing the shared denominator lets SigLIP chunk across devices and outperform softmax CLIP below 16k batch size.[3] SigLIP 2 adds captioning, self-distillation, and masked prediction for stronger VLM transfer, with NaFlex variants preserving native aspect ratios.[4][5]
Verify the L2 norm trap, CLIP's false-negative collision spike, and SigLIP's /N vs /N^2 reduction in NumPy:
import numpy as np
def l2_norm(x: np.ndarray) -> np.ndarray:
return x / np.linalg.norm(x, axis=-1, keepdims=True)
def clip_loss(img_e: np.ndarray, txt_e: np.ndarray, temp: float = 0.2) -> float:
logits = (l2_norm(img_e) @ l2_norm(txt_e).T) / temp
idx = np.arange(len(logits))
def row_ce(m: np.ndarray) -> float:
s = m - m.max(axis=-1, keepdims=True)
return float(np.mean(np.log(np.sum(np.exp(s), axis=-1)) + m.max(axis=-1) - m[idx, idx]))
return 0.5 * (row_ce(logits) + row_ce(logits.T))
# 1. Raw dot product vs L2-normalized cosine
img, cap_a, cap_b = np.array([1.0, 0.0]), np.array([0.8, 0.6]), np.array([9.0, 12.0])
print(f"raw dot: A={img @ cap_a:.1f}, B={img @ cap_b:.1f} | cosine: A={l2_norm(img) @ l2_norm(cap_a):.2f}, B={l2_norm(img) @ l2_norm(cap_b):.2f}")
# 2. Clean 3x3 batch vs false-negative collision
img_c = np.array([[0.95, 0.05, 0.00], [0.05, 0.92, 0.03], [0.00, 0.07, 0.94]])
txt_c = np.array([[0.91, 0.08, 0.01], [0.06, 0.89, 0.04], [0.02, 0.09, 0.90]])
img_d = np.array([[0.95, 0.05, 0.00], [0.92, 0.08, 0.00], [0.00, 0.07, 0.94]])
txt_d = np.array([[0.91, 0.09, 0.00], [0.89, 0.11, 0.00], [0.02, 0.09, 0.90]])
print(f"CLIP clean: {clip_loss(img_c, txt_c):.3f} | collision: {clip_loss(img_d, txt_d):.3f}")
# 3. SigLIP pairwise loss: /N vs /N^2 on 2x2 zero logits
losses = np.logaddexp(0.0, -(2.0 * np.eye(2) - 1.0) * np.zeros((2, 2)))
print(f"SigLIP /N: {losses.sum() / 2:.3f} | /N^2: {losses.sum() / 4:.3f}")raw dot: A=0.8, B=9.0 | cosine: A=0.80, B=0.60
CLIP clean: 0.022 | collision: 0.469
SigLIP /N: 1.386 | /N^2: 0.693Zero-shot classification and dual-encoder limits
Embedding prompt templates ("a photo of a {label}") gives zero-shot classification without training a new head: CLIP ViT-L/14@336px reached 76.2% ImageNet top-1, with prompt templates plus 80-template ensembling adding nearly +5 points over bare class names.[1] Never trust single-candidate softmax (softmax([-10]) = [1.0]); threshold raw cosine and top-1 vs top-2 margin.
Global pooling still hits four ceilings: no bounding-box localization or counting (requiring detectors like Grounding DINO[6] or grounded VLMs), no text generation, weak attribute binding and multi-digit OCR (CLIP scores 88% on MNIST but 51% on SVHN),[1] and both web bias[7] and the geometric modality gap where image and text embeddings occupy distinct hypersphere cones.[8] Generative VLMs solve this by stopping before pooling and handing spatial patch tokens to a decoder.
Vision tokenization and dynamic resolution
A generative multimodal LLM combines modality encoders, a cross-modal connector, and a language decoder into one pipeline.

ViT patchification and token scaling
A Vision Transformer (ViT) slices an image into patches, flattens each to scalars, projects it to width , adds positional embeddings, and runs global self-attention from layer 1.[9] For views of size padded to patch size :
Token counts scale quadratically with resolution: a 224px image at emits 256 patches, while 336px (LLaVA-1.5) emits 576.[10] Upload bytes never predict GPU cost: a 12 MB JPEG and a 400 KB WebP yield identical patch counts after resizing, whereas a tiny PNG tiled into five 336px crops emits 2,880 visual tokens. Always cap upload bytes and post-preprocessing visual tokens separately.
import numpy as np
def vit_patchify(image: np.ndarray, patch: int, dim: int) -> np.ndarray:
H, W, C = image.shape
gh, gw = H // patch, W // patch
flat = image.reshape(gh, patch, gw, patch, C).transpose(0, 2, 1, 3, 4).reshape(gh * gw, patch * patch * C)
return flat @ (np.random.default_rng(0).standard_normal((flat.shape[1], dim)) * 0.02)
print("224px @ P=16 projected shape:", vit_patchify(np.zeros((224, 224, 3), np.float32), 16, 768).shape)
for label, sz, views in [("224px (1 view)", 224, 1), ("336px (1 view)", 336, 1),
("672px (1 view)", 672, 1), ("chart (5x 336px)", 336, 5), ("video 60s @ 2fps", 224, 120)]:
vis = int(np.ceil(sz / 14)) ** 2 * views
total = vis + 2500
print(f"{label:<18} visual={vis:6,d} total={total:6,d} [{'fits 4K' if total <= 4096 else 'exceeds 4K'}]")224px @ P=16 projected shape: (196, 768)
224px (1 view) visual= 256 total= 2,756 [fits 4K]
336px (1 view) visual= 576 total= 3,076 [fits 4K]
672px (1 view) visual= 2,304 total= 4,804 [exceeds 4K]
chart (5x 336px) visual= 2,880 total= 5,380 [exceeds 4K]
video 60s @ 2fps visual=30,720 total=33,220 [exceeds 4K]
Dynamic resolution and AnyRes tiling
Downscaling a 4K chart to 336x336 smears small labels into unreadable pixels. Two modern patterns preserve fine text:
- AnyRes / multi-crop tiling: Always reserve slot 0 for one downscaled global thumbnail (layout context) and spend a capped local crop budget on native-resolution crops over high-detail regions, storing crop-to-original coordinates. Never let the thumbnail compete on local saliency score, and escalate or abstain if a hard crop cap omits a required legend.
- Native dynamic-resolution ViTs: Qwen2.5-VL encodes images at native aspect ratios using 2D RoPE and a 2x2 spatial patch merger (4x token reduction while preserving local geometry),[11] while SigLIP 2 NaFlex similarly avoids square distortion.[4]
![Dynamic AnyRes tiling schematic: a high-resolution 1344x896 chart divides into a 3x2 tile grid highlighting Tile 3 (upper-right metric badge) and Tile 4 (bottom axis timestamps). It emits one downsampled 336x336 global thumbnail plus two native-resolution local crops with normalized [y0, x0, y1, x1] coordinates, concatenated into an ordered decoder prefix of 1,728 visual tokens plus text prompt.](https://assets.leetllm.com/v1/498ba88f18ec/system-design/multimodal-llms-architecture-design/illustrations/_generated/dynamic_tiling_dark.png)
Vision-to-language connectors
The connector projects encoder patches of width into decoder width , choosing between keeping full spatial grids or compressing into learned query vectors:
| Connector | Visual tokens | Mechanism | Primary tradeoff |
|---|---|---|---|
| Linear / 2-layer MLP (LLaVA-1.5) | Per-patch projection (Linear -> GELU -> Linear)[10] | Preserves spatial layout; high token cost on tiled views | |
| 2x2 spatial merger (Qwen2.5-VL) | Merges adjacent patches before MLP[11] | 4x token cut with intact 2D neighborhoods | |
| Q-Former (BLIP-2) | Fixed (e.g., 32) | Learned queries cross-attend over all patches[12] | Predictable KV budget; can blur tiny OCR strings |
| Perceiver Resampler (Flamingo) | Fixed (e.g., 64) | Learned latent bank cross-attends over variable media[13] | Caps multi-image/video length; same fine-detail risk |
Q-Former and Perceiver do not discard 544 patches; every learned query attends across all 576 patches. Watch one scaling trap: applying 24 queries per view or per frame still scales linearly (10 frames 3 views 24 = 720 tokens), so clip caps require a clip-level resampler or frame limit. Connectors can also vary injection depth: MPnP taps intermediate vision blocks and injects projected K/V pairs directly into late decoder blocks for lightweight adaptation at the cost of shallower visual reasoning.[14]
import numpy as np
rng = np.random.default_rng(7)
N, d_v, d_llm, M = 576, 768, 2048, 32
patches = rng.standard_normal((N, d_v)).astype(np.float32)
W_lin = rng.standard_normal((d_v, d_llm)).astype(np.float32) * 0.02
linear_out = patches @ W_lin
queries = rng.standard_normal((M, d_v)).astype(np.float32) * 0.02
scores = (queries @ patches.T) / np.sqrt(d_v)
weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
weights /= weights.sum(axis=-1, keepdims=True)
qformer_out = (weights @ patches) @ W_lin
print(f"linear: {linear_out.shape} | q-former: {qformer_out.shape} ({N // M}x compression)")linear: (576, 2048) | q-former: (32, 2048) (18x compression)Fusion architectures: early, late, and cross-attention
| Strategy | Interaction point | Best fit | Attention & KV cost |
|---|---|---|---|
| Early fusion | Interleaved prefix before layer 0 | Fine OCR, chart QA, native VLMs | Shared self-attention and shared KV cache |
| Cross-attention | Selected decoder layers read visual bank | Frozen backbones, multi-image/video banks | Text self-attention plus per fusion layer |
| Late fusion | Pooled vectors after separate towers | Fast million-scale image-text search | One dot product; no generative decoder |
Early fusion (interleaved visual-text attention)
Early fusion concatenates projected visual tokens directly with text embeddings (from a standard tokenizer), letting every layer mix vision and language via standard self-attention (used in LLaVA, Qwen2.5-VL, GPT-4o, and Llama 4).[15][11][16][17] Every visual token consumes prefill FLOPs and KV cache just like text: pairing five 336px views (2,880 tokens) with 2,500 transcript/prompt/output tokens totals 5,380 tokens (exceeding 4K), whereas 32-query resampling (160 visual tokens) fits cleanly at 2,660 tokens.

Gated cross-attention (Flamingo-style)
Flamingo keeps resampled visual memory off the text prefix and inserts gated cross-attention blocks between frozen LLM layers:[13]
At , preserves the pretrained text LLM identically at step 0. Contrast that with inserting zero-initialized visual K/V pairs directly into the same self-attention softmax (as in shared-K/V injection like MPnP[14]): even a zero key emits logit 0, stealing probability mass in the shared denominator and halving the text output!
import numpy as np
def attend(q: np.ndarray, k: np.ndarray, v: np.ndarray) -> np.ndarray:
scores = (q @ k.T) / np.sqrt(q.shape[-1])
w = np.exp(scores - scores.max(axis=-1, keepdims=True))
return (w / w.sum(axis=-1, keepdims=True)) @ v
text_h = np.array([0.20, 0.10, 0.70])
vis_k = np.array([[0.20, 0.05, 0.75], [0.80, 0.10, 0.10], [0.05, 0.90, 0.05]])
vis_v = np.array([[0.10, 0.00, 0.90], [0.80, 0.10, 0.10], [0.10, 0.80, 0.10]])
att = attend(text_h, vis_k, vis_v)
for alpha in [0.0, 0.35]:
print(f"Flamingo alpha={alpha:.2f} -> {np.round(text_h + np.tanh(alpha) * att, 3).tolist()}")
# Shared-softmax zero-K/V dilution: text value 2.0 drops to 1.0
t_only = attend(np.array([1.0]), np.array([[0.0]]), np.array([[2.0]]))[0]
t_zero = attend(np.array([1.0]), np.array([[0.0], [0.0]]), np.array([[0.0], [2.0]]))[0]
print(f"shared softmax: text_only={t_only:.1f}, with_zero_kv={t_zero:.1f}")
T_text, T_vis = 2200, 160
print(f"scores: early={(T_text + T_vis)**2:,} | cross-attn={T_text * T_vis:,} (+ text self-attn)")Flamingo alpha=0.00 -> [0.2, 0.1, 0.7]
Flamingo alpha=0.35 -> [0.308, 0.191, 0.837]
shared softmax: text_only=2.0, with_zero_kv=1.0
scores: early=5,569,600 | cross-attn=352,000 (+ text self-attn)
Audio, video, and multi-rate frontends
Different modalities emit features at vastly different rates: five 336px crops emit 2,880 patches, 40 seconds of audio at 100 Hz emit 4,000 spectrogram frames, and a transcript adds 2,000 text tokens.
Match pretrained frontends to signal types: CLIP[1] or SigLIP[3] for images, Whisper[18] for speech spectrograms, and CLAP[19] for non-speech audio retrieval; for video, combine spatial compression with temporal sampling or spatiotemporal pooling (TimeSformer,[20] VideoMAE[21]). For speech, timestamped transcripts beat raw audio on cost unless tone, overlap, or alarms matter; when feeding raw audio, stride-10 temporal pooling compresses 4,000 -> 400 tokens (trading 10 ms precision for 100 ms steps). Always separate utterance time (when someone spoke) from event time (when a metric changed on a chart).
Training recipes and modern VLM tradeoffs
Adapter-based two-stage training (BLIP-2,[12] LLaVA,[15] LLaVA-1.5,[10] early PaLI[22]) separates bridge alignment from instruction tuning:
| Stage | Data | Vision encoder | Projector | LLM |
|---|---|---|---|---|
| 1. Feature alignment | Filtered CC3M captions[23] (558K in LLaVA-1.5) | Frozen | Train | Frozen |
| 2. Visual instruction tuning | Multimodal QA mix (665K in LLaVA-1.5) | Frozen | Train | Train (full FT or LoRA) |
In Stage 1, freeze LLM weights (requires_grad=False) so random projector gradients never corrupt pretrained language weights, while keeping activation backpropagation enabled through the autoregressive caption loss (wrapping the LLM in torch.no_grad() kills projector training!). LLaVA-1.5 finished both stages in roughly a day on 8 A100 GPUs.[10]
Joint / native multimodal pretraining unfreezes encoders and backbones together across rich text, image, audio, and video mixtures: Gemini,[24] Llama 4 (early fusion with MetaCLIP + sparse MoE),[17] GPT-4o (end-to-end text/vision/audio I/O),[16] and Qwen2.5-VL (dynamic ViT + 2x2 merger).[11] Joint training excels on dense OCR and charts, but unbalanced multimodal batches can erode pure-text reasoning; use per-component learning rates and track text-only evals continuously. Post-training with DPO[25] or RLHF sharpens abstention and formatting, yet never recovers pixels erased upstream: if verified OCR text succeeds where raw pixels fail, fix resolution or connector compression first.
Multimodal serving, KV-cache memory, and safety
In early-fusion VLMs, visual tokens occupy the decoder KV cache alongside text. PagedAttention eliminates fragmentation[26] but not token count. On a 32-layer GQA decoder (8 KV heads, head dim 128, BF16 = 2 B), each token consumes of KV cache: 2,880 direct visual tokens take 360.0 MiB/request, whereas 160 resampled tokens take 20.0 MiB/request, freeing 340 MiB/request for concurrent batches.

Keep reusable visual context before the changing user question so causal prefix-KV blocks stay identical across follow-up turns. Engines like vLLM hash prefix blocks using multimodal identities, LoRA IDs, and per-tenant cache salts;[27] always re-check access permissions externally before serving cache hits, and isolate vision-encoder workers from decoder pools. Note that Mixture-of-Experts (MoE) cuts active FFN FLOPs per token[28] without reducing vision encoding, visual prefix length, or visual KV memory.
Finally, images can hide prompt injections inside rendered pixels that bypass text filters.[29] Treat pixels and OCR text strictly as untrusted data, validate decoded dimensions against decompression bombs, scope downstream tools to read-only access, and evaluate OCR exact match and region IoU separately from fluency (using explicit np.isfinite checks so NaN never silently passes score < floor).