Encoder–Decoder Models, Attention and Contextual Embeddings #
Translation and summarisation produce sequences whose lengths can differ from the input. In an encoder–decoder model, the encoder builds source representations and the decoder generates one output token at a time. Attention lets the decoder consult different source positions as its output changes.
1. Choosing the next token #
An autoregressive model estimates a distribution for the next token given the prefix. In an encoder–decoder model it also conditions on the source. The probability of a complete sequence is the product of its successive token probabilities.
| Decoding method | How it chooses | Typical trade-off |
|---|---|---|
| Greedy | Takes the most likely next token at each step | Fast and deterministic |
| Beam search | Keeps the best few partial sequences by cumulative score | More search, higher cost |
| Sampling | Draws a token from the distribution | Produces varied outputs |
Suppose two candidate first tokens have probabilities 0.60 and 0.40. If their best continuations have probabilities 0.50 and 0.95 respectively, the prefixes score 0.30 and 0.38. A beam of width two can keep the second path alive. When sampling, lowering a positive temperature sharpens the distribution and raising it spreads probability more evenly.
2. From encoder–decoder attention to Q, K and V ☆ #
Early recurrent encoder–decoder models compressed the source into one fixed-size vector. Attention lets each decoder step score the available encoder states and take a weighted average of them. The weights can change as the decoder moves through the output.
A Transformer obtains a query (what a position is looking for), a key (how a position can be matched) and a value (the information it contributes) through learned projections. Dot products match queries with keys. Divide scores by the square root of the key dimension to control their scale, then apply softmax across available keys.
\[ \operatorname{Attention}(Q,K,V)= \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V \]The mask \( M \) assigns a large negative score, conceptually negative infinity, to disallowed positions.
| Attention | Queries | Keys and values | Which tokens can contribute? |
|---|---|---|---|
| Encoder self-attention | Encoder sequence | Same encoder sequence | All non-padding input positions |
| Causal decoder self-attention | Decoder sequence | Same decoder sequence | Current and earlier decoder positions, subject to padding |
| Encoder–decoder cross-attention | Decoder states | Encoder outputs | Available source positions |
Attention shapes #
For 10 tokens and a model width of 512 split into 8 equal heads, a common setup gives each head a query, key and value vector of width 64 per token. Each self-attention head forms a 10-by-10 query–key score matrix. Heads use separate projections. Their outputs are concatenated and projected back to the model width. Standard dense self-attention forms a number of scores proportional to the square of sequence length.
3. Transformer blocks #
Positional representations supply word-order information. Multi-head attention mixes information across tokens. A position-wise feed-forward network then transforms each token representation. Residual connections and layer normalisation help the network train. Encoder-only models support bidirectional representations, decoder-only models generate autoregressively, and encoder–decoder models combine source encoding and conditional generation.
4. BERT and contextual embeddings ☆ #
BERT uses a bidirectional Transformer encoder. Masked language modelling trains it to predict selected tokens from the available surrounding text. Original BERT also used next sentence prediction during pretraining. You can fine-tune a sequence-level head for classification or a token-level head for tagging and extractive question answering.
A static embedding gives bank one vector. A contextual encoder gives bank in “the river flooded the bank” a different representation from bank in “the bank approved the loan”. If a word splits into multiple subword tokens, make the choice of first piece or pooled representation explicit when comparing words.