Multimodal NLP: Text and Vision Integration
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Compare two-tower, fusion, and bridge architectures for image and text
- 2Derive the contrastive loss that aligns images with their captions
- 3Score captions with CIDEr and measure hallucination with CHAIR
- 4Explain the VQA soft accuracy metric and why it tolerates disagreement
Multimodal NLP joins an image encoder with a text encoder so that pictures and sentences live in one embedding space. The same stack supports image captioning, visual question answering, image text retrieval, and zero-shot classification.
Three Architecture Families
A two-tower model encodes images and texts separately, projects both into a shared space, and trains them to match with a contrastive loss. CLIP (Radford et al., 2021) trained this way on 400 million image text pairs and reached 76.2 percent top-1 accuracy on ImageNet with zero training on those labels, because each class name is just another text prompt.
A fusion model lets the two modalities attend to each other before predicting. Co-attention stacks such as ViLBERT alternate image to text and text to image attention, while ViLT feeds image patches into a standard transformer without a region detector. Fusion wins on reasoning tasks like NLVR2 and VQA, where the answer depends on relating a phrase to a specific region.
A bridge model freezes both sides and learns a small connector: Flamingo uses a perceiver resampler with gated cross attention, and BLIP-2 trains a Q former that maps image features into prompts a frozen language model understands. Only the connector is trained.
| Family | Interaction | Strong tasks | Example |
|---|---|---|---|
| Two-tower | late, at the embedding | retrieval, zero-shot classification | CLIP |
| Fusion | early, token level cross attention | VQA, NLVR2, grounding | ViLBERT, ViLT |
| Bridge | learned tokens into a language model | captioning, visual dialogue | Flamingo, BLIP-2 |
Captioning and Visual Question Answering
Captioning is conditional generation: an autoregressive decoder produces tokens conditioned on image features, and training maximizes the log probability of the reference captions. The standard corpus is MS COCO, which contains 123,287 images with at least five captions each, usually split 113k train, 5k validation, and 5k test following Karpathy and colleagues.
Evaluation mixes corpus metrics with hallucination checks. CIDEr weights each n-gram by its inverse document frequency so that distinctive phrases count more than generic ones, and CHAIR catches captions that name an object not in the picture.
Visual question answering asks for a short answer given an image and a question. The metric allows for human disagreement: the prediction earns full credit once three annotators gave it.
Human annotators reach about 86.8 percent on VQAv2 under this metric, so systems above 80 percent are already close to the practical ceiling.
Worked Code
The first program computes a contrastive loss and runs zero-shot matching with nothing but lists and math.
import math
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def norm(a):
return math.sqrt(dot(a, a))
def cosine(a, b):
return dot(a, b) / (norm(a) * norm(b))
def info_nce(images, texts, tau=0.07):
total, n = 0.0, len(images)
for i in range(n):
sims = [cosine(images[i], texts[j]) / tau for j in range(n)]
exps = [math.exp(s) for s in sims]
total -= math.log(exps[i] / sum(exps))
return total / n
images = [[1.0, 0.1, 0.0], [0.0, 1.0, 0.2], [0.9, 0.8, 0.1]]
texts = [[0.9, 0.2, 0.1], [0.1, 1.0, 0.3], [0.8, 0.7, 0.2]]
print("loss:", round(info_nce(images, texts), 3))
prompts = ["a dog", "a car", "a cake"]
query = [0.95, 0.05, 0.05]
scores = [(round(cosine(query, t), 3), label) for t, label in zip(texts, prompts)]
scores.sort(reverse=True)
print("ranking:", scores)
The second program scores a caption against references with a small CIDEr style n-gram metric plus the CHAIR hallucination check.
import math
from collections import Counter
def ngrams(tokens, n):
return [tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1)]
def idf(gram, df, total):
return math.log((total + 1) / (df[gram] + 1)) + 1
def cider_ngram(pred, refs, n):
pred_n = ngrams(pred, n)
if not pred_n:
return 0.0
df = Counter()
for ref in refs:
df.update(set(ngrams(ref, n)))
total = len(refs)
def vec(toks):
return {g: cnt * idf(g, df, total) for g, cnt in Counter(toks).items()}
vp, np_ = vec(pred_n), math.sqrt(sum(v * v for v in vec(pred_n).values()))
if np_ == 0:
return 0.0
score = 0.0
for ref in refs:
vr = vec(ngrams(ref, n))
nr = math.sqrt(sum(v * v for v in vr.values()))
dot = sum(vp[g] * vr.get(g, 0.0) for g in vp)
score += 0.0 if nr == 0 else dot / (np_ * nr)
return score / total
VOCAB = {"dog", "frisbee", "bicycle", "cat", "grass", "field", "ball"}
def chair_s(sentences, objects):
flagged = [s for s in sentences
if any(w.strip(".,") in VOCAB and w.strip(".,") not in objects
for w in s.split())]
return round(len(flagged) / max(len(sentences), 1), 3)
image_objects = {"dog", "frisbee", "grass"}
preds = ["A dog catches a frisbee on the grass", "A dog runs beside a bicycle"]
refs = [["A dog catches a frisbee on the grass", "The dog plays with a frisbee"],
["A dog runs across the grass", "A dog near the field"]]
print("CIDEr-1 first:", round(cider_ngram(preds[0].split(), [r.split() for r in refs[0]], 1), 3))
print("CIDEr-1 second:", round(cider_ngram(preds[1].split(), [r.split() for r in refs[1]], 1), 3))
print("CHAIR_s:", chair_s(preds, image_objects))
Real-World Applications
- E commerce search: shoppers photograph an item and type "waterproof hiking boot", and a shared embedding space ranks listings by both signals.
- Accessibility: screen readers generate captions for photos, where the CHAIR score gates a release because a wrong object name misleads a blind user.
- Medical imaging: report generation pairs a scan with a sentence, and fusion models check that each claim points at a visible region.
đĄReport both retrieval and reasoning numbers
Common Mistakes
Evaluating captions with BLEU alone
Fix: Add CIDEr and a hallucination metric such as CHAIR so object errors are visible
Comparing VQA scores across different answer spaces
Fix: State the dataset and whether soft accuracy or exact match was used
Treating zero-shot accuracy as task free
Fix: Remember that prompt templates were tuned on validation data
Best Practices
- Freeze encoders first and train only the projection or bridge before joint fine tuning
- Keep batch size large in contrastive training because negatives come from the batch
- Report temperature and prompt templates, since both shift zero shot numbers
Key Takeaways
- Two-tower models align embeddings late, fusion models attend early, bridges connect to frozen language models
- The contrastive loss normalizes over the batch, so every pair is a negative for every other pair
- CIDEr downweights common n-grams and CHAIR penalizes objects that are not in the image
- VQA accuracy caps at one once three annotators agree, and humans reach about 86.8 percent
Frequently Asked Questions
Why does batch size matter in contrastive training?
Negatives come from the batch, so a bigger batch gives more distractors and a sharper signal. Systems gather embeddings across devices to build larger effective batches.
When should a fusion model be preferred?
When the task requires relating a phrase to a region, such as counting objects or spatial questions. Two-tower models suffice when one global embedding can describe the image.
How is hallucination measured beyond CHAIR?
CHAIR counts object mentions absent from the ground truth object set. Some pipelines go further and block any noun that an object detector cannot verify.
Interview Questions
Q1: Explain the role of temperature in the contrastive loss
It scales similarities before the softmax, controlling how hard the model pushes away negatives and how sharply zero shot scores separate classes
Q2: Why does BLIP-2 train a Q former instead of the whole model?
It freezes the image encoder and language model and trains a small connector, which keeps training cheap while still mapping image features into the language model space
Q3: What does CHAIR catch that BLEU misses?
BLEU only compares against references, while CHAIR checks the image itself, exposing objects the caption invents