Key takeaways
- The core idea of multimodality is surprisingly simple: translate an image into a sequence of vectors in exactly the same format as text-token vectors, join them with the text, and hand everything to the same Transformer.
- ViT (the Vision Transformer) cuts an image into patches, flattens each one, multiplies it by a shared matrix and adds a position vector. The image becomes a sequence of tokens.
- CLIP uses two encoders and contrastive learning so that matching images and captions land close together in the same space. Its image encoder becomes "an eye that understands language".
- LLaVA plugs CLIP's image encoder into a language model through a projection W: first feature alignment, then instruction tuning. That's the skeleton of most open-source multimodal models today.
- To see big images clearly, LLaVA-NeXT cuts them into tiles, while Qwen2-VL throws out the learned position table for a 2D RoPE that works at any size, and uses M-RoPE to give text, images and video one shared numbering.
How does a language model "see"?
You may have tried this: send a chatbot a photo and ask, "What's in this picture?" It really does understand, and answers in plain words. So how does it actually see?
Think back to episode 0: a language model only understands tokens. Each token is turned into a vector, which is then fed into the Transformer. But an image isn't a string of words. It has no vocabulary, and you can't chop it up with BPE. So how does it get in?
The answer: translate the image into a sequence of vectors too, in exactly the same format as the vectors for text tokens. Then join the two sequences and hand them to the same Transformer. Everything after that is machinery you already know.
The plan for this episode: first how ViT cuts an image into tokens, then how CLIP lines images up with text. Next, LLaVA, which stitches the two together; then how to handle big images of any size, and Qwen2-VL. Finally, today's standard recipe.
What an image is inside a computer
Zoom in on an image and you'll see lots of tiny squares, each one a pixel. A pixel's color is stored as three numbers: how bright its red, green and blue light are, each from 0 to 255.
- A pixel on the sun: red 244, green 196, and blue only 48. Mix them and you get golden yellow.
- A pixel of sky: blue is the brightest, (156, 203, 239).
So an image is really three tables of numbers stacked up, one each for red, green and blue (the three channels): height × width × 3 numbers in all. A tiny 12×12 pixel picture is 12×12×3=432 numbers. A small 224×224 photo already has 224×224×3=150528.
One pixel per token? No way
The most direct idea: make each pixel a token? Then a 224×224 image becomes 50,176 tokens. Remember from episode 7: attention computes a score between every pair of tokens, so the cost grows with the square of the length. 50,000 squared is 2.5 billion.
And a single pixel means almost nothing on its own. A blue dot could be sky, or it could be a window.
Intuition: Remember BPE? It merges letters that often appear together into a single token (l, o, w become low). Images can do the same: bundle a small block of neighboring pixels into one token.
ViT step one: cut the image into patches
In 2020, a paper from Google gave the answer. Its title: An Image is Worth 16x16 Words, where each "word" is a 16×16 square of pixels. The model is called the Vision Transformer, or ViT: turn the image into a sequence of vectors, then run a standard Transformer encoder on it. It's the visual foundation of every multimodal model that follows.
Using our tiny 12×12 picture:
- Cut: make a cut every 4×4 pixels. Three across, three down: nine patches of equal size.
- Line up: arrange them left to right, top to bottom, just like the tokens in a sentence. Now it's a sequence.
- Flatten: lay each patch's 16 pixels out in a single strip. Each pixel is 3 numbers, so that's 48 numbers: every patch is now a 48-dimensional vector.
In general, for an image of height H and width W cut into patches of side P, the number of patches is
N=PH×PW
and each flattened patch holds P×P×3 numbers. (Here W is the image width; don't confuse it with the projection matrix W coming up.)
| Model |
Patch size |
A 224×224 image |
| Original ViT |
16×16 |
14 per side, 196 patches, 768 numbers each |
| CLIP / LLaVA |
14×14 |
256 patches, 588 numbers each |
256 patches instead of 50,000-plus pixels: almost 200 times fewer.
Linear projection: patches become vectors
Right now each patch is just a list of raw color numbers. Next we multiply it by a matrix to turn it into the kind of vector the model uses inside. This is a linear projection.
A mini example: a 2×2 grayscale patch with brightness 0.9, 0.1, 0.8 and 0.2 (top left, top right, bottom left, bottom right). Flatten it into a 4-dimensional vector x and multiply by a matrix W with 3 rows and 4 columns:
10101−110101−10.90.10.80.2=1.70.31.4
- Row 1, (1,0,1,0), adds up the left column: 0.9+0.8=1.7.
- Row 2, (0,1,0,1), adds up the right column: 0.3.
- Row 3, (1,−1,1,−1), is left minus right: 1.4. Bright on the left, dark on the right: this row is detecting a vertical edge.
The real W isn't designed by hand. It's learned in training, and discovers all kinds of detectors on its own: edges, colors, textures. In CLIP's ViT, W turns each patch's 588 numbers into a 1024-dimensional vector.
Watch out: The key is that every patch shares the same W (each patch is multiplied independently by the same matrix). It's a lot like word embeddings: every token looks up the same table, and every patch is multiplied by the same matrix. The resulting vectors are called patch embeddings, and they're the image's tokens.
Position vectors and CLS
Once the patches are in a row, the model no longer knows where each one sat in the picture. Shuffle the nine patches and reassemble them, and you get a completely different picture. Yet to attention, it's the same tokens in a different order, and the outputs simply get reordered too. It's the "dog bites man" versus "man bites dog" problem from episode 8.
ViT's fix is direct: give every position its own position vector p and add it to the patch embedding there. These position vectors are learned too: one for the first position, one for the second, and so on, one per patch.
ViT also puts a special token at the very front, called CLS (short for classification). It doesn't belong to any patch; it's simply a learnable vector of its own, xcls. Its job: as it passes through the Transformer, it gathers up information from the whole image. As formulas:
z0=xcls+p0,zi=Wxi+pi(i=1,…,N)
So the sequence has N+1 tokens: 9+1=10 for our tiny picture, and 257 for an image with 256 patches.
The Transformer encoder and classification
Next comes a standard Transformer: attention plus a feed-forward network, stacked many layers deep. But there's one important difference from a language model.
A language model writes one token at a time, so each token can only see the ones before it: the causal mask from episode 7. An image has no before and after. A patch in the top left looking at one in the bottom right makes perfect sense. So ViT has no mask at all: every patch can see every other patch. A Transformer where every position can see everything is called an encoder.
Feed the ten position-tagged tokens into the encoder, and every position puts out a vector at the top:
- During training, take only the output at the CLS position and attach a small classifier head that predicts what the image shows, say, a house. Attention lets CLS see every patch and collect information from the whole image. The original paper trained on about 300 million labeled images.
- Once trained, the classifier head is removed. Every patch's output has blended in information from the whole image, and these vectors are the image's features.
Watch out: Training on fixed classes has a limitation: the model only knows the classes picked in advance, and its features only serve classification. We'd like image vectors that line up directly with language.
CLIP: teaching images and text one language
In 2021, OpenAI released CLIP. Instead of hand-labeled classes, it learned from about 400 million image–caption pairs collected from the internet. Lots of images online already come with a sentence describing them. Those captions are free supervision, far richer than a fixed list of classes.
CLIP has two encoders, often pictured as two towers:
- an image encoder, a ViT for example, turns the picture into a vector u;
- a text encoder, a Transformer, turns the caption into a vector v.
The two vectors have the same dimension and live in the same space. Both are first scaled to length 1 (so they all sit on a circle), which makes their dot product exactly the cosine of the angle between them:
sim(u,v)=u⋅v=cosθ
The closer the directions, the higher the similarity. The training goal is plain: the vectors of a matching image and caption should point the same way, and mismatched ones should be pushed apart.
The similarity matrix and the contrastive loss
A batch of four, a 4-by-4 table
Each step takes a small batch, say 4 image–caption pairs. Pair every image with every caption, compute a similarity for each, and you get a 4×4 table (rows are images, columns are captions):
- the 4 cells on the diagonal are the true pairs, called positives;
- the other 12 cells are mismatches, called negatives.
Read across the first row. For the house image, it's a four-way multiple choice: which caption is its own? Divide the similarities in this row by a small number τ, the temperature (0.2 in the illustration), then apply softmax to get a probability for each option. The correct answer sits on the diagonal with probability 69%. The loss is the cross-entropy from episode 5, the negative log of the correct answer's probability: −log0.69≈0.37.
Read down the first column. For the caption "a house", which of the four images is the right one? Another four-way choice.
As formulas
First divide each similarity by the temperature:
sij=τui⋅vj
Each row is a four-way choice whose correct answer is the diagonal entry sii; averaging those cross-entropies gives the image-to-text loss. Doing the same down every column gives the text-to-image loss. Average the two and you have the total CLIP loss:
LI→T=−N1i∑log∑jesijesii,LT→I=−N1j∑log∑iesijesjj
L=21(LI→T+LT→I)
Training keeps pushing the diagonal up (toward 0.9, say) and pressing everything else down. This way of training, pulling positives together and pushing negatives apart, is called contrastive learning.
At real scale
The real CLIP trains on batches of N=32768 pairs. So the table holds over 30,000 positives and N2−N, over a billion, negatives. Every image has to pick out its own caption from more than 30,000. The more negatives there are, the better the model has to get at telling subtle differences apart.
What CLIP learned
Once trained, CLIP has a neat trick: it can classify images with no extra training at all.
- Write each candidate class as a sentence: "a photo of a cat", "a photo of a dog", and so on.
- The text encoder turns each sentence into a vector.
- Pick the sentence the image is most similar to.
This is zero-shot classification, because the model was never trained for this particular task. How well does it work? CLIP's largest model gets 76.2% zero-shot accuracy on ImageNet, about the same as a ResNet-50 trained directly on ImageNet's 1.28 million labeled images.
But for us, the bigger deal is this: the vectors from CLIP's image encoder are already aligned with language. It has learned how pictures and words correspond. It's like an eye that understands language, perfect for plugging into a language model.
LLaVA: connecting the eye to a language model
LLaVA, from 2023, is strikingly simple: an off-the-shelf CLIP image encoder plus an off-the-shelf language model, joined by a small adapter, the projection W. The architecture is three blocks in a chain: the CLIP image encoder, then the projection W, then the language model. The image goes into the encoder, the projection turns the result into visual tokens, and those enter the language model together with the text.
The catch is that the sizes don't match. In LLaVA, the language model's hidden size is D=4096, while CLIP's is 1024, so a projection has to take 1024 up to 4096. Let's follow one image through and watch the shape of the data at each step:
Image [224, 224, 3]
↓ patchify
Patches [256, 588]
↓ linear projection (independent)
Patch embeddings [256, 1024]
↓ prepend CLS, add position embeddings
Sequence [257, 1024]
↓ CLIP (transformer encoder with 24 layers)
CLIP output [256, 1024]
↓ projection W applied independently per token
Visual embeddings [256, 4096]
↓ concatenate with text embeddings [N, 4096]
Full sequence [256 + N, 4096]
↓ LLM transformer
Line by line:
- Patchify: the 224×224×3 input, cut into 14×14 patches, gives 256 patches of 588 numbers each.
- Linear projection: each patch independently becomes a 1024-dimensional patch embedding.
- CLS and positions: add CLS at the front plus the position vectors; the sequence length becomes 257.
- CLIP encoder: 24 layers. LLaVA keeps only the outputs at the patch positions, taken from the second-to-last layer, and drops CLS, leaving 256 vectors of 1024 dimensions.
- Projection W: acts on each vector separately, taking it from 1024 to 4096 dimensions. The resulting 256 vectors have exactly the same format as text-token vectors. We call them visual tokens.
- Concatenate: put the visual tokens in front of the text (N tokens of 4096 dimensions), forming a sequence of length 256+N for the language model.
To the language model, the visual tokens are just context to read first. Then it carries on autoregressively as usual, writing the answer one token at a time.
Watch out: During training, the loss is computed only on the answer. The image and the question are just the condition; the model doesn't have to predict them.
LLaVA's two training stages
How are these three parts trained? LLaVA does it in two stages:
|
Stage 1: feature alignment |
Stage 2: instruction tuning |
| Trained |
projection W only |
projection + language model |
| Frozen |
image encoder, language model |
image encoder |
| Data |
about 595,000 images with short captions |
158,000 multimodal instruction conversations |
- Stage 1, feature alignment. The task is simple: look at the image and say its caption. It's like writing an image dictionary for the language model, making the projected visual tokens land somewhere the model can read.
- Stage 2, instruction tuning. The conversations were written by a text-only GPT-4: it was given text descriptions of each image and the positions of its objects, and asked to make up questions and answers. They include everyday conversations, detailed descriptions and harder questions that take some reasoning.
LLaVA-1.5, later the same year, made a few upgrades: the projection became a small two-layer MLP, and the input resolution went up to 336, which means 576 visual tokens (336/14=24, and 24×24=576). The whole training run takes about a day on a single machine with 8 A100s.
Intuition: Vision encoder + projection + language model is the skeleton of most open-source multimodal models today.
Seeing big images: dynamic resolution
LLaVA's input size is fixed, say 336×336. Give it a big image, like a screenshot of a document page, and it has to shrink it first. Once shrunk, the small text blurs into mush, and however smart the model is, it can't read that.
LLaVA-NeXT's solution is called AnyRes, for any resolution (dynamic resolution):
- cut the big image into several 336×336 tiles (crops) and send each one separately through the same encoder;
- also shrink the whole image into a thumbnail and send it in too: each tile only sees one local piece, while the thumbnail provides the overall layout;
- each tile yields 576 visual tokens. A 672×672 image cut 2×2, plus the thumbnail, gives 5×576=2880 in total, all joined into one long sequence.
It supports several grids: 2×2 for square images, 1×4 for tall ones, 4×1 for wide ones. Given an image, it picks the grid whose aspect ratio is closest, to minimize stretching and wasted space.
Watch out: The cost is obvious: visual tokens jump from 576 to 2,880, five times as many, and the cost of attention grows with the square of the length.
There's a deeper question here, though: why does the encoder need a fixed input size at all?
Qwen2-VL: drop the position table, use 2D-RoPE
The problem is the position table
The answer is hiding in the position vectors. ViT's position vectors are learned absolute positions: a table with the fixed shape [256,D], one row per patch. Now say the image is bigger and gets cut into 20×20=400 patches. Which row does patch 257 get? There simply isn't one. With only 256 learned position embeddings, you're stuck with 256-patch images (always 224×224, for example).
The usual workaround is to interpolate the table up to a bigger size, but quality always suffers. It's what we saw in episode 8: a learned position table can't extrapolate.
Two-dimensional RoPE
Qwen2-VL is decisive: throw out the table and use the rotary position embedding from episode 8, RoPE, but in two dimensions (2D-RoPE). The patch size stays fixed, but positions are encoded as (row, column):
- Every patch has a coordinate, its row and its column, counting from zero. Say a patch sits in row 1, column 2.
- In attention, the q and k vectors are split into two halves: the first half is rotated by the row number, the second half by the column number. Row 1, so the first half turns by one step; column 2, so the second half turns by two steps.
Why does this work? Episode 8 showed that when two vectors are each rotated by their position, their dot product depends only on the difference between the positions:
⟨Rmθq,Rnθk⟩=q⊤R(n−m)θk
Now split q into its first half q(1) and second half q(2) (and k the same way), so the dot product becomes two halves added together. With the query patch at (r1,c1) and the key patch at (r2,c2), apply that result to each half:
q(1)⊤R(r2−r1)θk(1)+q(2)⊤R(c2−c1)θk(2)
The row half depends only on the difference in rows, the column half only on the difference in columns. So attention between two patches only looks at how many rows and columns apart they are, not which corner of the image they're in.
Intuition: RoPE's rotation angles are computed on the fly, with no table at all, so row 1,000 and column 1,000 work just as well. No longer tied to a fixed number of learned position embeddings, the model generalizes to any resolution and any aspect ratio.
Naive dynamic resolution
Qwen2-VL calls this naive dynamic resolution: images go in at roughly their original size, and you get as many tokens as there are patches. There's also a trick to save tokens:
- The patch size is 14, and before entering the language model, each 2×2 group of neighboring patches is merged into one token by a small MLP. So each visual token covers 28×28 pixels.
- The image sides are first adjusted to multiples of 28, and then the token count is
28H×28W
| Image size |
Visual tokens |
| 224×224 |
64 |
| 1344×756 |
1296 |
Small images spend few tokens and big images spend more, so tokens go where they're needed, and tall or wide images don't have to be squashed into squares. The paper's own example: a 224×224 image enters the language model as 64 visual tokens; add the two special start and end markers and that's 66.
M-RoPE: one numbering for text, images and video
Once the visual tokens are inside the language model, the same problem shows up again. RoPE in a language model is one-dimensional: the position is simply the token's index. Unroll the image tokens row by row and number them in order, and two patches that sit right on top of each other end up a whole row apart. (Number a 3×4 grid 0 to 11 row by row: cells 1 and 5 are vertical neighbors, but 4 apart.) The wider the image, the bigger the gap, so the numbers no longer reflect how close the patches really are.
Qwen2-VL's M-RoPE (multimodal RoPE) writes each position as three numbers: time t, height h and width w. The dimensions used for rotation are split into three sections too, and each section rotates by its own coordinate.
An example: two words, then an image with 2 rows and 3 columns, then three more words (r and c are a patch's row and column, from 0):
| Token |
t |
h |
w |
| word 1 |
0 |
0 |
0 |
| word 2 |
1 |
1 |
1 |
| patch (r,c) |
2 |
2+r |
2+c |
| next three words |
5, 6, 7 |
5, 6, 7 |
5, 6, 7 |
- Text tokens: all three numbers are the same, just the position in the sequence. All three sections rotate by the same angle, so M-RoPE reduces to ordinary 1D RoPE. With pure text, it's exactly the original language model.
- Image tokens: the time coordinate stays fixed; height and width take the row and column numbers, each shifted by the starting position, 2.
- Text after the image picks up from the largest number used so far, plus one. Here the largest is 2+2=4, so the next word starts at 5.
- Video is just a sequence of images: the time coordinate counts up frame by frame, while height and width work as before.
Intuition: There's a bonus too. A big image has over a thousand tokens (1,296 for a 1344×756 image), but its position numbers only move forward by a few dozen. Numbers that grow slowly make long inputs easier for the model to handle.
Today's paradigm
Today's multimodal models do two jobs: understanding images and drawing them.
- Understanding is basically the structure from this episode: a vision encoder (a ViT) extracts features, a projection turns them into visual tokens, and a language model takes it from there. The LLaVA family, the Qwen-VL family and InternVL, the mainstream open-source models, all share this skeleton. They differ mainly in the encoder, the resolution and the training data.
- Generation is mostly done with diffusion models: start from pure noise, remove the noise step by step, and end up with an image. They usually work directly in pixel space, or in a compressed latent space, rather than producing one token at a time the way text is written.
Some research also cuts images into discrete tokens and has the model draw them one at a time, like writing, or unifies understanding and generation in a single model. That's still a very active area.
Recap
- Multimodality comes down to translating an image into vectors in the same format as text tokens and feeding them into the same Transformer.
- ViT cuts an image into patches (256 patches of 588 numbers for a 224×224 image with patch size 14), multiplies each by one shared matrix, adds a learned position vector, and puts a CLS token in front. The encoder has no causal mask.
- CLIP trains an image encoder and a text encoder with a contrastive loss, cross-entropy across the rows and down the columns of the similarity matrix, so matching images and captions end up close together. That makes zero-shot classification possible, and makes CLIP a ready-made eye for multimodal models.
- LLaVA: CLIP encoder (second-to-last layer, CLS dropped) → projection W (1024 → 4096) → visual tokens placed before the text → language model. Stage 1 trains only the projection for alignment; stage 2 instruction-tunes the projection and the language model together.
- LLaVA-NeXT handles big images with tiles plus a thumbnail (576 → 2,880 tokens). Qwen2-VL replaces the fixed position table with 2D-RoPE to support any resolution and aspect ratio, merges 2×2 patches so each token covers 28×28 pixels, and uses M-RoPE's (t,h,w) to number text, images and video in one scheme.
- Today's recipe: understanding uses an encoder plus a language model; generation uses diffusion models.
Next up is a bonus episode: a bit of statistics, so you can tell what the experimental numbers in papers are really saying.