Ismail Ben Alla

Image Captioner

Multimodal Image Captioning

Multimodal · Aug 2024 · Completed

A model that looks at a photo and writes a sentence describing it

Built withPyTorchCustom TransformersStreamlitPoetryHugging Face Transformerseinopstorchvision

Image Captioner — overview

Overview

Image captioning asks a model to connect two modalities: pixels and words. I wanted to understand that connection from the inside, so I wrote every piece of a captioning model by hand in PyTorch instead of assembling pretrained components.

I built an encoder-decoder Transformer: a Vision Transformer encoder turns the image into a sequence of patch tokens, and a Transformer decoder writes the caption one token at a time, using cross-attention to look at the image tokens at every step. The training setup targets the Flickr30k image-caption dataset on Kaggle.

The project taught me how cross-attention lets a text decoder condition on a different modality, and how small choices such as weight tying, label smoothing, and length-aware batching shape training. It is a learning artifact trained on limited data, not a production captioner.

The question

Can a from-scratch ViT encoder plus a cross-attention Transformer decoder learn to align visual and textual representations well enough to caption images end-to-end?

Key features

How it works

  1. Patch the image

    A convolution with kernel and stride equal to the patch size turns the image into a sequence of patch embeddings, then learnable position encodings are added.

  2. Encode

    Stacked residual self-attention and feed-forward blocks build contextual visual tokens.

  3. Decode with cross-attention

    The caption decoder attends to earlier words with masked self-attention and to the visual tokens with cross-attention.

  4. Train

    GPT-2 tokenizer with added start, end, and pad tokens; label-smoothed cross-entropy over the real caption tokens; warmup learning-rate schedule and gradient clipping.

  5. Describe

    Beam search with length normalization and top-k / top-p filtering picks the best caption hypothesis.

Examples

The pipeline: image patches go through a ViT encoder, and a cross-attention decoder writes the caption.
The pipeline: image patches go through a ViT encoder, and a cross-attention decoder writes the caption.

Tech stack

What I learned

Limitations