TAI BUI
Back to curriculum
BuildPython

Transfusion: Autoregressive Text + Diffusion Image in One Transformer

Chameleon and Emu3 bet on discrete tokens. It works, but the quantization bottleneck shows: image quality plateaus below continuous-space diffusion models. Transfusion (Meta, Zhou et al., August 2024) takes the opposite bet. Keep images continuous, drop the VQ-VAE, and train one transformer with two losses. Text tokens get next-token prediction, image patches get a flow-matching diffusion loss, and both objectives update the same weights. The architecture behind Stable Diffusion 3 (MMDiT) is a close cousin. This lesson walks through the Transfusion thesis, builds a toy two-loss trainer, and traces the attention mask that lets one transformer do both jobs.

TIME: ~180 minutesPREREQUISITES: Phase 12 · 11 (Chameleon), Phase 8 (Generative AI)

Learning Objectives

  • Wire a transformer that runs two losses (NTP on text tokens, diffusion MSE on image patches) on one backbone.
  • Explain why bidirectional attention across image patches plus causal attention over text tokens is the right mask choice.
  • Compare Transfusion-style (continuous images, diffusion loss) to Chameleon-style (discrete images, NTP) on compute, quality, and code complexity.
  • Name MMDiT's contribution: modality-specific weights at each block, joint attention at the residual stream.

The Problem

The debate over discrete versus continuous image representations is older than LLMs. Continuous representations (raw pixels, VAE latents) preserve detail. Discrete tokens (VQ indices) fit the transformer's native vocabulary but lose detail at the quantization step.

Chameleon and Emu3 went discrete. You get one loss and one architecture, but image fidelity is capped by the tokenizer.

Diffusion models went continuous. Image quality is excellent, but the model is separate from the LLM, the noise schedule takes real engineering, and there is no clean way to fold in text generation.

Transfusion asks whether you can have both: keep images continuous, still train one model, and combine two losses in one gradient step.

Warm-up0/3
1. How does Chameleon turn an image into something a transformer can train on with next-token prediction?Warm-up
A sentence shown as six word chips, and a 4 by 4 grayscale image with an arrow to a dashed box asking what the image becomes so the model can train on it.
Typed schematic. The sentence and the 4x4 image are illustrative.
2. In a standard diffusion model (Phase 8), what is the basic training setup?Warm-up
Three clean 4 by 4 grayscale images in a row and a network box on the right, with a dashed box asking what the network is trained on.
Typed schematic. The images are illustrative 4x4 grayscale grids.
3. Why does a decoder-only language model use a causal attention mask when it trains on next-token prediction?Warm-up
A six-word sentence as an input row and a one-step-shifted target row, with position 2 (sat, target on) highlighted.
Typed schematic. The sentence is illustrative.
Check: The Problem0/2
1. What problem with pure diffusion models does Transfusion address?Explain
Three 4 by 4 snapshots labelled t = 1, 0.5 and 0 that go from pure noise to a clean blob image.
Typed schematic. The 4x4 image and the noise draw are illustrative.
2. Why is image fidelity in a Chameleon-style model capped?Explain
A pipeline of image, tokenizer, transformer with next-token loss and decoder, with a dashed box asking what image comes out and a small 4 by 4 input image.
Typed schematic. Box names follow the lesson's Problem section.

The Concept

The two-loss architecture

A single decoder-only transformer processes a sequence that contains:

  • Text tokens (discrete, from a BPE vocab).
  • Image patches (continuous, 16x16 pixel blocks projected into the hidden dim with a linear embedding, the same input layer a ViT uses).
  • <image> and </image> tags marking where the continuous patches live.

The forward pass runs once. Each token then gets one of two heads:

  • Text tokens get standard cross-entropy on the vocab-logits head.
  • Image patches get a diffusion loss on the continuous patches: predict the noise that was added to each patch.

Gradients flow through the shared transformer body, so both losses improve the same weights at the same time.

Attention mask: causal text + bidirectional image

Text has to stay causal. If a text token can see future text, teacher forcing breaks. An image is different. Its patches are one snapshot, so within the same image block they should attend to each other in both directions.

The mask:

M[i, j] = 1 if:
  (i is text and j is text and j <= i)   # causal for text
  OR (i is image and j is image and same_image_block(i, j))   # bidirectional within image
  OR (i is text and j is image and j < i_image_end)   # text attends to previous images
  OR (i is image and j is text and j < i_image_start)   # image attends to preceding text

You build it as a block-triangular mask, and the same mask is used at training and at inference.

Diffusion loss inside the transformer

The diffusion loss is the standard one. Add noise to an image patch and ask the model to undo it, either by predicting the noise or the clean patch (the two are equivalent). Transfusion's version uses flow matching, where the model predicts the velocity field from noisy to clean.

During training:

  1. For each image patch x0, sample a random timestep t.
  2. Sample noise ε, compute xt = (1-t) * x0 + t * ε (linear interpolation for flow matching).
  3. The transformer predicts v_theta(xt, t); loss = MSE(v_theta(xt, t), ε - x0).
  4. Backprop alongside the text NTP losses from the same sequence.

At inference, text tokens come from standard autoregressive sampling. Image patches come from a diffusion sampling loop (10-30 steps typical), conditioned on the text tokens before them.

MMDiT: Stable Diffusion 3's variant

Stable Diffusion 3 (Esser et al., March 2024) shipped MMDiT (Multimodal Diffusion Transformer) around the same time as Transfusion, and the two architectures are siblings.

MMDiT differs in three ways:

  • Modality-specific weights per block. Each transformer block has separate Q, K, V, and MLP weights for text tokens and image patches. Attention is joint across modalities, and everything else is modality-specific.
  • Rectified flow training. This is a specific flow-matching variant with known sampling and simpler math than DDPM.
  • Scale. MMDiT is the backbone for SD3 (2B and 8B param variants), while the Transfusion paper scales to 7B.

Both land on the same core idea: one transformer runs NTP on text and diffusion on continuous image representations.

Why this beats Chameleon-style

The quality gap between continuous diffusion and discrete NTP for image generation is measurable. The Transfusion paper reports:

  • At 7B params, it beats a same-size Chameleon-style model on FID by 3-5 points.
  • No tokenizer training. The image encoder is a linear projection to the hidden dim, same as a ViT's input layer.
  • Inference can denoise image patches in parallel, which autoregressive image tokens can't do.

The downside is that Transfusion is a dual-loss model, so training dynamics are trickier. Loss weights need tuning, and a schedule mismatch between NTP and diffusion can let one head dominate.

What sits downstream

Janus-Pro (Lesson 12.15) refines Transfusion by decoupling the vision encoder for understanding from the one for generation (SigLIP for one, VQ for the other) while sharing the transformer body. Show-o (Lesson 12.14) swaps diffusion for discrete diffusion (masked prediction). The unified-generation family branches quickly after Transfusion.

Production VLMs that emit images in 2026 (Gemini 3 Pro, GPT-5, Claude Opus 4.7's image generation path) almost certainly use some descendant of this family, but the details are proprietary.

Check: The Concept0/24
1. What is two-loss training in a Transfusion-style model?Define
A sequence of three text tokens and four patches between image tags feeds one decoder-only transformer, with a dashed box asking what the training step optimizes.
Typed schematic with illustrative values, not captured.
2. What is flow matching, as Transfusion uses it for images?Define
Three 4 by 4 grayscale snapshots labelled t = 0, 0.5 and 1 that go from a clean blob image to noise, with a dashed box asking what the network outputs at each point.
Typed schematic. Values are computed for an illustrative 4x4 image and a fixed noise draw.
3. What is MMDiT?Define
A three-word prompt and a noisy 4 by 4 patch grid feed a box named MMDiT, which outputs a cleaner patch grid.
Typed schematic with illustrative values, not captured.
4. What is a block-triangular mask?Define
A blank 9 by 9 grid whose rows and columns are the tokens T0, T1, image-open tag, P0 to P3, image-close tag and T2, with the four-by-four patch region outlined.
Typed schematic. Cells are left blank.
5. What is a continuous image representation?Define
A 4 by 4 grayscale image with its top-left 2 by 2 patch outlined and an arrow to a dashed box asking what the transformer receives for this patch.
Typed schematic. The image is illustrative.
6. What does Transfusion's flow-matching loss train the model to predict?Define
Three 4 by 4 grids (a clean patch, a noise draw and the noisy patch at t = 0.6) with the noisy patch going into a network, and a dashed box asking what the prediction is.
Typed schematic. The 4x4 grids and t = 0.6 are illustrative.
7. In Transfusion's attention mask, how do patches inside one image block attend to each other?Explain
A sequence strip T0, T1, P0 to P3, T2 with the four patches outlined as one image block, above a blank 4 by 4 grid of patch queries against patch keys.
Typed schematic. Cells are left blank.
8. Besides causal text and bidirectional image blocks, what else does the mask allow?Explain
A 7 by 7 mask grid for T0, T1, P0 to P3 and T2 where only the text-to-earlier-text cells and the 4 by 4 patch block are filled; every other cell is dashed.
Typed schematic. Filled cells are the two rules the stem names; dashed cells are the open question.
9. Why must text tokens keep a causal mask in Transfusion?Explain
A caption of four text tokens followed by an image-open tag, four patches and an image-close tag, with a legend naming blue chips text tokens and orange chips image patches.
Typed schematic with illustrative values, not captured.
10. Why do the text loss and the image loss both improve the same model even though they use different heads?Explain
A shared transformer body above a text head and an image head, each feeding its own loss, with a dashed box asking how both reach the same weights.
Typed schematic.
11. What inference advantage does diffusion sampling give Transfusion over autoregressive image tokens?Explain
Two rows with the same three-word prompt: one followed by four dashed question-mark slots for autoregressive image tokens, one followed by four small noisy patch tiles for diffusion sampling.
Typed schematic. Same prompt, four image positions to produce.
12. Which part of an MMDiT block is joint across modalities, with everything else modality-specific?Explain
A vertical flow for one MMDiT block: seven input token boxes (three text, four image patch), then three stages named Q, K, V projections, attention and MLP, then tokens out.
Typed schematic. Stage names follow the lesson's Concept section.
13. At 7B parameters, how does Transfusion compare to a same-size Chameleon-style model?Explain
Two cards, Chameleon-style and Transfusion-style, both labelled 7B parameters and each showing FID with a question mark, plus a line saying FID is an image-quality score.
Typed schematic. Both models are the lesson's 7B comparison.
14. How does Transfusion generate output at inference time?Explain
A prompt box reading a red cat goes into a Transfusion box with outputs for text and an image, and a dashed box asks how each part is produced and in what order.
Typed schematic. The prompt is illustrative.
15. What does the Concept say distinguishes MMDiT's training and scale from Transfusion's?Explain
Two cards for Transfusion and MMDiT with their paper citations; Transfusion shows question marks for training and largest model, MMDiT shows question marks for training and model sizes.
Typed schematic from the lesson's Further Reading and Concept section.
16. How does Janus-Pro build on Transfusion's idea?Explain
Transfusion's inputs (text tokens and image patches) feeding one shared body and then output heads for text and image, with a dashed box asking what Janus-Pro changes.
Typed schematic.
17. What does Show-o change relative to Transfusion?Explain
Transfusion's image part drawn as continuous patches scored by a flow-matching loss, with a dashed box asking what Show-o's image part looks like.
Typed schematic.
18. A patch has x0 = 1.0 and sampled noise epsilon = 3.0, with t = 0.25. Using the lesson's flow-matching recipe, what are xt and the MSE target?Apply
Three input cards, x0 equal 1.0, epsilon equal 3.0 and t equal 0.25, feed a dashed box for xt, then a network box and a dashed box for the MSE target.
Typed schematic. The values are the stem's.
19. You train a Transfusion-style model. Text loss drops fast but image samples stay noisy. What is the most likely cause?Analyze
A falling text-loss curve next to two noisy 4 by 4 sample images labelled generated image samples that stay noisy.
Typed schematic. The curve and samples are illustrative, not measured.
20. A team lets text tokens attend bidirectionally, like image patches. Text training loss becomes very low, but generated text is useless. What explains this?Analyze
A 4 by 4 attention grid over the tokens a, red, cat, sat with every cell filled with a 1, and notes that text training loss is very low and generated text is useless.
Typed schematic. The caption tokens are illustrative.
21. Someone describes Transfusion as generating images autoregressively, patch by patch. What is wrong with that description?Analyze
A quoted claim that Transfusion generates images autoregressively patch by patch, above prompt tokens a red cat, an image-open tag, four noisy patch tiles p0 to p3 and an image-close tag.
Typed schematic. The prompt is illustrative.
22. A team compares a Chameleon-style model with a Transfusion-style one for image output. Which comparison is accurate?Analyze
Two rows with the same prompt a red cat: the Chameleon-style row and the Transfusion-style row each followed by four dashed image-position chips, and a dashed box asking which comparison is accurate.
Typed schematic with illustrative values, not captured.
23. You want a model that reads text and generates continuous audio frames, with NTP on text and a diffusion loss on audio. Which design fits the lesson's ideas?Design
Three text tokens followed by six continuous audio frames drawn as bars, with a next-token loss over the text and a diffusion loss over the audio, and a dashed box asking about the mask and logging.
Typed schematic. Frame heights are illustrative.
24. You need a single model that writes text and generates high-fidelity images, and you cannot afford to train and maintain an image tokenizer. Which design fits?Design
Two requirement cards, one model that writes text and one that generates high-fidelity images, and a red-bordered constraint box saying there is no budget for an image tokenizer, ending with design question mark.
Typed schematic. The requirements are the stem's.

Use It

code/main.py is a toy Transfusion on a tiny synthetic problem:

  • Each caption is a four-integer sequence that encodes a class from 0 to 6.
  • Each image is a 4x4 grid of floats whose shade depends on the class.
  • The "transformer" is a stand-in. A weight dict with two scale counters fakes the model's output, so the numbers it prints come from the loss plumbing, not from a trained network.
  • Each step computes a text loss and a flow-matching MSE loss on a noised image, then sums them with separate weights.
  • The block-triangular attention mask is built explicitly for a sequence with one image block and printed.

The transformer is fake. The two-loss plumbing and the mask construction are the real artifacts. The code has no generation loop, so the inference procedure above is something to read, not run.

Check: Use It0/6
1. In the main.py demo, the tokens are [10, 11, image-open tag, p0, p1, p2, p3, image-close tag, 12, 13]. Which positions does row 2, the opening tag, attend to?Apply
A blank 10 by 10 attention grid for the demo sequence 10, 11, image-open tag, p0 to p3, image-close tag, 12, 13, with row 2 outlined and a legend for text, tag and patch tokens.
Typed schematic. Cells are left blank; row 2 is outlined.
2. In the same demo mask, row 8 belongs to the text token 12 after the image. Which positions does it attend to?Apply
A blank 10 by 10 attention grid for the demo sequence 10, 11, image-open tag, p0 to p3, image-close tag, 12, 13, with row 8 outlined and a legend for text, tag and patch tokens.
Typed schematic. Cells are left blank; row 8 is outlined.
3. make_dataset draws cls = 3. What are that pair's caption and the first row of its image?Apply
Two panels for class 3: four dashed question-mark boxes for the caption and a 4 by 4 dashed grid for the image with its first row outlined.
Typed schematic. Row 0 of the image is outlined in orange.
4. In train(), the text loss uses probability 0.3 + 0.05 * text_scale for every caption token. At step 2, text_scale is 2. Roughly what text loss is printed?Apply
Lines of main.py that compute text_probs and the cross-entropy, above a strip of steps 0, 1 and 2 with text_scale 0, 1 and 2 and a note that text_scale increases by one after each step.
Lines from main.py, reflowed to fit; the clamp inside cross_entropy_toy is left out. The step strip is typed from the stem.
5. With the weights in train() (text_w 1.0, img_w 0.1), one step has text_loss 1.2 and img_loss 4.0. What is total?Apply
A line from main.py setting text_w to 1.0 and img_w to 0.1, a text_loss box reading 1.2, an img_loss box reading 4.0, and a dashed box asking for total.
Dict from main.py, reflowed over two lines. The two loss values are the stem's.
6. The toy run prints a text loss and an image loss that both fall over 10 steps. Why is that no evidence the model is learning?Analyze
Two small line charts from the captured run of main.py, text_loss and img_loss at steps 0, 2, 4, 6 and 8, both falling; no axis values are shown.
Captured from main.py: each panel is scaled to its own maximum, no axis values are shown.

Ship It

This lesson produces outputs/skill-two-loss-trainer-designer.md. Give it a new multimodal training task (text + image, text + audio, text + video) and it designs the two-loss schedule (loss weights, mask shape, shared vs modality-specific blocks) and flags implementation risks.

Author's Note

I'd run main.py and read the mask it prints before touching anything else. That is the one piece of the file that does real work. Check the rows for the <image> and </image> positions: the code treats those two tags as neither text nor image, so they attend to earlier text but not to themselves. Decide whether that is what you want before you answer the mask exercise.

I'd also be skeptical of the loss numbers. The text loss falls because a counter nudges the fake probabilities upward each step, and the image loss falls because a second counter pulls the predicted velocity toward the target. Nothing is learning. What the printout does show is how the two losses combine, with the text weight at 1.0 and the image weight at 0.1, both hardcoded.

My bet is that those two weights are where a real run would hurt. The body says loss weights need tuning and that one head can dominate, and here the ratio is a constant I picked by hand with no feedback from either loss. If you swap in a real model, I'd log the two losses separately from step one so you can see which head is driving the gradient.

Exercises

  1. A Transfusion-style model trains 70% text tokens and 30% image patches. The image diffusion loss is ~10x the text NTP loss in magnitude. What loss weights balance them?

  2. Implement the block-triangular mask for a sequence: [T, T, <image>, P, P, P, P, </image>, T]. Mark each entry 0 or 1.

  3. MMDiT has modality-specific QKV weights. What parameter count overhead does this add vs Transfusion's fully-shared transformer? At 7B params, is it worth it?

  4. Generation: given a text prompt, the model runs NTP for 50 tokens, then hits <image>, then runs diffusion on 256 patches over 20 denoise steps. How many forward passes total?

  5. Read SD3 paper Section 3. Describe rectified flow and why it converges in fewer inference steps than DDPM.

Key Terms

TermWhat people sayWhat it actually means
Two-loss training"NTP + diffusion"A single transformer optimizes both cross-entropy on text tokens and MSE on continuous image patches in the same gradient step
Flow matching"Rectified flow"Diffusion variant that predicts a velocity field from noise to clean data; simpler math than DDPM
MMDiT"Multimodal DiT"Stable Diffusion 3's architecture: joint attention, modality-specific MLPs and norms
Block-triangular mask"Causal text + bidirectional image"Attention mask that is causal across text but bidirectional within image regions
Continuous image representation"No VQ"Image patches as real-valued vectors, not integer codebook indices
Velocity prediction"v-parameterization"Network output is the velocity field between noise and data, not the noise itself

Further Reading

Code

Ships With