Skip to the content

fatehi.devx2Learning

Deep learning

Transformers

A network built from attention and feed-forward layers with residual connections and normalisation: an encoder stack, a decoder stack, or both.

The pieces put together

A Transformer is a stack of identical layers, each made of two kinds of sublayer: multi-head attention, in which every position reads the others, and a feed-forward layer, which works on each position on its own. Every sublayer sits on a residual connection with a layer normalisation. Below the stack, embeddings and a position encoding turn tokens into vectors; above it, a linear layer and a softmax turn vectors into probabilities.

The feed-forward sublayer is two linear layers with an activation between, applied to every position with the same weights; the middle is wider than the model, four times in the original:

FFN(x)=max(0,xW1+b1)W2+b2

x is one position’s vector, of width d; W1 of shape (d, 4d) and W2 of shape (4d, d), b1 and b2 their biases; max(0, ·) is the ReLU.

Three shapes

The original is an encoder-decoder: an encoder stack of self-attention reads the input; a decoder stack writes the output, with masked self-attention over what it has written and cross-attention to the encoder. Later models kept one half. Encoder-only models (BERT, 2018) read text to understand it. Decoder-only models (the GPT family, and most large language models since) drop the encoder and the cross-attention and write one token after another.

Writing: beam search

A decoder gives probabilities for the next token; to write a whole sentence it must choose. Taking the most probable token each time (greedy decoding) can lead into a dead end. Beam search keeps the k best partial sentences, scored by the sum of the logs of their tokens’ probabilities, extends each by every possible next token, and keeps the k best again.

Beam search with two beams (the paper used four). At each step both kept sentences are extended and the two best are kept; at step 3 both come from the first beam.

Test yourself

  1. What does the feed-forward sublayer do that attention does not?

    It works on each position on its own, transforming its vector with two linear layers and a ReLU; attention is the only place where positions exchange information.

  2. What does a decoder-only model leave out of the original Transformer?

    The encoder stack and the cross-attention; it keeps masked self-attention and the feed-forward layers and writes one token after another.

  3. Why keep several beams rather than the single most probable token at each step?

    A word that looks best now can lead to a worse sentence later; keeping several partial sentences lets a choice that starts slightly worse win in the end.

Where it leads

Kept in this browser only, never sent.