RETTA for Zero Shot Video Captioning

Analysis by Adnan Saeed · Practical AI Tools

  • RETTA
  • Video captioning
  • Retrieval
  • Soft prompts
RETTA video captioning diagram showing retrieval, CLIP frame scoring and soft prompts for GPT-2
RETTA connects video retrieval to caption generation through a learned prompt. Figure 2 by Ma and colleagues, reproduced within an original cover under CC BY 4.0.

An editor scrubs through a clip of someone cutting bread. The archive search system needs a sentence describing the scene. A caption about slicing a loaf would help. An answer that begins like a cooking tutorial would miss the point, even if a search engine had already found sentences about bread. The example in the RETTA paper captures an awkward feature of video captioning. Retrieval can put the right subject within reach while leaving the language model unsure what to do with it.

Key points

  • RETTA adapts five learnable prompt vectors while keeping the model weights frozen.
  • Retrieved captions, recurring nouns and verbs, sampled frames, and the base generator guide the next token.
  • RETTA leads the listed zero shot comparisons on CIDEr across MSVD, MSR-VTT, and VATEX.
  • The paper reports 60.4 seconds per video in its efficiency comparison.
  • A fair test isolates the retrieval corpus from evaluation references and inspects what cleanup changes.

What a caption is supposed to do

Yunchuan Ma and colleagues at the University of Chinese Academy of Science and Macquarie University approached the problem by changing how retrieval reaches the generator. In their published Pattern Recognition study, the retrieved sentences guide the probabilities of possible next tokens. GPT-2 receives a small learned prompt shaped by those signals for the current clip. The study gives us a specific editorial and engineering question. How much computation should a system spend to turn approximate evidence into a better sentence?

An editor might care about whether a clip shows someone opening a box or closing it. A vocabulary search could retrieve sentences about both events, since a box and a pair of hands dominate the image either way. A fluent caption can still choose the wrong verb. This makes video description a useful test for retrieval systems. A match that looks good at the topic level can fail on the very detail that makes the clip worth indexing.

RETTA shares a lineage with ZeroCap by Tewel and colleagues, where visual matching steers a frozen language model for images. Their later study on evolving pseudo tokens extends that idea to video using scores from selected frames. RETTA adds a separate video retrieval model and gives retrieved text two routes into the loss. Our DamageRAG analysis covers a related design problem from a different angle. In both systems, the quality of the evidence deserves its own evaluation before anyone reads the final output as a reliable description.

“learnable tokens as a communication medium”Ma and colleagues, RETTA abstract

Follow a clip through RETTA

Build two kinds of visual evidence

XCLIP receives 16 uniformly sampled frames and ranks captions from the retrieval corpus. In the main benchmark, that corpus is the text from the training split. RETTA keeps 15 retrieved sentences and extracts five frequent nouns or verbs. The full descriptions can carry relationships that an isolated word loses. The keyword list gives recurring details a second route into the objective, even when the retrieved sentences disagree about the rest of the scene.

The frame matching branch uses a different view of the clip. It samples three frames per second and then prunes redundancy using CLIP image embeddings. The first frame is kept as an anchor. A later frame joins the set and becomes the new anchor when the paper’s similarity rule drops below 0.9. XCLIP retrieves at the video level, while CLIP scores text against the retained frames. These two paths respond to different kinds of evidence and can both miss a brief action that falls between samples.

Frequency is a practical filter when the neighbors are varied but agree on an object or action. It becomes less persuasive when the corpus repeats the same kind of stock caption. If near duplicates all mention a kitchen, a vote on words can make a kitchen feel inevitable even when the clip was filmed in a shop. The paper reports the effect of changing retrieval settings. It does not measure how much near duplication contributes to the improvement.

Adapt the prompt during generation

GPT-2 medium proposes likely next tokens from a phrase such as “Video showing” and the text generated so far. The system scores candidate continuations with AnglE for text similarity and CLIP for visual matching. The original generator distribution supplies a language constraint. An optimizer updates the five continuous prompt vectors and the generator can then emit a token with those vectors in its context. This repeats as the caption grows.

The candidate shortlist limits the expense and also defines what the evidence can see at that step. The paper uses 100 candidates for the main system. The VATEX experiment found its highest CIDEr with 250 candidates, at roughly twice the time of 100. A very specific noun with low initial probability might therefore get little direct support early in a sentence. A longer shortlist can expose more vocabulary to the scoring models, but every extra continuation adds text and image matching work.

At the end of a sentence, RETTA keeps the adapted prompt and starts another candidate caption. The reported configuration uses 16 caption generation rounds and allows up to 15 generated tokens per sentence. That distinction matters for estimating compute. An entire round can include several optimization steps as tokens are decoded. When the rounds finish, mean CLIP similarity across the retained frames selects a caption. A model trained on CommonGen then rebuilds it from extracted nouns and verbs.

Key takeaway

Five prompt vectors describe the size of the update. The runtime also includes the frozen model calls and the work of scoring candidate continuations at every decoding step.

Four signals shape the next token

Let \(s_k\) be the current caption extended by candidate token \(k\). Write \(R\) for the retrieved sentences, \(W\) for the frequent words, and \(F\) for retained frames. The three evidence terms in the paper use mean alignment scores across these sets. The expression below groups the terms so their different inputs are easy to see.

$$ a_k=\frac{1}{|R|}\sum_{r\in R}\operatorname{AnglE}(r,s_k),\qquad b_k=\frac{1}{|W|}\sum_{w\in W}\operatorname{AnglE}(w,s_k),\qquad c_k=\frac{1}{|F|}\sum_{f\in F}\operatorname{CLIP}(f,s_k). $$

If \(q_k\) is the probability of candidate \(k\) after adding the learned prompt, each evidence loss has the form of a weighted negative log probability. The language term keeps that distribution close to what the frozen generator predicts with the ordinary text prompt and the preceding tokens. The printed equations call the alignment averages soft targets but leave details of score normalization unspecified. A reconstruction should make that decision visible because the numerical scales of separate similarity models affect how much the losses can pull on the prompt.

$$ \mathcal{L}_{x}=-\sum_{k}x_k\log q_k,\quad x\in\{a,b,c\},\qquad \mathcal{L}=1.6\mathcal{L}_{\mathrm{language}}+0.8\mathcal{L}_{a}+0.3\mathcal{L}_{b}+1.0\mathcal{L}_{c}. $$

A candidate can score well in AnglE because it resembles several retrieved descriptions and poorly in CLIP because the visible subject differs. The language term also has opinions of its own. These terms add pressure in different directions, and the optimizer finds a compromise within the vocabulary of the generator. Agreement can increase confidence in a candidate, though the sources may share biases. A frame scorer and a retriever trained on familiar visual concepts can both favor the common action in a visually ambiguous scene.

The final score is another average over frames. There is a difference between observing an open box somewhere in a clip and observing the moment the box opens. A match to individual frames can support the first claim more readily than the second. An editor checking a verb reversal should examine the sampled frames in order. That review is worth doing even when the caption sounds entirely natural.

Read the quality and speed numbers together

On the three datasets, RETTA leads the zero shot methods listed in the paper on CIDEr. CIDEr rewards agreement with reference captions, giving weight to informative expressions shared with those references. The entries below are points on the reported scale. An increase from 18.6 to 24.3 is 5.7 CIDEr points. Expressing that change as accuracy would give readers the wrong idea about what was counted.

CIDEr from Tables 1 to 3 of the paper
DatasetBest listed zero shot comparatorComparatorRETTAGainBest listed supervised
MSVDEPT17.449.832.4121.5
MSR-VTTDeCap using COCO18.624.35.753.0
VATEXDeCap using COCO18.723.85.151.6

The comparison also depends on the selected metric. On MSR-VTT, RETTA scores 14.0 on BLEU at four and 19.3 on METEOR, while DeCap using COCO reaches 14.7 and 20.4. VATEX gives another mixed result. RETTA leads that comparator on METEOR, 16.3 versus 15.3, while trailing on BLEU at four, 11.4 versus 13.1. A user who values a particular naming convention or a consistent sentence form should examine samples alongside the scores. The broader AI Trend Blend article on prompt benchmarking looks at why an evaluation target matters when comparing prompts.

Efficiency comparison from Table 4 of the paper
MethodTraining secondsInference seconds per sampleCIDEr
DeCap using CC3M25,1970.118.4
EPT042.68.9
RETTA060.423.8

The paper describes experiments on one NVIDIA RTX A6000. Its timing table puts RETTA at 60.4 seconds per sample and EPT at 42.6 seconds. The zero in the training column refers to additional training within this comparison. The underlying weights were learned beforehand, and RETTA spends compute on adaptation during inference. These numbers are measured results for the reported setup. Any archive deployment would have to measure its own throughput, including decoding video, loading checkpoints, and accessing the corpus.

Table 5 suggests where some of that quality comes from. On VATEX the baseline scores 8.9 CIDEr. Adding sentence retrieval alone reaches 20.8. Adding word retrieval alone reaches 14.9. Using both reaches 21.4, and CommonGen cleanup raises that to 23.8. The sentence term has the larger isolated gain, and the keyword term gives a smaller incremental gain in the combined setup. Meanwhile cleanup moves BLEU at four from 2.4 to 11.4. That makes a useful case for saving the raw and cleaned outputs during an evaluation. A single final score hides how much of the change happened after visual reranking.

Key takeaway

Compare the raw winning caption with the cleaned version. The cleanup model receives keywords and can change the action or who performed it even when the sentence becomes easier to read.

What the evaluation leaves open

The most revealing corpus experiment uses the benchmark test split as a text source. On MSVD, CIDEr rises from 49.8 with training split captions to 60.7 with test split captions. It moves from 24.3 to 26.7 on MSR-VTT, and from 23.8 to 25.8 on VATEX. These are separate conditions from the main results. When retrieval has access to text from the evaluation split, the source becomes more closely aligned with the same references used to score the outputs. Those rows describe corpus sensitivity. A deployment claim should be based on results from a collection separated from evaluation references.

The difference between a useful corpus and a misleading one may depend less on its size than on what it covers. A collection of sports captions can offer useful language for serve, volley, and rally. It may generate plausible mistakes for clips of a racket being restrung. The three benchmarks provide evidence for the tested video collections. To estimate transfer, a team could keep the target videos fixed and compare an independent general corpus with an independent corpus written for the same domain. Keeping annotation boundaries intact gives that comparison a clear interpretation.

The frame sampler is another source of uncertainty. It is designed to discard similar frames, which is attractive when a static shot contains many repeated views. An action such as dropping a small object can happen while most pixels and much of the embedding stay similar. A visual error analysis could separate absent objects, reversed actions, incorrect participants, and missed brief events. These categories tell a video editor more about review time than a single aggregate caption score.

CommonGen introduces a different question. A fluent rewrite can add a subject or a setting to connect a supplied set of words. An editor cannot recover the source of that addition from the final sentence alone. A trace that records the selected frames, retrieved sentences, raw caption, and cleaned caption would make it possible to tell where an unsupported detail entered. The paper reports aggregate gains from cleanup. How often this stage adds unsupported details remains a question for a separate audit.

A practical test for a video archive

Use clips from the collection that will receive the captions. Choose a mix of ordinary footage and cases in which direction, timing, or who did what makes a meaningful difference. Hold those clips and their reference text out of corpus construction. Freeze a snapshot of the caption index before comparing systems. Record whether a failure came from retrieval, missing evidence in the frames, a candidate outside the shortlist, or the final rewrite. The same clip can expose more than one failure, so the reviewer should be able to keep multiple labels.

One comparison worth running is a direct frozen model caption against the full adapted result. A second is the winning caption before and after cleanup. A third is a smaller candidate or generation budget versus the reported configuration. Evaluate every configuration on the same clips and include both median and tail latency. Human review can ask a simple question for each sentence. Would a person relying on this description search for the right clip and understand the main action when they found it?

An archive that processes overnight might spend extra compute on clips where an initial caption conflicts with retrieved evidence. An interactive editor may care more about the immediate response, reserving deeper adaptation for material that goes into a searchable catalogue. The HybridAgent article covers a comparable decision about when to send an input through an expensive visual workflow. RETTA did not test a conditional compute policy, so the cost and quality effects of such a policy would need to be measured.

The benchmarks also differ in how much language they attach to each clip. The study describes around 40 references per MSVD video, 20 English annotations per MSR-VTT clip, and 10 English annotations for VATEX. A model gets more ways to agree with the human descriptions when annotators mention different details. Read each gain against methods on its own dataset. A score of 49.8 on MSVD and 23.8 on VATEX cannot tell us how often the same action would be described correctly under a common annotation policy.

The practical test can also expose differences between people reviewing captions for search and people reading them as descriptions. A search index may benefit from specific object names even when sentence order is awkward. A viewer may care more about whether the sentence assigns the right action to the right person. During review, ask separately whether all stated details are supported and whether the important event was mentioned. A broad caption can be fully supported while omitting the reason someone wanted to find the clip.

Where RETTA earns its extra computation

RETTA shows that retrieval can guide caption generation through an objective applied while the sentence is being written. The strongest evidence is the gain on CIDEr across all three listed zero shot benchmark comparisons. The margin varies substantially between datasets, which is useful information for anyone choosing where to invest time in replication.

The design puts the optimization budget next to the clip that needs it. It avoids fitting a new generator for the task and adds repeated work at inference. That choice fits a searchable archive with time to process clips. The same timing makes a live tool a harder case without changes to the decoding budget.

A similar approach could help with subject specific video collections if the corpus contains useful terminology and the clips have visual evidence that can support it. Independent corpora and accurate descriptions of unfamiliar events would make that a much stronger transfer test. The published results establish a reason to run it.

The immediate research opportunity is to measure which examples benefit from adaptation and at what point the gains taper off. Raw caption logs and independent assessments of factual detail would expose improvements that a consensus score could miss. Those same logs would show where the output became fluent at the expense of an important visual distinction.

The final test remains the clip itself. Give the system time when that time buys a description an editor can verify. Explore other workflow analyses in the Practical AI Tools collection.

PyTorch reconstruction

The example runs the optimization loop at inference and includes the retrieval, image matching, language generation, and cleanup stages. It uses the checkpoints named in the paper or their equivalent hosted version. The authors do not specify every implementation detail needed to reproduce the results. This reconstruction chooses softmax normalization for the alignment scores, cross entropy from the base distribution to the adapted distribution, and greedy decoding. Its dummy input test checks the caption loop and verifies that the generator stays frozen. Benchmark replication would require the original retrieval splits and a matching evaluation setup.

Show the complete Python example
# Python 3.10+. Install PyTorch for the smoke test.
# For actual video: transformers==4.49.0, pillow, opencv-python, spacy.
# For optional corpus evaluation: pycocoevalcap and Java on PATH.
# Run: python -m spacy download en_core_web_sm
# Then: python retta.py --video clip.mp4 --corpus independent_captions.txt
import argparse
from collections import Counter
from dataclasses import dataclass
import random

import torch
from torch import nn
from torch.nn import functional as F


@dataclass(frozen=True)
class Config:
    prompt_tokens: int = 5
    neighbors: int = 15
    keywords: int = 5
    candidates: int = 100
    rounds: int = 16
    max_tokens: int = 15


class SoftPrompt(nn.Module):
    def __init__(self, size, embedding):
        super().__init__()
        self.vectors = nn.Parameter(
            torch.randn(size, embedding.shape[-1], device=embedding.device,
                        dtype=embedding.dtype) * 0.02
        )

    def forward(self, text_embeddings):
        return torch.cat((self.vectors, text_embeddings), dim=0)


def four_losses(adapted, original, ids, sentence, word, vision):
    log_q = adapted.float().log_softmax(dim=-1)
    # Softmax converts each set of cosine scores to a unit mass target.
    # This normalization and the CE direction are reconstruction choices.
    def retrieval_ce(scores):
        if scores.numel() == 0:
            return log_q.new_zeros(())
        return -(scores.float().softmax(dim=0) * log_q[ids]).sum()

    language = -(original.float().softmax(dim=-1) * log_q).sum()
    return language, retrieval_ce(sentence), retrieval_ce(word), retrieval_ce(vision)


@torch.no_grad()
def evaluate(captions, visual_score):
    """Return the winning caption and its mean frame similarity."""
    scores = visual_score(captions)
    index = int(scores.argmax())
    return captions[index], float(scores[index])


def evaluate_cider(predictions, references):
    """Return CIDEr on the paper's scale for matched clip IDs."""
    from pycocoevalcap.cider.cider import Cider
    from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer

    if not predictions or set(predictions) != set(references):
        raise ValueError("Predictions and references must share nonempty clip IDs.")
    if any(not captions for captions in references.values()):
        raise ValueError("Each clip needs at least one reference caption.")
    tokenizer = PTBTokenizer()
    gold = {i: [{"caption": text} for text in references[i]] for i in predictions}
    generated = {i: [{"caption": text}] for i, text in predictions.items()}
    score, _ = Cider().compute_score(tokenizer.tokenize(gold), tokenizer.tokenize(generated))
    return 100 * float(score)


class RETTA(nn.Module):
    def __init__(self, generator, tokenizer, cfg=Config()):
        super().__init__()
        self.generator = generator.eval().requires_grad_(False)
        self.tokenizer = tokenizer
        self.cfg = cfg

    def caption(self, evidence, seed=0):
        cfg = self.cfg
        rng = random.Random(seed)
        embed = self.generator.get_input_embeddings()
        device = embed.weight.device
        prompt = SoftPrompt(cfg.prompt_tokens, embed.weight)
        optimizer = torch.optim.AdamW(prompt.parameters(), lr=1e-4, weight_decay=0.3)
        stop = self.tokenizer.eos_token_id
        candidates = []
        for _ in range(cfg.rounds):
            phrase = rng.choice(("Video showing", "Video of", "Video shows"))
            hard = self.tokenizer.encode(phrase, add_special_tokens=False)
            generated = []
            for _ in range(cfg.max_tokens):
                ids = torch.tensor(hard + generated, device=device, dtype=torch.long)
                fixed = embed(ids).detach()
                with torch.no_grad():
                    original = self.generator(
                        inputs_embeds=fixed[None], use_cache=False
                    ).logits[0, -1]
                    pool = original.topk(min(cfg.candidates, original.numel())).indices
                    texts = [self.tokenizer.decode(generated + [i], skip_special_tokens=True).strip()
                             for i in pool.tolist()]
                    sentence, word = evidence.semantic(texts)
                    vision = evidence.visual(texts)
                optimizer.zero_grad(set_to_none=True)
                scores = self.generator(
                    inputs_embeds=prompt(fixed)[None], use_cache=False
                ).logits[0, -1]
                lang, sent, key, frame = four_losses(
                    scores, original, pool, sentence, word, vision
                )
                loss = 1.6 * lang + 0.8 * sent + 0.3 * key + frame
                loss.backward()
                optimizer.step()
                with torch.no_grad():
                    logits = self.generator(
                        inputs_embeds=prompt(fixed)[None], use_cache=False
                    ).logits[0, -1]
                    token = int(logits.argmax())
                if token == stop:
                    break
                generated.append(token)
                if self.tokenizer.decode([token]).rstrip().endswith((".", "!", "?")):
                    break
            text = self.tokenizer.decode(generated, skip_special_tokens=True).strip()
            if text:
                candidates.append(text)
        if not candidates:
            raise RuntimeError("The generator produced no nonempty captions.")
        raw, score = evaluate(candidates, evidence.visual)
        return {"raw": raw, "caption": evidence.clean(raw), "frame_score": score}


class VideoEvidence:
    """One clip, one independent caption corpus, and fixed scoring models."""
    @torch.no_grad()
    def __init__(self, source, corpus, device, cfg):
        import cv2
        import spacy
        from PIL import Image
        from transformers import (AutoModel, AutoModelForSeq2SeqLM, AutoProcessor,
                                  AutoTokenizer, CLIPModel, CLIPProcessor)

        self.device = device
        self.nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"])
        if not corpus:
            raise ValueError("Provide a nonempty corpus containing one caption per line.")

        cap = cv2.VideoCapture(source)
        all_frames = []
        try:
            fps = cap.get(cv2.CAP_PROP_FPS)
            if fps <= 0:
                raise ValueError("The video has no usable frame rate.")
            while True:
                ok, frame = cap.read()
                if not ok:
                    break
                all_frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
        finally:
            cap.release()
        if not all_frames:
            raise ValueError("No video frames could be decoded.")

        selected = torch.linspace(0, len(all_frames) - 1, 16).round().long().tolist()
        video = [all_frames[i] for i in selected]
        xclip_id = "microsoft/xclip-base-patch16-kinetics-600-16-frames"
        xproc = AutoProcessor.from_pretrained(xclip_id)
        xclip = AutoModel.from_pretrained(xclip_id).to(device).eval()
        ranks = []
        for start in range(0, len(corpus), 32):
            batch = xproc(text=corpus[start:start + 32], videos=video, padding=True,
                          truncation=True, return_tensors="pt").to(device)
            ranks.append(xclip(**batch).logits_per_video[0].cpu())
        top = torch.cat(ranks).topk(min(cfg.neighbors, len(corpus))).indices.tolist()
        neighbors = [corpus[i] for i in top]
        del xclip
        keys = [term for term, _ in Counter(
            word for text in neighbors for word in self.terms(text)
        ).most_common(cfg.keywords)]

        clip_id = "openai/clip-vit-large-patch14"
        self.clip = CLIPModel.from_pretrained(clip_id).to(device).eval()
        self.clip_processor = CLIPProcessor.from_pretrained(clip_id)
        count = min(len(all_frames), max(1, int(len(all_frames) * 3 / fps + 0.999)))
        rate_indices = [min(len(all_frames) - 1, int(i * fps / 3)) for i in range(count)]
        pixels = self.clip_processor(images=[all_frames[i] for i in rate_indices],
                                     return_tensors="pt").pixel_values
        frame_vecs = F.normalize(torch.cat([
            self.clip.get_image_features(pixel_values=batch.to(device))
            for batch in pixels.split(32)
        ]), dim=-1)
        keep = [0]
        for i in range(1, len(frame_vecs)):
            if float(frame_vecs[i] @ frame_vecs[keep[-1]]) < 0.9:
                keep.append(i)
        self.frame_vecs = frame_vecs[keep]
        angle_id = "WhereIsAI/UAE-Large-V1"
        self.angle = AutoModel.from_pretrained(angle_id).to(device).eval()
        self.angle_tokenizer = AutoTokenizer.from_pretrained(angle_id)
        self.neighbor_vecs = self.encode_text(neighbors)
        self.key_vecs = self.encode_text(keys) if keys else None
        cleaner_id = "mrm8488/t5-base-finetuned-common_gen"
        self.cleaner_tokenizer = AutoTokenizer.from_pretrained(cleaner_id)
        self.cleaner = AutoModelForSeq2SeqLM.from_pretrained(cleaner_id).to(device).eval()

    def terms(self, text):
        return [t.lemma_.lower() for t in self.nlp(text)
                if t.is_alpha and t.pos_ in {"NOUN", "PROPN", "VERB"}]

    @torch.no_grad()
    def encode_text(self, texts):
        batch = self.angle_tokenizer(texts, padding=True, truncation=True,
                                     return_tensors="pt").to(self.device)
        return F.normalize(self.angle(**batch).last_hidden_state[:, 0], dim=-1)

    @torch.no_grad()
    def semantic(self, captions):
        vecs = self.encode_text(captions)
        sentence = (vecs @ self.neighbor_vecs.T).mean(dim=1)
        word = (vecs @ self.key_vecs.T).mean(dim=1) if self.key_vecs is not None else vecs.new_empty(0)
        return sentence, word

    @torch.no_grad()
    def visual(self, captions):
        batch = self.clip_processor(text=captions, padding=True, truncation=True,
                                    return_tensors="pt").to(self.device)
        vecs = F.normalize(self.clip.get_text_features(**batch), dim=-1)
        return (vecs @ self.frame_vecs.T).mean(dim=1)

    @torch.no_grad()
    def clean(self, raw):
        words = list(dict.fromkeys(self.terms(raw)))
        if not words:
            return raw
        text = " ".join(words)
        batch = self.cleaner_tokenizer(text, return_tensors="pt").to(self.device)
        output = self.cleaner.generate(**batch, max_new_tokens=32, num_beams=4)
        return self.cleaner_tokenizer.decode(output[0], skip_special_tokens=True).strip() or raw


def smoke_test():
    from types import SimpleNamespace

    class TinyGenerator(nn.Module):
        def __init__(self):
            super().__init__()
            self.embeddings = nn.Embedding(8, 12)
            self.head = nn.Linear(12, 8)

        def get_input_embeddings(self):
            return self.embeddings

        def forward(self, inputs_embeds, use_cache=False):
            logits = self.head(inputs_embeds.cumsum(dim=1))
            logits = logits.masked_fill(torch.arange(8) == 0, -1000)
            return SimpleNamespace(logits=logits)

    class TinyTokenizer:
        eos_token_id = 0

        def encode(self, text, add_special_tokens=False):
            return [1, 2]

        def decode(self, ids, skip_special_tokens=True):
            return " ".join(f"token{idx}" for idx in ids if idx != 0)

    class TinyEvidence:
        def visual(self, texts):
            return torch.tensor([0.2 + 0.1 * text.count("token3") for text in texts])

        def semantic(self, texts):
            return self.visual(texts), torch.arange(len(texts), dtype=torch.float32)

        def clean(self, text):
            return text.capitalize()

    torch.manual_seed(7)
    cfg = Config(rounds=2, candidates=4, max_tokens=3)
    model = RETTA(TinyGenerator(), TinyTokenizer(), cfg)
    weights = [p.detach().clone() for p in model.parameters()]
    result = model.caption(TinyEvidence())
    assert result["raw"] and result["caption"] and torch.isfinite(torch.tensor(result["frame_score"]))
    assert all(torch.equal(p, old) and p.grad is None for p, old in zip(model.parameters(), weights))
    print(result)


if __name__ == "__main__":
    from pathlib import Path
    parser = argparse.ArgumentParser()
    parser.add_argument("--video")
    parser.add_argument("--corpus")
    args = parser.parse_args()
    if bool(args.video) != bool(args.corpus):
        parser.error("--video and --corpus must be provided together")
    if not args.video:
        smoke_test()
    else:
        from transformers import AutoModelForCausalLM, AutoTokenizer
        torch.manual_seed(7)
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        cfg = Config()
        corpus = [line.strip() for line in Path(args.corpus).read_text(encoding="utf-8").splitlines()
                  if line.strip()]
        evidence = VideoEvidence(args.video, corpus, device, cfg)
        generator_id = "openai-community/gpt2-medium"
        model = RETTA(AutoModelForCausalLM.from_pretrained(generator_id).to(device),
                      AutoTokenizer.from_pretrained(generator_id), cfg)
        print(model.caption(evidence, seed=7))

Frequently asked questions

What does RETTA update when captioning a video?

RETTA updates five continuous prompt vectors while the pretrained model weights stay frozen. Each new clip gets its own prompt.

Where do the retrieved sentences come from?

The main experiments retrieve captions from the training split text corpus. A separate corpus comparison uses text from the test split and reports separate results.

Why does RETTA take so long to caption a clip?

It scores many possible continuations during decoding, updates the prompt, generates multiple captions, and reranks them. The paper reports 60.4 seconds per sample in its efficiency comparison.

Which dataset showed the largest CIDEr gain?

MSVD showed the largest gain against the best listed zero shot comparator. RETTA scored 49.8 and EPT scored 17.4, a difference of 32.4 CIDEr points.

Does the final cleanup step inspect the video again?

The cleanup model rewrites extracted nouns and verbs from the selected caption. The paper describes no additional frame check after that rewrite.

Can I run the PyTorch example without video checkpoints?

Yes. Run it without arguments to use the illustrated smoke test with dummy inputs. The video mode downloads pretrained checkpoints and takes a video and an independent text corpus.

Read the paper and dataset documentation

Yunchuan Ma, Laiyun Qing, Guorong Li, Yuankai Qi, Amin Beheshti, Quan Z. Sheng, and Qingming Huang. RETTA. Pattern Recognition 171, article 112170, 2026. doi.org/10.1016/j.patcog.2025.112170.

This analysis is based on the published paper and an independent evaluation of its claims.

Related reading

2 thoughts on “RETTA for Zero Shot Video Captioning”

Leave a Comment

Your email address will not be published. Required fields are marked *