From text to image
How does the model understand what you ask for in words?
Lesson complete
If you like:
You type “an astronaut cat” and, in seconds, a program hands you an image nobody drew. How does it turn a sentence into an image?
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain how CLIP trains an image encoder and a text encoder together so each image lands close to its sentence, by reading the similarity table and its diagonal.
- Describe how the sentence’s vector conditions diffusion, and predict what happens to faithfulness and variety as the guidance scale goes up.
- Recognize the limits of these models (amplified biases, never-seen combinations, what goes with what, counting and writing) and the risks around rights, impersonation, and provenance.
Key ideas
- CLIP trains an image encoder and a text encoder together. Both output vectors of the same size, compared with cosine similarity.
- Training is contrastive: in each batch, the similarity table must light up its diagonal (the correct pairs) and dim the rest. No hand labels are needed, just images with their sentences.
- To generate from text, the diffusion network gets an extra input: the sentence’s vector. That is conditioning. The prompt is that sentence, and the model only understands the words it saw during training.
- Classifier-free guidance predicts the noise with and without the sentence and exaggerates the difference by the guidance scale: more scale, more faithfulness and less variety; too much distorts.
- Models inherit and amplify the biases in their data, do worse on the never-seen, can mix up what goes with what, and struggle to count and write. Their data raises questions about rights, and their images about impersonation and provenance.
What many people believe
Common belief An image generator understands the sentence the way a person does: if the words are written correctly, it draws exactly what you asked for.
What is true It turns the sentence into a vector learned from image-and-text pairs, and diffusion is guided by that vector. Whatever was missing from its data (words, combinations, quantities, letters) it handles poorly, and whatever was frequent in its data it repeats too much.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
CLIP’s contrastive loss
In a batch of pairs, the image encoder and the text encoder produce unit vectors and . Their cosine similarity is . These are divided by a temperature (also learned), and cross-entropy asks each image to pick its own sentence and each sentence to pick its own image:
This is the symmetric loss from Radford and colleagues’ paper (Figure 3): it raises the diagonal of the table and lowers the rest of its row and column. CLIP used batches of 32,768 pairs, that is, tables of more than a billion cells at every step, and about 400 million image-and-text pairs gathered from publicly available sources on the internet. The model card is dated January 2021.
In our toy, the image encoder receives 720 numbers (12 × 12 pixels, each with 5 one-hot color slots) and has a hidden layer of 96; the text encoder reads 5 word positions, each word with a 16-number vector plus a vector for its position, and has a hidden layer of 64. Both output . It trained for 2,500 steps with batches of 96; the temperature went from to . In the fixed six-pair batch the scene shows, the diagonal ends between 0.78 and 0.88. The batch error does not reach zero with batches of 96: many incomplete sentences (“circle”) repeat within the same batch and cannot tell their images apart.
Conditioning and guiding
The diffusion network predicts the noise of a 16-number latent , at step , given the sentence vector . During training, the sentence is replaced with the empty sentence 10% of the time (as in Stable Diffusion v1-4). When sampling, with guidance scale :
With the sentence does not count; with it is the plain conditional network; with it is exaggerated. This is the convention of the diffusers library (default scale 7.5, “enabled when greater than 1”). Ho and Salimans write the same thing as , with , and present it as a trade-off between sample quality and diversity. GLIDE (Nichol and colleagues, 2021) already used it with text, and human evaluators preferred it to CLIP guidance.
Our sampler follows the lesson 17 recipe: steps, linear from 0.02 to 0.30, and reverse-step variance . The latent comes from a 16-number VAE and is decoded at the end. Stable Diffusion conditions differently (cross-attention over the per-word vectors from CLIP’s text encoder); here, to fit in the browser, the sentence vector is appended to the input of a three-layer network.
What the scene measured
- Guidance scale with “circle” (256 starting noises): circles 36% at , 80% at , 95% at , 93% at , and 63% at . The scene’s twenty-four images (seeds 1000 to 1023, prompt “circle”) give 11, 20, 23, and 13 circles at , and 18, 11, 6, and 8 distinct combinations of shape, color, and background (with the Spanish prompt «círculo»: 11, 19, 21, and 16 circles; 18, 12, 7, and 7 combinations).
- Bias: in the data, 64.9% of circles are magenta (one image in two gets its shape’s typical color, the other a random one). Among the twenty-four images, 15 are magenta at and 22 at .
- The never-seen (ten combinations left out of training, 16 noises per combination, ): 86.4% correct on the 70 seen combinations and 75.6% on the 10 never-seen ones. At the gap is wider: 85.6% versus 45.6%.
- What goes with what (60 pairs with swapped colors, in both languages): the encoder that reads word order picks the right sentence 100% of the time; the bag of words gives exactly the same vector to both sentences (0%: always a tie).
The shape and color counts come from a fixed-rule reader, not a learned one: the background is the most common color along the border, the shape is the rest, and the shape type is the template (circle, square, triangle, or cross, at several positions and sizes) that overlaps best; if none exceeds 0.6 intersection over union, the image counts as “no shape.” It reads all 20 real images in the lesson correctly. It is less reliable with squares: the model often draws them with rounded corners and the reader takes them for circles, so the scene does not use them for counting.
In code
import numpy as np
def contrastive_loss(U, V, tau=0.07):
"""U, V: unit vectors of N images and N sentences (row i = pair i)."""
S = U @ V.T / tau
S = S - S.max(axis=1, keepdims=True)
rows = -np.mean(np.diag(S) - np.log(np.exp(S).sum(axis=1)))
S2 = (U @ V.T / tau).T
S2 = S2 - S2.max(axis=1, keepdims=True)
cols = -np.mean(np.diag(S2) - np.log(np.exp(S2).sum(axis=1)))
return (rows + cols) / 2
rng = np.random.default_rng(0)
U = rng.normal(size=(4, 8)); U /= np.linalg.norm(U, axis=1, keepdims=True)
V_random = rng.normal(size=(4, 8)); V_random /= np.linalg.norm(V_random, axis=1, keepdims=True)
V_good = U + 0.1 * rng.normal(size=(4, 8)); V_good /= np.linalg.norm(V_good, axis=1, keepdims=True)
print(round(contrastive_loss(U, V_random), 3), round(contrastive_loss(U, V_good), 6))
def guidance(e_without, e_with, s):
return e_without + s * (e_with - e_without)
e_without, e_with = np.array([0.2, -0.4]), np.array([0.5, 0.1])
for s in (0, 1, 3):
print(s, guidance(e_without, e_with, s))
# 6.064 0.000141
# 0 [ 0.2 -0.4]
# 1 [0.5 0.1]
# 3 [1.1 1.1]
With random sentences the error is high; with sentences almost identical to their image, the diagonal dominates and the error falls to nearly zero. The second function is the whole guidance scale.
What comes next
Here text only went in: it was turned into a vector. In lesson 19 text comes out: a language model assigns probabilities to the next word and writes one word after another.
Decision lens
What this idea means if your job is to decide, not to code.
- Provenance and rights: ask what data the model was trained on, under what licenses, and what the vendor covers if there is a claim. The U.S. Copyright Office reported in 2025 dozens of pending lawsuits over using works for training; the legal answer is not settled yet.
- Impersonation: have your policy forbid generating images of real people without their consent, review what gets published, and never accept an image alone as proof. Mark what you publish: C2PA content credentials and, if the vendor offers it, a watermark.
- Bias: the model repeats, and with guidance exaggerates, whatever is frequent in its data. Audit with many images per prompt (not one), especially when people appear, and check who is shown and how.
- Control and reproducibility: keep the prompt, seed, and guidance scale of every image you use. More guidance is not always better: it reduces variety and, pushed too far, distorts.
Terms in this lesson
- CLIP An OpenAI method (2021) that trains an image encoder and a text encoder together so each image and its description land close together in one shared vector space. It was trained on about 400 million image-and-text pairs taken from the internet.
- Contrastive learning Training by comparing correct pairs with wrong ones: pulling together in vector space what belongs together and pushing the rest apart, without hand-written labels.
- Prompt The text used to ask a generative model for something; in an image generator, the description of the desired image.
- Conditioning Giving a generative model an extra input (a label or a sentence’s vector) that steers what it produces. Image generators are conditioned on the prompt’s vector.
- Embedding A vector of numbers, learned from data, that represents something (a word, a sentence, an image) so that similar things end up close. Each word has a row in an embedding table.
- Cosine similarity The cosine of the angle between two vectors: 1 if they point the same way, 0 if they are perpendicular, −1 if they oppose. It ignores length and measures direction only.
- Vector space A space whose points are vectors. In an embedding space, the distance or angle between two points measures how alike their meanings are.
- Vector An ordered list of numbers. In machine learning, each example reaches the model as a vector.
- Pixel The smallest dot of a digital image. In grayscale it is a number from 0 (black) to 255 (white); in color it is three numbers (red, green, and blue).
- Training data Examples, each with its correct answer, from which a model adjusts its parameters.
- Batch A small set of examples, picked at random, used to estimate the gradient in one training step.
- Loss function A single number that summarizes how wrong a model is on its data. Training is the search for the parameters that make it as small as possible.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Generative model A model that learns the distribution of its data (what is common, what is rare) and can therefore produce new, similar data. A model that classifies, by contrast, only learns the boundary between groups.
- Latent space The space of a model’s codes (“latent” means hidden): each data point is a point, and nearby points tend to be similar data. Any point can be decoded.
- Variational autoencoder (VAE) An autoencoder that sums up each data point as a cloud (center and size) instead of a point, and penalizes clouds that stray from a standard zone. That way the latent space has no holes and you can sample from it.
- Diffusion model A generative model that learns to undo a fixed process that mixes data with noise step by step (the forward process). It generates by starting from pure static and removing a little estimated noise, many times.
- Denoising The task of the network in a diffusion model: it takes a noisy image and the step number, and estimates the noise so it can be subtracted.
- Latent diffusion Doing diffusion in the code space of an autoencoder, much smaller than the image, and decoding at the end. It is cheaper; that is how Stable Diffusion works.
- Classifier-free guidance When generating, the noise estimate is computed with the hint (a label or a text) and without it, and their difference is exaggerated by the guidance scale: more fidelity to the hint, less variety.
Full transcript
Sources
- Radford, A., Kim, J. W., Hallacy, C., Ramesh, A., Goh, G., Agarwal, S., Sastry, G., Askell, A., Mishkin, P., Clark, J., Krueger, G., Sutskever, I. (2021). Learning Transferable Visual Models From Natural Language Supervision (CLIP)
- OpenAI (2021). CLIP model card (Model Date: January 2021)
- Ho, J., Salimans, T. (2022). Classifier-Free Diffusion Guidance
- Nichol, A., Dhariwal, P., Ramesh, A., Shyam, P., Mishkin, P., McGrew, B., Sutskever, I., Chen, M. (2021). GLIDE: Towards Photorealistic Image Generation and Editing with Text-Guided Diffusion Models
- Ramesh, A., Dhariwal, P., Nichol, A., Chu, C., Chen, M. (2022). Hierarchical Text-Conditional Image Generation with CLIP Latents (DALL·E 2), §7 Limitations and Risks
- Rombach, R., Blattmann, A., Lorenz, D., Esser, P., Ommer, B. (2022). High-Resolution Image Synthesis with Latent Diffusion Models
- CompVis (2022). Stable Diffusion v1-4 model card (CLIP ViT-L/14 text encoder; 10 % text-conditioning dropout)
- Hugging Face (2026). Diffusers: StableDiffusionPipeline (guidance_scale, default 7.5)
- Bianchi, F., Kalluri, P., Durmus, E., Ladhak, F., Cheng, M., Nozza, D., Hashimoto, T., Jurafsky, D., Zou, J., Caliskan, A. (2023). Easily Accessible Text-to-Image Generation Amplifies Demographic Stereotypes at Large Scale (FAccT 2023)
- U.S. Copyright Office (2025). Copyright and Artificial Intelligence, Part 3: Generative AI Training (pre-publication version)
- U.S. Copyright Office (2024). Copyright and Artificial Intelligence, Part 1: Digital Replicas
- Coalition for Content Provenance and Authenticity (C2PA) (2025). C2PA and Content Credentials Explainer (version 2.2)
- Google DeepMind (2023). SynthID: watermarking AI-generated content
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub