- Compute cosine similarity between embeddings and explain why it is used for search by meaning.
- Explain how contrastive training gives CLIP a shared image–text space and enables zero-shot classification.
- Calculate how many patch tokens an image produces and how attention cost grows with resolution.
- Describe the forward noising process and noise-prediction objective of diffusion models, and work a one-pixel example.
- Explain how audio is turned into a spectrogram for speech models, and evaluate the main limits of multimodal systems.
Before this: How Large Language Models Work
Why this matters
Much of today's AI does far more than chat in text. It describes photos, transcribes meetings, speaks aloud, and generates images and video. The same few ideas sit underneath all of it, and knowing them helps you understand what these tools can do and where they go wrong.
Embeddings: meaning as coordinates
Start with the idea that ties everything together. An embedding is a list of numbers that represents the meaning of something, whether a word, a sentence, an image or a sound clip, as a point in space. Think of it as "meaning coordinates".
A toy example with only three dimensions:
| Item | Coordinates |
|---|---|
| "puppy" | (0.9, 0.8, 0.1) |
| "dog" | (0.8, 0.9, 0.1) |
| "invoice" | (0.1, 0.0, 0.9) |
"Puppy" and "dog" sit close together; "invoice" is far away. Real embeddings use hundreds or thousands of dimensions, and no single number has a neat human meaning, but the principle is the same: things with similar meaning land near each other. Embeddings power search by meaning (finding "car repair" when you typed "fixing my vehicle"), recommendations, and the links between text and images described below.
Image understanding
To a computer, a photo is a grid of numbers: each pixel has values for red, green and blue. A vision model learns, through the same training loop as any neural network, to turn that grid into useful patterns: edges in early layers, then textures, shapes, and finally objects and scenes.
Many modern vision models cut an image into small square patches and treat each patch much like a token, so the same transformer design used for text can process pictures.
A key step was learning to connect pictures and words. OpenAI's CLIP, released in 2021, was trained on about 400 million images paired with their captions. It learned to place a picture and a matching caption close together in a shared embedding space. That lets software ask "which of these descriptions fits this photo?" without being trained on a fixed list of categories.
Image generation: diffusion in plain words
Many of the best-known image generators use diffusion or close variants of it. The idea, simplified:
- During training, take real images and add random noise step by step until each becomes pure static.
- Train a network to undo one small step of that: given a noisy image, predict what it looked like slightly less noisy.
- To create a new image, start from pure random noise and apply the denoiser many times, guided by your text prompt (usually via a text embedding), until a clean picture emerges.
An analogy: a sculptor who has seen millions of statues, handed a rough block and told "a horse", chipping away a little at a time until a horse appears. Because each run starts from different random noise, the same prompt gives a different image each time.
Stable Diffusion, publicly released in August 2022, was an early widely used diffusion model whose weights anyone could download and run. Many newer generators use variations of the same approach.
Speech: listening and talking
Speech-to-text (automatic speech recognition) turns audio into words. Audio is converted into a picture-like representation of which sound frequencies occur over time, and a model maps that to text. OpenAI's Whisper, released as open source in September 2022, was trained on about 680,000 hours of audio paired with transcripts, which is part of why it copes well with accents and background noise.
Text-to-speech goes the other way: a model predicts the sound waves for a given text, now often with natural rhythm and emotion. Modern systems can imitate a specific voice from a short sample, which is useful for accessibility and also a real risk for fraud and impersonation.
Video
Video adds time. Video generators typically extend diffusion: they compress video into a smaller internal representation, cut it into small blocks that span both space and time, and denoise those blocks together so that motion stays consistent from frame to frame. OpenAI described this approach for its Sora model in February 2024, saying it could generate up to a minute of high-definition video.
Video understanding models do the reverse, sampling frames and describing or answering questions about them. Keeping objects, people and physics consistent over many seconds remains hard, and generated video can still show objects appearing, vanishing or moving impossibly.
Multimodal models
A modality is a type of data: text, image, audio or video. A multimodal model handles more than one. Early products chained separate models together, for example speech-to-text, then a language model, then text-to-speech. Each hand-off added delay and lost information such as tone of voice.
Newer models are trained to handle several modalities in one network. When OpenAI introduced GPT-4o in May 2024, it said a single model was trained end-to-end across text, images and audio, and reported average spoken response times of about 320 milliseconds, compared with several seconds for its earlier chained voice mode.
Limits to keep in mind
- Vision models can misread small text, count objects wrongly, or confidently describe things that aren't there.
- Speech recognition is less accurate for under-represented accents, languages and noisy recordings.
- Generated images and voices can look and sound real. Treat unexpected media, especially urgent requests "from" someone you know, with caution.
Going deeper
Measuring closeness: cosine similarity
"Close together" in an embedding space is usually measured by the angle between two vectors rather than the straight-line distance. Cosine similarity is
where is the dot product (multiply matching entries and add) and is the length of (the square root of the sum of its squared entries). The result runs from (opposite) through (unrelated) to (same direction).
Worked example with the toy table above:
- puppy dog . Both lengths are . Cosine .
- puppy invoice . The invoice length is . Cosine .
import numpy as np
emb = {
"puppy": np.array([0.9, 0.8, 0.1]),
"dog": np.array([0.8, 0.9, 0.1]),
"invoice": np.array([0.1, 0.0, 0.9]),
}
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
for a, b in [("puppy", "dog"), ("puppy", "invoice"), ("dog", "invoice")]:
print(f"{a:>6} vs {b:<8} {cosine(emb[a], emb[b]):.3f}")
The code prints 0.993, 0.165 and 0.155. Many systems normalise every embedding to length 1 when it is stored; the cosine is then just the dot product, which is fast to compute across millions of items.
How CLIP builds a shared space
CLIP uses two encoders: one turns an image into a vector, the other turns a caption into a vector, both normalised to length 1. Training takes a batch of matching image–caption pairs and builds an table of cosine similarities: row is image compared with every caption. The correct pairs sit on the diagonal. The loss is a softmax cross-entropy that pushes each diagonal entry up and every other entry in its row and column down. This style of training, which learns by pulling matching pairs together and pushing mismatched pairs apart, is called contrastive learning.
The payoff is zero-shot classification. To sort photos into "dog", "cat" or "invoice" without any training for those labels, embed a caption for each ("a photo of a dog", and so on), embed the photo, and pick the caption with the highest cosine similarity. Wording matters: the CLIP authors found that a caption template such as "a photo of a {label}" usually works better than the bare label, because captions in the training data are rarely a single word. Zero-shot accuracy therefore depends partly on writing labels the way real captions are written, and it should always be checked on a labelled sample before use.
Images as tokens
The Vision Transformer, introduced in a paper titled "An Image is Worth 16x16 Words", cuts an image into square patches and treats each patch as a token. A pixel image cut into patches gives patches. Each patch holds numbers (three colour channels), which a learned linear layer maps to an embedding.
This explains why image size matters for cost. Standard attention compares every token with every other, so the work grows with the square of the token count: pairs. Doubling the side to pixels quadruples the patches to and multiplies the pairs by 16, to . Assistants that accept images typically resize or tile them for this reason, and charge more tokens for larger images.
Diffusion, a little more formally
In the influential 2020 formulation called denoising diffusion probabilistic models (DDPM), the noising process has a convenient closed form. After steps, a clean image becomes
where is fresh random noise and is a number that falls from about 1 (almost clean) to about 0 (pure noise) as goes from 0 to the last step (the DDPM paper used ). A network is trained to look at , the step number and, for text-to-image, the prompt, and predict the noise:
Worked example for one pixel. Let and , so and . Draw . Then . If the network predicts the noise perfectly, the clean value can be recovered by rearranging: . Generation runs this in reverse from pure noise, removing a little predicted noise at each step; modern samplers need far fewer steps than the training schedule.
Audio as a picture
Speech models rarely read raw sound waves. The original Whisper models, for example, resample audio to 16,000 samples per second, convert it into an 80-channel log-Mel spectrogram, computed on 25-millisecond windows every 10 milliseconds, and process audio in 30-second chunks (a later version, large-v3, uses 128 Mel channels). A 30-second chunk is samples, but only spectrogram frames of 80 numbers each: a compact, image-like grid that a transformer can attend over.
Common pitfalls
- Mixing embedding models. Vectors from two different embedding models live in unrelated spaces. Comparing them, or searching an index built with one model using queries from another, gives meaningless scores.
- Forgetting to normalise. A raw dot product rewards long vectors as well as similar directions. Use cosine similarity or normalise first.
- Trusting numbers read from images. Vision models can misread digits, units and small print. Check any figure that matters against the source.
- Feeding huge images blindly. More pixels means more tokens and cost, and the model may downscale anyway. Crop to the region that matters.
- Assuming detectors can reliably spot generated media. Detection is an arms race; provenance records and verification through a second channel are more dependable.
- Ignoring licences. Check the licence and terms of the generator and of any model weights before using outputs commercially.
In practice
- Try giving an assistant a photo of a chart, a receipt or an error screen; it is often faster than typing a description, but check numbers it reads out.
- Use transcription for meetings and lectures, then skim for errors in names and technical terms.
- When generating images, iterate: vary the prompt and generate several options, since each run starts from new random noise.
- Agree a verification phrase with family or colleagues for urgent voice or video requests involving money.
Key takeaways
- Embeddings represent meaning as coordinates, so similar things land close together whether they are words, images or sounds.
- Vision models learn patterns from pixel grids, and models such as CLIP link images and text in a shared embedding space.
- Diffusion models generate images by starting from random noise and removing it step by step, guided by a prompt.
- Speech-to-text and text-to-speech models convert between audio and text, and voice cloning creates real fraud risks.
- Multimodal models handle several data types in one system, which is faster and keeps more information than chaining separate models.
Terms in this lesson
- Embedding
- A list of numbers that places an item, such as a word or image, in a space where similar meanings are close together.
- Modality
- A type of data, such as text, images, audio or video.
- Multimodal model
- A model that can take in or produce more than one modality.
- Diffusion model
- A generative model that creates images or video by gradually removing noise from random static, guided by a prompt.
- Speech-to-text
- Technology that converts spoken audio into written text, also called automatic speech recognition.
- Text-to-speech
- Technology that converts written text into spoken audio.
- Voice cloning
- Using a short audio sample to make a text-to-speech system imitate a particular person's voice.
- Cosine similarity
- A measure of how closely two vectors point in the same direction, equal to their dot product divided by the product of their lengths.
- Contrastive learning
- Training that pulls the embeddings of matching pairs together and pushes mismatched pairs apart.
- Spectrogram
- A grid showing how much energy an audio signal has at each frequency over time, used as the input to many speech models.
Check your understanding
- 1.
In an embedding space, what does it mean if two items have coordinates very close together?
- 2.
How does a diffusion model create a new image?
- 3.
What is a main advantage of one multimodal model over chaining speech-to-text, a language model and text-to-speech?
- 4.
A Vision Transformer cuts a 224 x 224 image into 16 x 16 patches. How many patch tokens does it produce?
- 5.
Why can CLIP classify images into categories it was never explicitly trained on?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
Compute the cosine similarity of and .
Show solution
Dot product: . Lengths: and . Cosine .
- Exercise 2Core
A vision model uses pixel patches on images. (a) How many patch tokens per image? (b) How many query–key pairs does one full attention layer compare? (c) Separately: Whisper-style processing turns each 30-second chunk into 3,000 frames. How many frames does a 10-minute recording produce?
Show solution
(a) per side, so tokens.
(b) pairs.
(c) 10 minutes = 600 s = 20 chunks of 30 s, so frames.
- Exercise 3Core
Coding. Write a toy zero-shot classifier: given normalised embeddings for three captions and one image, rank the captions by cosine similarity. Use caption vectors dog , cat , invoice and image , normalising each first.
Show solution
import numpy as np def normalise(v): v = np.asarray(v, dtype=float) return v / np.linalg.norm(v) # Toy embeddings standing in for a real image and text encoder. labels = { "a photo of a dog": normalise([0.9, 0.1, 0.2]), "a photo of a cat": normalise([0.2, 0.9, 0.1]), "a scanned invoice": normalise([0.1, 0.1, 0.95]), } image = normalise([0.7, 0.3, 0.2]) scores = {text: float(image @ emb) for text, emb in labels.items()} for text, s in sorted(scores.items(), key=lambda kv: -kv[1]): print(f"{s:.3f} {text}")Output: 0.959 for the dog caption, 0.589 for cat, 0.383 for invoice, so the image is classified as a dog. Because every vector is normalised, the dot product equals the cosine similarity. A real system would replace the toy vectors with outputs from a trained image encoder and text encoder of the same model.
- Exercise 4Challenge
One pixel has clean value . At step , and the sampled noise is . (a) Compute . (b) The network predicts . What estimate does that imply, and how large is the error? (c) Explain why the same noise-prediction error matters more at very noisy steps.
Show solution
(a) and , so .
(b) . The error is , versus a noise error of .
(c) In general . Here that factor is . At very noisy steps is close to 0, so the factor becomes large and small noise errors become large image errors. That is one reason samplers take many small steps instead of jumping straight from noise to a final image.
Further reading
- paperAlec Radford et al., Learning Transferable Visual Models From Natural Language Supervision (CLIP, 2021)
- paperAlexey Dosovitskiy et al., An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale (2020)
- paperJonathan Ho, Ajay Jain, Pieter Abbeel, Denoising Diffusion Probabilistic Models (2020)
- paperAlec Radford et al., Robust Speech Recognition via Large-Scale Weak Supervision (Whisper, 2022)
- bookAston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola, Dive into Deep Learning (2021–2023; free online book, arXiv 2106.11342)
Go further
Sources
- Learning Transferable Visual Models From Natural Language Supervision (Radford et al., 2021, CLIP paper)
- Stable Diffusion public release (Simon Willison, 22 August 2022)
- OpenAI Launches AI Transcription Tool Whisper (AI Business, September 2022)
- Video generation models as world simulators (OpenAI, 15 February 2024)
- Hello GPT-4o (OpenAI, 13 May 2024)
- Denoising Diffusion Probabilistic Models (Ho, Jain, Abbeel, arXiv 2006.11239)
- Robust Speech Recognition via Large-Scale Weak Supervision (Whisper paper, arXiv 2212.04356)
Fact-checked and last reviewed 2026-11-05