MODULE 2 · LESSON 8 · 14 MIN
The Transformer Architecture Explained
By Siten Sanghvi · Published · Updated
A transformer is a stack of repeated layers. In a typical layer, attention lets every position mix in information from the positions it is allowed to read, and a small feed-forward network then transforms each position on its own. Position information has to be supplied, and residual connections and normalization help deep stacks train. Many widely used language models are built this way, with variations. The name describes a design. It does not guarantee understanding, truth or reliable recall.
In 2017, researchers mostly at Google published "Attention Is All You Need" (Vaswani et al.). It introduced the transformer for translation and sentence parsing. This lesson builds on the query, key and value idea in Tokens, Embeddings, and Context Windows Explained.
The problem it addressed
Before transformers, leading language models were recurrent networks, including LSTM variants, where each step depends on the previous one. The original paper names two costs: no parallel computation within a training example, and long paths between distant positions (Sections 1 and 4). Self-attention (each position weighing others in its sequence; explained next) connects any two positions in one step, and the paper reports faster training on translation. The price is that attention compares every position with every other, so its work per layer grows with the square of the sequence length (the paper's Table 1).
A shorter path makes long-range links easier to learn, not guaranteed recall. On the tasks in one long-input study, accuracy depended on where the evidence sat, with weaker use of the middle (Lost in the Middle).
Attention in one picture
For each position, attention produces a weighted mix of information from other positions. Learned query and key projections give the weights, the value vectors are what gets mixed, and a mask decides which positions may be read. The scores become weights that add up to 1 over the allowed positions.
Take "The company deposited funds at the bank." In a left-to-right model, the final word "bank" can read earlier words only. After attention, its representation can reflect "deposited" and "funds" in a way the plain lookup of "bank" could not. Weights are learned and differ by head and layer.
Multi-head attention
A layer runs several attention calculations (heads) side by side, each with its own learned projections, and combines the outputs. The original base model used 8; one head scored lower in its translation test, and so did too many (Section 6.2).
It is tempting to say each head owns one grammar rule. The evidence is more modest: some heads look related to sentence structure, and a later study found a few specialized heads did most of the work; pruning 38 of 48 encoder heads cost only 0.15 BLEU (a translation-quality score) in one setting (Voita et al.).
One transformer layer
An encoder layer, or a layer in a decoder-only model, has two sub-layers, as in the original design. (The original decoder layer adds a third, cross-attention to the encoder's output, covered below.)
- Multi-head attention mixes information across the positions a position may read.
- A feed-forward network is applied to each position separately, with the same weights at every position.
Around each sub-layer the original adds a residual connection (the sub-layer's output is added to its input) and then layer normalization. Residual learning was introduced to make much deeper networks easier to optimize (ResNet). Where normalization sits changes how easily a deep stack trains: "pre-norm" (inside the residual branch) has better-behaved gradients at the start and can skip the warm-up, a stage of small training steps, that the original placement needed (Xiong et al.). GPT-3 uses pre-normalization (Brown et al.).
The model stacks many same-shaped layers, each with its own learned weights. Depth varies widely (published examples, checked 2026-11-09):
| Model | Layers |
|---|---|
| Original Transformer (base) | 6 per stack |
| GPT-3 smallest / largest | 12 / 96 (Table 2.1) |
| Llama 3 8B / 70B / 405B | 32 / 80 / 126 (paper) |
These are examples, not a typical value; one scaling study found that, at a given size, depth versus width had minimal effect on loss within a wide range, so layer count alone is a weak guide.
EXHIBIT 08 / MASK
Explore the mechanismWho can read whom?
Attention mixes positions. The mask sets the boundary.
Attention: Mixes allowed positions.
Causal visibility; these are allowed connections, not attention weights or an explanation of a model’s answer.
Inspect the example data and reasoning
| Element | What to notice |
|---|---|
| Layer sketch | Attention → add-back → norm; feed-forward → add-back → norm. |
| Encoder-decoder note | The original decoder adds a cross-attention sublayer. |
| Selected row can read | 1, 2, 3 |
Illustrative masks. Attention weights alone do not explain an answer. Encoder-decoder cross-attention is additional.
Read the mechanism without interacting
- Attention
- Mix information across the positions the mask permits.
- Feed-forward
- Transform each position separately, with add-back paths around the sublayers.
- Masks
- A five-token causal mask permits 15 cells; full visibility permits 25; a three-token prefix permits 18.
Read the five-token sentence one position at a time. A causal row never reads a later token.
Try explaining it: If words are appended, can an earlier causal position read them?
Position information
Attention over a set of vectors with no mask does not use order by itself. With no recurrence, the original design adds positional encodings to the input embeddings so the model can use order (Section 3.5). "The dog bit the man" and "The man bit the dog" need that signal to be told apart.
Designs vary. The original used fixed sine and cosine patterns; learned position embeddings gave nearly identical translation results. Rotary position embeddings (RoPE), used by Llama 3, rotate vectors by position inside attention so the score reflects relative distance (RoFormer).
Encoder, decoder and both
The same layer ideas are arranged in different ways. A major distinguishing factor is the mask, meaning which positions may be read (T5 paper, Figure 4).
- Encoder-decoder, as in the original and T5: the encoder reads the whole input with fully visible attention; the decoder writes output left to right and reads the encoder's output through cross-attention.
- Encoder-only, as in BERT: every position can read the whole input, both sides. BERT used a masked-word objective (described in the T5 paper) and was evaluated on understanding tasks such as language inference and question answering (BERT). The T5 paper describes this style as suited to classification and span prediction rather than generative tasks like translation.
- Decoder-only: positions read only earlier positions, and the model generates by predicting the next token and appending it. GPT-3 is described as an autoregressive (next-token) language model (paper); Llama 3 is described as a standard Transformer (paper), and the Hugging Face Llama configuration describes its hidden layers as a "Transformer decoder" (docs).
These pairings are conventions, not rules: the GPT-3 paper also evaluates its model on classification-style and translation tasks by prompting alone. Closed products often do not publish their architecture, so do not assume it from the brand.
Why transformers spread, and where they stop
- Parallel training. Attention processes a training sequence's positions together, so the original trained faster. In the plain loop, generating text still adds one token at a time; BT-L09 covers the detail.
- Smooth scaling trends. Language-model test loss (how wrong the predictions are on held-out text) followed smooth trends as size, data and compute grew, with network shape mattering little within a broad range (Kaplan et al.). Later work found that for a fixed training compute budget, model size and training tokens should be scaled together (Chinchilla). Lower loss is not, by itself, a better result on your task.
- Other domains. A transformer on image patches matched strong convolutional image networks after very large pre-training (ViT). AlphaFold 2 mixes attention-based and other components (Jumper et al.).
- Not the only option. Mamba is a published attention-free alternative reporting competitive language results (Mamba).
Try it
Mask drill (pen and paper). Draw a 5-by-5 grid for "The dog bit the man." Rows are the reading position, columns the position it may read.
- Left-to-right: fill cells at or before each row. Count them.
- Fully visible (BERT-style): fill everything. Count them.
- Prefix model, first three tokens as prefix: the three prefix rows read the whole prefix; each of the last two rows reads the prefix and later positions up to itself. Count them.
Check yourself: 15, 25 and 18. If you append ten words to a left-to-right prompt, no earlier row changes in that layer, because none can read ahead. That is what lets implementations reuse earlier computation while generating; BT-L09 covers it.
A caution on attention maps. A heat map of attention weights is tempting evidence for why a model answered as it did, but attention weights can disagree with other importance measures such as gradients (how sensitive the output is to each input), and different weightings can give the same prediction (Jain and Wallace). Others reply that it depends on how explanation is defined and tested (Wiegreffe and Pinter). Treat a map as a clue to test with controlled input changes.
The takeaway
An encoder or decoder-only transformer layer is attention (mix information across allowed positions) then a feed-forward network (transform each position), wrapped with residual connections and normalization, and stacked with separate weights per layer. Position information has to be supplied. Encoder, decoder and encoder-decoder designs differ in which positions may be read (a major distinguishing factor). Layer counts are examples, not a ranking; attention weights alone do not establish why a model answered, and the design guarantees neither understanding nor reliable recall.
Related lessons
- How Neural Networks Actually Work (Without the Math) → — the layers and weights a transformer builds on.
- Tokens, Embeddings, and Context Windows Explained → — the tokens, embeddings and attention this lesson assembles.
- Pre-Training, Fine-Tuning, and RLHF — The Three Phases → — how the weights are learned.
Up next
Inference: How a Model Generates a Response →
The next lesson follows a trained model at run time: how a prompt becomes a response, and which choices in that loop change what you see.
VISUAL FIELDNOTES / 08
Keep the big picture.
A one-page visual companion. Save it, print it, or explain it to someone else.
View the full-size sheet ↗Who can read whom?
Attention mixes positions. The mask sets the boundary.
One US Letter page · Vector artwork · Fits A4 when printed to fit
Read the key points as text
- Attention
- Mix information across the positions the mask permits.
- Feed-forward
- Transform each position separately, with add-back paths around the sublayers.
- Masks
- A five-token causal mask permits 15 cells; full visibility permits 25; a three-token prefix permits 18.
Remember: Mix information across the positions the mask permits.
Try it: Read the five-token sentence one position at a time. A causal row never reads a later token.
Recall: If words are appended, can an earlier causal position read them?
OPTIONAL CHECK
Check your understanding.
The optional check requires JavaScript. You can continue reading the lesson.
A colleague says a transformer never forgets its input because attention connects every position directly. What is the most accurate reply?
Inside one attention head, what produces the weights used to mix information from other positions?
A teammate says each attention head in a layer is guaranteed to track one grammar rule. What does the evidence support?
In an encoder layer or a decoder-only layer, which statement about the two sub-layers is accurate?
Why does each sub-layer's output get added back to its input in a deep stack?
A slide says: 'Loss falls smoothly as compute grows, so a bigger transformer is always better.' What is the best correction?
A design uses an unmasked attention layer over word vectors and nothing marks position. Two prompts contain the same words in different order. What is the issue?
Which pairing is the conventional one in this lesson's examples (conventions, not rules)? Task one: classify a support ticket using the whole text. Task two: draft a reply token by token. Task three: translate a paragraph.
You append ten words to a prompt for a left-to-right transformer. In a given layer, what happens to the internal representation of an earlier word?
An analyst shows an attention heat map and says, 'This proves why the model refused the request.' What is the best response?
Quiz complete
YOUR LEARNING
Keep your place.
Your progress is saved on this device.