Shipped
Image captioning with a Transformer
An encoder-decoder Transformer written from scratch in PyTorch that turns an image into a one-line caption, trained on the full COCO captions set.
stack: Python, PyTorch, Hugging Face Accelerate, COCO
Source codeApproach
The model has no pretrained backbone. Every layer is written in PyTorch.
The encoder cuts the image into patches with a convolutional patch embedding and adds a learned positional encoding. A stack of Transformer encoder layers then runs self-attention over the patches.
The decoder adds a sinusoidal positional encoding to the caption tokens. Each decoder layer runs masked self-attention over the words so far, then cross-attention over the image patches. Captions are tokenized with the GPT-2 tokenizer from Hugging Face, with start and end tokens added.
Training
The model was trained on the full COCO 2017 captions set, about 118,000 images, each normalized to the dataset’s own mean and standard deviation. Training used AdamW with a cosine learning-rate schedule and fp16 mixed precision through Hugging Face Accelerate. After each epoch the model writes captions for the validation images, and the checkpoint with the best BLEU-4 score is kept.
Results
The model reached a BLEU-4 score of 0.169. That is a baseline with no large-scale pretraining behind it. The captions partly match what is in the image but need more tuning.
What I’d do next
- Start from pretrained embeddings such as CLIP, ViT, or BERT instead of training every layer from zero.
- Add data augmentation so the model generalizes better.