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.

Newfoundland dog from the ViT and CLIP lectures

How does visual information become context for next-token prediction?

Oxford-IIIT Pet · CC BY-SA 4.001 / 178

Teaching notes

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

Image and text independently become 512D unit vectors. The image ViT reads CLS; the causal text Transformer reads EOT. Their dot product is the match score.“a photo of a dog”Image ViTFull self-attentionFinal CLS state → LayerNormLearned projection → unit normalizationu · 512 coordinatesText TransformerCausal self-attentionFinal EOT state → LayerNormLearned projection → unit normalizationv · 512 coordinatesu · vcosine

CLIP compares an image vector with a supplied text vector.

CLIP · Radford et al., 2021 · Previous lecture · CLIP02 / 178

Teaching notes

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

A batch supplies image rows and text columns. Scaled dot products form a score matrix. Paired cells supply row and column targets; their average loss updates both shared encoder branches, both projections and the score scale.Observed pairsShared encodersUnit vectors“a cat”“a dog”“a car”Image encoder+ projectionText encoder+ projectionUVS = α U Vᵀcolumns: textT1T2T3I1●··I2·●·I3··●Paired cells are the targetsRows+ columns→ lossAverage → backpropagateUpdate both encoders, both projections and the score scale.

The matching image–caption pair is the target in both directions.

CLIP · Radford et al., 2021 · Previous lecture · CLIP03 / 178

Teaching notes

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

Three applications of frozen CLIP: match an image to supplied descriptions, match supplied text to gallery images, or compare a normalized after-minus-before image-vector difference with candidate words.Name an imageImage → unit vector uu · vdogu · vcatRank supplied descriptionsSearch with words“a dog”Text → unit vector vRank gallery images by uᵢ · vDescribe a changebefore → bafter → aUnit image vectorsd = unit(a − b)d · vhatd · vboatRank candidate changesReuse the frozen encoders. Choose which vectors to compare.

New descriptions give us new choices without retraining the encoders.

CLIP · Radford et al., 2021 · Previous lecture · CLIP04 / 178

Teaching notes

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

Same dog image, two concrete tasks. CLIP compares descriptions supplied in advance and selects a dog from a dog, a cat and a car. The new task supplies only the image and Describe this dog, with no answer choices. A generative VLM includes a language decoder and writes the illustrative reply A black, long-haired dog is outdoors token by token. The shown reply is authored, not a measured model output.CLIP · WE SUPPLY THE POSSIBLE DESCRIPTIONSa doga cata carCLIP comparisonScores each optionBest match: “a dog”Chosen from our listGENERATIVE VLM · WE SUPPLY AN IMAGE + A QUESTIONDescribe this dog.No answer choices supplied.Generative VLMLanguage decoderA black, long-haireddog is outdoors.Reply generated token by tokenIllustrative reply · not a measured model output

A language decoder writes the reply, using the image as context.

CLIP · Radford et al., 2021 · Previous lecture · CLIP05 / 178

Teaching notes

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.

Original teaching example / diagram06 / 178

Teaching notes

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?

Is the laptop plugged in?

QUESTION

Is the laptop plugged in?

Original teaching example / diagram07 / 178

Teaching notes

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?

Is the laptop plugged in?

REFERENCE ANSWER

Is the laptop plugged in?

Yes. A cable connects the laptop to the socket.

Original teaching example / diagram08 / 178

Teaching notes

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?

Is the laptop plugged in?

ARCHITECTURAL REQUIREMENT

Is the laptop plugged in?

Yes. A cable connects the laptop to the socket.

Trace a connection between objects.

Original teaching example / diagram09 / 178

Teaching notes

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

What is immediately left of the mug?

QUESTION

What is immediately left of the mug?

Original teaching example / diagram10 / 178

Teaching notes

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

What is immediately left of the mug?

REFERENCE ANSWER

What is immediately left of the mug?

The red ball.

Original teaching example / diagram11 / 178

Teaching notes

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

What is immediately left of the mug?

ARCHITECTURAL REQUIREMENT

What is immediately left of the mug?

The red ball.

Keep object identity and spatial relations.

Original teaching example / diagram12 / 178

Teaching notes

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

How many apples are outside the bowl?

QUESTION

How many apples are outside the bowl?

Original teaching example / diagram13 / 178

Teaching notes

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

How many apples are outside the bowl?

REFERENCE ANSWER

How many apples are outside the bowl?

Three.

Original teaching example / diagram14 / 178

Teaching notes

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

How many apples are outside the bowl?

ARCHITECTURAL REQUIREMENT

How many apples are outside the bowl?

Three.

Represent multiple objects and the region that selects them.

Original teaching example / diagram15 / 178

Teaching notes

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

What is the invoice ID?
What percentage of the subtotal is GST?

QUESTION

What is the invoice ID?
What percentage of the subtotal is GST?

Original teaching example / diagram16 / 178

Teaching notes

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

What is the invoice ID?
What percentage of the subtotal is GST?

REFERENCE ANSWER

What is the invoice ID?
What percentage of the subtotal is GST?

ES667-042. GST is 180 / 1000 × 100 = 18%.

Original teaching example / diagram17 / 178

Teaching notes

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

What is the invoice ID?
What percentage of the subtotal is GST?

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.

Original teaching example / diagram18 / 178

Teaching notes

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

Which month is highest?
How much higher is March than January?

QUESTION

Which month is highest?
How much higher is March than January?

Original teaching example / diagram19 / 178

Teaching notes

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

Which month is highest?
How much higher is March than January?

REFERENCE ANSWER

Which month is highest?
How much higher is March than January?

March. The difference is 45 µg/m³.

Original teaching example / diagram20 / 178

Teaching notes

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

Which month is highest?
How much higher is March than January?

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.

Original teaching example / diagram21 / 178

Teaching notes

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

What is x?

QUESTION

What is x?

Original teaching example / diagram22 / 178

Teaching notes

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

What is x?

REFERENCE ANSWER

What is x?

x = 5, using the marked right angle and sides 3 and 4.

Original teaching example / diagram23 / 178

Teaching notes

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

What is x?

ARCHITECTURAL REQUIREMENT

What is x?

x = 5, using the marked right angle and sides 3 and 4.

Combine diagram evidence with a mathematical rule.

Original teaching example / diagram24 / 178

Teaching notes

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

What changed from A to B?

QUESTION

What changed from A to B?

Original teaching example / diagram25 / 178

Teaching notes

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

What changed from A to B?

REFERENCE ANSWER

What changed from A to B?

The chair moved to the right; the cup disappeared.

Original teaching example / diagram26 / 178

Teaching notes

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

What changed from A to B?

ARCHITECTURAL REQUIREMENT

What changed from A to B?

The chair moved to the right; the cup disappeared.

Compare evidence across images.

Original teaching example / diagram27 / 178

Teaching notes

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

Where should I click to disable notifications?

QUESTION

Where should I click to disable notifications?

Original teaching example / diagram28 / 178

Teaching notes

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

Where should I click to disable notifications?

REFERENCE ANSWER

Where should I click to disable notifications?

The blue toggle on the Notifications row.

Original teaching example / diagram29 / 178

Teaching notes

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

Where should I click to disable notifications?

ARCHITECTURAL REQUIREMENT

Where should I click to disable notifications?

The blue toggle on the Notifications row.

Locate a control relative to its label.

Original teaching example / diagram30 / 178

Teaching notes

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

What is the hottest measured region?

QUESTION

What is the hottest measured region?

Original teaching example / diagram31 / 178

Teaching notes

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

What is the hottest measured region?

REFERENCE ANSWER

What is the hottest measured region?

Row 3, column 4: 62 °C.

Original teaching example / diagram32 / 178

Teaching notes

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

What is the hottest measured region?

ARCHITECTURAL REQUIREMENT

What is the hottest measured region?

Row 3, column 4: 62 °C.

Read a scale and local measurements.

Original teaching example / diagram33 / 178

Teaching notes

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

What color is the bicycle?

QUESTION

What color is the bicycle?

Original teaching example / diagram34 / 178

Teaching notes

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

What color is the bicycle?

REFERENCE ANSWER

What color is the bicycle?

No bicycle is visible.

Original teaching example / diagram35 / 178

Teaching notes

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

What color is the bicycle?

ARCHITECTURAL REQUIREMENT

What color is the bicycle?

No bicycle is visible.

Let visual evidence override the wording of the question.

Original teaching example / diagram36 / 178

Teaching notes

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 familyInformation needed
Counting / spatialMultiple objects and their arrangement
OCR / chartsFine detail, labels, values and units
UI / multiple imagesLocations and correspondence across views
False premiseEvidence that can contradict the prompt

Would one global CLIP vector always be enough?

Original teaching example / diagram37 / 178

Teaching notes

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

Newfoundland dog

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.

SmolVLM-256M · model card · SmolVLM-500M · model card · Official Transformers.js browser example38 / 178

Teaching notes

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.

Original teaching example / diagram39 / 178

Teaching notes

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

Beyond Attention decoder-only portrait. The illustrative prefix Raghav goes to becomes input embeddings e1, e2 and e3 with position information. L decoder blocks contain causal self-attention plus residual and an MLP plus residual. Each position reads itself and earlier positions. All three states are updated, but the last updated e3 supplies vocabulary scores to choose the illustrative next token school. Append school and repeat. Normalization is omitted; word-sized token boundaries and the continuation are illustrative, not a measured model trace.Raghavgoestoinput e1input e2input e3Input eᵢ = token embedding + position · word-sized tokens shown for illustrationCausal self-attention + residualMLP + residual× LblocksEach token readsitself + its pastAllowed attentione₁e₂e₃Vocabulary headScores → choose schoolAppend school → Raghav goes to school → repeat.

Read the last updated state → score the vocabulary → append a token → repeat.

Original teaching example / diagram40 / 178

Teaching notes

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

Two useful pieces, not connected yet. The dog image passes through a full-attention ViT encoder to N image feature rows h1 through hN, with intermediate rows abbreviated. The description prompt uses the same decoder architecture as the preceding Beyond Attention recap: token embeddings and positions, repeated causal attention and MLP blocks, then the last updated text state and vocabulary head. No separate text encoder is needed. The next section derives how visual rows can become decoder context. Word-sized text token boundaries are illustrative; normalization is omitted.VISION ENCODERViT encoderFull self-attentionh₁h₂hN…N image feature rowsLANGUAGE DECODERDescribeinput e1thisinput e2dog.input e3Causal self-attention + residualMLP + residual× Lblockse₃Vocabulary head → next tokenHow can these image rows become context for this decoder?

We have both components. Next, choose how the decoder accesses the visual rows.

Original teaching example / diagram41 / 178

Teaching notes

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.

Original teaching example / diagram42 / 178

Teaching notes

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

All N projected patch vectors are concatenated with embeddings of question tokens and answer tokens generated so far, then passed through causal self-attention, decoder updates and a vocabulary headIMAGE PATHVision encoder (ViT)Full self-attention over patchesProject every rowV1V2VN…All N patch rowsTEXT PATHWhat animal is shown?+ answer so far (empty at first)Tokenizer → IDsEmbeddingsONE INPUT SEQUENCE OF VECTORSQuestion embeddingsAnswer-so-far embeddingsCausal self-attention: image + textMLP + residual updatesDECODERText reads earlierimage and text rows.Vocabulary headNext token

Keep all N patch vectors in this design; N depends on the image grid.

LLaVA · Liu et al., 202343 / 178

Teaching notes

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

A vision encoder supplies N feature vectors as separate memory. Question and answer-so-far tokens become text embeddings. The language decoder uses causal self-attention for text and cross-attention to read image memory before decoder updates and the vocabulary head predict the next token.IMAGE PATHVision encoder (ViT)Full self-attention over patchesVISUAL MEMORYh1h2h3hN…The encoder outputs stay available.224 × 224 image, 16 × 16 patches:196 patch rows; 197 if CLS is kept.N depends on the encoder setup.TEXT PATHWhat animal is shown?+ answer so far (empty at first)Tokenizer → IDs → embeddingse1e2eT…TEXT DECODERCausal self-attention: read textCross-attention: read imageSequence-to-sequence:the image is the source.MLP + residual updatesVocabulary head → next token

As in translation: encode the source, then let the text decoder read its states.

Transformer · Vaswani et al., 2017 · ViT · Dosovitskiy et al., 202044 / 178

Teaching notes

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

The image becomes all N ViT patch features. M learned queries cross-attend to those features to produce M image-dependent summaries. Alternative A projects the summaries and prepends them to text embeddings for causal self-attention. Alternative B keeps summaries as memory that the text decoder reads through cross-attention before its vocabulary head.ViT encoderFull self-attentionh1h2hN…All N patch featuresLearned summarizerCross-attentionM learned query vectorsQueries read all patch rows.S1…SMM < N summariesImage-dependentA · Prefix: concatenate vectorsProject summariesS1 … SMQuestion + answer so fartokenize → embedv1 … vMe1 … eTDecoder: causal self-attentionVocabulary head → next tokenB · Decoder reads separate memoryQuestion + answer so fartokenize → embed → e1 … eTSummary memoryS1 … SMCausal self-attentionK, VQCross-attentionVocabulary head → next token

Compression reduces N image rows to M summaries; either decoder connection remains possible.

BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 202245 / 178

Teaching notes

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

IdeaHigh-level decisionThen we will explain…
1 · Visual prefixPut visual vectors before text.How to make them fit the decoder input.
2 · Separate memoryLet language read the image.How a text state retrieves visual information.
3 · Shorter summaryUse fewer visual vectors.How learned readers make the summaries.

Ideas 1 and 2 choose the access route. Idea 3 can be used with either.

Original teaching example / diagram46 / 178

Teaching notes

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

Complete prefix architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderProject each visual vectorV1V2…VNSame rows, new width.All N patch rows; middle rows omitted.LANGUAGE: GROWING TEXTQuestion + answer so farV1V2…VNText embeddingsCausal self-attention + residualMLP + residualVocabulary head → next token

One sequence; the same causal self-attention can use both kinds of context.

LLaVA · Liu et al., 202347 / 178

Teaching notes

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?

JobWhy it is needed
1. Keep image feature vectorsThe decoder needs access to visual evidence.
2. Match the decoder input widthAll input rows must have the same number of coordinates.
3. Place them before the questionCausal attention can read earlier context.

We already have the decoder. Now build its visual input.

Original teaching example / diagram48 / 178

Teaching notes

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

A numbered twelve-patch image enters a ViT encoder. All twelve contextual feature rows h1 through h12 are shown. Full self-attention updates each patch row using information from all patches; no single row is guaranteed to preserve every image detail.12345678910111212 patches in this exampleIllustrative 3 × 4 gridViT encoderFull self-attentionALL 12 PATCH ROWSh1h2h3h4h5h6h7h8h9h10h11h12Each row is a feature vector.Self-attention updates each patch rowusing information from all patches.

Patch 1 has row h1, patch 2 has row h2, and so on through patch 12.

ViT · Dosovitskiy et al., 202049 / 178

Teaching notes

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

A numbered twelve-patch image enters a ViT encoder. All twelve contextual feature rows h1 through h12 are shown. The CLS token participates inside the encoder, but its output summary row is left out when forwarding the patch sequence in this design.12345678910111212 patches in this exampleIllustrative 3 × 4 gridViT encoderFull self-attentionALL 12 PATCH ROWSh1h2h3h4h5h6h7h8h9h10h11h12Each row is a feature vector.CLS · summary stateLeave out after encoding

Forward all 12 patch rows to the projector; leave out the CLS output.

ViT · Dosovitskiy et al., 202050 / 178

Teaching notes

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

An invoice question needs small text and numbers. ViT provides one CLS summary output plus twelve contextual patch rows in this illustrative example. For the LLaVA-style patch-only connection taught here, leave out the CLS output after encoding and retain all twelve patch rows h1 through h12. Project every retained row and use those twelve vectors as the visual prefix alongside text embeddings. The CLS token still participates inside the vision encoder. Retaining patch features provides multiple spatially indexed feature rows; this choice does not guarantee OCR accuracy. Twelve illustrates the selection rule, not an actual model token count.The question needs image detailsInvoice ID? GST percentage?SELECT FROM THE ViT OUTPUTSCLS output12 patch rowsh1h2h3h4h5h6h7h8h9h10h11h12Leave out after encodingKEEP EVERY PATCH ROWProjecteach rowVisual prefix12 vectorsCombine with text embeddingsfor the language decoder.Illustration: 12 patch rows; CLS left out.

This design sends all N patch rows to the projector and omits the CLS output.

LLaVA · Liu et al., 2023 · ViT · Dosovitskiy et al., 202051 / 178

Teaching notes

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 dog image is divided into all twelve numbered patches. Patch embedding and positions create twelve input tokens. A ViT with full self-attention produces twelve contextual patch rows. All twelve rows and both feature columns are drawn in H V, an illustrative 12 by 2 matrix. Patch five, token p5 and output vector h5 are highlighted. CLS and the batch dimension are omitted.One image1234567891011123 × 4 = 12 patchesPatch embed+ positionsPatch tokensp1p2p3p4p5p6p7p8p9p10p11p1212 tokensViT encoderFull attentionPatch rows only;CLS not shown.Feature 1Feature 2h1h1,1h1,2h2h2,1h2,2h3h3,1h3,2h4h4,1h4,2h5h5,1h5,2h6h6,1h6,2h7h7,1h7,2h8h8,1h8,2h9h9,1h9,2h10h10,1h10,2h11h11,1h11,2h12h12,1h12,2Hᵥ: 12 × 2Illustrative grid and feature width; no measured values.dᵥ = 2 columnsN = 12rowsh5= one row vector2 feature values in this exampleHᵥ has shapeN × dᵥ

One patch position → one output row. Each row has dᵥ feature values.

ViT · Dosovitskiy et al., 2020 · Oxford-IIIT Pet · CC BY-SA 4.052 / 178

Teaching notes

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

Word IDs become embedding vectors before the decoder; image vectors enter at the same input interfaceWhat animal is shown?Tokenizer → IDsEmbedding lookupe1e2e3e4e5e6Inside the decoder, text is already a sequence of vectors.Visual vectors can enter at this vector interface.

Text IDs become embeddings before reaching the Transformer blocks.

Original teaching example / diagram53 / 178

Teaching notes

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

The dog image supplies N toy two-coordinate image rows. The question and answer so far supply T toy three-coordinate text embeddings. Their widths differ, so they cannot yet be stacked as decoder input.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Can these rows enter the same decoder?h121e11022 coordinates per image row3 coordinates per text row≠ widthWe need to turn each image row into a 3-coordinate vector.

To form one input sequence, every vector must have the decoder’s input width.

Original teaching example / diagram54 / 178

Teaching notes

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 same image and text remain visible. N by 2 image features multiply one shared 2 by 3 projector to give N by 3 visual vectors. T by 3 text embeddings remain unchanged.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Insert a shared projector on the image pathImage features HᵥN × 22 × 3Projector WₚN × 3Visual vectors ZText stays ET × 3Z = Hᵥ Wₚ · Keep N rows. Change 2 coordinates to 3.

The projector changes N × 2 image features into N × 3 visual vectors.

Original teaching example / diagram55 / 178

Teaching notes

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

Projector worked example, step 1. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. h1 is one of the image rows above. Its two coordinates are 2 and 1.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×Shared projectorWₚ2 × 3=???z11 × 3: same width as e1h1 is one of the image rows above. Its two coordinates are 2 and 1.

Take one 2-coordinate row from the image feature sequence.

Original teaching example / diagram56 / 178

Teaching notes

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

Projector worked example, step 2. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. Each of the three columns of Wₚ will make one output coordinate.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=???z11 × 3: same width as e1Each of the three columns of Wₚ will make one output coordinate.

Each column makes one of the 3 decoder-input coordinates.

Original teaching example / diagram57 / 178

Teaching notes

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

Projector worked example, step 3. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. First column: how much of 2, and how much of 1, should we use?IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=???z11 × 3: same width as e1First column: how much of 2, and how much of 1, should we use?

Which input coordinates does this column combine?

Original teaching example / diagram58 / 178

Teaching notes

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

Projector worked example, step 4. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. First coordinate: 2 × 1 + 1 × 0 = 2IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=2??z11 × 3: same width as e1First coordinate: 2 × 1 + 1 × 0 = 2

The first output coordinate copies the first input in this toy map.

Original teaching example / diagram59 / 178

Teaching notes

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

Projector worked example, step 5. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. Second column: use the same input [2, 1] again.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=2??z11 × 3: same width as e1Second column: use the same input [2, 1] again.

Now use the same input row with the second column.

Original teaching example / diagram60 / 178

Teaching notes

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

Projector worked example, step 6. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. Second coordinate: 2 × 0 + 1 × 1 = 1IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=21?z11 × 3: same width as e1Second coordinate: 2 × 0 + 1 × 1 = 1

The second output coordinate copies the second input in this toy map.

Original teaching example / diagram61 / 178

Teaching notes

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

Projector worked example, step 7. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. Third coordinate: 2 × 1 + 1 × 1 = 3IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=213z11 × 3: same width as e1Third coordinate: 2 × 1 + 1 × 1 = 3

The third output coordinate adds the two inputs in this toy map.

Original teaching example / diagram62 / 178

Teaching notes

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

Projector worked example, step 8. The same image, encoder, image feature table, question, answer prefix and text embedding table remain visible. The image row [2, 1] has become [2, 1, 3]. The text rows stay as they are.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Zoom into h1211 × 2×101011Wₚ2 × 3=213z11 × 3: same width as e1The image row [2, 1] has become [2, 1, 3]. The text rows stay as they are.

The row [2, 1, 3] fits beside the 3-coordinate text embeddings.

Original teaching example / diagram63 / 178

Teaching notes

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

Apply the same 2 by 3 matrix to every image row. [2,1] becomes [2,1,3], [1,3] becomes [1,3,4], and [0,2] becomes [0,2,2]. All N rows remain. All projected rows now have the same width as the text embeddings.IMAGE → FEATURE VECTORSViT encoderAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Every image rowh121h213…⋮⋮hN02N × 22 × 3×Same Wₚ101011N × 3=All N projected rowsz1213z2134…⋮⋮⋮zN022Width now matches EN is unchanged.

N rows stay N rows; every projected row now has 3 coordinates.

Original teaching example / diagram64 / 178

Teaching notes

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?

The same image has a three-by-four grid: twelve patch rows. The two-feature vision row and three-feature text row are chosen teaching widths from the preceding example, not measured values. Multiplying H V of shape 12 by 2 by the shared 2 by 3 projector produces Z with three features per row. Predict its row count.Same image grid123456789101112N = 3 × 4 = 12 patch rowsFrom our toy ViTExample row h₁21dᵥ = 2 features per rowIllustrative width, as beforeFrom the text embeddingsExample row e₁102dₗ = 3 features per rowIllustrative width, as beforeImage features Hᵥ12 × 2Shared projector Wₚ2 × 3×Projected features Z? × 3=How many rows will Z have?

Predict the output shape before advancing.

Oxford-IIIT Pet · CC BY-SA 4.065 / 178

Teaching notes

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 same image has a three-by-four grid: twelve patch rows. The two-feature vision row and three-feature text row are chosen teaching widths from the preceding example, not measured values. Multiplying H V of shape 12 by 2 by the shared 2 by 3 projector produces Z of shape 12 by 3. Row count is unchanged.Same image grid123456789101112N = 3 × 4 = 12 patch rowsFrom our toy ViTExample row h₁21dᵥ = 2 features per rowIllustrative width, as beforeFrom the text embeddingsExample row e₁102dₗ = 3 features per rowIllustrative width, as beforeImage features Hᵥ12 × 2Shared projector Wₚ2 × 3×Projected features Z12 × 3=12 rows stay 12 rows. Each row changes from 2 features to 3.

The projector changes each row’s features and keeps every patch position.

Oxford-IIIT Pet · CC BY-SA 4.066 / 178

Teaching notes

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

The image rows are projected to width three and stacked before width-three text embeddings, including the question and the answer generated so far. The ViT uses full attention. In this LLaVA-style design, the joined N plus T rows feed a language decoder whose causal mask applies from the first projected image row z1, including both image and text positions. An alternative model can allow bidirectional attention within the image block while keeping text causal. The vocabulary head predicts text tokens. Projected visual rows are continuous features, not word IDs. The decoder mask does not erase image context already mixed by the vision encoder.IMAGE → FEATURE VECTORSViT encoderFull attentionAll N patch rowsh121h213…⋮⋮hN02Hᵥ: N × 2TEXT → EMBEDDING VECTORSWhat animal is shown?Answer so far: “A black”Tokenize → IDs → embede1102e2021…⋮⋮⋮eT210E: T × 3Toy widths and values; not measured from this image or text. Middle rows omitted.Image → shared Wₚ → ZN projected rowsz1213…⋮⋮⋮zN022+ T text rows(N + T) × 3e1102…⋮⋮⋮eT210Language decoderCausal from z1 · LLaVA-styleAlternative: full image block + causal text.Head → next token

Our LLaVA-style example uses causal attention from the first image position.

Original teaching example / diagram67 / 178

Teaching notes

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

The same image gives twelve patch rows. A shared projector changes each row from two features to three. All twelve projected vectors are kept before the formatted conversation.Same 12 patchesViT encoder12 rows × 2 featuresShared projector2 → 3 features per rowV1V2V3V4V5V6V7V8V9V10V11V12THE VISUAL PREFIX · ALL 12 ROWSEach Vᵢ is a vector with 3 features in our running example.Next, put the formatted conversation after these vectors.

Keep all 12 patch rows; each row has the decoder’s input width.

Oxford-IIIT Pet · CC BY-SA 4.068 / 178

Teaching notes

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

A chat template marks the user message and the start of the assistant response. Both markers are already in the supplied prompt. The causal decoder and language head predict the first answer token. USER and ASST are simplified labels; exact templates and token counts depend on the model.What animal is shown?Apply chat templateV1 … V12USERWhat animal is shown?User message beginsASSTAssistant reply begins hereThe template supplies both markers.Causal decoder + LM headItExample next tokenUSER / ASST are teaching labels; a real role marker can span several tokens.

The template supplies the role markers; generation continues after ASST.

Chat templates · Hugging Face69 / 178

Teaching notes

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

In the illustrative single-token role format, USER, What and ASST each map to a vocabulary ID, which selects a row of the same embedding table E. All embeddings have decoder width d L, shown as three features. New rows are initialized once and learn if trainable; existing rows are loaded from the trained checkpoint for inference.Formatted textVocabulary IDsSelected rows of table EUSERWhatASSTOne token per label here.idᵤid_widₐAn ID selects a vocabulary row.E[idᵤ]E[id_w]E[idₐ]dₗ = 3 features in this exampleInitialize new rowsLearn when trainableLoad for inferenceExisting tokens reuse learned rows. Adding a new token requires a new initialized row.

A special role token is a vocabulary entry with its own learned embedding row.

Chat templates · Hugging Face · Vocabulary embeddings · Transformers70 / 178

Teaching notes

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

Twelve visual vectors occupy zero-based positions zero to eleven. In this illustrative word-level tokenization, USER occupies twelve, four question tokens occupy thirteen to sixteen, and ASST occupies seventeen. Role tokens use the same positional scheme as other positions. Additive schemes add a position vector; LLaMA instead applies RoPE to queries and keys in attention. The final ASST state goes through the language head to predict It; if selected, its embedding occupies position eighteen on the next input.ONE SEQUENCE OF VECTORSV1 … V12USERWhat animal is shown?ASSTIllustration: 12 visual rows + 1 USER + 4 question tokens + 1 ASST.0 … 111213 14 15 1617PositionUSER is at 12; ASST is at 17. Positions do not restart at a role boundary.Position-aware causal self-attentionAdditive scheme: xᵢ = E[token IDᵢ] + Pᵢ, including role tokens.LLaMA uses RoPE: position i rotates Qᵢ and Kᵢ inside attention.ItLM head →Next inputposition: 18

Role tokens have sequence positions and participate in the same causal attention.

Chat templates · Hugging Face · LLaMA · embedding lookup and RoPE71 / 178

Teaching notes

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?

Course mask grammar: queries in rows, keys in columns, allowed coloured cells and blocked grey cellsCurrent text queryASSISTANT positionV1✓V2✓V3✓What✓animal✓?✓All six are earlier context.No future text position is available.

The assistant’s state can use both the picture and the question.

Original teaching example / diagram72 / 178

Teaching notes

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

Two decoder attention masks for the same illustrative sequence z1, z2, z3, T1, T2, T3, A. Rows are queries; columns are keys. z1 through z3 are projected image vectors from one image; T1 through T3 are prompt text and A is the assistant-start position. The LLaVA-style default is lower triangular over the entire sequence: z1 reads itself and z2 reads z1 and itself. The image-block alternative also permits the three upper-triangular image-to-image edges, shown in amber: z1 can then read z2 and z3, and z2 can read z3. The text rows are identical in both masks. Neither permits image positions or earlier text to read a future answer. ViT full self-attention has already contextualized the image features before either decoder mask. Gemma 3 provides a real image-block example; the drawing abstracts local windows, special markers and multiple images.z: image · T: prompt · A: assistant start. ViT mixed the image features earlier.OUR DEFAULT · LLaVA-STYLECausal across image + textKeys →Query ↓z1z2z3T1T2T3Az1z2z3T1T2T3Az1 reads itself; z2 reads z1 + z2.ALTERNATIVE · e.g. GEMMA 3Full image block; causal textKeys →Query ↓z1z2z3T1T2T3Az1z2z3T1T2T3Az1 can read z1, z2 and z3.Colored:allowedGrey:blockedAmber:extra links

Both keep text causal. The difference is which image rows can read each other.

LLaVA · Liu et al., 2023 · Gemma 3 · image-block attention73 / 178

Teaching notes

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

Complete prefix architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderProject each visual vectorV1V2…VNSame rows, new width.All N patch rows; middle rows omitted.LANGUAGE: GROWING TEXTQuestion + answer so farV1V2…VNText embeddingsCausal self-attention + residualMLP + residualVocabulary head → next token

Projected patch vectors occupy earlier positions; they do not become word IDs.

LLaVA · Liu et al., 202374 / 178

Teaching notes

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 ↗
Original LLaVA architecture: image Xv enters a vision encoder, features Zv pass through projection W to visual embeddings Hv, and these join instruction embeddings Hq in a language model producing response Xa.
Original Figure 1 · Image features and instruction embeddings enter the same language model.

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.

LLaVA · Liu et al., 202375 / 178

Teaching notes

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

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.IDEA 1 · ALL PATCH ROWS → VISUAL PREFIXReal shapes / token IDs · illustrative answerViT patch features196 rows × 192 featuresLinear projector192 → 768Visual input matrix V196 × 768Notebook: (224 ÷ 16)² = 196 patches · DeiT-Tiny width 192 · DistilGPT2 width 768Question: What animal is shown? ↵ Answer:Question24361:25·What1867·animal5044·is318·shown3402?30↵198Answer33706:2510 real token IDs; · marks a leading space, ↵ marks the newline.Embedding lookup E[IDs] → 10 × 768196 visual rows10 text rows206 × 768

196 visual rows + 10 prompt embeddings = 206 decoder positions.

Oxford-IIIT Pet · CC BY-SA 4.076 / 178

Teaching notes

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

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.IDEA 1 · ALL PATCH ROWS → VISUAL PREFIXHand-set toy head · not model scoresh₂₀₅: 1 × 768W_vocab: 768 × 50,25750,257 logitsh₂₀₅ is the final prompt “:” state after decoder blocks and final normalization.Tiny worked head: choose h = [1, 2], four vocabulary entries, and zero bias.12h: 1 × 2×·A11·The10·dog00EOS-10W: 2 × 4 · hand-set weightshW → logits·A3·The1·dog0EOS-1For ·A: 1 × 1 + 2 × 1 = 3

Each output column scores one vocabulary entry using the same final state.

Oxford-IIIT Pet · CC BY-SA 4.077 / 178

Teaching notes

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

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.IDEA 1 · ALL PATCH ROWS → VISUAL PREFIXHand-set toy head · not model scoressoftmax: exponentiate each score, then divide by their sumTokenLogitexp(logit)Probability·A3·The1·dog0EOS-120.0862.7181.0000.368Sum = 24.1720.83100.11250.04140.0152Sum = 1; displayed values rounded.Greedy choice: “ A” → token ID 317 → embedding lookup next

The four-entry calculation is a toy; the real vocabulary has 50,257 entries.

Oxford-IIIT Pet · CC BY-SA 4.078 / 178

Teaching notes

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

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.IDEA 1 · ALL PATCH ROWS → VISUAL PREFIXReal shapes / token IDs · illustrative answerWhat animal is shown?Answer so far: emptySelected “ A” · ID 317E[317]: one 768-wide rowSelection returns an ID.The decoder receives its embedding.196 image vectors10 prompt embeddingsE[317]new position 206207 positions → same causal decoder → next token

Append E[317] for “ A”; the image and question stay fixed.

Oxford-IIIT Pet · CC BY-SA 4.079 / 178

Teaching notes

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

The same Newfoundland image, supplied to the ViT

image
One image

question = “What animal is shown?”

answer_so_far = “It is a” (empty at the start)

One next-token step · high-level pseudocodeShapes · batch omitted
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 ID

causal_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.

LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.080 / 178

Teaching notes

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?

Original teaching example / diagram81 / 178

Teaching notes

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

Complete cross architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderh1h2h3hN…Memory = N encoder feature rowsBatch shape: B × N × dVB: batch size · N: rows · dV: row widthLANGUAGE: GROWING TEXTQuestion + answer so farText embeddings + positionsCausal self-attention + residualCross-attention + residualK, VMLP + residualVocabulary head → next token

Causal self-attention reads text; cross-attention reads image memory.

Transformer · Vaswani et al., 201782 / 178

Teaching notes

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

Complete translation architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: ENGLISHRaghav goes to school in DelhiEnglish encoderh1h2h3h4h5Keep the source states.Schematic; vector boxes show a subset.LANGUAGE: GROWING TEXTHindi prefix generated so farText embeddings + positionsCausal self-attention + residualCross-attention + residualK, VMLP + residualVocabulary head → next token

English source states stayed available while the Hindi prefix grew.

Original teaching example / diagram83 / 178

Teaching notes

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

Complete cross architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderh1h2h3hN…Memory = N encoder feature rowsBatch shape: B × N × dVB: batch size · N: rows · dV: row widthLANGUAGE: GROWING TEXTQuestion + answer so farText embeddings + positionsCausal self-attention + residualCross-attention + residualK, VMLP + residualVocabulary head → next token

The source changes. The decoder still reads a separate memory.

Original teaching example / diagram84 / 178

Teaching notes

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?

The same Newfoundland photo supports two authored question and answer-prefix pairs. What animal is shown? It is a: dog. What is behind the dog? Behind it are: trees. These reference continuations motivate why the language query must depend on the question and answer so far. No measured model output or attention map is shown.ONE IMAGEA dog, with trees behind it.QUESTION AWhat animal is shown?Answer so far: “It is a”Reference continuation: dogQUESTION BWhat is behind the dog?Answer so far: “Behind it are”Reference continuation: treesAuthored examples;not a recorded model run.

Different questions need different visual evidence from the same image.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201785 / 178

Teaching notes

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

The actual dog image is split into the same twelve patches. A ViT gives twelve contextual image rows h1 to h12. Separate learned projections W K and W V give twelve paired keys and values. The question What animal is shown and the answer prefix It is a are tokenized, embedded and processed with causal self-attention. Select h t at the final supplied token a; this contextual state can use the question, It is and a itself. It is not the raw embedding of a. W Q projects this selected state into q. One head and one current text position are shown; vector coordinates are not measured or named semantic attributes.SAME IMAGE1234567891011123 × 4 = 12 patchesViT encoderFull attentionh1h2h3h4h5h6h7h8h9h10h11h12HᵥW_Kk1k2k3k4k5k6k7k8k9k10k11k12Keys KW_Vv1v2v3v4v5v6v7v8v9v10v11v12Values VRow i supplies both kᵢ and vᵢ.What animal is shown?Answer so far: “It is a”Tokenize → embedCausal attention → hₜ at “a”W_Qq

Each image row supplies a key and value; the contextual state at “a” supplies q.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201786 / 178

Teaching notes

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

For the concrete question What animal is shown and answer prefix It is a, the last supplied token a is highlighted. An arrow starts from that token position and leads to its contextual hidden state after causal self-attention; this state has access to the earlier question and It is, as well as a itself. Project this state through W Q to obtain the one query shown. The query is compared with all twelve image keys. Scaled dot products followed by softmax give twelve weights alpha1 through alpha12. Each weight multiplies the paired value vector; the sum is a visual feature message c. Output projection, the residual update of the state at a and remaining decoder computation precede the vocabulary head, which predicts the next token after a. Dog is an authored reference continuation, not a decoded attention value or measured prediction. The supplied a is not the prediction target in this step. No attention weights have been fabricated.What animal is shown?Answer so far:ItisaState at “a” → W_Q → qAfter causal self-attentionIncludes the question + “It is”.1 · Compare q with every keyk1k2k3k4k5k6k7k8k9k10k11k122 · Softmax gives weights α₁ … α₁₂, which sum to 1α1α2α3α4α5α6α7α8α9α10α11α12×v1×v2×v3×v4×v5×v6×v7×v8×v9×v10×v11×v12c = Σᵢ αᵢ vᵢUpdate “a” state → LM headdogReference continuation

Update the state at “a”; the language head predicts the next token after it.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201787 / 178

Teaching notes

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

Compute q from the final available text position. For What animal is shown and It is a, the a position has assumed h_t=[1,2], giving q=[1,0]. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoQUESTION + ANSWER: READABLE TOKEN LABELSWhatanimalisshown?ItisaTokenizer → IDs → embeddings + position handlingCausal self-attention → current text state hₜhₜ (1 × 2)12×W_Q (2 × 2)010.5-0.5=q (1 × 2)10q = [1, 2] W_Q = [1, 0]Toy hₜ is assumed after the text sublayer; W_Q stays fixed.

Use the final supplied text state, after causal self-attention, to make q.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201788 / 178

Teaching notes

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

The twelve patch positions map to twelve numeric feature rows. K = H_V W_K; W_K swaps the two coordinates in this toy, so row 6 [0,3] becomes key [3,0]. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoViT output Hᵥ12 rows × 2 features130221321430511603713821910100211021220W_K01102 × 2Keys K12 rows × 2 features103212312403511630731812901102011201202Hᵥ W_K = KRow 6: [0, 3] W_K = [3, 0]

Apply W_K to every encoder row; inspect patch 6 without dropping the other rows.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201789 / 178

Teaching notes

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 twelve patch positions map to twelve numeric feature rows. V = H_V W_V; row 6 [0,3] becomes value [3,6]. K and V are different projections of the same source rows. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoViT output Hᵥ12 rows × 2 features130221321430511603713821910100211021220W_V10122 × 2Values V12 rows × 2 features130232332430522636746832910102411241220Hᵥ W_V = VRow 6: [0, 3] W_V = [3, 6]

The key determines the match; its paired value supplies the features to mix.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201790 / 178

Teaching notes

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

q=[1,0] at the supplied a position is compared with all twelve keys. q dot k6=3, then scaling by sqrt(2) gives 2.121. Every numbered image patch has a numeric score badge, colored border and translucent overlay matched to its table score. A shared light-to-dark teal scale covers 0.000 to 2.121; patches 6 and 7 tie for the highest score. The overlay and score column appear together. These are pre-softmax similarity scores, not probabilities or a measured model heatmap. No patch has been removed or selected by argmax. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoq = [1, 0] · one head has dₖ = 2Patch i123456789101112Key kᵢ[0, 3][1, 2][1, 2][0, 3][1, 1][3, 0][3, 1][1, 2][0, 1][2, 0][2, 0][0, 2]q · kᵢ011013310220Score sᵢ = (q · kᵢ)/√20.0000.7070.7070.0000.7072.1212.1210.7070.0001.4141.4140.00010.00020.70730.70740.00050.70762.12172.12180.70790.000101.414111.414120.000Score scale · before softmax0.0000.7071.4142.121Patch 6: (1 × 3 + 0 × 0) / √2 = 2.121

One query × twelve keys gives twelve scores; every patch stays in the computation.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201791 / 178

Teaching notes

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

Exponentiate each score then divide by the sum of all twelve exponentials. Alpha sums to one before rounding. Patch 6 weight is 0.225. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoαᵢ = exp(sᵢ) / Σⱼ exp(sⱼ)Patch i123456789101112Score sᵢ0.0000.7070.7070.0000.7072.1212.1210.7070.0001.4141.4140.000exp(sᵢ)1.0002.0282.0281.0002.0288.3428.3422.0281.0004.1134.1131.000Weight αᵢ0.0270.0550.0550.0270.0550.2250.2250.0550.0270.1110.1110.027Patch 6: 8.342 / 37.023 = 0.225Σᵢ αᵢ = 1 exactly before rounding; these are not word probabilities.

Divide each exponential by the sum of all twelve exponentials.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201792 / 178

Teaching notes

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

Every alpha_i weights v_i from the same image position. All weights, value coordinates and contribution coordinates are displayed with exactly three decimal places, including zeros, using fixed-width digits so vector coordinates align down the columns. Products and sums use unrounded values. Sum all twelve weighted vectors to get c=[2.867, 4.031]. This is a feature vector, not a word ID. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoc = αV = Σᵢ αᵢ vᵢPatch i123456789101112Weight αᵢ0.0270.0550.0550.0270.0550.2250.2250.0550.0270.1110.1110.027Value vᵢ[3.000, 0.000][3.000, 2.000][3.000, 2.000][3.000, 0.000][2.000, 2.000][3.000, 6.000][4.000, 6.000][3.000, 2.000][1.000, 0.000][2.000, 4.000][2.000, 4.000][2.000, 0.000]Contribution αᵢvᵢ[0.081, 0.000][0.164, 0.110][0.164, 0.110][0.081, 0.000][0.110, 0.110][0.676, 1.352][0.901, 1.352][0.164, 0.110][0.027, 0.000][0.222, 0.444][0.222, 0.444][0.054, 0.000]Add all 12 rows → c = [2.867, 4.031]Shown to 3 decimal places; products and sums use full precision.

All twelve contributions add up to one visual message for the current text position.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201793 / 178

Teaching notes

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”

Compute q from the final available text position. For What is behind the dog and Behind it are, the are position has assumed h_t=[3,0], giving q=[0,3] with the exact same W_Q. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What is behind the dog?ANSWER SO FARBehinditareRead the state at “are”.Toy numbers · one headNot measured from this photoQUESTION + ANSWER: READABLE TOKEN LABELSWhatisbehindthedog?BehinditareTokenizer → IDs → embeddings + position handlingCausal self-attention → current text state hₜhₜ (1 × 2)30×W_Q (2 × 2)010.5-0.5=q (1 × 2)03q = [3, 0] W_Q = [0, 3]Toy hₜ is assumed after the text sublayer; W_Q stays fixed.

The image, keys, values and W_Q stay fixed; the text state changes.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201794 / 178

Teaching notes

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

Zoom into patch 6. Its key stays [3, 0]. The animal query has dot product 3.0; the background query has dot product 0.0. All twelve memory rows still participate. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoZOOM INTO PATCH 6 · SAME KEY IN BOTH LOOKUPSh6 = [0, 3] → k6 = [3, 0]ANIMAL QUESTION[1, 0] · [3, 0] = 3Scaled score: 3 / √2 = 2.121BACKGROUND QUESTION[0, 3] · [3, 0] = 0Scaled score: 0 / √2 = 0.000This is one row zoom. Both lookups still use all 12.

A fixed image key can match different language queries differently.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201795 / 178

Teaching notes

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

Zoom into patch 1. Its key stays [0, 3]. The animal query has dot product 0.0; the background query has dot product 9.0. All twelve memory rows still participate. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoZOOM INTO PATCH 1 · SAME KEY IN BOTH LOOKUPSh1 = [3, 0] → k1 = [0, 3]ANIMAL QUESTION[1, 0] · [0, 3] = 0Scaled score: 0 / √2 = 0.000BACKGROUND QUESTION[0, 3] · [0, 3] = 9Scaled score: 9 / √2 = 6.364This is one row zoom. Both lookups still use all 12.

The query changes which keys receive large scores.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201796 / 178

Teaching notes

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

Twelve keys are reused. Compute separate scores and softmax distributions for q=[1,0] and q=[0,3]. Each distribution sums to one. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What is behind the dog?ANSWER SO FARBehinditareRead the state at “are”.Toy numbers · one headNot measured from this photoSAME 12 KEYS · DIFFERENT LANGUAGE QUERIESPatch123456789101112Key kᵢ[0, 3][1, 2][1, 2][0, 3][1, 1][3, 0][3, 1][1, 2][0, 1][2, 0][2, 0][0, 2]sᵢ: q = [1, 0]0.0000.7070.7070.0000.7072.1212.1210.7070.0001.4141.4140.000Weight0.0270.0550.0550.0270.0550.2250.2250.0550.0270.1110.1110.027sᵢ: q = [0, 3]6.3644.2434.2436.3642.1210.0002.1214.2432.1210.0000.0004.243Weight0.3960.0470.0470.3960.0060.0010.0060.0470.0060.0010.0010.047Softmax runs separately for each query.The keys did not change. The comparison with those keys did.

Each query gets its own twelve weights; the image memory is reused.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201797 / 178

Teaching notes

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

The same dog photograph is shown twice with the twelve calculated attention weights labeled on their patch positions. These weights are produced by the authored matrices, not extracted from a model. Contextual image rows can contain information from outside the drawn patch; a high weight does not establish a causal explanation or grounding. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.Calculated toy weights on patch positions · not a measured model attention mapWhat animal is shown?It is a → q = [1, 0]10.02720.05530.05540.02750.05560.22570.22580.05590.027100.111110.111120.027Σ weights = 1What is behind the dog?Behind it are → q = [0, 3]10.39620.04730.04740.39650.00660.00170.00680.04790.006100.001110.001120.047Σ weights = 1

Same image and keys; different queries give different mixtures of image values.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201798 / 178

Teaching notes

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

The two queries mix the same twelve value rows into contexts [2.867, 4.031] and [2.94, 0.34]. Neither numeric vector is an English word. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoV STAYS FIXED; EACH QUERY CHOOSES ITS MIXTUREAnimal question · q = [1, 0]c = Σᵢ₌₁¹² αᵢ vᵢ = [2.867, 4.031]All 12 rows; weights from the first softmax.Background question · q = [0, 3]c = Σᵢ₌₁¹² αᵢ vᵢ = [2.94, 0.34]All 12 rows; weights from the second softmax.Different messages can update the language state differently.Neither 2-number vector is the word “dog” or the word “trees”.

Changing q can change the visual message without recomputing K or V.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 201799 / 178

Teaching notes

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

For the animal question, explicitly compute c W_O and h_t plus c W_O. This one-head toy uses decoder width two. A real multi-head layer concatenates head outputs before W_O; normalizations and model-specific gates are omitted. Only the later vocabulary head scores output tokens. All numeric feature states and projection matrices are authored teaching values, not a measured model run. One head and twelve image positions; actual models use much wider states. Readable word labels stand in for tokenizer pieces; role delimiters are omitted.SAME IMAGE · ALL 12 PATCHES123456789101112What animal is shown?ANSWER SO FARItisaRead the state at “a”.Toy numbers · one headNot measured from this photoRETURN THE VISUAL MESSAGE TO THE TEXT PATHc = [2.867, 4.031] (1 × 2)c ×100.51=[4.883, 4.031]W_O (2 × 2)h′ₜ = hₜ + cW_O= [1, 2] + [4.883, 4.031] = [5.883, 6.031]Remaining decoder → vocabulary head → next token

The visual message changes the state at “a”; a later vocabulary head scores words.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017100 / 178

Teaching notes

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

c≈[2.867,4.031]c\approx[2.867,4.031]

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?

Original teaching example / diagram101 / 178

Teaching notes

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

Complete cross architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderh1h2h3hN…Memory = N encoder feature rowsBatch shape: B × N × dVB: batch size · N: rows · dV: row widthLANGUAGE: GROWING TEXTQuestion + answer so farText embeddings + positionsCausal self-attention + residualCross-attention + residualK, VMLP + residualVocabulary head → next token

Visual lookup changes the language state; the language head chooses words.

Original teaching example / diagram102 / 178

Teaching notes

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

Same image and prompt: visual context in sequence versus visual context in separate memorySame image. Same question: What animal is shown?A · VISUAL PREFIXV1V2V3questionASSTCausal self-attentionB · SEPARATE MEMORYVisual K, VText query QCross-attention

In-sequence visual context or a separate visual memory.

Original teaching example / diagram103 / 178

Teaching notes

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

The same Newfoundland image, supplied to the vision encoder

image
One image

question = “What animal is shown?”

answer_so_far = “It is a” (empty at the start)

One next-token step · high-level pseudocodeShapes · batch omitted
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 ID

cross_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.

Transformer · Vaswani et al., 2017 · Oxford-IIIT Pet · CC BY-SA 4.0104 / 178

Teaching notes

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?

Original teaching example / diagram105 / 178

Teaching notes

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?

Actual notebook input: a 224 by 224 crop divided into all 196 patches; after dropping CLS, DeiT-Tiny outputs 196 vectors, each with 192 dimensions. The projector maps each 192-dimensional vector to a 768-dimensional vector. There are still 196 vectors. The exact complete text Question: What animal is shown? newline Answer: It is a has 13 DistilGPT2 token IDs and therefore 13 text embedding vectors, each with 768 dimensions. The combined decoder input has 209 positions, each represented by a 768-dimensional vector. Counts are specific to this preprocessing and tokenizer.ONE IMAGE · AFTER RESIZE / CROP224 × 224 pixelsCOMPLETE TEXT SUPPLIED TO THE MODELQuestion: What animal is shown?Answer: It is a16 × 16 pixels / patchDeiT-Tiny / ViTFull self-attention224 ÷ 16 = 14 per side14 × 14 = 196 patchesDrop CLS; keep all patches.Project each vector196 vectors192 dimensions each196 vectors768 dimensions eachDistilGPT2 tokenizer → these 13 piecesQuestion:·What·animal·is·shown?↵Answer:·It·is·a· = leading space ↵ = one newline token13 IDs → 13 text embeddings768 dimensions per vector196 image vectors13196 visual + 13 text = 209 positions in the causal decoder

Projection changes each vector: 192 → 768 dimensions. We still have 196 vectors.

Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020106 / 178

Teaching notes

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?

Idea 1 with a visual prefix. The same 196 projected image vectors and 13 text embeddings give 209 positions. Before the first answer token, every decoder layer processes all 209 input states. Each layer stores keys and values for the 196 image positions as well as the text. Each later answer token supplies a new query that reads those image keys and values and the available text, including itself. Caching avoids recomputing previous states; it does not remove their storage or attention-read cost. Layer 1, Layer 2 and Layer L depict a stack with middle layers omitted.196 image vectors+13 text vectors209 decoder positions1 · PROCESS THE INPUTLayer 1209 statesLayer 2209 statesLayer L209 statesWork before the first answer token2 · STORE THE IMAGE K, V196 image keys196 image valuesIn every layer’s cache+ keys and values for the text3 · READ THEM AGAINNew token’s state → qRead 196 image K, V+ the available text, including itselfCaching reuses K and V; it does not remove the image positions.

Every image position adds decoder work, cache storage and later attention reads.

Key/value caching · Hugging Face107 / 178

Teaching notes

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

Reuse the same 196 image rows and 13 text embeddings. Choose eight learned readers, as in the notebook. Their outputs are eight image-dependent feature mixtures, not eight selected patches. Project them to width 768 and use a causal-decoder prefix of 8 plus 13 equals 21 positions. Compare with 209 on the same scale. Image encoding is still required; this is not a total runtime speedup claim.SAME IMAGE + ViT196patch rowsSAME TEXTQuestion: What animal is shown?Answer: It is a13 text embeddingsLearned summarizerChoose M = 8 readersAll 196 rows remain available.z1z2z3z4z5z6z7z88 summary vectorsProject 8 rows to width 768 → prepend them before the same 13 text embeddingsFull prefix: 196 + 13 = 209196 image vectors13Short prefix: 8 + 13 = 21813188 fewer decoder positions to processA smaller cache to store and read · same scale

Summarize 196 image vectors into 8: fewer decoder positions, with evidence we must preserve.

Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020108 / 178

Teaching notes

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

Complete compressed architecture using the source-left decoder-right grammar of the earlier attention lectureSOURCE: IMAGEVision encoderSummarize + projectv1v2v3v4Fewer rows, then match width.Schematic; vector boxes show a subset.LANGUAGE: GROWING TEXTWhat animal is shown? + prefixv1v2v3v4Text embeddingsCausal self-attention + residualMLP + residualVocabulary head → next token

Replace the row-wise projector with a learned summary followed by projection.

Original teaching example / diagram109 / 178

Teaching notes

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

Build the notebook summarizer. Same processed dog image, all 196 patch rows, each 192 features. Grid cells denote full vectors, not individual feature coordinates. Encode every patch before choosing the summary length.Same image14 × 14 patchesDeiT-TinyViT encoderAll 196 patch rowsOne cell = one vector192 features per vectorThe source is unchanged.We have encoded every patch.Now choose how manysummary rows to return.The grid tracks patch positions; the feature matrix is Hᵥ ∈ ℝ¹⁹⁶ˣ¹⁹².ViT full attention lets each patch row use information from the rest of the image.

The source memory is the encoded image: one feature vector per patch position.

Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020110 / 178

Teaching notes

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?

Stored query slots S and image-dependent summary vectors Z are different. Eight trainable 192-dimensional starting slots are shared across images. An attention reader uses the current image features to produce eight new 192-dimensional output vectors. A summary token is one continuous output vector, not an English summary, vocabulary ID or prescribed object label.STARTING QUERY SLOTS · Ss1s2s3s4s5s6s7s88 stored vectors × 192 numbersShared across imagesImage features HAttention readerCOMPUTED SUMMARIES · Zz1z2z3z4z5z6z7z88 output vectors × 192 numbersNew values for each image“Summary token” = one vector in Z. It has no vocabulary ID or assigned object name.

A stored query slot asks for information; a summary vector contains the image-dependent result.

BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022111 / 178

Teaching notes

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

Exact slot initialization from the teaching notebook, written with the same factors in a different order. Normal random values have mean zero and standard deviation 0.02. nn.Parameter registers the bank for optimization when included in the optimizer. The leading singleton is a shared batch dimension; the same bank is broadcast to every example. Eight is the chosen summary length and 192 is this reader width. Only S has 1536 numbers; attention and output projections have additional trainable weights. A trained checkpoint loads learned parameters rather than redrawing them.CHOOSE 8 SLOTSUSE THE READER WIDTH: 192A design choice, not an object count192 scalar coordinates in every slotS = nn.Parameter(0.02 * torch.randn(1, 8, 192))1 shared bank · 8 rows · 192 coordinates per rows1s2s3s4s5s6s7s88 × 192 = 1,536 trainable numbers in SInitialize once → train → save → reuse. Do not redraw S for each image.An existing trained checkpoint loads S. Our notebook creates a new, untrained reader.

Choose the count and width; start with small random numbers, then learn them.

BLIP-2 · Li et al., 2023 · BLIP-2 · learned-query initialization112 / 178

Teaching notes

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?

The exact notebook dimensions: MultiheadAttention has three heads with 64 coordinates per head. Slot states S, 8 by 192, supply projected Q, 8 by 64 in the highlighted head. Image H, 196 by 192, supplies separate K and V, each 196 by 64 per head. Each key and value pair comes from the same contextual image row. Follow q1 next. The image question is not an input to this minimal single-layer summarizer. Biases are omitted in the diagram notation but included by PyTorch.3 HEADS · 192 ÷ 3 = 64 COORDINATES PER HEADs1s2s3s4s5s6s7s8Stored S: 8 × 192W_Qq1q2q3q4q5q6q7q8Q: 8 × 64Image H196 × 192W_KW_VK · 196 × 64One key per patchV · 196 × 64One value per patchkᵢ and vᵢ come from the same image row hᵢ.Next: follow q₁, a 64-dimensional query, through this one head.The question is added later. It is not an input to this minimal summarizer.

Slots supply queries; the current image supplies all keys and values.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch113 / 178

Teaching notes

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

A soft lookup compares q1 with all 196 image keys in this one width-64 head. The scaled score for image position i is q1 dot ki divided by sqrt(64). Softmax over the 196 positions produces nonnegative weights summing to one. Subscript 1 identifies the query and i identifies the image position. This is not vocabulary embedding lookup, nearest-neighbor selection, or retrieval of a stored English summary. Middle key positions are abbreviated, not excluded. No numeric image attention weights are claimed.FOLLOW ONE SLOT · ONE HEADq₁ · 1 × 64Compare q₁ with every image keyk₁k₂…k₁₉₆score₁score₂…score₁₉₆q₁ · kᵢ / √64196 scalar scoresSoftmax over all 196 scoresα₁₁, α₁₂, …, α₁,₁₉₆ · sum = 1No vocabulary lookup and no top-1 choice. These weights will mix image values.

Compute 196 scores → softmax → 196 weights that sum to one.

Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch114 / 178

Teaching notes

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

For q1 in one head, multiply every 64-dimensional value vector by its paired scalar weight and sum all 196 weighted values coordinatewise. This yields a 64-dimensional head mixture. Each of three heads uses its own projected queries, keys, values and weights. Concatenate the three mixtures for the same slot into 192 coordinates, then apply the shared output projection WO to obtain z1. Repeat for all eight slots to obtain Z of shape 8 by 192. No semantic field or word is assigned to a slot.SAME q₁ · SAME HEAD · ALL 196 VALUESα₁₁×v₁+α₁₂×v₂+…×…+α₁,₁₉₆×v₁₉₆Each vᵢ has 64 coordinates. Add the vectors coordinate by coordinate.c₁ = Σᵢ α₁ᵢ vᵢ · 1 × 64Head 1 · 64Head 2 · 64Head 3 · 64Three mixtures for the same slotJoin: 192W_Oz₁ · 1 × 192Repeat for all 8 slots → Z has 8 rows, each a 192-dimensional summary.

One slot produces one summary vector, after combining the three attention heads.

Transformer · Vaswani et al., 2017 · MultiheadAttention · PyTorch115 / 178

Teaching notes

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

A toy with all twelve image positions and two reader queries, each width two. The queries [1,0] and [0,3] are assumed fixed outputs of the slot projection, not language questions. All twelve key and value rows are reused from the earlier numeric attention example. Every number is deliberately hand-set, not measured from the photo. This toy differs from the notebook configuration of 196 patch rows, eight slots and width 192.TOY: 12 PATCHES → 2 SUMMARIES123456789101112Assume two projected reader queries:q₁ = [1, 0]q₂ = [0, 3]SAME IMAGE MEMORY AS BEFOREPatch iKey kᵢValue vᵢ1[0, 3][3, 0]2[1, 2][3, 2]3[1, 2][3, 2]4[0, 3][3, 0]5[1, 1][2, 2]6[3, 0][3, 6]7[3, 1][4, 6]8[1, 2][3, 2]9[0, 1][1, 0]10[2, 0][2, 4]11[2, 0][2, 4]12[0, 2][2, 0]Q: 2 × 2 K, V: 12 × 2 → two output vectors, each with 2 featuresHand-set values, not photo measurements

For this small calculation, choose two readers; give both all twelve memory rows.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017116 / 178

Teaching notes

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

Two fixed reader queries attend to the same twelve hand-set key/value rows. Each overlay displays all twelve computed softmax weights for its query. Each weighted mixture produces one output feature vector. Stacking them gives two output rows. The first vector is [2.867, 4.031] and the second is [2.94, 0.34]. Output projection is identity for this one-head toy; residuals and MLPs are omitted. These are calculated toy maps, not measured photo attention or semantic labels for the readers.READER 1 · q₁ = [1, 0]Match = 1 × the key’s first coordinate123456789101112Toy head · α = softmax(qKᵀ / √2) · output projection = I · not measured attention0.0270.0550.0550.0270.0550.2250.2250.0550.0270.1110.1110.027z₁ = Σᵢ α₁ᵢ vᵢ ≈ [2.867, 4.031]READER 2 · q₂ = [0, 3]Match = 3 × the key’s second coordinate1234567891011120.3960.0470.0470.3960.0060.0010.0060.0470.0060.0010.0010.047z₂ = Σᵢ α₂ᵢ vᵢ ≈ [2.94, 0.34]12 value rows → 2 weighted mixtures · each reader can use every patch

A fixed number of readers gives a fixed number of summary vectors.

Oxford-IIIT Pet · CC BY-SA 4.0 · Transformer · Vaswani et al., 2017117 / 178

Teaching notes

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

The reader reduces 196 image rows to eight summary rows while retaining outer width 192. It uses all image rows, not eight selected patches. A separate linear projector then maps each 192-dimensional summary to a 768-dimensional language-model input vector without changing the eight-row count. Add text embeddings afterward. These dimensions are the teaching notebook configuration, not universal constants.IMAGE FEATURES Hh₁h₂h₃⋮h₁₉₆196 × 192Reader8 slotsSUMMARIES Zz1z2z3z4z5z6z7z88 × 192ProjectorVISUAL PREFIXp1p2p3p4p5p6p7p88 × 768Summarize: fewer vectors. Project: wider vectors, same count.Add text embeddings only after this step. No English caption is created in the reader.

196 × 192 → 8 × 192 → 8 × 768. Count and width change in different steps.

BLIP-2 · Li et al., 2023 · MultiheadAttention · PyTorch118 / 178

Teaching notes

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

PyTorch · inside the summarizerShapes / comments
# Construct once; register these in your modelSetup
S = nn.Parameter(0.02 * torch.randn(1, 8, 192))1 × 8 × 192
reader = nn.MultiheadAttention(192, 3, batch_first=True)3 heads × 64
projector = nn.Linear(192, 768)192 → 768
# Each forward call: H contains encoded patchesH: B × 196 × 192
slots = S.expand(H.shape[0], -1, -1)B × 8 × 192
Z, weights = reader(slots, H, H,Query, key, value inputs
average_attn_weights=False)Keep weights per head
visual = projector(Z)B × 8 × 768

reader 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.

MultiheadAttention · PyTorch119 / 178

Teaching notes

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?

One possible training recipe for the minimal reader, not a claim about the complete BLIP-2 or Flamingo recipe. Freeze the vision encoder and language-model parameters. Train stored slots S, attention Q/K/V and output projections, and the projector to language width. Reference answer tokens are used with teacher forcing and answer-only cross-entropy. Gradients pass backward through the frozen language model and visual prefix into the connector; freezing LM parameters must not disable autograd through its inputs. No ground-truth summary vector or manually named slot is provided. Repeated data and optimization shape the useful mixtures. Captions and task-specific question-answer pairs can supply training examples. The following training section explains the loss in detail. The notebook currently initializes this reader but does not train it; this diagram does not report a trained result.Prompt: Describe this image.Reference: A black dog outdoors.ILLUSTRATIVE TRAINING RECIPEViTFIXEDAttention readerUPDATE S + weightsProjectorUPDATELanguage modelFIXEDAnswer-token lossGradients teach S and the reader which mixtures help predict the reference answer.No target z₁…z₈ is supplied. Repeat over many training examples; save the learned reader.

The answer loss trains the slots and reader; we never supply a “correct summary vector”.

BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022120 / 178

Teaching notes

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

Schematic return to the notebook configuration. A dog photograph and a separate invoice image use the same ViT, reader weights and eight stored query slots S. Assume the same 224 by 224 preprocessing for each, yielding 196 patch rows of width 192. Each reader call returns eight image-dependent rows, denoted a1 through a8 or b1 through b8. These labels denote vectors, not measured numeric activations or captions. One input image is handled per example. Project to language width, then concatenate that example’s text and decode. The minimal reader does not receive the text question; other models may additionally condition their query activations on text.A · PHOTOBACK TO THE NOTEBOOK: 196 → 8ViT196 × 192Same readera1a2a3a4a5a6a7a88 rows × 192 featuresSame S: 8 × 192B · INVOICEViT196 × 192Same readerb1b2b3b4b5b6b7b88 rows × 192 featuresSame count; image-dependent contents.Project 8 rows → add question + answer prefix → causal decoder → next token

The summary length stays fixed; its feature values depend on the source image.

Oxford-IIIT Pet · CC BY-SA 4.0 · ViT · Dosovitskiy et al., 2020 · BLIP-2 · Li et al., 2023121 / 178

Teaching notes

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 synthetic invoice contains ID ES667-042, GST 180 rupees and total 1180 rupees. A ViT and eight learned readers yield a symbolic matrix Z with eight rows and 192 feature columns, or 1536 scalar features. All eight rows are shown; ellipses abbreviate middle feature columns. The matrix is a representation sketch, not measured invoice activations. Features can represent details across rows and coordinates; no row has a predefined field label. These dimensions reuse the minimal notebook configuration, not a trained document-reading result. The next slide makes the desired behavior testable with three reference answers.One synthetic invoice imageViT encoder196 patch rowsLearned summarizer8 readers mix those rows192 feature values in each rowz₁z1,1z1,2…z1,192z₂z2,1z2,2…z2,192z₃z3,1z3,2…z3,192z₄z4,1z4,2…z4,192z₅z5,1z5,2…z5,192z₆z6,1z6,2…z6,192z₇z7,1z7,2…z7,192z₈z8,1z8,2…z8,192Z =8 × 192 = 1,536 feature valuesNo row is predefined as “invoice ID”, “GST” or “total”.

A detail can be represented across several rows and feature coordinates.

Original teaching example / diagram122 / 178

Teaching notes

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 same invoice summary Z is reused across three independent prompts. Project its eight 192-wide rows to width 768, tokenize and embed each question and answer so far, concatenate a visual prefix, and apply the causal language decoder and vocabulary head to generate one token at a time. The answer is empty initially for each new question. Desired reference answers are ES667-042 for the invoice ID, 180 rupees for GST, and 1180 rupees for total payable. These answers are transcribed from the synthetic invoice, not measured outputs of the untrained notebook. The question enters after compression in this design. Retention means that the trained decoder can reliably recover needed details from Z and the question; the feature count alone does not guarantee this.SAME SUMMARY ZZ: 8 × 192Project each row8 × 192 → 8 × 768QUESTION + ANSWER SO FARTokenize + embedT text rows, width 7688 visual rows | question + answer embeddingsCausal decoder+ vocabulary headNext token → answerREUSE Z · START A FRESH ANSWER FOR EACH QUESTIONReference answers we want after trainingWhat is the invoice ID?ES667-042How much GST is charged?₹180What is the total payable?₹1,180

The summary is useful when it preserves evidence for the questions we need to answer.

Original teaching example / diagram123 / 178

Teaching notes

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

A simplified three-column comparison. Each model starts with an image and a vision encoder. LLaVA keeps its ViT patch vectors, projects each to the text embedding width, and sends image vectors alongside text through the language model. Flamingo encodes CNN image features, summarizes them with a Perceiver Resampler, and keeps the resulting visual memory separate. Text enters the language model and reads that memory through cross-attention. BLIP-2 uses Q-Former to make a few summary vectors from ViT features, projects those summaries, and sends them alongside text to its OPT language model. Text means the question plus the answer so far. All language models predict the next text token. Exact dimensions, counts, CLS handling, attention internals, training and repeated decoder layers are deliberately left to the speaker notes and optional paper slides. Compression and how language accesses vision are separate choices: both Flamingo and BLIP-2 summarize.LLaVAVision encoderViT patch vectorsFlamingoVision encoderCNN image featuresBLIP-2Vision encoderViT patch vectorsText = question + answer so far. BLIP-2 shows its OPT language-model route.Project the patch vectorsKeep every patch rowImage vectors + textLanguage modelKeep the patch vectors.Pass them alongside the text.Summarize the imagePerceiver ResamplerVisual memoryTextLanguage modelCross-attentionText reads a separate memory.Summarize the imageQ-Former + projectionSummary vectors + textLanguage modelSummarize first.Pass the summary with the text.

LLaVA · Liu et al., 2023 · Flamingo · Alayrac et al., 2022 · BLIP-2 · Li et al., 2023124 / 178

Teaching notes

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.

Two separate inference runs reuse one model. A single amber table contains the same eight stored reader vectors s1 through s8, each of width 192 in the notebook. Dashed amber arrows supply these same parameters to both encode-and-summarize calls. Solid blue arrows carry a dog image in run one and a cat image in run two. The vision-encoder and reader weights are identical across the two runs. The dog produces eight summary vectors a1 through a8; the cat produces eight summary vectors b1 through b8. All summaries have width 192, but their values depend on the input image. The labels are schematic vector names, not words, measured features, or assigned semantic roles. The two photos are processed independently, not jointly. Training can update the reader slots and other trainable weights; ordinary inference does not update model parameters. The notebook reader itself is untrained; learned reader denotes the kind of trainable parameter used by a trained summarizer. The language model is omitted to focus on parameters versus computed visual activations.TWO SEPARATE RUNS · SAME MODELSame learned readers Ss1s2s3s4s5s6s7s8Same vision-encoder and reader weights in both runsRUN 1Encode + summarizea1a2a3a4a5a6a7a8Summary for this dog imageEach a is a 192-dimensional vector.reuseRUN 2Encode + summarizeb1b2b3b4b5b6b7b8Summary for this cat imageSame shape; image-dependent values.Training can update S. Inference reuses S and computes new summaries.

The readers are stored parameters; each image produces its own summary vectors.

Oxford-IIIT Pet · CC BY-SA 4.0125 / 178

Teaching notes

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

The same Newfoundland image, supplied to the vision encoder

image
One image

question = “What animal is shown?”

answer_so_far = “It is a” (empty at the start)

One next-token step · high-level pseudocodeShapes · batch omitted
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 ID

summarizer: 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.

BLIP-2 · Li et al., 2023 · Flamingo · Alayrac et al., 2022 · Oxford-IIIT Pet · CC BY-SA 4.0126 / 178

Teaching notes

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.

Original teaching example / diagram127 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDsWhat animal is shown?The input imageThe input questionA black dog.Written by the teacherThis is the reference answer.Training targets·A·black·dog.EOSID 317ID 2042ID 3290ID 13ID 50256· marks a leading space. EOS says the answer is finished.

The dataset supplies the answer we want the model to learn.

Oxford-IIIT Pet · CC BY-SA 4.0128 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDsPretrained ViT196 × 192 patch featuresNew projector196 × 768 visual vectors10 prompt tokensQuestion: … Answer:196 image rows10 prompt embeddingsJOINPretrained causal decoder → h₂₀₅ → vocabulary head50,257 probabilities · find entry 317 for “ A”

The reference ID tells us which vocabulary probability to inspect.

Oxford-IIIT Pet · CC BY-SA 4.0129 / 178

Teaching notes

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?

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONIllustrative probabilities · not measuredReference target: “ A”From the last “Answer:” statesoftmax over all 50,257 vocabulary scores“ A” · ID 3170.20“ The” · ID 3830.30Other 50,255 entries0.50Select p[317] = 0.20All entries sum to 1.The target stays “ A”.Loss for this target = −ln(0.20) = 1.609If p[317] were 0.80, its loss would be only −ln(0.80) = 0.223.

Low probability on the correct token gives a large loss.

Oxford-IIIT Pet · CC BY-SA 4.0130 / 178

Teaching notes

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?

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONIllustrative probabilities · not measuredQuestion: What animal is shown?Current text ends with: Answer:p(“ A”) = 0.20 · p(“ The”) = 0.30 · suppose “ The” is highestTRAINING · TEACHER FORCINGReference: “A black dog.”Score A using −ln(0.20).Answer:AReference A → predict target blackINFERENCE · GREEDY DECODINGChoose “The”: highest probability.No reference answer is supplied.Answer:TheChosen The → predict the next tokenInference may sample instead of taking the maximum; it still uses its own chosen token.

Training uses the reference token; inference uses the model’s selected token.

Teacher forcing · PyTorch · Greedy decoding and sampling · Hugging Face · Oxford-IIIT Pet · CC BY-SA 4.0131 / 178

Teaching notes

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 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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDsQuestion: What animal is shown?Reference: A black dog.Same image + question in every rowVISIBLE TEXT ENDS WITHNEXT TARGETREAD POSITIONAnswer:·A205Answer: ·A·black206Answer: ·A ·black·dog207Answer: ·A ·black ·dog.208Answer: ·A ·black ·dog .EOS209All prefixes are known → one causal pass computes all five predictions.Each predicting state is blocked from its target and later tokens. · = leading space.

Each position predicts the next reference token using only its allowed prefix.

Oxford-IIIT Pet · CC BY-SA 4.0132 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONIllustrative probabilities · not measuredQuestion: What animal is shown?Reference: A black dog.Reference target·A·black·dog.EOSp(correct target)0.200.400.500.800.90Loss = −ln p1.609For A: −ln(0.20) = 1.6090.9160.6930.2230.105Total answer loss = 3.547Mean answer loss = total ÷ 5 = 0.709Sum before rounding. Image and question targets are excluded from this average.

Score each correct token, then average the five penalties, including EOS.

Oxford-IIIT Pet · CC BY-SA 4.0133 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDs196 image rows + 10 prompt tokens + 5 reference tokens = 211 positionsEach decoder input row has 768 features. Batch size B = 1.196 image vectors10 prompt tokens·A·black·dog.EOSTarget labels at the same positions:−100 means “do not score this target”.−100 at all 206 context positions317204232901350256logits at positions 205–209 → labels at positions 206–210The final prompt “:” predicts the first “ A”. The final EOS logit is unused.

Ignore context labels; still use the image and question as context.

Oxford-IIIT Pet · CC BY-SA 4.0134 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDsQuestion: What animal is shown?Answer: 〈empty〉Predict “ A” at the last prompt “:”Image vectorsQuestion … Answer:A · black · dog · . · EOSThe “:” state can read this context.Future positions: hiddenLoss = −ln p[target ID 317]Target: “ A” · 317We grade answer targets only. The question remains visible to attention.

Attention controls what a state reads. Loss labels select what we grade.

Oxford-IIIT Pet · CC BY-SA 4.0135 / 178

Teaching notes

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

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.TRAIN IDEA 1 · THE SAME IMAGE AND QUESTIONOne authored reference answer · real token IDsFORWARDViT encoderFixed weightsProjectorTrainable weightsCausal LM + headFixed weightsLossAnswer targetsAlso receives prompt + reference embeddings.BACKWARDFrom lossThrough LM operationsProjector gradientThe LM passes the gradient back; only the projector changes.Projector weights ← weights − learning rate × gradient

Frozen LM weights still pass a gradient to the trainable visual connection.

Oxford-IIIT Pet · CC BY-SA 4.0136 / 178

Teaching notes

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

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.TRAIN IDEA 1 · ADD SUPERVISION TO THE SAME FORWARD PASSX =196 image vectors10 question / prompt rows5 reference rows: A black dog . EOSPrepared X: [1, 211, 768] · answer_ids: [1, 5] · one example, no padding.# 1. Ignore context targets (-100); score the reference answer.labels = torch.full(X.shape[:2], -100, device=X.device)labels[:, -answer_ids.shape[1]:] = answer_ids# 2. Predict next tokens and average the five answer losses.loss = lm(inputs_embeds=X, labels=labels).loss# 3. Differentiate through the frozen LM; change the projector.optimizer.zero_grad() # clear previous gradientsloss.backward() # compute projector gradientsoptimizer.step() # update projector weightsSetup: frozen vit + lm; optimizer owns only projector parameters. Keep LM autograd on.

The reference supplies the targets; only the projector weights change.

Oxford-IIIT Pet · CC BY-SA 4.0137 / 178

Teaching notes

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

Both rows describe training in the original LLaVA recipe, using authored dog examples. The dataset supplies captions first, then image-question-answer examples. For each training example, predict each next reference token, compute its loss, and update only the marked weights. Caption training updates the projector while vision and language weights stay fixed. Instruction tuning continues from those weights, keeps vision fixed, and updates the projector and language model. Dashed red paths indicate gradients, including through the fixed language model in stage 1. At inference there is no supplied reference answer: a new image and question condition generated tokens. This overview introduces the next three detailed training diagrams; prompt/reference-prefix inputs are abbreviated here, with causal teacher forcing already explained earlier.1 · TRAIN ON IMAGE–CAPTION PAIRSDescribe this image.Supplied target: A black dog outdoors.Vision encoderProjectorLanguage modelAnswer lossFIXEDUPDATEFIXEDThe dataset supplies captions first, then question–answer examples.Predict each next reference token → measure its loss → update the marked weights.Continue from the stage 1 weights ↓2 · TRAIN ON IMAGE + QUESTION + ANSWERWhat colour is the dog?Supplied target: Black.Vision encoderProjectorLanguage modelAnswer lossFIXEDUPDATEUPDATEAt inference: supply a new image + question; the model generates its own answer.

Captions train the visual connection; varied instructions train the model to answer questions.

LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0138 / 178

Teaching notes

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

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.ORIGINAL LLAVA · STAGE 1 OF 2Authored example · not a model outputPrompt: Describe this image.Reference caption: A black dog outdoors.Vision encoderCLIP ViTProjectornew WPrompt + reference prefixLanguage modelcausal decoderscoresLossNext tokenReferencetargetsWEIGHTS FIXEDUPDATE WEIGHTSWEIGHTS FIXEDGradient passes through the fixed LM.Train only the new projector.

Caption targets train the projector; vision and language weights stay fixed.

LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0139 / 178

Teaching notes

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

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.ORIGINAL LLAVA · BETWEEN THE TWO STAGESAuthored examples · supplied referencesStage 1 checkpointLearned projector + retained vision and LMStart stage 2 from these weightsContinue with the same model.Same imageCAPTION EXAMPLESUPPLIED REFERENCEDescribe this image.A black dog outdoors.INSTRUCTION EXAMPLESWhat colour is the dog?Black.Where is the dog?Outdoors.Different questions → different reference answers.

Stage 2 reuses the trained model and broadens the questions it learns to answer.

LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0140 / 178

Teaching notes

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

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.ORIGINAL LLAVA · STAGE 2 OF 2Authored example · not a model outputQuestion: What colour is the dog?Reference answer: Black.Vision encoderCLIP ViTProjectorlearned WPrompt + reference prefixLanguage modelcausal decoderscoresLossNext tokenReferencetargetsWEIGHTS FIXEDUPDATE WEIGHTSUPDATE WEIGHTSUpdate projector + language model.

The next-token loss stays; the projector and language model can now change.

LLaVA · Liu et al., 2023 · Oxford-IIIT Pet · CC BY-SA 4.0141 / 178

Teaching notes

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.

Original teaching example / diagram142 / 178

Teaching notes

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.

Three model portraits: ViT produces contextual patch features; CLIP ranks descriptions provided by the user; a generative VLM connects image features to a language decoder and its vocabulary head. The shown choices and word dog are illustrative.ViT · REPRESENTp₁p₂…ViT encoderh₁h₂…hNOne vector per patchFull attention mixes image context.CLIP · COMPARE“a dog”, “a cat”ImageencoderTextencoderuv·Best supplied description“a dog”GENERATIVE VLM · WRITEWhat animal?VisionfeaturesDecoderVocab headdogAppendand repeatIllustrative match and generated word; these are model portraits, not measured outputs.

A generative VLM adds a language decoder and a path from the image to that decoder.

ViT · Dosovitskiy et al., 2020 · CLIP · Radford et al., 2021 · LLaVA · Liu et al., 2023143 / 178

Teaching notes

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

Idea 1 projects all N image vectors and prepends them to text. Idea 2 uses text queries to cross-attend to separate image keys and values. Idea 3 uses M learned query vectors to read N image vectors and produce M image-dependent summaries, which can be used with either access route. M is less than N in this compression example. Repeated blocks and MLPs are omitted from this routing overview.Vision encoderh₁h₂…hNN contextual patch vectors1 · PREPENDProject each patch vectorz₁…zNtextDecoderImage + text in one sequence2 · READ MEMORYh₁…hNtextCausal self-attnQK, VCross-attentionText reads the image features3 · SUMMARIZEh₁h₂…hNAttention readers₁…M learnedquery vectorsz₁…zMFewer rows: M < NUse M summaries with 1 or 2Projection changes vector width. Summarization changes row count. Access chooses the path.

Project width. Choose the access path. Optionally shorten the visual sequence.

LLaVA · Liu et al., 2023 · Flamingo · Alayrac et al., 2022 · BLIP-2 · Li et al., 2023144 / 178

Teaching notes

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

Concrete Idea 1 recap with the notebook components. DeiT-Tiny produces 196 patch vectors of width 192 after dropping CLS. The projector changes each vector to width 768. The given prompt and answer-so-far have 13 DistilGPT2 tokens and embeddings of width 768. The joined sequence has 209 positions. Causal decoder blocks update the sequence; the last text state at a supplies the vocabulary head, yielding 50257 token scores. The selected example token dog is illustrative and appended to the text. Position handling and final normalization are omitted from this recap. New connectors in the notebook are untrained; it does not produce the illustrated answer reliably.IMAGE → FEATURE VECTORSViTh₁…hN196 patch vectors192 dimensions per vectorProject each row: 192 → 768196 vectors, each 768-dimensionalTEXT → EMBEDDING VECTORSQuestion: What animal is shown?Answer so far: It is aTokenizer → 13 IDs → embedding lookup13 text vectors · 768 dimensions each196 + 13 = 209 positionsCausal self-attention + residualMLP + residual× LVocabulary head768 → 50,257 token scoresRead the state at the last “a”Select: dogAppend the selected token; repeat with the longer text.DeiT-Tiny + DistilGPT2 dimensions · dog is an illustrative choice, not a measured prediction.

The image supplies context; the language vocabulary supplies the next token.

ViT · Dosovitskiy et al., 2020 · Oxford-IIIT Pet · CC BY-SA 4.0145 / 178

Teaching notes

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

Original teaching example / diagram146 / 178

Teaching notes

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.

Original teaching example / diagram147 / 178

Teaching notes

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

Authored room drawings, provided as two separate image inputs in a single ordered prompt. A is before; B is after. Ask what changed from before to after. The chair moves right and the cup disappears in the reference scene, revealed later. This optional worked design is not an executed model result.IMAGE A · BEFOREIMAGE B · AFTERWhat changed from before to after?Two image inputs + one question → one answer

Keep “before” and “after” attached to the correct image.

Multi-image prompts · Idefics2 documentation148 / 178

Teaching notes

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

Illustrative configuration, using the small notebook widths. Resize each entire room frame to 224 square, split into 16-pixel patches, yielding a 14 by 14 grid. One shared vision encoder is applied independently to A and B. Discard each CLS output to obtain H_A and H_B, each 196 by 192. Patch positions are local to each image. No cross-image comparison has happened in this independent encoder stage.Teaching setup · 224 × 224 image · 16 × 16 pixels per patchA · BEFORESame ViT encoderH_A · 196 patch vectorsEach vector has 192 dimensionsB · AFTERSame ViT encoderH_B · 196 patch vectorsEach vector has 192 dimensions14 × 14 = 196 patches per image · 392 patch vectors across the pair

Keep the two feature groups identifiable from the start.

ViT · Dosovitskiy et al., 2020149 / 178

Teaching notes

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

Per-image compression in the worked design. The same initial eight by 192 slot parameters and attention weights are reused for two independent reader calls. Z_A equals reader(S,H_A); Z_B equals reader(S,H_B). Each returns eight width-192 vectors. A reader mixes all 196 rows of its current image, not both images and not the text question. Keep both output groups. Labels A1 to A8 and B1 to B8 are vector names and preserve provenance; they are not object labels or numerical measurements.Same 8 learned readers S · two separate readsA · BEFOREH_A: 196 × 192Reader with SA1A2A3A4A5A6A7A8Z_A: 8 vectors × 192B · AFTERH_B: 196 × 192Reader with SB1B2B3B4B5B6B7B8Z_B: 8 vectors × 1928 summaries from A + 8 summaries from B = 16 visual vectorsThis reader sees one image at a time. The decoder will compare the groups.

The same readers produce two image-dependent groups.

Original teaching example / diagram150 / 178

Teaching notes

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 prompt text in this teaching example, not reserved special tokens. The tokenizer produces IDs and the language embedding table supplies a width-768 vector per token, exactly as for the question and answer prefix. Purple boxes represent spans, not guaranteed single tokens. The other path projects sixteen image-dependent width-192 summaries to width 768. A1 to A8 and B1 to B8 name visual vectors; they are not vocabulary IDs. Arrange both kinds of vector in prompt order. All share the decoder input width. The diagram omits model-specific boundary markers and role tokens. This is a teaching configuration, not a literal Idefics2 chat template.TEXT LABELS: “Before:” AND “After:”Tokenizer → token IDs → embedding tableOne 768-dimensional vector per text tokenVISUAL SUMMARIES: A1…A8, B1…B8Project each vector: 192 → 768 dimensionsStill 8 from A + 8 from B · no vocabulary lookupONE ORDERED DECODER INPUTBefore:A1A2A3A4A5A6A7A8After:B1B2B3B4B5B6B7B8Question + answer so far8 visual vectors from A8 visual vectors from BCausal language decoder → next tokenPurple boxes show text spans; each may contain several tokenizer pieces.Next: build this same ordered sequence in code.

Before and After are ordinary text; A and B vectors come from the images.

Multi-image prompts · Idefics2 documentation151 / 178

Teaching notes

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

Image A: room before the changeA · before
Image B: room after the changeB · after

question = “What changed from before to after?”

answer_so_far = “The chair moved to the”

Pseudocode · the same ordered input as the preceding diagramShapes / comments · batch omitted
# summary_A and summary_B are already computedEach: 8 × 192
A = projector(summary_A)8 × 768
B = projector(summary_B)8 × 768
before = embed(tokenize("Before:"))Ordinary text → vectors
after = embed(tokenize("After:"))Ordinary text → vectors
text = embed(tokenize(question, answer_so_far))One vector per text token
parts = [before, A, after, B, text]Same order as the diagram
inputs = concat(parts, axis="tokens")(16 + T) × 768
hidden = causal_decoder(inputs)(16 + T) × 768
next_id = argmax(lm_head(hidden[-1]))Next text token ID

T counts tokens in both labels, the question and the answer so far. Every input vector is 768-dimensional.

Original teaching example / diagram152 / 178

Teaching notes

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

A single conceptual decoder self-attention head at the last supplied word the, after the prefix The chair moved to the. The displayed sixteen visual-position probabilities are authored, not measured. A weights sum to 0.30, B weights to 0.40, and all visible text positions together have mass 0.30. This is one normalization across all permitted keys, not a separate softmax for each image and not normalization over image keys alone. The state at the last position contains earlier text context and can access both earlier image groups. It multiplies each paired value by its attention weight, including text values. No summary slot is assigned to chair or cup. Attention permission and authored weights do not demonstrate reliable reasoning or object correspondence.Answer so far: “The chair moved to the”State at the last “the” → this head’s query qOne softmax over all visible image AND text keysA · BEFORE8 visual positionsA10.01A20.02A30.04A40.12A50.04A60.03A70.02A80.02B · AFTER8 visual positionsB10.02B20.03B30.06B40.16B50.05B60.04B70.02B80.02A total: 0.30B total: 0.40Text positions together: 0.300.30 + 0.40 + 0.30 = 1 · each weight multiplies its paired value vectorIllustrative weights only · every head and text position can use different weights.

Attention weights are assigned to positions across the permitted context.

Transformer · Vaswani et al., 2017153 / 178

Teaching notes

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

Closing recap for the optional multiple-image section. The two authored room drawings remain visible, labelled A before and B after. Prepare each image through the already-explained encoder and per-image summarizer, preserve their A-then-B order with ordinary text labels and the question, and generate one answer using both earlier image groups in the worked causal-prefix design. The shown answer is the authored reference for these drawings, not a measured model output. This recap ends the multi-image section. Joint summarization, architecture-specific mask comparisons and the additional token-cost comparison are omitted from the slide route. No new generation or cache mechanism is introduced here.A · BEFOREB · AFTERWhat changed frombefore to after?1 · Prepare each imageEncode → summarize2 · Keep their orderA, then B + question3 · Generate an answerUse both image groups“The chair moved to the right; the cup disappeared.”Authored reference answer for these drawings · not a measured model output

Prepare each image, preserve its order, then answer using both.

Multi-image prompts · Idefics2 documentation154 / 178

Teaching notes

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.

Original teaching example / diagram155 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2Decode next token3Append selected token4Reuse cached keys / values5Repeat until EOS / limit6

Prepare the fixed context once; repeatedly predict and append a token.

Original teaching example / diagram156 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1

Only the generated prefix changes at each decoding step.

Original teaching example / diagram157 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2

Only the generated prefix changes at each decoding step.

Original teaching example / diagram158 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2Decode next token3

Only the generated prefix changes at each decoding step.

Original teaching example / diagram159 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2Decode next token3Append selected token4

Only the generated prefix changes at each decoding step.

Original teaching example / diagram160 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2Decode next token3Append selected token4Reuse cached keys / values5

Only the generated prefix changes at each decoding step.

Original teaching example / diagram161 / 178

Teaching notes

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

Encode once, prefill once, then decode, append and reuse cached computationEncode fixed image1Prefill visual + text context2Decode next token3Append selected token4Reuse cached keys / values5Repeat until EOS / limit6

Only the generated prefix changes at each decoding step.

Original teaching example / diagram162 / 178

Teaching notes

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

A*black*dog*

Reference prefix supplied.
Target loss and gradients.

Inference

Ablack?

Generated prefix grows.
No reference answer or backward pass.

Known targets allow parallel teacher-forced positions; generation is sequential.

Original teaching example / diagram163 / 178

Teaching notes

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

Black Newfoundland dog outdoors

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.

Oxford-IIIT Pet · CC BY-SA 4.0164 / 178

Teaching notes

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.

Original teaching example / diagram165 / 178

Teaching notes

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

Coffee photograph without a bicycle

What color is the bicycle?

Reference: No bicycle is visible.

Recorded baseline: “The bicycle is red.”

Fluent ≠ grounded.

Original teaching example / diagram166 / 178

Teaching notes

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

Dog

There is a black dog in the foreground.

Cat

Cat

A cat is visible.

Blank

Blank

A squirrel.

p(yt∣y<t,I,P)p(y_t\mid y_{<t},I,P)

Recorded SmolVLM-256M answers: a separate trained model.

SmolVLM-256M · model card167 / 178

Teaching notes

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

ImageFixed questionReference
DogWhat animal is this?Dog
DeskIs the laptop plugged in?Yes, visible cable connected
ShapesWhat is immediately left of the mug?Red ball
InvoiceWhat is the invoice number?ES667-042
ChartWhich month has the highest value?March
CoffeeWhat color is the bicycle?No bicycle visible
Run / record the diagnostic suite ↗Offline fallback: recorded model outputs

Preserve the raw answer, reveal the reference, then judge support.

Original teaching example / diagram168 / 178

Teaching notes

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

Capability map to representative benchmark families, not a leaderboardPerceptionOCR · documentsOCRBench · DocVQAReasoningCharts · maths · subjectsChartQA · MathVista · MMMUIntegrated skillsBroad + combined tasksMMBench · MM-VetReliabilityIllusions · hallucinationHallusionBench

Choose the evaluation from the capability you need.

OCRBench · DocVQA · ChartQA · MathVista · MMMU · MMBench · MM-Vet · HallusionBench169 / 178

Teaching notes

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

Invoice

Read: What is the invoice ID?

Chart

Calculate: March minus January?

Triangle

Reason: What is x?

Coffee

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.

Original teaching example / diagram170 / 178

Teaching notes

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 / useMeasureWhat still needs inspection
Fixed answerAccuracyAmbiguity and answer normalization
Document textExact / normalized string match; ANLSOCR errors and layout dependence
Open explanationHuman or specified model rubricJudge bias and unsupported details
Grounding coordinatesIoU / pointing accuracyObject identity and spatial accuracy
DeploymentLatency, memory, output tokens/sHardware and decoding settings

Report the evaluation protocol along with the number.

DocVQA171 / 178

Teaching notes

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.

Original teaching example / diagram172 / 178

Teaching notes

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 ↗
Original Flamingo Figure 3, with six numbered teaching callouts and arrows. Read from the input images and text upward. One: each NFNet vision encoder supplies a feature grid. Two: each Perceiver Resampler returns 64 visual vectors. Three: the processed text and image markers are tokenized and embedded for the language stream. Four: added gated cross-attention blocks let text queries read visual summaries. Five: the pretrained language-model blocks update text states and the vocabulary head predicts a next token; the figure shows an example completed continuation. Six: the original blue/snowflake symbols denote frozen pretrained modules, while purple denotes newly trained modules. Teal outlines and leader arrows are course annotations, not paper notation. The original PNG pixels remain unchanged.Original Figure 3 + teaching callouts · follow the arrows from the images and text upwards1 · Vision encoderEach image becomesa grid of features.2 · Make a summaryThe resampler returns64 vectors per image.3 · Supply the textTokenize, then embedwords + image markers.4 · Visual lookupText queries readthe visual summaries.5 · Language modelUpdate text states;predict the next token.6 · Read the colorsBlue + snowflake:pretrained and frozen.Purple: trained here.

Flamingo · Alayrac et al., 2022173 / 178

Teaching notes

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 ↗
Original BLIP-2 Figure 3: frozen image encoder feeds learned queries in a Q-Former; an FC projection connects their outputs to either an OPT-style decoder or a FlanT5-style encoder-decoder.
Original Figure 3 · Top: decoder-only LLM. Bottom: encoder–decoder LLM.

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.

BLIP-2 · Li et al., 2023174 / 178

Teaching notes

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.

Original teaching example / diagram175 / 178

Teaching notes

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.

Original teaching example / diagram176 / 178

Teaching notes

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.

Original teaching example / diagram177 / 178

Teaching notes

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.

Original teaching example / diagram178 / 178

Teaching notes

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.