Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 05 of 10 · VLM fusion
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.
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).
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 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
z = W2 GELU(W1 v + b1) + b2
[B, N_v, d_v] → [B, N_v, d_t]
x = cat([z, E[text_ids]], dim=1) [B, N_v + N_t, d_t]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.
[B, N, V](the loss/next-token prediction uses only the text positions).
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:
The lab file's imports. Run this cell first (or press Run all).
count_image_tokens(height, width, patch_size, merge=1)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.
pixel_shuffle_merge(x, grid_h, grid_w, r=2)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).
class MLPProjector(nn.Module)LLaVA-1.5 projector: Linear(d_in, d_out) → GELU → Linear(d_out, d_out).
forward(x)[B, N, d_in] → [B, N, d_out], applied to every image token independently.
build_sequence(image_embeds, text_embeds)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
joint_attention_mask(n_img, n_txt, image_bidirectional=False, device=None)[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).
class DecoderBlock(nn.Module)class TinyDecoder(nn.Module)class VLMConfigclass TinyVLM(nn.Module)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]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).