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.
Build a Text-to-Image Generator (from Scratch) ebook for free