VLMs · Attention follow-up 2
From CLIP to Vision-Language Models
Following our CLIP lecture · ES 667 · Nipun Batra · IIT Gandhinagar
How Images Become Context for Language Generation
Last time: compare an image with descriptions.
Today: use the image to generate an answer.
How does visual information become context for next-token prediction?
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.001 / 178
80-minute teaching route; progressive builds are physical slides. The model lab and measured records are separate from illustrative arithmetic.
Ask: How does visual information become context for next-token prediction?
Answer: 80-minute teaching route; progressive builds are physical slides. The model lab and measured records are separate from illustrative arithmetic.
REVISION · CLIP · 1 / 4
Recall: two encoders, one comparison space
CLIP compares an image vector with a supplied text vector.
How does visual information become context for next-token prediction?
CLIP · Radford et al., 2021 · Previous lecture · CLIP02 / 178
Revision 1 of 4. Reuse the final encoder diagram from the CLIP lecture. Image ViT uses full attention and reads the final CLS state; the text Transformer uses causal attention and reads EOT. Both outputs are projected and unit-normalized before the dot product. The illustrated 512-coordinate width is the ViT-B/32 example, not a universal width. CLIP uses the text branch for representation, not autoregressive answer generation.
Ask: CLIP compares an image vector with a supplied text vector.
Answer: Revision 1 of 4. Reuse the final encoder diagram from the CLIP lecture. Image ViT uses full attention and reads the final CLS state; the text Transformer uses causal attention and reads EOT. Both outputs are projected and unit-normalized before the dot product. The illustrated 512-coordinate width is the ViT-B/32 example, not a universal width. CLIP uses the text branch for representation, not autoregressive answer generation.
REVISION · CLIP · 2 / 4
Recall: paired examples teach the match
The matching image–caption pair is the target in both directions.
How does visual information become context for next-token prediction?
CLIP · Radford et al., 2021 · Previous lecture · CLIP03 / 178
Revision 2 of 4. Cat, dog and car are the same illustrative pairs used in CLIP. Compare all images with all captions; the diagonal identifies observed pairs. Recall P = row-softmax(S), Q = column-softmax(S). Each direction averages the negative log probability of its paired cells; CLIP averages the two directional losses. Backpropagate into both encoders, both projections and the learned score scale. These probabilities are over batch candidates, not over next-word vocabulary tokens. Keep the numerical loss derivation in the preceding lecture.
Ask: The matching image–caption pair is the target in both directions.
Answer: Revision 2 of 4. Cat, dog and car are the same illustrative pairs used in CLIP. Compare all images with all captions; the diagonal identifies observed pairs. Recall P = row-softmax(S), Q = column-softmax(S). Each direction averages the negative log probability of its paired cells; CLIP averages the two directional losses. Backpropagate into both encoders, both projections and the learned score scale. These probabilities are over batch candidates, not over next-word vocabulary tokens. Keep the numerical loss derivation in the preceding lecture.
REVISION · CLIP · 3 / 4
Recall: reuse the vectors for different tasks
New descriptions give us new choices without retraining the encoders.
How does visual information become context for next-token prediction?
CLIP · Radford et al., 2021 · Previous lecture · CLIP04 / 178
Revision 3 of 4. Revisit the CLIP lecture examples: rank supplied descriptions, search a gallery with text, and compare a normalized after-minus-before image-vector difference with candidate words such as hat, boat, cup and cat. The last is the earlier hat-change experiment, not a universal arithmetic rule. All three rank given candidates; none generates a new answer token by token. The toy cat/dog/car illustrations and real hat-image pair are reused unchanged from the preceding lecture.
Ask: New descriptions give us new choices without retraining the encoders.
Answer: Revision 3 of 4. Revisit the CLIP lecture examples: rank supplied descriptions, search a gallery with text, and compare a normalized after-minus-before image-vector difference with candidate words such as hat, boat, cup and cat. The last is the earlier hat-change experiment, not a universal arithmetic rule. All three rank given candidates; none generates a new answer token by token. The toy cat/dog/car illustrations and real hat-image pair are reused unchanged from the preceding lecture.
REVISION · CLIP · 4 / 4
Next task: generate an answer from the image
A language decoder writes the reply, using the image as context.
How does visual information become context for next-token prediction?
CLIP · Radford et al., 2021 · Previous lecture · CLIP05 / 178
Revision 4 of 4. Keep the same dog image in both rows. First supply the descriptions a dog, a cat and a car: CLIP compares their image–text match scores and selects a dog from that list. Then change the task: provide the image and the instruction Describe this dog, with no candidate answers. We want an output sentence such as A black, long-haired dog is outdoors. The illustrated choice and reply are authored, not measured model results. New answer means an output sequence that was not supplied as a complete candidate description, not newly invented vocabulary entries. A generative VLM uses a language decoder to predict tokens from its existing vocabulary, conditioned on the image and prompt. We will derive the visual connection after the application examples. CLIP is a VLM in the broader sense, but its text encoder and matching score do not themselves implement this answer-generation path. If we supplied possible captions or colour descriptions, CLIP could rank those too; the distinction here is the requested output and interface, not an inability to represent such concepts.
Ask: A language decoder writes the reply, using the image as context.
Answer: Revision 4 of 4. Keep the same dog image in both rows. First supply the descriptions a dog, a cat and a car: CLIP compares their image–text match scores and selects a dog from that list. Then change the task: provide the image and the instruction Describe this dog, with no candidate answers. We want an output sentence such as A black, long-haired dog is outdoors. The illustrated choice and reply are authored, not measured model results. New answer means an output sequence that was not supplied as a complete candidate description, not newly invented vocabulary entries. A generative VLM uses a language decoder to predict tokens from its existing vocabulary, conditioned on the image and prompt. We will derive the visual connection after the application examples. CLIP is a VLM in the broader sense, but its text encoder and matching score do not themselves implement this answer-generation path. If we supplied possible captions or colour descriptions, CLIP could rank those too; the distinction here is the requested output and interface, not an inability to represent such concepts.
Section 01
What can a VLM do?
Start with the evidence an answer needs.
How does visual information become context for next-token prediction?
Original teaching example / diagram06 / 178
Start with the evidence an answer needs.
Ask:
Answer: Start with the evidence an answer needs.
01 · What can a VLM do?
Can the answer use visible evidence?
QUESTION
Is the laptop plugged in?
How does visual information become context for next-token prediction?
Original teaching example / diagram07 / 178
A visible connection does not prove power is flowing.
Ask: Is the laptop plugged in?
Answer: Yes. A cable connects the laptop to the socket.
01 · What can a VLM do?
Can the answer use visible evidence?
REFERENCE ANSWER
Is the laptop plugged in?
Yes. A cable connects the laptop to the socket.
How does visual information become context for next-token prediction?
Original teaching example / diagram08 / 178
A visible connection does not prove power is flowing.
Ask: Is the laptop plugged in?
Answer: Yes. A cable connects the laptop to the socket.
01 · What can a VLM do?
Can the answer use visible evidence?
ARCHITECTURAL REQUIREMENT
Is the laptop plugged in?
Yes. A cable connects the laptop to the socket.
Trace a connection between objects.
How does visual information become context for next-token prediction?
Original teaching example / diagram09 / 178
A visible connection does not prove power is flowing.
Ask: Is the laptop plugged in?
Answer: Yes. A cable connects the laptop to the socket.
01 · What can a VLM do?
Identity is only part of the question
QUESTION
What is immediately left of the mug?
How does visual information become context for next-token prediction?
Original teaching example / diagram10 / 178
The cube is also above the book; use this as a second oral question.
Ask: What is immediately left of the mug?
Answer: The red ball.
01 · What can a VLM do?
Identity is only part of the question
REFERENCE ANSWER
What is immediately left of the mug?
The red ball.
How does visual information become context for next-token prediction?
Original teaching example / diagram11 / 178
The cube is also above the book; use this as a second oral question.
Ask: What is immediately left of the mug?
Answer: The red ball.
01 · What can a VLM do?
Identity is only part of the question
ARCHITECTURAL REQUIREMENT
What is immediately left of the mug?
The red ball.
Keep object identity and spatial relations.
How does visual information become context for next-token prediction?
Original teaching example / diagram12 / 178
The cube is also above the book; use this as a second oral question.
Ask: What is immediately left of the mug?
Answer: The red ball.
01 · What can a VLM do?
The question selects a subset
QUESTION
How many apples are outside the bowl?
How does visual information become context for next-token prediction?
Original teaching example / diagram13 / 178
Five apples total; two in the bowl and three outside.
Ask: How many apples are outside the bowl?
Answer: Three.
01 · What can a VLM do?
The question selects a subset
REFERENCE ANSWER
How many apples are outside the bowl?
Three.
How does visual information become context for next-token prediction?
Original teaching example / diagram14 / 178
Five apples total; two in the bowl and three outside.
Ask: How many apples are outside the bowl?
Answer: Three.
01 · What can a VLM do?
The question selects a subset
ARCHITECTURAL REQUIREMENT
How many apples are outside the bowl?
Three.
Represent multiple objects and the region that selects them.
How does visual information become context for next-token prediction?
Original teaching example / diagram15 / 178
Five apples total; two in the bowl and three outside.
Ask: How many apples are outside the bowl?
Answer: Three.
01 · What can a VLM do?
Read first, then calculate
QUESTION
What is the invoice ID?
What percentage of the subtotal is GST?
How does visual information become context for next-token prediction?
Original teaching example / diagram16 / 178
Synthetic document. Separate text extraction errors from arithmetic errors.
Ask: What is the invoice ID? What percentage of the subtotal is GST?
Answer: ES667-042. GST is 180 / 1000 × 100 = 18%.
01 · What can a VLM do?
Read first, then calculate
REFERENCE ANSWER
What is the invoice ID?
What percentage of the subtotal is GST?
ES667-042. GST is 180 / 1000 × 100 = 18%.
How does visual information become context for next-token prediction?
Original teaching example / diagram17 / 178
Synthetic document. Separate text extraction errors from arithmetic errors.
Ask: What is the invoice ID? What percentage of the subtotal is GST?
Answer: ES667-042. GST is 180 / 1000 × 100 = 18%.
01 · What can a VLM do?
Read first, then calculate
ARCHITECTURAL REQUIREMENT
What is the invoice ID?
What percentage of the subtotal is GST?
ES667-042. GST is 180 / 1000 × 100 = 18%.
Preserve fine text, numbers and their roles.
How does visual information become context for next-token prediction?
Original teaching example / diagram18 / 178
Synthetic document. Separate text extraction errors from arithmetic errors.
Ask: What is the invoice ID? What percentage of the subtotal is GST?
Answer: ES667-042. GST is 180 / 1000 × 100 = 18%.
01 · What can a VLM do?
The labels change the answer
QUESTION
Which month is highest?
How much higher is March than January?
How does visual information become context for next-token prediction?
Original teaching example / diagram19 / 178
Synthetic values: January 30, February 45, March 75, April 40.
Ask: Which month is highest? How much higher is March than January?
Answer: March. The difference is 45 µg/m³.
01 · What can a VLM do?
The labels change the answer
REFERENCE ANSWER
Which month is highest?
How much higher is March than January?
March. The difference is 45 µg/m³.
How does visual information become context for next-token prediction?
Original teaching example / diagram20 / 178
Synthetic values: January 30, February 45, March 75, April 40.
Ask: Which month is highest? How much higher is March than January?
Answer: March. The difference is 45 µg/m³.
01 · What can a VLM do?
The labels change the answer
ARCHITECTURAL REQUIREMENT
Which month is highest?
How much higher is March than January?
March. The difference is 45 µg/m³.
Bind chart labels to values and units.
How does visual information become context for next-token prediction?
Original teaching example / diagram21 / 178
Synthetic values: January 30, February 45, March 75, April 40.
Ask: Which month is highest? How much higher is March than January?
Answer: March. The difference is 45 µg/m³.
01 · What can a VLM do?
A diagram supplies conditions
QUESTION
What is x?
How does visual information become context for next-token prediction?
Original teaching example / diagram22 / 178
The right-angle marker, rather than appearance alone, licenses Pythagoras.
Ask: What is x?
Answer: x = 5, using the marked right angle and sides 3 and 4.
01 · What can a VLM do?
A diagram supplies conditions
REFERENCE ANSWER
What is x?
x = 5, using the marked right angle and sides 3 and 4.
How does visual information become context for next-token prediction?
Original teaching example / diagram23 / 178
The right-angle marker, rather than appearance alone, licenses Pythagoras.
Ask: What is x?
Answer: x = 5, using the marked right angle and sides 3 and 4.
01 · What can a VLM do?
A diagram supplies conditions
ARCHITECTURAL REQUIREMENT
What is x?
x = 5, using the marked right angle and sides 3 and 4.
Combine diagram evidence with a mathematical rule.
How does visual information become context for next-token prediction?
Original teaching example / diagram24 / 178
The right-angle marker, rather than appearance alone, licenses Pythagoras.
Ask: What is x?
Answer: x = 5, using the marked right angle and sides 3 and 4.
01 · What can a VLM do?
Compare presence and position
QUESTION
What changed from A to B?
How does visual information become context for next-token prediction?
Original teaching example / diagram25 / 178
Two panels in a single composite for the small browser model. Native multi-image systems can take separate ordered images.
Ask: What changed from A to B?
Answer: The chair moved to the right; the cup disappeared.
01 · What can a VLM do?
Compare presence and position
REFERENCE ANSWER
What changed from A to B?
The chair moved to the right; the cup disappeared.
How does visual information become context for next-token prediction?
Original teaching example / diagram26 / 178
Two panels in a single composite for the small browser model. Native multi-image systems can take separate ordered images.
Ask: What changed from A to B?
Answer: The chair moved to the right; the cup disappeared.
01 · What can a VLM do?
Compare presence and position
ARCHITECTURAL REQUIREMENT
What changed from A to B?
The chair moved to the right; the cup disappeared.
Compare evidence across images.
How does visual information become context for next-token prediction?
Original teaching example / diagram27 / 178
Two panels in a single composite for the small browser model. Native multi-image systems can take separate ordered images.
Ask: What changed from A to B?
Answer: The chair moved to the right; the cup disappeared.
01 · What can a VLM do?
A screenshot is a spatial interface
QUESTION
Where should I click to disable notifications?
How does visual information become context for next-token prediction?
Original teaching example / diagram28 / 178
Describing a control is distinct from executing a click.
Ask: Where should I click to disable notifications?
Answer: The blue toggle on the Notifications row.
01 · What can a VLM do?
A screenshot is a spatial interface
REFERENCE ANSWER
Where should I click to disable notifications?
The blue toggle on the Notifications row.
How does visual information become context for next-token prediction?
Original teaching example / diagram29 / 178
Describing a control is distinct from executing a click.
Ask: Where should I click to disable notifications?
Answer: The blue toggle on the Notifications row.
01 · What can a VLM do?
A screenshot is a spatial interface
ARCHITECTURAL REQUIREMENT
Where should I click to disable notifications?
The blue toggle on the Notifications row.
Locate a control relative to its label.
How does visual information become context for next-token prediction?
Original teaching example / diagram30 / 178
Describing a control is distinct from executing a click.
Ask: Where should I click to disable notifications?
Answer: The blue toggle on the Notifications row.
01 · What can a VLM do?
The image can be a scientific figure
QUESTION
What is the hottest measured region?
How does visual information become context for next-token prediction?
Original teaching example / diagram31 / 178
Synthetic test-plate measurements; count rows and columns from the top left.
Ask: What is the hottest measured region?
Answer: Row 3, column 4: 62 °C.
01 · What can a VLM do?
The image can be a scientific figure
REFERENCE ANSWER
What is the hottest measured region?
Row 3, column 4: 62 °C.
How does visual information become context for next-token prediction?
Original teaching example / diagram32 / 178
Synthetic test-plate measurements; count rows and columns from the top left.
Ask: What is the hottest measured region?
Answer: Row 3, column 4: 62 °C.
01 · What can a VLM do?
The image can be a scientific figure
ARCHITECTURAL REQUIREMENT
What is the hottest measured region?
Row 3, column 4: 62 °C.
Read a scale and local measurements.
How does visual information become context for next-token prediction?
Original teaching example / diagram33 / 178
Synthetic test-plate measurements; count rows and columns from the top left.
Ask: What is the hottest measured region?
Answer: Row 3, column 4: 62 °C.
01 · What can a VLM do?
The question can be wrong
QUESTION
What color is the bicycle?
How does visual information become context for next-token prediction?
Original teaching example / diagram34 / 178
Coffee photo by Rachel Michetti, CC0 via scikit-image. A color answer would be unsupported.
Ask: What color is the bicycle?
Answer: No bicycle is visible.
01 · What can a VLM do?
The question can be wrong
REFERENCE ANSWER
What color is the bicycle?
No bicycle is visible.
How does visual information become context for next-token prediction?
Original teaching example / diagram35 / 178
Coffee photo by Rachel Michetti, CC0 via scikit-image. A color answer would be unsupported.
Ask: What color is the bicycle?
Answer: No bicycle is visible.
01 · What can a VLM do?
The question can be wrong
ARCHITECTURAL REQUIREMENT
What color is the bicycle?
No bicycle is visible.
Let visual evidence override the wording of the question.
How does visual information become context for next-token prediction?
Original teaching example / diagram36 / 178
Coffee photo by Rachel Michetti, CC0 via scikit-image. A color answer would be unsupported.
Ask: What color is the bicycle?
Answer: No bicycle is visible.
01 · What can a VLM do?
What must survive the visual representation?
| Question family | Information needed |
|---|---|
| Counting / spatial | Multiple objects and their arrangement |
| OCR / charts | Fine detail, labels, values and units |
| UI / multiple images | Locations and correspondence across views |
| False premise | Evidence that can contradict the prompt |
Would one global CLIP vector always be enough?
How does visual information become context for next-token prediction?
Original teaching example / diagram37 / 178
A global vector can be useful, but fine-grained tasks motivate exposing richer visual states. This is a design motivation, not an impossibility theorem.
Ask: Would one global CLIP vector always be enough?
Answer: A global vector can be useful, but fine-grained tasks motivate exposing richer visual states. This is a design motivation, not an impossibility theorem.
01 · What can a VLM do?
Compare two small vision-language models
Predict → compare → inspect both answers.
Open the VLM lab ↗256M and 500M · same image and question.
Live or recorded answers; image-swap experiment.
A reference answer is not a model prediction.
How does visual information become context for next-token prediction?
SmolVLM-256M · model card · SmolVLM-500M · model card · Official Transformers.js browser example38 / 178
Preload the model before class. First download needs network; recorded outputs are available offline. Run the dog, spatial and absent-object cases.
Ask: A reference answer is not a model prediction.
Answer: Preload the model before class. First download needs network; recorded outputs are available offline. Run the dog, spatial and absent-object cases.
Section 02
From matching to generation
We have an image encoder. We also know a language decoder.
How does visual information become context for next-token prediction?
Original teaching example / diagram39 / 178
We have an image encoder. We also know a language decoder.
Ask:
Answer: We have an image encoder. We also know a language decoder.
02 · From matching to generation
We already know this decoder from Beyond Attention
Read the last updated state → score the vocabulary → append a token → repeat.
How does visual information become context for next-token prediction?
Original teaching example / diagram40 / 178
Reuse the decoder-only portrait and the Raghav goes to → school example from Beyond Attention. First reveal the known text. Then look up the token embeddings and supply position information. The drawing uses additive positions as the familiar teaching example; other decoders may implement positions with RoPE inside attention. Repeat L blocks of causal self-attention plus residual and MLP plus residual. The triangular permission matrix means each position can use itself and earlier positions. Every position gets an updated state, but to extend this prefix read only the last one, e3. Final normalization, where required by the model, is omitted from this recap. The vocabulary head maps the last state to scores for all vocabulary entries; a selection rule chooses the next token. The illustrative continuation is school. Append its token, look up its embedding and repeat with the longer prefix; a KV cache can reuse preceding computation. These are illustrative word-sized tokens, not measured tokenizer boundaries or a checkpoint output. No separate text encoder or cross-attention is needed for this text-only decoder. The source architecture is transformer-outputs/figures/decoder-use.svg, generated by decoder_portrait in its src/refinement_diagrams.py.
Ask: Read the last updated state → score the vocabulary → append a token → repeat.
Answer: Reuse the decoder-only portrait and the Raghav goes to → school example from Beyond Attention. First reveal the known text. Then look up the token embeddings and supply position information. The drawing uses additive positions as the familiar teaching example; other decoders may implement positions with RoPE inside attention. Repeat L blocks of causal self-attention plus residual and MLP plus residual. The triangular permission matrix means each position can use itself and earlier positions. Every position gets an updated state, but to extend this prefix read only the last one, e3. Final normalization, where required by the model, is omitted from this recap. The vocabulary head maps the last state to scores for all vocabulary entries; a selection rule chooses the next token. The illustrative continuation is school. Append its token, look up its embedding and repeat with the longer prefix; a KV cache can reuse preceding computation. These are illustrative word-sized tokens, not measured tokenizer boundaries or a checkpoint output. No separate text encoder or cross-attention is needed for this text-only decoder. The source architecture is transformer-outputs/figures/decoder-use.svg, generated by decoder_portrait in its src/refinement_diagrams.py.
02 · From matching to generation
Keep this decoder; give it access to the image
We have both components. Next, choose how the decoder accesses the visual rows.
How does visual information become context for next-token prediction?
Original teaching example / diagram41 / 178
Carry the same causal attention / MLP / last-state / vocabulary-head grammar forward from Beyond Attention. Now the text prompt is Describe this dog. The ViT image branch uses full self-attention and exposes N contextual feature rows; h1, h2, …, hN denotes all retained rows, with middle rows abbreviated. The text branch tokenizes the prompt and looks up embeddings with position information; there is no separate text encoder. For clarity this drawing shows only the last updated output state, although the blocks update every position. Word-sized tokens are illustrative. Normalization, tokenizer IDs and exact position implementation are omitted here. Keep the two branches disconnected: the decoder can already generate tokens but has not yet been given the image features. Do not imply that an unconnected language decoder can see the dog. The three following idea diagrams show the alternative connections before we derive their details.
Ask: We have both components. Next, choose how the decoder accesses the visual rows.
Answer: Carry the same causal attention / MLP / last-state / vocabulary-head grammar forward from Beyond Attention. Now the text prompt is Describe this dog. The ViT image branch uses full self-attention and exposes N contextual feature rows; h1, h2, …, hN denotes all retained rows, with middle rows abbreviated. The text branch tokenizes the prompt and looks up embeddings with position information; there is no separate text encoder. For clarity this drawing shows only the last updated output state, although the blocks update every position. Word-sized tokens are illustrative. Normalization, tokenizer IDs and exact position implementation are omitted here. Keep the two branches disconnected: the decoder can already generate tokens but has not yet been given the image features. Do not imply that an unconnected language decoder can see the dog. The three following idea diagrams show the alternative connections before we derive their details.
Section 03
How can vision enter a language model?
First, see the three ideas. Then build each connection.
How does visual information become context for next-token prediction?
Original teaching example / diagram42 / 178
First, see the three ideas. Then build each connection.
Ask:
Answer: First, see the three ideas. Then build each connection.
03 · How can vision enter a language model?
Idea 1 · prepend the image as visual tokens
Keep all N patch vectors in this design; N depends on the image grid.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 202343 / 178
Trace both paths before naming the join. The vision encoder produces one contextual feature row per patch; a row-wise projector adapts every row to the decoder width. V1, V2, …, VN represents the full N-row sequence, not a selection of four patches. The question and answer generated so far are token IDs with embedding vectors; concatenate their embeddings after the image vectors. At the first step, no answer tokens exist. Generation appends one token at a time; cached computation can reuse earlier states. Chat/system markers and positional handling are omitted here. No separate text encoder is added: tokenization and embedding lookup feed the causal language decoder. Show all three ideas before deriving patch grids, widths or weights.
Ask: Do we keep only four patches, and does the decoder receive raw question text?
Answer: No. This basic prefix design keeps all N patch rows and projects each one. The question and already-generated answer tokens are embedded; their vectors follow V1, V2, …, VN in one decoder input sequence. Before the first prediction, the answer portion is empty.
03 · How can vision enter a language model?
Idea 2 · let the decoder look at a visual memory
As in translation: encode the source, then let the text decoder read its states.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 2017 · ViT · Dosovitskiy et al., 202044 / 178
Visual memory is the sequence produced by the vision encoder, not a second encoder or a separate learned memory bank. h1, h2, …, hN abbreviates all N retained image feature rows. The question and answer-so-far tokens become e1, e2, …, eT through embedding lookup; T is the current text length. The answer is empty for the first prediction and grows only from generated token IDs. A causal decoder needs cross-attention sublayers to use this route: text states supply queries, visual features supply keys and values, and the attention result updates text states before the vocabulary head scores the next token. This is the sequence-to-sequence connection from English-to-Hindi translation, with the image as source. The overview shows the two attention operations and the MLP/residual updates; normalization, projection details, positional handling, chat markers and repeated blocks are omitted. The example uses a 224×224 image and 16×16 patches: 14×14=196 patch rows; retaining the global CLS row gives 197. Neither is universal. Compression can shorten this memory later; Flamingo also resamples features and uses gated cross-attention, so this is not its exact architecture.
Ask: Is visual memory another model? Does cross-attention itself produce the answer word?
Answer: Visual memory is the encoder’s sequence of image features. The language decoder reads it through cross-attention, like a translation decoder reading source-language states. That updates text states; the vocabulary head then scores the next token. N is not fixed: a 224×224 image with 16×16 patches gives 196 patch rows, or 197 rows if CLS is retained.
03 · How can vision enter a language model?
Idea 3 · summarize the image, then use either connection
Compression reduces N image rows to M summaries; either decoder connection remains possible.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 202245 / 178
Read the common image path first: the ViT encoder uses full self-attention and exposes all N contextual patch rows. A learned-query summarizer uses M shared trainable query vectors to cross-attend to those image features, producing M image-dependent summaries. This is a representative resampler mechanism, not a subset selection and not a complete implementation of a named model. N > M; omitted boxes stand for intermediate rows. Now choose one of two alternative decoder connections. A projects each summary to the decoder width, concatenates those vectors before text embeddings, and uses causal self-attention over the joined sequence. Projection changes width, not the already-reduced M row count. B retains S1…SM as separate memory: text embeddings enter causal self-attention, then text states supply Q while summaries supply K,V for decoder cross-attention. The vocabulary head produces next-token scores in both routes. The compression cross-attention uses learned queries; decoder cross-attention uses text-derived queries. Question tokens and previously generated answer tokens are embedded; the answer starts empty. v labels are projected summary vectors; e labels are text embeddings. A and B are alternatives, not consecutive stages. Decoder MLPs, residuals, normalization, position handling and repeated blocks are abstracted in this overview and restored in the deep dives. Source notes discuss BLIP-2 and Flamingo as examples with additional model-specific components.
Ask: After producing M summaries, must language read them with cross-attention?
Answer: No. In route A, project the M summaries, prepend them to the text embeddings, and use decoder causal self-attention. In route B, keep the M summaries separate and let decoder cross-attention read them. The summarizer itself can use learned-query cross-attention in either route; that is a different operation from the decoder’s text-query cross-attention.
03 · How can vision enter a language model?
The map: two access routes, one compression choice
| Idea | High-level decision | Then we will explain… |
|---|---|---|
| 1 · Visual prefix | Put visual vectors before text. | How to make them fit the decoder input. |
| 2 · Separate memory | Let language read the image. | How a text state retrieves visual information. |
| 3 · Shorter summary | Use fewer visual vectors. | How learned readers make the summaries. |
Ideas 1 and 2 choose the access route. Idea 3 can be used with either.
How does visual information become context for next-token prediction?
Original teaching example / diagram46 / 178
Spend roughly five minutes on the three preceding idea slides, with no matrix shapes or attention arithmetic. Ask students to explain each idea in one sentence. Now return to Idea 1 and derive it. Ideas 2 and 3 get their own later deep dives.
Ask: Must a model choose only one of these three ideas?
Answer: No. Prefix and separate memory are two ways to access vision. Compression can be combined with either; for example, a short visual summary can be prepended to the text.
03 · How can vision enter a language model?
Idea 1 in detail · build the visual prefix
One sequence; the same causal self-attention can use both kinds of context.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 202347 / 178
Trace all N patch rows through the amber projector into the input row. Trace question and answer-so-far tokenization and embedding into the same row. The answer is initially empty, then grows by generated tokens. V1, V2, …, VN abbreviates the full visual sequence. Point to causal self-attention, MLP and vocabulary head from the previous lecture. Positions, normalization and exact chat markers are omitted. We will now unpack only the new visual path.
Ask: One sequence; the same causal self-attention can use both kinds of context.
Answer: Trace all N patch rows through the amber projector into the input row. Trace question and answer-so-far tokenization and embedding into the same row. The answer is initially empty, then grows by generated tokens. V1, V2, …, VN abbreviates the full visual sequence. Point to causal self-attention, MLP and vocabulary head from the previous lecture. Positions, normalization and exact chat markers are omitted. We will now unpack only the new visual path.
03 · How can vision enter a language model?
What must we build to make this work?
| Job | Why it is needed |
|---|---|
| 1. Keep image feature vectors | The decoder needs access to visual evidence. |
| 2. Match the decoder input width | All input rows must have the same number of coordinates. |
| 3. Place them before the question | Causal attention can read earlier context. |
We already have the decoder. Now build its visual input.
How does visual information become context for next-token prediction?
Original teaching example / diagram48 / 178
Return to this three-job plan after the projector calculation and after the mask. Students should be able to point to each job in the preceding complete architecture.
Ask: We already have the decoder. Now build its visual input.
Answer: Return to this three-job plan after the projector calculation and after the mask. Students should be able to point to each job in the preceding complete architecture.
03 · How can vision enter a language model?
Recall ViT: every patch already has an output row
Patch 1 has row h1, patch 2 has row h2, and so on through patch 12.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 202049 / 178
The numbered 3 × 4 grid is an illustrative twelve-patch example, not a model configuration. All twelve patch rows are drawn, in row-major order matching the image labels. Each box denotes one whole feature vector, not one scalar coordinate. ViT embeds the patches, adds positions, and updates their states with full self-attention. The row at patch position i can therefore contain information from the whole image. The CLS row is introduced on the next slide.
Ask: Patch 1 has row h1, patch 2 has row h2, and so on through patch 12.
Answer: The numbered 3 × 4 grid is an illustrative twelve-patch example, not a model configuration. All twelve patch rows are drawn, in row-major order matching the image labels. Each box denotes one whole feature vector, not one scalar coordinate. ViT embeds the patches, adds positions, and updates their states with full self-attention. The row at patch position i can therefore contain information from the whole image. The CLS row is introduced on the next slide.
03 · How can vision enter a language model?
ViT outputs a CLS state and one row per patch
Forward all 12 patch rows to the projector; leave out the CLS output.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 202050 / 178
Use the same twelve numbered image patches and twelve output rows as the previous slide. This standard ViT also has a CLS token, introduced before the encoder; its output state provides a whole-image summary. CLS is an extra sequence position, not a thirteenth image patch or a separate encoder. The diagram abstracts patch embedding, positions, and the input CLS token inside the ViT path. Its twelve patch states are contextual vectors, not isolated patch descriptors. For the visual-prefix design being developed, retain all twelve patch rows and then project each one to the decoder width; the CLS state is not included in that patch sequence. Twelve is the complete illustrative example, not a universal model count. Keep this explanation about ViT outputs; the earlier CLIP matching discussion need not be repeated.
Ask: Forward all 12 patch rows to the projector; leave out the CLS output.
Answer: Use the same twelve numbered image patches and twelve output rows as the previous slide. This standard ViT also has a CLS token, introduced before the encoder; its output state provides a whole-image summary. CLS is an extra sequence position, not a thirteenth image patch or a separate encoder. The diagram abstracts patch embedding, positions, and the input CLS token inside the ViT path. Its twelve patch states are contextual vectors, not isolated patch descriptors. For the visual-prefix design being developed, retain all twelve patch rows and then project each one to the decoder width; the CLS state is not included in that patch sequence. Twelve is the complete illustrative example, not a universal model count. Keep this explanation about ViT outputs; the earlier CLIP matching discussion need not be repeated.
03 · How can vision enter a language model?
Pass the patch rows onward; leave out CLS
This design sends all N patch rows to the projector and omits the CLS output.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · ViT · Dosovitskiy et al., 202051 / 178
Answer the selection question explicitly: use the patch rows alone, not CLS plus patch rows. The CLS token is still present inside the ViT; only its output row is excluded at the connector interface. The twelve displayed patch rows are the complete illustrative set, not a count measured from a model processing this invoice. In general N follows from the retained image patch grid. The invoice asks for an exact ID and a numerical relationship, motivating access to multiple spatially indexed feature vectors rather than routing the entire image through only one global summary. All patch rows are contextual after full self-attention; they are not isolated pixel crops or object labels. Keeping them gives the decoder access to these separate features but does not guarantee OCR or fine-detail accuracy. This is the LLaVA-style patch-only connection being taught, not a rule that every VLM must discard CLS. Original LLaVA feature_select in patch mode keeps image_features[:, 1:], while cls_patch is an alternative. Return to the Newfoundland image on the next frame.
Ask: Do we forward CLS plus the patch rows, or just the patch rows?
Answer: Just the N patch output rows in this design. CLS participates inside the vision encoder, then its output row is omitted. Every retained patch row goes through the projector and becomes one visual-prefix vector. Other architectures may make a different selection.
03 · How can vision enter a language model?
A visual state is one row of the feature matrix
One patch position → one output row. Each row has dᵥ feature values.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 2020 · Oxford-IIIT Pet · CC BY-SA 4.052 / 178
Revisit the same dog and complete twelve-patch grid as the preceding ViT recap. Read the image in row-major order: all twelve patches become twelve input tokens after patch embedding and position information. The full-attention ViT updates every token using image context. Stack all twelve retained output patch rows into Hᵥ. Every matrix cell hᵢ,ⱼ is one scalar feature; hᵢ is the complete row vector, not one scalar or an object label. N counts rows (visual token positions); dᵥ counts columns (features per token). Highlight patch 5, input token p5, and output row h5 to show position correspondence, while emphasizing that full attention makes h5 contextual rather than an isolated patch descriptor. This illustration uses N=12 and dᵥ=2 to show every row and column, consistent with the two-coordinate worked example that follows. These are illustrative dimensions, not actual model widths or measured features. No patch rows are omitted. CLS is excluded from the retained patch matrix and the batch axis is omitted because we show one image. With a batch, the shape is B × N × dᵥ.
Ask: In the drawn example, how many visual tokens and how many features does each output token have?
Answer: Twelve retained visual tokens give N=12 rows. Each output row has dᵥ=2 feature values, so Hᵥ is 12 × 2. h5 is the whole fifth row, whose two cells are h5,1 and h5,2. Attention allows that row to contain information from other image patches.
03 · How can vision enter a language model?
Recall: the decoder already consumes vectors
Text IDs become embeddings before reaching the Transformer blocks.
How does visual information become context for next-token prediction?
Original teaching example / diagram53 / 178
This is the connection to the earlier text architecture: tokenization selects embedding rows. Image vectors bypass a word-ID lookup and enter at the vector interface. They also need the implementation’s positional treatment.
Ask: Text IDs become embeddings before reaching the Transformer blocks.
Answer: This is the connection to the earlier text architecture: tokenization selects embedding rows. Image vectors bypass a word-ID lookup and enter at the vector interface. They also need the implementation’s positional treatment.
03 · How can vision enter a language model?
The image rows have 2 coordinates; text rows have 3
To form one input sequence, every vector must have the decoder’s input width.
How does visual information become context for next-token prediction?
Original teaching example / diagram54 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. Ask students to point to one row, then count its coordinates. The image and text may have different numbers of rows; the problem is their different row widths.
Ask: Do N and T need to match, or must the number of coordinates per row match?
Answer: The row widths must match. N image rows and T text rows can have different counts. After projecting the image rows to width 3, concatenate N + T rows for the decoder.
03 · How can vision enter a language model?
Add a projector to the image path
The projector changes N × 2 image features into N × 3 visual vectors.
How does visual information become context for next-token prediction?
Original teaching example / diagram55 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. Read each shape beneath the corresponding visible module. The text embeddings are already T × 3 and remain unchanged. In general Hᵥ is N × dV, Wₚ is dV × dL, and Z = HᵥWₚ is N × dL. Bias is omitted. Real connectors can use an MLP. Matching shapes only makes the interface valid; learning must make the projected contents useful.
Ask: The projector changes N × 2 image features into N × 3 visual vectors.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. Read each shape beneath the corresponding visible module. The text embeddings are already T × 3 and remain unchanged. In general Hᵥ is N × dV, Wₚ is dV × dL, and Z = HᵥWₚ is N × dL. Bias is omitted. Real connectors can use an MLP. Matching shapes only makes the interface valid; learning must make the projected contents useful.
03 · How can vision enter a language model?
Zoom into one row from the image
Take one 2-coordinate row from the image feature sequence.
How does visual information become context for next-token prediction?
Original teaching example / diagram56 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: Take one 2-coordinate row from the image feature sequence.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
Use a 2 × 3 matrix to change the width
Each column makes one of the 3 decoder-input coordinates.
How does visual information become context for next-token prediction?
Original teaching example / diagram57 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: Each column makes one of the 3 decoder-input coordinates.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
The first column makes the first coordinate
Which input coordinates does this column combine?
How does visual information become context for next-token prediction?
Original teaching example / diagram58 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: Which input coordinates does this column combine?
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
The first output coordinate is 2
The first output coordinate copies the first input in this toy map.
How does visual information become context for next-token prediction?
Original teaching example / diagram59 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: The first output coordinate copies the first input in this toy map.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
The second column reuses the same image row
Now use the same input row with the second column.
How does visual information become context for next-token prediction?
Original teaching example / diagram60 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: Now use the same input row with the second column.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
The second output coordinate is 1
The second output coordinate copies the second input in this toy map.
How does visual information become context for next-token prediction?
Original teaching example / diagram61 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: The second output coordinate copies the second input in this toy map.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
The third column combines both input coordinates
The third output coordinate adds the two inputs in this toy map.
How does visual information become context for next-token prediction?
Original teaching example / diagram62 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: The third output coordinate adds the two inputs in this toy map.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
Now this image vector has the required width
The row [2, 1, 3] fits beside the 3-coordinate text embeddings.
How does visual information become context for next-token prediction?
Original teaching example / diagram63 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
Ask: The row [2, 1, 3] fits beside the 3-coordinate text embeddings.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The highlighted h1 is the first image feature row in the persistent top diagram. Wₚ = [[1,0,1],[0,1,1]] is shared across all image rows. The weights are chosen for easy arithmetic; actual connector weights are learned. Each output coordinate is the input row dotted with one matrix column. The lower zoom changes while both input paths remain fixed. Predict the next coordinate before advancing.
03 · How can vision enter a language model?
Use the same matrix for all N image rows
N rows stay N rows; every projected row now has 3 coordinates.
How does visual information become context for next-token prediction?
Original teaching example / diagram64 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The same Wₚ gives [2,1,3] from [2,1], [1,3,4] from [1,3], and [0,2,2] from [0,2]. No patch is dropped and no independent projector is created for each patch. Text E is unchanged.
Ask: N rows stay N rows; every projected row now has 3 coordinates.
Answer: The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. The same Wₚ gives [2,1,3] from [2,1], [1,3,4] from [1,3], and [0,2,2] from [0,2]. No patch is dropped and no independent projector is created for each patch. Text E is unchanged.
03 · How can vision enter a language model?
Check: did the projector create more visual tokens?
Predict the output shape before advancing.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.065 / 178
Stay with the example already on the board. Twelve is derived from the complete 3 × 4 patch grid shown again here. Two is the illustrative vision feature width in Hᵥ; three is the illustrative text embedding and decoder-input width. The widths are teaching choices from the preceding worked example, not quantities measured from the dog image. Wₚ has two rows and three columns so it maps every two-feature image row to a three-feature vector. Do not introduce realistic model-scale widths at this checkpoint.
Ask: Our image has 3 × 4 patches. Hᵥ is 12 × 2 and Wₚ is 2 × 3. What is the shape of Z?
Answer: 12 × 3. Twelve comes from the image patch count. Two and three are the illustrative input and output feature widths from our worked example. Row-wise projection retains all twelve visual token positions.
03 · How can vision enter a language model?
Still 12 rows; each row now has 3 features
The projector changes each row’s features and keeps every patch position.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.066 / 178
The source panels and matrix shapes stay in the same places as on the question slide. Read (12 × 2)(2 × 3) = 12 × 3. The shared inner dimension two makes the multiplication valid; twelve rows remain, and each output row has three coordinates. A lower row count would require an additional compression operation, introduced later. These are the same illustrative feature widths, not a newly introduced model configuration.
Ask: Which dimensions change, and where did they come from?
Answer: N=12 comes from the 3 × 4 image grid and stays fixed. The feature width changes from the chosen vision width dᵥ=2 to the chosen decoder/text width dₗ=3.
03 · How can vision enter a language model?
Now the two sequences fit one decoder input
Our LLaVA-style example uses causal attention from the first image position.
How does visual information become context for next-token prediction?
Original teaching example / diagram67 / 178
The photograph and actual question provide the same visual context on every frame. All displayed embedding values and widths are hand-set, not measured from either input. Two and three mean coordinates per feature vector, not image dimensions or counts of tokens. N is the full retained patch-row count; T includes question and already-generated answer tokens. Middle rows are omitted only from the drawing. The illustrative answer so far is A black; it is empty before the first prediction. Real token boundaries, chat markers and position handling are omitted. Hᵥ contains contextual vision-encoder features. The text branch tokenizes to IDs and looks up embeddings; no separate text encoder is added. Z has N rows and E has T rows; their joined input is (N + T) × 3 in this toy example. Distinguish the two attention stages: the ViT uses full image self-attention before projection; the standard causal decoder applies a lower-triangular mask across every joined position, starting at z1 rather than switching it on only at the first text position. At a decoder layer, z1 reads itself, z2 reads z1 and itself, and the first text row reads all N preceding visual rows and itself. The visual vectors already contain whole-image context from the ViT, so a causal decoder does not undo that encoder context. With the image and prompt supplied, all their positions can be computed in parallel within each decoder layer during prefill; this does not generate image patches one at a time. Only new answer tokens are generated autoregressively. This is the basic LLaVA-style causal-prefix design, not a universal rule: some other VLMs allow bidirectional attention within an image block. System/role markers and positions are abstracted. Visual rows remain continuous vectors, not vocabulary IDs.
Ask: Does the causal mask start only when the decoder reaches the first text row?
Answer: In this design it covers the whole decoder sequence, including visual positions from z1. The ViT earlier used full image attention. Known image and prompt rows are processed together in a masked prefill pass; later answer tokens are generated one by one. The upcoming mask shows exactly which visual and text positions can read each other.
03 · How can vision enter a language model?
Start with all the projected image vectors
Keep all 12 patch rows; each row has the decoder’s input width.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.068 / 178
Continue the same 3 × 4 image and 2-to-3 feature-width example. All twelve projected vectors are drawn. They are inserted as vectors rather than looked up from word vocabulary IDs. The next slides explain the formatted text part.
Ask: Keep all 12 patch rows; each row has the decoder’s input width.
Answer: Continue the same 3 × 4 image and 2-to-3 feature-width example. All twelve projected vectors are drawn. They are inserted as vectors rather than looked up from word vocabulary IDs. The next slides explain the formatted text part.
03 · How can vision enter a language model?
USER and ASST mark who is speaking
The template supplies the role markers; generation continues after ASST.
How does visual information become context for next-token prediction?
Chat templates · Hugging Face69 / 178
This is a teaching chat format, not an exact LLaVA serialization. USER and ASST are readable stand-ins. Some models have dedicated single vocabulary tokens for roles; others spell roles using ordinary tokens and separators, so one role label need not equal one token. Image placement, delimiters and tokenization depend on the trained chat template. Keep the same template at training and inference. The user marker begins the human message; the assistant marker cues the model response. Both are already in the inference prompt before generating the first answer token. It is an illustrative first token, not a measured prediction. Chat training teaches the model how to respond to these structural cues.
Ask: Does the model have to generate ASST before it can answer?
Answer: In this illustrated template, no. The application adds the assistant-start marker to the prompt. The model predicts the first answer token from the final supplied position.
03 · How can vision enter a language model?
Role tokens use the same embedding table
A special role token is a vocabulary entry with its own learned embedding row.
How does visual information become context for next-token prediction?
Chat templates · Hugging Face · Vocabulary embeddings · Transformers70 / 178
This is a teaching chat format, not an exact LLaVA serialization. USER and ASST are readable stand-ins. Some models have dedicated single vocabulary tokens for roles; others spell roles using ordinary tokens and separators, so one role label need not equal one token. Image placement, delimiters and tokenization depend on the trained chat template. Keep the same template at training and inference. For this single-token illustration, idᵤ and idₐ are symbolic vocabulary indices, not extra numerical features. E has vocabulary-size rows and dL columns; only three selected rows are shown. The blank cells stand for learned coordinates. Existing tokens reuse checkpoint embeddings. When training from scratch, embedding weights are initialized once; adding tokens to an existing vocabulary requires allocating and initializing new rows, for example randomly or from statistics of existing rows. Exact initialization is model/recipe dependent, not necessarily identical for new and original rows. Chat-format training shapes the model’s use of roles through the answer loss; embedding rows change only if trainable. A frozen language model can reuse already learned role embeddings. Nothing is randomly reinitialized per prompt at inference.
Ask: Is USER a separate encoder or a fixed hand-written feature vector?
Answer: No. In a dedicated-token format its ID selects a learned row of the same text embedding table used for ordinary words. The whole language model learns how to use the role cue. Existing embeddings are loaded at inference; newly added tokens need initialized rows and appropriate training.
03 · How can vision enter a language model?
Finish the question; start the assistant’s answer
Role tokens have sequence positions and participate in the same causal attention.
How does visual information become context for next-token prediction?
Chat templates · Hugging Face · LLaMA · embedding lookup and RoPE71 / 178
This is a teaching chat format, not an exact LLaVA serialization. USER and ASST are readable stand-ins. Some models have dedicated single vocabulary tokens for roles; others spell roles using ordinary tokens and separators, so one role label need not equal one token. Image placement, delimiters and tokenization depend on the trained chat template. Keep the same template at training and inference. Positions are zero-based and derived here: twelve visual rows occupy 0–11, USER is 12, the illustrative four word-level question tokens occupy 13–16, and ASST is 17. Real tokenizers may split the question differently, so these exact indices are illustrative. The final supplied ASST state, after causal decoder processing, is sent through the LM head to predict the first answer token. If It is selected, its input embedding is placed at 18 next; it is not supplied in the first forward pass. All positions follow the model’s positional scheme. An additive scheme adds a position vector to input embeddings, while LLaMA uses RoPE rotations on queries and keys inside attention. Do not imply that RoPE is an extra learned token embedding or that it is added to the input. Role markers get no exemption from positions or causal masking. The image encoder has its own earlier position handling; decoder positions apply to the combined input.
Ask: Does a role marker get a position? Do positions restart when the speaker changes?
Answer: Each constituent role token occupies a normal sequence position. In this example USER is at 12 and ASST at 17; positions do not restart at the role boundary. All positions use the decoder’s positional mechanism, including RoPE when that is the architecture.
03 · How can vision enter a language model?
What may the current text position read?
The assistant’s state can use both the picture and the question.
How does visual information become context for next-token prediction?
Original teaching example / diagram72 / 178
Read one query row first. The current position may also attend to itself; the simplified row here emphasizes earlier context.
Ask: The assistant’s state can use both the picture and the question.
Answer: Read one query row first. The current position may also attend to itself; the simplified row here emphasizes earlier context.
03 · How can vision enter a language model?
The decoder mask is a model choice
Both keep text causal. The difference is which image rows can read each other.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Gemma 3 · image-block attention73 / 178
Compare the same illustrative input under two decoder masks. z1–z3 are projected image vectors from one image, T1–T3 are prompt positions, and A is the assistant-start position. Rows are queries; columns are keys. LEFT: the LLaVA/LLaMA baseline used in this lecture is lower triangular across image and text. z1 reads itself, z2 reads z1 and itself, and z3 reads all three image positions. Qwen2.5-VL also uses a causal decoder, corroborating that this is a common construction, not merely a teaching convention. RIGHT: Gemma 3 is a concrete alternative with bidirectional attention inside the image block. The three additional amber edges let z1 read z2 and z3, and z2 read z3. This diagram abstracts local attention windows, special image markers and multiple images; it is not a complete Gemma 3 layer mask. Text rows are identical in this simplified comparison: they read preceding image and text positions and themselves; neither construction allows future answer tokens to leak into earlier positions. Earlier full self-attention inside ViT has already mixed image information in both cases. That encoder context is not erased by a later causal decoder mask, but neither does it require a bidirectional decoder image block. All supplied image/prompt positions can be processed together in parallel within each layer during prefill; only new answer tokens are generated autoregressively afterwards. Avoid claiming a universal mask for all VLMs.
Ask: Both keep text causal. The difference is which image rows can read each other.
Answer: Compare the same illustrative input under two decoder masks. z1–z3 are projected image vectors from one image, T1–T3 are prompt positions, and A is the assistant-start position. Rows are queries; columns are keys. LEFT: the LLaVA/LLaMA baseline used in this lecture is lower triangular across image and text. z1 reads itself, z2 reads z1 and itself, and z3 reads all three image positions. Qwen2.5-VL also uses a causal decoder, corroborating that this is a common construction, not merely a teaching convention. RIGHT: Gemma 3 is a concrete alternative with bidirectional attention inside the image block. The three additional amber edges let z1 read z2 and z3, and z2 read z3. This diagram abstracts local attention windows, special image markers and multiple images; it is not a complete Gemma 3 layer mask. Text rows are identical in this simplified comparison: they read preceding image and text positions and themselves; neither construction allows future answer tokens to leak into earlier positions. Earlier full self-attention inside ViT has already mixed image information in both cases. That encoder context is not erased by a later causal decoder mask, but neither does it require a bidirectional decoder image block. All supplied image/prompt positions can be processed together in parallel within each layer during prefill; only new answer tokens are generated autoregressively afterwards. Avoid claiming a universal mask for all VLMs.
03 · How can vision enter a language model?
This is the basic LLaVA-style connection
Projected patch vectors occupy earlier positions; they do not become word IDs.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 202374 / 178
A simple row-wise linear or MLP projector keeps the patch-row count. The few boxes are a drawn subset, not token selection. LLaVA variants differ in details. Later compression methods deliberately reduce the visual sequence.
Ask: Projected patch vectors occupy earlier positions; they do not become word IDs.
Answer: A simple row-wise linear or MLP projector keeps the patch-row count. The few boxes are a drawn subset, not token selection. LLaVA variants differ in details. Later compression methods deliberately reduce the visual sequence.
PAPER · LLaVA · NeurIPS 2023
Visual Instruction Tuning
Haotian Liu · Chunyuan Li · Qingyang Wu · Yong Jae Lee
Read the paper ↗1 · Vision encoder
CLIP ViT-L/14 supplies image features Zᵥ.
2 · Projection W
The original paper uses a linear map to match the LM embedding width.
3 · Language model
Vicuna reads the visual vectors and text, then predicts the response.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 202375 / 178
Figure 1 is cropped from page 4 of arXiv 2304.08485v2; the architecture itself is unaltered. Read the diagram bottom to top. The paper calls unprojected features Zv and projected visual embeddings Hv; our lecture uses Hv and Z respectively, so map by role rather than letter. The original connector is linear; later variants can use an MLP. The few drawn tokens are schematic. The figure abstracts tokenization, positions and repeated decoder blocks. Visual instruction tuning also contributes a data/training recipe; this slide focuses on the architecture.
Ask: Point to the modules that implement the connection we just derived.
Answer: Vision encoder: CLIP ViT-L/14 supplies image features Zᵥ. Projection W: The original paper uses a linear map to match the LM embedding width. Language model: Vicuna reads the visual vectors and text, then predicts the response.
03 · How can vision enter a language model?
Build the exact image-and-question input
196 visual rows + 10 prompt embeddings = 206 decoder positions.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.076 / 178
The exact prompt is Question: What animal is shown? newline Answer:. All ten DistilGPT2 token pieces and IDs are displayed. The answer is initially empty. Retain all 196 patch rows, project 192 to 768, embed all ten IDs using the language embedding table, and concatenate to a 206 by 768 decoder input. Actual tokenizer IDs and model dimensions; no measured generated answer. This example belongs to Idea 1, the uncompressed visual-prefix route. Idea 2 separate memory and Idea 3 learned compression are not used here. Use the same processed Newfoundland image and exact prompt: Question: What animal is shown? newline Answer:. The initial answer is empty. Shapes and tokenizer IDs are verified against the pinned DeiT-Tiny and DistilGPT2 notebook components. The reply A black dog. is an authored teaching trace, not a saved model output; newly added notebook connectors remain untrained. For the head arithmetic only, explicitly switch to two hand-set features and four toy vocabulary entries; these are not a subset normalized from measured logits. DistilGPT2 has 50,257 vocabulary entries and width 768. Greedy decoding can take argmax directly on logits; softmax makes the normalized distribution explicit. The diagram shows the logical complete input sequence. At runtime KV caching reuses previous computations, as explained in the later inference section. Token labels with a middle dot show a leading space; EOS denotes DistilGPT2 endoftext ID 50256. Decoder inputs have their positional embeddings; the final hidden state is read after all blocks and final normalization. A full authored continuation would select IDs 317, 2042, 3290, 13 and 50256 for space-A, space-black, space-dog, period and EOS. Stop on EOS; the decoder never receives a future answer token. No labels, object names or probabilities are assigned to arbitrary image-feature coordinates.
Ask: Which connection are we using, which input position predicts next, and what changes at the following step?
Answer: Idea 1: all 196 projected patch rows are a prefix. The last supplied position predicts the next vocabulary token. Append its ID, look up its embedding, and repeat with the same image, question, decoder and head. Stop on EOS.
03 · How can vision enter a language model?
Read the final “:” state, then score the vocabulary
Each output column scores one vocabulary entry using the same final state.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.077 / 178
Actual interface: one 768-feature last hidden state is linearly read into 50,257 DistilGPT2 vocabulary logits. Independent toy arithmetic below deliberately uses two hand-set features and four entries. h=[1,2], W rows [1,1,0,-1] and [1,0,0,0], zero bias, give logits [3,1,0,-1] for space-A, space-The, space-dog and EOS. These numbers are not model activations or measured predictions. This example belongs to Idea 1, the uncompressed visual-prefix route. Idea 2 separate memory and Idea 3 learned compression are not used here. Use the same processed Newfoundland image and exact prompt: Question: What animal is shown? newline Answer:. The initial answer is empty. Shapes and tokenizer IDs are verified against the pinned DeiT-Tiny and DistilGPT2 notebook components. The reply A black dog. is an authored teaching trace, not a saved model output; newly added notebook connectors remain untrained. For the head arithmetic only, explicitly switch to two hand-set features and four toy vocabulary entries; these are not a subset normalized from measured logits. DistilGPT2 has 50,257 vocabulary entries and width 768. Greedy decoding can take argmax directly on logits; softmax makes the normalized distribution explicit. The diagram shows the logical complete input sequence. At runtime KV caching reuses previous computations, as explained in the later inference section. Token labels with a middle dot show a leading space; EOS denotes DistilGPT2 endoftext ID 50256. Decoder inputs have their positional embeddings; the final hidden state is read after all blocks and final normalization. A full authored continuation would select IDs 317, 2042, 3290, 13 and 50256 for space-A, space-black, space-dog, period and EOS. Stop on EOS; the decoder never receives a future answer token. No labels, object names or probabilities are assigned to arbitrary image-feature coordinates.
Ask: Which connection are we using, which input position predicts next, and what changes at the following step?
Answer: Idea 1: all 196 projected patch rows are a prefix. The last supplied position predicts the next vocabulary token. Append its ID, look up its embedding, and repeat with the same image, question, decoder and head. Stop on EOS.
03 · How can vision enter a language model?
Turn the scores into one next-token choice
The four-entry calculation is a toy; the real vocabulary has 50,257 entries.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.078 / 178
Four-entry toy softmax of [3,1,0,-1] has approximate probabilities [.8310,.1125,.0414,.0152]. Greedy selection chooses space-A. The real DistilGPT2 ID for space-A is 317; only this ID is factual tokenizer data, while the toy logits and probabilities are authored. Real decoding normalizes across all 50,257 entries. Greedy argmax is identical on logits and probabilities; sampling is another option. This example belongs to Idea 1, the uncompressed visual-prefix route. Idea 2 separate memory and Idea 3 learned compression are not used here. Use the same processed Newfoundland image and exact prompt: Question: What animal is shown? newline Answer:. The initial answer is empty. Shapes and tokenizer IDs are verified against the pinned DeiT-Tiny and DistilGPT2 notebook components. The reply A black dog. is an authored teaching trace, not a saved model output; newly added notebook connectors remain untrained. For the head arithmetic only, explicitly switch to two hand-set features and four toy vocabulary entries; these are not a subset normalized from measured logits. DistilGPT2 has 50,257 vocabulary entries and width 768. Greedy decoding can take argmax directly on logits; softmax makes the normalized distribution explicit. The diagram shows the logical complete input sequence. At runtime KV caching reuses previous computations, as explained in the later inference section. Token labels with a middle dot show a leading space; EOS denotes DistilGPT2 endoftext ID 50256. Decoder inputs have their positional embeddings; the final hidden state is read after all blocks and final normalization. A full authored continuation would select IDs 317, 2042, 3290, 13 and 50256 for space-A, space-black, space-dog, period and EOS. Stop on EOS; the decoder never receives a future answer token. No labels, object names or probabilities are assigned to arbitrary image-feature coordinates.
Ask: Which connection are we using, which input position predicts next, and what changes at the following step?
Answer: Idea 1: all 196 projected patch rows are a prefix. The last supplied position predicts the next vocabulary token. Append its ID, look up its embedding, and repeat with the same image, question, decoder and head. Stop on EOS.
03 · How can vision enter a language model?
Feed the selected token back as an embedding
Append E[317] for “ A”; the image and question stay fixed.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.079 / 178
Fixed prompt Question: What animal is shown? newline Answer:. The chosen illustrative space-A token has actual DistilGPT2 ID 317. Lookup E[317] and append this 768-wide embedding after 196 visual rows and ten prompt embeddings, increasing length from 206 to 207. Its new zero-based position is 206. Include the position embedding and use the same decoder and head for the next prediction. It does not replace the previous colon state. This example belongs to Idea 1, the uncompressed visual-prefix route. Idea 2 separate memory and Idea 3 learned compression are not used here. Use the same processed Newfoundland image and exact prompt: Question: What animal is shown? newline Answer:. The initial answer is empty. Shapes and tokenizer IDs are verified against the pinned DeiT-Tiny and DistilGPT2 notebook components. The reply A black dog. is an authored teaching trace, not a saved model output; newly added notebook connectors remain untrained. For the head arithmetic only, explicitly switch to two hand-set features and four toy vocabulary entries; these are not a subset normalized from measured logits. DistilGPT2 has 50,257 vocabulary entries and width 768. Greedy decoding can take argmax directly on logits; softmax makes the normalized distribution explicit. The diagram shows the logical complete input sequence. At runtime KV caching reuses previous computations, as explained in the later inference section. Token labels with a middle dot show a leading space; EOS denotes DistilGPT2 endoftext ID 50256. Decoder inputs have their positional embeddings; the final hidden state is read after all blocks and final normalization. A full authored continuation would select IDs 317, 2042, 3290, 13 and 50256 for space-A, space-black, space-dog, period and EOS. Stop on EOS; the decoder never receives a future answer token. No labels, object names or probabilities are assigned to arbitrary image-feature coordinates.
Ask: Which connection are we using, which input position predicts next, and what changes at the following step?
Answer: Idea 1: all 196 projected patch rows are a prefix. The last supplied position predicts the next vocabulary token. Append its ID, look up its embedding, and repeat with the same image, question, decoder and head. Stop on EOS.
03 · How can vision enter a language model?
Idea 1, end to end in one function
image
One image
question = “What animal is shown?”
answer_so_far = “It is a” (empty at the start)
def next_token(image, question, answer_so_far): patches = vit(image).patch_statesN × dV visual = projector(patches)N × dLM ids = tokenize(question, answer_so_far)T token IDs text = embed(ids)T × dLM inputs = concat([visual, text], axis="tokens")(N + T) × dLM hidden = causal_decoder(inputs)(N + T) × dLM scores = lm_head(hidden[-1])Vocabulary scores return argmax(scores)Next text token IDcausal_decoder stacks causal self-attention + MLP blocks over all input positions.
Display the returned token with the tokenizer; append its ID to the answer and predict again.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.080 / 178
High-level pseudocode for one next-token prediction, not executable library calls. One image is shown and the batch dimension is omitted. Image preprocessing is folded into vit; patch_states selects all N contextual patch rows and excludes CLS in this design. ViT uses full image attention. The shared row-wise projector changes dV to dLM while preserving N. tokenize(question, answer_so_far) is a conceptual helper for constructing and tokenizing the text context in that order, not the tokenizer API for paired sequences. In a real model, use its chat template and processor; keep generated answer IDs rather than repeatedly retokenizing them. T counts all supplied text positions, including already-generated answer tokens. The answer portion is empty at the first prediction. concat stacks visual rows before text rows along the token axis, not the feature axis. The decoder consumes embeddings directly, with positional handling and a causal mask from the first visual position. causal_decoder means the full repeated Transformer block stack, including MLPs, normalization and residuals; it is not only one attention operation. hidden[-1] is the last supplied position and predicts the next, as-yet-unknown answer token. The language head produces a score for every vocabulary entry. argmax shows greedy selection; softmax is unnecessary for choosing the largest score. The result is a text token ID, not a visual token. Decode it with the tokenizer to display text. This deliberately unoptimized function summarizes the dependency graph. During actual generation, encode the fixed image once and reuse the decoder KV cache rather than recomputing the whole function on every token. Question and answer text are illustrative; no measured answer or embedding is claimed.
Ask: Which line combines image and text, and which state predicts the next token?
Answer: concat joins N projected visual rows and T text embeddings along the token axis. The causal decoder processes their combined sequence; the language head reads hidden[-1], the last supplied position, to score the next text token.
Section 04
Could vision remain separate?
Return to Idea 2: how can language read separate visual memory?
How does visual information become context for next-token prediction?
Original teaching example / diagram81 / 178
Return to Idea 2: how can language read separate visual memory?
Ask:
Answer: Return to Idea 2: how can language read separate visual memory?
04 · Could vision remain separate?
Idea 2 in detail · read a separate visual memory
Causal self-attention reads text; cross-attention reads image memory.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 201782 / 178
Trace the two inputs separately. The purple path embeds the question and tokens generated so far; the answer portion is empty initially. The vision encoder exposes h1, h2, …, hN, a sequence of feature rows. B × N × dV means batch size × retained visual rows per example × features per row; the drawing shows one image. Text states supply Q, image states are projected to K and V. The attention result updates the language states before the vocabulary head. N varies with image resolution, patch size, CLS handling and any compression; 197 is only a conditional example. This schematic shows the standard sequence-to-sequence mechanism, not Flamingo’s exact layer ordering or gates.
Ask: Causal self-attention reads text; cross-attention reads image memory.
Answer: Trace the two inputs separately. The purple path embeds the question and tokens generated so far; the answer portion is empty initially. The vision encoder exposes h1, h2, …, hN, a sequence of feature rows. B × N × dV means batch size × retained visual rows per example × features per row; the drawing shows one image. Text states supply Q, image states are projected to K and V. The attention result updates the language states before the vocabulary head. N varies with image resolution, patch size, CLS handling and any compression; 197 is only a conditional example. This schematic shows the standard sequence-to-sequence mechanism, not Flamingo’s exact layer ordering or gates.
04 · Could vision remain separate?
We already did this with English-to-Hindi translation
English source states stayed available while the Hindi prefix grew.
How does visual information become context for next-token prediction?
Original teaching example / diagram83 / 178
Use the complete source-left, decoder-right architecture from the final diagrams of the earlier lecture. The current target state first uses causal target self-attention and then reads source states. Replace only the source modality on the next slide.
Ask: English source states stayed available while the Hindi prefix grew.
Answer: Use the complete source-left, decoder-right architecture from the final diagrams of the earlier lecture. The current target state first uses causal target self-attention and then reads source states. Replace only the source modality on the next slide.
04 · Could vision remain separate?
Keep the decoder idea; change English to an image
The source changes. The decoder still reads a separate memory.
How does visual information become context for next-token prediction?
Original teaching example / diagram84 / 178
The text sequence remains separate from visual memory. We have not yet computed a visual message.
Ask: The source changes. The decoder still reads a separate memory.
Answer: The text sequence remains separate from visual memory. We have not yet computed a visual message.
04 · Could vision remain separate?
Same image, two questions: what should we read?
Different questions need different visual evidence from the same image.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201785 / 178
Use the same Newfoundland photograph already familiar from the lecture. Ask students to complete It is a with dog, then Behind it are with trees. Both are authored reference continuations supported by the image, not recorded predictions. The image alone does not specify which answer to give. The language query comes from the current decoder state, which reflects the question and answer prefix. At a fixed cross-attention layer, an unchanged image memory and fixed projection weights give unchanged K and V. A different text context gives a different query and can change its readout. Later-layer language states can also reflect earlier visual reads. No attention heatmap or human-interpretable coordinate is being claimed.
Ask: Why can the same photograph support two different next words?
Answer: The questions and answer prefixes differ. They produce different language states and queries, while the same image memory supplies the same keys and values at this layer. The decoder uses the resulting visual message to continue the requested answer.
04 · Could vision remain separate?
The text supplies Q; the image supplies K and V
Each image row supplies a key and value; the contextual state at “a” supplies q.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201786 / 178
Trace the actual photo first, then the concrete question and answer prefix. The 12 rows come from the same 3 × 4 image grid; all twelve h, k and v rows are drawn. A row is a vector, not a named object. ViT contextualization lets every row include information from other patches. W_K and W_V are distinct learned projections of the same image features. K is compared against q; V supplies the content to mix. W_Q maps the contextual language state at the last supplied token a, after causal self-attention, to one query. The state includes preceding question and answer-prefix context; it is not the raw embedding of a. The tokenization, positional treatment and normalization use the decoder’s usual rules; the overview abstracts their internal details. We show one current position and one attention head. The complete decoder can compute queries for every text position. All vectors here are symbolic, not measured from the image. The next slide uses this exact query and these paired rows.
Ask: Does q come directly from the image? Does each key have a paired value?
Answer: q is computed from the contextual state at a, the last supplied token in It is a. Causal self-attention lets that state use the question and earlier answer tokens. The image encoder supplies the rows used for K and V. Row i gives both kᵢ and vᵢ, through different learned projections.
04 · Could vision remain separate?
Use the keys to weight the values, then continue the answer
Update the state at “a”; the language head predicts the next token after it.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201787 / 178
Carry What animal is shown? and It is a through one lookup. The highlighted a is the final supplied token. Select its hidden state after causal self-attention and apply W_Q to obtain q. This is a contextual state with access to the question, It is and a itself, not an isolated word embedding or a pooled state over the text. The image lookup updates that same position. The final state there predicts the next token after a, such as the reference continuation dog; it does not predict a again. A full decoder pass can form queries at every text position, but this next-token example follows only the last position. Normalization and other decoder details are abstracted. Compute a scaled dot product with each of the twelve keys; softmax across those scores gives twelve weights summing to one. Weight alpha_i belongs to value v_i from the same row. Add all twelve weighted value vectors to obtain c. The decoder uses the projected attention output in its residual update, continues its remaining layers, and applies the vocabulary head to the current text state. With multiple heads, their outputs are concatenated and projected first. Dog is an authored reference next word, not a literal word stored in v_i and not a measured generation. The diagram intentionally does not invent numeric weights or a heatmap. For the background question, the same image K,V can be reused but the different incoming text state supplies a different query. We now unpack W_Q, W_K, W_V and the exact arithmetic in the following slides; the following numeric walkthrough keeps all twelve rows and labels its assumed feature values and weights explicitly.
Ask: Which part decides the mixing weights, and where does the word dog appear?
Answer: Comparing q with K determines the scores; softmax gives the weights used to mix V. The result c is a vector. The language head later reads the updated final state at a to score the next token. Dog is the reference continuation after It is a for this illustrated question.
04 · Could vision remain separate?
The state at “a” supplies the query
Use the final supplied text state, after causal self-attention, to make q.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201788 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The question and answer prefix are tokenized and embedded with the decoder’s position handling. The highlighted a is the last available token, not the next token to generate. Its assumed state h_t=[1,2] is not a raw embedding; multiply by W_Q=[[0,1],[0.5,-0.5]] to obtain [1,0]. These are cross-attention query weights, separate from self-attention weights. In a full pass there are queries for every text position; we inspect the final one.
Ask: Use the final supplied text state, after causal self-attention, to make q.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The question and answer prefix are tokenized and embedded with the decoder’s position handling. The highlighted a is the last available token, not the next token to generate. Its assumed state h_t=[1,2] is not a raw embedding; multiply by W_Q=[[0,1],[0.5,-0.5]] to obtain [1,0]. These are cross-attention query weights, separate from self-attention weights. In a full pass there are queries for every text position; we inspect the final one.
04 · Could vision remain separate?
The same twelve image rows become twelve keys
Apply W_K to every encoder row; inspect patch 6 without dropping the other rows.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201789 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Here H_V is 12 by 2, W_K is 2 by 2, and K is 12 by 2. W_K swaps two coordinates solely to make the classroom multiplication visible. The row-6 feature [0,3] becomes key [3,0]. In real models the vision and key widths need not be equal.
Ask: Apply W_K to every encoder row; inspect patch 6 without dropping the other rows.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Here H_V is 12 by 2, W_K is 2 by 2, and K is 12 by 2. W_K swaps two coordinates solely to make the classroom multiplication visible. The row-6 feature [0,3] becomes key [3,0]. In real models the vision and key widths need not be equal.
04 · Could vision remain separate?
Each image row also supplies a paired value
The key determines the match; its paired value supplies the features to mix.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201790 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The same H_V is multiplied by W_V=[[1,0],[1,2]]. Row 6 [0,3] becomes value [3,6], while its key was [3,0]. K and V remain in matching image-position order.
Ask: The key determines the match; its paired value supplies the features to mix.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The same H_V is multiplied by W_V=[[1,0],[1,2]]. Row 6 [0,3] becomes value [3,6], while its key was [3,0]. K and V remain in matching image-position order.
04 · Could vision remain separate?
Score every image row for this text position
One query × twelve keys gives twelve scores; every patch stays in the computation.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201791 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Use q=[1,0] and all twelve key rows from the preceding slide. Patch 6 dot product is 3. Divide by sqrt(d_k)=sqrt(2), not sqrt(12). Each numbered image patch carries the exact same three-decimal score and color as its table cell. The overlay, borders, numeric badges and table share one linear sequential scale from 0.000 (light) to 2.121 (dark). Patches 6 and 7 tie at 2.121; patches 1, 4, 9 and 12 score zero. Reveal the overlay together with the scaled-score column. Scores are similarities before softmax, not probabilities; zero-score patches still receive positive softmax weight on the next slide. The map is calculated from authored toy features, not measured from the photo. Patch positions identify the source rows, whose encoder features can already contain whole-image context.
Ask: One query × twelve keys gives twelve scores; every patch stays in the computation.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Use q=[1,0] and all twelve key rows from the preceding slide. Patch 6 dot product is 3. Divide by sqrt(d_k)=sqrt(2), not sqrt(12). Each numbered image patch carries the exact same three-decimal score and color as its table cell. The overlay, borders, numeric badges and table share one linear sequential scale from 0.000 (light) to 2.121 (dark). Patches 6 and 7 tie at 2.121; patches 1, 4, 9 and 12 score zero. Reveal the overlay together with the scaled-score column. Scores are similarities before softmax, not probabilities; zero-score patches still receive positive softmax weight on the next slide. The map is calculated from authored toy features, not measured from the photo. Patch positions identify the source rows, whose encoder features can already contain whole-image context.
04 · Could vision remain separate?
Normalize across all twelve image positions
Divide each exponential by the sum of all twelve exponentials.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201792 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Each alpha is nonnegative and the exact row sums to one. Three-decimal displayed entries can sum slightly away from one due to rounding. The denominator includes all image positions, not a selected subset. These are value-mixing weights, not answer-word probabilities.
Ask: Divide each exponential by the sum of all twelve exponentials.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Each alpha is nonnegative and the exact row sums to one. Three-decimal displayed entries can sum slightly away from one due to rounding. The denominator includes all image positions, not a selected subset. These are value-mixing weights, not answer-word probabilities.
04 · Could vision remain separate?
Weight the paired values and add the twelve rows
All twelve contributions add up to one visual message for the current text position.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201793 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Multiply each value row by the weight for that same position. Do not mix keys. The displayed values, contributions and final context use one shared numeric fixture and full-precision computation before rounding. On this slide, all weights and vector coordinates display exactly three decimal places, including 0.000 and trailing zeros, with monospaced tabular digits. This keeps the first and second coordinates aligned across every row. Displayed rounded weights are not substituted back into the calculation.
Ask: All twelve contributions add up to one visual message for the current text position.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Multiply each value row by the weight for that same position. Do not mix keys. The displayed values, contributions and final context use one shared numeric fixture and full-precision computation before rounding. On this slide, all weights and vector coordinates display exactly three decimal places, including 0.000 and trailing zeros, with monospaced tabular digits. This keeps the first and second coordinates aligned across every row. Displayed rounded weights are not substituted back into the calculation.
04 · Could vision remain separate?
Change the question; read the state at “are”
The image, keys, values and W_Q stay fixed; the text state changes.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201794 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Now the prompt is What is behind the dog? and the supplied answer prefix is Behind it are. For the state at are, assume h_t=[3,0]. The same W_Q gives q=[0,3]. This new h_t is a teaching assumption, not computed by a real language model. Both example queries belong to the same layer and head.
Ask: The image, keys, values and W_Q stay fixed; the text state changes.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Now the prompt is What is behind the dog? and the supplied answer prefix is Behind it are. For the state at are, assume h_t=[3,0]. The same W_Q gives q=[0,3]. This new h_t is a teaching assumption, not computed by a real language model. Both example queries belong to the same layer and head.
04 · Could vision remain separate?
Same patch 6, two different query scores
A fixed image key can match different language queries differently.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201795 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Patch 6 has h6=[0,3] and k6=[3,0]. The animal query [1,0] has dot product 3; the background query [0,3] has dot product 0. This slide inspects one row; all twelve rows are used in each actual lookup.
Ask: A fixed image key can match different language queries differently.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Patch 6 has h6=[0,3] and k6=[3,0]. The animal query [1,0] has dot product 3; the background query [0,3] has dot product 0. This slide inspects one row; all twelve rows are used in each actual lookup.
04 · Could vision remain separate?
Now inspect patch 1 with those same queries
The query changes which keys receive large scores.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201796 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Patch 1 has h1=[3,0] and k1=[0,3]. Its dot product is 0 for the animal query and 9 for the background query. The toy features are deliberately chosen to make the comparison legible, not evidence of semantic coordinates learned by a model.
Ask: The query changes which keys receive large scores.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Patch 1 has h1=[3,0] and k1=[0,3]. Its dot product is 0 for the animal query and 9 for the background query. The toy features are deliberately chosen to make the comparison legible, not evidence of semantic coordinates learned by a model.
04 · Could vision remain separate?
Recompute the whole score row, then softmax
Each query gets its own twelve weights; the image memory is reused.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201797 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Compare every row of the two score and weight columns. Each query has its own softmax denominator. A high score is relative to other scores for that query, not a standalone probability. No rows disappear.
Ask: Each query gets its own twelve weights; the image memory is reused.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Compare every row of the two score and weight columns. Each query has its own softmax denominator. A high score is relative to other scores for that query, not a standalone probability. No rows disappear.
04 · Could vision remain separate?
Put the calculated weights back on the patch grid
Same image and keys; different queries give different mixtures of image values.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201798 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The numbers on each image are exactly the softmax weights from the previous slide, rounded to three decimals. They are a calculated toy illustration, not a measured attention map. A patch index locates the originating token; a contextual ViT row may carry information from the entire image. A high weight alone does not prove grounding or a faithful explanation.
Ask: Same image and keys; different queries give different mixtures of image values.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. The numbers on each image are exactly the softmax weights from the previous slide, rounded to three decimals. They are a calculated toy illustration, not a measured attention map. A patch index locates the originating token; a contextual ViT row may carry information from the entire image. A high weight alone does not prove grounding or a faithful explanation.
04 · Could vision remain separate?
Two questions, two messages from the same values
Changing q can change the visual message without recomputing K or V.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201799 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Sum all twelve weighted values separately for each query. The first and second contexts differ, but neither directly denotes dog or trees. The two words are reference continuations motivating the example, not measured model outputs.
Ask: Changing q can change the visual message without recomputing K or V.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. Sum all twelve weighted values separately for each query. The first and second contexts differ, but neither directly denotes dog or trees. The two words are reference continuations motivating the example, not measured model outputs.
04 · Could vision remain separate?
Project the visual message and update the text state
The visual message changes the state at “a”; a later vocabulary head scores words.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017100 / 178
All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. One-head illustrative residual update h_t prime = h_t + c W_O, with W_O=[[1,0],[0.5,1]]. In a multi-head layer, concatenate all head outputs before W_O. We omit normalization and model-specific gates. This toy happens to use width two for all stages; real vision, head and decoder widths can differ. The vocabulary prediction is not calculated by these attention numbers alone.
Ask: The visual message changes the state at “a”; a later vocabulary head scores words.
Answer: All feature states, tiny dimensions and projection weights are hand-set teaching values, not extracted from the photograph or a model. This is one head and one current language position. All twelve image rows are included. Word labels are readable shorthand for tokenizer pieces; role delimiters are omitted. Encoder rows are contextual, so their information is not restricted to the pictured patch. One-head illustrative residual update h_t prime = h_t + c W_O, with W_O=[[1,0],[0.5,1]]. In a multi-head layer, concatenate all head outputs before W_O. We omit normalization and model-specific gates. This toy happens to use width two for all stages; real vision, head and decoder widths can differ. The vocabulary prediction is not calculated by these attention numbers alone.
04 · Could vision remain separate?
Check: has cross-attention already answered “dog”?
Lookup result
What happens next?
Does c name a word?
Or does it update the decoder’s current state?
Predict before advancing: where does a vocabulary token actually appear?
How does visual information become context for next-token prediction?
Original teaching example / diagram101 / 178
The numerical vector is not a word ID. Ask students to point to the vocabulary head in the whole architecture.
Ask: Does the cross-attention output directly name the answer token?
Answer: No. It updates a language hidden state. The vocabulary head later scores output token IDs.
04 · Could vision remain separate?
The vocabulary head still produces the next-token scores
Visual lookup changes the language state; the language head chooses words.
How does visual information become context for next-token prediction?
Original teaching example / diagram102 / 178
Trace memory → cross-attention → updated decoder computation → vocabulary head. Cross-attention returns features, not an English answer. Model-specific blocks can repeat this lookup in depth.
Ask: Visual lookup changes the language state; the language head chooses words.
Answer: Trace memory → cross-attention → updated decoder computation → vocabulary head. Cross-attention returns features, not an English answer. Model-specific blocks can repeat this lookup in depth.
04 · Could vision remain separate?
Two ways for language to access vision
In-sequence visual context or a separate visual memory.
How does visual information become context for next-token prediction?
Original teaching example / diagram103 / 178
Same image and prompt. Neither access pattern is universally better; training, model size, compute and task matter.
Ask: In-sequence visual context or a separate visual memory.
Answer: Same image and prompt. Neither access pattern is universally better; training, model size, compute and task matter.
04 · Could vision remain separate?
Idea 2, end to end in one function
image
One image
question = “What animal is shown?”
answer_so_far = “It is a” (empty at the start)
def next_token(image, question, answer_so_far): memory = vision_encoder(image).featuresN × dV ids = tokenize(question, answer_so_far)T token IDs text = embed(ids)T × dLM for block in decoder_blocks: text = block.causal_self_attn(text)T × dLM text = block.cross_attn(text, memory)T × dLM text = block.mlp(text)T × dLM return argmax(lm_head(text[-1]))Next text token IDcross_attn: Q from text; K and V from image memory. The two sequences stay separate.
Sublayer helpers include residuals and norms. Append the returned token ID to the answer; repeat.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 2017 · Oxford-IIIT Pet · CC BY-SA 4.0104 / 178
A conceptual encoder-decoder computation for one image and one next-token prediction, batch omitted. vision_encoder includes image preprocessing and produces all N feature rows. For the ViT teaching example these are contextual patch states, with full image attention. The tokenizer helper formats question and answer prefix, as on the Idea 1 slide; T includes all supplied text positions. Each causal_self_attn helper returns updated text states using causal self-attention, residual addition and normalization; cross_attn and mlp also include their residual and normalization steps. Positional handling and the final stack normalization are abstracted. The cross-attention helper has separate learned projections: Q comes from text and K/V from image memory. Per-head Q and K widths must match, but dV and dLM need not match; the internal projections and output projection handle this. No visual/text concatenation occurs. The decoder text stream keeps T rows, and the final text position feeds the vocabulary head. Image memory is constant within this prediction. This is the familiar standard sequence-to-sequence ordering, not an exact implementation of Flamingo. Flamingo adds gated visual cross-attention at selected points among pretrained language blocks and uses a resampled visual memory. The later Flamingo paper slide maps those differences explicitly. For efficient generation, encode the image once and cache reusable attention keys and values. argmax is greedy decoding; display via the tokenizer and append the ID, stopping at EOS or the generation limit. All APIs and the answer prefix are illustrative.
Ask: Where do Q, K and V come from, and how many text states leave each block?
Answer: Cross-attention gets Q from text states and K/V from image memory. It updates T text states; the N image rows remain separate. The last text state supplies the next-token scores.
Section 05
Do we need every visual token?
Every image adds decoder positions. What do they cost, and can a shorter visual summary help?
How does visual information become context for next-token prediction?
Original teaching example / diagram105 / 178
Every image adds decoder positions. What do they cost, and can a shorter visual summary help?
Ask:
Answer: Every image adds decoder positions. What do they cost, and can a shorter visual summary help?
05 · Do we need every visual token?
How long is this image + question + answer prefix?
Projection changes each vector: 192 → 768 dimensions. We still have 196 vectors.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020106 / 178
Switch from the preceding twelve-row toy arithmetic to the actual minimal notebook configuration. One dog image is resized and center-cropped by the pinned DeiT-Tiny processor to 224 by 224. Patch size 16 gives 14 by 14 = 196 patches. The ViT outputs 197 rows; we discard CLS and retain all 196 patch rows of width 192. Each of these 196 patch vectors contains 192 numbers: it is a 192-dimensional vector, not 192 tokens. The same row-wise projector maps each vector to a 768-dimensional vector, matching the size of a DistilGPT2 text embedding. The feature matrix therefore changes from 196 by 192 to 196 by 768; the number of image positions stays 196. The complete supplied string is Question: What animal is shown? followed by a newline and Answer: It is a. With the pinned DistilGPT2 tokenizer it has exactly 13 tokens, including punctuation and the newline. The displayed leading-space symbol is a readable rendering of each decoded token piece, not an added token. There is no hidden system message or chat template in this notebook. These 13 text embeddings plus 196 projected image rows give 209 decoder positions before predicting the next token. Counts change with preprocessing, tokenizer, formatting and generated answer length. The model revisions and token IDs are recorded in src/token-cost-example.json.
Ask: Projection changes each vector: 192 → 768 dimensions. We still have 196 vectors.
Answer: Switch from the preceding twelve-row toy arithmetic to the actual minimal notebook configuration. One dog image is resized and center-cropped by the pinned DeiT-Tiny processor to 224 by 224. Patch size 16 gives 14 by 14 = 196 patches. The ViT outputs 197 rows; we discard CLS and retain all 196 patch rows of width 192. Each of these 196 patch vectors contains 192 numbers: it is a 192-dimensional vector, not 192 tokens. The same row-wise projector maps each vector to a 768-dimensional vector, matching the size of a DistilGPT2 text embedding. The feature matrix therefore changes from 196 by 192 to 196 by 768; the number of image positions stays 196. The complete supplied string is Question: What animal is shown? followed by a newline and Answer: It is a. With the pinned DistilGPT2 tokenizer it has exactly 13 tokens, including punctuation and the newline. The displayed leading-space symbol is a readable rendering of each decoded token piece, not an added token. There is no hidden system message or chat template in this notebook. These 13 text embeddings plus 196 projected image rows give 209 decoder positions before predicting the next token. Counts change with preprocessing, tokenizer, formatting and generated answer length. The model revisions and token IDs are recorded in src/token-cost-example.json.
05 · Do we need every visual token?
209 positions fit. What do they cost?
Every image position adds decoder work, cache storage and later attention reads.
How does visual information become context for next-token prediction?
Key/value caching · Hugging Face107 / 178
Continue Idea 1, the all-patch visual prefix. There is nothing intrinsically wrong with 196 patch vectors or 209 total positions; this small example fits the notebook language model. The cost is that these positions participate in every decoder layer. During prefill, the layers process all input states before the first answer token is selected. Dense causal attention has a number of allowed query-key pairs proportional to the square of the input length, while the per-position MLP and key/value cache scale with length at fixed model dimensions. Do not imply that a full square score matrix must be materialized by an efficient attention kernel. During cached decoding, old K/V are reused, but each new answer token still reads the available image and text keys and values, including its own text position. Only the image portion of K/V is drawn. Layer L means the final layer; middle layers are omitted. This slide introduces the cost in plain language; the later inference section derives cache reuse in detail. No timings or hardware-memory figures are claimed.
Ask: Every image position adds decoder work, cache storage and later attention reads.
Answer: Continue Idea 1, the all-patch visual prefix. There is nothing intrinsically wrong with 196 patch vectors or 209 total positions; this small example fits the notebook language model. The cost is that these positions participate in every decoder layer. During prefill, the layers process all input states before the first answer token is selected. Dense causal attention has a number of allowed query-key pairs proportional to the square of the input length, while the per-position MLP and key/value cache scale with length at fixed model dimensions. Do not imply that a full square score matrix must be materialized by an efficient attention kernel. During cached decoding, old K/V are reused, but each new answer token still reads the available image and text keys and values, including its own text position. Only the image portion of K/V is drawn. Layer L means the final layer; middle layers are omitted. This slide introduces the cost in plain language; the later inference section derives cache reuse in detail. No timings or hardware-memory figures are claimed.
05 · Do we need every visual token?
Keep the text; shorten the visual prefix
Summarize 196 image vectors into 8: fewer decoder positions, with evidence we must preserve.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020108 / 178
Reuse exactly the same image and complete supplied text. Eight is the notebook’s chosen number of learned query slots, not a property inferred from the image. Attention mixes all 196 image rows into eight image-dependent summaries; it does not merely select eight patches. Project those eight rows to width 768 and prepend them before the same 13 text embeddings. Both length bars use the same scale. The language decoder now receives 21 positions instead of 209: 188 fewer positions in every layer. It processes fewer prefix states and stores and reads fewer visual keys and values. This addresses the cost just motivated, but the summary must retain the evidence the answer needs. All image patches are still encoded, and the summarizer itself adds computation. No measured speedup or caption quality is asserted. Other designs can use different summary lengths or send summaries to separate cross-attention memory.
Ask: Summarize 196 image vectors into 8: fewer decoder positions, with evidence we must preserve.
Answer: Reuse exactly the same image and complete supplied text. Eight is the notebook’s chosen number of learned query slots, not a property inferred from the image. Attention mixes all 196 image rows into eight image-dependent summaries; it does not merely select eight patches. Project those eight rows to width 768 and prepend them before the same 13 text embeddings. Both length bars use the same scale. The language decoder now receives 21 positions instead of 209: 188 fewer positions in every layer. It processes fewer prefix states and stores and reads fewer visual keys and values. This addresses the cost just motivated, but the summary must retain the evidence the answer needs. All image patches are still encoded, and the summarizer itself adds computation. No measured speedup or caption quality is asserted. Other designs can use different summary lengths or send summaries to separate cross-attention memory.
05 · Do we need every visual token?
Idea 3 in detail · make the visual context shorter
Replace the row-wise projector with a learned summary followed by projection.
How does visual information become context for next-token prediction?
Original teaching example / diagram109 / 178
Compare with the first complete prefix architecture. Only the left-hand connector changes. The decoder still consumes visual vectors followed by text. The same compression idea can instead provide the separate memory used by cross-attention.
Ask: Replace the row-wise projector with a learned summary followed by projection.
Answer: Compare with the first complete prefix architecture. Only the left-hand connector changes. The decoder still consumes visual vectors followed by text. The same compression idea can instead provide the separate memory used by cross-attention.
05 · Do we need every visual token?
Build the summary from all 196 image rows
The source memory is the encoded image: one feature vector per patch position.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020110 / 178
Continue the actual notebook dimensions: 196 patch rows, 192 features each. Every input row is drawn. The 14 by 14 feature grid arranges complete vectors by patch position; the feature matrix is 196 by 192. Full attention has contextualized every row. For an invoice photograph, the source is likewise image features; the memory rows are not separate retrieved documents.
Ask: The source memory is the encoded image: one feature vector per patch position.
Answer: Continue the actual notebook dimensions: 196 patch rows, 192 features each. Every input row is drawn. The 14 by 14 feature grid arranges complete vectors by patch position; the feature matrix is 196 by 192. Full attention has contextualized every row. For an invoice photograph, the source is likewise image features; the memory rows are not separate retrieved documents.
05 · Do we need every visual token?
What is a summary token?
A stored query slot asks for information; a summary vector contains the image-dependent result.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022111 / 178
Distinguish starting slots S from computed outputs Z before any algebra. S is a bank of eight trainable parameter vectors, each 192-dimensional. The attention reader uses S with the current image features H to produce Z, eight continuous output vectors of width 192. A summary token means one row of Z. It has no vocabulary ID, is not an English sentence and has no manually assigned object or region label. The same starting S is reused across images; Z is computed afresh. The notation describes the minimal notebook reader, not the full Q-Former architecture.
Ask: A stored query slot asks for information; a summary vector contains the image-dependent result.
Answer: Distinguish starting slots S from computed outputs Z before any algebra. S is a bank of eight trainable parameter vectors, each 192-dimensional. The attention reader uses S with the current image features H to produce Z, eight continuous output vectors of width 192. A summary token means one row of Z. It has no vocabulary ID, is not an English sentence and has no manually assigned object or region label. The same starting S is reused across images; Z is computed afresh. The notation describes the minimal notebook reader, not the full Q-Former architecture.
05 · Do we need every visual token?
Initialize eight query slots once
Choose the count and width; start with small random numbers, then learn them.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · BLIP-2 · learned-query initialization112 / 178
The exact notebook parameter is nn.Parameter(0.02 * torch.randn(1,8,192)). Independent random coordinates have mean zero and standard deviation 0.02. Eight is the chosen summary count, not an inferred number of objects. Width 192 matches this reader and DeiT-Tiny configuration; other systems choose other widths. The singleton batch axis allows the same parameter bank to be broadcast to each example. There are 1536 scalar parameters in S alone, with additional parameters in attention projections and the language projector. Parameter registration makes numbers eligible for optimizer updates; it does not train them automatically. Initialize only on constructing a new model. Training updates and checkpoints store this bank; a pretrained checkpoint loads it. The notebook currently creates an untrained reader. Do not redraw S for each image or label the slots as dog/background.
Ask: Choose the count and width; start with small random numbers, then learn them.
Answer: The exact notebook parameter is nn.Parameter(0.02 * torch.randn(1,8,192)). Independent random coordinates have mean zero and standard deviation 0.02. Eight is the chosen summary count, not an inferred number of objects. Width 192 matches this reader and DeiT-Tiny configuration; other systems choose other widths. The singleton batch axis allows the same parameter bank to be broadcast to each example. There are 1536 scalar parameters in S alone, with additional parameters in attention projections and the language projector. Parameter registration makes numbers eligible for optimizer updates; it does not train them automatically. Initialize only on constructing a new model. Training updates and checkpoints store this bank; a pretrained checkpoint loads it. The notebook currently creates an untrained reader. Do not redraw S for each image or label the slots as dog/background.
05 · Do we need every visual token?
Where do the reader’s Q, K and V come from?
Slots supply queries; the current image supplies all keys and values.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch113 / 178
Use the actual notebook reader: three heads share outer width 192, giving 64 query/key/value coordinates per head. Each head has its own learned projections. S has eight rows of width 192. Its projection gives eight queries of width 64 in this head. H has 196 rows of width 192; separate projections give paired K and V, each 196 by 64. Select q1 for the next two slides. Every reader query can access all 196 image positions: this reader has no causal patch mask. The text question is added after summarization in the minimal example; text-conditioned Q-Former variants are beyond this sketch. Bias terms are omitted only in diagram notation.
Ask: Slots supply queries; the current image supplies all keys and values.
Answer: Use the actual notebook reader: three heads share outer width 192, giving 64 query/key/value coordinates per head. Each head has its own learned projections. S has eight rows of width 192. Its projection gives eight queries of width 64 in this head. H has 196 rows of width 192; separate projections give paired K and V, each 196 by 64. Select q1 for the next two slides. Every reader query can access all 196 image positions: this reader has no causal patch mask. The text question is added after summarization in the minimal example; text-conditioned Q-Former variants are beyond this sketch. Bias terms are omitted only in diagram notation.
05 · Do we need every visual token?
A soft lookup compares one query with every image key
Compute 196 scores → softmax → 196 weights that sum to one.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch114 / 178
For the first slot in one head, q1 is 1 by 64 and K is 196 by 64. q1 K transpose divided by sqrt(64) yields 196 scalar scores. Softmax runs across image positions, producing alpha_1i. The first subscript is the slot and the second is the patch position. Middle positions are abbreviated in the drawing but all 196 participate. A soft lookup does not select just one row, retrieve a caption or consult the text embedding table. Larger scores receive larger weights. Each head and query produces its own distribution. No numeric attention map is measured or invented here.
Ask: Compute 196 scores → softmax → 196 weights that sum to one.
Answer: For the first slot in one head, q1 is 1 by 64 and K is 196 by 64. q1 K transpose divided by sqrt(64) yields 196 scalar scores. Softmax runs across image positions, producing alpha_1i. The first subscript is the slot and the second is the patch position. Middle positions are abbreviated in the drawing but all 196 participate. A soft lookup does not select just one row, retrieve a caption or consult the text embedding table. Larger scores receive larger weights. Each head and query produces its own distribution. No numeric attention map is measured or invented here.
05 · Do we need every visual token?
Use the weights to mix image values
One slot produces one summary vector, after combining the three attention heads.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch115 / 178
Multiply each 64-dimensional value vector by the scalar weight paired with its image position and sum all 196 vectors coordinatewise. This creates one 64-dimensional mixture in the highlighted head. Repeat the lookup and mixture with the other two heads, whose projections and weights differ. Concatenate the three mixtures for this same slot to recover 192 coordinates, then apply the reader output projection W_O. The result is z1. All eight slots run the same process in parallel using shared head projection weights and image K,V, producing Z of shape eight by 192. The subsequent language projector is a different layer. No slot is prescribed to represent a particular object, and multiple summaries may contain overlapping information.
Ask: One slot produces one summary vector, after combining the three attention heads.
Answer: Multiply each 64-dimensional value vector by the scalar weight paired with its image position and sum all 196 vectors coordinatewise. This creates one 64-dimensional mixture in the highlighted head. Repeat the lookup and mixture with the other two heads, whose projections and weights differ. Concatenate the three mixtures for this same slot to recover 192 coordinates, then apply the reader output projection W_O. The result is z1. All eight slots run the same process in parallel using shared head projection weights and image K,V, producing Z of shape eight by 192. The subsequent language projector is a different layer. No slot is prescribed to represent a particular object, and multiple summaries may contain overlapping information.
05 · Do we need every visual token?
Try two numeric readers on the familiar image
For this small calculation, choose two readers; give both all twelve memory rows.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017116 / 178
Return explicitly to the earlier twelve-patch, two-feature toy example. This is not the notebook configuration. Assume projected reader queries q1=[1,0] and q2=[0,3], and reuse all twelve earlier key and value rows. These queries have the same numerical values as the earlier language queries, so the arithmetic is familiar; here they are fixed reader queries rather than being computed from the question. Values are authored, not extracted from this photograph or learned by the notebook. There are no predetermined meanings attached to slot 1 or slot 2. The two readers are chosen only to keep the worked calculation legible.
Ask: For this small calculation, choose two readers; give both all twelve memory rows.
Answer: Return explicitly to the earlier twelve-patch, two-feature toy example. This is not the notebook configuration. Assume projected reader queries q1=[1,0] and q2=[0,3], and reuse all twelve earlier key and value rows. These queries have the same numerical values as the earlier language queries, so the arithmetic is familiar; here they are fixed reader queries rather than being computed from the question. Values are authored, not extracted from this photograph or learned by the notebook. There are no predetermined meanings attached to slot 1 or slot 2. The two readers are chosen only to keep the worked calculation legible.
05 · Do we need every visual token?
Two readers make two mixtures of the same image
A fixed number of readers gives a fixed number of summary vectors.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017117 / 178
For each reader compute softmax(qK transpose / sqrt(2)) over all twelve memory positions, then sum the paired values. The displayed overlays show all twelve rounded calculated weights. q1 produces [2.867, 4.031]; q2 produces [2.94, 0.34]. Stack the results into a two by two output matrix. This one-head toy assumes identity output projection and omits residuals and MLPs. No attention map is measured from a model, and neither vector is itself an English summary or an object label. A learned reader need not specialize in a particular semantic category. The next slide returns to the actual notebook sizes.
Ask: A fixed number of readers gives a fixed number of summary vectors.
Answer: For each reader compute softmax(qK transpose / sqrt(2)) over all twelve memory positions, then sum the paired values. The displayed overlays show all twelve rounded calculated weights. q1 produces [2.867, 4.031]; q2 produces [2.94, 0.34]. Stack the results into a two by two output matrix. This one-head toy assumes identity output projection and omits residuals and MLPs. No attention map is measured from a model, and neither vector is itself an English summary or an object label. A learned reader need not specialize in a particular semantic category. The next slide returns to the actual notebook sizes.
05 · Do we need every visual token?
First reduce the count; then match the language width
196 × 192 → 8 × 192 → 8 × 768. Count and width change in different steps.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · MultiheadAttention · PyTorch118 / 178
Return from the explicitly hand-set two-dimensional toy to the actual notebook sizes. Attention reads every one of the 196 encoded patch rows and produces eight summaries, each 192-dimensional. This is learned aggregation, not selection of eight original patches. The separate linear projector maps each summary from 192 to the language input width 768, preserving the eight rows. Text embeddings enter later. A larger feature width does not mean additional token positions; projection cannot restore information discarded by a lossy summary. Retention of fine details must be evaluated after training.
Ask: 196 × 192 → 8 × 192 → 8 × 768. Count and width change in different steps.
Answer: Return from the explicitly hand-set two-dimensional toy to the actual notebook sizes. Attention reads every one of the 196 encoded patch rows and produces eight summaries, each 192-dimensional. This is learned aggregation, not selection of eight original patches. The separate linear projector maps each summary from 192 to the language input width 768, preserving the eight rows. Text embeddings enter later. A larger feature width does not mean additional token positions; projection cannot restore information discarded by a lossy summary. Retention of fine details must be evaluated after training.
05 · Do we need every visual token?
The summarizer, step by step in Python
# Construct once; register these in your modelSetupS = nn.Parameter(0.02 * torch.randn(1, 8, 192))1 × 8 × 192reader = nn.MultiheadAttention(192, 3, batch_first=True)3 heads × 64projector = nn.Linear(192, 768)192 → 768# Each forward call: H contains encoded patchesH: B × 196 × 192slots = S.expand(H.shape[0], -1, -1)B × 8 × 192Z, weights = reader(slots, H, H,Query, key, value inputs average_attn_weights=False)Keep weights per headvisual = projector(Z)B × 8 × 768reader projects Q/K/V internally, matches keys, applies softmax, mixes values and joins heads.
Z: B × 8 × 192. weights: B × 3 × 8 × 196. B is the batch size.
Initialize once; reuse the same reader on each new image.
How does visual information become context for next-token prediction?
MultiheadAttention · PyTorch119 / 178
Executable reader construction and forward statements, using torch and nn imports. In a real model, construct once in __init__, assigning S as an nn.Parameter attribute and reader/projector as module attributes; this registers them for the optimizer and checkpoint. Use a common device and dtype for H, S, reader and projector. H comes from the image encoder. S.expand shares the same starting parameters across B examples without redrawing randomness or allocating an independent parameter bank. MultiheadAttention accepts unprojected slot states as its query argument and H as key and value arguments; its internal distinct learned projections produce Q/K/V. No attention mask is provided: each slot can read every patch. average_attn_weights=False returns one 8 by 196 weight matrix per head and image. The output Z has B by 8 by 192 shape after concatenating heads and applying the attention output projection; the separate projector changes the width to 768. Dropout defaults to zero in this teaching reader. Full resamplers can add repeated blocks, residuals, norms and MLPs; they are outside this minimal example. Constructing nn.Parameter does not train it. Include S, reader and projector in an optimizer, use answer-token loss, backward and step to train. The notebook initializes but does not train these new components. No attention or answer quality is asserted by this snippet.
Ask: Initialize once; reuse the same reader on each new image.
Answer: Executable reader construction and forward statements, using torch and nn imports. In a real model, construct once in __init__, assigning S as an nn.Parameter attribute and reader/projector as module attributes; this registers them for the optimizer and checkpoint. Use a common device and dtype for H, S, reader and projector. H comes from the image encoder. S.expand shares the same starting parameters across B examples without redrawing randomness or allocating an independent parameter bank. MultiheadAttention accepts unprojected slot states as its query argument and H as key and value arguments; its internal distinct learned projections produce Q/K/V. No attention mask is provided: each slot can read every patch. average_attn_weights=False returns one 8 by 196 weight matrix per head and image. The output Z has B by 8 by 192 shape after concatenating heads and applying the attention output projection; the separate projector changes the width to 768. Dropout defaults to zero in this teaching reader. Full resamplers can add repeated blocks, residuals, norms and MLPs; they are outside this minimal example. Constructing nn.Parameter does not train it. Include S, reader and projector in an optimizer, use answer-token loss, backward and step to train. The notebook initializes but does not train these new components. No attention or answer quality is asserted by this snippet.
05 · Do we need every visual token?
What teaches the slots to extract useful summaries?
The answer loss trains the slots and reader; we never supply a “correct summary vector”.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022120 / 178
This is a possible training setup for our minimal compressed-prefix model, not the full BLIP-2 or Flamingo recipe. Supply images, prompts and reference answers. Encode with a fixed ViT, compute summaries with trainable S and reader projections, project to the fixed language model width, and train with teacher-forced answer-only next-token cross-entropy. Backpropagation passes through the fixed language model to the visual inputs, projector, attention weights and S. The optimizer includes S, reader and projector. Do not wrap the frozen LM forward in no_grad: its parameters can be frozen while derivatives with respect to the visual input remain necessary. No target Z or manually assigned slot category is supplied. Repeat across many examples and save the parameters. The detailed loss and teacher-forcing section follows later. The actual notebook reader is initialized but untrained; a separate implementation check validates shapes and gradient flow without claiming meaningful trained summaries.
Ask: The answer loss trains the slots and reader; we never supply a “correct summary vector”.
Answer: This is a possible training setup for our minimal compressed-prefix model, not the full BLIP-2 or Flamingo recipe. Supply images, prompts and reference answers. Encode with a fixed ViT, compute summaries with trainable S and reader projections, project to the fixed language model width, and train with teacher-forced answer-only next-token cross-entropy. Backpropagation passes through the fixed language model to the visual inputs, projector, attention weights and S. The optimizer includes S, reader and projector. Do not wrap the frozen LM forward in no_grad: its parameters can be frozen while derivatives with respect to the visual input remain necessary. No target Z or manually assigned slot category is supplied. Repeat across many examples and save the parameters. The detailed loss and teacher-forcing section follows later. The actual notebook reader is initialized but untrained; a separate implementation check validates shapes and gradient flow without claiming meaningful trained summaries.
05 · Do we need every visual token?
Same readers; a different image to summarize
The summary length stays fixed; its feature values depend on the source image.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020 · BLIP-2 · Li et al., 2023121 / 178
Schematic comparison of two separate inputs: the dog photograph and an invoice image. Apply the same 224 by 224 preprocessing, ViT and reader configuration to each. Each image gives 196 patch rows, while the same eight by 192 stored slots produce eight output rows of width 192. Symbols a1 through a8 and b1 through b8 denote different input-dependent activations, not measured numeric outputs or words. Project the eight rows to language width, add that input’s question and answer prefix, then use the causal decoder and vocabulary head. Here the question is introduced after summarization. The number eight is the notebook setting; the two-reader example was a smaller calculation, not an intermediate stage in the notebook.
Ask: The summary length stays fixed; its feature values depend on the source image.
Answer: Schematic comparison of two separate inputs: the dog photograph and an invoice image. Apply the same 224 by 224 preprocessing, ViT and reader configuration to each. Each image gives 196 patch rows, while the same eight by 192 stored slots produce eight output rows of width 192. Symbols a1 through a8 and b1 through b8 denote different input-dependent activations, not measured numeric outputs or words. Project the eight rows to language width, add that input’s question and answer prefix, then use the causal decoder and vocabulary head. Here the question is introduced after summarization. The number eight is the notebook setting; the two-reader example was a smaller calculation, not an intermediate stage in the notebook.
05 · Do we need every visual token?
Eight vectors can represent many image details
A detail can be represented across several rows and feature coordinates.
How does visual information become context for next-token prediction?
Original teaching example / diagram122 / 178
This is one synthetic invoice image, with invoice ID ES667-042, GST 180 rupees and total 1180 rupees highlighted. We reuse the notebook dimensions as a conceptual design: resize to 224 by 224, 16 by 16 patches, drop CLS, retain all 196 patch rows of width 192, then use eight learned readers. Z has eight rows of 192 scalar feature values: 1536 values, not eight words or eight selected invoice fields. All eight rows are drawn; ellipses hide only middle columns. The z_ij symbols are coordinates, not measured invoice activations. Information about a field can be distributed across multiple rows and columns. This is what the representation should learn, not a claim that an untrained eight-query reader already preserves the document. Image preprocessing can also lose detail before summarization. The next slide shows what preserving the information would mean operationally.
Ask: A detail can be represented across several rows and feature coordinates.
Answer: This is one synthetic invoice image, with invoice ID ES667-042, GST 180 rupees and total 1180 rupees highlighted. We reuse the notebook dimensions as a conceptual design: resize to 224 by 224, 16 by 16 patches, drop CLS, retain all 196 patch rows of width 192, then use eight learned readers. Z has eight rows of 192 scalar feature values: 1536 values, not eight words or eight selected invoice fields. All eight rows are drawn; ellipses hide only middle columns. The z_ij symbols are coordinates, not measured invoice activations. Information about a field can be distributed across multiple rows and columns. This is what the representation should learn, not a claim that an untrained eight-query reader already preserves the document. Image preprocessing can also lose detail before summarization. The next slide shows what preserving the information would mean operationally.
05 · Do we need every visual token?
Reuse the summary; change only the question
The summary is useful when it preserves evidence for the questions we need to answer.
How does visual information become context for next-token prediction?
Original teaching example / diagram123 / 178
Keep the same invoice and computed Z, then start three independent prompts. For each prompt, project Z from width 192 to 768, tokenize and embed the new question, and concatenate the visual prefix before text embeddings. The answer-so-far portion begins empty and grows as the causal decoder and vocabulary head generate tokens. The summarizer here does not see the question; it must produce a representation useful across these tasks. ES667-042, 180 rupees and 1180 rupees are reference answers transcribed from the authored image, not measured model outputs. After training, we would compare generated answers against these references. Training examples for multiple fields can send gradients through the decoder to the reader, encouraging its features to retain useful evidence. No vector is assigned to one field, and 1536 features alone do not guarantee that exact text survives. The notebook wiring uses untrained new components and does not demonstrate invoice reading. More summary rows, better source resolution or better training may be needed if the required answers cannot be recovered.
Ask: The summary is useful when it preserves evidence for the questions we need to answer.
Answer: Keep the same invoice and computed Z, then start three independent prompts. For each prompt, project Z from width 192 to 768, tokenize and embed the new question, and concatenate the visual prefix before text embeddings. The answer-so-far portion begins empty and grows as the causal decoder and vocabulary head generate tokens. The summarizer here does not see the question; it must produce a representation useful across these tasks. ES667-042, 180 rupees and 1180 rupees are reference answers transcribed from the authored image, not measured model outputs. After training, we would compare generated answers against these references. Training examples for multiple fields can send gradients through the decoder to the reader, encouraging its features to retain useful evidence. No vector is assigned to one field, and 1536 features alone do not guarantee that exact text survives. The notebook wiring uses untrained new components and does not demonstrate invoice reading. More summary rows, better source resolution or better training may be needed if the required answers cannot be recovered.
05 · Do we need every visual token?
How each model uses the image
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Flamingo · Alayrac et al., 2022 · BLIP-2 · Li et al., 2023124 / 178
Teach only the broad route on this slide: LLaVA keeps patch vectors and passes them with text; Flamingo summarizes into separate memory that text reads; BLIP-2 summarizes and passes the summaries with text. The three columns reveal one at a time. Compression is a separate choice from prefix versus cross-attention access, so these are not three mutually exclusive mechanisms. All three language models predict a next token. Configuration details below are reference notes, not labels students need to read on the slide. The original LLaVA linear connector keeps every retained patch row; later variants can use an MLP and different image resolutions. For the original 224-pixel CLIP ViT-L/14 example, 16 by 16 patches give 256 rows after omitting CLS. Flamingo uses an NFNet-F6 CNN grid, not ViT patches. Its Perceiver Resampler uses learned latent queries; attention keys and values include image and latent features, with repeated attention and MLP blocks. The resulting 64 rows remain separate memory. Added language cross-attention uses text queries and a learned gate controls the visual update. Q-Former means Querying Transformer: queries communicate through self-attention and read image features through cross-attention. BLIP-2 uses 32 width-768 query outputs; the ViT-L/14 example retains 256 patch states plus CLS. Its FC layer projects the summaries for an OPT visual prefix. Q-Former is initialized from BERT and trained with image-text objectives before connection to a frozen LLM; its shared text branch and training masks are omitted here. The shown generation route supplies the prompt to OPT after the visual prefix; question-conditioned Q-Former variants and FlanT5 interfaces differ. Learned queries are model parameters, not written questions. T is the current embedded text length; before generation the answer portion is empty. Tokenization, residuals, normalization, positions and repeated LM blocks are abstracted. These are configuration examples, not a capacity or quality ranking.
Ask: Which models put visual vectors alongside text, and which reads a separate memory?
Answer: LLaVA puts projected patch vectors alongside text. BLIP-2 first summarizes the image, then puts projected summaries alongside text in the OPT route. Flamingo summarizes the image too, but its language model reads those summaries from separate memory through cross-attention.
05 · Do we need every visual token?
Same readers. New image, new summary.
The readers are stored parameters; each image produces its own summary vectors.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0125 / 178
At inference, process the dog and cat as two independent runs of the same model. The single amber S table supplies identical starting reader parameters to both calls. Vision-encoder and reader projection weights also stay unchanged. Blue arrows carry image data, while dashed amber arrows indicate reused parameters. Each call returns eight vectors of width 192, denoted a1 through a8 for the dog and b1 through b8 for the cat. These symbolic names are not measured outputs, English summaries or predetermined semantic reader roles. The row count and width stay fixed, while values depend on the image. The notebook reader is initialized but untrained; learned reader here refers to the kind of trainable parameter a trained summarizer learns. Ordinary inference does not update weights or slots; training can update whichever parameters are trainable. A pretrained but frozen weight is still a learned parameter. Computed image features, attention scores, mixture weights and summaries are activations. Fixed initial slots do not imply fixed intermediate query activations in a deeper resampler. The language model is omitted here to keep one distinction visible.
Ask: The readers are stored parameters; each image produces its own summary vectors.
Answer: At inference, process the dog and cat as two independent runs of the same model. The single amber S table supplies identical starting reader parameters to both calls. Vision-encoder and reader projection weights also stay unchanged. Blue arrows carry image data, while dashed amber arrows indicate reused parameters. Each call returns eight vectors of width 192, denoted a1 through a8 for the dog and b1 through b8 for the cat. These symbolic names are not measured outputs, English summaries or predetermined semantic reader roles. The row count and width stay fixed, while values depend on the image. The notebook reader is initialized but untrained; learned reader here refers to the kind of trainable parameter a trained summarizer learns. Ordinary inference does not update weights or slots; training can update whichever parameters are trainable. A pretrained but frozen weight is still a learned parameter. Computed image features, attention scores, mixture weights and summaries are activations. Fixed initial slots do not imply fixed intermediate query activations in a deeper resampler. The language model is omitted here to keep one distinction visible.
05 · Do we need every visual token?
Idea 3, end to end in one function
image
One image
question = “What animal is shown?”
answer_so_far = “It is a” (empty at the start)
def next_token(image, question, answer_so_far): patches = vit(image).patch_statesN × dV summary = summarizer(queries, patches)M × dS; M < N visual = projector(summary)M × dLM ids = tokenize(question, answer_so_far)T token IDs text = embed(ids)T × dLM inputs = concat([visual, text], axis="tokens")(M + T) × dLM hidden = causal_decoder(inputs)(M + T) × dLM return argmax(lm_head(hidden[-1]))Next text token IDsummarizer: M learned queries read all N patch rows through cross-attention; outputs depend on the image.
Shown: BLIP-2 / OPT-style prefix. For a Flamingo-style connection, use the summaries as Idea 2’s memory.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022 · Oxford-IIIT Pet · CC BY-SA 4.0126 / 178
This conceptual function demonstrates the compressed-prefix route, corresponding to the top OPT-style path in the BLIP-2 architecture figure. The image enters a ViT and all N contextual patch features enter the summarizer. queries is an M-row learned parameter bank shared across images, not an input text question. The summarizer forms attention queries from this bank and its evolving states; patch features supply image keys and values. Its M output rows depend on the image and are mixtures, not M selected original patches. dS is the summarizer output width. The summarizer can contain repeated self-attention, cross-attention and MLP blocks, with residuals and norms; this one call is not a full specification of Q-Former or Perceiver Resampler. BLIP-2 uses 32 learned queries. M < N expresses the compression example rather than a universal constraint at every possible resolution. The projector changes width dS to dLM, preserving M. Then the same tokenize, embed, concat, causal decoder and language head as Idea 1 produce the next answer token. For the other connection, keep summary as a separate memory and pass it to the Idea 2 cross-attention decoder with the T text embeddings; do not also concatenate. Flamingo exemplifies compression plus separate memory, with NFNet visual features rather than this ViT and a gated cross-attention architecture. Its memory need not be externally projected to dLM; cross-attention has its own K/V and output projections. BLIP-2 also has an encoder-decoder FlanT5 route, shown in the paper figure but not implemented by this decoder-only sketch. The input formatting, positional handling, masking, full decoder stack, final normalization and generation caching conventions are the same conceptual abstractions as Idea 1. The summarizer queries are learned parameters; its summaries are newly computed activations. Freeze/train choices are taught in the training section.
Ask: Which line changes the number of visual rows, and which line changes their width?
Answer: summarizer changes N patch rows into M image-dependent summaries. projector changes each summary’s width to dLM while retaining M. This sketch uses a prefix; the same summaries could instead become separate memory.
Section 06
How do we train the connection?
Return to Idea 1’s visual prefix and the dog question. Supply a correct answer, score its tokens, then update the projector.
How does visual information become context for next-token prediction?
Original teaching example / diagram127 / 178
Return to Idea 1’s visual prefix and the dog question. Supply a correct answer, score its tokens, then update the projector.
Ask:
Answer: Return to Idea 1’s visual prefix and the dog question. Supply a correct answer, score its tokens, then update the projector.
06 · How do we train the connection?
Training starts with a correct answer supplied by us
The dataset supplies the answer we want the model to learn.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0128 / 178
Start with an image, a question and a correct answer from the dataset. Here the teacher authored A black dog. The model does not create its own reference. Tokenize the space-prefixed reference with DistilGPT2 and append its EOS ID 50256. The teacher controls the text; the tokenizer determines the IDs. In real datasets references can be human-written captions or reviewed question–answer annotations. No claim is made that this dog is a LLaVA training example. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Run the same model; inspect the first answer prediction
The reference ID tells us which vocabulary probability to inspect.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0129 / 178
Start with the same empty-answer prefix as generation: 196 visual vectors followed by ten prompt embeddings. The pretrained vision encoder and language model already contain learned parameters; the projector is newly initialized. The last prompt colon is position 205, whose final decoder hidden state feeds the 50,257-way vocabulary head. Training evaluates the probability assigned to known target ID 317. It does not need argmax or sampling to define its target. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
How much probability did the correct token receive?
Low probability on the correct token gives a large loss.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0130 / 178
The numbers are hand-set full-vocabulary probability aggregates: .20 for space-A (ID 317), .30 for space-The (ID 383), and .50 in total for all remaining 50,255 entries. This is a new illustrative training distribution, not the earlier four-entry generation toy. The target ID selects p[317]; negative natural log gives 1.609437912. If p[317] were .80 the loss would instead be .223143551; this is a hypothetical comparison, not a measured optimizer result. Cross-entropy acts on probabilities, not numerical distances between token IDs. No generated token is needed to compute this loss. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Which token do we feed back next?
Training uses the reference token; inference uses the model’s selected token.
How does visual information become context for next-token prediction?
Teacher forcing · PyTorch · Greedy decoding and sampling · Hugging Face · Oxford-IIIT Pet · CC BY-SA 4.0131 / 178
Teacher forcing supplies correct earlier answer tokens as context during supervised training. Start at the final Answer colon with the same illustrative probabilities as the preceding slide: space-A has .20, space-The has .30, and all other tokens share .50. For this comparison, additionally assume no individual remaining token exceeds .30; the aggregate .50 is not a candidate token. The reference is A black dog. Training first scores space-A with loss -ln(.20), regardless of which token is most likely. The next supervised position receives the reference space-A, so its context ends with Answer: A and its next target is space-black. It does not receive the model-preferred space-The. In ordinary inference the reference answer is unavailable. Greedy decoding selects space-The, embeds and appends it, and predicts again from Answer: The. Sampling could select a different token; whichever token is selected becomes part of the next prefix. The two branches hold the model, image, question and illustrative first-token distribution fixed to isolate the feedback choice. The same word may be plausible in another answer; reference loss here scores the supplied answer sequence. Spaces before words are implicit in the large token boxes. No optimizer update happens between the illustrated training positions: in a causal transformer the known reference is supplied together and all shifted targets can be scored in one causal forward pass, as shown next. The model cannot see its own target or future tokens from the predicting position. The sum or mean answer loss is then differentiated and the selected weights are updated. This diagram explains the standard teacher-forced objective used in this lecture, not every possible training algorithm. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: The model prefers The, but the reference starts with A. Which token enters the next prefix?
Answer: Teacher-forced training uses reference A, then predicts reference black. Greedy inference uses the selected The, then predicts from that generated prefix. Sampling is another inference choice. Training can compute all known reference positions in one causal pass; it does not require an optimizer step between tokens.
06 · How do we train the connection?
Now line up all five next-token targets
Each position predicts the next reference token using only its allowed prefix.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0132 / 178
Each row denotes the context visible at one supervised position in the same example, not five independent images or required model calls. All rows see the image and complete question prompt. The prompt ends with Answer:; shown answer prefixes then contain zero, one, two, three or four correct earlier answer tokens. Read positions 205,206,207,208,209 to predict A, black, dog, period and EOS. The dot attached to a word denotes a leading space; the separate period is a punctuation token. Full token IDs remain in the verified fixture. During implementation the entire reference sequence is supplied together, and the causal mask prevents each predicting state from reading its own target or future tokens. Within each decoder layer the known positions are computed in parallel; the decoder layers still run in order. Teacher forcing does not use the model guess from the preceding position. The following slide collects the probabilities and losses; later labels and mask slides explain the exact shift and ignore index. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Turn five target probabilities into one answer loss
Score each correct token, then average the five penalties, including EOS.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0133 / 178
This slide scores the five target positions established by the preceding prefix table. Probabilities .20,.40,.50,.80,.90 are authored, not measured outputs. Apply negative natural log separately, obtaining [1.6094379124341003, 0.916290731874155, 0.6931471805599453, 0.2231435513142097, 0.10536051565782628]. Their unrounded sum is 3.5473798918402366 and mean is 0.7094759783680473. The five targets include EOS. Displayed penalties and total are rounded only for readability; add unrounded values before taking the mean. Each probability comes from a different next-token distribution, conditioned on its correct reference prefix. These five probabilities therefore are not required to sum to one. Image and question targets are excluded from the loss average, while remaining visible as context. One backward pass on the combined mean follows, as illustrated later; no weight update occurs between these columns. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
One input sequence; five answer targets to score
Ignore context labels; still use the image and question as context.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0134 / 178
The no-padding batch has inputs_embeds shape [1,211,768] and labels shape [1,211]. Fill label positions 0–205 with ignore index -100, then positions 206–210 with answer IDs 317,2042,3290,13,50256. DistilGPT2 causal LM loss internally compares logits[..., :-1, :] with labels[..., 1:], ignoring -100. Thus supervised logits are positions 205–209, including the final prompt colon that predicts first answer A. The EOS token is included as a known input for the convenient full-sequence implementation, but its final output logit has no subsequent target and is discarded. Image vectors and prompt tokens remain context even though their label entries are ignored. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Knowing the answer does not let the model peek ahead
Attention controls what a state reads. Loss labels select what we grade.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0135 / 178
At position 205 (the final colon of the prompt), causal attention may read image positions 0–195 and text positions 196–205, but no answer position 206 or later. The reference A is available outside that hidden-state computation as its target, so teacher forcing does not let a position see its own next-token answer. Loss masking ignores targets on image and prompt positions; it does not hide those context vectors from attention. At later answer positions the causal mask permits the earlier reference answer tokens. The answer label A at 206 is graded using the prompt colon output at 205. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Use the answer loss to change the projector
Frozen LM weights still pass a gradient to the trainable visual connection.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0136 / 178
This example chooses a frozen vision encoder, frozen language model and trainable linear projector. Backpropagate the mean answer loss through the language operations to the visual-prefix inputs and then into projector weights. Frozen means that the optimizer does not update a parameter; it does not mean the computation can be excluded from autograd when its input depends on trainable parameters. Vision features can be computed under no_grad here; the LM forward must remain tracked. SGD updates the projector by subtracting learning_rate times gradient. That local direction is intended to reduce loss for sufficiently small steps, not a guarantee that every optimizer step improves all examples. Repeat with many diverse labelled examples; one example cannot teach general visual understanding. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · How do we train the connection?
Training adds targets, a loss and a weight update
The reference supplies the targets; only the projector weights change.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0137 / 178
This is the training-specific continuation of Idea 1, not another generation demonstration. The prepared input X already contains the 196 projected image rows, ten prompt embeddings and five known reference embeddings. The reference comes from the dataset. The original four preparation statements are: ['with torch.no_grad(): H = vit(pixel_values=pixels).last_hidden_state[:, 1:]', 'V = projector(H)', 'ids = torch.cat([prompt_ids, answer_ids], dim=1)', 'X = torch.cat([V, lm.get_input_embeddings()(ids)], dim=1)']. The six displayed training statements are executable Python, with comments and syntax colours. Before preparation: freeze vit and lm parameters, initialize nn.Linear(192,768), and construct an optimizer over projector.parameters() only. The deterministic check uses eval mode to disable dropout. X has shape [1,211,768], answer_ids has shape [1,5] including EOS, and no padding is used. Fill labels with ignore index -100, then replace the final five positions with reference IDs. The negative slice is correct here because the answer is last and there is no padding. The causal LM applies the one-position shift internally and returns mean cross-entropy over the five answer targets. Earlier reference tokens are visible only where the causal mask allows. No next-token sampling or generated answer is required. zero_grad clears previous gradients, backward computes them through the frozen LM into the projector, and step updates only parameters owned by the optimizer. Keep the LM forward tracked by autograd even when its weights are frozen; only the vision preparation uses no_grad. For minibatches with padding, use an appropriate attention mask and label mask instead of this single-example suffix assignment. The displayed continuation, together with its four preparation statements, is executed by check_training_walkthrough.py; this checks implementation, not useful VLM quality. This training walkthrough selects Idea 1, using all 196 patch rows from the same 224-pixel DeiT-Tiny input and a 192-to-768 projector. The exact ten-token prompt is Question: What animal is shown? newline Answer:. The five reference answer IDs are 317, 2042, 3290, 13, 50256, for space-A, space-black, space-dog, period and EOS. The reference is authored by the lecturer, not generated by the model. Token IDs and dimensions are real; probabilities are explicitly hand-set examples, not measured outputs from the notebook. We first teach a projector-only update on this example; that teaching choice is distinct from the original LLaVA two-stage recipe at the end. Batch size one and no padding are used in the code. Other connectors use the same next-token supervision, but have different trainable parameters and information paths.
Ask: Who supplies the target, which state predicts it, and which weights are updated?
Answer: The dataset supplies reference answer tokens. Each preceding position predicts the next token; the final prompt colon predicts the first answer. Our first code example updates only the projector. The final three diagrams explain the distinct original LLaVA caption and instruction stages.
06 · TRAINING · CAPTIONS TO INSTRUCTIONS
Both stages train on supplied reference answers
Captions train the visual connection; varied instructions train the model to answer questions.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0138 / 178
Start a dedicated two-stage training subsection before the summary. Both rows are optimization stages, not demonstrations of inference. A dataset supplies each image, prompt and correct reference answer; the model predicts next-token probabilities from the image, prompt and allowed earlier reference tokens, and loss changes selected weights. Stage 1 updates a newly initialized projector using image-caption pairs while the pretrained vision encoder and language model stay fixed. Stage 2 continues from those weights, uses varied image-question-answer examples, and updates the projector plus language model while keeping vision fixed. Repeat across many examples. At inference the reference answer is absent and no training update occurs. This is the original LLaVA recipe, not a universal recipe for all VLMs. The dog examples are authored illustrations. Follow with the three existing detailed diagrams, rather than introducing these stages in the closing recap.
Ask: Are the displayed captions and answers supplied training targets or generated replies?
Answer: They are supplied training targets in both stages. We predict each next target token and use its loss to update the marked weights. At inference we supply no reference answer.
06 · TRAINING · CAPTIONS TO INSTRUCTIONS
Stage 1: learn the visual connection from captions
Caption targets train the projector; vision and language weights stay fixed.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0139 / 178
Stage 1 connects pretrained vision features to the pretrained language model by training a newly initialized projector on image-caption examples. A brief-description prompt is paired with the original caption as the reference. Here Describe this image and A black dog outdoors are authored teaching data. The prompt plus allowed earlier reference tokens enter the causal decoder; target tokens select the probabilities that contribute to the loss. Vision and language weights remain fixed. The dashed red route is a loss gradient through the frozen language computation to projector parameters, not a generated sentence sent backward. Repeat on many image-caption pairs. The objective encourages a useful visual interface; it does not guarantee that one pair teaches every visual detail. The fixed/update badges explicitly identify parameter updates. Solid coloured arrows show forward information; dashed red arrows show gradient flow. The arrow from reference text to the loss supplies labels, not an input bypass to the hidden state. Reference prefix means only earlier reference tokens visible under the causal mask; future targets are hidden. Parameter-matrix squares are schematic, not numerical weights. These three slides describe the original LLaVA training recipe in Visual Instruction Tuning, section 4.2, https://arxiv.org/html/2304.08485v2#S4.SS2. The image, captions and question-answer examples are authored teaching illustrations, not quotations from its training dataset or measured model outputs. The earlier small DeiT/DistilGPT2 projector-only code check is a separate demonstration; its dimensions and choice of a question-answer example do not define LLaVA stage 1. Here the vision encoder is CLIP ViT and the language decoder is pretrained Vicuna. Both stages use teacher-forced next-token supervision. The diagrams omit batch size, tokenization, positional encoding and internal decoder layers for clarity.
Ask: Which weights change when we train on these captions?
Answer: Only the new projector. Vision and language weights stay fixed, but the loss gradient passes through the language computation to the projector.
06 · TRAINING · CAPTIONS TO INSTRUCTIONS
Keep the learned connection; change the training examples
Stage 2 reuses the trained model and broadens the questions it learns to answer.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0140 / 178
Move from caption alignment to instruction tuning without resetting the learned projector. The stage-1 checkpoint carries the learned projector plus the retained pretrained vision and language weights; stage 2 starts from these same weights. The diagram then contrasts authored examples using one image so that the data change is visible: a general description, a colour question and a location question. Arrows pair inputs with dataset references; these are not generated answers and do not assert measured stage-1 or stage-2 capabilities. More varied instruction examples specify which aspects of the visual content to address. Stage-1 caption pairs can already be wrapped in a brief-description instruction, so the difference is not simply whether a question string exists. The next slide shows the change in trainable parameter sets. Real training uses many images and instruction types; the repeated photograph here holds the visual input fixed for explanation. These three slides describe the original LLaVA training recipe in Visual Instruction Tuning, section 4.2, https://arxiv.org/html/2304.08485v2#S4.SS2. The image, captions and question-answer examples are authored teaching illustrations, not quotations from its training dataset or measured model outputs. The earlier small DeiT/DistilGPT2 projector-only code check is a separate demonstration; its dimensions and choice of a question-answer example do not define LLaVA stage 1. Here the vision encoder is CLIP ViT and the language decoder is pretrained Vicuna. Both stages use teacher-forced next-token supervision. The diagrams omit batch size, tokenization, positional encoding and internal decoder layers for clarity.
Ask: What is carried forward, and what do the new examples teach?
Answer: Continue with the same vision encoder, learned projector and language model weights. Instruction examples pair different questions with the reference answers appropriate to each question.
06 · TRAINING · CAPTIONS TO INSTRUCTIONS
Stage 2: learn to answer visual instructions
The next-token loss stays; the projector and language model can now change.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0141 / 178
Stage 2 continues from the stage-1 checkpoint. Use varied image-conditioned instruction/answer examples, such as the authored colour question and reference Black. Both the learned projector and language-model parameters can now update; the vision encoder remains frozen. The model receives the question and allowed earlier reference tokens, predicts next-token scores, and compares them with reference targets. The red backward path branches to both trainable parameter sets. Repeat across many instruction examples; one dog question does not teach general instruction following. The original paper uses GPT-assisted visual instruction data, including conversation, detailed description and reasoning tasks. The fixed/update badges explicitly identify parameter updates. Solid coloured arrows show forward information; dashed red arrows show gradient flow. The arrow from reference text to the loss supplies labels, not an input bypass to the hidden state. Reference prefix means only earlier reference tokens visible under the causal mask; future targets are hidden. Parameter-matrix squares are schematic, not numerical weights. These three slides describe the original LLaVA training recipe in Visual Instruction Tuning, section 4.2, https://arxiv.org/html/2304.08485v2#S4.SS2. The image, captions and question-answer examples are authored teaching illustrations, not quotations from its training dataset or measured model outputs. The earlier small DeiT/DistilGPT2 projector-only code check is a separate demonstration; its dimensions and choice of a question-answer example do not define LLaVA stage 1. Here the vision encoder is CLIP ViT and the language decoder is pretrained Vicuna. Both stages use teacher-forced next-token supervision. The diagrams omit batch size, tokenization, positional encoding and internal decoder layers for clarity.
Ask: What changes in stage 2, and what remains the same?
Answer: The examples cover varied visual instructions, and both projector and language-model weights can update. Vision stays fixed; the reference-token loss and teacher forcing remain the same.
Section 07
Summary
Rebuild the whole picture: represent the image, connect it to language, and predict the next word.
How does visual information become context for next-token prediction?
Original teaching example / diagram142 / 178
Rebuild the whole picture: represent the image, connect it to language, and predict the next word.
Ask:
Answer: Rebuild the whole picture: represent the image, connect it to language, and predict the next word.
07 · Summary
ViT represents. CLIP compares. A VLM generates.
A generative VLM adds a language decoder and a path from the image to that decoder.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 2020 · CLIP · Radford et al., 2021 · LLaVA · Liu et al., 2023143 / 178
Use the same model-portrait grammar as Beyond Attention: visible input and output rows, full versus causal attention icons, and an autoregressive return arrow. ViT exposes contextual patch vectors; downstream readouts can classify or retrieve. CLIP compares normalized image and text representations from supplied descriptions. A generative VLM predicts vocabulary tokens conditioned on image features and text. The VLM connector is abstracted here and unpacked on the next recap. The shown match and dog token are illustrative, not saved measurements.
Ask: A generative VLM adds a language decoder and a path from the image to that decoder.
Answer: Use the same model-portrait grammar as Beyond Attention: visible input and output rows, full versus causal attention icons, and an autoregressive return arrow. ViT exposes contextual patch vectors; downstream readouts can classify or retrieve. CLIP compares normalized image and text representations from supplied descriptions. A generative VLM predicts vocabulary tokens conditioned on image features and text. The VLM connector is abstracted here and unpacked on the next recap. The shown match and dog token are illustrative, not saved measurements.
07 · Summary
Choose how image features reach the decoder
Project width. Choose the access path. Optionally shorten the visual sequence.
How does visual information become context for next-token prediction?
LLaVA · Liu et al., 2023 · Flamingo · Alayrac et al., 2022 · BLIP-2 · Li et al., 2023144 / 178
The three numbered ideas are not three mutually exclusive architectures. Idea 1 projects every retained patch vector and prepends the result to text embeddings. Idea 2 adds cross-attention: text states supply Q and separate visual memory supplies K,V. Idea 3 compresses N image rows into M image-dependent summaries using learned query vectors; those summaries can enter either Idea 1 or Idea 2. Projection changes width without changing row count. Compression changes row count, potentially losing detail; access chooses where the decoder reads the image. Tiny vector boxes abbreviate whole sequences. MLPs, residual paths, normalization and positions are omitted from this routing overview.
Ask: Project width. Choose the access path. Optionally shorten the visual sequence.
Answer: The three numbered ideas are not three mutually exclusive architectures. Idea 1 projects every retained patch vector and prepends the result to text embeddings. Idea 2 adds cross-attention: text states supply Q and separate visual memory supplies K,V. Idea 3 compresses N image rows into M image-dependent summaries using learned query vectors; those summaries can enter either Idea 1 or Idea 2. Projection changes width without changing row count. Compression changes row count, potentially losing detail; access chooses where the decoder reads the image. Tiny vector boxes abbreviate whole sequences. MLPs, residual paths, normalization and positions are omitted from this routing overview.
07 · Summary
From this image to the next word
The image supplies context; the language vocabulary supplies the next token.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 2020 · Oxford-IIIT Pet · CC BY-SA 4.0145 / 178
Close with Idea 1 using the pinned notebook components. The DeiT-Tiny image has 196 retained patch rows, each 192-dimensional; dropping CLS is the chosen interface. Project each row to DistilGPT2 width 768. Question: What animal is shown? newline Answer: It is a gives 13 tokenizer pieces. Join 196 visual and 13 text embeddings, all width 768. The decoder uses causal attention over this sequence; the image features already used full ViT attention. Read the final state at a, score all 50,257 vocabulary entries, choose one token and append its embedding on the next step. Dog is an authored example, not an actual output from the untrained notebook connector. Position handling, final normalization, special chat markers and cache implementation are abstracted. Exit ticket: point to where width, row count, image access and trainable weights are chosen.
Ask: The image supplies context; the language vocabulary supplies the next token.
Answer: Close with Idea 1 using the pinned notebook components. The DeiT-Tiny image has 196 retained patch rows, each 192-dimensional; dropping CLS is the chosen interface. Project each row to DistilGPT2 width 768. Question: What animal is shown? newline Answer: It is a gives 13 tokenizer pieces. Join 196 visual and 13 text embeddings, all width 768. The decoder uses causal attention over this sequence; the image features already used full ViT attention. Read the final state at a, score all 50,257 vocabulary entries, choose one token and append its embedding on the next step. Dog is an authored example, not an actual output from the untrained notebook connector. Position handling, final normalization, special chat markers and cache implementation are abstracted. Exit ticket: point to where width, row count, image access and trainable weights are chosen.
BACKUP · CONTENTS
Backup and optional reading
The main lecture ends here. Open a topic when needed.
How does visual information become context for next-token prediction?
Original teaching example / diagram146 / 178
All optional material begins at this boundary, after the three-slide recap. Five contiguous groups keep extensions, familiar LLM material, evaluation, model-specific details and sources separate. Each directory entry opens the corresponding group.
Ask:
Answer: All optional material begins at this boundary, after the three-slide recap. Five contiguous groups keep extensions, familiar LLM material, evaluation, model-specific details and sources separate. Each directory entry opens the corresponding group.
BACKUP A · MULTIPLE IMAGES
Optional · compare multiple images
What changed from before to after?
Follow two images all the way to one answer.
How does visual information become context for next-token prediction?
Original teaching example / diagram147 / 178
Optional extension after the completed main lecture. Use one before/after pair to explain independent encoding, per-image compression, prompt order, decoder attention and a short closing recap. End the extension at that recap.
Ask:
Answer: Optional extension after the completed main lecture. Use one before/after pair to explain independent encoding, per-image compression, prompt order, decoder attention and a short closing recap. End the extension at that recap.
BACKUP A · MULTIPLE IMAGES
One question, two ordered images
Keep “before” and “after” attached to the correct image.
How does visual information become context for next-token prediction?
Multi-image prompts · Idefics2 documentation148 / 178
This optional extension follows the completed main lecture. The earlier change example used one composite image. Here A and B are two separate image inputs in one prompt. All pictures and answers in this extension are authored. The chair moves right; the cup disappears. We will follow one per-image summary plus causal-prefix design, not claim this is the only multi-image architecture.
Ask: Keep “before” and “after” attached to the correct image.
Answer: This optional extension follows the completed main lecture. The earlier change example used one composite image. Here A and B are two separate image inputs in one prompt. All pictures and answers in this extension are authored. The chair moves right; the cup disappears. We will follow one per-image summary plus causal-prefix design, not claim this is the only multi-image architecture.
BACKUP A · MULTIPLE IMAGES
Encode each image with the same vision model
Keep the two feature groups identifiable from the start.
How does visual information become context for next-token prediction?
ViT · Dosovitskiy et al., 2020149 / 178
Controlled teaching dimensions extend the notebook, but this extension is not an executed notebook run. Resize the entire frame to 224 square to keep all objects visible, rather than pretending the notebook center crop was used. A patch is 16 by 16 pixels, so each image gives 196 retained patch rows of width 192 after dropping CLS. Process the two images independently with shared ViT weights and local within-image patch positions. Use image labels and boundaries later to preserve their identity; repeated patch index 1 in two images is not one global position.
Ask: Keep the two feature groups identifiable from the start.
Answer: Controlled teaching dimensions extend the notebook, but this extension is not an executed notebook run. Resize the entire frame to 224 square to keep all objects visible, rather than pretending the notebook center crop was used. A patch is 16 by 16 pixels, so each image gives 196 retained patch rows of width 192 after dropping CLS. Process the two images independently with shared ViT weights and local within-image patch positions. Use image labels and boundaries later to preserve their identity; repeated patch index 1 in two images is not one global position.
BACKUP A · MULTIPLE IMAGES
Summarize A and B separately
The same readers produce two image-dependent groups.
How does visual information become context for next-token prediction?
Original teaching example / diagram150 / 178
Each reader call uses the same eight stored query slots and projection weights, but reads only one 196-row feature matrix. It computes eight width-192 vectors for each image; stack the two groups later. The question is not an input to this minimal summarizer. No slot is pre-assigned to chair or cup. A and B output names denote vector provenance and do not assert measured activations or correspondence between like-numbered slots.
Ask: The same readers produce two image-dependent groups.
Answer: Each reader call uses the same eight stored query slots and projection weights, but reads only one 196-row feature matrix. It computes eight width-192 vectors for each image; stack the two groups later. The question is not an input to this minimal summarizer. No slot is pre-assigned to chair or cup. A and B output names denote vector provenance and do not assert measured activations or correspondence between like-numbered slots.
BACKUP A · MULTIPLE IMAGES
Text labels and image vectors share one input sequence
Before and After are ordinary text; A and B vectors come from the images.
How does visual information become context for next-token prediction?
Multi-image prompts · Idefics2 documentation151 / 178
Before: and After: are ordinary text in this schematic. Tokenize them into IDs and look up their learned LM embeddings, just as for the question. Each purple box may represent multiple tokens. Project each of sixteen image summary vectors from 192 to 768 dimensions without changing the row count. The text lookup and visual projector both supply width-768 vectors to this teaching decoder. A1 to A8 and B1 to B8 are visual vector names, not vocabulary IDs. Image markers and role templates are omitted for clarity. Decoder positions follow the combined sequence order; vision patch positions were local to each image. Labels supply the intended before/after roles; successful comparison also depends on training.
Ask: Before and After are ordinary text; A and B vectors come from the images.
Answer: Before: and After: are ordinary text in this schematic. Tokenize them into IDs and look up their learned LM embeddings, just as for the question. Each purple box may represent multiple tokens. Project each of sixteen image summary vectors from 192 to 768 dimensions without changing the row count. The text lookup and visual projector both supply width-768 vectors to this teaching decoder. A1 to A8 and B1 to B8 are visual vector names, not vocabulary IDs. Image markers and role templates are omitted for clarity. Decoder positions follow the combined sequence order; vision patch positions were local to each image. Labels supply the intended before/after roles; successful comparison also depends on training.
BACKUP A · MULTIPLE IMAGES
Build the two-image input, line by line
question = “What changed from before to after?”
answer_so_far = “The chair moved to the”
# summary_A and summary_B are already computedEach: 8 × 192A = projector(summary_A)8 × 768B = projector(summary_B)8 × 768before = embed(tokenize("Before:"))Ordinary text → vectorsafter = embed(tokenize("After:"))Ordinary text → vectorstext = embed(tokenize(question, answer_so_far))One vector per text tokenparts = [before, A, after, B, text]Same order as the diagraminputs = concat(parts, axis="tokens")(16 + T) × 768hidden = causal_decoder(inputs)(16 + T) × 768next_id = argmax(lm_head(hidden[-1]))Next text token IDT counts tokens in both labels, the question and the answer so far. Every input vector is 768-dimensional.
How does visual information become context for next-token prediction?
Original teaching example / diagram152 / 178
Continue the immediately preceding ordered-input diagram. This is high-level pseudocode, not executable model API code. Image A is the room before the change; image B is the room after it. Both use the same vision encoder, the same eight learned query slots, the same summarizer weights and the same projector. The two preceding slides have already computed summary_A and summary_B, each with eight width-192 rows. Apply the projector to each group to obtain A and B, each eight by 768. These are continuous visual vectors, not token IDs. Before: and After: are ordinary prompt strings. Tokenization may produce multiple pieces for each; embed looks up a width-768 vector for every ID in the language embedding table. The conceptual tokenize(question, answer_so_far) helper formats those spans in order, as on the earlier code recap; it does not mean a tokenizer paired-input API. Preserve generated answer IDs in an actual implementation. All five entries of parts are matrices of vectors. Concatenate their rows in exactly this order: label Before, eight A vectors, label After, eight B vectors, question plus the current answer prefix. T includes all three text spans. The decoder receives (16 + T) rows of width 768, with positional handling and a causal mask across the joined sequence. The full decoder includes attention, MLPs, residuals and normalization. Its last supplied text state predicts the next token. Argmax illustrates greedy selection; the chosen ID can be decoded for display and appended for another step. The example prefix is authored; no measured next token is claimed. At the start, the answer prefix is empty. This sketch omits image boundaries, chat roles, padding and batching; use the actual processor for a supported trained model. Encoding two images or adding labels alone does not train a model to compare them. During generation, reuse fixed image summaries and the decoder cache rather than recomputing the whole sequence.
Ask: Which inputs use a vocabulary lookup, and in what order do we join the vectors?
Answer: Before:, After:, the question and answer-so-far use tokenization and LM embedding lookup. A and B come from projected image summaries. Join Before vectors, A vectors, After vectors, B vectors, then question and answer vectors along the token axis. All rows have width 768.
BACKUP A · MULTIPLE IMAGES
The last text state can read both image groups
Attention weights are assigned to positions across the permitted context.
How does visual information become context for next-token prediction?
Transformer · Vaswani et al., 2017153 / 178
Follow the current answer prefix The chair moved to the and select its final word the, displayed as a readable token label. Its contextual decoder state supplies the query. Both image groups are earlier in our causal prefix and visible. A real decoder head also reads text positions, so the illustrative image weights sum to only 0.70 and text has 0.30. This is one joint softmax across all visible keys, not independent image softmaxes. Each paired value contributes to the mixed update, followed by output projection, residual and remaining decoder computation. The hand-set weights are not a measured model explanation and do not establish correct reasoning or object tracking.
Ask: Attention weights are assigned to positions across the permitted context.
Answer: Follow the current answer prefix The chair moved to the and select its final word the, displayed as a readable token label. Its contextual decoder state supplies the query. Both image groups are earlier in our causal prefix and visible. A real decoder head also reads text positions, so the illustrative image weights sum to only 0.70 and text has 0.30. This is one joint softmax across all visible keys, not independent image softmaxes. Each paired value contributes to the mixed update, followed by output projection, residual and remaining decoder computation. The hand-set weights are not a measured model explanation and do not establish correct reasoning or object tracking.
BACKUP A · MULTIPLE IMAGES
Two images, one ordered context, one answer
Prepare each image, preserve its order, then answer using both.
How does visual information become context for next-token prediction?
Multi-image prompts · Idefics2 documentation154 / 178
Close the optional section here. Recap only the established path: encode and summarize each image separately, keep the labelled A-then-B order beside the question, and generate one answer using both groups as context. The room images and completed reference answer are authored, not measured model outputs. The worked causal-prefix design permits access to both earlier image groups. Real use requires a model and processor trained for the intended multi-image interface. Do not reopen the generation loop or introduce alternative summarizers, model-specific masks or another cost calculation. The next divider begins separate optional inference reading.
Ask: Prepare each image, preserve its order, then answer using both.
Answer: Close the optional section here. Recap only the established path: encode and summarize each image separately, keep the labelled A-then-B order beside the question, and generate one answer using both groups as context. The room images and completed reference answer are authored, not measured model outputs. The worked causal-prefix design permits access to both earlier image groups. Real use requires a model and processor trained for the intended multi-image interface. Do not reopen the generation loop or introduce alternative summarizers, model-specific masks or another cost calculation. The next divider begins separate optional inference reading.
BACKUP B · INFERENCE REFRESHER
Optional · inference and caching
A refresher from our LLM lectures: prepare the context, decode tokens and reuse the cache.
How does visual information become context for next-token prediction?
Original teaching example / diagram155 / 178
Optional reading after the main conclusion. This section revisits inference, caching, training versus inference and multi-turn context from the preceding LLM lectures.
Ask:
Answer: Optional reading after the main conclusion. This section revisits inference, caching, training versus inference and multi-turn context from the preceding LLM lectures.
BACKUP B · INFERENCE REFRESHER
The whole generation loop before its individual steps
Prepare the fixed context once; repeatedly predict and append a token.
How does visual information become context for next-token prediction?
Original teaching example / diagram156 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is the same autoregressive loop from the earlier language-model lecture, with one new preparation step for the image. The next frames walk through each step in this complete loop. A cache stores computed keys and values; it does not store the future answer.
Ask: Prepare the fixed context once; repeatedly predict and append a token.
Answer: This is the same autoregressive loop from the earlier language-model lecture, with one new preparation step for the image. The next frames walk through each step in this complete loop. A cache stores computed keys and values; it does not store the future answer.
BACKUP B · INFERENCE REFRESHER
Encode the fixed image once
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram157 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Prefill the image and question context
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram158 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Decode one new token
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram159 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Append the selected token
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram160 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Reuse the cached keys and values
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram161 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Repeat until EOS or the generation limit
Only the generated prefix changes at each decoding step.
How does visual information become context for next-token prediction?
Original teaching example / diagram162 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
Ask: Only the generated prefix changes at each decoding step.
Answer: This is one generation call with fixed preprocessing and weights. The generate API handles the loop. Prefix models cache visual positions; cross-attention models may also cache per-layer visual K,V. Caching avoids recomputing states, not all attention work.
BACKUP B · INFERENCE REFRESHER
Same conditional model, different available prefix
Training
Reference prefix supplied.
Target loss and gradients.
Inference
Generated prefix grows.
No reference answer or backward pass.
Known targets allow parallel teacher-forced positions; generation is sequential.
How does visual information become context for next-token prediction?
Original teaching example / diagram163 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. The asterisk marks reference tokens. At inference each selected output becomes part of the next step’s input.
Ask: Known targets allow parallel teacher-forced positions; generation is sequential.
Answer: The asterisk marks reference tokens. At inference each selected output becomes part of the next step’s input.
BACKUP B · INFERENCE REFRESHER
Reuse the image; keep the conversation context
User: What animal is this?
Assistant: A dog.
User: What colour is its fur?
Assistant: Black.
Illustrative conversation, not a captured model transcript.
Visual features can persist. Decoder cache reuse also depends on the exact prefix.
How does visual information become context for next-token prediction?
Oxford-IIIT Pet · CC BY-SA 4.0164 / 178
Optional refresher from the LLM lectures; use after the main conclusion or assign as reading. 69–71 min. Reprocessing the full conversation is valid but less efficient. Image feature caching and decoder KV caching are distinct. The included classroom lab evaluates independent questions; it does not claim multi-turn KV reuse.
Ask: Visual features can persist. Decoder cache reuse also depends on the exact prefix.
Answer: 69–71 min. Reprocessing the full conversation is valid but less efficient. Image feature caching and decoder KV caching are distinct. The included classroom lab evaluates independent questions; it does not claim multi-turn KV reuse.
BACKUP C · EVALUATION
Optional · can we trust the answer?
Check evidence use, not just fluent language.
How does visual information become context for next-token prediction?
Original teaching example / diagram165 / 178
Optional reading after the main conclusion and inference refresher. Compare visual evidence with generated answers, then inspect a small diagnostic suite.
Ask:
Answer: Optional reading after the main conclusion and inference refresher. Compare visual evidence with generated answers, then inspect a small diagnostic suite.
BACKUP C · EVALUATION
A fluent sentence can have no visual support
What color is the bicycle?
Reference: No bicycle is visible.
Recorded baseline: “The bicycle is red.”
Fluent ≠ grounded.
How does visual information become context for next-token prediction?
Original teaching example / diagram166 / 178
Optional evaluation reading after the main conclusion. The displayed raw answer was measured in the earlier six-case browser run and is preserved in output/verification/live-model-results.json. The rebuilt lab also records this preset with the fixed decoding settings.
Ask: Fluent ≠ grounded.
Answer: The displayed raw answer was measured in the earlier six-case browser run and is preserved in output/verification/live-model-results.json. The rebuilt lab also records this preset with the fixed decoding settings.
BACKUP C · EVALUATION
Measured check: change only the image.
What animal is shown?
Dog
There is a black dog in the foreground.
Cat
A cat is visible.
Blank
A squirrel.
Recorded SmolVLM-256M answers: a separate trained model.
How does visual information become context for next-token prediction?
SmolVLM-256M · model card167 / 178
Optional evaluation reading after the main conclusion. Evaluate image sensitivity with the separate trained SmolVLM-256M browser baseline. The same prompt is used with a dog, a cat and a blank input. These are actual saved answers with the lab prompt and chat template; they are not generations from the untrained notebook wiring. Blank means a white image passed through the same image processor, not omission of the image input. Responses test sensitivity to image changes; they do not by themselves establish reliable grounding. Full exact records and metadata are in results/vlm_lab_outputs.json.
Ask: Recorded SmolVLM-256M answers: a separate trained model.
Answer: Evaluate image sensitivity with the separate trained SmolVLM-256M browser baseline. The same prompt is used with a dog, a cat and a blank input. These are actual saved answers with the lab prompt and chat template; they are not generations from the untrained notebook wiring. Blank means a white image passed through the same image processor, not omission of the image input. Responses test sensitivity to image changes; they do not by themselves establish reliable grounding. Full exact records and metadata are in results/vlm_lab_outputs.json.
BACKUP C · EVALUATION
Keep a small diagnostic suite
| Image | Fixed question | Reference |
|---|---|---|
| Dog | What animal is this? | Dog |
| Desk | Is the laptop plugged in? | Yes, visible cable connected |
| Shapes | What is immediately left of the mug? | Red ball |
| Invoice | What is the invoice number? | ES667-042 |
| Chart | Which month has the highest value? | March |
| Coffee | What color is the bicycle? | No bicycle visible |
Preserve the raw answer, reveal the reference, then judge support.
How does visual information become context for next-token prediction?
Original teaching example / diagram168 / 178
Optional evaluation reading after the main conclusion. Dog, desk, spatial, invoice, chart and false-premise questions span distinct failure modes. Mark supported / partial / unsupported in the lab. Six items are a classroom diagnostic, not benchmark performance.
Ask: Preserve the raw answer, reveal the reference, then judge support.
Answer: Dog, desk, spatial, invoice, chart and false-premise questions span distinct failure modes. Mark supported / partial / unsupported in the lab. Six items are a classroom diagnostic, not benchmark performance.
BACKUP C · EVALUATION
Different benchmarks probe different capabilities
Choose the evaluation from the capability you need.
How does visual information become context for next-token prediction?
OCRBench · DocVQA · ChartQA · MathVista · MMMU · MMBench · MM-Vet · HallusionBench169 / 178
71–73 min. Representative benchmark families, not current rankings. MMMU covers 30 subjects; MathVista emphasizes visual mathematical reasoning. MMBench and MM-Vet test different broad or integrated capabilities. Multi-turn and multi-image interaction need additional protocols.
Ask: Would high OCR performance establish good spatial reasoning?
Answer: No. The capabilities and failure modes differ.
BACKUP C · EVALUATION
Inspect the questions before interpreting a score
Read: What is the invoice ID?
Calculate: March minus January?
Reason: What is x?
Reject: What colour is the bicycle?
Authored classroom examples, not copied benchmark items.
A wrong answer may come from perception, reasoning, or accepting a false premise.
How does visual information become context for next-token prediction?
Original teaching example / diagram170 / 178
73–74 min. Ask students to localize the error: wrong extracted number versus wrong subtraction, for example. The benchmark names motivate task families; these four examples are not official items.
Ask: How could you separate a chart-reading error from an arithmetic error?
Answer: First ask for the two values, then ask for their difference.
BACKUP C · EVALUATION
Use a metric that matches the answer format
| Output / use | Measure | What still needs inspection |
|---|---|---|
| Fixed answer | Accuracy | Ambiguity and answer normalization |
| Document text | Exact / normalized string match; ANLS | OCR errors and layout dependence |
| Open explanation | Human or specified model rubric | Judge bias and unsupported details |
| Grounding coordinates | IoU / pointing accuracy | Object identity and spatial accuracy |
| Deployment | Latency, memory, output tokens/s | Hardware and decoding settings |
Report the evaluation protocol along with the number.
How does visual information become context for next-token prediction?
DocVQA171 / 178
74–75 min. Recall@K is relevant to retrieval systems such as CLIP, not the default metric for generated answers. ANLS is average normalized Levenshtein similarity; DocVQA uses a thresholded normalized edit-similarity convention. Do not treat model grading as ground truth.
Ask: Report the evaluation protocol along with the number.
Answer: 74–75 min. Recall@K is relevant to retrieval systems such as CLIP, not the default metric for generated answers. ANLS is average normalized Levenshtein similarity; DocVQA uses a thresholded normalized edit-similarity convention. Do not treat model grading as ground truth.
BACKUP D · MODEL DETAILS
Model details
Original architectures and further training choices.
Use these diagrams when a model-specific question comes up.
How does visual information become context for next-token prediction?
Original teaching example / diagram172 / 178
Backup D groups the original Flamingo and BLIP-2 paper diagrams with further training choices. The broad comparison remains in the main lecture.
Ask:
Answer: Backup D groups the original Flamingo and BLIP-2 paper diagrams with further training choices. The broad comparison remains in the main lecture.
BACKUP D · MODEL DETAILS
Flamingo: a Visual Language Model for Few-Shot Learning
Jean-Baptiste Alayrac · Jeff Donahue · Pauline Luc · et al.
Read the paper ↗How does visual information become context for next-token prediction?
Flamingo · Alayrac et al., 2022173 / 178
Optional paper detail. Use after the main lecture, or open from the slide map when a student asks about this model. Original Figure 3 from arXiv 2204.14198v1, surrounded by editable teal course callouts. The original PNG is unchanged. Follow the numbered leaders rather than reading every paper label at once. Read bottom to top: each image enters an NFNet-F6 CNN; its feature grid enters a Perceiver Resampler, producing 64 vectors. The two branches depict separate image instances using shared model weights. Text markers preserve where images occur in the interleaved prompt; token IDs are embedded before entering the language stack. The added gated cross-attention reads visual memory using text queries, with a mask controlling which preceding image can be read. Vision is not prepended as 64 ordinary text embeddings in this architecture. The frozen LM blocks process the updated text states and a vocabulary head predicts the next token; the pink box shows the resulting example continuation, not a single token. The head is abstracted in the original diagram. Blue/snowflake means frozen pretrained parameters; purple denotes trained additions. Teal highlights are our annotations, not a third paper module type. Gated cross-attention and dense updates recur between LM blocks; implementation details remain in the paper.
Ask: Point to the modules that implement the connection we just derived.
Answer: Vision encoder: Each image becomes a grid of features. Perceiver Resampler: Return 64 visual vectors per image. Text input: Tokenize and embed words and image markers. Visual lookup: Text queries read visual summaries through gated cross-attention. Language model: Update text states and predict the next token through the vocabulary head. Paper colors: Blue and snowflakes mean pretrained and frozen; purple blocks are trained here.
BACKUP D · MODEL DETAILS
BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models
Junnan Li · Dongxu Li · Silvio Savarese · Steven Hoi
Read the paper ↗1 · Idea 3 · learned-query summaries
32 learned queries produce 32 image-dependent output vectors.
2 · Idea 1 · prefix for OPT (top)
Project the summaries; prepend them to text embeddings.
3 · Bottom: encoder–decoder
Visual vectors + text enter the encoder; its decoder generates the answer.
How does visual information become context for next-token prediction?
BLIP-2 · Li et al., 2023174 / 178
Optional paper detail. Use after the main lecture, or open from the slide map when a student asks about this model. Original Figure 3 from arXiv 2301.12597v3, showing the second generative-pretraining stage. The top OPT route maps to our compressed visual-prefix connection. The lower FlanT5 route conditions the language encoder, so it is not the same decoder-only interface. The fully connected layer changes vector width after Q-Former compression. Query outputs depend on the image, while the learned query parameters are shared. Image encoder and LLM remain frozen in this stage; Q-Former and the connecting projection are trained. The first representation-learning stage and its objectives are described elsewhere in the paper; the simple learned-reader diagram was not a full Q-Former specification.
Ask: Point to the modules that implement the connection we just derived.
Answer: Idea 3 · learned-query summaries: 32 learned queries produce 32 image-dependent output vectors. Idea 1 · prefix for OPT (top): Project the summaries; prepend them to text embeddings. Bottom: encoder–decoder: Visual vectors + text enter the encoder; its decoder generates the answer.
BACKUP D · MODEL DETAILS
Further training can change how the model answers
Behaviour
Instruction following
Preference optimisation
Safer responses
Evidence use
Better grounding data
Hard negative examples
Missing-evidence responses
The basic inference target remains image-conditioned next-token prediction.
How does visual information become context for next-token prediction?
Original teaching example / diagram175 / 178
65–66 min. Optional post-training is a single-slide preview. Do not claim every model uses every method. Return to the original conditional distribution.
Ask: The basic inference target remains image-conditioned next-token prediction.
Answer: 65–66 min. Optional post-training is a single-slide preview. Do not claim every model uses every method. Return to the original conditional distribution.
BACKUP E · SOURCES
Sources
Model papers and evaluation references.
How does visual information become context for next-token prediction?
Original teaching example / diagram176 / 178
Backup E collects references. Detailed image credits and local measurement provenance remain in SOURCES.md.
Ask:
Answer: Backup E collects references. Detailed image credits and local measurement provenance remain in SOURCES.md.
BACKUP E · SOURCES
Sources · architectures and browser implementation
CLIP · Radford et al., 2021
https://arxiv.org/abs/2103.00020
LLaVA · Liu et al., 2023
https://arxiv.org/abs/2304.08485
Flamingo · Alayrac et al., 2022
https://arxiv.org/abs/2204.14198
BLIP-2 · Li et al., 2023
https://arxiv.org/abs/2301.12597
SmolVLM-256M · model card
https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct
Official Transformers.js browser example
https://github.com/huggingface/transformers.js-examples/tree/main/smolvlm-webgpu
Oxford-IIIT Pet · CC BY-SA 4.0
https://www.robots.ox.ac.uk/~vgg/data/pets/
Primary sources; no leaderboard scores are used in this lecture.
How does visual information become context for next-token prediction?
Original teaching example / diagram177 / 178
Source links checked 1 October 2026. Full provenance and limitations are in SOURCES.md. Sources describe named architectures; drawings are original simplifications.
Ask: Primary sources; no leaderboard scores are used in this lecture.
Answer: Source links checked 1 October 2026. Full provenance and limitations are in SOURCES.md. Sources describe named architectures; drawings are original simplifications.
BACKUP E · SOURCES
Sources · evaluation
OCRBench
https://arxiv.org/abs/2305.07895
DocVQA
https://arxiv.org/abs/2007.00398
ChartQA
https://arxiv.org/abs/2203.10244
MathVista
https://arxiv.org/abs/2310.02255
MMMU
https://arxiv.org/abs/2311.16502
MMBench
https://arxiv.org/abs/2307.06281
MM-Vet
https://arxiv.org/abs/2308.02490
HallusionBench
https://arxiv.org/abs/2310.14566
The local six-image suite is an instructional diagnostic, not one of these benchmarks.
How does visual information become context for next-token prediction?
Original teaching example / diagram178 / 178
Benchmark examples in the deck are authored analogues and are not official samples. Do not compare the six-case result against published benchmark scores.
Ask: The local six-image suite is an instructional diagnostic, not one of these benchmarks.
Answer: Benchmark examples in the deck are authored analogues and are not official samples. Do not compare the six-case result against published benchmark scores.