AS·173
Multimodal AI
Models that see, hear and watch, and how to engineer with them: images as tensors and patches, vision Transformers and image-token arithmetic, image embeddings (CLIP, SigLIP) for search and zero-shot classification, OCR and document understanding from classic pipelines to vision-language models, classification, object detection (boxes, IoU, non-maximum suppression implemented) and segmentation (semantic, instance, promptable), how vision-language models are built and prompted, audio as waveforms and spectrograms (an STFT from scratch), speech-to-text (Whisper-style models, word error rate implemented), text-to-speech, streaming voice pipelines and latency budgets, speech-to-speech models, audio embeddings, video through frame sampling and scene detection, temporal understanding and multimodal context budgets, evaluation, privacy and safety, with code across Python, TypeScript, Java, Go and Rust.
Start here: models that see and hear
A multimodal model takes more than text: images, audio, video, documents. The trick that makes it work is the same everywhere: turn each kind of input into a sequence of vectors that a Transformer can read alongside text tokens.
Images become tokens
A vision encoder cuts an image into square patches (often 14 or 16 pixels across) and turns each into one vector, an "image token". The arithmetic matters because tokens cost time and money:
| Image size | Patch size | Image tokens |
|---|---|---|
| 224 × 224 | 14 | 256 |
| 336 × 336 | 14 | 576 |
| 448 × 448 | 14 | 1,024 |
| 1,024 × 1,024 | 16 | 4,096 |
Higher resolution sees more detail (small print, a crack in a weld) but costs quadratically more tokens; many systems resize images or tile large ones.
Audio is similar: a speech encoder such as Whisper's turns 30 seconds of audio into 1,500 vectors. Video multiplies image tokens by frames: one frame per second for a minute at 256 tokens per frame is 15,360 tokens, which is why video models sample frames sparingly.
Teaching images and words to meet
CLIP-style models learn a shared space for images and text: train an image encoder and a text encoder together so a picture and its caption land close together, and mismatched pairs far apart (the contrastive training of chapter 159). Then you can classify an image by asking which caption it's nearest to, search photos with words, or feed image vectors into a language model.
The lab trained a tiny one from scratch on 8 × 8 handwritten digits and captions like "a handwritten seven". It labelled 97–99% of unseen digits correctly by nearest caption, including with a caption wording it had never seen in training; at half the resolution, accuracy fell to about 93%.
How deep to go in multimodal AI
Volume 17 defines six mastery levels; for multimodal AI they look like this:
| Level | You can… |
|---|---|
| L1 | explain how images, audio and video become tokens |
| L2 | build features with vision, speech-to-text and text-to-speech APIs |
| L3 | explain vision encoders, contrastive alignment, connectors and audio models |
| L4 | debug resolution, OCR, transcription, latency and cost problems |
| L5 | design multimodal products with evaluation, privacy and accessibility in mind |
| L6 | run multimodal pipelines at scale with cost controls and safety review |
Multimodality in one picture
Modern multimodal systems convert every modality into sequences of vectors a Transformer can process (chapter 154): image patches, audio frames, video frames, text tokens. Either the model is trained natively on several modalities, or a modality encoder (vision or audio) is connected to a language model through a projector.
Vision
Images as tensors and patches
An RGB image is a tensor [3, H, W] of pixel intensities (usually normalised per channel). CNNs (chapter 153) process it with sliding kernels; Vision Transformers (ViT) split it into fixed-size patches (e.g. 16×16 or 14×14 pixels), flatten and linearly embed each patch, add position embeddings, and run a Transformer over the patch sequence.
A 224×224 image with 16×16 patches gives (224/16)² = 196 patches. A 1024×1024 image would give 4,096 patches: images are expensive in tokens. Vision-language models therefore resize or tile images, merge neighbouring patches (e.g. 2×2 pooling after the encoder), or use dynamic resolution; providers document how image size maps to token count and cost. Practical rule: send the smallest image that preserves the needed detail (crop to the region of interest; downscale photos; keep text-heavy documents at readable resolution).
def patch_tokens(width, height, patch=14, merge=2, max_side=1568):
"""Approximate visual-token count for a ViT-style encoder with patch merging (illustrative)."""
scale = min(1.0, max_side / max(width, height))
w, h = int(width * scale), int(height * scale)
return (w // (patch * merge)) * (h // (patch * merge))
for size in [(224, 224), (1024, 768), (4032, 3024)]: # thumbnail, screenshot, phone photo
print(size, patch_tokens(*size))
# 64 · 972 · 2,352 (the photo is downscaled first); tokens grow with area, so crop to what matters
Image embeddings
CLIP (2021) and successors (SigLIP, EVA-CLIP and others) train an image encoder and a text encoder contrastively on image–caption pairs (chapter 159's InfoNCE), so matching images and texts land close in one space. Uses:
- Text-to-image and image-to-image search (product catalogues, photo libraries, deduplication).
- Zero-shot classification: embed "a photo of a {label}" for each label; pick the label most similar to the image. No training data needed; accuracy improves with prompt templates and ensembles.
- Image features for downstream classifiers (linear probes) and as the vision encoder inside VLMs.
- Content moderation and clustering of image collections.
OCR and document understanding
| Approach | How | Strengths / limits |
|---|---|---|
| Classic OCR (Tesseract, cloud OCR APIs, PaddleOCR) | Text detection → recognition → reading order | Fast, cheap, exact characters with bounding boxes; struggles with complex layouts, handwriting, tables |
| Layout-aware document AI | OCR + layout models detecting blocks, tables, key-value pairs (cloud document AI services, Docling, LayoutLM-style models) | Structured extraction from forms, invoices, scientific papers |
| OCR-free VLMs | Vision-language model reads the page image directly; can output Markdown/JSON | Handles messy layouts, charts, handwriting, reasoning about content; may hallucinate characters; costlier |
| Hybrid | OCR text + page image given to a VLM; validate extracted values against OCR text | Best accuracy and verifiability for business documents |
For extraction pipelines, combine a VLM with structured outputs (chapter 167) and grounding checks: every extracted value should appear in the OCR text or be traceable to a region.
Classification, detection and segmentation
| Task | Output | Typical models |
|---|---|---|
| Classification | One or more labels per image | Fine-tuned CNN/ViT, CLIP zero-shot, VLM prompting |
| Object detection | Bounding boxes + labels + confidence | YOLO family, DETR/RT-DETR; open-vocabulary detectors (Grounding DINO, OWL-ViT) find objects described in text |
| Semantic segmentation | A class per pixel | U-Net, SegFormer, Mask2Former |
| Instance segmentation | A mask per object | Mask R-CNN, YOLO-seg |
| Promptable segmentation | Mask for an object indicated by a point, box or text | Segment Anything (SAM, SAM 2 for video) |
| Keypoints / pose, depth, tracking | Body joints, per-pixel depth, object identities over frames | Specialised models |
Detection quality is measured with IoU (intersection over union of predicted and true boxes) and mean average precision (mAP) at IoU thresholds. Detectors output many overlapping candidate boxes; non-maximum suppression (NMS) keeps the highest-confidence box and removes others that overlap it above an IoU threshold.
import numpy as np
def iou(a, b):
"""Boxes as [x1, y1, x2, y2]."""
x1, y1 = max(a[0], b[0]), max(a[1], b[1]); x2, y2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0, x2 - x1) * max(0, y2 - y1)
area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
return inter / (area(a) + area(b) - inter)
def nms(boxes, scores, iou_threshold=0.5):
order = list(np.argsort(scores)[::-1]); keep = []
while order:
best = order.pop(0); keep.append(best)
order = [i for i in order if iou(boxes[best], boxes[i]) < iou_threshold]
return keep
boxes = [[10, 10, 110, 110], [15, 12, 112, 108], [200, 50, 260, 120], [205, 55, 262, 118], [12, 8, 105, 115]]
scores = [0.92, 0.85, 0.77, 0.80, 0.60]
round(iou(boxes[0], boxes[1]), 3), nms(boxes, scores) # two objects survive: indices 0 and 3
Vision-language models
VLMs (most frontier models and many open ones such as Qwen-VL, Gemma, Llama vision variants, Pixtral, InternVL) answer questions about images, read documents and charts, compare images, describe screenshots, and drive computer-use agents that operate GUIs from screenshots.
Prompting tips:
- Put the image before the question; refer to images explicitly when there are several ("in the second image…").
- Ask for structured output and for evidence (quote the text you read; give coordinates if supported).
- Crop and zoom for small text or details; split long documents into pages.
- Verify counting, small text, spatial relations and chart values: classic VLM weaknesses that improve yearly but still fail.
Audio
Waveforms and spectrograms
Audio is a 1-D signal sampled at a rate (speech often 16 kHz; music 44.1/48 kHz). Most speech models work on log-mel spectrograms: short overlapping windows (≈25 ms, 10 ms hop) → short-time Fourier transform (STFT) → power at each frequency → mapped to the mel scale (spaced like human pitch perception) → log. The result is an image-like [mel bins × time frames] array that Transformers process as a sequence of frames.
def stft_magnitude(signal, n_fft=400, hop=160):
"""Short-time Fourier transform magnitude: frames × frequency bins (16 kHz: 25 ms window, 10 ms hop)."""
window = np.hanning(n_fft)
frames = [signal[i:i + n_fft] * window for i in range(0, len(signal) - n_fft, hop)]
return np.abs(np.fft.rfft(np.array(frames), axis=1))
sr = 16_000; t = np.arange(sr) / sr # 1 second
signal = np.sin(2 * np.pi * 440 * t) * (t < 0.5) + np.sin(2 * np.pi * 1000 * t) * (t >= 0.5) # A4 then 1 kHz
S = stft_magnitude(signal)
freqs = np.fft.rfftfreq(400, 1 / sr)
S.shape, freqs[S[10].argmax()], freqs[S[80].argmax()] # ~98 frames; 440 Hz early, 1000 Hz later
Speech-to-text
Automatic speech recognition (ASR): audio → text. Whisper (OpenAI, 2022; open weights) popularised robust multilingual encoder-decoder ASR trained on large weakly labelled data; many successors and alternatives exist (open models such as distilled Whisper variants, NVIDIA Parakeet/Canary, and commercial streaming APIs).
Engineering concerns:
- Streaming vs batch: streaming ASR emits partial hypotheses with low latency for voice agents; batch transcription is more accurate for recordings.
- Voice activity detection (VAD) and endpointing: detecting when the user has finished speaking is critical for conversational latency.
- Diarisation: who spoke when (meetings, call centres).
- Word-level timestamps, punctuation, custom vocabulary (product names), language identification.
- Hallucination on silence or noise (generating plausible text from nothing): trim silence, use VAD, check confidence.
Word error rate (WER) = (substitutions + deletions + insertions) / reference words, computed with edit distance over words:
def wer(reference, hypothesis):
r, h = reference.lower().split(), hypothesis.lower().split()
d = np.zeros((len(r) + 1, len(h) + 1), dtype=int)
d[:, 0] = range(len(r) + 1); d[0, :] = range(len(h) + 1)
for i in range(1, len(r) + 1):
for j in range(1, len(h) + 1):
d[i, j] = min(d[i - 1, j] + 1, d[i, j - 1] + 1, d[i - 1, j - 1] + (r[i - 1] != h[j - 1]))
return d[len(r), len(h)] / len(r)
wer("please transfer five thousand rupees to anita", "please transfer five thousand rupee to a nita") # 3 errors / 7 words ≈ 0.43
Normalise text (case, punctuation, numbers: "5,000" vs "five thousand") before computing WER, and measure per accent, language, noise condition and domain vocabulary.
Text-to-speech
TTS turns text into natural speech: neural models generate spectrograms or audio-codec tokens, then a vocoder/decoder produces waveforms. Modern systems offer many voices, emotion/style control, multilingual speech, and low-latency streaming (first audio in a few hundred milliseconds). Voice cloning from short samples raises consent, impersonation and fraud risks: require consent for custom voices, watermark generated audio where possible, and follow provider policies and local law.
Voice pipelines and speech-to-speech
Voice-agent essentials: stream every stage; begin TTS on the first sentence of the LLM's reply; support barge-in (user interrupts → stop audio, cancel generation); keep replies short and speakable (no Markdown, spell out numbers appropriately); handle telephony audio (8 kHz, noise); confirm critical details back to the user (amounts, dates) because ASR errors are inevitable. Transport: WebRTC for browsers/apps, SIP/telephony gateways for phone calls, WebSockets for server-to-server streams.
Audio embeddings
Audio encoders (CLAP for audio–text, speaker-embedding models, wav2vec 2.0 / HuBERT-style self-supervised encoders) map clips to vectors for sound search, classification (alarms, machinery faults), speaker verification (with liveness checks against spoofing), music similarity and deduplication.
Video
Video multiplies cost: 30 frames per second × hundreds of visual tokens per frame. Understanding video is mostly about choosing what to look at.
- Frame sampling: uniform sampling (e.g. 1 frame per second, or N frames per clip) is the baseline; scene-change detection picks frames when content changes; keyframes from the codec are cheap to extract; event-driven sampling uses motion or audio cues.
- Temporal understanding: ordering, actions, cause and effect, counting events, tracking objects across frames. VLMs with native video input and timestamps handle this better than independent frame captions, but long videos still need chunking: summarise segments, index them, and retrieve relevant segments for questions (video RAG).
- Multimodal context: combine sampled frames with the audio transcript (often the richest signal in talks, meetings and tutorials), on-screen text (OCR) and metadata. Align by timestamps so answers can cite "at 12:40".
def scene_change_frames(frames, threshold=0.25, min_gap=5):
"""Pick frames whose colour histogram differs strongly from the last kept frame."""
def hist(f): h = np.histogram(f, bins=32, range=(0, 255))[0].astype(float); return h / h.sum()
keep, last = [0], hist(frames[0])
for i in range(1, len(frames)):
h = hist(frames[i])
if 0.5 * np.abs(h - last).sum() > threshold and i - keep[-1] >= min_gap: # total-variation distance
keep.append(i); last = h
return keep
rng = np.random.default_rng(0)
scenes = [rng.integers(lo, lo + 60, size=(48, 64)) for lo in (10, 120, 190)] # three visually distinct scenes
video = [scenes[min(i // 40, 2)] + rng.integers(0, 5, size=(48, 64)) for i in range(120)]
scene_change_frames(video) # ≈ [0, 40, 80]: one representative frame per scene
Budget arithmetic: a 60-minute video at 1 frame/second ≈ 3,600 frames; at ~250 tokens per frame that's ~900k tokens before audio. Sampling at scene changes plus a transcript often reduces this by an order of magnitude with little loss for most questions.
Evaluation, privacy and safety
- Evaluate per modality and condition: document types and scan quality, lighting and camera angles, accents and noise levels, languages; field-level accuracy for extraction, WER for ASR, mAP/IoU for detection, human ratings for TTS naturalness (MOS) and intelligibility.
- Hallucination checks: VLM reading errors (digits, names), ASR inventing words in silence, captions describing things not present.
- Privacy: images, voices and videos contain faces, licence plates, screens, background conversations and biometric identifiers. Minimise retention, blur/redact where appropriate, obtain consent, follow biometric and data-protection laws.
- Safety: moderation of uploaded images and generated media; prompt injection inside images (text in a screenshot or document telling the model what to do) is real: treat image text as untrusted data (chapter 176); deepfake and voice-cloning abuse (chapter 174).
- Accessibility: multimodal models power alt text, captions, audio description and voice interfaces; evaluate with the people who rely on them.
Across stacks
# Python: Hugging Face pipelines for local models; provider SDKs accept images/audio in messages
from transformers import pipeline
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small")
print(asr("call.wav", return_timestamps=True)["text"])
clf = pipeline("zero-shot-image-classification", model="google/siglip-base-patch16-224")
print(clf("photo.jpg", candidate_labels=["invoice", "receipt", "id card", "screenshot"]))
det = pipeline("object-detection", model="PekingU/rtdetr_r50vd")
print(det("street.jpg")[:3])
// TypeScript: send an image to a VLM (provider SDK message with an image content block)
const msg = await client.messages.create({
model: "claude-sonnet-5-5", max_tokens: 500,
messages: [{ role: "user", content: [
{ type: "image", source: { type: "base64", media_type: "image/png", data: pngBase64 } },
{ type: "text", text: "Extract the invoice number, date and total as JSON." },
]}],
});
// Java: Spring AI multimodal user message (image + text); DJL/ONNX Runtime for local vision models
var media = new Media(MimeTypeUtils.IMAGE_PNG, new ClassPathResource("invoice.png"));
String json = chatClient.prompt()
.user(u -> u.text("Extract the invoice number, date and total as JSON.").media(media))
.call().content();
// Go: ffmpeg for frame/audio extraction, then send frames or audio to a model API
cmd := exec.CommandContext(ctx, "ffmpeg", "-i", "talk.mp4",
"-vf", "select='gt(scene,0.3)',scale=768:-1", "-vsync", "vfr", "frames/%04d.jpg", // scene-change frames
"-map", "0:a", "-ac", "1", "-ar", "16000", "audio.wav") // 16 kHz mono for ASR
if err := cmd.Run(); err != nil { return err }
// Rust: candle ships Whisper, CLIP, SAM and other examples; whisper-rs binds whisper.cpp
let ctx = WhisperContext::new_with_params("ggml-small.bin", WhisperContextParameters::default())?;
let mut state = ctx.create_state()?;
state.full(FullParams::new(SamplingStrategy::Greedy { best_of: 1 }), &pcm_f32_16khz)?;
for i in 0..state.full_n_segments()? { println!("{}", state.full_get_segment_text(i)?); }
Lab: a tiny CLIP and the arithmetic of modalities
Setup. PyTorch on 2 CPU threads; scikit-learn's 1,797 handwritten digits (8 × 8 greyscale), 1,400 for training and 397 held out. Scope: a toy version of CLIP's training method on a toy dataset. It shows the mechanism (two encoders, one shared space, classification by nearest caption); it can't show the open-vocabulary generalisation that comes from training on hundreds of millions of image–caption pairs.
The model
- Image encoder: split the image into patches, project each patch to 64 numbers, add learned position vectors, one Transformer layer, average, project to 32 dimensions.
- Text encoder: average word embeddings of the caption, project to 32 dimensions.
- Training: batches of 64 images with random captions from five templates ("a handwritten seven", "the digit seven", "a photo of the number seven", "a scan showing seven", "seven written by hand"); symmetric contrastive loss with a learned temperature, and soft targets because several images in a batch share a digit. 1,500 steps, 7–12 s.
- Test: embed each held-out image and the ten captions for one template; the predicted digit is the nearest caption. The template "an image of a …" was never used in training.
Experiment 1: image tokens and detail
| Input | Patch | Image tokens | Accuracy, "a handwritten …" | Accuracy, unseen template "an image of a …" |
|---|---|---|---|---|
| 8 × 8 | 2 × 2 | 16 | 0.975 | 0.967 |
| 8 × 8 | 4 × 4 | 4 | 0.987 | 0.975 |
| 4 × 4 (downsampled) | 2 × 2 | 4 | 0.937 | 0.919 |
| 4 × 4 | 4 × 4 | 1 | 0.937 | 0.929 |
- Classifying by nearest caption worked well, and nearly as well with a caption wording the model had never seen, because the shared words ("seven") carry the meaning in this tiny text encoder.
- Resolution mattered more than token count: four tokens from the full 8 × 8 image beat four tokens from a 4 × 4 image by about 5 points. Throwing away pixels loses information no encoder can recover; grouping pixels into bigger patches lets the encoder learn what to keep. Real systems face the same trade-off with documents and screenshots, where small text disappears at low resolution.
- On a dataset this easy, 16 small patches didn't beat 4 larger ones; more tokens pay off when there's more detail to see.
Experiment 2: token budgets for real inputs
| Input | Arithmetic | Tokens |
|---|---|---|
| 224 × 224 image, 14-px patches | (224/14)² | 256 |
| 336 × 336 | 24² | 576 |
| 448 × 448 | 32² | 1,024 |
| 1,024 × 1,024, 16-px patches | 64² | 4,096 |
| 30 s of speech, Whisper-style encoder (100 frames/s, downsampled 2×) | 30 × 50 | 1,500 |
| 60 s of video, 1 frame/s, 256 tokens per frame | 60 × 256 | 15,360 |
Many products compress further (pooling patches, adaptive resolution, tiling with a thumbnail) and providers bill images by their own formulas, so check yours, but the scaling (quadratic in image side, linear in duration) is universal and is what to budget for.
Try it yourself
- Add Gaussian noise to the test images and plot accuracy against noise level for 16- and 4-token encoders.
- Hold out the digit "seven" from training entirely. Can the model label sevens? Explain why not, and what web-scale captions change.
- Retrieve images from text: for each caption, rank the 397 test images and report recall@5.
- Estimate the monthly token cost of processing 10,000 screenshots a day at 1,024 × 1,024 versus 448 × 448 under your provider's pricing.
Revision sheet: multimodal AI
Key ideas
- Every modality becomes a sequence of vectors: image patches (ViT), audio frames (spectrogram encoders, neural codecs), video frames (sampled, compressed).
- Contrastive alignment (CLIP, SigLIP) learns shared image–text spaces for search and zero-shot classification.
- Vision-language models connect a vision encoder to an LLM with a projector or cross-attention; trained on captions, interleaved documents and instructions.
- Practical vision: OCR and document understanding, charts, screenshots, UI agents; resolution and tiling choices drive accuracy and cost.
- Audio: speech recognition (Whisper-style), speech synthesis, speech-to-speech with low latency; diarisation, timestamps, accents and noise.
- Video: frame sampling, temporal grounding, long-context cost.
- Evaluation per task (OCR accuracy, WER, grounding), bias across accents and skin tones, privacy (faces, voices, documents), and injection via text in images and audio.
Numbers to remember
- Patches = (side / patch)²: 224/14 → 256; 336/14 → 576; 448/14 → 1,024.
- 30 s speech → 1,500 encoder frames (Whisper-style).
- Lab: tiny CLIP 97–99% by nearest caption; ~93% at half resolution.
Pitfalls
- Downscaling documents until text is unreadable.
- Paying for maximum resolution when a thumbnail would do.
- Trusting text extracted from images as instructions.
- Evaluating speech only on clean, single-accent audio.
- Storing faces, voices or ID documents without consent and retention rules.
Glossary
- Patch embedding: projecting an image patch to a vector.
- CLIP / SigLIP: contrastive image–text models.
- VLM: vision-language model.
- WER: word error rate for speech recognition.
- Tiling: splitting a large image into crops processed separately.