Skip to content
30 November 2026 An independent technology publication
Guide

Transformer architecture in 2027: 7 Important diagrams that make it click

The transformer architecture explained in 7 diagrams: attention, grouped-query attention, positions, KV cache costs and the design changes behind 2027 models.

Transformer architecture in 2027: 7 Important diagrams that make it click, DevQuarry featured image

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.

Transformer architecture in 2027 explained with diagrams, DevQuarry featured image

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 typeWork per layerSteps that must run in sequenceLongest path between two tokens 
Self-attentiongrows with n² · d11
Recurrent (RNN)grows with n · d²nn
Convolutiongrows with k · n · d²1log 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

SettingBase modelBig model 
Layers in encoder and decoder6 each6 each
Vector size (d_model)5121,024
Feed-forward size2,0484,096
Attention heads816
Parameters65 million213 million
Training12 hours on 8 P100 GPUs3.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

Decoder-only transformer block diagram read from the bottom up: token IDs, token embeddings with positions added via RoPE, then N repeated blocks of RMSNorm, masked self-attention, RMSNorm and a feed-forward network with residual connections, ending in a final norm and next-token softmax probabilities.

The diagram shows a decoder-only transformer, the layout used by GPT-style language models. Reading it from the bottom:

  1. Text is split into tokens, and each token ID becomes a vector through an embedding table.
  2. The vectors pass through N identical blocks. Llama 3 8B has 32 of them; Llama 3 405B has 126.
  3. Inside each block, an attention layer lets each token gather information from earlier tokens.
  4. A feed-forward network then processes each token’s vector on its own.
  5. Each sub-layer is wrapped in a residual connection, so its output is added to its input instead of replacing it.
  6. After the last block, a final projection turns each vector into a score for every word in the vocabulary.
  7. 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.

VariantWhat it seesTypical useExamples 
Encoder-onlythe whole input at once, in both directionsclassification, search embeddingsBERT and its descendants
Decoder-onlyonly earlier tokens (causal mask)text generation, chat, codeGPT series, Llama, Qwen, DeepSeek
Encoder-decoderencoder reads, decoder writestranslation, summarisationthe 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

Self-attention in the transformer architecture: queries, keys, values and softmax weights

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:

  1. Score: take the dot product of its query with every key. A high score means a good match.
  2. 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.
  3. Normalise: apply softmax so the scores become weights that sum to 1.
  4. 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:

bash
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

Comparison of multi-head, grouped-query and multi-query attention. Eight query heads stay separate in all three; they share 8, then 4, then 1 key-value head. KV cache for Llama 3 8B at 131,072 tokens falls from 64 GiB to 16 GiB to 2 GiB.

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 typeQuery headsKey-value headsKV cacheQuality 
Multi-head (MHA)manysame as query headslargestbaseline
Grouped-query (GQA)manya few groups4 to 16 times smallerclose to MHA
Multi-query (MQA)many1smallestcan 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 contextMHA (32 KV heads)GQA (8 KV heads)MQA (1 KV head) 
1,0240.50 GiB0.12 GiB0.02 GiB
8,1924 GiB1 GiB0.12 GiB
32,76816 GiB4 GiB0.5 GiB
131,07264 GiB16 GiB2 GiB
Bar chart of KV cache memory per sequence for a Llama 3 8B shape at 1,024 to 131,072 tokens, comparing MHA, GQA and MQA. At 131,072 tokens MHA needs 64 GiB, GQA 16 GiB and MQA 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

Heatmap of sinusoidal positional encoding from the original transformer: 64 sequence positions by 128 embedding dimensions, sines in dimensions 0 to 63 and cosines in 64 to 127, with frequencies running fast on the left to slow on the right.

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.

MethodUsed inHow it worksLong-context behaviour 
Sinusoidal, addedoriginal transformerfixed sine and cosine pattern added to embeddingsweak beyond training length
Learned, addedBERT, GPT-2a trained vector per positioncannot go past the trained maximum
Rotary (RoPE)Llama, Qwen, Mistral and most 2024 to 2026 LLMsrotates Q and K by a position-dependent anglecan 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

Share of compute spent on attention as context grows in a 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 lengthShare of compute in the attention matrix 
512 tokens1.0%
2,048 tokens3.7%
8,192 tokens13.3%
32,768 tokens38.1%
131,072 tokens71.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

Table comparing the 2017 original transformer with a typical 2026 to 2027 model across layout, normalisation, positions, attention, feed-forward, context length and parameter size.

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.

Part2017 originalTypical 2026 to 2027 model 
Overall layoutencoder plus decoderdecoder only
NormalisationLayerNorm after each sub-layerRMSNorm before each sub-layer
Positionssinusoidal, added to embeddingsrotary (RoPE) on queries and keys
Attentionmulti-headgrouped-query or compressed latent attention
Feed-forwardReLU, 2 matricesSwiGLU, 3 matrices, often mixture of experts
Context lengtha few hundred tokens128K to 1M tokens
Size65M to 213M parameters1B to over 1T parameters
Training dataabout 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:

SettingLlama 3 8BLlama 3 70BLlama 3 405B 
Layers3280126
Model dimension4,0968,19216,384
Feed-forward dimension14,33628,67253,248
Attention heads3264128
Key-value heads888
Vocabulary128,000128,000128,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:

  1. Prefill: the model reads the whole prompt in one parallel pass and fills the KV cache.
  2. Decode: it predicts one token, appends it, and runs again, reusing the cache so only the new token needs fresh computation.
  3. 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:

DomainHow the input becomes tokensExample 
Imagessplit into patches, each patch becomes a tokenVision Transformer (ViT)
Image generationlatent patches denoised step by stepdiffusion transformers such as the one in Stable Diffusion 3
Audio and speechshort slices of a spectrogramWhisper-style speech models
Videopatches across space and timetext-to-video models
Multimodal chatimage patches and text tokens in one sequencevision-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 LSTMCNNTransformer architecture 
Built-in assumptionorder matters, process step by stepnearby inputs matter mostany input can relate to any other
Parallel trainingpoor, one step at a timegoodvery good
Long-range linksweak, signal fades over many stepsneed many stacked layersdirect, one attention step
Cost as input growslinearlinearquadratic in attention
Data neededmoderatemoderate, strong for imageslarge; weak assumptions need more data
Where it still winsstreaming and tiny devicessmall image datasets, edge visionalmost 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 fileWhat it means in the diagrams 
num_hidden_layershow many blocks are stacked (Diagram 1)
hidden_sizethe vector size for each token
num_attention_headsquery heads (Diagram 3)
num_key_value_headskey-value heads; fewer than query heads means GQA
intermediate_sizethe feed-forward width (Diagram 5)
rope_thetathe rotary position base frequency (Diagram 4)
max_position_embeddingsthe longest context the model was set up for
num_experts, num_experts_per_tokpresent 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:

  1. Implement single-head attention in NumPy, as in the snippet above, and check the weights sum to 1.
  2. Build a tiny character-level GPT in PyTorch. Andrej Karpathy’s Neural Networks: Zero to Hero course walks through this from scratch.
  3. Load a small open model and print its configuration. Match each number to the diagrams above.
  4. 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.

About the author Aradhya Chaudhary

Data Scientist | Freelancer | Speaker & Writer skilled in programming, development and building AI/ML backed systems.

More from Aradhya
Keep reading

More in AI & ML

All of AI & ML →