A PyTorch implementation of Show, Attend and Tell (Xu et al., 2015): a ResNet-50 encoder feeding a Bahdanau-attention LSTM decoder that generates a natural-language caption for an image, attending to a different region of the image at every word it produces.
Status: the architecture, training loop, beam-search decoder and BLEU evaluation are fully implemented and runnable end to end. No trained checkpoint ships with this repository, so no BLEU scores are reported below — train it yourself with the commands in Quickstart.
A plain CNN-to-LSTM captioner compresses the whole image into a single vector before the decoder sees it. Everything spatial is gone by the first word, and the model drifts toward safe, generic captions ("a man is standing outside").
This implementation keeps the encoder output as a 14 x 14 x 2048 spatial grid. At each decoding step the attention module scores all 196 regions against the current hidden state and builds a weighted context vector, so the word "frisbee" can be generated while the model is looking at the frisbee.
Two details from the paper that matter in practice and are implemented here:
- Gating (
f_beta) — a sigmoid gate lets the decoder decide how much visual context to admit at each step. Function words like "the" need almost none. - Doubly stochastic attention regularization — penalises
(1 - sum_t alpha_t)^2, pushing the model to attend to every region across the sentence rather than fixating on one, which measurably reduces repetitive captions.
Image (3, 224, 224)
|
v
EncoderCNN ResNet-50, fc + avgpool removed, frozen by default
| AdaptiveAvgPool2d -> (14, 14)
v
(196, 2048) spatial features
|
+---------------------------+
| |
v v
Attention <--------------- LSTMCell hidden state h_t
(additive, Bahdanau) ^
| |
v |
context (2048) --> gate --> concat with word embedding
|
v
Linear -> vocab logits
| Component | Choice |
|---|---|
| Encoder | ResNet-50, ImageNet weights, frozen (optionally fine-tune blocks 3-4) |
| Attention | Additive / Bahdanau, attention_dim configurable |
| Decoder | Single-layer LSTMCell, explicit time loop, teacher forcing |
| Decoding | Beam search (default beam = 5) |
| Loss | Cross-entropy over packed sequences + doubly stochastic attention penalty |
| Metric | Corpus BLEU-1 to BLEU-4 (NLTK, smoothing method 4) |
git clone https://github.com/MrDanial-Rafiee/image-captioning-attention.git
cd image-captioning-attention
pip install -r requirements.txtThis repo is built for the Flickr8k / Flickr30k layout. The dataset is not committed here (Flickr30k alone is ~32,000 images). Download it from Kaggle and arrange it as:
data/
├── captions.txt two columns: image,caption (one row per caption)
└── Images/ all .jpg files, flat
prepare_data.py groups the raw CSV by image and splits at the image level, so no image ever appears in both train and test:
python prepare_data.py --captions data/captions.txt --image_dir data/Images --out_dir dataOn Flickr30k this produces:
Parsed 158914 captions across 31783 images.
val : 1589 images, 7945 captions -> data/val_captions.json
test : 1589 images, 7945 captions -> data/test_captions.json
train: 28605 images, 143024 captions -> data/train_captions.json
python train.py \
--train_json data/train_captions.json \
--val_json data/val_captions.json \
--image_dir data/Images \
--epochs 20 --batch_size 32Checkpoints go to checkpoints/last.pth and checkpoints/best.pth; the vocabulary is written once to checkpoints/vocab.json and reused on later runs.
python evaluate.py \
--checkpoint checkpoints/best.pth --vocab checkpoints/vocab.json \
--test_json data/test_captions.json --image_dir data/Imagespython inference.py \
--checkpoint checkpoints/best.pth --vocab checkpoints/vocab.json \
--image path/to/photo.jpg --beam_size 5├── model.py EncoderCNN, Attention, DecoderRNNWithAttention, beam search
├── dataset.py CaptionDataset, dynamic-padding collate, image transforms
├── vocabulary.py word <-> index mapping, frequency threshold, save/load
├── prepare_data.py raw CSV -> train/val/test JSON, image-level split
├── train.py training loop, checkpointing, CLI
├── evaluate.py corpus BLEU-1..4
└── inference.py caption a single image or a whole folder
| Flag | Default | Notes |
|---|---|---|
--embed_dim |
256 | word embedding size |
--decoder_dim |
512 | LSTM hidden size |
--attention_dim |
256 | attention projection size |
--lr |
4e-4 | decoder learning rate |
--encoder_lr |
1e-4 | only used with --fine_tune_encoder |
--alpha_c |
1.0 | doubly stochastic attention weight |
--grad_clip |
5.0 | gradient norm clipping |
--freq_threshold |
5 | words rarer than this become <unk> |
- No pretrained checkpoint. Training Flickr30k for 20 epochs needs a GPU and several hours; nothing here has been trained to convergence, so no BLEU numbers are claimed.
- BLEU is a weak metric for captioning. CIDEr and SPICE correlate far better with human judgement and are not implemented.
- The encoder is frozen by default.
--fine_tune_encoderexists but has not been benchmarked against the frozen baseline. - The tokenizer is a regex split on alphanumerics. A subword tokenizer would shrink the
<unk>rate on rare words. - Attention maps are computed and returned but not visualised. Overlaying
alphaon the image per generated word is the obvious next addition. - A modern comparison point would be a ViT encoder or a pretrained BLIP/CLIP baseline.
Xu et al., Show, Attend and Tell: Neural Image Caption Generation with Visual Attention, ICML 2015. arXiv:1502.03044
MIT — see LICENSE.