Families and objectives: decoder-only, encoders, encoder-decoder, multi-token prediction, diffusion LMs

One transformer stack, two dials: the attention mask and the training objective. Each mask and objective run here on the topic's tiny GPT and its TinyStories running example (Apple M1 Pro), published results kept apart. A child of Topic: llm-architecture. Data as of October 2026. Reading: 34 min, plus 14 in closed details.

The idea in one screen

Every model on this page is the same stack of transformer blocks with two dials set differently: the attention mask (which positions each position may read) and the objective (which tokens it is asked to predict, from what input). The mask decides what can be cached and whether the model can generate; the objective decides how much training signal each sequence gives. Multi-token prediction and diffusion attack the decoder's one-token-per-forward loop from opposite sides.

You need: the decoder block and its causal attention (The transformer from zero) and what a KV cache holds (Attention variants). Width, depth, the attention variant and mixture of experts are shared by every family; recurrent mixers (Beyond attention) have no bidirectional form. The root, Topic: llm-architecture, puts the three families in one table in its section 10; this page owns the masks, the objectives, MTP and diffusion LMs.

Causal, bidirectional mask
position i reads 0 to i; or every position reads every position.
Cross-attention
a decoder layer whose keys and values come from the encoder's output.
Prefix LM
a decoder whose prompt is read both ways and continuation causally.
MLM, span corruption
predict hidden tokens (BERT); predict hidden spans, each replaced by one sentinel (T5).
MTP
multi-token prediction: extra loss terms for tokens two or more places ahead.
Masked diffusion LM
a bidirectional model trained to unmask text at every masking rate, which then writes by unmasking many tokens per forward.

Running example: the topic's tiny GPT (6 layers, 256 wide, 5.8M parameters) trained on TinyStories, its reference checkpoint ref_baseline_s1500 (held-out loss 2.278), and the 256-token running sequence about Roxy the rhinoceros. Labels: measured on Apple M1 Pro here; vendor; independent; derived with the formula shown.

Fig. 1 · Six families, one block: the mask (top, rows are queries, columns keys) and what is scored (bottom)

may read (self-attention)reads the encoder (cross-attention)input hidden ([MASK] or sentinel)scored positionsecond target (MTP)

Eight positions per family, illustrative choices of which are hidden; the rates are the real ones (BERT 15%, T5 15% in spans of mean 3, LLaDA one random rate t per sequence).

The six families in one table (reference)
FamilyMaskObjectiveLoss terms per 256-token windowGenerates byUsed for, October 2026
Decoder-only (causal LM)causal: position i reads 0..inext token255 (every position)one token per forward, KV cachealmost every chat, code and reasoning model
Encoder (masked LM)bidirectional: every position reads every positionrecover masked tokens (BERT: 15%)about 38it does not, in practiceembeddings, retrieval, rerankers, classifiers (ModernBERT, Ettin)
Encoder-decoderbidirectional encoder; causal decoder that also reads the encoder (cross-attention)span corruption (T5) or input to outputtargets only (about a fifth of input length in T5)decoder, one token per forward; input encoded onceinput-heavy tasks: translation, summarisation, speech (Whisper), T5Gemma 2
Prefix LMbidirectional over the prompt, causal after itnext token on the continuationcontinuation onlylike a decodera training mode (UL2's S-denoiser, T5Gemma's PrefixLM), rarely a product
Decoder + MTPcausalnext token plus one or more further tokens255 + 254 per extra depthone token per forward, or 1 to 2 with the MTP draft verifiedDeepSeek-V3/V3.2, GLM-4.5, Qwen3-Next, MiMo, Gemma 4
Masked diffusion LMbidirectionalrecover tokens masked at a random rate t, weighted 1/ta random share t of positionsstart fully masked, unmask many tokens per forward in any orderfast generation: Mercury, Gemini Diffusion, DiffusionGemma; LLaDA in research

1. One block, four masks

Attention scores form a T by T matrix: row i is the query (the position asking), column j the key (the position read). The mask adds minus infinity to forbidden cells before the softmax, so their weight is exactly zero. Left unmasked, a model asked to predict token i+1 while it can see token i+1 learns to copy; the mask is how one architecture serves both understanding and writing. The first 12 tokens of the running sequence under each pattern, the marked query (a ball, an illustrative choice) fed by every key it may read:

Fig. 2 · Which keys each query may read, and what that lets you cache

  1. Causal (decoder-only). Query i reads keys 0 to i: 78 of the 144 cells stand. The marked query, " forest" at position 9, draws on the ten keys up to itself. Every position trains at once, and a past key never changes when a token arrives, so it is computed once and cached.
  2. Bidirectional (encoder). All 144 cells stand: query " a" at position 2 now reads the nine keys after it too. Each token gets both sides, but a new token changes every row, so there is nothing to cache and nothing to generate with.
  3. Prefix LM, prefix of 5. The first 5 tokens (the prompt, inside the dashed line) read each other both ways: 88 of 144 cells. Query " a" reads up to position 4; later tokens are causal but read the whole prompt. Only the continuation is scored.
  4. Encoder-decoder, as one fused matrix. Rows 0 to 5 are the encoder over the input, bidirectional. Rows 6 to 11 are the decoder: causal over its own tokens (blue) and reading every encoder token through cross-attention (purple), as " forest" does here. T5Gemma 2 fuses the decoder's two attentions into one mask of this shape.
  5. Same weights, swapped mask, measured. The reference tiny GPT, trained causally, under three masks at inference (first and last 128 positions of each window). Bidirectional: becomes overall. Prefix 128: the last 128 positions stay causal, yet rise from to . Seeing more makes a causal model worse.

The mask is free and decides the cache. Same FLOPs, same parameters. A causal model's past keys and values never change when a token arrives, so they are computed once and kept: the KV cache. Under a bidirectional mask every new token changes every earlier position's output, so an encoder or a diffusion LM recomputes the whole sequence every pass. An encoder-decoder's decoder caches its own causal KV plus the cross-attention keys and values of the encoder output, computed once per input; T5Gemma 2 fuses the decoder's self- and cross-attention into one attention with one mask.

A mask is a training-time contract. Step 5 is the test: we took the reference tiny GPT, trained causally, and changed only the mask at inference (src/lab/masks.py, the topic's 20 fixed held-out batches of 32 windows, 640 windows of 256 tokens; correction: the 2026-10-18 page said "20 windows", checked against the script). Predict before it plays: with a bidirectional mask the model can see the very token it must predict. Does its loss go down?

measured on Apple M1 Pro (CPU, 4 threads), 2026-10-18; the causal row reproduces the topic's reference 2.278 (measured there on MPS). The loss rises by nats: the model never learned to use the future, and the extra keys disturb representations learned under the causal contract. With a 128-token prefix even the causal suffix degrades, because it reads keys computed under a mask the model never saw. What transfers: the direction (a mask is learned, not a switch); the size of the gap does not.

The masks in code, the full table, and a 24-token explorer (depth)
  • Causal in transformers 5.20.1 is literally kv_idx <= q_idx (masking_utils.py line ); bidirectional_mask_function returns q_idx >= 0, always true (line ). ModernBERT sets self.is_causal = False (modeling_modernbert.py line ).
  • T5Gemma 2's fused mask: modeling_t5gemma2.py line , "Fused causal and encoder mask".
mask at inferenceheld-out lossfirst 128 positionslast 128 positionsrunning sequence
causal (as trained)
bidirectional
prefix LM, prefix 128

Click any token to make it the query: highlighted tokens are the keys it may read; the green underline marks the positions the family's objective scores (BERT's 15% sample for the bidirectional case); the slider moves the prefix or encoder boundary.

readable (self-attention)readable through cross-attentionscored by the objective (underline)

The code that ran. The topic's tiny GPT builds an additive mask in attn_bias (root src/data/tiny_gpt.py); this page swaps in a version with a mode switch without editing the shared file (src/lab/fo_common.py):

MASK = {"mode": "causal", "prefix": 0}

def attn_bias(cfg, layer_idx, q_pos, k_pos, device, slopes=None):
    diff = q_pos[:, None] - k_pos[None, :]
    if MASK["mode"] == "causal":
        keep = diff >= 0
    elif MASK["mode"] == "bidir":
        keep = torch.ones_like(diff, dtype=torch.bool)
    elif MASK["mode"] == "prefix":
        keep = (diff >= 0) | (k_pos[None, :] < MASK["prefix"])
    return torch.zeros(keep.shape, device=device).masked_fill(~keep, float("-inf"))[None]

def enable_masks():
    tiny_gpt.attn_bias = attn_bias
    tiny_gpt.is_local = lambda cfg, li: True   # forces the explicit softmax path (SDPA would apply is_causal)

Output of masks.py (scrubbed of timings), Apple M1 Pro, CPU, torch 2.14.1. The is_local override matters: the tiny GPT's fast path calls F.scaled_dot_product_attention(..., is_causal=True) and would ignore any custom mask.

Fig. 3 · One text, six objectives: what goes in, what is scored, what each scored token can see

model input
scored targets
[MASK] or sentinelscored targetsecond target (MTP)prefix, read both ways

Which positions are masked or corrupted is one seeded draw (illustrative positions); the rules are the real ones.

2. The objectives: what the model is asked to predict

An objective turns raw text into (input, target) pairs and a loss. The same 40 tokens of the running sequence under six of them; the top row is what the model reads, the bottom row what it is scored on:

  1. Causal LM. Input tokens 0 to 38; the target at each position is the next token: 39 loss terms from 40 tokens, each seeing only its left.
  2. Masked LM (BERT). 15% of 40 = 6 positions chosen; in this draw 5 became [MASK] and 1 stayed unchanged (green), none a random token (struck through when it happens). All 6 are scored, each from both sides.
  3. Span corruption (T5). round(0.15 x 40) = 6 corrupted tokens in 2 spans, each replaced by one sentinel (<X0> stands for <extra_id_0>): input 37 tokens, target 9 (the sentinels, the hidden tokens and a closing sentinel). The encoder reads the input both ways, the decoder writes the target.
  4. Prefix LM. The first 16 tokens are the prefix, read both ways and not scored (dashed); the 24 continuation targets are scored causally.
  5. CLM + MTP. Each position is scored twice: the main head on token i+1 (blue) and the MTP module on token i+2 (yellow), the module also given the real token i+1: 39 + 38 = 77 loss terms.
  6. Masked diffusion, t = 0.5. One rate for the whole sequence: 20 of 40 tokens masked in this draw, each scored and weighted by 1/t = 2. The next sequence draws a new t, from nearly clean to nearly all masked.
  • Causal LM (CLM). Target: the text shifted left by one; a 256-token window gives 255 loss terms (the topic's trainer reads 257 tokens and scores all 256). It won because every token of every document is a training example, any task can be written as a prompt, and the model generates with the same forward it was trained with; Pretraining runs it at scale. The costs: a strict left-to-right loop at inference and no right-hand context for the token being predicted.
  • Masked LM (MLM). BERT (BERT paper page) picks 15% of positions; of those, 80% become [MASK], 10% a random token, 10% stay unchanged, because [MASK] never appears at fine-tuning and a model that only sees [MASK] at scored positions learns nothing useful about real tokens there. transformers 5.20.1 keeps these defaults in DataCollatorForLanguageModeling: mlm_probability = 0.15, mask_replace_prob = 0.8, random_replace_prob = 0.1 (data/data_collator.py lines ). The cost is signal: about 38 loss terms per 256-token window against CLM's 255. ELECTRA (Clark et al. 2020, ICLR 2020) answered with replaced-token detection, where "the task is defined over all input tokens rather than just the small subset that was masked out"; ModernBERT raised the masking rate to 30%.
  • Span corruption (T5). Contiguous spans are replaced by one sentinel each (<extra_id_0>, ...); the target is each sentinel followed by the tokens it replaced. T5's default corrupts 15% in spans of mean length 3 (T5 paper page, whose Reading runs T5's own masking code on text you type). Per 512 input tokens the target is tokens ( corrupted, sentinels, one end token), so the decoder, the expensive autoregressive half, works on about a fifth of the text.
  • Prefix LM, MTP and masked diffusion have their own sections (6, 7, 8). Masked diffusion is MLM with the rate drawn at random between 0 and 1 per sequence and each term weighted by one over it: at rate 0.15 it is exactly BERT's objective, and the random rate is what makes it a generator.
Per 256-token window, every objective. Count is not quality: an MLM term sees both sides.
objectiveinput tokensloss termseach scored token seesgenerates?

derived: MLM 15% of 256; T5's lengths from its random_spans_helper arithmetic (round(0.15 L) noise tokens, round(noise / 3) spans, one sentinel per span, one end token); prefix LM with a 128 prefix; MTP one extra depth; diffusion at the mean rate 0.5.

Predict, then reveal: seven questions on the objectives (optional)
For one 256-token window, which objective produces the most loss terms?

BERT masks 15% of 512 tokens. How many tokens actually show [MASK] in the input?

T5 span corruption on 512 tokens: how long is the target?

A causal model is trained on 256-token windows. Is it trained to predict token 1 from token 0 alone?

Masked diffusion at rate t = 0.9 against BERT at 0.15: which gets more loss terms, and which is easier per term?

DeepSeek-V3 trains one MTP depth with λ = 0.3. At inference, what happens to the module?

Which objective lets a decoder answer a prompt it reads bidirectionally, without a second stack?

3. Why the causal mask is not optional: the leak, measured

Pair the next-token objective with a bidirectional mask and the target sits in the input, one position to the right: one attention head that reads position i+1 solves the task. We fine-tuned the reference tiny GPT for 150 steps (16 windows of 256 per step, learning rate 1e-3) with exactly this mistake (src/lab/masks.py):

Fig. 4 · The loss collapses below anything the data allows: the same checkpoint before and after 150 steps of leaking

  1. The contract. The query at position i (" a", an illustrative position) must predict token i+1 (" time") from the keys up to itself. The causal mask is the wall between them.
  2. Remove the wall. Under a bidirectional mask the answer is in the input, one position to the right, and nothing stops a head from reading it. Before training, the reference checkpoint with the mask removed has a loss of : it does not know how to use the future yet.
  3. The copying is learned in layer 1. Average attention weight on the key one position to the right, on the running sequence, both models under the bidirectional mask: in layer 1 it rises from (the reference with the mask removed) to after the 150 leak steps; the other five layers barely move. One head's worth of shortcut is enough.
  4. The loss collapses. The training loss every 25 steps: slow at first while the model still predicts from the past, then below the honest model's once a head reads position i+1, down to . Held-out under the same leaky mask it is , a tenth of the honest model's.
  5. Then we asked it to write. Generation cannot see the future, so the model runs under the causal mask, where its held-out loss is nats: worse than the 6.01 of a model that ignores context entirely (the unigram loss the Block lab measured).

Greedy decoding from the opening of the running sequence, the reference model against the leaky one:


Real output, greedy, 40 tokens (src/lab/out/masks.json), measured on Apple M1 Pro (CPU), the same run as the figure.

How this happens in real code

Writing your own attention with F.scaled_dot_product_attention(q, k, v) and forgetting is_causal=True (the default is False); passing a padding mask and assuming it also makes attention causal; or loading a decoder checkpoint into an encoder class. The symptom is always the same: a training loss far below anything plausible for the data (here nats per token on stories whose honest loss is about 2.3), then nonsense at generation. A loss that is too good is a bug until proven otherwise.

4. Encoders: both sides of every token

Many jobs never generate text: embed a query and a million documents and find the nearest, label a ticket, score whether a passage answers a question. For those the best representation of each token uses the words on both sides, in one forward pass. An encoder is the same stack with a bidirectional mask, trained with MLM; a task head reads its per-token vectors: a pooled vector for classification and embedding models, a relevance score over a concatenated query and document for a cross-encoder reranker, per-token labels for tagging. A decoder takes the same small head, but under the causal mask only the last position has seen the whole text, so the head reads the last non-padding token's hidden state (with right padding, simply reading the last position reads a pad token instead); on one IMDb split Raschka's fine-tuned GPT-2 124M reached 91.88% against ModernBERT large's 95.07%, single runs (Raschka on text classification).

Measured: both sides win, once the model has learned to use them. The masked diffusion model of section 8 is, at a fixed rate, an MLM encoder adapted from the reference tiny GPT. We hid a fixed random 15%, 50% or 90% of 16 held-out windows and asked it to recover them in one bidirectional pass; the causal reference predicted the same positions from the true left context (every real token before the blank, which the encoder is not given). Predict: at 90% hidden, which wins?

At 15% hidden the encoder beats the causal model clearly; at 90% the order reverses, because the encoder sees almost nothing while the causal model still sees the true past. That is why MLM masks a small share, and why a diffusion LM's first steps, with almost everything masked, are its least certain. Turning right-hand context into accuracy has to be learned: after the first adaptation steps the encoder did not yet win at 15% ( against the causal ). At full pretraining the gap is the same sign: BERT Table 5 gives 87.9 against 77.8 F1 on SQuAD dev for the same model trained left to right.

What changed since BERT. RoBERTa dropped next-sentence prediction (which the BERT paper page treats as unproven: one run, reversed by RoBERTa) and trained longer on more data with dynamic masking. ModernBERT (December 2024) brought the decoder era's parts into an encoder: RoPE, GeGLU, alternating global and 128-token sliding-window layers, MLM at 30%, 2 trillion tokens at native context 8,192; base about 149M parameters, large about 395M. Ettin (Seq vs Seq paper page, July 2025) trained encoders and decoders in pairs on the same data and recipe from 17M to 1B: encoders win classification and retrieval, decoders win generation, at every size, and 50B tokens of continued training on the other objective closes neither gap (the 400M encoder reaches 91.3 on MNLI against the 1B decoder's 89.9).

Cost and how to check. An encoder forward costs about 2N FLOPs per token (N parameters), like a decoder's prefill, with no KV cache afterwards; at 149M parameters it embeds a chunk in one pass on a CPU. Size buys a decoder-as-embedder its lead back only at large ratios (the Ettin paper page puts the largest ratio a native model wins at 2.7x, against the abstract's "10x"). An encoder's config names a ...ForMaskedLM or ...Model class rather than ...ForCausalLM, its attention sets is_causal = False, and its tokenizer has a [MASK] (or <mask>) token; model.generate either fails or produces filler.

Fill-in numbers, ModernBERT's recipe and the lineage in full (depth)
share hiddenpositions scoredencoder (both sides, corrupted) losstop-1causal (true left context) losstop-1

Final model; the -step model reached top-1 at 15%.

  • BERT (2018): MLM at 15% plus next sentence prediction; the bidirectional gain is real (Table 5 above).
  • RoBERTa (Liu et al. 2019): no NSP, more data, longer training, dynamic masking.
  • ModernBERT (Warner et al., arXiv 2412.13663): pre-norm LayerNorm without biases; every third layer global, the others a 128-token sliding window; RoPE theta 160,000 on global layers and 10,000 on local ones; no NSP; base 22 layers, large 28 layers. vendor: about twice DeBERTaV3's speed on short inputs (about 148k against 70k tokens/s at 512 tokens on an RTX 4090). transformers 5.20.1 builds the pattern from global_attn_every_n_layers (default 3) and halves local_attention (128) into a 64-token window on each side (configuration_modernbert.py lines and ).

Both sides beat the left side only when most of both sides is visible

Top-1 accuracy on the hidden positions, measured on Apple M1 Pro (CPU), src/lab/diff_eval.py, after adaptation steps.

5. Encoder-decoder: T5 to T5Gemma 2

A bidirectional encoder reads the input once; a causal decoder writes the output, and in every block a cross-attention layer lets each output position read every encoder vector (the encoder-decoder view of the mask figure in section 1). The input can be long and fully bidirectional while generation stays causal.

Fig. 5 · Read the input once, cross-attend from every decoder layer

  1. The encoder reads the input both ways. Six input tokens (the running sequence's opening) go up through the encoder stack, every position attending to every other: bidirectional, and run once per input. Four layers are drawn per stack (illustrative; T5's compared models have 12).
  2. Its output, computed once. The last encoder layer's vectors are projected to keys (teal) and values (purple) for cross-attention, once per input; nothing about them depends on what the decoder writes.
  3. Every decoder layer reads it. Each decoder block has a causal self-attention over the outputs so far and a cross-attention whose keys and values are that plate: the input reaches every layer of the decoder, not only the first.
  4. Writing, one token per forward. The decoder writes like a decoder-only model: one output token per forward, its own self-attention keys and values cached and growing by one each step, while the cross keys and values stay exactly as computed.
  5. Twice the parameters, the same FLOPs. T5 Table 2: the 12 + 12 encoder-decoder has 2P parameters against a 12-layer decoder's P, yet the same FLOPs M over an input plus target of the same total length, because each token passes through only one stack. GLUE: 83.28 against the prefix LM's 81.82 and the causal decoder's 74.70.

Twice the parameters, the same FLOPs. T5 compared architectures at equal compute (Table 2 of T5): a 12 + 12 layer encoder-decoder has twice the parameters (2P) of a 12-layer decoder yet the same FLOPs (M) over an input plus target of the same total length, because each token passes through only one 12-layer stack:

T5 Table 2 (denoising objective)paramsFLOPsGLUESuperGLUECNN/DM
encoder-decoder2PM83.2871.3619.24
encoder-decoder, shared weightsPM82.8170.7318.78
prefix LM (decoder-only)PM81.8268.1118.61
language model (causal decoder)PM74.7055.0217.93

Published, T5 Table 2 (arXiv 1910.10683; values as printed in the T5 page's tables.json), 220M-class models, one run each; the T5 page puts the paper's run-to-run noise at a fraction of these gaps. With fine-tuning on understanding-heavy benchmarks, bidirectional reading of the input was worth about 7 to 8 GLUE points over a causal decoder in 2019.

Why decoders won anyway. Wang et al. 2022 (arXiv 2204.05832, models over 5B parameters on 170B tokens) found that after purely unsupervised pretraining causal decoders have the strongest zero-shot generalisation, while non-causal MLM models win only after multitask fine-tuning. A general assistant answers anything zero-shot and writes long outputs from short prompts, and one stack makes caching, batching and serving simpler.

Where encoder-decoders still win: long input, short output tied to it: translation, summarisation, speech recognition (Whisper: "We chose an encoder-decoder Transformer", Radford et al. 2022, section 2.2). T5Gemma and T5Gemma 2 (paper page) build encoder-decoders by copying a pretrained decoder's weights into both stacks and continuing with UL2 or PrefixLM: after instruction tuning the 2B-2B beats Gemma 2 2B by 7.1 points (46.1 against 39.0); the unbalanced 9B-2B decodes at about 1.05x Gemma 2 2B's latency with much higher accuracy on GSM8K; T5Gemma 2's 4B-4B scores 81.7 on RULER 32K against Gemma 3 4B's 66.8 although pretrained at 16K (57.6 against 51.7 at 128K). The paper page's verdict: the direction is believable, the sizes are single runs from models with about twice the parameters. The shape is also back at frontier scale for a serving reason rather than quality: DeepSeek-V4.1-Flash (September 2026, 552B, open) splits 40 layers into a 20-layer encoder and a 20-layer decoder to shrink the KV cache of long agent loops (DeepSeek owns how).

6. Prefix LM and mixtures of objectives (UL2)

A prefix LM is a decoder with the prefix mask of section 1: prompt read bidirectionally, continuation causally, only the continuation scored. It buys most of the encoder-decoder's gain with one stack (T5 Table 2: 81.82 against 83.28 GLUE; the causal LM 74.70). The price is at inference: the prompt's keys and values depend on the whole prompt, so a prompt cannot be extended without recomputing its cache, which breaks the multi-turn and prefix-caching tricks serving relies on (Batching, KV cache and scheduling). And it has to be trained as one: our causal checkpoint run with a 128-token prefix got worse even on the scored suffix (section 1). A fine-tuning-time variant keeps the causal model and adds a bidirectional read: Bitune reads the prompt twice, causally and bidirectionally with an adapter each, mixes the two sets of keys and values per block with learned weights and still generates causally (+0.1 to +4.0 points over LoRA on five 2B to 8B models, for about 3 times the fine-tuning time).

UL2 (Tay et al., arXiv 2205.05131) mixes three denoisers in one run, each announced by a mode token: R (regular span corruption, mean spans 3 and 8 at 15%), S (sequential: one span covering the last quarter of the input, which is prefix LM), X (extreme: spans of 64 tokens or corruption at 50%). Its 20B model reported beating 175B GPT-3 on zero-shot SuperGLUE (vendor, 2022). UL2 survives as the adaptation objective of T5Gemma.

7. Multi-token prediction (MTP)

Next-token prediction asks each position about one token, so a model can do well on local patterns without planning; and at inference the decoder makes one forward per token, each limited at small batch by reading the weights from memory, not by arithmetic (Performance math). Multi-token prediction adds loss terms for tokens two or more places ahead: a denser training signal, and a ready-made guess for the next forward to check.

Fig. 6 · Two ways to predict the token after next: the sequential module is told the next token

  1. The trunk and its head. The tokens up to position i (" a", an illustrative position) flow up through the 6 blocks to hi, the last hidden state; the shared head turns it into the next token, " time". The frozen reference's top-1 on t+1 over 128 held-out windows: .
  2. A parallel head (Gloeckle et al.). One extra block reads hi alone and the same head predicts ti+2: top-1 . It has to guess ti+1 implicitly.
  3. The sequential module (DeepSeek-V3, depth 1). The module is also told the known ti+1: M projects [RMSNorm(hi) ; RMSNorm(Emb(ti+1))] from 2d to d, then one block of the main model's shape and the shared head: top-1 on t+2, close to the main model's own next-token score.
  4. As a draft. A draft is accepted when it equals the main model's next greedy choice: of the time for the sequential module against for the parallel head on held-out windows; on the 8 evaluation prompts that is against tokens per forward.
  5. What it costs. To scale: the sequential module's parameters and the parallel head's beside the main model's . Training pays for one more block; inference can drop it.
  • Parallel heads (Gloeckle et al., arXiv 2404.19737, April 2024): n independent one-layer heads on a shared trunk and unembedding; head k predicts t+k from the trunk's state at t alone. Heads run forward and backward one at a time, so peak memory stays O(V + d) instead of O(nV + d). vendor (Meta): at 13B, 12% more HumanEval and 17% more MBPP problems solved; "worse than the baseline for small model sizes, but outperform the baseline at scale"; n = 4 best for token-level code; as drafts, 3.0x faster decoding on code and 2.7x on text.
  • Sequential module (DeepSeek-V3, arXiv 2412.19437 section 2.2): depth k takes the previous depth's state and the embedding of the known token ti+k, so the chain stays causal (the paper compares it to EAGLE). DeepSeek-V3 uses D = 1 and weights the loss by λ = 0.3 for the first 10T tokens and 0.1 for the remaining 4.8T.
h′i = M [ RMSNorm(hi) ; RMSNorm(Emb(ti+1)) ],   Pi+2 = OutHead(TRM(h′i)),   L = Lmain + λ · CE(Pi+2, ti+2)
hi
the main model's last hidden state at position i (d = 7,168 in DeepSeek-V3; 256 in the tiny GPT)
M
d by 2d projection (eh_proj in the checkpoint)
TRM
one transformer block of the main model's shape (in V3 an MLA + MoE block)
OutHead, Emb
shared with the main model

Cost. One extra block in training, nothing at inference: the module can be discarded. DeepSeek-V3's MTP layer is 13.46B parameters, mostly its own stored copies of the embedding and output head, which is why the Hub says 685B where the paper says 671B (bill in the closed block). Benefit, published: DeepSeek-V3 Table 4 shows real but small single-run gains at 15.7B and 228.7B (and MMLU 0.9 lower at large scale); as a draft in serving, the second-token guess has "between 85% and 90%" acceptance and gives "1.8 times TPS" (section 5.4.3).

Measured: is it worth it at equal compute?

The baseline tiny GPT with a sequential depth-1 module beside it, λ = 0.3, at exactly the reference budget (1,500 steps of 8,192 tokens, same seed, schedule and batches; src/lab/train_mtp_joint.py, MPS). Predict, then switch the x-axis:

At equal tokens the main model's loss ends at with MTP against for the reference (seed 0), and against with seed 1, gaps several times the rerun spread of the seed-0 baseline (2.2744 to 2.2811). But the module adds a seventh block and a second pass through the output head, more training FLOPs per step (derived from the Block lab's FLOP counts); spent on plain next-token training instead (1,980 steps), the baseline reaches . At equal compute MTP loses at this scale, in line with Gloeckle et al.'s small-model result (their parallel heads; ours is the sequential design) and with DeepSeek's evidence being single runs at large scale. What transfers: an MTP loss is cheap to add and free at inference; whether it pays must be measured at equal compute and at your scale.

MTP wins at equal tokens and loses at equal FLOPs: held-out loss of the main model

Measured: the module as a draft

Both designs trained on top of the frozen reference, 600 steps each, only the module learning (src/lab/mtp_frozen.py, CPU). In self-speculative greedy decoding each forward of the main model checks the previous draft and makes a new one, so it emits 2 tokens when the draft was right and 1 when it was wrong, and the output is identical to plain greedy decoding. One prompt, the running sequence's opening, decoded with each draft:

Over the 8 evaluation prompts, 120 new tokens each, the sequential draft gives tokens per forward and the parallel head , output identical to plain greedy in every case (). The sequential module, told token t+1, predicts t+2 almost as well as the main model predicts t+1; the parallel head must guess t+1 too. Tokens per forward is not speed: on a GPU the verifying forward costs about a normal decode step only while decoding is memory-bound; Speculative decoding owns the batch-size crossover and the acceptance rule for sampling.

measured on Apple M1 Pro (CPU), 2026-10-18; greedy, no KV cache (each forward recomputes the sequence; counts of forwards, not timings, are the result).

The parameter bill, DeepSeek-V3 Table 4, the draft numbers per prompt, an acceptance calculator (depth)

The Config calculator (on Topic: llm-architecture) counts DeepSeek-V3's MTP layer at parameters (13.46B), which with the main model's and 41.5M FP8 scales reproduces the Hub's 684,531,386,000 exactly. Split by the formula above (derived, src/lab/make_page_data.py from the calculator's DeepSeek-V3 config):

part of the MTP layerparametersshare

The checkpoint stores its own copies of the embedding and output head inside layer 61 (the calculator's mtp_copy; GLM-4.5 does the same, Qwen3-Next does not), although training shares them. Loading DeepSeek-V3 in transformers 5.20.1 silently drops the layer: _keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"] (modeling_deepseek_v3.py line ), so a "671B" model in memory is correct and the MTP draft is not there, while serving engines load it for drafting (Speculative decoding lists 27 MTP model types in vLLM v0.31.0).

DeepSeek-V3 Table 4small MoE+ MTPlarge MoE+ MTP

Published (DeepSeek-V3 Table 4, values from the DeepSeek-V3 paper page's tables.json): small 15.7B total (2.4B active) on 1.33T tokens, large 228.7B (20.9B active) on 540B tokens; the MTP module is discarded at evaluation, so inference cost is identical. The paper page's verdict: real but small, single-run gains.

predictor (128 held-out windows)parameterslosstop-1agrees with main model's greedy choice

The last column is the draft acceptance rate under greedy decoding with a teacher-forced prefix.

promptsequential: forwardstokens per forwardacceptanceparallel: forwardstokens per forwardacceptancejoint-trained module: tokens per forwardidentical to greedy

Acceptance counts every forward after the first (which has no draft yet). The joint-trained column uses the main model and module trained together from scratch, decoding that model's own greedy text.

Acceptance to tokens per forward

derived: expected tokens per forward = 1 + a + a² + ... + ak when each further draft token is accepted with the same probability a and only after the previous one. Defaults: DeepSeek-V3's lower reported acceptance (85%) at its trained depth 1 gives 1.85 tokens per forward against the 1.8x TPS they report (vendor, section 5.4.3): the small gap is the cost of the extra module and verification.

Training the two draft modules on the frozen trunk

Training loss on the token two places ahead, 600 steps of 16 windows of 256, AdamW lr 1e-3, only the module learning (trunk, embedding, final norm and head frozen). The sequential module starts from a better place because it is given the real next token. Parameters: sequential (one block plus the 512 to 256 projection and two norms), parallel ; main model .

Same prompt, same output, fewer forwards when the draft is told the next token

emitted by the main model (verified)draft accepted: a free tokendraft rejected (struck)

8. Diffusion language models

A decoder writes 48 tokens in 48 forwards, each waiting for the last. An image diffusion model starts from noise and refines the whole picture at once over a fixed number of steps (Diffusion from zero teaches it for pixels). A diffusion language model does the same for text with masking as the noise: start from a row of [MASK] tokens and fill in several per forward, in any order. Here is ours (the reference tiny GPT adapted into one, below) writing the same 48-token continuation of the running sequence's opening that the causal model writes token by token:

Fig. 7 · Fewer sequential forwards, more token positions processed: one continuation, two decoders

  1. The start. Both decoders read the same 31-token prompt. The causal model has 48 empty slots to fill in order; the diffusion model starts from 48 [MASK] tokens.
  2. Three forwards. The causal model commits 3 tokens, one per forward. The diffusion model predicts every masked slot at once and commits the 4 most confident each step: 12 tokens, wherever it is surest (the recorded order), not left to right.
  3. Six forwards. 6 tokens against 24: every committed slot is context for the next step's guesses, on both sides of the slots still masked.
  4. Twelve forwards: the diffusion model is done. All 48 slots in 12 forwards, 4 tokens per forward; the causal model has written 12.
  5. Forty-eight forwards, and what each cost. The causal model finishes 36 forwards later. But with a KV cache it processes each new token once after a prefill of the prompt: token positions, against for diffusion, whose every step reads the prompt and all 48 slots because nothing can be cached between steps.

How it works: masked diffusion from zero

  1. Forward process (the noise). Pick a time t between 0 and 1 and hide each token independently with probability t: clean at t = 0, all [MASK] at t = 1.
  2. The model is a bidirectional transformer (an encoder) that reads the partly masked sequence and predicts the original token at every masked position.
  3. The loss (LLaDA, Nie et al., arXiv 2502.09992): cross-entropy on the masked positions only, each weighted by 1/t, averaged over the sequence length. The weight makes the sum an upper bound on the negative log-likelihood; MDLM (Sahoo et al., NeurIPS 2024) calls it "a mixture of classical masked language modeling losses". Fix t = 0.15 and you have BERT; draw t at random and the model learns every stage from nearly clean to fully masked.
  4. Sampling (the reverse process), what the card beside replays word by word (pick a decoder, then step or scrub): start with the prompt followed by L masks; each step, predict every masked position, commit some and leave the rest masked. LLaDA commits the most confident ones (low-confidence remasking). With L tokens and K steps it commits L/K tokens per forward.
L(θ) = − Et, x0, xt [ (1/t) Σi 1[xti = M] log pθ(x0i | xt) ] / L
t
masking rate, uniform in (0, 1]; LLaDA draws p = (1 − ε) t + ε with ε = 0.001
M
the mask token; positions not masked give no loss
L
sequence length (256 here)

Why 1/t: at rate t the expected number of masked tokens is tL; dividing by t makes every rate contribute a comparable per-sequence term, and the result bounds the likelihood, so training it is maximum-likelihood training of a generative model rather than a fixed-rate MLM. The bound is not a perplexity: our adapted model's and the causal model's 2.28 are not the same kind of number.

Masked denoising of one sentence: every slot is guessed each step, the most confident are committed

still masked (the current guess, faint)committed this stepcommitted earlier

measured on Apple M1 Pro (CPU), src/lab/diff_eval.py, greedy commits with low-confidence remasking (LLaDA). "Token positions processed" counts what each forward reads: the causal model with a KV cache processes each new token once after a prefill of the prompt; every diffusion step reads the prompt and all 48 answer slots, because nothing can be cached between steps.

Measured: the reference tiny GPT turned into a diffusion LM

Adapting a trained AR model is how DiffuLLaMA (Gong et al., ICLR 2025: GPT-2 and LLaMA from 127M to 7B, under 200B tokens) and Dream 7B (HKU blog, April 2025: "initialized with weights from Qwen2.5 7B", 580B tokens) were built; LLaDA 8B was trained from scratch on 2.3T tokens with 0.13 million H800 GPU hours. We added a [MASK] token to the reference checkpoint's embedding, switched the mask to bidirectional and trained with the LLaDA loss for steps of 16 windows ( at learning rate 1e-3, then the rest at 5e-4; src/lab/train_diffusion.py, CPU, minutes in all). Held-out bound: at the start, after the first stage, at the end.

The shift, measured: the change that matters most when adapting

An AR checkpoint's output at position i was trained to predict token i+1. Dream "predicts all the masked tokens in a shifted manner": the masked token at i is read from the logits at i−1, keeping that alignment. Our first 100-step probe without it reached a held-out bound of ; with it, . Without the shift the adapted model spends its budget relearning which position answers which question. LLaDA, trained from scratch, needs no shift.

Fewer steps, more tokens per forward, lower quality. 48-token continuations of the 8 evaluation prompts, judged by an independent model (SmolLM2-135M's per-token loss on the continuation; lower is more fluent to that judge):

Committing more tokens per forward from the same, partly masked context lowers quality. Random remasking instead of confidence order is clearly worse at 48 steps ( against ), as in LLaDA's own ablation, but at 12 steps it is better here ( against ): committing the 4 most confident slots at once tends to pick the same easy pieces in neighbouring places, which random order avoids. LLaDA's table is at one step per token; this toy does not test it at few steps. The tiny model is small and briefly adapted: read the ordering, not the gap to AR.

Real bad output: parallel commits do not coordinate

The causal model continues prompt 7 with "". The diffusion model at 12 steps writes "". Our tokenizer splits the name Roxy into pieces (R, o, x, y), and each step predicts every masked slot independently given the current context, so slots filled in the same step cannot agree: the name comes out as fragments ("R", "Ro", "Roy") and confident common pieces land side by side ("named named"). This conditional-independence cost grows with tokens per step, which is why fewer steps lose quality and why production systems commit in small blocks with confidence thresholds.

Each halving of the steps costs fluency; the causal model stays ahead

What it costs

Every diffusion step is a full bidirectional forward over prompt plus answer, and nothing can be cached between steps because every position's keys change as tokens are committed ("LLaDA is incompatible with KV caching"). So diffusion trades more FLOPs for fewer sequential forwards: worth it when decoding is memory-bound (one user, small batch), not when a server is already compute-bound at large batch. For the 48-token continuation of an -token prompt, 12 diffusion steps process token positions against the AR decoder's (derived; the counter in the figure). Block diffusion (Arriola et al., ICLR 2025) fixes the caching problem: generate blocks left to right, diffuse inside each block, cache the finished ones. DiffusionGemma uses the same block-AR idea; its paper page runs that sampler on its own toy.

Published results

  • LLaDA (vendor, arXiv v3, 2025-10-18): 8B "competitive with strong LLMs like LLaMA3 8B in in-context learning"; low-confidence remasking beats random on every benchmark of its Table 9, by 12.9 (BBH) to 48.7 (GSM8K) points; on reversal poem completion LLaDA 8B Instruct scores 51.8 forward and 45.6 reversed against GPT-4o's 82.7 and 34.3: an order-free model suffers less from the reversal curse. Throughput 1.5x and 1.8x LLaMA3 8B Base on GSM8K and Math at comparable quality.
  • Mercury (Inception Labs, arXiv 2506.17298, June 2025): Mercury Coder Mini 1,109 and Small 737 tokens/s on H100s, independent (Artificial Analysis, as cited by the authors). The current line, Mercury 3 (19 October 2026), is API-only with a 1M-token context (Mercury 2.5: 260K), 1,068 tokens/s on NVIDIA GPUs and $0.20 / $0.70 per million input and output tokens (vendor, Inception); Inception says it beats GPT-6 Luna and Claude Haiku 5.5 "across a range of benchmarks" but published no scores, and no independent index listed it at release: a speed figure with no quality figure beside it.
  • Gemini Diffusion (Google DeepMind, model page, announced 2025-05-20, an experimental demo): vendor 1,479 tokens/s excluding 0.84 s overhead; level with Gemini 2.0 Flash-Lite on code, well behind on GPQA Diamond (40.4 against 56.5).
  • DiffusionGemma (paper page, weights 2026-06-09, report August 2026): Gemma 4 26B A4B warm-started from AR weights with under 10% of the AR token budget; 19.74 tokens per forward on average, 1,479 tokens/s on one H100 at one request (vendor; 7.2x plain AR, 4.9x Gemma 4 with MTP at 1.40 tokens per forward), and a quality tax: 73.2 against 82.3 on GPQA-Diamond. The paper page puts the crossover where batched AR serving wins at about 32 concurrent users, so a tokens-per-second figure means nothing without its batch size. (The 1,479 matches Gemini Diffusion's figure digit for digit; both are as printed by their sources.)
Quality table, continuations, LLaDA Table 9, Gemini Diffusion's table, the adaptation curve (depth)
decoderforwards for 48 tokenstokens per forwardjudge lossdistinct bigrams

measured, greedy (argmax) commits, 2026-10-18. Judge: SmolLM2-135M (revision 93efa2f0), per-token loss of each continuation given its prompt, re-tokenised with its own tokenizer, mean over the 8 prompts. A judge from outside the topic avoids the bias of scoring the causal model's greedy text with the causal model itself (that self-score is in src/lab/out/diffusion_eval.json). Repetitive text scores well with any language-model judge, so distinct bigrams are shown beside it. The 1,500-step model scored worse everywhere (in src/lab/out/diffusion_eval.json): more adaptation helps at every step count.

decodercontinuation of prompt 7 (48 tokens)
LLaDA 8B Base, length 256, Table 9BBHGSM8KMathHumanEvalMBPP
random remasking32.121.39.211.621.0
low-confidence remasking45.070.030.332.940.2

Gemini Diffusion against Gemini 2.0 Flash-Lite (vendor, speed averaged over the reported evals): HumanEval 89.6 against 90.2, MBPP 76.0 against 75.8, GPQA Diamond 40.4 against 56.5, Global MMLU Lite 69.1 against 79.0.

The adaptation run

Held-out loss bound on 64 windows with a fixed masking draw, every 100 steps of train_diffusion.py --shift: the reference checkpoint plus one [MASK] embedding row, bidirectional mask, LLaDA loss, AdamW, 16 windows of 256 per step, CPU: steps at lr 1e-3 (50 warmup steps, cosine decay), then 3,000 more at 5e-4 on new windows (--resume). The page's diffusion results use the final model; the 1,500-step model's are in src/lab/out/diffusion_eval.json.

9. Choosing

  • Generate open-ended text, follow instructions or reason: a decoder-only model. If it ships MTP weights, use them as the draft; if you pretrain at billions of parameters, a depth-1 sequential MTP loss is a cheap addition (one block, λ around 0.1 to 0.3) that you can drop at inference, judged at equal compute.
  • Vectors or labels for a lot of text, cheaply: an encoder (ModernBERT-class, 150M to 400M), fine-tuned for the task. At equal size and data it beats a decoder used as an embedder (Ettin).
  • Long input, short output tied to it (translation, summarisation, speech): consider an encoder-decoder, ideally adapted from a decoder you trust (T5Gemma 2); an unbalanced large encoder with a small decoder buys quality at small-decoder latency.
  • Labels with no training data, only a description of each label: a hosted decision model, which takes text and typed questions and returns a probability per allowed answer with no generation (TypeSafe's Jev: 96.47% on IMDb with no IMDb training, one run, possible contamination; its probabilities can come rounded and piled at 0 and 1). Fine-tune an encoder once labelled data and volume justify it. Measured on Raschka on text classification; the provider is on Other notable providers.
  • One user, latency first, quality tax acceptable: a block-diffusion LM. At high concurrency a batched AR server with speculative decoding is the better use of the GPU.

Depth

In production, October 2026: which checkpoints are which, and how to tell (reference)
FamilyOpen examplesWhat the checkpoint tells you
Decoder-onlyLlama 3/4, Qwen3, DeepSeek-V3.2, Kimi K2, gpt-oss, Gemma 3/4 (the root's Architecture map has 46)...ForCausalLM in architectures
Decoder + MTPDeepSeek-V3/V3.2 (1 module, 13.46B and 13.48B), GLM-4.5 (5.54B) and GLM-4.5-Air (3.62B), Qwen3-Next (1.65B), MiMo and Gemma 4 (drafting heads in vLLM)num_nextn_predict_layers (DeepSeek, GLM) or mtp_num_hidden_layers (Qwen3-Next); MiniMax-M2's config names 3 MTP modules that are not in the released weights
EncoderModernBERT base and large, Ettin (17M to 1B), the encoders inside embedding and reranker models...ForMaskedLM, a mask token, is_causal = False
Encoder-decoderT5 and Flan-T5, T5Gemma and T5Gemma 2, Whisper, DeepSeek-V4.1-Flashis_encoder_decoder: true, separate encoder and decoder layer counts
Diffusion LMLLaDA 8B, Dream 7B, DiffusionGemma (open weights); Mercury and Gemini Diffusion are served, not releaseda bidirectional backbone plus a sampler with steps and block length; custom generation code

MTP parameter counts from the root's Config calculator (FACTS, 2026-10-18); MiMo and Gemma 4 from the Speculative decoding page's vLLM v0.31.0 survey.

Mistakes the core does not already show (depth)
  • Judging an extra objective at equal tokens. Our MTP run beat the reference by nats at equal tokens; a baseline given the same training FLOPs beat the MTP run by . An auxiliary module that adds compute must be compared at equal compute.
  • Sampling with an MTP draft and accepting by equality. Exact-match acceptance is correct only for greedy decoding (our runs: identical to plain greedy, ). At temperature above 0 the speculative acceptance rule (accept with probability min(1, p/q), resample the remainder) keeps the model's distribution; see Speculative decoding.
  • Comparing a diffusion LM's loss with a perplexity. Compare generations with one judge, as section 8 does, or compute the bound for both models.
Interview rehearsal: six questions and three design questions (optional)
Why did decoder-only models win over encoder-decoders?
One objective that makes every token a training example and every task a prompt; the strongest zero-shot generalisation after unsupervised pretraining (Wang et al. 2022); one stack, one cache, simple batching and prefix caching. Encoder-decoders still win input-heavy tasks at equal compute (T5 Table 2).
Why can't you generate well with BERT?
It was trained to fill a few blanks given almost all of the context; generation starts with no right context at all and needs many tokens committed in a sensible order. A masked diffusion model is the same architecture trained at every masking rate, which is exactly what fixes this.
An encoder-decoder has twice the parameters of a decoder. Does it cost twice as much to run?
No: each token passes through one stack, so at equal total length the FLOPs are about the same (T5 Table 2: 2P parameters, M FLOPs for both). Memory for weights doubles; the decoder caches its own KV plus cross-attention KV computed once from the encoder.
What does DeepSeek-V3's MTP module see, and why does that matter for drafting?
The main model's last hidden state at i and the embedding of the true token i+1; one block and the shared head predict i+2. Knowing i+1 makes its guess much better than a parallel head's (measured here: top-1 against ), so as a draft it is accepted often (85 to 90% in DeepSeek's report) and gives up to 2 tokens per forward.
With a depth-1 draft accepted with probability a, how many tokens per forward?
1 + a for one draft token per forward (each forward always yields the verified token, plus the draft when accepted); DeepSeek's 0.85 to 0.9 gives 1.85 to 1.9, close to their reported 1.8x TPS. With chained depth-k drafts accepted independently, 1 + a + a² + ... + ak.
Design: classify 50 million support tickets a day and draft a reply for the 1% that need a human.
A fine-tuned encoder (ModernBERT-base class, about 150M parameters) for the classification: one forward per ticket, batched on CPUs or one small GPU, no generation. A decoder-only model only for the 500k drafts, with MTP or a draft model for latency, prompted with the classifier's label and retrieved replies (an encoder again, as the embedder). Using the decoder for both would cost hundreds of times more per ticket for worse classification at equal size (Ettin).
Design: code completion in an editor, one user, under 100 ms for 30 tokens on one GPU.
Decode is memory-bound at batch 1, so cut sequential forwards. Options: an AR model with its MTP heads or an EAGLE-style draft (1.5 to 3x, exact distribution, easy to serve); a block-diffusion model (DiffusionGemma reports about 20 tokens per forward at one request, with a quality tax); or a smaller model. Measure acceptance on real completions first: code is repetitive, so drafts are accepted often. Revisit at high concurrency, where batching beats both.
Design: you are pretraining a 30B decoder. Would you add MTP, and how would you know it helped?
Yes, depth 1, sequential, λ about 0.3 then 0.1, shared embedding and head: about one extra block of compute per step and no inference cost. Know it helped by an equal-compute ablation (not equal tokens: the module adds FLOPs) at two scales on code, maths and knowledge benchmarks, several seeds or at least the noise of reruns, and the draft acceptance rate as a bonus. Our tiny run shows why equal compute matters: the module added FLOPs per step.

Built 2026-10-18 from the repository, rebuilt 2026-10-23 with the four lab tabs folded into Reading (source in this page's src/). Measured results: Apple M1 Pro, CPU at 4 threads or MPS, shared machine. Published numbers are labelled vendor or independent and dated at the point of use.