Image captioning on Flickr8k: frozen ResNet-50 + Transformer decoder

A small captioning model, written from scratch: a frozen ResNet-50 (ImageNet weights) turns the photo into a 7ร—7 grid of region vectors, and a 3-layer Transformer decoder writes the caption token by token, reading those regions through cross-attention. Captions use a byte-level BPE tokenizer of 2,048 tokens, also written from scratch.

Try it in your browser: layeser.github.io โ€บ ML from scratch (the ONNX files of this repository, run with ONNX Runtime Web; your photo never leaves your device).

The first eight test photos, model and human captions

Results on the 1,000 Flickr8k test photos

Method BLEU-1 BLEU-2 BLEU-3 BLEU-4
The same caption for every photo 31.1 12.7 5.0 2.4
Copy a caption of the most similar training photo 48.0 28.4 16.7 9.6
This model, greedy decoding 62.2 44.0 29.8 19.9
This model, beam search (3) 65.5 47.5 33.4 23.1
A human caption, scored against the 4 others 63.7 44.7 30.6 21.0
This model, beam 3, scored against the same 4 captions 60.7 42.3 28.7 19.2

BLEU is computed with an implementation written from the paper and checked against NLTK. Against the same four references as a human caption, the model scores slightly below people (19.2 vs 21.0 BLEU-4).

Cross-attention over the 7ร—7 regions, word by word

Files

File What it is
encoder.onnx photo (1, 3, 224, 224) โ†’ memory (1, 49, 512): ResNet-50 regions, projected, with their positions
decoder.onnx memory (B, 49, 512), tokens (B, T) โ†’ log-probabilities of the next token (B, 2048), and the last layer's cross-attention for that step (B, 49)
tokenizer.json the caption BPE: regex pattern, merges, ids of <pad>, <bos>, <eos>
captioner.pt the PyTorch decoder checkpoint, for the project's own code

The ONNX files store their weights in float16 and compute in float32. On 200 test photos, 196 beam-search captions are identical to PyTorch's, with the same BLEU-4.

Use the ONNX files in Python

import json
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from PIL import Image

REPO = "layeser/flickr8k-captioning-resnet50-transformer"
enc = ort.InferenceSession(hf_hub_download(REPO, "encoder.onnx"))
dec = ort.InferenceSession(hf_hub_download(REPO, "decoder.onnx"))
tok = json.load(open(hf_hub_download(REPO, "tokenizer.json")))

# Token id -> bytes: 256 single bytes, then one entry per merge, in order.
vocab = [bytes([i]) for i in range(256)]
for a, b in tok["merges"]:
    vocab.append(vocab[a] + vocab[b])
bos, eos = tok["special"]["<bos>"], tok["special"]["<eos>"]

# Whole photo resized to 224x224 (bilinear), ImageNet normalisation, channels first.
img = Image.open("photo.jpg").convert("RGB").resize((224, 224), Image.BILINEAR)
x = (np.asarray(img, dtype=np.float32) / 255 - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
x = x.transpose(2, 0, 1)[None].astype(np.float32)

memory = enc.run(None, {"image": x})[0]
ids = [bos]
for _ in range(30):  # greedy decoding
    logp = dec.run(None, {"memory": memory, "tokens": np.array([ids], dtype=np.int64)})[0]
    nxt = int(logp[0].argmax())
    if nxt == eos:
        break
    ids.append(nxt)
print(b"".join(vocab[i] for i in ids[1:]).decode("utf-8", errors="replace").strip())

This is greedy decoding (BLEU-4 19.9). Beam search of width 3 (BLEU-4 23.1) is in the project's code.

Training

  • Data: Flickr8k, official split: 6,000 training photos (five human captions each), 1,000 for choosing the epoch, 1,000 for the final score.
  • Model: ResNet-50 frozen, region features computed once; decoder of 512 dimensions, 3 layers, 8 heads, dropout 0.3, 15.8 M trainable parameters.
  • Training: teacher forcing, AdamW, warm-up then cosine decay, label smoothing 0.1, 20 epochs; the epoch with the best dev BLEU-4 (epoch 8) is kept.

Limits

  • Trained on 6,000 photos of people and animals: it miscounts ("two dogs" for one), describes everything else with the words it knows, and can write fluent nonsense.
  • ImageNet features describe objects, not counts or relations; BLEU rewards common phrasings, which flatters generic captions.

Code and licence

Code, explainer and tests: github.com/Layeser/ai-portfolio โ€บ ml-from-scratch (docs/image_captioning.md). Research and educational use only: the decoder was trained on Flickr8k, whose photos come from Flickr and are distributed for research; the encoder uses torchvision's ImageNet weights of ResNet-50.

Author: Sekou Kaba

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Space using layeser/flickr8k-captioning-resnet50-transformer 1

Collection including layeser/flickr8k-captioning-resnet50-transformer