$$ \newcommand{\dint}{\mathrm{d}} \newcommand{\vphi}{\boldsymbol{\phi}} \newcommand{\vpi}{\boldsymbol{\pi}} \newcommand{\vpsi}{\boldsymbol{\psi}} \newcommand{\vomg}{\boldsymbol{\omega}} \newcommand{\vsigma}{\boldsymbol{\sigma}} \newcommand{\vzeta}{\boldsymbol{\zeta}} \renewcommand{\vx}{\mathbf{x}} \renewcommand{\vy}{\mathbf{y}} \renewcommand{\vz}{\mathbf{z}} \renewcommand{\vh}{\mathbf{h}} \renewcommand{\b}{\mathbf} \renewcommand{\vec}{\mathrm{vec}} \newcommand{\vecemph}{\mathrm{vec}} \newcommand{\mvn}{\mathcal{MN}} \newcommand{\G}{\mathcal{G}} \newcommand{\M}{\mathcal{M}} \newcommand{\N}{\mathcal{N}} \newcommand{\S}{\mathcal{S}} \newcommand{\diag}[1]{\mathrm{diag}(#1)} \newcommand{\diagemph}[1]{\mathrm{diag}(#1)} \newcommand{\tr}[1]{\text{tr}(#1)} \renewcommand{\C}{\mathbb{C}} \renewcommand{\R}{\mathbb{R}} \renewcommand{\E}{\mathbb{E}} \newcommand{\D}{\mathcal{D}} \newcommand{\inner}[1]{\langle #1 \rangle} \newcommand{\innerbig}[1]{\left \langle #1 \right \rangle} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\norm}[1]{\lVert #1 \rVert} \newcommand{\two}{\mathrm{II}} \newcommand{\GL}{\mathrm{GL}} \newcommand{\Id}{\mathrm{Id}} \newcommand{\grad}[1]{\mathrm{grad} \, #1} \newcommand{\gradat}[2]{\mathrm{grad} \, #1 \, \vert_{#2}} \newcommand{\Hess}[1]{\mathrm{Hess} \, #1} \newcommand{\T}{\text{T}} \newcommand{\dim}[1]{\mathrm{dim} \, #1} \newcommand{\partder}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\rank}[1]{\mathrm{rank} \, #1} $$

VLM Project

Build a miniature vision-language model: see an image, read a question, answer, and check that it really looked.

Learning goals: describe the anatomy of a VLM; build and train one in Keras; validate it with controls (blank and shuffled images) and with unseen combinations.

Context and objectives

Course

What is a vision-language model?

A vision-language model (VLM) answers questions about an image, describes it or follows instructions that mention it. Nearly all of them share three parts:

  1. a vision encoder that turns the image into a list of vectors, one per patch (a vision transformer, often pretrained as in CLIP or SigLIP);
  2. a projector, a small linear or MLP layer that maps these vectors to the same space as the word embeddings of the language model;
  3. a language model, a transformer that reads image tokens and word tokens as one sequence and writes the answer.

In this project you build a miniature with exactly this anatomy, in Keras, small enough to train on a CPU in about twenty minutes. It uses synthetic scenes: two coloured objects on a dark background, and a question such as “what color is the circle?”. The page assumes Transformers with Keras (attention, block, training, inference), and its block is given.

Image, vision encoder, projector, language model and answer
The anatomy of a vision-language model. The pretrained parts of real systems are replaced here by small models trained from scratch.
Exercise

Objectives to carry out

  1. Generate reproducible scenes, questions and answers, with a validation set and a test set, plus a set of scenes with unseen colour–shape combinations (Part 1).
  2. Build the vision side: patches, position, one transformer block and a projector (Part 2).
  3. Fuse the image tokens with the question tokens and build the complete model; count its parameters (Part 3).
  4. Train and validate; prove that the model uses the image by testing it with blank and shuffled images (Part 4).
  5. Ask new questions, evaluate on the test set and on the unseen combinations, and look at where the answer token looks (Part 5).
  6. Write a short report with numbers, figures and limits (Part 6).

Each part starts with an explanation and proposes small exercises with a very light starting code (TO DO lines); the correction is folded just after. Try before you open it.

Course

How to work: environment and discipline

Install tensorflow==2.21.0 numpy matplotlib in an isolated Python environment (checked with Python 3.12 and TensorFlow CPU 2.21). The data are generated by the code of the page; nothing is downloaded. Run the blocks in order in one notebook or session. Keep the test and the unseen-combination scenes untouched until Part 5: choose the epoch on validation only. Random seeds make runs reproducible, but hardware and library versions can change exact scores.

PythonCode provided · imports, constants, vocabulary and transformer block
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersSEED = 42keras.utils.set_random_seed(SEED)IMG, PATCH = 32, 8                       # 32x32 images cut into (32/8)^2 = 16 patchesN_PATCH = (IMG // PATCH) ** 2D, HEADS, FFN = 64, 4, 128               # width, attention heads, feed-forward sizeCOLORS = ["red", "green", "blue", "yellow"]SHAPES = ["square", "circle", "triangle"]RGB = {"red": (0.9, 0.1, 0.1), "green": (0.1, 0.7, 0.2), "blue": (0.15, 0.25, 0.95), "yellow": (0.95, 0.85, 0.1)}WORDS = ["<pad>", "what", "color", "shape", "is", "the", "object", "left", "of", "?", "<ans>"]VOCAB = WORDS + COLORS + SHAPES + ["yes", "no"]ID = {w: i for i, w in enumerate(VOCAB)}ANSWERS = COLORS + SHAPES + ["yes", "no"]            # the nine possible answersANS_ID = {a: i for i, a in enumerate(ANSWERS)}QLEN = 8                                            # a question has at most 8 words (padded on the left)def block(x, index, causal=False):    """Pre-norm transformer block (see the page Transformers with Keras)."""    h = layers.LayerNormalization(name=f"ln_a{index}")(x)    h = layers.MultiHeadAttention(HEADS, D // HEADS, name=f"attn{index}")(h, h, use_causal_mask=causal)    x = layers.Add()([x, h])    h = layers.LayerNormalization(name=f"ln_f{index}")(x)    h = layers.Dense(FFN, activation="gelu")(h)    h = layers.Dense(D)(h)    return layers.Add()([x, h])

Part 1 · Generate scenes and questions

Course

Scenes, questions and answers

A scene is a $32\times32$ RGB image with a dark noisy background and two $10\times10$ objects: each has a colour (red, green, blue, yellow) and a shape (square, circle, triangle). The two objects differ in colour and in shape, so that “the circle” and “the red object” are unambiguous. A question is one of three types, each with a one-word answer:

TypeQuestionAnswerChance
colourwhat color is the circle ?one of 4 colours25%
shapewhat shape is the red object ?one of 3 shapes33%
positionis the square left of the circle ?yes / no50%

Questions are lists of word tokens from a vocabulary of 21 words. They are padded on the left to 8 words, then a special token <ans> is added: the model will write its answer at this last position.

Exercise

Exercise 1.1 · draw a scene

  1. Complete object_mask for the square, the circle and the triangle in a $10\times10$ box.
  2. In draw_scene, paint the pixels of each mask with the colour of the object plus a little noise.
  3. Display a scene with a red square on the left and a blue triangle on the right.
PythonStarting code · shapes and scenes
def object_mask(shape, size=10):    yy, xx = np.mgrid[0:size, 0:size] + 0.5    c = size / 2    if shape == "square":   return ...  # TO DO: the full box    if shape == "circle":   return ...  # TO DO: a disc of radius size/2    if shape == "triangle": return ...  # TO DO: wide at the bottom, a point at the top    raise ValueError(shape)def draw_scene(objects, rng):    """objects: list of (color, shape, x, y) with (x, y) the top-left corner of the 10x10 box."""    img = 0.08 + 0.04 * rng.random((IMG, IMG, 3))            # dark noisy background    for color, shape, x, y in objects:        m = object_mask(shape)        patch = img[y:y + 10, x:x + 10]        patch[m] = ...  # TO DO: paint the pixels of the mask with the color    return np.clip(img, 0, 1).astype("float32")rng = np.random.default_rng(SEED)scene = [("red", "square", 3, 4), ("blue", "triangle", 18, 15)]plt.imshow(draw_scene(scene, rng)); plt.axis("off"); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · object masks and scene drawing
# Each shape is a boolean mask on a size x size box; pixel coordinates are taken at pixel centres.def object_mask(shape, size=10):    yy, xx = np.mgrid[0:size, 0:size] + 0.5    c = size / 2    # The square fills the box.    if shape == "square":   return np.ones((size, size), bool)  # the full box    # Points at distance less than size/2 from the centre c.    if shape == "circle":   return (xx - c) ** 2 + (yy - c) ** 2 < c ** 2  # a disc of radius size/2    #     # x - c    #  < y/2: the width of the row grows with y, so the triangle is wide at the bottom and pointed at the top.    if shape == "triangle": return np.abs(xx - c) < yy / 2  # wide at the bottom, a point at the top    raise ValueError(shape)def draw_scene(objects, rng):    """objects: list of (color, shape, x, y) with (x, y) the top-left corner of the 10x10 box."""    # Dark background with a little noise.    img = 0.08 + 0.04 * rng.random((IMG, IMG, 3))            # dark noisy background    for color, shape, x, y in objects:        m = object_mask(shape)        # patch is a view on the 10 x 10 box of the image: writing in it changes img.        patch = img[y:y + 10, x:x + 10]        # The pixels selected by the mask get the colour of the object plus Gaussian noise (one noise value per colour channel).        patch[m] = np.array(RGB[color]) + 0.05 * rng.normal(size=(m.sum(), 3))  # paint the pixels of the mask with the color    return np.clip(img, 0, 1).astype("float32")rng = np.random.default_rng(SEED)scene = [("red", "square", 3, 4), ("blue", "triangle", 18, 15)]plt.imshow(draw_scene(scene, rng)); plt.axis("off"); plt.show()

The triangle is the set of pixels with $|x-c|<y/2$: it is wide at the bottom and reduced to a point at the top. Everything is drawn at $32\times32$ pixels so that a CPU can train in minutes.

Exercise

Exercise 1.2 · write a question and its answer

  1. Complete the shape question: ask for the shape of the object of a given colour and return that shape.
  2. Complete the position question: the answer is “yes” if the first object has a smaller $x$ than the second one.
  3. Complete encode: words to integers, <ans> at the end, padding at the beginning.
PythonStarting code · questions
def make_question(objects, rng):    """Return (list of words, answer) for a random question about a two-object scene."""    kind = rng.integers(3)    (c1, s1, x1, _), (c2, s2, x2, _) = objects    if kind == 0:                                         # "what color is the <shape> ?"        i = rng.integers(2); c, s = objects[i][:2]        return ["what", "color", "is", "the", s, "?"], c    if kind == 1:                                         # "what shape is the <color> object ?"        i = rng.integers(2); c, s = objects[i][:2]        return ...  # TO DO: ask the shape, answer with the shape    i = rng.integers(2); j = 1 - i                        # "is the <shape> left of the <shape> ?"    a, b = objects[i], objects[j]    return ...  # TO DO: compare the x positionsdef encode(words):    ids = [ID[w] for w in words] + [ID["<ans>"]]print(make_question(scene, rng))print(encode(make_question(scene, rng)[0]))
Show the correction
PythonComplete solution · three question types
def make_question(objects, rng):    """Return (list of words, answer) for a random question about a two-object scene."""    # 0 = colour question, 1 = shape question, 2 = position question.    kind = rng.integers(3)    (c1, s1, x1, _), (c2, s2, x2, _) = objects    # The shape is named in the question and the answer is its colour.    if kind == 0:                                         # "what color is the <shape> ?"        i = rng.integers(2); c, s = objects[i][:2]        return ["what", "color", "is", "the", s, "?"], c    # Mirror question: the colour is named, the answer is the shape.    if kind == 1:                                         # "what shape is the <color> object ?"        i = rng.integers(2); c, s = objects[i][:2]        return ["what", "shape", "is", "the", c, "object", "?"], s  # ask the shape, answer with the shape    # i is the first object of the question and j the other one.    i = rng.integers(2); j = 1 - i                        # "is the <shape> left of the <shape> ?"    a, b = objects[i], objects[j]    # The answer is yes when object a has a smaller x (it is more to the left).    return ["is", "the", a[1], "left", "of", "the", b[1], "?"], ("yes" if a[2] < b[2] else "no")  # compare the x positions# Words -> integers with the vocabulary; <ans> is the position where the model will write its answer.def encode(words):    ids = [ID[w] for w in words] + [ID["<ans>"]]    return [ID["<pad>"]] * (QLEN + 1 - len(ids)) + ids  # pad on the left so <ans> is always the last tokenprint(make_question(scene, rng))print(encode(make_question(scene, rng)[0]))

Padding on the left keeps <ans> at the same position for every question, so the model can read the answer there.

Course

A split that tests composition

Training, validation and test scenes are drawn with the same rule, but three colour–shape combinations are never shown in them: red triangle, blue circle and yellow square. A fourth set contains scenes in which at least one object has such an unseen combination. A model that really composes “blue” and “circle” should answer about a blue circle; a model that memorized the nine seen pairs will not. Remember the principle of the course: different sets answer different questions. Validation is for choosing, the test set for reporting, the unseen-combination set for asking about generalization.

Exercise

Exercise 1.3 · build the four sets

  1. In sample_objects, count the objects that use a held-out combination and accept the scene only if it matches the requested set.
  2. Generate 30,000 training, 2,000 validation, 2,000 test and 1,000 unseen-combination samples (one question per scene).
  3. Check the shapes and the proportion of each answer.
PythonStarting code · splits
HELD_OUT = {("red", "triangle"), ("blue", "circle"), ("yellow", "square")}   # combinations never seen in trainingdef sample_objects(rng, held_out):    while True:        cs = rng.choice(COLORS, 2, replace=False); ss = rng.choice(SHAPES, 2, replace=False)        xs = rng.integers(0, IMG - 10, 2); ys = rng.integers(0, IMG - 10, 2)        if abs(xs[0] - xs[1]) < 8: continue                                  # keep "left of" unambiguous        objs = [(str(cs[k]), str(ss[k]), int(xs[k]), int(ys[k])) for k in range(2)]        n_held = ...  # TO DO: how many objects use a held-out combination        keep = ...  # TO DO: keep the scene only if it matches the requested split        if keep:            return objsdef make_dataset(n, rng, held_out=False):    images, questions, answers = [], [], []    for _ in range(n):        objs = sample_objects(rng, held_out)        words, ans = make_question(objs, rng)        images.append(draw_scene(objs, rng)); questions.append(encode(words)); answers.append(ANS_ID[ans])    return np.stack(images), np.array(questions), np.array(answers)rng = np.random.default_rng(SEED)img_tr, q_tr, a_tr = make_dataset(30000, rng)img_va, q_va, a_va = make_dataset(2000, rng)img_te, q_te, a_te = make_dataset(2000, rng)img_ho, q_ho, a_ho = make_dataset(1000, rng, held_out=True)      # final composition testprint(img_tr.shape, q_tr.shape, np.bincount(a_tr, minlength=9) / len(a_tr))
Show the correction
PythonComplete solution · datasets
# Colour-shape combinations that never appear in training, validation and test scenes.HELD_OUT = {("red", "triangle"), ("blue", "circle"), ("yellow", "square")}   # combinations never seen in trainingdef sample_objects(rng, held_out):    # Rejection sampling: draw a random scene until it satisfies the constraints.    while True:        cs = rng.choice(COLORS, 2, replace=False); ss = rng.choice(SHAPES, 2, replace=False)        xs = rng.integers(0, IMG - 10, 2); ys = rng.integers(0, IMG - 10, 2)        # Objects at least 8 pixels apart in x: "left of" is never ambiguous.        if abs(xs[0] - xs[1]) < 8: continue                                  # keep "left of" unambiguous        objs = [(str(cs[k]), str(ss[k]), int(xs[k]), int(ys[k])) for k in range(2)]        # A scene uses a held-out combination when one of its objects has a forbidden (colour, shape) pair.        n_held = sum((o[0], o[1]) in HELD_OUT for o in objs)  # how many objects use a held-out combination        # Training scenes: no held-out object (n_held == 0). Unseen-combination scenes: at least one (n_held > 0).        keep = (held_out and n_held > 0) or (not held_out and n_held == 0)  # keep the scene only if it matches the requested split        if keep:            return objs# One question per scene; the lists are stacked into arrays at the end.def make_dataset(n, rng, held_out=False):    images, questions, answers = [], [], []    for _ in range(n):        objs = sample_objects(rng, held_out)        words, ans = make_question(objs, rng)        images.append(draw_scene(objs, rng)); questions.append(encode(words)); answers.append(ANS_ID[ans])    return np.stack(images), np.array(questions), np.array(answers)rng = np.random.default_rng(SEED)img_tr, q_tr, a_tr = make_dataset(30000, rng)img_va, q_va, a_va = make_dataset(2000, rng)img_te, q_te, a_te = make_dataset(2000, rng)# This last set is only used once, in Part 5.img_ho, q_ho, a_ho = make_dataset(1000, rng, held_out=True)      # final composition testprint(img_tr.shape, q_tr.shape, np.bincount(a_tr, minlength=9) / len(a_tr))

The answers are not uniform: the 4 colours, 3 shapes and yes/no do not appear equally often. A model that ignores the image could still use these frequencies, so the baselines of Part 4 are needed to prove that it uses the image.

Part 2 · See: patches, tokens and a projector

Course

From pixels to tokens

A transformer reads a list of vectors. To feed it an image, we cut the $32\times32$ image into $16$ patches of $8\times8$ pixels and map each patch, flattened ($8\cdot8\cdot3=192$ numbers), to a vector of dimension $D=64$ with one shared linear map. This is exactly a convolution whose stride is equal to its kernel size. As for words, a learned position vector tells which patch is where. A first transformer block (without the causal mask: patches can look at all other patches) then lets the patches exchange information. This is the principle of the vision transformer (ViT).

An image cut into 16 patches that become 16 tokens
Sixteen patches, sixteen tokens.

The projector is the bridge between the two worlds: a linear layer that maps vision features into the space where the language model works. In many real VLMs it is the only part trained from scratch, while the vision encoder and the language model are pretrained.

Exercise

Exercise 2.1 · patch embedding with a convolution

  1. Create a Conv2D with $D$ filters, kernel size and stride equal to PATCH.
  2. Apply it to three images and reshape the result to (batch, 16, $D$).
  3. Check the parameter count: $(8\cdot8\cdot3+1)\cdot64$.
PythonStarting code · patches
patch_embed = ...  # TO DO: a convolution whose stride equals its kernel size cuts the image into patchesx = patch_embed(img_tr[:3])print(x.shape)                                         # (3, 4, 4, D)tokens = ...  # TO DO: 16 patch tokens per imageprint(tokens.shape, "parameters:", patch_embed.count_params(), "= (8*8*3+1)*64 =", (PATCH * PATCH * 3 + 1) * D)
Show the correction
PythonComplete solution · patches as tokens
# A convolution with kernel = stride = 8 looks at each 8 x 8 patch exactly once and maps its 8*8*3 = 192 numbers to D = 64 features with the same weights.patch_embed = layers.Conv2D(D, PATCH, strides=PATCH, name="patch_embed")  # a convolution whose stride equals its kernel size cuts the image into patches# Shape (3, 4, 4, 64): a 4 x 4 grid of patch vectors.x = patch_embed(img_tr[:3])print(x.shape)                                         # (3, 4, 4, D)# Flatten the grid into a sequence of 16 tokens: (3, 16, 64).tokens = layers.Reshape((N_PATCH, D))(x)  # 16 patch tokens per imageprint(tokens.shape, "parameters:", patch_embed.count_params(), "= (8*8*3+1)*64 =", (PATCH * PATCH * 3 + 1) * D)

The output of the convolution is a $4\times4$ grid of vectors, reshaped into a sequence of 16 tokens. The $12{,}352$ parameters are shared by all patches.

Exercise

Exercise 2.2 · vision encoder and projector

  1. Add the position vectors to the patch tokens (AddPosition is given).
  2. Apply one transformer block to the patch tokens.
  3. Write the projector as one Dense layer and build the vision-side model; print its output shape and parameters.
PythonStarting code · vision side
class AddPosition(layers.Layer):    def __init__(self, length, **kw):        super().__init__(**kw)        self.emb = layers.Embedding(length, D)    def call(self, x):        return x + self.emb(tf.range(tf.shape(x)[1]))def vision_encoder(image):    x = layers.Conv2D(D, PATCH, strides=PATCH, name="patch_embed")(image)    x = layers.Reshape((N_PATCH, D))(x)    x = ...  # TO DO: the model must know where each patch is    x = ...  # TO DO: one bidirectional transformer block over the patches    return xdef projector(x):    return ...  # TO DO: linear map from vision features to the language model spaceimage = keras.Input((IMG, IMG, 3))vision = keras.Model(image, projector(vision_encoder(image)), name="vision_side")print(vision.output_shape, vision.count_params())
Show the correction
PythonComplete solution · patch tokens ready for the language model
# Learned position vectors, as in the Transformers page (one table of length x D).class AddPosition(layers.Layer):    def __init__(self, length, **kw):        super().__init__(**kw)        self.emb = layers.Embedding(length, D)    def call(self, x):        return x + self.emb(tf.range(tf.shape(x)[1]))def vision_encoder(image):    # Patches -> tokens, as in the previous exercise.    x = layers.Conv2D(D, PATCH, strides=PATCH, name="patch_embed")(image)    x = layers.Reshape((N_PATCH, D))(x)    # Without positions the model could not tell a patch in the top-left corner from one in the bottom-right.    x = AddPosition(N_PATCH, name="patch_position")(x)  # the model must know where each patch is    # No causal mask here (causal=False by default): every patch may read every other patch, as in a vision transformer.    x = block(x, "v0")  # one bidirectional transformer block over the patches    return xdef projector(x):    # A linear projector; real VLMs often use a small MLP here.    return layers.Dense(D, name="projector")(x)  # linear map from vision features to the language model spaceimage = keras.Input((IMG, IMG, 3))# A model that maps an image to 16 tokens of dimension 64, ready for the language model.vision = keras.Model(image, projector(vision_encoder(image)), name="vision_side")print(vision.output_shape, vision.count_params())

The output has shape (batch, 16, 64): one 64-dimensional token per patch. One block is enough for these simple scenes; real vision encoders have tens of blocks and are pretrained on millions of images.

Part 3 · Read image and question together

Course

One sequence for two modalities

Word tokens are embedded as in Transformers with Keras: an embedding and a position vector. The sequence given to the language model is the concatenation of the 16 projected image tokens and the 9 question tokens (8 words and <ans>):

\[z=[\,v_1,\dots,v_{16},\;w_1,\dots,w_8,\;\texttt{<ans>}\,]\in\mathbb R^{25\times64}.\]

Self-attention then lets the word “circle” in the question find the circle in the image, and the <ans> token gather what is needed. After four blocks, we read the vector of the <ans> position and map it to nine scores: four colours, three shapes, yes and no. Real VLMs generate a whole sentence, token by token, exactly as in Part 5 of the Transformers page; we restrict the output to one token to keep the data and the training small. Since the image and the question are both given before the answer, we do not need a causal mask here (many VLMs use full attention on the image and the prompt, and a causal mask on the generated text).

Image tokens and question tokens form one sequence read by transformer blocks
Image tokens (blue) and question tokens (gold) in one sequence.
Exercise

Exercise 3.1 · build the complete model

  1. Concatenate the image tokens and the question tokens along the sequence axis.
  2. Stack the transformer blocks on the fused sequence.
  3. Read the last position, and apply a Dense layer with one output per possible answer.
  4. Compare the parameter counts: complete model against the vision side (patch embedding, positions, projector).
PythonStarting code · the vision-language model
def build_vlm(n_blocks=4):    image = keras.Input((IMG, IMG, 3), name="image")    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    v = projector(vision_encoder(image))                                  # (batch, 16, D) image tokens    q = layers.Embedding(len(VOCAB), D, name="word_embedding")(question)   # (batch, 9, D) word tokens    q = AddPosition(QLEN + 1, name="word_position")(q)    z = ...  # TO DO: one sequence: image tokens first, then the question    for i in range(n_blocks):        z = ...  # TO DO: the "language model" reads both kinds of tokens    z = layers.LayerNormalization()(z)    answer = ...  # TO DO: read the last position (the <ans> token)    return keras.Model([image, question], answer)vlm = build_vlm()n_vis = sum(l.count_params() for l in vlm.layers if l.name in ("patch_embed", "patch_position", "projector"))print("parameters:", vlm.count_params(), "| patch embedding, positions and projector:", n_vis)print(vlm.output_shape)
Show the correction
PythonComplete solution · image tokens and question tokens in one sequence
def build_vlm(n_blocks=4):    image = keras.Input((IMG, IMG, 3), name="image")    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    # Image tokens: (batch, 16, 64).    v = projector(vision_encoder(image))                                  # (batch, 16, D) image tokens    # Word tokens: (batch, 9, 64) for the 8 padded words and <ans>.    q = layers.Embedding(len(VOCAB), D, name="word_embedding")(question)   # (batch, 9, D) word tokens    q = AddPosition(QLEN + 1, name="word_position")(q)    # Concatenation along axis 1 (the sequence axis): (batch, 25, 64). From here on, the transformer does not know which tokens come from the image.    z = layers.Concatenate(axis=1)([v, q])  # one sequence: image tokens first, then the question    for i in range(n_blocks):        # Four blocks: enough depth to find the objects, bind colours to shapes and compare their x positions.        z = block(z, i)  # the "language model" reads both kinds of tokens    z = layers.LayerNormalization()(z)    # z[:, -1] is the vector of the <ans> position: (batch, 64). The Dense layer gives 9 scores, one per possible answer.    answer = layers.Dense(len(ANSWERS), name="answer")(z[:, -1])  # read the last position (the <ans> token)    return keras.Model([image, question], answer)vlm = build_vlm()# Parameters of the vision side only, to compare with the total.n_vis = sum(l.count_params() for l in vlm.layers if l.name in ("patch_embed", "patch_position", "projector"))print("parameters:", vlm.count_params(), "| patch embedding, positions and projector:", n_vis)print(vlm.output_shape)

The model has 187,465 parameters. Patch embedding, patch positions and the projector make up only 17,536 of them; the four transformer blocks hold the rest. In a real VLM, most of the parameters are in the pretrained language model.

Part 4 · Train, validate, and check that the model looks

Course

Train, and then prove that the image matters

The loss is the cross-entropy over the nine answers. You choose the epoch with the validation loss (early stopping with restored weights). A high accuracy is not enough: the answer frequencies and the wording of a question can carry information. We therefore evaluate the same frozen model in three ways:

  • with the real images;
  • with blank images (the model hears the question but sees nothing);
  • with shuffled images (each question receives the image of another scene).

If accuracy collapses towards chance when the image is blank or wrong, the model uses the image. Accuracy is reported separately for each question type, because an average would hide the difference between them.

Exercise

Exercise 4.1 · train and validate

  1. Complete train: Adam (learning rate 0.001), cross-entropy from logits, accuracy; the inputs are a dictionary with the image and the question.
  2. Pass the validation inputs and answers, with early stopping on the validation loss.
  3. Report the best epoch, the validation loss and accuracy, and plot the curves.
PythonStarting code · training
def train(model, epochs=100, rate=1e-3):    model.compile(optimizer=keras.optimizers.Adam(rate),                  loss=...,  # TO DO: cross-entropy over the nine answers                  metrics=["accuracy"])    stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=8, restore_best_weights=True)    return model.fit({"image": img_tr, "question": q_tr}, a_tr,                     validation_data=...,  # TO DO: validation inputs and answers                     batch_size=64, epochs=epochs, callbacks=[stop], verbose=0)keras.utils.set_random_seed(SEED)history = train(vlm)best = int(np.argmin(history.history["val_loss"]))print(f"best epoch {best+1}: val loss {history.history['val_loss'][best]:.3f}, val accuracy {history.history['val_accuracy'][best]:.3f}")plt.plot(history.history["loss"], label="train"); plt.plot(history.history["val_loss"], "--", label="validation")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()
Show the correction
PythonComplete solution · training with early stopping
# The inputs are a dictionary: the keys must match the names given to the keras.Input layers.def train(model, epochs=100, rate=1e-3):    model.compile(optimizer=keras.optimizers.Adam(rate),                  # One answer among 9: sparse categorical cross-entropy on the integer answers, from logits.                  loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),  # cross-entropy over the nine answers                  metrics=["accuracy"])    # patience = 8 because the position question has a plateau before it is learned: a smaller patience would stop too early.    stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=8, restore_best_weights=True)    return model.fit({"image": img_tr, "question": q_tr}, a_tr,                     # Early stopping looks at the validation loss, never at the test set.                     validation_data=({"image": img_va, "question": q_va}, a_va),  # validation inputs and answers                     batch_size=64, epochs=epochs, callbacks=[stop], verbose=0)# Seed fixed: same initial weights and same data order each time.keras.utils.set_random_seed(SEED)history = train(vlm)best = int(np.argmin(history.history["val_loss"]))print(f"best epoch {best+1}: val loss {history.history['val_loss'][best]:.3f}, val accuracy {history.history['val_accuracy'][best]:.3f}")plt.plot(history.history["loss"], label="train"); plt.plot(history.history["val_loss"], "--", label="validation")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()

In the reference run, training stops at epoch 40 with a validation loss of 0.003 and an accuracy of 0.999 over the three question types. The colour and shape questions are learned first; the position question needs more training: it requires finding two objects and comparing their $x$ positions, and a smaller model (two blocks) or a larger learning rate stayed at chance in our tests. Model size and learning rate matter, and a plateau at 50% is a sign to be patient or to change the design, not to stop reading the curves.

Exercise

Exercise 4.2 · blank images, shuffled images and accuracy per type

  1. Complete accuracy_by_type: the accuracy of each of the three question types.
  2. Build the blank and the shuffled versions of the validation images.
  3. Print a table: question type against input condition, and compare with chance.
PythonStarting code · is the image used?
def question_type(q):    words = [VOCAB[i] for i in q]    return "color" if "color" in words else "shape" if "shape" in words else "left of"def accuracy_by_type(images, questions, answers, model=None):    model = model or vlm                                   # the model of Part 4 unless another one is given    pred = model.predict({"image": images, "question": questions}, verbose=0).argmax(axis=-1)    kinds = np.array([question_type(q) for q in questions])    return ...  # TO DO: accuracy of each question typerng_s = np.random.default_rng(7)settings = {    "real images":      img_va,    "blank images":     ...,  # TO DO: the model hears the question but sees nothing    "shuffled images":  ...,  # TO DO: the image belongs to another question}print(f"{'':16s}", "  ".join(f"{k:>8s}" for k in ["color", "shape", "left of"]))for name, images in settings.items():    acc = accuracy_by_type(images, q_va, a_va)    print(f"{name:16s}", "  ".join(f"{acc[k]:8.3f}" for k in ["color", "shape", "left of"]))print("chance:           0.250     0.333     0.500")
Show the correction
PythonComplete solution · accuracy per question type with real, blank and shuffled images
# Recover the type of a question from its words.def question_type(q):    words = [VOCAB[i] for i in q]    return "color" if "color" in words else "shape" if "shape" in words else "left of"# argmax over the 9 scores gives the predicted answer; accuracy is computed separately for each question type.def accuracy_by_type(images, questions, answers, model=None):    model = model or vlm                                   # the model of Part 4 unless another one is given    pred = model.predict({"image": images, "question": questions}, verbose=0).argmax(axis=-1)    kinds = np.array([question_type(q) for q in questions])    return {k: float((pred[kinds == k] == answers[kinds == k]).mean()) for k in ["color", "shape", "left of"]}  # accuracy of each question type# Fixed seed: the shuffled version is reproducible.rng_s = np.random.default_rng(7)settings = {    "real images":      img_va,    # All pixels equal to 0: only the question is informative. Accuracy at chance level means the model needs the image.    "blank images":     np.zeros_like(img_va),  # the model hears the question but sees nothing    # A random permutation pairs each question with an image of another scene.    "shuffled images":  img_va[rng_s.permutation(len(img_va))],  # the image belongs to another question}print(f"{'':16s}", "  ".join(f"{k:>8s}" for k in ["color", "shape", "left of"]))for name, images in settings.items():    acc = accuracy_by_type(images, q_va, a_va)    print(f"{name:16s}", "  ".join(f"{acc[k]:8.3f}" for k in ["color", "shape", "left of"]))print("chance:           0.250     0.333     0.500")

colourshapeposition
real images0.9981.0001.000
blank images0.3680.4520.472
shuffled images0.3650.4610.515
chance0.2500.3330.500

With blank or shuffled images the accuracy is close to chance, slightly above on colour and shape because the answers are not equally frequent. The model really uses the image. Always run this control: a VLM that answers well without the image is only reading the question.

Part 5 · Answer, test and look inside

Course

Use the model, test it, and look inside

For the inference of a VLM, you give an image and a question written in words: the code encodes the words with the same vocabulary, runs the model and returns the most likely answer with its probability. Then comes the final evaluation: the test scenes (same rule as training), and the scenes with unseen colour–shape combinations, which ask a harder question: did the model learn colour and shape as separate concepts, or did it memorize the nine pairs it saw?

Exercise

Exercise 5.1 · ask questions

  1. Complete answer: encode the text, run the model on one image, and return the best answer and its probability.
  2. Draw a scene with a green circle and a red square and ask four questions, including the same position question in both directions.
PythonStarting code · inference
def answer(model, image, text):    words = text.lower().replace("?", " ?").split()    q = ...  # TO DO: the same encoding as in training    logits = model.predict({"image": image[None], "question": q}, verbose=0)[0]    p = np.exp(logits - logits.max()); p /= p.sum()    return ANSWERS[int(p.argmax())], float(p.max())rng_d = np.random.default_rng(3)objs = [("green", "circle", 4, 20), ("red", "square", 19, 6)]img = draw_scene(objs, rng_d)for text in ["what color is the circle ?", "what shape is the red object ?", "is the circle left of the square ?", "is the square left of the circle ?"]:    print(f"{text:40s} -> {answer(vlm, img, text)}")plt.imshow(img); plt.axis("off"); plt.show()
Show the correction
PythonComplete solution · answer a question in words
# Lower-case and split the text like in training; "?" becomes a separate word.def answer(model, image, text):    words = text.lower().replace("?", " ?").split()    # Batch of one question, encoded and left-padded.    q = np.array([encode(words)])  # the same encoding as in training    # image[None] adds the batch axis: (1, 32, 32, 3).    logits = model.predict({"image": image[None], "question": q}, verbose=0)[0]    # Softmax by hand, to turn the scores into probabilities.    p = np.exp(logits - logits.max()); p /= p.sum()    return ANSWERS[int(p.argmax())], float(p.max())rng_d = np.random.default_rng(3)# A scene that was not generated by the dataset code.objs = [("green", "circle", 4, 20), ("red", "square", 19, 6)]img = draw_scene(objs, rng_d)for text in ["what color is the circle ?", "what shape is the red object ?", "is the circle left of the square ?", "is the square left of the circle ?"]:    print(f"{text:40s} -> {answer(vlm, img, text)}")plt.imshow(img); plt.axis("off"); plt.show()

The answers to “is the circle left of the square?” and “is the square left of the circle?” must be opposite: it is a simple consistency test you can use on any trained model. Question words that are not in the vocabulary would raise an error: a real VLM has a much larger vocabulary and subword tokens.

Exercise

Exercise 5.2 · test and unseen combinations, once

  1. Freeze the model chosen on validation.
  2. Compute the accuracy per question type on the test scenes and on the unseen-combination scenes.
  3. Describe the gap and propose two explanations.
PythonStarting code · final report
chosen = vlm                                         # frozen after validationtest = accuracy_by_type(img_te, q_te, a_te)held = ...  # TO DO: the same function on scenes that contain an unseen color-shape combinationfor k in test:    print(f"{k:8s} test {test[k]:.3f}   unseen combination {held[k]:.3f}")
Show the correction
PythonComplete solution · test and unseen combinations
# No change of model, epoch or hyper-parameter after this point.chosen = vlm                                         # frozen after validationtest = accuracy_by_type(img_te, q_te, a_te)# Scenes with a colour-shape combination that is absent from the training set.held = accuracy_by_type(img_ho, q_ho, a_ho)  # the same function on scenes that contain an unseen color-shape combinationfor k in test:    print(f"{k:8s} test {test[k]:.3f}   unseen combination {held[k]:.3f}")

colourshapeposition
test0.9880.9970.998
unseen combinations0.2990.2780.439

The test scores are high, but on unseen combinations the model falls to roughly chance (colour 0.299 against 0.250, shape 0.278 against 0.333) and even below chance on position (0.439): it did not learn colour and shape as separate, recombinable concepts from nine pairs; it largely memorized the pairs. This is a genuine limit of training from scratch on little, regular data, and it is why real systems use large pretrained encoders and varied data. Exercise 5.4 tests what changes when the model sees more combinations.

Exercise

Exercise 5.3 · where does the answer look?

  1. Complete look_at: build the input of the attention layer of the last block, and call it with return_attention_scores=True.
  2. Average over the heads and read the row of the <ans> token, restricted to the 16 image patches.
  3. Display the image and the $4\times4$ attention map for “what color is the circle ?” and for another question. Does the map follow the object mentioned?
PythonStarting code · attention over the patches
def look_at(model, image, text, block_index=1):    """Attention of the <ans> token over the 16 patches, averaged over heads."""    q = np.array([encode(text.lower().replace("?", " ?").split())])    ln = model.get_layer(f"ln_a{block_index}")    h = keras.Model(model.inputs, ln.output)({"image": image[None], "question": q})    _, w = ...  # TO DO: weights (1, heads, 25, 25)    last = ...  # TO DO: the last row: what the <ans> token reads    return last[:N_PATCH].reshape(IMG // PATCH, IMG // PATCH)grid = look_at(chosen, img, "what color is the circle ?")fig, axes = plt.subplots(1, 2, figsize=(7, 3.5))axes[0].imshow(img); axes[0].set_title("image")for a in axes: a.axis("off")plt.show()
Show the correction
PythonComplete solution · attention of the answer token
# We read the attention weights of one block (numbered from 0). Block 1 is the second one: a block in the middle of the network, where image and question have already been mixed once.def look_at(model, image, text, block_index=1):    """Attention of the <ans> token over the 16 patches, averaged over heads."""    q = np.array([encode(text.lower().replace("?", " ?").split())])    # The LayerNorm just before the attention layer of that block.    ln = model.get_layer(f"ln_a{block_index}")    # Sub-model giving the normalized tokens that enter the attention layer.    h = keras.Model(model.inputs, ln.output)({"image": image[None], "question": q})    # Weights of shape (1, heads, 25, 25): rows = reading token, columns = attended token.    _, w = model.get_layer(f"attn{block_index}")(h, h, return_attention_scores=True)  # weights (1, heads, 25, 25)    # Average over the heads; the last row is the <ans> token; its first 16 columns are the image patches.    last = w.numpy()[0].mean(axis=0)[-1]  # the last row: what the <ans> token reads    return last[:N_PATCH].reshape(IMG // PATCH, IMG // PATCH)# Reshaped as a 4 x 4 grid, it can be compared with the image.grid = look_at(chosen, img, "what color is the circle ?")fig, axes = plt.subplots(1, 2, figsize=(7, 3.5))axes[0].imshow(img); axes[0].set_title("image")axes[1].imshow(grid, cmap="viridis"); axes[1].set_title("attention on the patches")for a in axes: a.axis("off")plt.show()

The map has one value per patch. If it is high on the patches of the object named in the question, this agrees with the idea that the model finds it, but it is only a clue: weights of one layer do not explain a decision by themselves, and the information may already have been copied into the word tokens by the previous block.

Exercise

Exercise 5.4 · extension: show the model more combinations

  1. Keep the model of Part 4 as vlm_first. Change HELD_OUT so that only the red triangle stays unseen: the blue circle and the yellow square are now allowed in the training scenes.
  2. Generate new training and validation scenes, and 1,000 scenes that contain a red triangle. Train the same architecture again, with the same seed and the same train function.
  3. Compare, on the scenes with a red triangle, the accuracy per question type of vlm_first and of the new model. What does the comparison say about what the model learned?
PythonStarting code · more combinations in the training data
vlm_first = vlm                                 # the model of Part 4: three combinations never seenHELD_OUT = ...  # TO DO: only the red triangle stays unseen: the blue circle and the yellow square are now in the training scenesrng = np.random.default_rng(SEED + 1)img_tr, q_tr, a_tr = make_dataset(30000, rng)    # new training scenes (the red triangle never appears)img_va, q_va, a_va = make_dataset(2000, rng)     # new validation scenesimg_ho, q_ho, a_ho = ...  # TO DO: scenes that contain a red trianglekeras.utils.set_random_seed(SEED)vlm = build_vlm()                               # same architecture, same training, new datahistory = train(vlm)print("best epoch", int(np.argmin(history.history["val_loss"])) + 1)for name, model in [("first model (3 combinations unseen)", vlm_first), ("trained with 2 more combinations", vlm)]:    acc = ...  # TO DO: accuracy per question type on scenes with a red triangle    print(f"{name:38s}", "  ".join(f"{k} {acc[k]:.3f}" for k in acc))
Show the correction
PythonComplete solution · compare two training sets
# Keep the first model to compare with the new one.vlm_first = vlm                                 # the model of Part 4: three combinations never seen# make_dataset reads this global variable: now only the red triangle is forbidden in training.HELD_OUT = {("red", "triangle")}  # only the red triangle stays unseen: the blue circle and the yellow square are now in the training scenesrng = np.random.default_rng(SEED + 1)img_tr, q_tr, a_tr = make_dataset(30000, rng)    # new training scenes (the red triangle never appears)img_va, q_va, a_va = make_dataset(2000, rng)     # new validation scenes# held_out=True gives scenes in which at least one object is a red triangle.img_ho, q_ho, a_ho = make_dataset(1000, rng, held_out=True)  # scenes that contain a red trianglekeras.utils.set_random_seed(SEED)# New weights, same architecture and same seed: the only difference is the training data.vlm = build_vlm()                               # same architecture, same training, new datahistory = train(vlm)print("best epoch", int(np.argmin(history.history["val_loss"])) + 1)for name, model in [("first model (3 combinations unseen)", vlm_first), ("trained with 2 more combinations", vlm)]:    # The same evaluation function, now with the model given as an argument.    acc = accuracy_by_type(img_ho, q_ho, a_ho, model)  # accuracy per question type on scenes with a red triangle    print(f"{name:38s}", "  ".join(f"{k} {acc[k]:.3f}" for k in acc))

scenes with a red trianglecolourshapeposition
first model (3 combinations unseen)0.3510.3580.568
trained with 2 more combinations0.4970.5000.856

Seeing two more combinations during training helps a lot on the position question (0.568 to 0.856), but the colour and shape questions stay around 0.5. In these scenes the question concerns the red triangle about half of the time, and the other object (a combination seen in training) the rest of the time: a score of about 0.5 is what we would get if the model answered correctly about the familiar object and wrongly about the red triangle. This is a plausible reading, not a proof: check it by splitting the accuracy according to the object that the question is about. Whatever the exact mechanism, the model does not compose “red” and “triangle” from its parts after seeing 11 of the 12 combinations. Going from 9 to 11 combinations improves the result without solving the problem: what is missing is variety and scale in the data, not a different training loop.

Part 6 · A vision transformer encoder

Course

From a small encoder to a vision transformer (ViT)

So far the encoder of Part 2 was one block applied to 16 patches. A real vision transformer (Dosovitskiy et al., 2021) is the same idea, made systematic: cut the image into patches, project each patch linearly, add a position vector, and apply a stack of transformer blocks. Two details matter for a VLM.

  • No causal mask. In a language model a word only sees the previous words. In an image there is no “before”: every patch can look at every patch.
  • The class token. One extra learned vector, cls, is added in front of the patches. After the blocks, its output is a summary of the whole image. A classifier, or CLIP, uses this vector; a VLM keeps the 16 patch outputs.
A vision transformer encoder with a class token
A vision transformer: patches, patch embedding, class token, positions, transformer blocks.

The encoder of this page has 3 blocks, width 64 and 17 tokens (1 + 16), for 114,048 parameters.

Exercise

Exercise 6.1 · build the encoder with a class token

  1. Complete ClassToken: a layer that owns one learned vector of size 64 and puts it in front of every sequence of the batch.
  2. In vit_encoder: patches, Dense projection, class token, positions, three blocks. Check the output shape $(\text{None},17,64)$.
  3. Count the parameters of the encoder and of one block. Which part holds most of them?
PythonStarting code · a ViT encoder
class ClassToken(layers.Layer):    """A learned vector prepended to the sequence of patch tokens: it will summarize the whole image."""    def build(self, input_shape):        self.cls = ...  # TO DO: one trainable token of dimension D    def call(self, x):        cls = ...  # TO DO: the same token for every image of the batch        return ...  # TO DO: (batch, 1 + 16, D): the class token comes firstdef vit_encoder(image, depth=3, name="vit"):    x = ...  # TO DO: one token per 8 x 8 patch    x = layers.Reshape((N_PATCH, D))(x)    x = ClassToken(name=f"{name}_cls")(x)                                                  # prepend the class token    x = AddPosition(N_PATCH + 1, name=f"{name}_pos")(x)                                    # one position vector per token, class token included    for i in range(depth):        x = ...  # TO DO: bidirectional transformer blocks    return layers.LayerNormalization(name=f"{name}_out")(x)                                 # (batch, 17, D)image_in = keras.Input((IMG, IMG, 3))vit = keras.Model(image_in, vit_encoder(image_in), name="vit")print("output shape:", vit.output_shape, "| parameters:", vit.count_params())print("one block:", sum(l.count_params() for l in vit.layers if l.name.startswith("vit0") or l.name.endswith("_a0") or "vit0" in l.name))tokens = vit(img_va[:2])print("class token and patch tokens:", tokens[:, 0].shape, tokens[:, 1:].shape)
Show the correction
PythonComplete solution · class token and encoder
class ClassToken(layers.Layer):    """A learned vector prepended to the sequence of patch tokens: it will summarize the whole image."""    def build(self, input_shape):        self.cls = self.add_weight(name="cls", shape=(1, 1, D), initializer="zeros")  # one trainable token of dimension D    def call(self, x):        cls = tf.tile(self.cls, [tf.shape(x)[0], 1, 1])  # the same token for every image of the batch        return tf.concat([cls, x], axis=1)  # (batch, 1 + 16, D): the class token comes firstdef vit_encoder(image, depth=3, name="vit"):    x = layers.Conv2D(D, PATCH, strides=PATCH, name=f"{name}_patch")(image)  # one token per 8 x 8 patch    x = layers.Reshape((N_PATCH, D))(x)    x = ClassToken(name=f"{name}_cls")(x)                                                  # prepend the class token    x = AddPosition(N_PATCH + 1, name=f"{name}_pos")(x)                                    # one position vector per token, class token included    for i in range(depth):        x = block(x, f"{name}{i}")  # bidirectional transformer blocks    return layers.LayerNormalization(name=f"{name}_out")(x)                                 # (batch, 17, D)image_in = keras.Input((IMG, IMG, 3))vit = keras.Model(image_in, vit_encoder(image_in), name="vit")print("output shape:", vit.output_shape, "| parameters:", vit.count_params())print("one block:", sum(l.count_params() for l in vit.layers if l.name.startswith("vit0") or l.name.endswith("_a0") or "vit0" in l.name))tokens = vit(img_va[:2])print("class token and patch tokens:", tokens[:, 0].shape, tokens[:, 1:].shape)

The output has 17 tokens of size 64 and the encoder has 114,048 parameters; one block has 16,896, so the three blocks hold about 44% of them and the rest is the patch projection and the position vectors. The class token is just a trainable parameter: the attention layers let it collect information from all the patches.

Exercise

Exercise 6.2 · what does the patch size cost?

  1. Complete block_macs: multiply-accumulate operations of one block for $T$ tokens of width $D$ (projections $4TD^2$, attention $2T^2D$, feed-forward $8TD^2$).
  2. Print a table for patch sizes 2, 4, 8 and 16 on a $32\times32$ image: tokens, embedding parameters, attention entries, MACs, and the share of the attention.
  3. Which patch size would you choose for a $224\times224$ photograph, and why?
PythonStarting code · cost against patch size
def block_macs(n_tokens, width=D, ffn=FFN):    """Multiply-accumulate operations of one transformer block on n_tokens tokens."""    projections = ...  # TO DO: queries, keys, values and output projections    attention = ...  # TO DO: scores QK^T and the weighted sum of the values    mlp = ...  # TO DO: the two Dense layers of the feed-forward network    return projections + attention + mlpprint(f"{'patch':>5s} {'tokens':>7s} {'embed params':>13s} {'attention entries':>18s} {'MACs per block':>15s} {'attention share':>16s}")for patch in [2, 4, 8, 16]:    n_tokens = ...  # TO DO: patches plus the class token    embed = (patch * patch * 3 + 1) * D                      # the patch-embedding convolution    total = block_macs(n_tokens)    share = 2 * n_tokens ** 2 * D / total    print(f"{patch:5d} {n_tokens:7d} {embed:13,d} {n_tokens ** 2:18,d} {total:15,d} {share:16.2f}")
Show the correction
PythonComplete solution · cost table
def block_macs(n_tokens, width=D, ffn=FFN):    """Multiply-accumulate operations of one transformer block on n_tokens tokens."""    projections = 4 * n_tokens * width ** 2  # queries, keys, values and output projections    attention = 2 * n_tokens ** 2 * width  # scores QK^T and the weighted sum of the values    mlp = 2 * n_tokens * width * ffn  # the two Dense layers of the feed-forward network    return projections + attention + mlpprint(f"{'patch':>5s} {'tokens':>7s} {'embed params':>13s} {'attention entries':>18s} {'MACs per block':>15s} {'attention share':>16s}")for patch in [2, 4, 8, 16]:    n_tokens = (IMG // patch) ** 2 + 1  # patches plus the class token    embed = (patch * patch * 3 + 1) * D                      # the patch-embedding convolution    total = block_macs(n_tokens)    share = 2 * n_tokens ** 2 * D / total    print(f"{patch:5d} {n_tokens:7d} {embed:13,d} {n_tokens ** 2:18,d} {total:15,d} {share:16.2f}")

Halving the patch size multiplies the number of tokens by 4 and the number of attention entries by 16: with patches of 2 pixels, half of the computation is attention and the model sees 257 tokens. Patches of 8 pixels are a good compromise for these scenes. For a photograph, 16 pixels gives $14\times14=196$ tokens, which is why “ViT-B/16” is standard.

Part 7 · Pretrain the encoder with captions

Course

Teach the encoder with captions: contrastive learning

To answer questions an encoder must already know what “red”, “circle” or “left” look like. Real VLMs do not learn this from the questions: their encoder is pretrained with captions, as in CLIP (Radford et al., 2021). Two towers, one for images and one for texts, map their input to vectors of size 64 that are normalized. For a batch of $B$ pairs (image, caption), with embeddings $u_i$ and $v_i$:

\[ s_{ij}=\frac{u_i\cdot v_j}{\tau},\qquad \mathcal{L}=\frac12\Big(\underbrace{-\frac1B\sum_i \log\frac{e^{s_{ii}}}{\sum_j e^{s_{ij}}}}_{\text{image}\to\text{caption}}\;\underbrace{-\frac1B\sum_j \log\frac{e^{s_{jj}}}{\sum_i e^{s_{ij}}}}_{\text{caption}\to\text{image}}\Big).\]

It is a cross-entropy where, for each image, the correct caption is the one of the same row and the $B-1$ other captions of the batch are the wrong answers (and the same for each caption). The temperature $\tau$ ($0.07$ here) sharpens the softmax. A model that treats all captions alike has the loss $\log B$; when the pairs are well aligned it tends to $0$.

Contrastive pretraining with an image tower and a text tower
Two towers and the similarity matrix of a batch: the diagonal holds the true pairs.

Here captions are generated from the scene: “a red circle and a blue square”. The vocabulary has 42 distinct captions, so two images may share a caption: this must be taken into account when testing retrieval.

Exercise

Exercise 7.1 · captions for scenes

  1. Complete make_caption: from the colours and shapes of the two objects, build the caption “a COLOR SHAPE and a COLOR SHAPE”.
  2. Generate 20,000 training scenes and 2,000 validation scenes with their captions and encode them as token sequences.
PythonStarting code · scenes with captions
CAPS = ["a", "and"] + COLORS + SHAPES                       # the 9 words of the captionsCAP_ID = {w: i for i, w in enumerate(CAPS)}def make_scenes(n, rng, held_out=False):    images, scenes = [], []    for _ in range(n):        objs = ...  # TO DO: the same scene generator as Part 1        objs = ...  # TO DO: order the objects from left to right        images.append(draw_scene(objs, rng)); scenes.append(objs)    return np.stack(images), scenesdef make_caption(objs):    (c1, s1, _, _), (c2, s2, _, _) = objs    words = ...  # TO DO: "a red square and a blue circle", left object first    return wordsdef encode_caption(words):    return [CAP_ID[w] for w in words]rng_w = np.random.default_rng(SEED + 10)img_c, scenes_c = make_scenes(20000, rng_w)img_cv, scenes_cv = make_scenes(2000, rng_w)cap_c = np.array([encode_caption(make_caption(o)) for o in scenes_c])cap_cv = np.array([encode_caption(make_caption(o)) for o in scenes_cv])print(" ".join(make_caption(scenes_c[0])), "|", cap_c[0], "| shapes:", img_c.shape, cap_c.shape)print("distinct captions:", len({tuple(c) for c in cap_c}))
Show the correction
PythonComplete solution · captions
CAPS = ["a", "and"] + COLORS + SHAPES                       # the 9 words of the captionsCAP_ID = {w: i for i, w in enumerate(CAPS)}def make_scenes(n, rng, held_out=False):    images, scenes = [], []    for _ in range(n):        objs = sample_objects(rng, held_out)  # the same scene generator as Part 1        objs = sorted(objs, key=lambda o: o[2])  # order the objects from left to right        images.append(draw_scene(objs, rng)); scenes.append(objs)    return np.stack(images), scenesdef make_caption(objs):    (c1, s1, _, _), (c2, s2, _, _) = objs    words = ["a", c1, s1, "and", "a", c2, s2]  # "a red square and a blue circle", left object first    return wordsdef encode_caption(words):    return [CAP_ID[w] for w in words]rng_w = np.random.default_rng(SEED + 10)img_c, scenes_c = make_scenes(20000, rng_w)img_cv, scenes_cv = make_scenes(2000, rng_w)cap_c = np.array([encode_caption(make_caption(o)) for o in scenes_c])cap_cv = np.array([encode_caption(make_caption(o)) for o in scenes_cv])print(" ".join(make_caption(scenes_c[0])), "|", cap_c[0], "| shapes:", img_c.shape, cap_c.shape)print("distinct captions:", len({tuple(c) for c in cap_c}))

There are 42 distinct captions (ordered pairs of two different colour–shape objects).

Exercise

Exercise 7.2 · the contrastive loss

  1. Complete clip_loss: normalize the embeddings, compute the $B\times B$ similarity matrix divided by $\tau$, and average the two cross-entropies with the diagonal as labels.
  2. Check it with $B=64$: aligned embeddings should give a value close to $0$ and random embeddings a large value; compare with $\log B$.
  3. Display the similarity matrix of aligned embeddings.
PythonStarting code · the CLIP loss
def clip_loss(img_emb, txt_emb, temperature=0.07):    img = ...  # TO DO: unit-norm embeddings: the dot product is a cosine    txt = tf.math.l2_normalize(txt_emb, axis=1)    logits = ...  # TO DO: (B, B) matrix: similarity of every image with every caption    labels = tf.range(tf.shape(logits)[0])                  # the matching pair is on the diagonal    ce = keras.losses.SparseCategoricalCrossentropy(from_logits=True)    loss_i = ...  # TO DO: image -> text: which caption goes with each image?    loss_t = ...  # TO DO: text -> image: which image goes with each caption?    return (loss_i + loss_t) / 2B = 64v = tf.constant(np.random.default_rng(1).normal(size=(B, 32)), dtype="float32")print("random embeddings :", float(clip_loss(v, tf.constant(np.random.default_rng(2).normal(size=(B, 32)), dtype="float32"))), "| log(B) =", np.log(B))print("aligned embeddings:", float(clip_loss(v, v)))print("aligned, temperature 1:", float(clip_loss(v, v, temperature=1.0)))sim = tf.math.l2_normalize(v, axis=1) @ tf.transpose(tf.math.l2_normalize(v, axis=1))plt.imshow(sim[:16, :16], cmap="viridis"); plt.title("cosine similarity, 16 aligned pairs: bright diagonal"); plt.colorbar(); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · InfoNCE in the two directions
def clip_loss(img_emb, txt_emb, temperature=0.07):    img = tf.math.l2_normalize(img_emb, axis=1)  # unit-norm embeddings: the dot product is a cosine    txt = tf.math.l2_normalize(txt_emb, axis=1)    logits = img @ tf.transpose(txt) / temperature  # (B, B) matrix: similarity of every image with every caption    labels = tf.range(tf.shape(logits)[0])                  # the matching pair is on the diagonal    ce = keras.losses.SparseCategoricalCrossentropy(from_logits=True)    loss_i = ce(labels, logits)  # image -> text: which caption goes with each image?    loss_t = ce(labels, tf.transpose(logits))  # text -> image: which image goes with each caption?    return (loss_i + loss_t) / 2B = 64v = tf.constant(np.random.default_rng(1).normal(size=(B, 32)), dtype="float32")print("random embeddings :", float(clip_loss(v, tf.constant(np.random.default_rng(2).normal(size=(B, 32)), dtype="float32"))), "| log(B) =", np.log(B))print("aligned embeddings:", float(clip_loss(v, v)))print("aligned, temperature 1:", float(clip_loss(v, v, temperature=1.0)))sim = tf.math.l2_normalize(v, axis=1) @ tf.transpose(tf.math.l2_normalize(v, axis=1))plt.imshow(sim[:16, :16], cmap="viridis"); plt.title("cosine similarity, 16 aligned pairs: bright diagonal"); plt.colorbar(); plt.show()

With $B=64$, aligned embeddings give $0.0007$ at $\tau=0.07$ and $3.2$ at $\tau=1$: the temperature controls how strongly the loss pushes the similarity of true pairs above the others. Random embeddings give $6.69$, above $\log64=4.16$: with $\tau=0.07$ the random cosines (about $\pm0.18$) become logits of size $\pm2.5$, so the model is confidently wrong. The value $\log B$ is the loss of a model that gives the same similarity to all captions.

Exercise

Exercise 7.3 · train the two towers

  1. Build the image tower (ViT, the output of the class token, Dense to 64) and the text tower (embedding, positions, two blocks, mean over the words, Dense to 64).
  2. Write a training step with tf.GradientTape that uses clip_loss, and train 12 epochs with batches of 256.
  3. Plot the loss. At which value does it stop, and why can it not reach $0$?
PythonStarting code · contrastive training
EMB = 64def image_tower():    image = keras.Input((IMG, IMG, 3))    tokens = vit_encoder(image, depth=3, name="clipvit")    return ...  # TO DO: the class token, projected to the shared spacedef text_tower():    words = keras.Input((7,), dtype="int32")    x = layers.Embedding(len(CAPS), D)(words)    x = AddPosition(7)(x)    for i in range(2):        x = ...  # TO DO: a small bidirectional transformer over the 7 words    x = layers.GlobalAveragePooling1D()(x)    return keras.Model(words, layers.Dense(EMB, name="text_projection")(x), name="text_tower")                  # mean of the word tokens, projectedkeras.utils.set_random_seed(SEED)img_tower, txt_tower = image_tower(), text_tower()optimizer = keras.optimizers.Adam(1e-3)BATCH, EPOCHS = 256, 12@tf.functiondef train_step(images, captions):    with tf.GradientTape() as tape:        loss = ...  # TO DO: one loss for both towers    variables = img_tower.trainable_variables + txt_tower.trainable_variables    ...  # TO DO: both towers are updated together    return lossn_batches = len(img_c) // BATCHhistory = []for epoch in range(EPOCHS):    order = np.random.default_rng(epoch).permutation(len(img_c))    losses = [float(train_step(img_c[order[b * BATCH:(b + 1) * BATCH]], cap_c[order[b * BATCH:(b + 1) * BATCH]])) for b in range(n_batches)]    history.append(np.mean(losses))    if epoch % 3 == 0 or epoch == EPOCHS - 1:        print(f"epoch {epoch + 1:2d}: contrastive loss {np.mean(losses):.3f} (chance level log(256) = {np.log(256):.3f})")plt.plot(range(1, EPOCHS + 1), history, "o-", label="contrastive loss"); plt.axhline(np.log(BATCH), ls="--", c="gray", label="chance level log(256)")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · training loop
EMB = 64def image_tower():    image = keras.Input((IMG, IMG, 3))    tokens = vit_encoder(image, depth=3, name="clipvit")    return keras.Model(image, layers.Dense(EMB, name="image_projection")(tokens[:, 0]), name="image_tower")  # the class token, projected to the shared spacedef text_tower():    words = keras.Input((7,), dtype="int32")    x = layers.Embedding(len(CAPS), D)(words)    x = AddPosition(7)(x)    for i in range(2):        x = block(x, f"txt{i}")  # a small bidirectional transformer over the 7 words    x = layers.GlobalAveragePooling1D()(x)    return keras.Model(words, layers.Dense(EMB, name="text_projection")(x), name="text_tower")                  # mean of the word tokens, projectedkeras.utils.set_random_seed(SEED)img_tower, txt_tower = image_tower(), text_tower()optimizer = keras.optimizers.Adam(1e-3)BATCH, EPOCHS = 256, 12@tf.functiondef train_step(images, captions):    with tf.GradientTape() as tape:        loss = clip_loss(img_tower(images, training=True), txt_tower(captions, training=True))  # one loss for both towers    variables = img_tower.trainable_variables + txt_tower.trainable_variables    optimizer.apply_gradients(zip(tape.gradient(loss, variables), variables))  # both towers are updated together    return lossn_batches = len(img_c) // BATCHhistory = []for epoch in range(EPOCHS):    order = np.random.default_rng(epoch).permutation(len(img_c))    losses = [float(train_step(img_c[order[b * BATCH:(b + 1) * BATCH]], cap_c[order[b * BATCH:(b + 1) * BATCH]])) for b in range(n_batches)]    history.append(np.mean(losses))    if epoch % 3 == 0 or epoch == EPOCHS - 1:        print(f"epoch {epoch + 1:2d}: contrastive loss {np.mean(losses):.3f} (chance level log(256) = {np.log(256):.3f})")plt.plot(range(1, EPOCHS + 1), history, "o-", label="contrastive loss"); plt.axhline(np.log(BATCH), ls="--", c="gray", label="chance level log(256)")plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()

The loss falls from 4.19 (the chance level for a batch of 256 is $\log256=5.55$) to 1.91 after 12 epochs. It cannot reach 0 because only 42 captions exist: a batch of 256 contains about 6 identical captions per caption, and they are counted as wrong answers for each other. The best possible value is close to $\log(256/42)\approx1.8$.

Exercise

Exercise 7.4 · retrieval

  1. Compute the embeddings of 2,000 validation images and of the 42 distinct captions.
  2. For each image, find the most similar caption and count it correct if it equals the true caption.
  3. Display three images with their retrieved captions and the similarity matrix.
PythonStarting code · image to caption retrieval
ie = ...  # TO DO: embeddings of the 2,000 validation imageste = ...  # TO DO: and of their captionssim = ie @ te.T                                                                                        # (2000, 2000) similarity matrixbest = ...  # TO DO: for each image, the most similar captionsame = np.array([tuple(cap_cv[b]) == tuple(cap_cv[i]) for i, b in enumerate(best)])                    # a retrieved caption that is identical to the true one is correctprint("image -> caption retrieval, top-1:", float(same.mean()), "| chance level for 2,000 captions: about", float(np.mean([np.mean([tuple(c) == tuple(cap_cv[i]) for c in cap_cv]) for i in range(200)])))for i in range(3):    ranked = np.argsort(-sim[i])[:3]    print("image", i, "true:", " ".join(CAPS[w] for w in cap_cv[i]), "| retrieved:", [" ".join(CAPS[w] for w in cap_cv[j]) for j in ranked[:2]])plt.imshow(sim[:32, :32], cmap="viridis"); plt.title("image-caption similarity, 32 validation pairs"); plt.colorbar(); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · retrieval of captions
ie = tf.math.l2_normalize(img_tower.predict(img_cv, batch_size=256, verbose=0), axis=1).numpy()  # embeddings of the 2,000 validation imageste = tf.math.l2_normalize(txt_tower.predict(cap_cv, batch_size=256, verbose=0), axis=1).numpy()  # and of their captionssim = ie @ te.T                                                                                        # (2000, 2000) similarity matrixbest = sim.argmax(axis=1)  # for each image, the most similar captionsame = np.array([tuple(cap_cv[b]) == tuple(cap_cv[i]) for i, b in enumerate(best)])                    # a retrieved caption that is identical to the true one is correctprint("image -> caption retrieval, top-1:", float(same.mean()), "| chance level for 2,000 captions: about", float(np.mean([np.mean([tuple(c) == tuple(cap_cv[i]) for c in cap_cv]) for i in range(200)])))for i in range(3):    ranked = np.argsort(-sim[i])[:3]    print("image", i, "true:", " ".join(CAPS[w] for w in cap_cv[i]), "| retrieved:", [" ".join(CAPS[w] for w in cap_cv[j]) for j in ranked[:2]])plt.imshow(sim[:32, :32], cmap="viridis"); plt.title("image-caption similarity, 32 validation pairs"); plt.colorbar(); plt.show()

The top-1 accuracy is 1.00 on the validation scenes, against about 0.024 by chance. The encoder has learned colours, shapes and the two-object structure with no question at all: this is the “knowledge” that Part 8 reuses. It does not say anything yet about the captions of combinations never seen.

Part 8 · A VLM built on the pretrained encoder

Course

Build the VLM on a frozen encoder

We now build the VLM as LLaVA does: the pretrained ViT is frozen (its weights are not updated), its 16 patch outputs go through a trainable projector, and a small language transformer reads the projected patches and the question. Only the projector and the language model are trained: 73,673 parameters. Two ways to give the image to the language model are in use:

  • concatenation (LLaVA, PaliGemma): the image tokens are put in front of the question tokens in one sequence;
  • cross-attention (Flamingo): the language blocks keep a sequence of words only and add a layer whose queries come from the words and whose keys and values come from the image;
  • a third family compresses the patches with a fixed number of learned queries (BLIP-2) so that long images cost a fixed number of tokens.
Three ways to connect a frozen vision encoder to a language model
Three families of VLM: concatenation, cross-attention, and learned queries.
Exercise

Exercise 8.1 · freeze the encoder and precompute the features

  1. Extract the image tower of the contrastive model up to the layer clipvit_out and set trainable = False.
  2. Precompute the 17 tokens of the 30,000 training scenes, of the validation scenes and of the 1,000 held-out combinations. Check the shape and that the encoder has no trainable weight.
PythonStarting code · frozen features
vit_frozen = ...  # TO DO: the ViT of the image tower, up to its patch tokensvit_frozen.trainable = ...  # TO DO: frozen: its weights will not change againdef vit_tokens(images):    return ...  # TO DO: (n, 17, 64): the class token and the 16 patch tokensdef question_type(q):    words = [VOCAB[i] for i in q]    return "color" if "color" in words else "shape" if "shape" in words else "left of"rng_v = np.random.default_rng(SEED + 20)def vqa_set(n, held_out=False):    imgs, qs, ans = [], [], []    for _ in range(n):        objs = sample_objects(rng_v, held_out)        words, a = make_question(objs, rng_v)        imgs.append(draw_scene(objs, rng_v)); qs.append(encode(words)); ans.append(ANS_ID[a])    return np.stack(imgs), np.array(qs), np.array(ans)img_t, q_t, a_t = vqa_set(30000)img_v, q_v, a_v = vqa_set(2000)img_h, q_h, a_h = vqa_set(1000, held_out=True)tok_t, tok_v, tok_h = vit_tokens(img_t), vit_tokens(img_v), vit_tokens(img_h)print("frozen features:", tok_t.shape, "| the encoder has", sum(int(np.prod(w.shape)) for w in vit_frozen.trainable_weights), "trainable weights now")
Show the correction
PythonComplete solution · frozen ViT features
vit_frozen = keras.Model(img_tower.input, img_tower.get_layer("clipvit_out").output)  # the ViT of the image tower, up to its patch tokensvit_frozen.trainable = False  # frozen: its weights will not change againdef vit_tokens(images):    return vit_frozen.predict(images, batch_size=256, verbose=0)  # (n, 17, 64): the class token and the 16 patch tokensdef question_type(q):    words = [VOCAB[i] for i in q]    return "color" if "color" in words else "shape" if "shape" in words else "left of"rng_v = np.random.default_rng(SEED + 20)def vqa_set(n, held_out=False):    imgs, qs, ans = [], [], []    for _ in range(n):        objs = sample_objects(rng_v, held_out)        words, a = make_question(objs, rng_v)        imgs.append(draw_scene(objs, rng_v)); qs.append(encode(words)); ans.append(ANS_ID[a])    return np.stack(imgs), np.array(qs), np.array(ans)img_t, q_t, a_t = vqa_set(30000)img_v, q_v, a_v = vqa_set(2000)img_h, q_h, a_h = vqa_set(1000, held_out=True)tok_t, tok_v, tok_h = vit_tokens(img_t), vit_tokens(img_v), vit_tokens(img_h)print("frozen features:", tok_t.shape, "| the encoder has", sum(int(np.prod(w.shape)) for w in vit_frozen.trainable_weights), "trainable weights now")

The features have shape $(30000,17,64)$. Because the encoder is frozen, computing them once makes all later trainings much faster.

Exercise

Exercise 8.2 · projector, language model and training

  1. Complete build_frozen_vlm: Dense projector on the 17 tokens, concatenation with the question embeddings, two transformer blocks, answer read at the <ans> position.
  2. Train it on the 30,000 questions and measure the accuracy per type on validation and on the unseen combinations.
PythonStarting code · the frozen-encoder VLM
def build_frozen_vlm(n_blocks=2):    vis = keras.Input((N_PATCH + 1, D), name="vision_tokens")                  # precomputed tokens of the frozen ViT    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    v = ...  # TO DO: the projector: the only part that connects the two worlds    q = layers.Embedding(len(VOCAB), D, name="word_embedding")(question)    q = AddPosition(QLEN + 1, name="word_position")(q)    z = ...  # TO DO: vision tokens then question tokens, as in Part 3    for i in range(n_blocks):        z = ...  # TO DO: the language model    z = layers.LayerNormalization()(z)    return keras.Model([vis, question], layers.Dense(len(ANSWERS), name="answer")(z[:, -1]))def train_vlm(model, data, answers, val, val_answers, epochs=40, rate=1e-3, batch=128):    model.compile(optimizer=keras.optimizers.Adam(rate), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])    stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=6, restore_best_weights=True)    return model.fit(data, answers, validation_data=(val, val_answers), batch_size=batch, epochs=epochs, callbacks=[stop], verbose=0)keras.utils.set_random_seed(SEED)frozen_vlm = build_frozen_vlm()hist = train_vlm(frozen_vlm, {"vision_tokens": tok_t, "question": q_t}, a_t, {"vision_tokens": tok_v, "question": q_v}, a_v)trainable = sum(int(np.prod(w.shape)) for w in frozen_vlm.trainable_weights)print("trainable parameters (projector and language model):", trainable, "| epochs:", len(hist.history["loss"]))def accuracy_per_type(model, data, questions, answers):    pred = model.predict(data, batch_size=256, verbose=0).argmax(axis=-1)    kinds = np.array([question_type(q) for q in questions])    return {k: float((pred[kinds == k] == answers[kinds == k]).mean()) for k in ["color", "shape", "left of"]}print("validation:", accuracy_per_type(frozen_vlm, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v))print("unseen combinations:", accuracy_per_type(frozen_vlm, {"vision_tokens": tok_h, "question": q_h}, q_h, a_h))
Show the correction
PythonComplete solution · training the projector and the language model
def build_frozen_vlm(n_blocks=2):    vis = keras.Input((N_PATCH + 1, D), name="vision_tokens")                  # precomputed tokens of the frozen ViT    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    v = layers.Dense(D, name="projector")(vis)  # the projector: the only part that connects the two worlds    q = layers.Embedding(len(VOCAB), D, name="word_embedding")(question)    q = AddPosition(QLEN + 1, name="word_position")(q)    z = layers.Concatenate(axis=1)([v, q])  # vision tokens then question tokens, as in Part 3    for i in range(n_blocks):        z = block(z, f"lm{i}")  # the language model    z = layers.LayerNormalization()(z)    return keras.Model([vis, question], layers.Dense(len(ANSWERS), name="answer")(z[:, -1]))def train_vlm(model, data, answers, val, val_answers, epochs=40, rate=1e-3, batch=128):    model.compile(optimizer=keras.optimizers.Adam(rate), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])    stop = keras.callbacks.EarlyStopping(monitor="val_loss", patience=6, restore_best_weights=True)    return model.fit(data, answers, validation_data=(val, val_answers), batch_size=batch, epochs=epochs, callbacks=[stop], verbose=0)keras.utils.set_random_seed(SEED)frozen_vlm = build_frozen_vlm()hist = train_vlm(frozen_vlm, {"vision_tokens": tok_t, "question": q_t}, a_t, {"vision_tokens": tok_v, "question": q_v}, a_v)trainable = sum(int(np.prod(w.shape)) for w in frozen_vlm.trainable_weights)print("trainable parameters (projector and language model):", trainable, "| epochs:", len(hist.history["loss"]))def accuracy_per_type(model, data, questions, answers):    pred = model.predict(data, batch_size=256, verbose=0).argmax(axis=-1)    kinds = np.array([question_type(q) for q in questions])    return {k: float((pred[kinds == k] == answers[kinds == k]).mean()) for k in ["color", "shape", "left of"]}print("validation:", accuracy_per_type(frozen_vlm, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v))print("unseen combinations:", accuracy_per_type(frozen_vlm, {"vision_tokens": tok_h, "question": q_h}, q_h, a_h))

colourshapeposition
validation1.0001.0001.000
unseen combinations0.2630.2120.566

Honest result: pretraining the encoder does not remove the failure on unseen combinations. The captions of the pretraining contained the same combinations as the questions, so the encoder never saw a blue circle either. What pretraining changes is the cost of learning, which the next exercise measures.

Exercise

Exercise 8.3 · how many labels do we need?

  1. Keep only 1,000 labelled questions. Train (a) the VLM of Part 3 from scratch on pixels and (b) the frozen-encoder VLM, with the same language model and the same number of epochs.
  2. Print the accuracy per question type for each of them.
  3. Which type benefits most from pretraining? Which one stays hard?
PythonStarting code · pretraining against labels
n_small = 1000                                                              # a small labelled set of questions and answerssmall = slice(0, n_small)keras.utils.set_random_seed(SEED)scratch = ...  # TO DO: the Part 3 model, learned from the pixels, with the same two blockstrain_vlm(scratch, {"image": img_t[small], "question": q_t[small]}, a_t[small], {"image": img_v, "question": q_v}, a_v, epochs=80)keras.utils.set_random_seed(SEED)pretrained = ...  # TO DO: the frozen ViT of the contrastive pretrainingtrain_vlm(pretrained, {"vision_tokens": tok_t[small], "question": q_t[small]}, a_t[small], {"vision_tokens": tok_v, "question": q_v}, a_v, epochs=80)res_s = accuracy_per_type(scratch, {"image": img_v, "question": q_v}, q_v, a_v)res_p = accuracy_per_type(pretrained, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v)print(f"{n_small} labelled questions, validation accuracy per question type")print(f"{'':28s} {'colour':>7s} {'shape':>7s} {'left of':>8s}")print(f"{'from scratch (pixels)':28s} {res_s['color']:7.3f} {res_s['shape']:7.3f} {res_s['left of']:8.3f}")print(f"{'frozen contrastive ViT':28s} {res_p['color']:7.3f} {res_p['shape']:7.3f} {res_p['left of']:8.3f}")
Show the correction
PythonComplete solution · 1,000 labelled questions
n_small = 1000                                                              # a small labelled set of questions and answerssmall = slice(0, n_small)keras.utils.set_random_seed(SEED)scratch = build_vlm(n_blocks=2)  # the Part 3 model, learned from the pixels, with the same two blockstrain_vlm(scratch, {"image": img_t[small], "question": q_t[small]}, a_t[small], {"image": img_v, "question": q_v}, a_v, epochs=80)keras.utils.set_random_seed(SEED)pretrained = build_frozen_vlm()  # the frozen ViT of the contrastive pretrainingtrain_vlm(pretrained, {"vision_tokens": tok_t[small], "question": q_t[small]}, a_t[small], {"vision_tokens": tok_v, "question": q_v}, a_v, epochs=80)res_s = accuracy_per_type(scratch, {"image": img_v, "question": q_v}, q_v, a_v)res_p = accuracy_per_type(pretrained, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v)print(f"{n_small} labelled questions, validation accuracy per question type")print(f"{'':28s} {'colour':>7s} {'shape':>7s} {'left of':>8s}")print(f"{'from scratch (pixels)':28s} {res_s['color']:7.3f} {res_s['shape']:7.3f} {res_s['left of']:8.3f}")print(f"{'frozen contrastive ViT':28s} {res_p['color']:7.3f} {res_p['shape']:7.3f} {res_p['left of']:8.3f}")

1,000 questionscolourshapeposition
from scratch (pixels)0.7390.5940.512
frozen contrastive ViT0.9970.9810.875

With the pretrained encoder, 1,000 questions are enough to reach 0.98 or more on colour and shape; from scratch, the model is still weak on shape and at chance on position (0.512). This is the main argument for pretraining: the questions only have to teach the reading of the image, not the vision.

Exercise

Exercise 8.4 · cross-attention instead of concatenation

  1. Complete build_cross_vlm: the question words are the queries and the 17 image tokens are the keys and the values of MultiHeadAttention, in each language block.
  2. Train it on the same 1,000 questions and compare with the concatenation variant.
  3. Compare the parameter counts and the sequence length seen by the language model.
PythonStarting code · cross-attention variant
def build_cross_vlm(n_blocks=2):    """Flamingo-like variant: the language model reads the question; each block looks at the image tokens by cross-attention."""    vis = keras.Input((N_PATCH + 1, D), name="vision_tokens")    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    kv = layers.Dense(D, name="projector")(vis)    x = layers.Embedding(len(VOCAB), D)(question)    x = AddPosition(QLEN + 1)(x)    for i in range(n_blocks):        h = layers.LayerNormalization()(x)        h = ...  # TO DO: queries from the words, keys and values from the image tokens        x = layers.Add()([x, h])        x = block(x, f"xl{i}")                                                                               # self-attention among the words, then the feed-forward layer    x = layers.LayerNormalization()(x)    return keras.Model([vis, question], layers.Dense(len(ANSWERS))(x[:, -1]))keras.utils.set_random_seed(SEED)cross_vlm = build_cross_vlm()print("parameters: cross-attention VLM", cross_vlm.count_params(), "| concatenation VLM", frozen_vlm.count_params())train_vlm(cross_vlm, {"vision_tokens": tok_t[:n_small], "question": q_t[:n_small]}, a_t[:n_small], {"vision_tokens": tok_v, "question": q_v}, a_v, epochs=80)res_c = accuracy_per_type(cross_vlm, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v)print("cross-attention variant, 1,000 questions:", res_c)
Show the correction
PythonComplete solution · cross-attention VLM
def build_cross_vlm(n_blocks=2):    """Flamingo-like variant: the language model reads the question; each block looks at the image tokens by cross-attention."""    vis = keras.Input((N_PATCH + 1, D), name="vision_tokens")    question = keras.Input((QLEN + 1,), dtype="int32", name="question")    kv = layers.Dense(D, name="projector")(vis)    x = layers.Embedding(len(VOCAB), D)(question)    x = AddPosition(QLEN + 1)(x)    for i in range(n_blocks):        h = layers.LayerNormalization()(x)        h = layers.MultiHeadAttention(HEADS, D // HEADS, name=f"cross{i}")(query=h, value=kv, key=kv)  # queries from the words, keys and values from the image tokens        x = layers.Add()([x, h])        x = block(x, f"xl{i}")                                                                               # self-attention among the words, then the feed-forward layer    x = layers.LayerNormalization()(x)    return keras.Model([vis, question], layers.Dense(len(ANSWERS))(x[:, -1]))keras.utils.set_random_seed(SEED)cross_vlm = build_cross_vlm()print("parameters: cross-attention VLM", cross_vlm.count_params(), "| concatenation VLM", frozen_vlm.count_params())train_vlm(cross_vlm, {"vision_tokens": tok_t[:n_small], "question": q_t[:n_small]}, a_t[:n_small], {"vision_tokens": tok_v, "question": q_v}, a_v, epochs=80)res_c = accuracy_per_type(cross_vlm, {"vision_tokens": tok_v, "question": q_v}, q_v, a_v)print("cross-attention variant, 1,000 questions:", res_c)

1,000 questionscolourshapeposition
concatenation (73,673 parameters)0.9970.9810.875
cross-attention (107,209 parameters)0.9740.9220.896

Both reach similar accuracy; the differences are within what one seed can produce, so do not rank them from this single run. The practical differences are elsewhere: concatenation lengthens the sequence by the number of image tokens (17 here, hundreds in practice), whereas cross-attention keeps it short but adds parameters.

Part 9 · Deliverables and limits

Exercise

Build a defensible experiment

  1. Draw the architecture and state the shape of the tokens at every stage (patches, projector, fused sequence, answer).
  2. Count the parameters of each part and explain which part a real VLM would reuse from a pretrained model.
  3. Report the training and validation curves and how the epoch was chosen.
  4. Report accuracy per question type with real, blank and shuffled images, and compare with chance.
  5. Report test and unseen-combination accuracy, and discuss the gap honestly.
  6. Report the contrastive loss, the retrieval accuracy, and the comparison between the model from scratch and the model on the frozen ViT with 1,000 questions (Parts 6 to 8), including the cross-attention variant.
  7. Report the extension of Exercise 5.4 (more combinations in training) and interpret it. Optional: try a patch size of 4.

Deliver a rerunnable notebook, a results table, the attention figure and a paragraph of limits.

Course

What the results do not show

These scenes are simple, clean, synthetic and generated by a rule; the questions use a closed vocabulary and a single-word answer. Performance here says little about photographs, open questions or long answers. Real VLMs add a pretrained vision encoder and language model, large and varied training data, instruction following, and an evaluation on realistic benchmarks. They can also hallucinate, that is, describe objects that are not in the image: this is why we test them with blank and shuffled inputs, with unseen combinations, and with questions whose answers can be checked.

References and related learning

Course

Papers and documentation