Search

Search papers and lessons

Vision-Language Model

Level 3 · 11 min read

A vision-language model maps images and text into one shared representation, so a single system can look at a picture and read, compare or write about it.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Losses & regularization
  • Sign in to see your progress

TL;DR

A vision-language model (VLM) is a neural network that takes images and text as input and works with both. Some VLMs put the two kinds of input into one shared space, so a picture and a sentence can be compared directly. Others attach an image encoder to a language model, so the model can answer questions about a picture or describe it in words.

Where you'll see it: image search that accepts a plain-English query, zero-shot image classification, and chat assistants that can read a photo, a chart or a screenshot.

Intuition

Two translators into one language

Think of two interpreters who each speak only one language: one knows pictures, the other knows text. If they agree on a shared vocabulary of meanings, a caption and the photo it describes can be matched by meaning, even though neither interpreter understands the other's format. A vision-language model builds that shared vocabulary out of numbers. An image encoder turns a picture into a vector, a text encoder turns a sentence into a vector, and training pushes matching pairs to land near each other.

There is a second way to use the same idea. Instead of matching two vectors, keep the image as a short sequence of vectors and hand that sequence to a language model, as if the picture were a long prefix of words. The language model can then talk about the picture in the same way it talks about any text. Most modern chat-style VLMs work this way.

The reason these systems exist is that images carry information that text describes badly, and text carries intent that pixels do not. A fixed list of labels such as "cat" or "dog" throws away everything except the label. A model that reads free text can handle "a cat asleep on a red chair" or "why is this chart going down?" without anyone collecting labels for those exact phrases.

flowchart LR
    IMG[Image] --> VE[Vision encoder]
    VE --> PROJ[Projection into shared space]
    TXT[Text prompt] --> TE[Text encoder or token embeddings]
    PROJ --> FUSE{Shared space or language model}
    TE --> FUSE
    FUSE --> OUT[Similarity score or generated text]

The math

A VLM has three parts that appear in most designs: an image encoder ff, a text encoder or token embedding gg, and a head that uses both. For an image xx and a text tt, the encoders produce vectors

u=f(x)∈Rd,v=g(t)∈Rd\mathbf{u} = f(x) \in \mathbb{R}^{d}, \qquad \mathbf{v} = g(t) \in \mathbb{R}^{d}

where dd is the embedding dimension. In the shared-space design, both vectors are normalised to length one, and the score of the pair is their cosine similarity

s(x,t)=u⊤v∥u∥ ∥v∥s(x, t) = \frac{\mathbf{u}^{\top}\mathbf{v}}{\lVert \mathbf{u} \rVert \, \lVert \mathbf{v} \rVert}

which lies between −1-1 and 11. Training makes the score high for matching pairs and low for mismatched ones. The standard objective for this is contrastive learning, where each image in a batch of NN pairs must pick out its own caption among the NN candidates. Written with a temperature τ>0\tau \gt 0 and cross-entropy over one row of the similarity matrix, the image-to-text term for pair ii is

ℓi=−log⁡exp⁡(s(xi,ti)/τ)∑j=1Nexp⁡(s(xi,tj)/τ)\ell_i = -\log \frac{\exp\left(s(x_i, t_i)/\tau\right)}{\sum_{j=1}^{N} \exp\left(s(x_i, t_j)/\tau\right)}

The denominator is a Softmax over the batch. A smaller τ\tau makes the softmax sharper, so the model is penalised more for near-misses. The full loss averages this term with the matching text-to-image term.

In the generative design, the image is turned into KK vectors z1,…,zK\mathbf{z}_1, \dots, \mathbf{z}_K and placed before the text tokens t1,…,tTt_1, \dots, t_T. The language model then factorises the probability of the text given the image in the usual way:

p(t1,…,tT∣x)=∏k=1Tp(tk∣z1:K,t1:k−1)p(t_1, \dots, t_T \mid x) = \prod_{k=1}^{T} p\left(t_k \mid \mathbf{z}_{1:K}, t_{1:k-1}\right)

Each factor is a next-token prediction, exactly as in a language model. The only new piece is the conditioning on z1:K\mathbf{z}_{1:K}. Training minimises the negative logarithm of this product, summed over a dataset of image-text pairs.

Zero-shot classification

Given CC class names, write one prompt per class, such as "a photo of a dog". Embed each prompt with gg. For a new image, compute s(x,tc)s(x, t_c) for every class cc and turn the scores into probabilities with a softmax, using a fixed scale β\beta in place of 1/τ1/\tau:

P(c∣x)=exp⁡(β s(x,tc))∑c′=1Cexp⁡(β s(x,tc′))P(c \mid x) = \frac{\exp\left(\beta \, s(x, t_c)\right)}{\sum_{c'=1}^{C} \exp\left(\beta \, s(x, t_{c'})\right)}

Choosing the class with the largest probability is a classifier whose label set was written in words at test time. No new training is needed to add a class.

Worked examples

Example
Contrastive loss on a batch of two pairs

Use two-dimensional unit vectors so the numbers are easy to check. The image embeddings are u1=(1,0)\mathbf{u}_1 = (1, 0) and u2=(0,1)\mathbf{u}_2 = (0, 1). The text embeddings are v1=(0.8,0.6)\mathbf{v}_1 = (0.8, 0.6) and v2=(0.6,0.8)\mathbf{v}_2 = (0.6, 0.8). Take τ=0.5\tau = 0.5.

  1. Pair scores are dot products. s11=1(0.8)+0(0.6)=0.8s_{11} = 1(0.8) + 0(0.6) = 0.8.
  2. s12=1(0.6)+0(0.8)=0.6s_{12} = 1(0.6) + 0(0.8) = 0.6.
  3. s21=0(0.8)+1(0.6)=0.6s_{21} = 0(0.8) + 1(0.6) = 0.6, and s22=0(0.6)+1(0.8)=0.8s_{22} = 0(0.6) + 1(0.8) = 0.8.
  4. Divide by τ=0.5\tau = 0.5. The logits for row 1 are 1.61.6 (correct) and 1.21.2 (wrong).
  5. exp⁡(1.6)≈4.953\exp(1.6) \approx 4.953 and exp⁡(1.2)≈3.320\exp(1.2) \approx 3.320. The sum is 8.2738.273.
  6. The probability of the correct caption for image 1 is 4.953/8.273≈0.5994.953 / 8.273 \approx 0.599.
  7. The loss for that row is −ln⁡(0.599)≈0.513-\ln(0.599) \approx 0.513.

By symmetry, row 2 and both column terms also give 0.5130.513, so the batch loss is 0.5130.513. The loss is not zero because the correct pair scores only 0.80.8 against a wrong score of 0.60.6. Training would push the diagonal up and the off-diagonal down until the correct pair dominates.

Example
Zero-shot classification of one image (illustrative numbers)

These scores are illustrative, not measured. Suppose the image has cosine similarity 0.280.28 with the prompt "a photo of a dog" and 0.250.25 with "a photo of a cat". Use scale β=100\beta = 100.

  1. Scale the scores: 100×0.28=28100 \times 0.28 = 28 and 100×0.25=25100 \times 0.25 = 25.
  2. The difference is 33. With two classes, the softmax reduces to a sigmoid of the difference.
  3. P(dog∣x)=11+e−3=11+0.0498≈0.953P(\text{dog} \mid x) = \dfrac{1}{1 + e^{-3}} = \dfrac{1}{1 + 0.0498} \approx 0.953.
  4. The model says "dog" with about 95 percent probability, even though the two raw scores differ by only 0.030.03.

The large scale β\beta is what turns small cosine differences into confident probabilities. It is also why a model can look very sure about a wrong answer when two prompts are close.

−6−4−2024600.20.40.60.81logit gapprobability
  • P(dog) as the logit gap varies
The two-class softmax is a sigmoid of the score gap. The marked point is the dog example, where the gap is 3.
Example
Feeding an image to a language model

Take a ViT-style encoder that cuts a 224×224224 \times 224 image into 16×1616 \times 16 patches. That gives 14×14=19614 \times 14 = 196 patch vectors. A small projection maps each one into the language model's embedding size, which gives 196 visual tokens.

  1. The user sends a prompt of 30 text tokens, such as "What is wrong with this wiring?"
  2. The language model's input becomes 196+30=226196 + 30 = 226 tokens.
  3. The model's attention runs over all 226 positions. The image tokens are treated like any other tokens in the context.
  4. Each generated answer token is predicted from the 226 inputs plus the answer tokens so far.

The cost of the image is therefore a fixed block of extra context. A larger image or finer patches add more tokens and make every later step more expensive. Many designs reduce the visual token count with a learned query module, such as the Q-Former in BLIP-2, so the language model sees fewer image tokens.

Tradeoffs and failure modes

SituationProblemBetter choice
You need fast search over millions of imagesRunning a generative VLM on every pair is too slowA shared-space model, where image vectors are computed once and indexed
You need an answer about one imageA shared-space model returns a score, not a sentenceA generative VLM that conditions a language model on image tokens
Your labels are a closed, well-defined setZero-shot prompts may underperform a trained classifierA supervised classifier, or a few-shot fine-tune of a VLM
Fine detail matters, such as small text or countsPatch grids can blur small objects, and the encoder may drop detailsHigher input resolution, or more visual tokens
Prompt wording changes the answerZero-shot scores are sensitive to the exact promptAverage several prompt templates per class
The image is out of the training distributionThe model may match a plausible but wrong caption confidentlyCheck on a labelled sample from your own data before trusting it

Failure modes to expect in practice: hallucinated objects (the text describes something not in the image), attribute mix-ups (a red car and a blue bike swap colours), and weak spatial reasoning (left and right, or counting above a few items). A VLM also inherits the biases of its image-text training data. Web captions are noisy, so a model trained on them can learn loose associations.

History

Joint image-and-text models existed before 2020, but most were trained on small, carefully labelled datasets. Transformers changed the picture in two ways. The text side moved to large language models trained on web-scale text, and the image side moved to vision transformers in 2020, which let the same architecture handle both.

In 2021 OpenAI's CLIP paper trained an image encoder and a text encoder together on 400 million image-text pairs gathered from the internet, using the contrastive objective above. The paper's abstract reports that the zero-shot model matches the accuracy of a fully supervised ResNet-50 on ImageNet, without using any of ImageNet's 1.28 million training images. CLIP made the shared-space design the default for image-text retrieval and zero-shot classification.

From 2022 onward, the generative design gained ground. Flamingo (Alayrac et al., 2022) and BLIP-2 showed that a frozen vision encoder and a frozen language model could be joined by a small trainable bridge. LLaVA (2023) extended this to instruction following: it used a simple projection layer and a dataset of image-based conversations, and showed that a capable chat model could come from modest extra training.

Check yourself

QuestionRecall: what does the shared-space design compare, and how is the comparison scored?Show answer

It compares an image embedding with a text embedding. Both are normalised to unit length, and the score is their cosine similarity, the dot product of the unit vectors. Matching image-text pairs should get high scores and mismatched pairs low scores.

QuestionComputation: an image has cosine similarity 0.300.30 with the prompt for class A and 0.200.20 with the prompt for class B. With scale β=100\beta = 100, what is P(A∣x)P(A \mid x) to three decimal places?Show answer

Scale the scores to 3030 and 2020. The gap is 1010, so P(A∣x)=1/(1+e−10)≈1/(1+0.0000454)≈0.99995P(A \mid x) = 1/(1 + e^{-10}) \approx 1/(1 + 0.0000454) \approx 0.99995, which rounds to 1.0001.000 to three decimals. The point of the answer is that a gap of 0.100.10 in cosine similarity, once scaled, gives almost certainty. The scale hides how close the two scores are.

QuestionWhy does the contrastive loss in the batch example use the other captions as negatives, and what happens if the batch contains two near-identical photos of the same dog?Show answer

Each image in the batch has one correct caption. The other captions in the batch serve as wrong answers, so the softmax denominator has one positive and N−1N-1 negatives. If two images are near-duplicates with different captions, the model is asked to separate two things that look almost the same. This pushes the loss up and can make training noisy. Large batches make the chance of a true near-duplicate pair higher, which is one reason data cleaning matters for this objective.

QuestionApplied: you are building a photo search feature for a catalogue of 10 million product images, where users type short queries. Which design do you choose and why?Show answer

Choose a shared-space model. Encode every image once, store the vectors in an approximate nearest-neighbour index, and encode each query at search time. A query then costs one text encoding and one vector search, not one forward pass of a generative model per image. A generative VLM would be far too slow for this scale, since it would have to read every image for every query.

QuestionApplied: a chat assistant gets a photo of a chart and must answer a question about its trend. Why is the shared-space design a poor fit for this task?Show answer

A shared-space model outputs a similarity score between an image and a text. It cannot produce an open-ended answer such as "sales fell in the third quarter". The task needs a model that reads the image tokens and generates text token by token, which is the generative design.

Sources