LIVEยทThe trends shaping tomorrow's world.
AI

How Transformer Models Work

How a Transformer turns tokens into embeddings, uses multi-head self-attention, residual connections and feed-forward layers, and why it scales so well.

A Transformer is a neural network that processes a whole sequence at once and lets every token look at every other token to decide what matters. It does this with a mechanism called self-attention, stacked in identical blocks with feed-forward layers, residual connections and normalization. Introduced by Vaswani and colleagues in the 2017 paper "Attention Is All You Need" [1], it is the architecture underneath most modern language models and many image and audio models.

If you want the bigger picture of how chatbots use this machinery to generate text, start with our guide to how large language models work. This article goes one level down, into the block itself.

The problem Transformers solved

Before 2017, the leading models for language were recurrent neural networks (RNNs). An RNN reads text one token at a time and carries a running summary forward. That design has two costs. Training is hard to parallelize, because step 50 has to wait for step 49. And information from early in a long sentence has to survive many hand-offs to influence the end.

Attention first appeared as a patch on that design. In 2014, Bahdanau, Cho and Bengio argued that squeezing a whole source sentence into one fixed-length vector was a bottleneck for translation. They let the model "(soft-)search" the source sentence for the parts relevant to each output word [2].

The 2017 Transformer paper went further and removed recurrence entirely. Its authors described a model "based solely on attention mechanisms" and reported that it trained faster and parallelized better than recurrent or convolutional alternatives [1]. Their big English-to-French model trained for 3.5 days on eight NVIDIA P100 GPUs [1].

The path of a token through a Transformer

The diagram below follows one layer stack from input to output. Each stage is explained in the sections after it.

1. Tokens become embeddings

Text is first split into tokens, which are words or pieces of words. Each token ID is looked up in an embedding table and becomes a vector of numbers. In the original paper's base model, every embedding and every sublayer output has 512 dimensions, a size the authors call d_model [1].

These vectors start out representing a token in isolation. The word "bank" gets the same starting vector whether the sentence is about rivers or money. The job of the layers that follow is to rewrite each vector using context.

2. Positional encoding adds word order

Attention on its own has no sense of order. Shuffle the tokens and the raw attention math gives the same result. So the model adds position information to each embedding.

The original Transformer used fixed sine and cosine waves of different frequencies, one pattern per position, added directly to the embeddings [1]. The authors reported that learned position embeddings gave nearly identical results [1]. Later work introduced alternatives such as Rotary Position Embedding (RoPE), which rotates query and key vectors by an angle tied to position, so attention scores depend on how far apart two tokens are [7].

3. Multi-head self-attention mixes in context

This is the core of the design. For every token, the model computes three vectors by multiplying its embedding by learned weight matrices:

  • Query (Q): what this token is looking for.
  • Key (K): what this token offers to others.
  • Value (V): the information it passes along if selected.

Each token's query is compared with every token's key using a dot product. The scores are divided by the square root of the key dimension, passed through a softmax to turn them into weights that sum to 1, and used to take a weighted average of the value vectors. The paper writes this as Attention(Q, K, V) = softmax(QKแต€ / โˆšd_k)V [1].

The scaling step is there for a practical reason. The authors suspected that with large vectors, raw dot products grow big, which pushes the softmax into regions where gradients become tiny and learning stalls. Dividing by โˆšd_k counteracts that [1].

"Multi-head" means the model runs several attention operations in parallel, each with its own learned Q, K and V projections. The original base model used 8 heads, each working in 64 dimensions, then concatenated and projected the results back to 512 [1]. Different heads are free to learn different relationships, for example one tracking which noun a pronoun refers to and another tracking nearby words. Researchers can't always say what a given head does, so treat those examples as illustrations rather than a fixed rule.

An analogy: think of each token as a person at a meeting holding a question card (query), a name tag (key) and a set of notes (value). Everyone reads everyone's name tag, decides whose notes answer their question, and writes a summary weighted toward those people. Multi-head attention is several such meetings running at once on different topics.

4. Add & norm keeps deep stacks trainable

After attention, the block adds the sublayer's input back to its output (a residual connection) and then applies layer normalization. The original paper defines each sublayer's output as LayerNorm(x + Sublayer(x)) [1].

The residual path gives gradients a direct route back through dozens of layers. Normalization keeps the scale of activations stable. Without these two pieces, very deep Transformers are hard to train.

Where the normalization sits turned out to matter. The 2017 design normalizes after the residual addition ("Post-LN"). A 2020 analysis showed that placing normalization inside the residual branch, before each sublayer ("Pre-LN"), gives well-behaved gradients at initialization and can remove the need for a learning-rate warm-up stage [6]. Many later models use the Pre-LN arrangement. The diagram shows the original Post-LN layout.

5. The feed-forward network works on each token

Next comes a small two-layer neural network applied to each token's vector separately. In the original paper it expands the vector from 512 to 2,048 dimensions, applies a ReLU activation, and projects back down: FFN(x) = max(0, xWโ‚ + bโ‚)Wโ‚‚ + bโ‚‚ [1].

Attention moves information between tokens. The feed-forward layer transforms the information within each token. Much of a Transformer's parameter count lives in these layers.

A second add & norm follows, and the block is done.

6. Repeat N times, then predict

The output of one block is the input to the next. The original encoder and decoder each stacked N = 6 identical blocks [1]. Modern large models stack many more; the exact numbers vary by model and aren't always disclosed.

For a language model, the final vectors go through a linear layer and a softmax to produce a probability for every token in the vocabulary. The model picks the next token, appends it, and runs again. Our LLM explainer covers that generation loop in detail.

Encoder, decoder, or both

The 2017 Transformer was built for translation, so it had two halves [1]:

  • An encoder that reads the full source sentence with unrestricted self-attention.
  • A decoder that generates the translation. Its self-attention is masked so a position can't see later positions, and it has an extra attention layer that looks at the encoder's output.

Later models kept one half or the other.

Variant

Attention pattern

Typical job

Example from the research record

Encoder-only

Every token sees every other token

Understanding: classification, search, tagging

BERT, pretrained using left and right context [3]

Decoder-only

Masked: each token sees only earlier tokens

Generation: text, code, chat

GPT-3, an autoregressive model with 175 billion parameters [4]

Encoder-decoder

Encoder unmasked, decoder masked plus cross-attention

Sequence-to-sequence: translation, summarization

The original Transformer [1]

The masking in decoder-only models is what makes them generators. During training, the model sees a whole sentence but each position must predict its next token using only what came before. At inference time, that is exactly the situation it faces.

Not just text

Nothing in the block is specific to language. It operates on a sequence of vectors. The Vision Transformer (ViT) showed that "a pure transformer applied directly to sequences of image patches" can perform well on image classification when pretrained on large datasets [5]. The same idea lets one model take text, images and audio as input, which is the basis of multimodal AI and much of modern computer vision.

Why the design scales so well

Three properties explain why Transformers took over.

Parallel training. All positions in a sequence are processed at once. The paper's comparison table lists self-attention as needing a constant number of sequential operations per layer, versus a number that grows with sequence length for recurrent layers [1]. That maps well onto GPUs and other accelerators built for large matrix multiplications; see our explainer on AI chips, CPUs, GPUs and TPUs.

Short paths between distant tokens. Any token can attend directly to any other token in one step. Information doesn't have to pass through every intermediate position.

Predictable gains from scale. Kaplan and colleagues reported in 2020 that Transformer language model loss falls as a power law as model size, dataset size and training compute increase, with some trends spanning more than seven orders of magnitude [10]. They also found that details such as width versus depth mattered little within a wide range [10]. That predictability gave labs a reason to keep building bigger models.

Limitations and costs

Attention is quadratic in sequence length. Every token compares itself with every other token, so the work and memory grow with the square of the sequence length. The original paper lists self-attention's per-layer complexity as O(nยฒยทd), where n is the sequence length and d the vector size [1]. Doubling the context roughly quadruples the attention cost. This is a major reason long context windows are expensive.

Memory traffic, not just math. The FlashAttention authors argued that attention is often slowed by reading and writing data between a GPU's high-bandwidth memory and its on-chip SRAM. Their exact attention algorithm uses tiling to cut that traffic [8]. It speeds things up without changing what the model computes.

The KV cache at inference. When a decoder generates text, it stores the keys and values for every previous token so it doesn't recompute them. That cache grows with every token and every concurrent user. The vLLM team showed that managing it like an operating system manages virtual memory pages improved serving throughput by 2 to 4 times over the systems they tested, at similar latency [9]. Our guide to AI training vs inference explains why serving costs are their own engineering problem.

No built-in truth check. A Transformer language model learns statistical patterns in its training data. Nothing in the block verifies facts, which is one root of AI hallucinations.

What to watch

Researchers continue to modify nearly every component: position schemes like RoPE [7], normalization placement [6], and attention implementations like FlashAttention [8]. These are refinements to the block rather than replacements for it.

Whether a different architecture eventually displaces the Transformer is an open question, and we're not aware of a consensus forecast from the sources reviewed here. For now, if you understand the five steps in the diagram (embed, add position, attend, transform, repeat), you understand the core of most large AI models in use.

Frequently asked questions

What does "attention" actually mean in a Transformer?

It is a learned weighting. For each token, the model scores how relevant every other token is, turns those scores into weights with a softmax, and takes a weighted average of their value vectors [1]. The result is a new representation of the token that includes context from the rest of the sequence.

Why is it called "Attention Is All You Need"?

The 2017 paper showed that a translation model could drop recurrence and convolution and rely on attention plus simple feed-forward layers [1]. Earlier systems used attention as an add-on to recurrent networks [2]. The title signals that attention alone was enough.

What is the difference between self-attention and multi-head attention?

Self-attention is one attention operation where queries, keys and values all come from the same sequence. Multi-head attention runs several of those operations in parallel with different learned projections, then combines them [1]. The original base model used 8 heads.

Are GPT-style models and BERT the same architecture?

They share the same building block but use different halves of the original design. BERT is encoder-only and attends in both directions, which suits understanding tasks [3]. GPT-style models are decoder-only with masked attention, which suits generating text one token at a time [4].

Why do long prompts cost more?

Attention compares every token with every other token, so its cost grows with the square of the sequence length [1]. During generation, the model also keeps a key-value cache that grows with each token [9]. Both push up compute and memory per request.

Do Transformers understand language?

They build contextual representations that are very useful for prediction, translation and generation. Whether that counts as understanding is a philosophical debate. Practically, they have no built-in mechanism to check facts, so outputs need verification.

Sources

  1. Attention Is All You Need, Vaswani et al., arXiv, 2017 (v7, 2023).
  2. Neural Machine Translation by Jointly Learning to Align and Translate, Bahdanau, Cho, Bengio, arXiv, 2014.
  3. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, Devlin et al., arXiv, 2018.
  4. Language Models are Few-Shot Learners, Brown et al., arXiv, 2020.
  5. An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, Dosovitskiy et al., arXiv, 2020.
  6. On Layer Normalization in the Transformer Architecture, Xiong et al., arXiv, 2020.
  7. RoFormer: Enhanced Transformer with Rotary Position Embedding, Su et al., arXiv, 2021.
  8. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, Dao et al., arXiv, 2022.
  9. Efficient Memory Management for Large Language Model Serving with PagedAttention, Kwon et al., arXiv, 2023.
  10. Scaling Laws for Neural Language Models, Kaplan et al., arXiv, 2020.