Welcome to this advanced course on multimodal AI. We open with the objectives and themes that will structure our study of how text and vision are integrated into a single model, from contrastive pretraining to cross-attention fusion.
First, scope and audience. This course assumes fluency in machine learning fundamentals: backpropagation, attention, and the transformer architecture of Vaswani and colleagues. We build directly on that foundation toward frontier multimodal systems.
Our focus is text-vision integration. We will dissect CLIP's contrastive objective, which aligns image and text embeddings via a temperature-scaled softmax over batch similarities, and BLIP's encoder-decoder design, examining precisely how each architecture fuses the two modalities.
The learning goals are concrete. Expect rigorous derivations of the underlying objectives, including the InfoNCE loss, hands-on implementation in Python and PyTorch, and critical discussion of open research problems in multimodal learning.
By the end, you will command both the theory and the engineering practice of multimodal AI, prepared to contribute original research or build production systems in this rapidly advancing field.
Equations, code and original cards
Course Introduction and Overview
Course Scope & Audience
• Advanced AI students
• ML engineers & researchers
Multimodal AI Models
• Text-Vision integration
• Architectures: CLIP, BLIP, others
Learning Goals
• Objective derivations (InfoNCE)
• Implementation in PyTorch
• Frontier research 2024-26
Moment 02 / 11
Foundations: Vision Transformers and Text Models
Today we isolate the two encoders behind cross-modal attention: the Vision Transformer, which tokenizes images, and the causal language model, which tokenizes text. Their shared interface is a sequence of embeddings.
Start with patchification: an image is split into non-overlapping sixteen by sixteen patches, flattened, then mapped by one learned linear projection into tokens of the model dimension. Add positional encodings, and self-attention sees a sequence rather than pixels.
In the Vision Transformer example, each flattened patch is multiplied by the same embedding matrix, so local texture becomes one vector in the residual stream, ready for layers of multi-head self-attention.
For language, bytes or words are segmented into subword tokens, each row of an embedding table is selected, and the causal model predicts every next token from only its prefix.
Formally, both modalities arrive as a matrix whose rows index tokens and whose columns span the model width; vision uses patch positions, text uses order, but attention computes over the same object.
That matrix is the residual stream: each token is a contextualized vector, updated by attention and feed-forward blocks, whether it began as a patch or as a subword.
The key point is alignment before fusion: pixels and characters become comparable token embeddings, so cross-attention can later exchange information between modalities without changing the transformer core.
Equations, code and original cards
Foundations: ViT Encoders and Causal Language Models
ViT Patchification: Image to Token Sequence
• Non-overlapping 16 by 16 patches; flatten each patch
• Shared linear projection to model width; add positional encodings
Causal LM Token Sequences
• Subword segmentation; embedding-table lookup
• Next-token objective: likelihood of each token given its prefix
Token matrix: rows are tokens, columns are model width
ViT patch embedding: flatten patch, apply shared linear map, add position, enter residual stream
Moment 03 / 11
Cross-Attention Mechanism Fundamentals
Today we examine cross-attention, the mechanism that lets one modality attend to another: it is the core of the encoder-decoder attention in Vaswani et al. 2017, and of modern vision-language models that inject image features into a text decoder.
The asymmetry is the point. Queries are projected from the text token embeddings, while keys and values are projected from image patch embeddings, so each text position selects which visual evidence enters its residual stream.
Concretely, the query matrix is a learned linear projection of the text hidden states, written as Q equals the text embeddings times a weight matrix W-Q. The keys and values get their own projections, W-K and W-V, applied to the image features.
Attention logits are the query-key dot products, scaled by one over the square root of the head dimension d-k. Without that scaling, the logits grow linearly in d-k, pushing softmax into saturation where gradients vanish.
So the score matrix S equals Q times K transpose, divided by the square root of d-k. Row-wise softmax turns these logits into a distribution over image patches, and multiplying by V yields a weighted sum of visual value vectors.
For backpropagation, gradients flow through the value matmul, the softmax Jacobian, and the score matmul. The softmax Jacobian is the delicate term: it couples every pair of keys within a row, which is exactly why saturated attention kills learning.
We denote the gradients of the loss with respect to Q, K, and V as the partial derivatives d-L by d-Q, d-L by d-K, and d-L by d-V. The chain rule gives d-L by d-Q from d-L by d-S times K, and d-L by d-K from the transpose contraction with Q.
In PyTorch this is a handful of lines: form the scaled scores, apply softmax over the key axis, multiply by V, and call backward. Autograd handles the softmax Jacobian and both matmuls; FlashAttention fuses them to avoid materializing the full score matrix.
In summary, cross-attention couples modalities through asymmetric projections: text queries, visual keys and values, scaled dot-product logits, softmax weighting, and exact gradient flow. This is the primitive behind Flamingo-style vision-language models and diffusion text conditioning.
Equations, code and original cards
Cross-Attention Mechanism Fundamentals
Asymmetric Projections: Text Queries Attend to Image Keys/Values
Query, Key, Value Matrices
• Q from text token embeddings • K, V from image patch embeddings • Dimensions: Q \(\in \mathbb{R}^{N_q \times d}\), K, V \(\in \mathbb{R}^{N_k \times d}\)
Start with the image tokenizer: the input is split into fixed patches, each flattened and passed through a learned linear projection into a visual token embedding, as in the vision transformer. These embeddings, plus positional encodings, become the keys and values for cross-attention.
Next, the language hidden states supply queries, while the visual tokens supply keys and values; compatibility is scored by the scaled dot product, softmax-normalized over patches, so each text position mixes image evidence by learned relevance.
Finally, those attention probabilities are reshaped onto the patch grid and rendered as heatmaps, exposing the effective receptive field of a query: which regions dominate its context and which are ignored.
Interact step by step: trace a patch into the residual stream, inspect query-key logits before softmax, then compare the heatmap with the answer to judge whether attention is evidence or merely correlation.
Equations, code and original cards
Moment 05 / 11
Semantic Alignment via CLIP
CLIP, introduced by Radford and colleagues in 2021, achieves semantic alignment by embedding images and text into a single shared latent space where cosine distance carries meaning.
The objective is symmetric InfoNCE: paired image and text embeddings are pulled together while every mismatched pair in the batch is pushed apart, in both directions.
A vision encoder, either a ResNet or a ViT, and a transformer text encoder map their inputs into the same d-dimensional space, so embeddings are directly comparable by dot product.
Scale is what makes this work. CLIP trained on 400 million image-text pairs scraped from the web, and that diversity is precisely what buys its zero-shot generalization.
So the recipe is contrastive learning over a shared embedding space at web scale, and that is what aligns image and text semantics well enough for zero-shot classification.
Equations, code and original cards
Semantic Alignment via CLIP
Aligning Text and Image Embeddings with Contrastive Learning
• Text encoder (Transformer): \(T \to t \in \mathbb{R}^d\)
• Trained jointly so matched pairs maximize cosine similarity
3. Large-Scale Pretraining Impact
• Trained on 400M image-text pairs (Radford et al., 2021)
• Enables robust zero-shot transfer and semantic understanding
Moment 06 / 11
Advanced Architectures: BLIP and Flamingo
Today we examine two landmark vision-language systems, BLIP and Flamingo, and the architectural choice that separates them: whether to fuse modalities at the input, or to bridge frozen unimodal encoders with learned cross-attention. The naive concatenation story is mostly wrong here.
Start with the fusion baseline. Early fusion concatenates patch embeddings with token embeddings before the encoder, so every layer sees both modalities; the cost is that the self-attention matrix grows quadratically in the combined sequence length, and cross-modal alignment must be learned from scratch.
The fused input is a concatenation of projected image patches and text tokens, plus modality and positional embeddings; the transformer then treats this as one sequence, with no explicit mechanism recording which tokens came from which sensor.
Multimodal attention generalizes Vaswani's scaled dot-product operation to a joint sequence; Flamingo instead freezes the language model and inserts gated cross-attention whose tanh gates start at zero, so optimization begins exactly at a pure language model.
The attention itself is unchanged: softmax of Q K transpose over the square root of d-k, times V; what changes is the provenance of Q, K, and V, with visual tokens serving as keys and values for linguistic queries.
Efficiency work from twenty twenty-four onward targets the quadratic bottleneck: FlashAttention reduces memory traffic, token pruning and the Perceiver resampler compress hundreds of visual patches to a fixed set of latents, and grouped-query attention cuts the key-value cache during decoding.
The snippet is the standard kernel; in Flamingo, wrap it as cross-attention with text queries and image-latent keys and values, then scale the output by a learnable tanh gate initialized to zero.
The takeaway: early concatenation is a baseline, not the state of the art; modern systems bridge frozen encoders with zero-initialized gated cross-attention or a Q-Former, and the systems work is about controlling the quadratic cost of the joint sequence.
Equations, code and original cards
BLIP, BLIP-2, and Flamingo: Bridging Frozen Encoders
1. Fusion: Early Concatenation vs. Gated Bridges
• Early fusion concatenates patch and token embeddings pre-encoder
• Cost: self-attention is O(n^2 d) in the joint sequence length
• BLIP-2 and Flamingo bridge frozen encoders via Q-Former or gated cross-attention
We now turn to implementation, examining PyTorch snippets that instantiate cross-attention and expose how gradients flow through the module during optimization.
The cross-attention module is the conditioning primitive of modern transformer decoders, letting one sequence attend to an external context such as text embeddings or latent tokens.
The class subclasses nn.Module. Its constructor allocates the query, key, value, and output projections; the head count and the inverse-square-root scale factor are fixed here.
The forward pass maps x to queries and the context to keys and values, reshapes into heads, then applies scaled dot-product attention: softmax of q k transpose over the square root of d-k, times v.
These batched matrix multiplications map onto cuBLAS and FlashAttention kernels, so the quadratic attention cost is often memory-bound rather than compute-bound; gradients propagate through the same graph under cross-entropy.
Reading these snippets connects the algebra to the autograd graph: cross-attention is a differentiable, permutation-aware operator you can profile, ablate, and optimize.
def forward(self, x, context):
q = self.to_q(x)
k = self.to_k(context)
v = self.to_v(context)
q = q.view(q.size(0), q.size(1), self.heads, -1).transpose(1,2)
k = k.view(k.size(0), k.size(1), self.heads, -1).transpose(1,2)
v = v.view(v.size(0), v.size(1), self.heads, -1).transpose(1,2)
Key Points:
• Forward: batched matmuls produce attention logits
• Scaled dot-product: softmax(QKᵀ/√d_k)V (Vaswani et al. 2017)
• Autograd: cross-entropy gradients through Q, K, V
Moment 08 / 11
Scaling Laws and Efficiency Trends (2024–2026)
Here we examine scaling laws and efficiency trends for multimodal transformers from 2024 to 2026: how parameter count, data volume, and compute jointly determine capability, and at what energy cost.
Scaling laws, following Kaplan and colleagues in 2020, quantify cross-entropy loss as a smooth power law in parameters, data, and compute, so performance improves predictably as models grow.
Formally, the loss falls as model size raised to a negative exponent, with a second term for dataset size; Hoffmann's Chinchilla analysis showed optimal training needs roughly twenty tokens per parameter, correcting earlier undertraining.
This PyTorch sketch shows width scaling implemented programmatically: multiply the embedding dimension by a scale factor, and depth and heads follow the same systematic recipe.
Finally, efficiency work, quantization, pruning, mixture-of-experts sparsity, targets the energy side, since training at ten to the twenty-third FLOPs makes operational cost a first-order constraint.
Let's turn to the alignment challenges that still define multimodal research. This slide catalogs the open problems in grounding language to vision, from contrastive objectives in CLIP to the unresolved question of whether shared embeddings actually encode compositional meaning.
First, grounding and explainability. Even strong vision-language models often latch onto spurious correlations rather than true referential structure, so their attention maps look plausible yet fail systematic probing and counterfactual tests.
Here is the canonical embedding view: text and image encoders map into a shared latent space, trained so paired examples are close and mismatched pairs are far. The geometry of that space is exactly where alignment succeeds or breaks.
The objective is typically a contrastive loss such as InfoNCE, where parameters theta minimize the expected negative log probability of the correct image-text pair under a softmax over a batch, scaled by temperature.
In PyTorch, that reduces to a few lines: encode both modalities, normalize the embeddings, form the pairwise similarity logits, and apply cross entropy with the diagonal as labels. The snippet here shows the cosine core.
Active work targets robust grounding under distribution shift, causal rather than correlational explanations, and bias mitigation, since contrastive pretraining inherits and can amplify the demographic skews present in web-scale data.
In short, multimodal alignment remains an open frontier: grounding is brittle, explanations are post hoc, and fairness is not guaranteed by scale alone. Keep these limitations in view, because they motivate the architectures and objectives we study next.
Equations, code and original cards
Alignment Challenges and Open Research Questions
• Grounding and explainability: spurious cues, brittle attention maps
• Contrastive paradigms (CLIP, InfoNCE) and their geometric assumptions
• Open problems: causal reasoning, compositionality, bias mitigation
Active research targets robust grounding under distribution shift, causal explainability, and bias mitigation in web-scale contrastive pretraining.
Moment 10 / 11
Challenging Quiz on Multimodal Cross-Attention
Time to test whether the cross-attention machinery has actually settled in. Work through each question on your own before we discuss the answers.
Once you finish, we'll walk through the responses together and pin down any points that remain unclear.
Equations, code and original cards
Moment 11 / 11
Summary and Future Outlook
Let's consolidate the key results from this module on text-vision fusion, from early concatenation baselines to cross-attention and co-attentional transformers.
The central mechanism is asymmetric attention: queries from one modality attend to keys and values from the other, aligning semantic features in a shared representation space rather than merely concatenating embeddings.
The fusion layer computes softmax of Q K transpose over the square root of d-k, times V, where Q comes from the language stream and K and V from image patch tokens.
Training relies on multimodal objectives: contrastive alignment as in CLIP, image-text matching, and masked multimodal modeling, each shaping the joint representation differently.
Looking forward, the field is moving toward dynamic fusion strategies, frozen backbones with lightweight adapters such as the Q-Former in BLIP-2, and interpretability of cross-modal attention maps.
I encourage you to treat these fusion mechanisms as building blocks: ablate them, extend them, and apply them to your own projects and research problems.
That concludes our summary and outlook on multimodal fusion. The open problems here, grounding, alignment, and efficiency, are where the next advances will come from.
Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.