16. Multimodal models
Why this layer exists
A language model reads a sequence of (d,) vectors, one per position, and until now every one of them was a row of the token-embedding table. Nothing in chapter 11’s blocks requires that. Attention, the feed-forward sublayer and the output head operate on whatever (T, d) array arrives; the table lookup is only the first step that produces it. A multimodal model replaces some of those rows with vectors computed from something that is not text: an image cut into patches and encoded, or audio turned into a spectrogram and encoded. The rest of the model does not change.
The reader’s fleet uses both routes (SYSTEM.md). Talos sends images to qwen3-vl-8b-abliterated on straylight :11434, a llama-server model whose vision half is a separate GGUF file attached by an explicit mmproj-url; straylight’s own vision role goes to ornith-1.5-35b-a3b on the same router. Speech takes the other route: whisper.cpp on straylight :11435 runs ggml-large-v3-turbo on the CPU, and clients get text back before the turn reaches the router, so the chat model never sees audio at all. Chapter 28 routes the vision role among providers, and chapter 41’s gateway carries images and whisper transcripts as message parts; both treat these models as black boxes that accept an image_url or return a transcript.
There are two ways to connect an encoder to a language model. Prefix models (LLaVA, Qwen-VL, and every model llama.cpp runs through its multimodal library) project the encoder’s output vectors to the language model’s width and put them in the input sequence, where the causal blocks treat them like tokens. Cross-attention models (Flamingo, and Whisper’s encoder-decoder) keep the encoder’s output in a separate memory and give the decoder extra attention layers whose keys and values come from it. The chapter builds the first in tinygpt.vision, derives the second, and uses it to read Whisper.
Mechanism
Patches as tokens
An image is an array of shape (H, W, C): height, width and channels, 3 for RGB. The Vision Transformer (ViT, Dosovitskiy et al.) turns it into a sequence by cutting it into non-overlapping squares of pixels. With and multiples of there are
patches, and patch , for and , is the block of shape (p, p, C). Flattened, it is a vector of numbers. The lab’s images are (16, 16, 3) with : 16 patches of 48 numbers, a (16, 48) array per image. Qwen3-VL-8B’s vision encoder uses (its config.json, vision_config.patch_size).
Each flattened patch goes through one linear map, the patch embedding: , with of shape (p²C,), of shape (p²C, d) and of shape (d,). Stacked over patches, (N, p²C) times (p²C, d) gives (N, d): tokens of width , chapter 3’s linear layer applied to every row.
This is a convolution. A convolution with output channels, kernel of shape (p, p, C, d), bias and stride computes, at output location and output channel ,
With stride the window at covers rows to and columns to : exactly patch , and neighbouring windows do not overlap. Flatten the patch in row-major order over , so that pixel , channel lands at index , and flatten the kernel’s first three axes the same way, . The triple sum runs over the same index triples as a sum over , so
A stride-, convolution and a Linear on flattened patches are the same map with the same parameters, and the output grid (H/p, W/p, d) read row by row is the token sequence (N, d). test_patch_embed_is_a_strided_convolution computes the quadruple sum with explicit loops on a (12, 8, 3) image, with the kernel taken as proj.weight.reshape(p, p, C, d), and compares. Implementations write it either way; the ViT paper describes the linear projection of flattened patches.
The encoder
Without a mask a stack of blocks is permutation-equivariant (chapter 10 derives it for attention, chapter 15 for the whole block and stack): it maps a shuffled set of patches to the same outputs, shuffled. So the only thing that tells the encoder where a patch was is the position embedding added to it. The ViT uses a learned table of shape (N, d), one row per patch index, as chapter 11’s learned positions; the ViT paper saw no significant gain from 2-D-aware variants:
Then come transformer blocks, chapter 11’s pre-norm block with the causal mask removed, so every patch attends to every patch, and a final layer norm. The output , (N, d), has one vector per patch. This is chapter 15’s encoder with patches in place of tokens: the same block without the causal mask. A single vector for the whole image, which the contrastive objective below needs, is the mean over patches, (d,). The ViT paper prepends a learned [class] token and uses its output instead; its appendix compares the two and finds that both work, with different learning rates.
tinygpt.vision builds each encoder block as chapter 11’s Block with attn.causal = False, chapter 15’s switch. It does not reuse chapter 15’s Encoder, which brings a token table and a head the ViT has no use for, and whose position table starts at a scale that, as the next paragraph measures, is too small for patches. test_vit_is_bidirectional changes only the last patch and checks that the first patch’s output changes, which a causal block would forbid.
How large the position table starts matters here. Chapter 11 draws its tables from , as GPT-2 does. On the lab’s images, a row of that size has norm 0.117 at , against 0.385 for the patch embedding of a background patch, 1.169 for a patch holding part of a shape, and 0.093 for the mean distance of a background patch embedding from the background mean, which is pixel noise. The position signal starts about as large as the noise. Trained end to end on the lab’s captions (seed 8, 800 steps), a captioner with ViT positions named the quadrant correctly for 0.268, 0.260, 0.256 and 0.292 of held-out images at steps 200, 400, 600 and 800, chance level for four quadrants; with positions, row norm 5.829, the same run reached 0.984 at step 200. Over three more seeds (10, 11 and 12), position accuracy at step 400 was 0.282, 0.264 and 0.260 with the small table and 0.994, 0.988 and 0.894 with the large one; colour, which needs no position, was learned with either table in those three runs (in the seed-8 run with the small table it was not, 0.280 at step 800). The reference draws the ViT’s position table from , and test_vit_shapes_and_parameters checks the standard deviation. A background patch contributes nothing but its position, so for position to be readable at all the model has to learn features that combine a patch’s content with its position; the measurements say that at the small initial scale this did not happen within the run, not why in general. Chapter 15’s text encoder, whose position rows start the same size as its token rows (the ViT’s start smaller than its patch embeddings), also stalled with learned positions, but there a larger table did not free it: the cause lay elsewhere.
Contrastive alignment
A vision encoder is usually trained before it meets a language model. CLIP (Radford et al.) trains an image encoder and a text encoder together on image-caption pairs so that matching pairs land close together in a shared space. Take a batch of pairs. Normalise each output to unit length,
and form the (B, B) matrix of cosine similarities divided by a temperature (written rather than chapters 12 and 13’s , which counts text tokens in this chapter),
with and the (B, d) stacks. Read row as the logits of a -way classification: which of the batch’s captions belongs to image ? The right answer is column . Its cross-entropy, chapter 8’s loss with target , averaged over rows, is
Column asks the reverse question, which image belongs to caption , and gives , the same formula applied to . The symmetric InfoNCE loss CLIP trains on is their mean, . The name comes from contrastive predictive coding (van den Oord, Li and Vinyals), where the same softmax over one positive and negatives was introduced. Swapping the two encoders’ roles transposes and swaps the two terms, so is symmetric in its arguments; one direction alone is not, which test_clip_loss_is_symmetric_cross_entropy checks along with the value.
Why it aligns the spaces. Write , the row softmax (in this section and exercise (c) only; from the projector on, counts image tokens). Chapter 8 derived the gradient of cross-entropy with respect to its logits, softmax minus one-hot, divided by the number of rows averaged over:
depends on through , whose gradient with respect to is . Summing over by the chain rule, and using ,
A gradient step moves against this: toward its own caption and away from , the average of all the batch’s captions weighted by how strongly image currently matches each. The captions it confuses itself with push hardest. By the symmetric argument on , moves toward and away from the images it is confused with. A convex combination of unit vectors equals the unit vector only if all its weight sits on copies of , so the gradient is zero for row only when row ’s probability lies entirely on captions equal to : when the batch’s captions are distinct, plus its duplicates’ probabilities equal to 1 when they are not. A softmax gives every other caption some mass, so neither happens exactly, and the loss keeps pulling matched pairs together and pushing confusable ones apart, and the two encoders end up in one space where the dot product measures match. (The gradient reaches the encoders’ parameters through the normalisation, whose Jacobian removes the component along itself; the direction argument is the same.)
Why the temperature. With unit vectors, every cosine lies in , so and . Row ’s loss is , and each of the exponents is at least , so
At and no arrangement of the vectors brings a row below 2.254 nats: the logits cannot spread far enough for a confident softmax. At the bound is . CLIP learns as a log-parameterised scalar, initialised to the equivalent of 0.07 and clipped so the logits are never scaled by more than 100; its batch was 32,768 pairs. The lab fixes . At the other extreme, identical embeddings for every item make every row uniform and the loss exactly , which test_clip_loss_extremes checks with .
Duplicates in a batch break the one-positive assumption. The lab’s grammar has 64 captions, and in a batch of 64 pairs drawn uniformly a given pair shares its caption with at least one other with probability ; such a duplicate is a correct match scored as a negative. The loss still aligns, since both copies are pulled toward the same images, but it can never reach zero.
A trained CLIP classifies without further training: embed one caption per class, embed the image, pick the caption with the largest cosine. The lab does this over all 64 captions.
The projector and the image prefix
The encoder’s output has its own width and was never trained to mean anything to the language model. LLaVA (Liu et al., “Visual Instruction Tuning”) connects them with a trainable linear map from to the language model’s width; its successor LLaVA-1.5 (“Improved Baselines with Visual Instruction Tuning”) replaced it with a two-layer MLP. The reference projector is that MLP, applied to each of the image tokens,
with of shape (P, d_v), (d_v, d), (d, d) and (P, d). Here ; Qwen-VL’s merger first concatenates each 2 × 2 block of neighbouring patch vectors (spatial_merge_size 2 in its config), so .
The prefix is the language model’s input with these rows in front. For text tokens and token table of shape (V, d),
using the language model’s own position table over all positions.
The blocks run unchanged, causal mask included. Text position attends to all image positions and to text positions up to itself; the image positions attend only among themselves, in order. The model produces logits at every position, and only the text positions are kept and trained with next-token cross-entropy: nothing asks the model to predict an image token. Two properties follow and are tested. With no image the model is exactly chapter 11’s GPT, since nothing is prefixed (test_text_only_mode_is_the_unchanged_gpt compares the logits for equality, both with the wrapped GPT and with a twin built separately from the same seed, so a wrapper that altered its GPT would fail). And changing the image changes the text logits, since every text position attends to the prefix.
What the prefix costs is sequence length. Every image token is a position: it takes a slot of the context window, passes through every layer, and stores a key and value per layer in the KV cache (chapter 12’s , now with ). Qwen3-VL resizes an image so that both sides are multiples of 32 ( times the 2 × 2 merge) within bounds on its pixel count, 65,536 to 16,777,216 in preprocessor_config.json, and emits one language-model token per 32 × 32 block: 64 tokens at the least, 16,384 at most. A 1024 × 768 screenshot is 768 tokens; a 1920 × 1080 one is resized to 1920 × 1088, 2,040 tokens (smart_resize in the Hugging Face processor; exercise (a) works it). The number of embeddings per image is variable, and it is set by resolution, not by content.
Ornith’s vision half (vision_config in its config.json, revision 10fbf86) is a ViT of 27 blocks of width 1,152 with 16 heads and feed-forward width 4,304, with the same 16-pixel patches and 2 × 2 merge, and its preprocessor_config.json has the same pixel bounds, so the same screenshot is the same 2,040 tokens there too. The merger’s output width, out_hidden_size 2,048, is ornith’s own hidden_size, so the image tokens arrive at the language model’s width with nothing further to project, and the text config’s M-RoPE (mrope_section [11, 11, 10]) gives them the multi-axis positions of the llama.cpp section below. What an image token costs there is different: ornith keeps a cache in only 10 of its 40 layers (chapter 15). Exercise (a) prices the prefix in both models.
Training in stages
LLaVA trains in two stages. In the first, “pre-training for feature alignment”, both the vision encoder and the language model are frozen and only the projection is trained, on image-caption pairs: in the paper’s words, “a compatible visual tokenizer for the frozen LLM”. In the second, “fine-tuning end-to-end”, the vision encoder stays frozen and the projection and the language model are trained together. Freezing means leaving a parameter out of the optimizer, and it saves less than it might seem. The gradient must still flow back through every frozen layer between the loss and the parameters that are trained. For one token through a weight of shape (in, out), costs FLOPs forward (chapter 3’s count); backward, passing the gradient on, , costs the same again, and the weight’s own gradient, , the same a third time. A frozen weight needs the first two and not the third, so for a language model of matrix weights stage 1 costs about FLOPs per token instead of the of training it, plus no optimizer state or updates for those weights. The reference does not take that saving: chapter 6’s @ backward computes both gradients whether or not anything will read the weight’s.
The reason for the order: at the start the projector is random, so the image tokens are noise in the language model’s input space; tuning the language model against noise would teach it to ignore the prefix, or damage what it knows. Stage 1 first maps the images into regions of the input space the frozen model can already read. The lab runs both stages on a ViT pretrained with the contrastive loss and a GPT pretrained on captions alone, and compares with training everything from scratch.
Cross-attention
The alternative keeps the encoder’s output out of the sequence. Let of shape (T, d) be the decoder’s text states and of shape (S, d_m) the encoder’s output, the memory. A cross-attention layer takes queries from one and keys and values from the other:
with (d, d_k), (d_m, d_k), (d_m, d_v), and
This is chapter 10’s derivation with nothing changed: a soft lookup whose queries come from one sequence and whose keys and values come from another. Chapter 10’s attention(q, k, v) already takes keys of length different from the queries. No causal mask is needed, because the memory is complete before decoding starts and contains no future text. Each text position gets a (d_v,) mixture of memory rows, projected back to (d,) and added to the residual stream like any sublayer. A decoder block then has three sublayers: causal self-attention over the text, cross-attention to the memory, the feed-forward sublayer.
Compared with the prefix: the text’s own self-attention is over positions instead of ; the memory’s keys and values are computed once per layer from and reused for every generated token, a second cache that never grows; and the memory’s rows are never updated by the text, because nothing flows from the decoder back into . In the prefix model the image positions pass through every block of the language model, so its layers can process them. With image tokens and text tokens, a causal prefix computes attention scores per head per layer, against for cross-attention plus the text’s self-attention.
Flamingo (Alayrac et al.) takes this route with a frozen language model: “freshly initialised cross-attention layers” are interleaved between the frozen layers, and each one’s output is multiplied by for a learned scalar initialised to 0, so at the start the model computes exactly what the frozen language model did, the same property as this chapter’s text-only mode. A Perceiver Resampler in front of them turns a variable number of vision features into “a fixed number of visual tokens”.
Audio: Whisper
Whisper (Radford et al., “Robust Speech Recognition via Large-Scale Weak Supervision”) is an encoder-decoder transformer of this cross-attention kind over a spectrogram. Its front end, log_mel_spectrogram in whisper/audio.py, is short.
Framing. Audio is resampled to 16,000 samples per second and processed in 30-second windows of 480,000 samples, zero-padded or trimmed. A short-time Fourier transform cuts the signal into overlapping frames of samples (25 ms), starting every samples (10 ms), multiplies each by a Hann window (the periodic form PyTorch uses), which tapers the frame’s ends to zero so that the cut does not act like a sharp edge in the spectrum, and takes a discrete Fourier transform of each:
For a real signal the bins above mirror those below, so bins remain, spaced Hz apart, from 0 to 8,000 Hz. The power gives an array of shape (201, frames). PyTorch’s stft pads the signal by at each end, which puts frame centres at every hop and yields frames; Whisper drops the last frame, stft[..., :-1], leaving 3,000: 100 per second.
The mel scale. Pitch perception is roughly linear in frequency at low frequencies and roughly logarithmic above about 1 kHz, and a feature bank spaced that way spends its channels where they carry information. Whisper’s filters come from librosa.filters.mel with its defaults (mel_filters.npz records the call), and librosa’s default is the Slaney scale, not the HTK formula . Its definition in librosa.hz_to_mel: below 1,000 Hz, mels are linear in frequency with Hz per mel,
so . Above, each mel multiplies the frequency by a constant factor chosen so that 27 mels span a factor of 6.4. Solve for the ratio per mel: , about 1.071, so , about 0.0688 in natural logarithms. A frequency is mel steps above 1 kHz, and continuity at 1 kHz fixes the offset at 15:
Then . The filterbank places points evenly in mel from to , converts them back to hertz as , and makes filter a triangle rising from 0 at to 1 at and falling back to 0 at , sampled at the 201 bin frequencies; the Slaney normalisation multiplies it by , so every triangle has the same area and a wide high-frequency filter does not collect more energy just by being wide. Whisper large-v3, and so turbo, uses (num_mel_bins 128 in both models’ config.json; the earlier models used 80). The mel step is then , 23.4 Hz in the linear region, narrower than the 40 Hz bins: 42 of the 128 filters are centred below 1 kHz, and 45 of them touch only one FFT bin. The filterbank is a fixed (128, 201) matrix, and the mel spectrogram is the product (128, 201) × (201, 3000) → (128, 3000).
Compression. Whisper takes of the power (after clamping at ), raises everything to at least the maximum minus 8, so the representation spans at most 8 decades of power, 80 dB, and rescales by . The encoder’s input is that (128, 3000) array.
Encoder and decoder (whisper/model.py). Two 1-D convolutions of kernel 3 with GELU, the second with stride 2, map (128, 3000) to (1500, 1280) for the large models: 1,500 positions, one per 20 ms. A fixed sinusoidal position table is added, and 32 transformer blocks without a mask follow, the encoder of chapter 15 over time instead of text. The decoder is a causal transformer over text tokens in which every block has self-attention, then cross-attention whose keys and values come from the encoder’s 1,500 output vectors, then the feed-forward sublayer (ResidualAttentionBlock with cross_attention=True).
The task is in the prompt. The decoder is prompted with special tokens (whisper/tokenizer.py): <|startoftranscript|>, then a language token such as <|en|>, then <|transcribe|> or <|translate|> (to English), and optionally <|notimestamps|>; the text follows and ends at <|endoftext|>. When the language is not given, the model’s next-token distribution over the language tokens at the <|startoftranscript|> position is the language detector. Timestamp tokens <|0.00|> to <|30.00|> in steps of 0.02 s, 1,501 of them, mark segment boundaries when timestamps are on, and <|nospeech|> is the token whose probability flags silence. These are chapter 13’s special tokens: text-format control that the model learned in training.
What turbo changes. OpenAI’s release note for large-v3-turbo (openai/whisper discussion #2363) calls it an optimised large-v3 with “only 4 decoder layers ... down from the 32 in the large series”, and the two config.json files agree: encoder_layers 32 in both, decoder_layers 32 in large-v3 and 4 in turbo, with , 128 mel bins, 1,500 source and 448 target positions in both. A decoder layer holds four (d, d) self-attention projections, four cross-attention projections and a feed-forward pair of , about weights; 28 removed layers are about 734 million weights. The encoder runs once per 30-second window, while the decoder runs once per output token, each step reading all its layers’ weights (chapter 14’s decode bound). Per token the decoder reads its layers plus the token table, which model.py also uses as the output projection (x @ token_embedding.weight.T, weights): about weights in large-v3 and in turbo, a factor of 5.3, while the encoder, and the audio features, stay the same. The reader’s whisper.cpp on straylight :11435 serves this model from ggml-large-v3-turbo on the CPU with --no-gpu (SYSTEM.md): an encoder pass per window, then a four-layer decoder per token.
llama.cpp: the projector file and libmtmd
llama.cpp keeps the vision half out of the language model’s file. (Everything here is as of llama.cpp commit da89bb3, 2026-09-29, the commit chapters 14 and 15 describe.) tools/mtmd/README.md: “running a multimodal model typically requires two GGUF files”: the language model, and “a corresponding multimodal projector (mmproj) file, which handles the image encoding and projection”. The mmproj file holds what this chapter calls ViT and Projector: the vision encoder’s weights, its preprocessing parameters and the merger or MLP that maps its output to the language model’s width. The language model’s GGUF is an ordinary text model that never sees a pixel.
The library between them is libmtmd, used by llama-server, llama-cli and the test tool llama-mtmd-cli. The prompt carries a media marker, <__media__> by default, where each image goes. mtmd_tokenize splits the prompt at the markers into chunks: text chunks tokenized as usual, and one image chunk per image whose mtmd_input_chunk_get_n_tokens is the number of embeddings it will produce, which depends on the image’s size for dynamic-resolution models such as Qwen-VL (--image-min-tokens and --image-max-tokens bound it; the defaults come from the model’s metadata). mtmd_encode_chunk runs the mmproj model on the image, and mtmd_get_output_embd returns n_embd × n_tokens floats, which the helper feeds to the language model’s decode as a batch of embeddings in place of token ids: the concat of this chapter’s VisionLM, at a position in the middle of the prompt rather than at the front. A model with Qwen’s multi-axis rotary positions (M-RoPE) gives image tokens 2-D positions, so a chunk’s position count, mtmd_input_chunk_get_n_pos, can differ from its token count. And for some projector types (Gemma 3 among them) mtmd_decode_use_non_causal returns true and the helper switches off the causal mask while it decodes the image chunk, so image tokens see each other in both directions. Over HTTP, an image arrives at /v1/chat/completions as a content part {"type": "image_url", "image_url": {"url": …}} whose URL may be a remote URL, a base64 data URI or, only when the server was started with --media-path DIR (off by default), a local file under that directory named by a file:// URL with a relative path (tools/server/README.md).
Attaching the projector. --mmproj FILE or --mmproj-url URL names it explicitly. With -hf user/repo[:quant], llama-server downloads the model and, unless --no-mmproj is given, also looks for a projector: find_best_mmproj in common/download.cpp accepts only a .gguf file in the same repository whose path contains mmproj and whose directory is the model file’s directory or one of its ancestors, up to the repository root; among those it prefers the deepest directory, then the quantization closest to the model’s. A repository that publishes its projector in another repository, in a sibling subdirectory, or under another name, gets no projector from -hf. A published GGUF repository of Ornith-1.5-35B-A3B such as bartowski’s lists mmproj-Ornith-1.5-35B-A3B-f16.gguf beside its quants, a layout -hf finds. That is a fact about the repository, not about the reader’s fleet: SYSTEM.md records that straylight’s vision aux uses ornith-1.5-35b-a3b on the :11434 router, but not which repository its preset names or whether its projector arrives through -hf or an explicit mmproj-url.
SYSTEM.md records that the reader’s qwen3-vl-8b-abliterated (Q4_K_M) is a section in the router’s models.ini preset with an explicit mmproj-url, “since router-mode --hf-repo does not attach the projector”. At da89bb3 the router code does not strip a preset’s own hf-repo: server_model_meta::update_args in tools/server/server-models.cpp removes only the TLS, key and router options and overwrites host, port and alias before rendering the child’s arguments, so the child receives --hf-repo and runs the -hf path above, projector search included. The model and projector options are stripped only from the router’s own command line (unset_reserved_args(base_preset, true)) before it is merged into every preset. (The server README says such arguments, “HF repo” among them, “will be removed or overwritten upon loading”; in the code, the removal applies to the router’s own command line.) So at this commit a preset’s hf-repo attaches a projector exactly when the repository holds a matching mmproj*.gguf sibling; whether the reader’s case failed on an older build or on a repository without that sibling is a question SYSTEM.md does not settle, and exercise (g) checks it. An explicit mmproj-url works in either case, so it is the safe choice for a quantized fine-tune whose projector lives in another repository.
Walkthrough
The reference module is py/tinygpt/vision.py. The data first.
def _mask(shape, s):
"""(s, s) boolean stencil of one shape of size s."""
r, c = np.mgrid[:s, :s]
mid = (s - 1) / 2
if shape == "square":
return np.ones((s, s), dtype=bool)
if shape == "circle":
return (r - mid) ** 2 + (c - mid) ** 2 <= (mid + 0.3) ** 2
if shape == "triangle":
return c <= r # right angle at the bottom left
return (r >= mid - 1) & (r < mid + 1) # bar: two rows across the middle
def synthetic_images(n, rng):
"""n images (n, 16, 16, 3) in [0, 1], each one shape in one quadrant, and labels (n, 3):
(shape, colour, position) as indices into SHAPES, COLOURS and POSITIONS."""
labels = np.stack([rng.integers(0, len(SHAPES), n), rng.integers(0, len(COLOURS), n),
rng.integers(0, len(POSITIONS), n)], axis=1)
images = np.full((n, 16, 16, 3), BACKGROUND)
for img, (s, c, p) in zip(images, labels):
size = int(rng.integers(5, 8)) # 5, 6 or 7 pixels across
top, left = 8 * (p // 2), 8 * (p % 2) # the quadrant's corner
dy, dx = rng.integers(0, 9 - size, 2) # anywhere inside the quadrant
colour = np.array(RGB[c]) * rng.uniform(0.75, 1.0)
region = img[top + dy:top + dy + size, left + dx:left + dx + size]
region[_mask(SHAPES[s], size)] = colour
images += rng.normal(0.0, 0.03, images.shape)
return np.clip(images, 0.0, 1.0), labels
synthetic_images draws, per image, a shape, a colour and a quadrant as integer labels, then paints one shape of size 5, 6 or 7 pixels at a random offset inside that quadrant, in its colour’s RGB value scaled by a brightness from 0.75 to 1, on a background of 0.1, and adds Gaussian noise of standard deviation 0.03 before clipping to . _mask gives each shape’s stencil: a full square, a disc of radius about the centre, a right triangle below the diagonal, and a bar of two rows. Everything is drawn from the rng argument, so a seed fixes the data (test_synthetic_images_are_deterministic_and_labelled). The 64 label combinations are the whole caption space.
def caption(label):
"""(shape, colour, position) -> "a red circle top left"."""
s, c, p = label
return f"a {COLOURS[c]} {SHAPES[s]} {POSITIONS[p]}"
def encode_captions(labels):
"""labels (n, 3) -> ids (n, 7): <bos> a colour shape vertical horizontal <eos>."""
return np.array([[WORDS.index(w) for w in ["<bos>", *caption(lab).split(), "<eos>"]] for lab in labels])
def decode_captions(tokens):
"""Generated tokens (n, >= 5), starting after <bos> -> labels (n, 3), -1 where a slot holds the wrong
kind of word: slot 1 must be a colour, slot 2 a shape, slots 3 and 4 a vertical and a horizontal."""
out = np.full((len(tokens), 3), -1)
for i, t in enumerate(tokens):
w = [WORDS[j] for j in t[:5]]
if w[2] in SHAPES:
out[i, 0] = SHAPES.index(w[2])
if w[1] in COLOURS:
out[i, 1] = COLOURS.index(w[1])
if f"{w[3]} {w[4]}" in POSITIONS:
out[i, 2] = POSITIONS.index(f"{w[3]} {w[4]}")
return out
def caption_metrics(pred, true):
"""Exact match and per-attribute accuracy of predicted labels (n, 3) against true labels (n, 3)."""
hit = np.asarray(pred) == np.asarray(true)
return {"exact": float(hit.all(axis=1).mean()), "shape": float(hit[:, 0].mean()),
"colour": float(hit[:, 1].mean()), "position": float(hit[:, 2].mean())}
The caption grammar is “a colour shape vertical horizontal”, and WORDS is its 15-word vocabulary with <bos> and <eos>, so an encoded caption is always 7 ids. decode_captions reads the five words after <bos> slot by slot and marks a slot when it holds a word of the wrong kind, so a malformed caption scores as wrong on that attribute rather than raising. caption_metrics reports exact match, all three attributes right, and each attribute’s accuracy.
def patchify(images, patch):
"""(B, H, W, C) -> (B, (H/p)(W/p), p*p*C): non-overlapping p x p patches, row-major over the grid,
each flattened in (row, column, channel) order."""
B, H, W, C = images.shape
if H % patch or W % patch:
raise ValueError(f"image {H}x{W} is not a whole number of {patch}x{patch} patches")
x = images.reshape(B, H // patch, patch, W // patch, patch, C)
return x.transpose(0, 1, 3, 2, 4, 5).reshape(B, (H // patch) * (W // patch), patch * patch * C)
class PatchEmbed:
"""One Linear on each flattened patch: a convolution with kernel p x p and stride p."""
def __init__(self, patch, channels, d_model, rng):
self.patch = patch
self.proj = Linear(patch * patch * channels, d_model, rng)
def parameters(self):
return self.proj.parameters()
def __call__(self, images):
return self.proj(Tensor(patchify(np.asarray(images, dtype=np.float64), self.patch))) # (B, N, d)
patchify is the reshape the Mechanism derived. (B, H, W, C) becomes (B, H/p, p, W/p, p, C), which names each pixel by (patch row, row within patch, patch column, column within patch, channel); the transpose brings the two patch indices together, (B, H/p, W/p, p, p, C), and the final reshape flattens the grid row-major into patches and each patch into values in (row, column, channel) order: the index of the convolution identity. test_patchify_order pins which pixels land in patches 0, 1 and 2. PatchEmbed is one Linear on that array; images are numpy data, not Tensors, since nothing trains the pixels.
class ViT:
"""Patch embeddings plus learned positions, encoder blocks, a final norm: images -> (B, N, d)."""
def __init__(self, cfg, rng):
self.cfg = cfg
n, d = cfg.n_patches, cfg.d_model
self.patch = PatchEmbed(cfg.patch, cfg.channels, d, rng)
self.pos = Tensor(rng.normal(0.0, 1.0, size=(n, d)))
block_cfg = GPTConfig(vocab_size=1, context=n, d_model=d, n_heads=cfg.n_heads, n_layers=cfg.n_layers)
self.blocks = [Block(block_cfg, rng) for _ in range(cfg.n_layers)]
for block in self.blocks:
block.attn.causal = False # chapter 15's switch: every patch reads every patch
self.ln_f = LayerNorm(d)
def parameters(self):
ps = self.patch.parameters() + [self.pos]
for m in self.blocks + [self.ln_f]:
ps += m.parameters()
return ps
def __call__(self, images):
s, c = self.cfg.image_size, self.cfg.channels
if np.ndim(images) != 4 or tuple(np.shape(images)[1:]) != (s, s, c):
raise ValueError(f"images must have shape (B, {s}, {s}, {c}), got {np.shape(images)}")
x = self.patch(images) + self.pos # (B, N, d) + (N, d)
for block in self.blocks:
x = block(x)
return self.ln_f(x) # (B, N, d): one vector per patch
def pool(self, h):
"""(B, N, d) -> (B, d): the mean over patches, one vector per image."""
return h.mean(axis=1)
ViT builds each block from a GPTConfig with a vocabulary of 1, which Block never reads, and switches its attention’s mask off, as chapter 15’s Encoder does; the flag draws nothing from rng, so each block’s parameters and their draws are chapter 11’s. Its forward pass is the Mechanism’s: patch embedding plus the (N, d) position table broadcast over the batch, the blocks, the final norm. pool is the mean over the patch axis. test_vit_matches_a_manual_forward recomputes all of it in numpy with a mask-free softmax.
class Projector:
"""Vision width to the LM's d_model: Linear, GELU, Linear, applied to every image token."""
def __init__(self, d_vision, d_model, rng):
self.up = Linear(d_vision, d_model, rng)
self.down = Linear(d_model, d_model, rng)
def parameters(self):
return self.up.parameters() + self.down.parameters()
def __call__(self, x):
return self.down(gelu(self.up(x))) # (B, N, d_vision) -> (B, N, d_model)
Projector is the Mechanism’s MLP. up takes the vision width to the language model’s, and down stays at that width, so all the change of basis a stage 1 can learn is in these two matrices and one GELU.
def concat(xs, axis):
"""Tensors joined along axis; the backward pass hands each input its own slice of the gradient."""
out = Tensor(np.concatenate([x.data for x in xs], axis=axis), tuple(xs), "concat")
cuts = np.cumsum([x.shape[axis] for x in xs])[:-1]
def backward():
for x, g in zip(xs, np.split(out.grad, cuts, axis=axis)):
x.grad += g
out._backward = backward
return out
def narrow(x, start, stop, axis):
"""x[..., start:stop, ...] on axis; the gradient flows back into that range and nowhere else."""
index = [slice(None)] * x.ndim
index[axis] = slice(start, stop)
index = tuple(index)
out = Tensor(x.data[index], (x,), "narrow")
def backward():
x.grad[index] += out.grad
out._backward = backward
return out
The prefix needs two operations chapter 6’s Tensor does not have. concat joins tensors along an axis; its backward pass splits the incoming gradient at the same cut points and adds each piece into its input’s gradient. The += matters when one tensor appears twice, which test_concat_and_gradcheck exercises with concat([x, x]). narrow takes a range along one axis, and its backward adds the gradient into that range of the input and leaves the rest untouched.
class VisionLM:
"""Image tokens from vit and projector, prefixed to gpt's token embeddings (LLaVA's arrangement)."""
def __init__(self, vit, projector, gpt):
if gpt.cfg.n_experts:
raise ValueError("VisionLM trains without a load-balancing loss; use a dense GPT")
self.vit, self.projector, self.gpt = vit, projector, gpt
def parameters(self):
ms = [m for m in (self.vit, self.projector) if m is not None] + [self.gpt]
return [p for m in ms for p in m.parameters()]
def __call__(self, ids, images=None):
"""Logits (B, T, V) at the text positions. Without images this is gpt(ids), unchanged."""
if images is None:
return self.gpt(ids)
g = self.gpt
ids = np.asarray(ids, dtype=np.int64) # (B, T)
prefix = self.projector(self.vit(images)) # (B, P, d)
B, P = prefix.shape[:2]
if ids.ndim != 2 or ids.shape[0] != B or ids.shape[1] == 0:
raise ValueError(f"ids must have shape ({B}, T) with T >= 1 to match the images, got {ids.shape}")
T = ids.shape[1]
if P + T > g.cfg.context:
raise ValueError(f"{P} image tokens + {T} text tokens exceed context {g.cfg.context}")
if ids.min() < 0 or ids.max() >= g.cfg.vocab_size:
raise ValueError(f"token ids must lie in [0, {g.cfg.vocab_size})")
x = concat([prefix, embedding(g.tok, ids)], axis=1) # (B, P + T, d)
if g.pos is not None:
x = x + embedding(g.pos, np.arange(P + T)) # positions count the image tokens too
for block in g.blocks:
x = block(x) # causal: text reads the whole image
return g.head(g.ln_f(narrow(x, P, P + T, axis=1))) # (B, T, V)
VisionLM.__call__ without images returns self.gpt(ids): the same call, not a copy of its arithmetic, so the text path is chapter 11’s by construction. With images it computes the (B, P, d) prefix, checks the batch sizes and that fits the context, concatenates the prefix with the token embeddings, adds gpt.pos over all positions when the model has a learned table (a RoPE model rotates by position inside each attention layer and needs nothing here), and runs gpt.blocks, gpt.ln_f and gpt.head, the modules of chapter 11’s model, with narrow keeping the text positions. Since the prefix path calls those modules rather than repeating their arithmetic, a change to Block changes both paths together; test_prefix_forward_matches_gpt_on_concatenated_embeddings builds the concatenated input by hand, runs the model’s blocks on it, and compares.
class TextTower:
"""A caption encoder for the contrastive loss: the mean of word embeddings, then a Linear."""
def __init__(self, vocab_size, d_model, rng):
self.embed = Tensor(rng.normal(0.0, 0.02, size=(vocab_size, d_model)))
self.proj = Linear(d_model, d_model, rng)
def parameters(self):
return [self.embed] + self.proj.parameters()
def __call__(self, ids):
return self.proj(embedding(self.embed, ids).mean(axis=1)) # (B, T) -> (B, d)
def _unit(x):
return x * ((x * x).sum(axis=-1, keepdims=True) ** -0.5) # each row scaled to length 1
def clip_loss(image_emb, text_emb, temperature):
"""Symmetric InfoNCE: image_emb and text_emb (B, d), row i of each from the same pair.
Cosine similarities (B, B) over temperature are logits; row i should pick column i (image to
text) and column i should pick row i (text to image). The loss is the mean of the two
cross-entropies.
"""
logits = (_unit(image_emb) @ _unit(text_emb).transpose()) * (1.0 / temperature) # (B, B)
labels = np.arange(logits.shape[0])
return (cross_entropy(logits, labels) + cross_entropy(logits.transpose(), labels)) * 0.5
TextTower is the smallest caption encoder that works here: the mean of word embeddings, then a Linear; it ignores word order, which the caption grammar makes harmless. _unit divides each row by its norm, , built from Tensor operations so the normalisation’s Jacobian is differentiated for free. clip_loss is the formula: a (B, B) product of unit rows divided by the temperature, cross-entropy with targets over rows and over columns, averaged.
def train_captioner(model, images, labels, params, steps, batch_size, lr, rng):
"""Minibatch next-token training on captions of images (None: captions alone).
Only params are stepped; everything else in model stays frozen. Returns the loss of every step.
"""
opt = Adam(params, lr)
ids = encode_captions(labels) # (n, 7)
losses = []
for _ in range(steps):
idx = rng.integers(0, len(ids), batch_size)
x, y = ids[idx, :-1], ids[idx, 1:] # <bos> ... horizontal -> a ... <eos>
opt.zero_grad()
loss = cross_entropy(model(x, None if images is None else images[idx]), y)
loss.backward()
opt.step()
losses.append(float(loss.data))
free_graph(loss)
return losses
def generate_captions(model, images, n_tokens=6, batch=None):
"""Greedy captions: n_tokens after <bos> for each image, (B, n_tokens). images None: text only,
batch rows."""
B = len(images) if images is not None else batch
ids = np.full((B, 1), WORDS.index("<bos>"))
for _ in range(n_tokens):
logits = model(ids, images)
ids = np.concatenate([ids, logits.data[:, -1].argmax(-1)[:, None]], axis=1)
free_graph(logits)
return ids[:, 1:]
train_captioner builds an Adam over params only, which is how a stage freezes the rest: frozen tensors still accumulate gradients in the backward pass, but no optimizer steps them (test_train_captioner_steps_only_the_given_parameters checks that only the projector moves). Each step samples a batch of captions and their images, shifts the 7-id captions into 6 inputs and 6 targets, and trains next-token prediction; images=None trains the same model on text alone. generate_captions decodes greedily from <bos> without a cache, one full forward pass per token, batched over images.
Exercises
(a) A 1920 × 1080 screenshot goes to Qwen3-VL-8B, preprocessed as the Hugging Face processor does (llama.cpp takes its bounds from the GGUF metadata, which may differ). How many patches does its encoder see, how many embeddings reach the language model, and what does the prefix cost in KV-cache memory per sequence? Use the text model’s config.json: 36 layers, 8 key-value heads of dimension 128, and an f16 cache. Then do the same for ornith-1.5-35b-a3b, whose cache is kept in 10 full-attention layers of 2 key-value heads of dimension 256.
Answer
smart_resize rounds each side to a multiple of : rounds to 34, so the height becomes 1088; exactly. pixels, inside the bounds. The encoder sees patches, and the 2 × 2 merge leaves embeddings.
With grouped-query attention the cache stores, per layer and position, a key and a value for each of the 8 key-value heads: numbers, 4,096 bytes in f16. Over 36 layers that is 147,456 bytes per position, and the image’s 2,040 positions take bytes, 287 MiB, before a single word of text. Chapter 12’s assumed one key-value head per query head; here the key-value width is , a quarter of the model width 4,096. A second screenshot in the conversation costs as much again, and every one stays in the cache for as long as the conversation does.
Ornith sees the same 8,160 patches and 2,040 embeddings, since its patch size, merge and pixel bounds are the same. Its cache holds numbers per position, 20,480 bytes in f16, so the image takes bytes, 39.8 MiB, about a seventh of Qwen3-VL-8B’s. Its 30 recurrent layers read the image into their fixed state of about 63 MiB, which is the same size after the image as before it.
(b) Show that a convolution with kernel and stride is still a Linear on patches, but not of patchify’s patches. How many patches does a 16 × 16 image give with , , and how many numbers does the “patchified” array hold compared with the image?
Answer
The convolution sum at reads the window , and the flattening argument of the Mechanism applies to any single window: with that window flattened. What changes is that the windows overlap, so they are not a partition of the image and a reshape cannot produce them; each pixel is copied into several windows. Window starts run over up to , so there are per side, 49 windows of numbers: 2,352 numbers against the image’s 768, about 3 copies of each pixel. The stride- case is the one where the copies are exactly one, so the “im2col” array is the image itself, reordered.
(c) For , derive and check both gradients against clip_loss’s autodiff gradients at inputs whose rows already have unit length.
Answer
, the column softmax . Its gradient with respect to is , and , so
is also in every row’s softmax of : . clip_loss divides by the norms, whose Jacobian at a unit vector is , so the autodiff gradient is the projection of the formula onto the plane orthogonal to each row:
import numpy as np
from tinygpt.autograd import Tensor
from tinygpt.vision import clip_loss
rng = np.random.default_rng(0)
B, d, tau = 5, 4, 0.3
u = rng.normal(size=(B, d)); u /= np.linalg.norm(u, axis=1, keepdims=True)
v = rng.normal(size=(B, d)); v /= np.linalg.norm(v, axis=1, keepdims=True)
U, V = Tensor(u), Tensor(v)
clip_loss(U, V, tau).backward()
S = u @ v.T / tau
P = np.exp(S - S.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
Q = np.exp(S - S.max(0, keepdims=True)); Q /= Q.sum(0, keepdims=True)
E = np.eye(B)
gu = 0.5 * ((P - E) @ v + (Q - E) @ v) / (B * tau)
gv = 0.5 * ((P - E).T @ u + (Q - E).T @ u) / (B * tau)
proj = lambda g, x: g - (g * x).sum(1, keepdims=True) * x
print(np.abs(proj(gu, u) - U.grad).max(), np.abs(proj(gv, v) - V.grad).max())
1.6653345369377348e-16 1.6653345369377348e-16
That is talos’s output. Straylight and orion print 1.110e-16 for the second difference and titan 2.220e-16 and 1.388e-16: the last bits of a float64 sum depend on the kernels that compute it (the lab section explains). Both differences are float64 rounding. The term’s gradient for is , which is what (Q - E) @ v computes; the factor 0.5 is the mean of the two directions.
(d) Compute the lower bound on a row’s contrastive loss for and and 32,768. What does it say about training CLIP with , and why is the bound not tight?
Answer
| 1 | 2.254 | 8.397 |
| 0.1 | ||
| 0.07 |
At with CLIP’s batch the loss cannot fall below 8.397 nats per row, against 10.397 for knowing nothing (): the logits span at most , and 32,767 negatives each at outweigh the positive. The gradient keeps pushing the positive up and every negative down even when the ranking is already right, because the softmax can never become confident. A small temperature widens the logit range to (about at 0.07) and removes that floor.
The bound assumes every negative can sit at cosine from its row’s image while every positive sits at . For items that is impossible: if all , then , so the off-diagonal cosines average at least , close to 0, not . The true floor is higher; the bound only shows how low it cannot go.
(e) Implement cross-attention with tinygpt.attention.attention for text states (B, T, d) and a memory (B, S, d_m), and show that its output at a text position does not depend on later text positions, without any mask. What does the memory never get that the prefix model’s image positions do?
Answer
import numpy as np
from tinygpt.attention import attention
from tinygpt.autograd import Tensor
from tinygpt.mlp import Linear
rng = np.random.default_rng(0)
B, T, S, d, dm = 2, 5, 7, 8, 6
Wq, Wk, Wv = Linear(d, d, rng, bias=False), Linear(dm, d, rng, bias=False), Linear(dm, d, rng, bias=False)
def cross(x, m):
return attention(Wq(x), Wk(m), Wv(m)) # (B, T, d) @ ... : scores (B, T, S), output (B, T, d)
x, m = rng.normal(size=(B, T, d)), rng.normal(size=(B, S, dm))
y = cross(Tensor(x), Tensor(m)).data
x2 = x.copy(); x2[:, 3:] = rng.normal(size=(B, 2, d)) # change text positions 3 and 4
y2 = cross(Tensor(x2), Tensor(m)).data
print(y.shape, np.abs(y[:, :3] - y2[:, :3]).max())
(2, 5, 8) 0.0
Each output row depends on its own query and on the memory only: the scores are , and no other text position enters, so the layer is causal without a mask. Causality in a decoder block comes from its self-attention sublayer, which keeps chapter 10’s mask. What the memory never gets is processing by the language model: it is a fixed input to every cross-attention layer, the same (S, d_m) array at every depth. In the prefix model the image positions are part of the sequence, so every block of the language model attends among them and runs its feed-forward sublayer on them, and each layer’s keys and values come from image states the language model itself has transformed. Neither design lets the text change the image’s states: the memory is only ever read, and the prefix’s image positions come first, so the causal mask stops them from looking at the text.
(f) Whisper’s front end at 128 mel bins: how many STFT bins fall under each of the lowest filters, and why do the lowest filters overlap so little of the spectrum? What is the largest filter’s width?
Answer
The 130 mel points are spaced mel apart, 23.4 Hz in the linear region, so filter spans Hz there, a little more than one 40 Hz bin spacing: every filter below 1 kHz covers one or two bins, and computing the filterbank with librosa’s rule shows 45 of the 128 filters with exactly one nonzero weight and none with zero. Such a filter is a copy of a single FFT bin, with nothing smoothed; 42 filters are centred below 1 kHz, a third of the bank on the lowest eighth of the band. At the top the log spacing makes the last filter span 7,623 to 8,000 Hz over 9 bins, and the Slaney normalisation divides its weights by that width so it does not dominate by collecting more power. The 80-bin bank of earlier Whisper models has a 0.559-mel step and 3 single-bin filters.
(g) On the reader’s straylight router, find out why the qwen3-vl-8b-abliterated preset needs mmproj-url.
Answer
Two reads settle it without loading anything large. First, list the files of the Hugging Face repository the preset names: sift fetch "https://huggingface.co/api/models/OWNER/REPO" --jq '[.siblings[].rfilename]'. If no .gguf path containing mmproj sits in the Q4_K_M file’s directory or one above it, find_best_mmproj at da89bb3 has nothing to find. Second, the router logs the child’s full argument list when it spawns an instance, spawning server instance with args: followed by one argument per line; with the preset temporarily using hf-repo and no mmproj-url, check whether --hf-repo reaches the child, and whether the child’s own log then shows a projector being loaded. Compare the running build (llama-server --version) with da89bb3: if the argument is absent on the reader’s build, the older router stripped it; if it is present and no projector loads, the repository is the cause. Either way the mmproj-url section keeps working, and /props?model=… reports the loaded model’s modalities.
(h) One training example has image tokens (one per patch) and text tokens; the ViT has matrix weights and the language model . Using the Mechanism’s per-weight count, give the FLOPs of one training step in stage 1, in stage 2, and with everything trained, ignoring the projector. Where does the backward pass stop in each, and how many Adam moments are kept?
Answer
The forward pass is the same in all three: for the ViT over its patches and for the language model, since every position, image or text, passes every layer. The loss sits at the text positions, at the top of the language model, and the projector sits below all of it; the text attended to the image positions, so the gradient reaches the projector only through every language-model block at all positions. That activation gradient, , is paid in every case.
- Stage 1: . The backward pass stops at the projector, below which nothing trains, so the ViT’s backward is skipped whole. Adam keeps moments for the projector alone.
- Stage 2: , adding the language model’s weight gradients. The backward pass still stops at the projector. Adam keeps moments.
- Everything: ; the backward pass continues through the ViT down to the patch embedding (only the gradient into the pixels is unneeded). Adam keeps .
So freezing the ViT saves its entire backward, per example, because it lies below everything that trains; freezing the language model as well saves only a third of its cost, because it lies above the projector. An engine gets the first saving by marking the ViT’s weights as not requiring gradients, so it records no graph below the projector.
Lab
Implement the stubs in py/labs/ch16/starter.py. They are the patch embedding (patchify, PatchEmbed); the encoder (ViT); the connector (Projector, concat, narrow, VisionLM); the contrastive pieces (TextTower, clip_loss); and the plumbing (train_captioner, generate_captions). The data, the caption grammar, caption_metrics and ViTConfig are provided. Run
make lab CH=16 IMPL=mine
until it passes. Read py/labs/ch16/test_lab.py first. The tests pin the patch order and the convolution identity; the ViT’s bidirectionality, its position table and a numpy recomputation of its forward pass; the projector’s arithmetic; concat and narrow with gradient checks; the prefix path against chapter 11’s modules run on a hand-built input, text-only mode against GPT itself, and causality at the text positions; clip_loss against a numpy transcription of the formula, its symmetry and its extremes; and freezing. The acceptance test, test_captioner_beats_text_only_on_held_out_images, trains a small captioner end to end for 500 steps and a text-only GPT on the same captions, and requires held-out colour and position accuracy above 0.9, shape above 0.4 and exact match 0.4 above the text-only model’s. It uses 8 × 8 patches to run in seconds, so each patch is exactly one quadrant and position reduces to which patch holds the shape; the lab script below uses 4 × 4 patches.
Then run the whole recipe: a caption language model, contrastive pretraining of the ViT, LLaVA’s two stages, and training from scratch for comparison. Save as /tmp/vision_lab.py:
import itertools
import sys
import time
import numpy as np
from tinygpt.mlp import Adam
from tinygpt.nn import free_graph
from tinygpt.transformer import GPT, GPTConfig
from tinygpt.vision import (Projector, TextTower, ViT, ViTConfig, VisionLM, caption_metrics, clip_loss,
decode_captions, encode_captions, generate_captions, synthetic_images,
train_captioner)
steps = [int(s) for s in sys.argv[1:]] or [300, 400, 400, 400, 800] # text, clip, stage 1, stage 2, scratch
train_x, train_y = synthetic_images(2000, np.random.default_rng(1))
test_x, test_y = synthetic_images(500, np.random.default_rng(2))
D, t0 = 32, time.perf_counter()
def show(name, labels):
m = caption_metrics(labels, test_y)
print(f"{name:26s} exact {m['exact']:.3f} shape {m['shape']:.3f} colour {m['colour']:.3f} "
f"position {m['position']:.3f} ({time.perf_counter() - t0:.0f} s)")
def captions(model, images):
return decode_captions(generate_captions(model, images, batch=len(test_y)))
# 1. A language model of captions alone: the text-only baseline, and the LM the stages start from.
lm = GPT(GPTConfig(vocab_size=15, context=24, d_model=D, n_heads=2, n_layers=1), np.random.default_rng(0))
train_captioner(VisionLM(None, None, lm), None, train_y, lm.parameters(), steps[0], 32, 3e-3,
np.random.default_rng(3))
show("text only", captions(VisionLM(None, None, lm), None))
# 2. Contrastive pretraining of the ViT against a bag-of-words text tower.
rng = np.random.default_rng(0)
vit, tower = ViT(ViTConfig(d_model=D), rng), TextTower(15, D, rng)
opt = Adam(vit.parameters() + tower.parameters(), 3e-3)
ids = encode_captions(train_y)[:, 1:-1] # the five caption words
for _ in range(steps[1]):
idx = rng.integers(0, len(ids), 64)
opt.zero_grad()
loss = clip_loss(vit.pool(vit(train_x[idx])), tower(ids[idx]), 0.1)
loss.backward()
opt.step()
free_graph(loss)
every = np.array(list(itertools.product(range(4), range(4), range(4)))) # all 64 (shape, colour, position)
text = tower(encode_captions(every)[:, 1:-1]).data
image = vit.pool(vit(test_x)).data
sims = (image / np.linalg.norm(image, axis=1, keepdims=True)) @ (text / np.linalg.norm(text, axis=1, keepdims=True)).T
show("CLIP zero-shot", every[sims.argmax(axis=1)])
# 3. Stage 1: ViT and LM frozen, train the projector alone.
vlm = VisionLM(vit, Projector(D, D, np.random.default_rng(5)), lm)
train_captioner(vlm, train_x, train_y, vlm.projector.parameters(), steps[2], 32, 3e-3, np.random.default_rng(6))
show("stage 1: projector", captions(vlm, test_x))
# 4. Stage 2: ViT still frozen, projector and LM trained together.
train_captioner(vlm, train_x, train_y, vlm.projector.parameters() + lm.parameters(), steps[3], 32, 3e-3,
np.random.default_rng(7))
show("stage 2: projector + LM", captions(vlm, test_x))
# 5. For comparison: everything from scratch, end to end, for as many steps as stages 1 and 2 together.
rng = np.random.default_rng(8)
scratch = VisionLM(ViT(ViTConfig(d_model=D), rng), Projector(D, D, rng),
GPT(GPTConfig(vocab_size=15, context=24, d_model=D, n_heads=2, n_layers=1), rng))
train_captioner(scratch, train_x, train_y, scratch.parameters(), steps[4], 32, 3e-3, np.random.default_rng(9))
show("end to end from scratch", captions(scratch, test_x))
and run it from py/:
OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/vision_lab.py
On talos, the laptop this chapter was written on (a 13th-generation Intel Core i3-1315U), at a load average near 3, it printed this in under a minute (the times are cumulative; the same script took 41 s on straylight at nice 19, and about four minutes on talos under a load average of 15):
text only exact 0.020 shape 0.262 colour 0.242 position 0.268 (1 s)
CLIP zero-shot exact 0.696 shape 0.696 colour 1.000 position 1.000 (14 s)
stage 1: projector exact 0.148 shape 0.296 colour 0.864 position 0.714 (25 s)
stage 2: projector + LM exact 0.716 shape 0.716 colour 1.000 position 1.000 (37 s)
end to end from scratch exact 0.666 shape 0.670 colour 0.998 position 0.996 (58 s)
The seeds fix the images, every initial weight and the order of the batches, so a rerun on the same machine prints the same accuracies. They do not fix the arithmetic. Each matrix product is a sum of floating-point products, and floating-point addition is not associative; a different CPU runs different vectorised kernels, both OpenBLAS’s matrix products and numpy’s own loops (AVX-512 on one machine, AVX2 on another), which group the sums differently, the last bits differ, and 800 training steps can carry the difference into a different greedy caption. On straylight (an AMD Ryzen AI MAX+ 395) the first four rows printed the same accuracies and the last did not: end to end from scratch exact 0.700 shape 0.700 colour 1.000 position 1.000. On titan (an Apple M3 Max) the last row’s exact accuracy was 0.708. Forcing straylight onto talos’s OpenBLAS kernels gave yet another value, 0.724, and also switching off numpy’s AVX-512 loops gave talos’s 0.666 exactly. A gap between two rows smaller than that movement does not rank them.
- Text only is chance. Greedy decoding from a model that has seen captions but no images writes the same caption for every image, the most probable one, so each attribute is right about a quarter of the time and the whole caption about of the time, 0.020 here. This is the floor every other row must beat, and the number
test_captioner_beats_text_only_on_held_out_imagesmeasures in its own configuration. - The contrastive ViT already knows colour and position. Picking the nearest of the 64 captions by cosine similarity, with no caption model at all, gets both attributes on every held-out image and the shape on 0.696 of them. Every exact-match failure is a shape failure, as in stage 2: shape, which needs the arrangement of pixels across patch boundaries, is the hard attribute here.
- Stage 1 moves a frozen caption model part of the way. Only the projector’s 2,112 parameters train, against a language model that learned captions without ever seeing a prefix. After 400 steps it gets colour on 0.864 of the images and position on 0.714, but shape barely above chance; the frozen model reads what the projector makes easy for its existing attention, and not yet the rest.
- Stage 2 reaches the contrastive encoder’s level. With the language model free to adapt as well, colour and position are perfect and shape reaches 0.716, close to the frozen ViT’s own zero-shot shape accuracy of 0.696. That suggests the frozen encoder’s shape features are the limit; the script does not test it, and adding
vit.parameters()to stage 2’s list is the experiment that would. - Staging and training from scratch end close together with the same 800 captioning steps: 0.716 exact match against 0.666 on talos and against 0.700 on straylight, gaps of 0.050 and 0.016, while the from-scratch row itself moved by 0.034 between the machines. The staged model also had 400 contrastive steps and 300 caption-model steps before it, and this is one seed; the toy does not rank the two. What the toy shows is the mechanism: a projector alone can connect a separately trained encoder to a language model that never saw images, and a second stage lets the language model use what arrives. Whether staging wins at scale is the papers’ question, not this script’s.
Further reading
- Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit and Neil Houlsby, “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”, ICLR (2021). The ViT: a linear projection of flattened patches, learned 1-D position embeddings, a
[class]token, and the comparison with global average pooling in the appendix. - Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger and Ilya Sutskever, “Learning Transferable Visual Models From Natural Language Supervision”, ICML (2021). CLIP: the symmetric contrastive loss over a batch’s similarity matrix, the learned log-parameterised temperature (initialised to 0.07, logits scaled by at most 100), minibatches of 32,768, and zero-shot classification by caption similarity.
- Aaron van den Oord, Yazhe Li and Oriol Vinyals, “Representation Learning with Contrastive Predictive Coding” (2018). The InfoNCE loss: a softmax classification of one positive among negatives.
- Haotian Liu, Chunyuan Li, Qingyang Wu and Yong Jae Lee, “Visual Instruction Tuning”, NeurIPS (2023). LLaVA: vision features projected into the language model’s word-embedding space by a trainable linear map, trained in two stages, feature alignment with both models frozen and then end-to-end fine-tuning with the vision encoder frozen.
- Haotian Liu, Chunyuan Li, Yuheng Li and Yong Jae Lee, “Improved Baselines with Visual Instruction Tuning”, CVPR (2024). LLaVA-1.5: the MLP connector in place of the linear projection.
- Jean-Baptiste Alayrac and others, “Flamingo: a Visual Language Model for Few-Shot Learning”, NeurIPS (2022). Frozen vision and language models joined by newly initialised cross-attention layers with tanh gates initialised at zero, and a Perceiver Resampler producing a fixed number of visual tokens.
- Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey and Ilya Sutskever, “Robust Speech Recognition via Large-Scale Weak Supervision”, ICML (2023). Whisper: the encoder-decoder over log-mel spectrograms of 30-second windows and the special-token task format. The code in
openai/whisper:whisper/audio.pyfor the front end,whisper/model.pyfor the encoder, decoder and cross-attention,whisper/tokenizer.pyfor the special tokens; discussion #2363 forlarge-v3-turbo. - llama.cpp (commit
da89bb3):docs/multimodal.mdandtools/mtmd/README.mdfor the mmproj file and the supported models,tools/mtmd/mtmd.hfor the chunk and embedding API,tools/server/README.mdfor--mmproj,--mmproj-url,-hf, the image-token bounds and router presets, andtools/server/server-models.cppandcommon/download.cppfor how the router passes a preset to its child and how-hfchooses a projector.