Looking for the lab runner…

Hands-on lab 05 of 10 · VLM fusion

Fusing image tokens into a language model (LLaVA style)

A vision-language model (VLM) is a ViT + a small projector + an LLM. The ViT turns the image into patch features; the projector maps each feature into the LLM's embedding space; the LLM then reads image tokens and text tokens as one sequence. You build the fusion: token counting, the 2 x 2 "pixel shuffle" merge, the MLP projector, the joint sequence, and its attention mask.

Time: 45-60 minCheck: python labs/check.py 5

The maths, step by step

B batch, P patch size, d_v vision width, d_t LLM width (d in the decoder code), V vocab, N_v image tokens, N_t text tokens (as in the VLM guide).

  1. 1
    How many image tokens?
    N_v = (H / P) * (W / P) / merge^2
    336 x 336, P = 14         → 24 * 24 = 576  (LLaVA-1.5)
    448 x 448, P = 14         → 1024; with a 2 x 2 merge → 256

    Every image token costs prefill compute and KV-cache memory, like text.

  2. 2

    2 x 2 merge (pixel shuffle, Qwen-VL / InternVL): on the patch grid gh x gw, stack each 2 x 2 neighbourhood along channels:

    [B, gh*gw, d_v] → [B, (gh/2)*(gw/2), 4*d_v]      4x fewer tokens
  3. 3
    Projector (LLaVA-1.5):
    z = W2 GELU(W1 v + b1) + b2
    [B, N_v, d_v] → [B, N_v, d_t]
  4. 4
    Joint sequence: image tokens first, then the text embeddings:
    x = cat([z, E[text_ids]], dim=1)                 [B, N_v + N_t, d_t]
  5. 5
    Attention mask over the joint sequence, N = N_v + N_t
    (True = may attend):
      causal (LLaVA):     allowed[i, j] = j <= i
      image-bidirectional option (a partial prefix-LM): additionally,
                          image token i sees ALL image tokens (bidirectional
                          inside the image block). A full prefix-LM
                          (PaliGemma, pi0) makes the whole prefix (image
                          AND prompt) bidirectional; here only the image.

    Text always sees every image token (they come first), and the image tokens never see the text.

  6. 6
    LLM decoder on x with that mask → logits [B, N, V]

    (the loss/next-token prediction uses only the text positions).

Read alongside

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 5: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab05_vlm_fusion.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.

Cells on this page:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 count image tokens

count_image_tokens(height, width, patch_size, merge=1)

to write

Number of image tokens the LLM sees for one height x width image.

The image is cut into patch_size x patch_size patches; then every merge x merge block of patches becomes one token. Raise ValueError if height or width is not a multiple of patch_size * merge.

Hint 1
patches per row = width // patch_size, per column = height // patch_size.
Hint 2
check divisibility by patch_size * merge first, then divide the patch count by merge * merge.

2 the 2 x 2 merge ("pixel shuffle")

pixel_shuffle_merge(x, grid_h, grid_w, r=2)

to write

Merge every r x r block of patch tokens into one token.

x: [B, grid_h * grid_w, d], tokens in row-major grid order. Returns [B, (grid_h // r) * (grid_w // r), r * r * d].

Merged token (i, j) (row-major over the coarse grid) is the concatenation, in row-major (dy, dx) order, of the r*r fine tokens at grid positions (r*i + dy, r*j + dx).

Hint 1
same idea as patchify in lab 04, but on a grid of tokens instead of pixels: reshape to [B, grid_h // r, r, grid_w // r, r, d].
Hint 2
you want [B, gh/r, gw/r, r(dy), r(dx), d] before the final reshape.
Hint 3
x.reshape(B, gh // r, r, gw // r, r, d).permute(0, 1, 3, 2, 4, 5) .reshape(B, (gh // r) * (gw // r), r * r * d)

3 the projector

class MLPProjector(nn.Module)

to write

LLaVA-1.5 projector: Linear(d_in, d_out) → GELU → Linear(d_out, d_out).

Write forward(x)

[B, N, d_in] → [B, N, d_out], applied to every image token independently.

Hint 1
one line; use the exact GELU (F.gelu default).

4 the joint sequence and its attention mask

build_sequence(image_embeds, text_embeds)

to write

Image tokens first, then text.

Args:

image_embeds: [B, N_v, d_t]  (already projected to the LLM width)
text_embeds:  [B, N_t, d_t]

Returns:

embeds:   [B, N_v + N_t, d_t]
is_image: [N_v + N_t] bool, True at the image positions
Hint 1
torch.cat along the sequence dim.
Hint 2
is_image = torch.arange(n_img + n_txt, device=...) < n_img

joint_attention_mask(n_img, n_txt, image_bidirectional=False, device=None)

to write

[N, N] bool mask over the joint sequence, N = n_img + n_txt; True = may attend.

image_bidirectional=False: plain causal mask (LLaVA). image_bidirectional=True: causal, except that image tokens also see every

other image token (image-bidirectional: a partial
prefix-LM that covers the image only).
Hint 1
start from the causal mask (lab 01): key j <= query i.
Hint 2
for the image-bidirectional variant, also allow the [:n_img, :n_img] block.
Hint 3
allowed = torch.ones(N, N, dtype=torch.bool, device=device).tril() if image_bidirectional: allowed[:n_img, :n_img] = True

G Given: a tiny LLM decoder that accepts an explicit attention mask

class DecoderBlock(nn.Module)

given
Show the given code (it is already written: just run it)

class TinyDecoder(nn.Module)

given
Show the given code (it is already written: just run it)

class VLMConfig

given
Show the given code (it is already written: just run it)

5 the fused forward pass

class TinyVLM(nn.Module)

to write

Write forward(vision_feats, text_ids, image_bidirectional=False)

Args:

vision_feats: [B, N_v, d_vision]  patch features from a ViT (lab 04)
text_ids:     [B, N_t]            token ids

Returns:

logits:       [B, N_v + N_t, vocab_size]
Hint 1
project the image, embed the text, build_sequence, joint_attention_mask, self.decoder(x, mask), self.lm_head.
Hint 2
create the mask on vision_feats.device.

✎ Scratch cell

Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).