The transformer architecture is a neural network design that processes a sequence by letting every token look at every other token through a mechanism called attention. Stacks of identical blocks, each made of an attention layer and a small feed-forward network, turn input tokens into predictions. Almost every large language model you will use in 2027 is a transformer, and so are most modern image, audio and video models.
This guide explains the architecture through seven diagrams instead of pages of equations. It starts with the 2017 original, walks through attention step by step, and ends with the changes that separate a 2017 transformer from the models being trained now: grouped-query attention, rotary positions, SwiGLU feed-forward layers and the memory cost of long context. The numbers in the charts come from published model configurations, worked through in a short script.

Key takeaways
- A transformer is a stack of identical blocks. Each block mixes information between tokens (attention) and then processes each token on its own (feed-forward network).
- Attention compares every token with every other token, so its cost grows with the square of the sequence length.
- Modern models keep the 2017 skeleton but swap almost every part: pre-normalisation, RMSNorm, SwiGLU, rotary position embeddings and grouped-query attention.
- For a Llama 3 8B shaped model, grouped-query attention cuts the memory needed to cache a 128K-token conversation from 64 GiB to 16 GiB.
- At 131K tokens of context, the attention matrix accounts for about 71% of the compute per token in that same model shape.
What is the transformer architecture?
The transformer was introduced in the 2017 paper “Attention Is All You Need” by Vaswani and colleagues at Google. It was built for machine translation and replaced the recurrent networks (RNNs and LSTMs) that read a sentence one word at a time.
The key idea was to drop recurrence entirely. Instead of passing a hidden state from word to word, every position in the sequence can read from every other position in a single step, using attention. That made training highly parallel on GPUs, and it let the model connect distant words without the signal fading along a long chain.
The original paper compared three kinds of layers. Its Table 1 is still the clearest summary of why attention won:
| Layer type | Work per layer | Steps that must run in sequence | Longest path between two tokens |
|---|---|---|---|
| Self-attention | grows with n² · d | 1 | 1 |
| Recurrent (RNN) | grows with n · d² | n | n |
| Convolution | grows with k · n · d² | 1 | log of n |
Here n is the sequence length, d is the size of each token’s vector and k is the convolution width. Attention needs only one step to connect any two tokens, and nothing has to wait for the previous word. The price is the n² term, which comes back later in this guide.
The original model in numbers
| Setting | Base model | Big model |
|---|---|---|
| Layers in encoder and decoder | 6 each | 6 each |
| Vector size (d_model) | 512 | 1,024 |
| Feed-forward size | 2,048 | 4,096 |
| Attention heads | 8 | 16 |
| Parameters | 65 million | 213 million |
| Training | 12 hours on 8 P100 GPUs | 3.5 days on 8 P100 GPUs |
| English to German (BLEU) | 28.4 |
The big model set a new record on the WMT 2014 English-to-German benchmark with 28.4 BLEU, at a fraction of the training cost of earlier systems. As a sanity check on the diagrams below, I computed the parameter count from the published settings. My script gives 63.1 million for the base model and 214.2 million for the big one, within a few percent of the paper’s figures.
Diagram 1: the transformer architecture at a glance

The diagram shows a decoder-only transformer, the layout used by GPT-style language models. Reading it from the bottom:
- Text is split into tokens, and each token ID becomes a vector through an embedding table.
- The vectors pass through N identical blocks. Llama 3 8B has 32 of them; Llama 3 405B has 126.
- Inside each block, an attention layer lets each token gather information from earlier tokens.
- A feed-forward network then processes each token’s vector on its own.
- Each sub-layer is wrapped in a residual connection, so its output is added to its input instead of replacing it.
- After the last block, a final projection turns each vector into a score for every word in the vocabulary.
- A softmax turns those scores into probabilities for the next token.
The residual connections matter more than they look. They give every block a direct path back to the input, so gradients flow through 100+ layers without vanishing. You can think of the stream of vectors as a shared scratchpad that each block reads from and writes a small update to.
Encoder, decoder or both?
The 2017 model had two halves: an encoder that read the source sentence and a decoder that wrote the translation. Later models kept only the half they needed.
| Variant | What it sees | Typical use | Examples |
|---|---|---|---|
| Encoder-only | the whole input at once, in both directions | classification, search embeddings | BERT and its descendants |
| Decoder-only | only earlier tokens (causal mask) | text generation, chat, code | GPT series, Llama, Qwen, DeepSeek |
| Encoder-decoder | encoder reads, decoder writes | translation, summarisation | the original transformer, T5 |
Decoder-only won for language models because one simple objective, predicting the next token, scales to any amount of text.
Diagram 2: how self-attention works in the transformer architecture

Attention is the heart of the transformer architecture, and it is easier to follow as a lookup. Each token asks a question, every token offers a label describing what it holds, and the model blends together the contents of the tokens whose labels best match the question.
Concretely, each token’s vector is multiplied by three learned matrices to produce three new vectors:
- a query (Q): what this token is looking for
- a key (K): what this token can offer
- a value (V): the information this token passes on if chosen
For one token, attention then runs four steps:
- Score: take the dot product of its query with every key. A high score means a good match.
- Scale: divide the scores by the square root of the key size (√64 = 8 in the original model). Without this, large dot products push the softmax into a region where gradients are tiny.
- Normalise: apply softmax so the scores become weights that sum to 1.
- Blend: multiply each value by its weight and add them up. The result is this token’s new vector.
The diagram uses the sentence “the cat sat on the mat” with illustrative weights to show the idea: when processing “sat”, the model might put most weight on “cat”, its subject. The weights in a real model are learned and much harder to read, but the mechanism is exactly this.
All of this fits in one line of maths, softmax(QKᵀ / √d_k) · V, and in a few lines of NumPy:
import numpy as np
def attention(Q, K, V, causal=True):
scores = Q @ K.T / np.sqrt(K.shape[-1]) # how well each query matches each key
if causal: # a decoder may only look backwards
scores = np.where(np.tril(np.ones_like(scores)) == 1, scores, -np.inf)
weights = np.exp(scores - scores.max(-1, keepdims=True))
weights /= weights.sum(-1, keepdims=True) # softmax: each row sums to 1
return weights @ V # blend the values
The causal mask is the only difference between an encoder’s attention and a decoder’s. It blocks each token from seeing tokens that come after it, which is what lets the model learn to predict the next word without cheating.
Diagram 3: multi-head and grouped-query attention

One attention pattern is not enough for a capable model, so the transformer architecture runs several at once. A token might need to track its grammatical subject, a name mentioned three paragraphs earlier and the closing bracket it must eventually match, all at once. Multi-head attention runs several attention operations in parallel, each with its own smaller Q, K and V projections, and joins their outputs.
The original base model split its 512-dimensional vectors into 8 heads of 64 dimensions each. Llama 3 8B uses 32 heads of 128 dimensions; Llama 3 405B uses 128.
Why grouped-query attention matters
When a model generates text, it stores the keys and values of every previous token so it does not recompute them for each new word. This store is the KV cache, and it is the main memory cost of long conversations.
Grouped-query attention (GQA), described by Ainslie and colleagues in 2023, lets several query heads share one key and value head. Llama 3 uses 8 key-value heads in every model size, whether it has 32 or 128 query heads. Multi-query attention (MQA) takes this to the limit with a single shared key-value head.
| Attention type | Query heads | Key-value heads | KV cache | Quality |
|---|---|---|---|---|
| Multi-head (MHA) | many | same as query heads | largest | baseline |
| Grouped-query (GQA) | many | a few groups | 4 to 16 times smaller | close to MHA |
| Multi-query (MQA) | many | 1 | smallest | can drop more |
To see what this means in memory, I computed the KV cache for one sequence using the Llama 3 8B shape (32 layers, 128-dimension heads, 16-bit values):
| Tokens in context | MHA (32 KV heads) | GQA (8 KV heads) | MQA (1 KV head) |
|---|---|---|---|
| 1,024 | 0.50 GiB | 0.12 GiB | 0.02 GiB |
| 8,192 | 4 GiB | 1 GiB | 0.12 GiB |
| 32,768 | 16 GiB | 4 GiB | 0.5 GiB |
| 131,072 | 64 GiB | 16 GiB | 2 GiB |

At 128K tokens, full multi-head attention would need 64 GiB just for one user’s cache, more than the 16 GB of 16-bit weights in the model itself. GQA brings that to 16 GiB. This is why most open models released since 2024 use GQA or a further compressed scheme, such as the multi-head latent attention in DeepSeek’s models.
Diagram 4: how a transformer knows word order

Attention on its own has no sense of order, which is a real gap in the transformer architecture. “Dog bites man” and “man bites dog” contain the same tokens, and without extra information the attention scores would be identical. Transformers fix this by adding position information to each token.
The original paper added a fixed pattern of sine and cosine waves to each embedding. The heatmap above is that exact pattern, computed for 64 positions and 128 dimensions, with the 64 sine dimensions on the left and the 64 cosine dimensions on the right. Each column is a wave of a different frequency. Within each half, the columns on the left change quickly from one position to the next and the columns on the right change slowly. Together they give every position a unique fingerprint, and nearby positions get similar fingerprints.
Modern models mostly use rotary position embeddings (RoPE), introduced by Su and colleagues. Instead of adding a pattern to the embedding, RoPE rotates each query and key vector by an angle that depends on its position. When two rotated vectors are compared, the result depends on the distance between them, which is what attention needs.
| Method | Used in | How it works | Long-context behaviour |
|---|---|---|---|
| Sinusoidal, added | original transformer | fixed sine and cosine pattern added to embeddings | weak beyond training length |
| Learned, added | BERT, GPT-2 | a trained vector per position | cannot go past the trained maximum |
| Rotary (RoPE) | Llama, Qwen, Mistral and most 2024 to 2026 LLMs | rotates Q and K by a position-dependent angle | can be stretched with scaling tricks |
Llama 3 sets the RoPE base frequency to 500,000, much higher than earlier models. That slows the rotation so positions stay distinguishable across very long contexts. Llama 3 was pre-trained at 8K tokens and then extended to 128K in a later training stage.
Diagram 5: feed-forward layers and normalisation in the transformer architecture
After attention mixes information between tokens, the second half of each block in the transformer architecture, the feed-forward network (FFN), works on each token alone. In the original transformer it was two linear layers with a ReLU in between, expanding 512 dimensions to 2,048 and back.
The FFN holds most of a transformer’s parameters. In the Llama 3 8B shape, each block has about 176 million FFN parameters against 42 million for attention. Much of what a model “knows” is believed to be stored in these layers, which is also why mixture-of-experts models replace exactly this part with many smaller expert networks. Our mixture of experts guide covers that design.
Two changes to this part of the block are now standard:
- SwiGLU activation. Proposed by Noam Shazeer in 2020, it uses three matrices instead of two and a gated activation. Llama 3 uses it in every model size.
- RMSNorm before each sub-layer. The original model normalised after each sub-layer (“post-norm”). Modern models normalise before attention and before the FFN (“pre-norm”), which makes deep stacks much easier to train. They also use RMSNorm, a simpler normalisation that skips mean-centring.
Diagram 6: why long context strains the transformer architecture

The n² term from the 2017 table is the reason long context is the hardest problem in the transformer architecture. Every new token must be compared with every token before it. For short prompts this barely matters, because the projections and feed-forward layers dominate the compute. As context grows, the attention matrix takes over.
I estimated the share of per-token compute spent on the attention scores themselves, for the Llama 3 8B shape, averaging over a causal sequence:
| Context length | Share of compute in the attention matrix |
|---|---|
| 512 tokens | 1.0% |
| 2,048 tokens | 3.7% |
| 8,192 tokens | 13.3% |
| 32,768 tokens | 38.1% |
| 131,072 tokens | 71.1% |
This is a back-of-the-envelope estimate that counts matrix multiplications only, but the trend is the point. At 128K tokens, most of the work goes into attention rather than into the parameters that store knowledge.
Engineers attack this cost from several directions:
- FlashAttention, introduced by Dao and colleagues in 2022, computes exact attention in tiles that fit in fast GPU memory, avoiding slow reads and writes of the full n × n matrix.
- Sliding-window and sparse attention let most layers look only at nearby or selected tokens.
- Compressed attention shrinks keys and values. DeepSeek reports that its V4 models, released in April 2026, need 27% of the per-token compute and 10% of the KV cache of its previous model at 1 million tokens, using new compressed attention schemes.
- State space models such as Mamba replace attention with a recurrent-style layer whose cost grows linearly. Several recent models mix a few attention layers with many linear-time layers.
Diagram 7: the transformer architecture in 2017 vs 2027

Put the original paper next to a current open model and the skeleton is the same: embeddings, a stack of attention and feed-forward blocks, residual connections and a final projection. Nearly every component inside has been replaced.
| Part | 2017 original | Typical 2026 to 2027 model |
|---|---|---|
| Overall layout | encoder plus decoder | decoder only |
| Normalisation | LayerNorm after each sub-layer | RMSNorm before each sub-layer |
| Positions | sinusoidal, added to embeddings | rotary (RoPE) on queries and keys |
| Attention | multi-head | grouped-query or compressed latent attention |
| Feed-forward | ReLU, 2 matrices | SwiGLU, 3 matrices, often mixture of experts |
| Context length | a few hundred tokens | 128K to 1M tokens |
| Size | 65M to 213M parameters | 1B to over 1T parameters |
| Training data | about 4.5M sentence pairs (EN-DE) | about 15T tokens for Llama 3 |
Llama 3 as a reference design
Llama 3 is a well-documented example of a modern dense transformer. From Meta’s Llama 3 paper:
| Setting | Llama 3 8B | Llama 3 70B | Llama 3 405B |
|---|---|---|---|
| Layers | 32 | 80 | 126 |
| Model dimension | 4,096 | 8,192 | 16,384 |
| Feed-forward dimension | 14,336 | 28,672 | 53,248 |
| Attention heads | 32 | 64 | 128 |
| Key-value heads | 8 | 8 | 8 |
| Vocabulary | 128,000 | 128,000 | 128,000 |
Plugging these settings into my parameter formula gives 8.03 billion for the 8B model and 406 billion for the 405B model. The architecture really is this regular: knowing six numbers lets you reconstruct the size of a frontier-scale model to within a percent.
How the transformer architecture is trained and used
The same transformer architecture runs in two very different modes: parallel training on whole sequences, and step-by-step generation that reuses a cache.
Training
During pre-training the model sees a long sequence and predicts every next token in parallel. Thanks to the causal mask, one forward pass over 8,000 tokens produces 8,000 predictions and 8,000 error signals. This parallelism is the main reason transformers replaced RNNs: an RNN must process those tokens one after another.
Training then usually continues in stages: instruction tuning on curated examples, preference tuning, and in recent models reinforcement learning on tasks with checkable answers. The architecture stays the same through all of them. Our guide to LLM distillation covers how smaller transformers are trained from larger ones.
Inference
Generation works one token at a time:
- Prefill: the model reads the whole prompt in one parallel pass and fills the KV cache.
- Decode: it predicts one token, appends it, and runs again, reusing the cache so only the new token needs fresh computation.
- Sampling: the next token is chosen from the probabilities, often with temperature or top-p settings.
Prefill is limited by raw compute; decoding is usually limited by memory bandwidth, because every step must read all the weights and the whole KV cache. That is why the KV cache numbers in Diagram 3 matter so much for serving costs.
The transformer architecture beyond text
The same transformer architecture now powers most areas of deep learning:
| Domain | How the input becomes tokens | Example |
|---|---|---|
| Images | split into patches, each patch becomes a token | Vision Transformer (ViT) |
| Image generation | latent patches denoised step by step | diffusion transformers such as the one in Stable Diffusion 3 |
| Audio and speech | short slices of a spectrogram | Whisper-style speech models |
| Video | patches across space and time | text-to-video models |
| Multimodal chat | image patches and text tokens in one sequence | vision-language models |
Our guide to diffusion models shows how transformers took over image generation as well.
Transformer architecture vs CNNs and RNNs
Before 2017, the two main families for sequences and images were recurrent networks and convolutional networks. Comparing them with the transformer architecture shows what each design assumes about the data.
| RNN or LSTM | CNN | Transformer architecture | |
|---|---|---|---|
| Built-in assumption | order matters, process step by step | nearby inputs matter most | any input can relate to any other |
| Parallel training | poor, one step at a time | good | very good |
| Long-range links | weak, signal fades over many steps | need many stacked layers | direct, one attention step |
| Cost as input grows | linear | linear | quadratic in attention |
| Data needed | moderate | moderate, strong for images | large; weak assumptions need more data |
| Where it still wins | streaming and tiny devices | small image datasets, edge vision | almost everything at scale |
The last two rows explain the trade-off. A transformer makes very few assumptions, so it needs more data to learn structure that a CNN gets for free. Once data and compute are plentiful, those weak assumptions become an advantage, because the model learns patterns a fixed design would miss. That is why the transformer architecture took over first in language, where text is abundant, and then in vision once large image datasets became common.
Reading a model card through the transformer architecture
The fastest way to make this guide useful is to read a real configuration file. Most open models publish one with fields like these:
| Field in a config file | What it means in the diagrams |
|---|---|
| num_hidden_layers | how many blocks are stacked (Diagram 1) |
| hidden_size | the vector size for each token |
| num_attention_heads | query heads (Diagram 3) |
| num_key_value_heads | key-value heads; fewer than query heads means GQA |
| intermediate_size | the feed-forward width (Diagram 5) |
| rope_theta | the rotary position base frequency (Diagram 4) |
| max_position_embeddings | the longest context the model was set up for |
| num_experts, num_experts_per_tok | present only in mixture-of-experts models |
With these numbers you can estimate parameter count, KV cache size per token and roughly how much memory a long conversation will need, using the same arithmetic behind the charts in this article.
Common misconceptions about the transformer architecture
- “Attention is the whole model.” In practice the feed-forward layers hold most of the parameters.
- “Attention weights explain the model’s reasoning.” They show where information moved in one layer, not why the final answer came out. Treat attention maps as hints.
- “Transformers understand word order naturally.” They do not; position has to be injected, and how it is done affects long-context quality.
- “Longer context is free once the model supports it.” Memory for the KV cache grows linearly and attention compute grows faster, as the charts show.
- “Every modern LLM is a plain transformer.” Many are mixture-of-experts transformers, and some mix in non-attention layers.
How to learn the transformer architecture hands-on
Reading diagrams gets you most of the way. Building one closes the gap. A practical order:
- Implement single-head attention in NumPy, as in the snippet above, and check the weights sum to 1.
- Build a tiny character-level GPT in PyTorch. Andrej Karpathy’s Neural Networks: Zero to Hero course walks through this from scratch.
- Load a small open model and print its configuration. Match each number to the diagrams above.
- Measure memory while generating with long prompts, and watch the KV cache grow.
The deep learning roadmap for 2027 places these exercises in a full learning plan.
FAQ
What is the transformer architecture in simple terms?
It is a neural network made of stacked blocks. In each block, an attention layer lets every token gather information from other tokens, and a feed-forward layer processes each token individually. Repeating this many times turns raw tokens into rich representations that can predict the next word or classify an input.
Why is it called a transformer?
The original paper named it after its job of transforming one sequence into another, such as an English sentence into German. The name stuck as the design spread to text generation, vision and audio.
What is the difference between attention and self-attention?
Self-attention is attention where the queries, keys and values all come from the same sequence, so tokens attend to each other. Cross-attention takes queries from one sequence and keys and values from another, as when a translation decoder attends to the encoded source sentence or an image model attends to a text prompt.
Why do transformers struggle with very long context?
Attention compares every token with every earlier token, so its compute grows with the square of the length, and the KV cache grows with every token stored. For a Llama 3 8B shaped model, the attention matrix uses about 71% of per-token compute at 131K tokens, and the cache needs 16 GiB per sequence even with grouped-query attention.
Will transformers still be used in 2027?
Yes. The leading open and closed models are transformers or transformer hybrids, and new work focuses on making attention cheaper rather than removing it. Linear-time alternatives such as state space models are mostly being combined with attention layers, not replacing them.
The architecture in one sentence
A transformer is a stack of blocks where tokens first share information through attention and then think on their own through a feed-forward network, repeated until the representation is good enough to predict what comes next. Everything else in this guide (multiple heads, grouped queries, rotary positions, compressed caches) is engineering to make that loop cheaper, deeper and longer.


