Course contents 23 / 28

23 / 28 · Pretrained Language Models

Encoder, decoder and encoder–decoder models

Choose an attention layout and training target for classification or generation; trace encoder, causal decoder, prefix and encoder–decoder information flow.

On this page 6

A system that assigns a label to a complete message and a system that writes a reply need different outputs. Both can use Transformer blocks. To choose a model, first specify which input positions each prediction may use and what the output must represent.

Baseline: the architecture name as the only description#

The names encoder and decoder describe common arrangements. They do not specify every attention mask, pretraining loss or downstream head. An encoder can be trained to reconstruct masked tokens or detect replacements; a decoder can be trained on all next-token targets or only a designated answer segment.

A useful description separates the information path, the prediction target and the task interface. The evolution of pretrained models showed why changing one of these need not change the others.

The three families#

Let ss denote the number of source tokens, tt the number of decoder input positions and dd the hidden width. Ignore padding in this discussion.

ArrangementInformation availableTypical output
EncoderAll source positions within its allowed masks×ds\times d contextual states
Causal decoderCurrent and earlier input positionsNext-token distribution per position
Encoder–decoderFull source through cross-attention; causal target prefixConditional output sequence

A fully visible encoder mask allows every source query to read every source key. This is useful when the entire input is known before a decision is required. A classifier can use a selected state or a pooling operation; a tagging head can predict a label for each input token. The contextual states alone do not define the final task prediction.

A causal decoder masks later input positions at every layer. Its current input token is visible while the corresponding target is the next token. This shift prevents target leakage. GPT derives that objective and the cache used during generation.

An encoder–decoder has two sequences. The encoder processes the complete source. Decoder self-attention sees the shifted target prefix, while cross-attention uses decoder queries and encoder keys/values. The conditional distribution factorizes as

pθ(y1:T∣x)=∏j=1Tpθ(yj∣y<j,x).p_\theta(y_{1:T}\mid x)=\prod_{j=1}^T p_\theta(y_j\mid y_{<j},x).

Full source access is compatible with causal target generation because the source is already observed. At inference, unknown future target tokens must stay unavailable.

A prefix language model uses one stack with a bidirectional source prefix and a causal output region. Source queries must never read target positions: otherwise information can travel from a future target through a source state and leak back into an earlier prediction in the next layer. For a two-position prefix followed by two output-input positions, the allowed binary mask is

A=(1100110011101111).A=\begin{pmatrix} 1&1&0&0\\ 1&1&0&0\\ 1&1&1&0\\ 1&1&1&1 \end{pmatrix}.

Rows are queries and columns are keys; ones mean allowed attention. A fully causal mask differs at the first row, which cannot read the second prefix token. A prefix model and an encoder–decoder can have similar visibility yet different parameter sharing, depth paths and separate attention operations. They are not numerically equivalent merely because their allowed edge counts match.

How the objectives differ in what they teach#

Masked-token prediction asks for original token identities at selected positions given a corrupted input. Next-token prediction asks for each token given its prefix. Denoising sequence prediction asks for a target sequence given a corrupted source. These objectives determine which mistakes receive gradients; the architecture determines which information can reduce those mistakes.

In the T5 span-corruption scheme, each removed span is replaced by a distinct sentinel token. The target lists the missing spans with matching sentinels and a final sentinel. Consider our newly composed sequence move amber crate to bay. Remove amber crate and bay:

RoleTokens
Corrupted sourcemove S0 to S1
Target, including end markerS0 amber crate S1 bay S2 EOS
Shifted decoder inputBOS S0 amber crate S1 bay S2

The sentinel identifies where each missing span belongs. The decoder predicts the target in order. This tiny example has seven target positions, whereas reconstructing the five original tokens plus EOS would use six. Predicting only missing spans often saves work on longer inputs with a low corruption rate, but the sentinel overhead matters for short examples. The lengths must be counted from the actual transformation.

For these s=4s=4 source and t=7t=7 decoder-input positions, full encoder attention has 16 allowed query-key pairs. Causal decoder attention has 28, and cross-attention has 28:

Cenc=s2,Cdec=t(t+1)2,Ccross=st.\begin{aligned} C_{\mathrm{enc}}&=s^2,\\ C_{\mathrm{dec}}&=\frac{t(t+1)}2,\\ C_{\mathrm{cross}}&=st. \end{aligned}

Their sum is 72. A prefix mask over the same eleven positions also allows 72 pairs. A fully causal mask over eleven positions allows 66. These are counts of logical pairs for one corresponding operation of each kind, not measured FLOPs, memory or latency. Layer count, projections, feed-forward work, kernels and whether masked entries are computed all change actual cost.

Loss normalization is another independent choice. If three scored target tokens have probabilities 0.5, 0.25 and 0.5, their mean loss in nats is

−log⁡0.5+log⁡0.25+log⁡0.53≈0.924196.-\frac{\log0.5+\log0.25+\log0.5}{3}\approx0.924196.

Adding unscored prompt tokens to the denominator would change this number without improving any prediction. In a prompt–answer training pair, the loss mask should explicitly state whether prompt tokens are part of the learning target.

Why a shared generation interface is useful#

A single next-token interface can express a continuation, an answer or a textual class label by changing the prefix. Its causal states also support incremental caching. GPT-3’s prompting experiments illustrate how tasks can share this interface without an individual gradient update for each test example.

This convenience does not establish architectural superiority for every task. An encoder can score a complete input with one forward pass and a small task head. An encoder–decoder separates a source representation from an independently growing output. Data, training objective and adaptation remain part of the comparison. A claim about which family dominates a market would require a defined population and date; the mechanism alone cannot establish it.

Choosing, in practice#

For a fixed label set, define whether the system should emit a class index or generate a label string. A class head can normalize directly over the allowed classes. A generation interface needs a rule for parsing outputs, handling invalid strings and scoring labels that tokenize into different numbers of tokens. Taking the first generated word is not a complete evaluation protocol.

For extraction, token-level states can score source spans. For a rewritten or translated sequence, an autoregressive output head can produce tokens that need not occur in the source. For retrieval, the pooling rule and training objective determine whether a vector represents useful similarity; choosing any encoder does not guarantee a good embedding.

Compare candidates on the same held-out task and resource budget. Include the tokenizer, context limit, fine-tuning data, decision rule and output constraints. Then measure the system’s actual latency and memory; logical attention counts only explain one part of the work.

Limitations#

The masks above assume complete source availability. Streaming input needs another visibility policy. A pretraining objective does not guarantee calibration, factual accuracy or a useful pooled representation. Encoder-only, decoder-only and encoder–decoder are broad families that contain many architectural variations; the examples isolate masks and targets without training a model.

What you should remember#

Specify information flow, target and output interface separately. Shift autoregressive targets. Block target-to-prefix leakage at every layer. Count sentinel overhead and scored positions. Equal attention-pair counts do not imply equal model cost or behavior.

Code#

This original calculation checks the span-example lengths and mask-pair counts. All tokens are explicitly supplied.

source = ['move', 'S0', 'to', 'S1']
target = ['S0', 'amber', 'crate', 'S1', 'bay', 'S2', 'EOS']
s, t = len(source), len(target)
encoder = s * s
decoder = t * (t + 1) // 2
cross = s * t
prefix = sum(j < s or (i >= s and j <= i)
             for i in range(s+t) for j in range(s+t))
causal = (s+t) * (s+t+1) // 2
print('source/target', s, t)
print('encoder/decoder/cross', encoder, decoder, cross)
print('prefix/causal', prefix, causal)
assert prefix == encoder + decoder + cross
source/target 4 7
encoder/decoder/cross 16 28 28
prefix/causal 72 66

Next#

Choosing a family still leaves model size and training duration open. Scaling laws uses an explicit loss model to allocate a fixed computation budget between parameters and tokens.

References#