Mental model
Multimodal fusion connects encoders whose features describe different signals, then gives a task model a learned way to compare or combine those features. The bridge may project image tokens into a language model, resample many patches into a fixed visual sequence, or combine calibrated predictions late. Shape compatibility is only an interface check; useful fusion also needs aligned meaning, time, masks, and evaluation.
Theory
An image encoder emits a grid or sequence of visual features; a text encoder emits contextual token states; an audio encoder may emit frame-level acoustic features or recognized tokens. Those vectors do not become interchangeable because they have the same width. They are learned in different spaces with different sampling rates, invariances, and failure patterns. A fusion layer must establish the route by which a text query can use visual or acoustic evidence.
LLaVA provides a direct visual-language example. A pretrained vision encoder produces image features, and a learned linear projector maps them into the language model's word-embedding width. The resulting visual tokens enter an instruction-tuned language sequence. Its original training separates feature alignment, where the projector learns while the vision encoder and language model are frozen, from visual instruction tuning, where the language model and projector are updated while the vision encoder stays fixed. Flamingo takes a different route: it keeps pretrained vision and language models frozen, uses a Perceiver Resampler to turn a variable number of image or video features into a fixed set of visual tokens, and inserts gated cross-attention layers into the language model. The two designs trade a simple projected sequence against an explicit visual-memory path and resampling.
At a cross-attention layer, text states supply queries and visual states supply keys and values:
For N_t text positions and N_v visual positions, Q has shape N_t by d_k, K has shape N_v by d_k, and V has shape N_v by d_v. The result has shape N_t by d_v. The division by the square root of d_k keeps dot-product logits in a useful scale as width changes; softmax weights are dimensionless and sum across visual positions. The values are model activations, not physical measurements. A padding or causal mask determines which image, frame, or audio chunk each text position may use. Without the mask, a caption token could attend to padded patches or to a later frame that should not yet be visible.
Example: bound image tokens before a long answer
Suppose a vision transformer receives an 896 by 896 image as 14 by 14 patches. It creates 64 by 64, or 4,096, visual tokens. If a request also has 2,048 text tokens, a hypothetical dense self-attention layer sees a sequence of 6,144 positions and forms about 37.75 million pairwise scores per head. If a resampler reduces the visual representation to 64 tokens, the combined sequence has 2,112 positions and about 4.46 million pairwise scores per head, roughly 8.5 times fewer positions in the quadratic score matrix. This calculation isolates the sequence-length term for dense self-attention; a resampler plus cross-attention has a different operation count, so measure the deployed architecture rather than treating the ratio as a latency promise.
Compression has a semantic cost. A 64-token visual summary may preserve broad scene layout while discarding a tiny label, a brief gesture, or the order of two nearby events. For video and audio, sampling also creates a clock: frame timestamps and audio spans must remain associated with features and text chunks. Uniformly sampling a long clip can miss a short event, while processing every frame can exhaust the token budget. Select temporal sampling for the task, preserve timestamps through resampling, and make the system abstain when required evidence was not observed.
Trade-offs
Early fusion puts modality embeddings into one shared sequence and lets self-attention mix them. It allows flexible interactions but can make sequence length and modality-specific masking expensive. Intermediate fusion uses a projector, gated cross-attention, or a resampler between existing encoders. It can reuse strong pretrained towers and bound visual memory, but the bridge may become a bottleneck. Late fusion combines decisions from separate models after each has processed its own modality. It keeps components replaceable and can tolerate a missing input, but its calibration layer must account for different score scales and correlated mistakes.
Evaluate the task the product actually asks the model to perform. A visual question-answering suite should separate object recognition, counting, text reading, spatial relations, and unanswerable questions. A video suite needs timestamped event probes; an audio-visual suite should test disagreement between speech and visible activity. Report quality by modality availability and relevant slice, not just one aggregate score. For each answer, capture which frames or regions were available to the model so a reviewer can distinguish a model error from a preprocessing omission.
Failure modes and misconceptions
| Failure | Mechanism | Operational response |
|---|---|---|
| Image token overflow | Resolution or patch count exceeds the context budget | Reject or tile with an explicit merge policy; never silently drop arbitrary patches |
| Padding leak | Attention includes empty or padded modality positions | Pass boolean masks with tested polarity and fail if a sample has no valid evidence |
| Video event loss | Temporal sampling skips a short action | Preserve timestamps, increase local sampling where justified, and test event-duration slices |
| Modality disagreement | Text says one thing while image or audio suggests another | Keep modality-specific evidence and allow abstention or a clarifying request |
| False grounding | A fluent answer mentions details absent from selected regions | Probe with counterfactual and unanswerable examples and evaluate cited evidence separately |
| Late-fusion calibration drift | One model's logits grow in scale after a version change | Refit calibration on a versioned held-out set and compare per-modality reliability |
Implementation: mask visual cross-attention
This PyTorch block models an intermediate fusion boundary: text positions query visual feature tokens, and a padding mask prevents padded image positions from contributing. The caller is responsible for passing features produced by the pinned encoders and for preserving the image or frame identifiers that accompany those features.
pythonimport torchfrom torch import nnclass VisualCrossAttention(nn.Module):def __init__(self, width: int, heads: int) -> None:super().__init__()self.attention = nn.MultiheadAttention(embed_dim=width, num_heads=heads, batch_first=True)self.norm = nn.LayerNorm(width)def forward(self,text_states: torch.Tensor,visual_states: torch.Tensor,visual_padding_mask: torch.Tensor,) -> torch.Tensor:if text_states.ndim != 3 or visual_states.ndim != 3:raise ValueError("expected batch, sequence, channel tensors")if text_states.size(0) != visual_states.size(0):raise ValueError("text and visual batch sizes differ")if visual_padding_mask.dtype != torch.bool:raise TypeError("padding mask must be boolean")if visual_padding_mask.all(dim=1).any():raise ValueError("every example needs at least one visual token")update, _ = self.attention(text_states, visual_states, visual_states,key_padding_mask=visual_padding_mask, need_weights=False,)return self.norm(text_states + update)if __name__ == "__main__":torch.manual_seed(7)block = VisualCrossAttention(width=256, heads=8)text = torch.randn(2, 12, 256)visual = torch.randn(2, 16, 256)padding = torch.zeros(2, 16, dtype=torch.bool)padding[1, 14:] = Truefused = block(text, visual, padding)assert fused.shape == text.shape and torch.isfinite(fused).all()
In PyTorch's attention API, True in a key-padding mask means that position is ignored. An all-true row can produce undefined attention weights, so the method rejects that input instead of returning plausible-looking NaNs. A production adapter should also check encoder revision, token-to-frame mapping, mask shape, and whether the question requires evidence that was removed by sampling.
Decision scenario
A video assistant must summarize a 12-minute maintenance recording, but a 64-token visual resampler can miss a brief warning light that appears for only two seconds. Compare uniform sampling with event-triggered local frames on timestamped clips, keep the selected frame IDs attached to the answer, and measure both token use and warning-light recall. If the critical event was not sampled, the system should request more evidence or abstain instead of inferring that the warning never occurred.
Learning outcomes
- Compare projected visual tokens, resampled memory, cross-attention, and late fusion.
- Calculate how sequence lengths change dense attention cost and identify the limits of that estimate.
- Test modality-specific masks, evidence grounding, temporal sampling, and abstention under missing input.