Multimodal Models

Updated · 8 min read
hardPython 3.13aimultimodalclipvision-language-modelsimage-to-text

A multimodal model works with more than one kind of data, or modality, such as text, images, audio and video. Text-to-image models turn words into pictures; image-to-text models describe or answer questions about pictures; and today's leading assistants accept photos, documents, audio and text in one conversation. The key idea is to put different kinds of data into a shared space of embeddings, so a model can relate a photo to the words that describe it.

"Foundation Models and Multimodal AI" introduced the idea. This lesson runs two real multimodal models.

Kinds of Multimodal Models

KindDescription
Contrastive models (CLIP)It is used to embed images and text in the same space, so matching pairs land close together
Text-to-imageIt is used to generate an image from a prompt; diffusion models use a text encoder such as CLIP's
Vision-language models (VLMs)It is used to answer questions about images: an image encoder feeds a language model
Speech and audio modelsTurn speech into text and back; see "Speech Recognition and Speech Synthesis"
Natively multimodal assistantsRead and sometimes produce text, images and audio in one model

Example: Matching a Photo to Captions with CLIP

CLIP, from OpenAI, was trained on hundreds of millions of image and caption pairs from the web to place each image near its own caption and far from the others. This program compares the golden retriever photo from "Computer Vision" (dog.jpg) with five captions.

The programs in this chapter need pip install torch transformers diffusers scikit-learn scipy pillow. The first run of each pretrained model downloads it from Hugging Face; download and loading messages are left out of the output shown.

Images and text in one space: matching, describing and answering
Python
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
 
# CLIP: one model that puts images and text in the same embedding space (from OpenAI)
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32", use_safetensors=True)
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
 
photo = Image.open("dog.jpg")                       # the golden retriever from "Computer Vision"
captions = ["a photo of a dog", "a photo of a cat", "a photo of a school bus",
            "a photo of a golden retriever in the grass", "a lunch menu"]
inputs = processor(text=captions, images=photo, return_tensors="pt", padding=True)
with torch.no_grad():
    out = model(**inputs)
 
print("Image embedding:", tuple(out.image_embeds.shape), "| text embeddings:", tuple(out.text_embeds.shape))
probs = out.logits_per_image.softmax(dim=1)[0]      # similarity of the image to each caption
for caption, p in sorted(zip(captions, probs.tolist()), key=lambda cp: -cp[1]):
    print(f"{p:6.1%}  {caption}")
Output
Image embedding: (1, 512) | text embeddings: (5, 512)
 92.8%  a photo of a golden retriever in the grass
  7.2%  a photo of a dog
  0.0%  a photo of a cat
  0.0%  a photo of a school bus
  0.0%  a lunch menu

Explanation:

  • The image and every caption become 512-number embeddings in the same space, like the text embeddings in "What Are Embeddings".
  • logits_per_image measures how close the image is to each caption; softmax turns that into shares that add up to 100%.
  • "A photo of a golden retriever in the grass" wins with 92.8%, ahead of the more general "a photo of a dog" (7.2%). The cat, the bus and the menu get 0.0%.
  • No training was needed to sort the photo into these made-up categories. This is zero-shot classification: write the categories as captions and pick the closest. The same embeddings power image search and help text-to-image models follow prompts.

Example: Asking Questions About Images

A vision-language model joins an image encoder to a language model, so you can talk about a picture. This program uses SmolVLM-256M-Instruct, a small open VLM from the same family as SmolLM2. It asks two questions about the dog and two about a lunch menu notice from "Transfer Learning" (notices/new/menu.jpg).

Python
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor
 
# SmolVLM-256M-Instruct: a small vision-language model from Hugging Face (Apache 2.0)
name = "HuggingFaceTB/SmolVLM-256M-Instruct"
processor = AutoProcessor.from_pretrained(name, do_image_splitting=False)   # one 512x512 view: much faster
model = AutoModelForImageTextToText.from_pretrained(name)
print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
 
def ask(image_file, question):
    messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}]
    prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
    inputs = processor(text=prompt, images=[Image.open(image_file).convert("RGB")], return_tensors="pt")
    with torch.no_grad():
        out = model.generate(**inputs, max_new_tokens=60, do_sample=False)
    answer = processor.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
    print(f"\n[{image_file.split('/')[-1]}] {question}\n  {answer}")
 
ask("dog.jpg", "Describe this image in one sentence.")
ask("dog.jpg", "What color is the collar?")
ask("notices/new/menu.jpg", "What kind of document is this?")    # from "Transfer Learning"
ask("notices/new/menu.jpg", "What is the price of the first item?")
Output
Parameters: 256,484,928
 
[dog.jpg] Describe this image in one sentence.
  In this image we can see a dog and in the background there are some plants.
 
[dog.jpg] What color is the collar?
  The collar is black.
 
[menu.jpg] What kind of document is this?
  Lunch Menu.
 
[menu.jpg] What is the price of the first item?
  12.50.

Explanation:

  • The image goes into the chat as a message part ({"type": "image"}), next to the text question. The processor turns the photo into image tokens the language model reads like words.
  • The dog answers are right: a dog with plants behind it, and a black collar.
  • "Lunch Menu" is right too; the model can read the large title on the notice.
  • "12.50" is invented. The photo is only 224 × 224 pixels, so each price is a few pixels tall and unreadable, and every price on that menu is between $2.00 and $6.75. Instead of saying it can't read them, the model guessed.
  • do_image_splitting=False keeps the image as one 512 × 512 view. With splitting on, the model looks at several close-up tiles, which can help with small text but took about 15 times longer on this laptop.

Where Multimodal Models Are Used

UseExample
AccessibilityDescribing photos for people who are blind or have low vision
Document understandingReading forms, receipts and charts, with checking
SearchFinding photos by describing them in words
AssistantsAsking about a photo of a homework problem or a broken appliance
Content moderationFlagging harmful images at scale, with human review

Common Mistakes

Trusting small text read from a photo. Check against the source, or use a larger, sharper image.

Assuming the model sees the image as you do. It sees a downscaled version split into patches; fine details may be lost.

Forgetting privacy. Photos can contain faces, addresses and documents; see "Privacy: What Not to Share with AI".

Using CLIP scores as probabilities of truth. They only rank the captions you gave; a photo of a cat with only dog captions still picks one.

Interview Corner

How does CLIP work?

It trains an image encoder and a text encoder together so that each image's embedding is close to its own caption's embedding and far from other captions. That shared space allows zero-shot classification, image search and guiding image generation.

How does a vision-language model answer questions about an image?

An image encoder turns the image into a sequence of embeddings that are fed to a language model alongside the text tokens, and the language model generates the answer. It is trained on image-text pairs and question-answer examples.

Practice

Exercise: your own captions. Change CLIP's captions to five that are all about dogs: "a puppy", "a sleeping dog", "a dog in the snow", "a dog playing fetch", "a dog's face up close". Which wins, and do the shares make sense for this photo?

Check your understanding:

  1. Why can CLIP sort the photo into categories it was never trained on?
  2. Why did the vision-language model get the price wrong but the title right?
  3. What would make the price question more reliable?

Quick check: multimodal models

4 questions
1Which caption did CLIP rank highest for the dog photo?
2What did SmolVLM say the first price was?
3What is zero-shot classification with CLIP?
4What does a vision-language model add to a language model?

Key Takeaways

Quick reference

NeedCode
CLIPCLIPModel.from_pretrained("openai/clip-vit-base-patch32", use_safetensors=True)
Match image and captionsmodel(**processor(text=captions, images=photo, return_tensors="pt", padding=True)).logits_per_image.softmax(dim=1)
A vision-language modelAutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM-256M-Instruct")
Image in a chat message{"type": "image"} next to {"type": "text", "text": question}

Was this tutorial helpful?

Lesson 156 of 186