Overview

4 Add captions to images

This chapter focuses on building the reverse of text-to-image generation—an image-to-text captioning system—as a practical stepping stone to multimodal generative models. It explains how both directions share the same core idea: mapping between visual and linguistic representations through an encoder-decoder transformer. By implementing a captioning model from scratch, you learn the mechanics of cross-modal attention and autoregressive decoding in a setting that is easier to train and reason about, while laying the groundwork for more complex text-to-image systems later on.

The model pairs a vision transformer (encoder) with a text generator (decoder). Images are standardized and split into patches that are turned into embeddings with positional information, producing a sequence representation of the picture. Captions are tokenized, wrapped with special start and end tokens, and transformed into input–target pairs by shifting the sequence to train next-token prediction. A causal attention mask in the decoder enforces that each token only attends to previous tokens, while cross-attention aligns the evolving text with the image embeddings. The chapter also covers batching, padding, vocabulary construction, and the overall data pipeline using image–caption pairs such as those in Flickr 8k.

Training minimizes cross-entropy between the predicted token distribution and the shifted target sequence, teaching the decoder to generate captions conditioned on the image and previously generated tokens. At inference, the model encodes the image once and decodes tokens autoregressively from a start symbol until an end symbol, with temperature controlling the diversity of the samples. The resulting captions are generally coherent and faithful to image content, demonstrating the effectiveness of the encoder–decoder design and preparing you for subsequent chapters that build on these ideas for text-to-image generation, including diffusion-based approaches.

Eight steps to build a text-to-image generator from scratch. In this chapter, you will reinforce and apply skills from steps 1 and 2: building a transformer that captions images. The encoder is a vision transformer (ViT), similar to what you created for image classification in chapter 3. The decoder generates text based on image features, much like the decoder you developed for German-to-English translation in chapter 2.
How to prepare data to train a transformer to add captions to images. We first obtain a training dataset of images paired with descriptive captions. The images are standardized to a certain size (for example, 3x128x128) so that we can feed them to the image encoder in the transformer. The captions are first tokenized, and we add <start> and <end> to the beginning and end of the caption. We omit the <end> token and use the rest of the tokens as the input sequence ([<start>, two, bears, fight]). We slide the input sequence one token to the right and use the result as the target sequence ([two, bears, fight, <end>]). The input sequence is fed to the decoder to make predictions on the next token. The target sequence serves as the ground truth. We compare the predicted output from the decoder with the target sequence and calculate the cross-entropy loss. During training, we modify model parameters to minimize this loss. This approach compels the model to predict the next token based on previous ones.
How the causal attention mask works. To force the model to predict the next token based on all tokens before it, but not tokens after it (future tokens), we apply the causal attention mask when calculating self-attention in the transformer’s decoder layer. Specifically, we mask out the attention weights above the main diagonal so that the model cannot access future tokens. The left matrix shows the attention weights before the causal attention mask and the right matrix shows the attention weights after we apply the causal attention mask. As a result, in the first iteration, the model predicts the token “two” using only the token “<start>”. In the second iteration, the model predicts the token “bears” using only tokens “<start> two” but not future tokens “bears fight.” In the last iteration, the model uses all four tokens “<start> two bears fight” to predict the next token (which is the token <end>).
The structure of an encoder-decoder transformer to add captions to images. The encoder in the transformer (left side of the diagram), which consists of N identical encoder layers, encodes an image into image embeddings that capture the features of the image. It then passes this tensor to the decoder (right side of the diagram), which consists of N identical decoder layers. The decoder takes the input sequence as the input ([<start>, two, bears, fight]) and predicts the output sequence. We compare the predictions with the ground truth, which is [two, bears, fight, <end>]. We modify the model parameters to minimize the cross-entropy loss. Since a causal attention mask is applied in each decoder layer, this is equivalent to training the model to predict the next token based on all tokens before it (but not tokens after it) in the sequence.
Adding a caption to an image using the trained transformer. We first feed the image to the trained encoder to obtain the image embeddings. We then pass the image embeddings to the decoder to generate a caption. The decoder constructs the caption in an autoregressive fashion. It starts with the beginning of the caption token, <start>, and predicts the next token in the caption. It then adds the prediction to the caption and predicts the token after it. It repeats the process until the predicted token is <end>, which signals the end of the caption.
Comparing generated captions with original captions. In this figure, we present three examples of generated captions with the trained encoder-decoder transformer. We display both the generated captions and the original captions on top of each image.

Summary

  • Training a multi-modal transformer for text-to-image generation (i.e., adding captions to images) and training one for image-to-text generation (i.e., generating images based on textual descriptions) share some similarities. Both tasks involve learning complex mappings between textual and visual modalities.
  • Understanding and training multi-modal transformers for image-to-text generation first can provide valuable insights and foundational knowledge, making the complex task of text-to-image generation more manageable.
  • We create an encoder-decoder transformer for image-to-text generation. The encoder converts an image into a sequence of image patches. It then uses image embedding to convert image patches to vector representations that capture the feature maps in these patches. The decoder generates captions one token at a time, based on the output from the encoder and previously generated tokens in the caption.
  • When preparing the training data, we generate input sequences and target sequences based on captions associated with the training images. The decoder tries to predict the next token after the input sequence.
    • For example, if the caption associated with an image is “a dog runs”, we’ll add <start> and <end> to the beginning and the end of the caption. We’ll use “<start> a dog runs” as the input sequence. We move the input sequence one token to the right and use it as the target sequence (i.e., the ground truth).
    • During training, we feed the input sequence to the model and compare the model output with the target sequence, “a dog runs <end>,” and calculate the cross-entropy loss. We modify model parameters to minimize this loss.

FAQ

Why start with image captioning before building a text-to-image model?Image captioning is simpler yet teaches the key multimodal skills you’ll reuse for text-to-image: extracting visual features with a Vision Transformer (ViT), aligning image and text via cross-attention, and generating sequences autoregressively with a decoder. Mastering these makes the later, more complex task of synthesizing images from text more approachable.
What architecture is used to add captions to images?An encoder–decoder transformer. The encoder is a ViT that converts an image into a sequence of patch embeddings with positional encodings. The decoder is a text generator that, using causal self-attention and cross-attention to the image embeddings, produces a caption token by token from a special <start> token until <end>.
How do input and target sequences for training get constructed?For a caption like “two bears fight,” you add <start> and <end>. The input sequence is [<start>, two, bears, fight] and the target sequence is [two, bears, fight, <end>]. The model learns to predict the next token at each position using cross-entropy loss (teacher forcing) while masking future tokens.
What is a causal attention mask and why is it needed?The causal mask prevents the decoder from attending to future tokens during self-attention by zeroing (or -∞ masking) attention weights above the main diagonal. This enforces left-to-right generation so each prediction depends only on previously known tokens, not future ones.
Which dataset and preprocessing steps are used?Flickr8k (≈8k images, 5 captions each). Images are resized to 3×128×128. Captions are tokenized; <start> and <end> are added. A vocabulary is built with special tokens <pad>, <start>, <end>, <unk>. Sequences are mapped to indices and padded per batch; DataLoader batches (e.g., size 128) are created for training and testing.
How does the Vision Transformer encode images here?Each 128×128 image is split into 8×8 patches (16×16 grid = 256 patches). Each patch (3×8×8 = 192 values) is linearly projected to hidden_size, positional embeddings are added, and the sequence passes through multiple transformer blocks (e.g., 6) with multi-head self-attention and feed-forward layers.
What are the key hyperparameters and their roles?- hidden_size (e.g., 192): dimensionality of patch/token embeddings. - num_layers (encoder, decoder), e.g., (6, 6): model depth and capacity. - num_heads (e.g., 8): parallel attention subspaces. - patch_size (e.g., 8): controls number of patches/sequence length. - Batch size, learning rate (e.g., 1e-4): training stability/speed. This setup yields ~9.5M parameters in the example model.
How is the model trained and what loss is used?The model is trained to predict the next token at every position with a cross-entropy loss over the vocabulary. Padding masks exclude padded positions from the loss. Adam optimizer (e.g., lr=1e-4) and mixed precision (torch.amp) accelerate training. Training proceeds over epochs, saving the model state_dict afterward.
How does caption generation (inference) work?At test time, encode the image with the trained encoder. Start the decoder with <start> and iteratively sample the next token (up to a max length or until <end>), conditioning on the image embeddings and previously generated tokens. A temperature parameter controls randomness: <1 is more deterministic; >1 is more diverse.
How does cross-attention align text with image features?In each decoder layer, queries (Q) come from the current text embeddings, while keys (K) and values (V) come from the encoder’s image embeddings. The attention weights QKᵀ/√dₖ highlight image patches relevant to the current decoding step, and the weighted sum over V feeds information about those patches into the decoder to guide the next-token prediction.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free