A vision-language model — PaliGemma

Images become tokens, tokens join the prompt, and a decoder-only language model answers — with rotary positions, RMSNorm and a KV cache.

What you'll learn
  • Trace an image and a prompt through SigLIP, the projector and Gemma
  • Explain rotary position embeddings and why scores depend only on distance
  • Describe what a KV cache saves during generation

PaliGemma answers questions about images: “caption en”, “what is in the bowl?”, “detect cat”. 09_paligemma_from_scratch rebuilds it in PyTorch module by module, ready to load Google’s released weights. It brings together nearly every idea in this course.

PaliGemma's data flow. The image passes through a patch embedding (a strided Conv2d), the SigLIP vision encoder and a linear projector that maps the vision width to Gemma's width, producing image tokens. The prompt is tokenised and embedded by Gemma's token embeddings. Image tokens, scaled by one over the square root of d, are followed by BOS and the prompt in one sequence. The Gemma decoder reads it with RMSNorm, rotary positions and a KV cache, image and prompt attending to each other in full, and produces the next text token, which is sampled and appended before repeating. PaliGemma's data flow. The image passes through a patch embedding (a strided Conv2d), the SigLIP vision encoder and a linear projector that maps the vision width to Gemma's width, producing image tokens. The prompt is tokenised and embedded by Gemma's token embeddings. Image tokens, scaled by one over the square root of d, are followed by BOS and the prompt in one sequence. The Gemma decoder reads it with RMSNorm, rotary positions and a KV cache, image and prompt attending to each other in full, and produces the next text token, which is sampled and appended before repeating.
Image tokens and prompt tokens form one sequence. The decoder generates the answer one token at a time, feeding each new token back in.

Images become tokens

The vision side is a Vision Transformer, SigLIP. Its first layer is lesson 4’s patch embedding exactly — a Conv2d whose kernel and stride both equal the patch size — followed by a learned position embedding and a stack of encoder layers:

self.patch_embedding = nn.Conv2d(config.num_channels, self.embed_dim,
                                 kernel_size=self.patch_size, stride=self.patch_size,
                                 padding="valid")

A linear projector then maps each image token to the language model’s width, and _merge_input_ids_with_image_features places them where the processor left <image> placeholder tokens in front of the prompt. The prefix — image plus prompt — attends to itself in full; only the generated answer is causal.

Gemma’s building blocks

RMSNorm is lesson 5’s, with one twist: the learned scale is stored as an offset, x * (1 + weight), so a zero-initialised weight starts as the identity.

Gated MLP. Instead of Linear → ReLU → Linear, Gemma computes down(gelu(gate(x)) * up(x)): one projection decides, feature by feature, how much of the other passes through.

Grouped-query attention. Gemma can have fewer key/value heads than query heads; repeat_kv copies each K/V head to serve several query heads, cutting the memory the cache needs.

Rotary position embeddings (RoPE). Instead of adding a position vector, RoPE rotates each pair of query and key dimensions by an angle proportional to the token’s position, with a different frequency per pair: \(\theta_i = 10000^{-2i/d}\). Rotating \(q\) by \(n\theta\) and \(k\) by \(m\theta\) changes their dot product only through the difference \(n - m\) — attention sees relative position for free.

One dimension pair of a query and a key, rotated by their positions. As both positions advance together the arrows turn but the angle between them — and so the score q·k — stays fixed. Change the distance to get a different, but again constant, score.

Generating with a KV cache

Generation appends one token at a time. Without a cache, every step would recompute keys and values for the whole sequence. The KVCache stores them per layer, so after the first (“prefill”) pass each new token needs only its own query, key and value — the attention for one row, not the whole matrix. inference.py then samples the next token with temperature and top-p, or takes the argmax for greedy decoding.

Before running it

The folder’s readme marks it as work in progress, and the first thing to fix is in the vision config:

class SiglipVisionConfig:
    def __init__(self, hidden_size=768, ...):
        super.__init__()

super.__init__() calls __init__ on the built-in type super itself and raises TypeError: descriptor '__init__' of 'super' object needs an argument — so PaliGemmaConfig, which builds this config, fails before a single weight loads. It should be super().__init__().

Two comments are worth correcting while there: rotate_half is documented as turning \([x_1, x_2, x_3, x_4]\) into \([-x_2, x_1, -x_4, x_3]\), but the code — correctly, matching the duplicated cat((freqs, freqs)) frequencies — splits the vector in halves and returns \([-x_3, -x_4, x_1, x_2]\); and in _merge_input_ids_with_image_features the “Prefill” and “Generation” labels are swapped (the branch with a non-empty cache is generation).

Try it yourself. Fix super().__init__() and build a GemmaRotaryEmbedding(8). Apply it to a random query at position 5 and a key at position 2, then to the same vectors at positions 9 and 6, and check that the two dot products agree to float precision. Then try positions 9 and 2 and see that they do not.

View source on GitHub →