Turing Registry

How the Transformer Model Works

The Transformer was introduced in 2017 in "Attention Is All You Need" by Vaswani and colleagues at Google. It handles sequences such as text without recurrence (as in RNNs) or convolution (as in CNNs). Instead it relies on attention: every position in a sequence looks at every other position and decides how much each one matters. That one change made the architecture fast to train and good at long-range dependencies, and it now underlies nearly every large language model.

The parts

Input embeddings and positional encoding

Tokens are first turned into dense vectors by an embedding layer. Because attention by itself has no notion of order, a positional encoding is added to each vector so the model knows where in the sequence every token sits.

The encoder

The encoder is a stack of identical layers, each with two sub-layers:

  • Multi-head self-attention. Each position attends to every other position and weighs its relevance. Several attention "heads" run in parallel, each free to learn a different kind of relationship.
  • A position-wise feed-forward network. Two linear transformations with a non-linearity (originally ReLU) between them, applied to each position independently.

Each sub-layer is wrapped in a residual connection and layer normalization, which is what lets the stack go deep.

The decoder

The decoder stacks layers like the encoder's, with two changes. Its self-attention is masked, and a third sub-layer, cross-attention, sits between that and the feed-forward network:

  • Masked self-attention. A position may only attend to earlier positions, so the model cannot peek at the tokens it is about to predict.
  • Encoder-decoder (cross) attention. Each decoder position attends over the encoder's output. This is how a translation model looks back at the source sentence.

The output

A final linear layer and a softmax turn each decoder position's vector into a probability distribution over the vocabulary, from which the next token is chosen.

Why it won

  • An RNN must process a sequence one step after another; a Transformer processes every position at once during training, which suits GPUs.
  • Any two positions are one attention step apart, however far apart they are in the text, which helps with long-range dependencies.
  • The same architecture works for translation, summarization, classification and generation, and, with the right tokenization, for images, audio and video.

Where it went

The original paper was about machine translation, where it beat the RNN models of the day. Encoder-only descendants (BERT) became the standard for understanding text; decoder-only descendants (the GPT family and today's chat models) became the standard for generating it; and vision and multimodal Transformers carried the same idea well beyond language.