Search

Search papers and lessons

Show, Attend and Tell: Neural Image Caption Generation with Visual Attention

Kelvin Xu, Jimmy Ba, Ryan Kiros et al. · 2015

Xu et al. (2015) generate image captions with an LSTM that, at each word, learns where to look in the image, and they train the attention either smoothly with backpropagation or by sampling with REINFORCE.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Architectures
  • Neural network basics
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

Xu et al. (2015) build an image captioner that writes one word at a time and, before each word, decides which part of the image to look at. The image is split into a grid of feature vectors, and a weighting over the grid is computed from the caption so far. The authors train this in two ways: a "soft" version that is a smooth function and can be trained by backpropagation, and a "hard" version that samples one location and is trained with a variance-reduced policy-gradient rule. The attention maps also show which region produced each word.

Builds on: Convolutional Neural Network, Long Short-Term Memory, Attention Mechanism · Leads to: Vision Transformer (ViT)

Why it mattered

Before this paper, most caption generators squeezed the whole image into one vector from the top of a convolutional network and fed it to a recurrent decoder once or at every step. The paper showed that letting the decoder pick its own image regions gives state-of-the-art BLEU on Flickr8k, Flickr30k and MS COCO with a single model, and that the learned alignments correspond strongly with human intuition. It made attention over image regions an ordinary tool. Later vision models such as Vision Transformer (ViT) apply attention to image patches in a related way.

The problem

Captioning needs two abilities at once. The model must recognise what is in the image, and it must express the relations between objects in a sentence. A single global feature vector throws away spatial detail, which the caption may need. The paper's answer is to keep a grid of local features and let the decoder learn which cells matter for each word. The open question is how to train that choice. A hard choice of one cell is not differentiable, and a soft average is differentiable but blurs the signal.

How it works

The model has three parts: an encoder that turns the image into a grid of vectors, an attention step that turns the grid and the current decoder state into one context vector, and an LSTM decoder that emits the next word.

flowchart LR
  I[image 224 by 224] --> C[VGG conv features: 14 by 14 by 512]
  C --> A[196 annotation vectors a_i]
  H[decoder state h_t minus 1] --> F[attention scores e_ti]
  A --> F
  F --> S[softmax weights alpha_ti]
  S --> Z[context vector z_t]
  A --> Z
  Z --> L[LSTM step]
  L --> W[next word]
  W --> H
  1. Encode the image. A convolutional network (the paper uses the 19-layer Oxford VGG network, pretrained on ImageNet) gives a 14×14×51214 \times 14 \times 512 feature map. Flatten it into L=196L = 196 annotation vectors ai\mathbf{a}_i, each of length D=512D = 512. Check: 14×14=19614 \times 14 = 196.
  2. Score each location. An attention network scores each ai\mathbf{a}_i against the previous hidden state ht−1\mathbf{h}_{t-1}, giving one number etie_{ti} per location. Toy case: scores (0,0,ln⁡2)(0, 0, \ln 2) for three locations.
  3. Normalise the scores with a softmax. Toy case: the exponentials are 1,1,21, 1, 2, which sum to 44, so the weights are α=(0.25,0.25,0.5)\alpha = (0.25, 0.25, 0.5). Check: the weights sum to 1.
  4. Form the context vector. Toy case, with a1=(1,0)\mathbf{a}_1 = (1, 0), a2=(0,1)\mathbf{a}_2 = (0, 1), a3=(1,1)\mathbf{a}_3 = (1, 1): z^t=0.25(1,0)+0.25(0,1)+0.5(1,1)=(0.75,0.75)\hat{\mathbf{z}}_t = 0.25(1,0) + 0.25(0,1) + 0.5(1,1) = (0.75, 0.75). The context leans towards the third location, which had the highest score.
  5. Update the LSTM with the previous word embedding, the previous hidden state and the context. The new state gives a distribution over the vocabulary, and the most likely (or a sampled) word is emitted.
  6. Repeat from step 2 with the new hidden state. Because ht\mathbf{h}_t changes, the attention moves as the caption unfolds. The paper's Figure 2 shows this shift.

Training differs only in step 4. The soft model uses the weighted average, which is smooth. The hard model samples one location from the weights and is trained with REINFORCE.

The math

Definition: Attention caption model

Given annotation vectors a1,…,aL\mathbf{a}_1, \dots, \mathbf{a}_L and a caption y1,…,yC\mathbf{y}_1, \dots, \mathbf{y}_C, the model scores locations with eti=fatt(ai,ht−1)e_{ti} = f_{\mathrm{att}}(\mathbf{a}_i, \mathbf{h}_{t-1}), normalises them to weights αti\alpha_{ti} that sum to one, forms a context z^t=ϕ({ai},{αti})\hat{\mathbf{z}}_t = \phi(\{\mathbf{a}_i\}, \{\alpha_{ti}\}), and predicts each word from the LSTM state and the context.

Step 2 in symbols: scores and weights

eti=fatt(ai,ht−1)e_{ti} = f_{\mathrm{att}}(\mathbf{a}_i, \mathbf{h}_{t-1}), where fattf_{\mathrm{att}} is a small multilayer perceptron. The weights are αti=exp⁡(eti)/∑k=1Lexp⁡(etk)\alpha_{ti} = \exp(e_{ti}) / \sum_{k=1}^{L} \exp(e_{tk}), a softmax over locations, so ∑iαti=1\sum_i \alpha_{ti} = 1.

Step 4 in symbols: the context

Soft attention uses ϕ=∑iαtiai\phi = \sum_{i} \alpha_{ti}\mathbf{a}_i. The soft model also learns a gate βt=σ(fβ(ht−1))\beta_t = \sigma(f_\beta(\mathbf{h}_{t-1})) and uses βt∑iαtiai\beta_t \sum_i \alpha_{ti}\mathbf{a}_i. Hard attention instead draws a location sts_t from the categorical distribution p(st,i=1)=αtip(s_{t,i} = 1) = \alpha_{ti} and sets z^t=ast\hat{\mathbf{z}}_t = \mathbf{a}_{s_t}.

Step 5 in symbols: the decoder

The LSTM uses the standard gates, with it,ft,ot\mathbf{i}_t, \mathbf{f}_t, \mathbf{o}_t the input, forget and output gates and gt\mathbf{g}_t the candidate memory: (it,ft,ot,gt)⊤=(σ,σ,σ,tanh⁡)⊤ TD+m+n,n(Eyt−1,ht−1,z^t)(\mathbf{i}_t, \mathbf{f}_t, \mathbf{o}_t, \mathbf{g}_t)^\top = (\sigma, \sigma, \sigma, \tanh)^\top\, T_{D+m+n,n}(\mathbf{E}\mathbf{y}_{t-1}, \mathbf{h}_{t-1}, \hat{\mathbf{z}}_t), then ct=ft⊙ct−1+it⊙gt\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \mathbf{g}_t and ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t). Here E\mathbf{E} is the word embedding, TT is an affine map, and ⊙\odot is element-wise multiplication. The initial state comes from the mean of the annotation vectors through two MLPs: c0=finit,c(1L∑iai)\mathbf{c}_0 = f_{\mathrm{init,c}}(\frac{1}{L}\sum_i \mathbf{a}_i) and h0=finit,h(1L∑iai)\mathbf{h}_0 = f_{\mathrm{init,h}}(\frac{1}{L}\sum_i \mathbf{a}_i). The word distribution is p(yt∣⋅)∝exp⁡(Lo(Eyt−1+Lhht+Lzz^t))p(\mathbf{y}_t \mid \cdot) \propto \exp(\mathbf{L}_o(\mathbf{E}\mathbf{y}_{t-1} + \mathbf{L}_h\mathbf{h}_t + \mathbf{L}_z\hat{\mathbf{z}}_t)).

Training the hard model

The hard model maximises a variational lower bound LsL_s on log⁡p(y∣a)\log p(\mathbf{y} \mid \mathbf{a}). Its gradient is estimated by sampling s~\tilde{s} from the attention weights: ∂Ls∂W≈1N∑n[∂log⁡p(y∣s~n,a)∂W+λr(log⁡p(y∣s~n,a)−b)∂log⁡p(s~n∣a)∂W+λe∂H[s~n]∂W]\frac{\partial L_s}{\partial W} \approx \frac{1}{N}\sum_n \left[\frac{\partial \log p(\mathbf{y} \mid \tilde{s}^n, \mathbf{a})}{\partial W} + \lambda_r(\log p(\mathbf{y} \mid \tilde{s}^n, \mathbf{a}) - b)\frac{\partial \log p(\tilde{s}^n \mid \mathbf{a})}{\partial W} + \lambda_e\frac{\partial H[\tilde{s}^n]}{\partial W}\right]. The baseline bb is a moving average, updated as bk=0.9 bk−1+0.1log⁡p(y∣s~k,a)b_k = 0.9\, b_{k-1} + 0.1 \log p(\mathbf{y} \mid \tilde{s}_k, \mathbf{a}). The term with λe\lambda_e is an entropy bonus. The paper notes that this is the REINFORCE rule with the log-likelihood as the reward.

Training the soft model and the doubly stochastic penalty

The soft model is differentiable end to end, and it is trained on Ld=−log⁡P(y∣x)+λ∑i(1−∑tαti)2L_d = -\log P(\mathbf{y} \mid \mathbf{x}) + \lambda \sum_i (1 - \sum_t \alpha_{ti})^2. The penalty pushes each location's total attention over the caption towards 1, so the model looks at every part of the image at some point.

Results

All numbers below are from the paper's Table 1 and Sections 4 to 5.

  • Flickr8k. BLEU-4 is 19.5 for the soft model and 21.3 for the hard model, against 17.7 for a log-bilinear baseline. The hard model's METEOR is 20.30.
  • Flickr30k. BLEU-4 is 19.1 for soft and 19.9 for hard, against 18.3 for Google NIC (Vinyals et al.) in the same table.
  • MS COCO. BLEU-4 is 24.3 for soft and 25.0 for hard. BLEU-1 is 70.7 and 71.8. The authors also report a METEOR improvement on COCO, which they speculate is connected to their regularisation and lower-level image features.
  • Single model. All of these are single models, without an ensemble. Several competing entries use ensembles.
  • Training cost. On COCO the soft model trained in under three days on one Titan Black GPU. Mini-batches are grouped by caption length, which the authors say speeds convergence without hurting quality.
  • Visualisation. The 14 by 14 attention grid is upsampled by a factor of 16 and smoothed, which yields the maps in Figures 2 and 3.

Limits. The comparison uses BLEU and METEOR, which score n-gram overlap with reference captions rather than whether a caption is correct. Results use different feature extractors and dataset splits across rows, and the paper says so. Hard attention needs sampling and variance reduction, and its two weights (λr\lambda_r and λe\lambda_e) were set by cross-validation. The attention maps are offered as an aid to understanding mistakes, not as a score of caption quality.

Reading guide

  1. Section 1 (Introduction). The task and the two attention variants. Needs Attention Mechanism only as a concept.
  2. Section 2 (Related Work). The encoder-decoder view of captioning, from Encoder-Decoder Architecture and the earlier models it cites, such as Learning Phrase Representations using RNN Encoder-Decoder for SMT and Neural Machine Translation by Jointly Learning to Align and Translate.
  3. Section 3.1. The encoder and decoder equations. Needs Convolutional Neural Network, Long Short-Term Memory and Word Embedding.
  4. Sections 3.1.1 and 3.1.2. The attention scores, the softmax and the LSTM update. Needs Softmax.
  5. Section 4.1. The hard model and its gradient estimator. Needs REINFORCE, Variational Lower Bound (ELBO) and Policy Gradient.
  6. Section 4.2. The soft model and the expectation argument. Needs Categorical Distribution.
  7. Section 4.3 and Section 5. Training and results. Needs RMSProp, Adam Optimizer, Dropout, Early Stopping, VGG Network and BLEU Score.
  8. Section 5.4. Visualisation. Needs nothing new beyond the grid picture.

Check yourself

QuestionThree locations have scores 0, 0 and ln 2. What are the attention weights?Show answer

The exponentials are 1, 1 and 2, which sum to 4. The weights are 0.25, 0.25 and 0.5.

QuestionWhy does the soft model need no sampling, and what does the hard model give up in exchange for picking one location?Show answer

The soft model uses the weighted average of the annotation vectors, which is differentiable, so ordinary backpropagation works. The hard model samples a single location, which is not differentiable, so its gradient must be estimated with a score-function (REINFORCE) rule. That estimator has high variance. The paper uses a moving-average baseline to reduce it, and adds an entropy term with its own weight.

QuestionWhy does the paper use a 14 by 14 grid of features rather than one global vector, and where does 196 come from?Show answer

Each cell of the grid corresponds to a region of the input, so the decoder can attend to parts of the image. The grid is 14 by 14 because the 224 by 224 crop is downsampled four times by max pooling, and 14 times 14 is 196 locations.

QuestionThe soft model reports BLEU-4 of 19.5 on Flickr8k and the hard model reports 21.3. Compute the difference and say whether a single difference like this settles which variant is better.Show answer

The difference is 1.8 BLEU-4 points. This is one comparison on one dataset, so it shows the hard model scored higher on that split but does not by itself settle which variant is better in general.

QuestionIn the penalty L_d, what does the term sum over t of alpha_ti approaching 1 encourage?Show answer

It encourages each image location to receive roughly total attention of 1 across all the words of the caption, so the caption covers the image rather than fixating on a few regions.

Sources

Read the full paper

Kelvin Xu, Jimmy Ba, Ryan Kiros et al., 2015. arXiv:1502.03044