Transformers Explained: From RNNs to the Architecture Behind Modern LLMs
How sequence models evolved, why attention changed everything, and what actually happens inside a Transformer.
When I started exploring Large Language Models, one term kept appearing everywhere: Transformers.
GPT, Llama, Mistral and many other modern language models are built around Transformer-based architectures. I knew that, but I wanted to understand what actually happens inside one.
How does a model process a sentence? How do words relate to each other? How does it understand their positions? And how does everything eventually help it predict the next token?
So I went back to the beginning.
This is my attempt to connect the dots, starting with the architectures that came before Transformers and gradually building up to the architecture used by modern LLMs.
Prerequisite: A basic understanding of vectors, matrices, matrix multiplication and softmax will help. This article focuses on the architecture, rather than tokenization algorithms or training a model from scratch.
1. Before Transformers: RNNs and LSTMs
Before Transformers, Recurrent Neural Networks (RNNs) were widely used for sequence-processing tasks.
An RNN processes tokens one at a time, maintaining a hidden state that carries information from previous tokens.
For example:
The → cat → sat → on → the → matThe → cat → sat → on → the → mat
Its basic operation is:
The current hidden state depends on the current input and the previous hidden state.
This creates two major problems:
Sequential computation: The next hidden state depends on the previous one, limiting parallelism across sequence positions.
Vanishing gradients: During training, gradients can become extremely small as they propagate through many recurrent steps, making long-range dependencies difficult to learn.
LSTMs and GRUs improved information retention using gating mechanisms, but they still relied on recurrent computation.
Researchers needed a different approach.
2. Seq2Seq and the Introduction of Attention
Sequence-to-Sequence models introduced an encoder-decoder architecture.
The encoder processes the input sequence, while the decoder generates the output. This was particularly useful for machine translation.
Early Seq2Seq models often compressed the input into a fixed-size context vector, creating a bottleneck for longer sequences.
Attention helped address this problem.
Instead of relying only on one compressed representation, the decoder could access different encoder hidden states and give different importance to different input positions.
This allowed it to retrieve relevant information while generating each output token.
An important distinction: Attention existed before Transformers. The breakthrough of the 2017 Transformer paper was building an architecture around attention, without recurrent or convolutional layers.
3. Understanding Attention: Query, Key and Value
Let's consider:
"The animal crossed the road because it was hungry."
When processing "it", a model needs to understand its relationship with other words, particularly "animal".
This is where self-attention becomes useful.
But before understanding the mathematics, there's one basic thing to establish: the model doesn't directly perform attention on English words.
Text is first divided into tokens. Each token is assigned an integer ID. An embedding layer then maps these IDs to learned vectors.
For example:
"animal" → Token ID → Embedding vector "crossed" → Token ID → Embedding vector "it" → Token ID → Embedding vector"animal" → Token ID → Embedding vector "crossed" → Token ID → Embedding vector "it" → Token ID → Embedding vector
If each token embedding has 512 dimensions, we can stack the vectors into an input matrix:
Here, is the sequence length. This matrix is what enters the Transformer computation.
What are Query, Key and Value?
A useful analogy is a search engine:
Query (Q): What information am I looking for?
Key (K): What information can be matched against?
Value (V): What information should I retrieve?
The model generates these representations through three learned projections:
The attention operation is:
Let's break it down:
calculates similarity scores between Queries and Keys.
Dividing by controls the magnitude of the scores and helps avoid softmax saturation.
Softmax converts scores into attention weights.
Multiplying by produces a weighted combination of Value vectors.
A small numerical example
Suppose the Query for "it" is compared with the Keys of three preceding tokens: "animal", "road" and "crossed".
For simplicity, assume the scaled attention scores are:
| Token | Score |
|---|---|
| animal | 2 |
| road | 1 |
| crossed | 0 |
Applying softmax:
The resulting attention weights are approximately:
animal: 66.5%
road: 24.5%
crossed: 9%
The model then uses these weights to combine the corresponding Value vectors.
These are illustrative scores, not actual model outputs. The model learns the projections and resulting attention patterns during training.
The important idea is that a token can retrieve information from multiple positions rather than relying entirely on a previous hidden state.
4. Multi-Head Attention: Why Multiple Heads?
Would one attention operation be enough to capture all the relationships in a sentence?
The Transformer introduced Multi-Head Attention (MHA).
Instead of performing attention once, it performs multiple attention operations in parallel, each with its own learned Query, Key and Value projections.
Each operation is called an attention head.
The outputs are concatenated and passed through another learned projection:
Different heads can learn different attention patterns, although their roles aren't manually assigned.
A small tensor example
Suppose:
Batch size = 2
Sequence length = 4
Model dimension = 8
Number of heads = 2
The input shape is:
After splitting into two heads:
The dimensions now represent:
Batch × Heads × Sequence × Head dimensionBatch × Heads × Sequence × Head dimension
Each head performs its own attention computation. Their outputs are concatenated back into:
The output projection preserves the model dimension.
This becomes important later when studying attention kernels, KV cache and inference optimization.
5. Positional Encoding: How Does the Model Know Word Order?
Consider:
Dog bites man. Man bites dog.Dog bites man. Man bites dog.
Both sentences contain the same words, but their meanings are different.
Self-attention alone does not inherently encode sequence order. We need to provide positional information.
The original Transformer uses sinusoidal positional encoding:
Different dimensions use different frequencies to represent positions.
The positional encoding is added to the token embedding:
This gives the model both token information and positional information.
Modern LLMs often use Rotary Positional Embeddings (RoPE) instead. RoPE applies position-dependent rotations to Query and Key representations, allowing attention scores to incorporate relative position information.
6. Causal Masking: Why Can't GPT See Future Tokens?
Consider a model learning from:
"The cat sat on the mat."
Its objective is next-token prediction:
| Input | Target |
|---|---|
| The | cat |
| The cat | sat |
| The cat sat | on |
When predicting "sat", the model shouldn't be allowed to look at future tokens such as "on the mat".
This is why GPT uses causal masking.
For four tokens, the allowed attention pattern looks like this:
T1 T2 T3 T4 T1 1 0 0 0 T2 1 1 0 0 T3 1 1 1 0 T4 1 1 1 1T1 T2 T3 T4 T1 1 0 0 0 T2 1 1 0 0 T3 1 1 1 0 T4 1 1 1 1
We add a mask to the attention scores before softmax:
Blocked future positions receive a value of , so their softmax probability becomes zero.
An interesting distinction: causal masking doesn't prevent parallel computation during training. All positions can still be processed together because the mask controls information access, not execution order.
During inference, however, autoregressive token generation happens sequentially.
7. What Happens After Attention? FFN, Residual Connections and LayerNorm
Attention allows tokens to exchange information. But the resulting representations also need to be transformed.
This is the job of the Feed-Forward Network (FFN), also called an MLP.
The original Transformer uses:
For its base configuration, the dimensions are:
The representation expands into a larger feature space, passes through a nonlinear activation, and is projected back.
One distinction worth remembering:
Attention mixes information across token positions; FFN transforms features independently at each position.
Residual connections
Transformers can contain many stacked layers. Residual connections help make deep networks easier to optimize.
Instead of using only the transformed output, we add the original input back:
This provides an identity path for information and gradients to propagate through the network.
Layer Normalization
LayerNorm helps maintain controlled activation scales during training.
Its operation is:
Here, the mean and variance are calculated across the hidden dimensions of each token representation.
The original Transformer uses Post-Norm:
Many modern architectures use Pre-Norm:
Modern LLMs also frequently use RMSNorm, which is related to LayerNorm but does not explicitly subtract the mean.
8. Putting Everything Together: A Transformer Block
Now the individual components fit together.
A standard encoder block in the original Transformer contains:
Multi-Head Self-Attention.
Residual connection and LayerNorm.
Feed-Forward Network.
Residual connection and LayerNorm.
The original decoder has an additional cross-attention sublayer between masked self-attention and the FFN.
Modern GPT-style models generally use decoder-only Transformer blocks.
A simplified modern Pre-Norm decoder block looks like this:
Input x | v LayerNorm | v Causal Self-Attention | v Add residual <---- x | v LayerNorm | v FFN / MLP | v Add residual <---- previous output | v OutputInput x | v LayerNorm | v Causal Self-Attention | v Add residual <---- x | v LayerNorm | v FFN / MLP | v Add residual <---- previous output | v Output
The model stacks multiple Transformer blocks to build increasingly contextual representations.
Original Transformer vs Modern GPT
| Component | Original Transformer | Common modern LLMs |
|---|---|---|
| Architecture | Encoder-Decoder | Decoder-only |
| Position | Sinusoidal | Often RoPE |
| Attention | MHA | MHA or GQA |
| Normalization | LayerNorm | Often RMSNorm |
| FFN activation | ReLU | Often SwiGLU |
| Normalization placement | Post-Norm | Often Pre-Norm |
A few terms worth knowing:
GQA (Grouped-Query Attention): Multiple Query heads share fewer Key and Value heads, reducing KV cache requirements.
SwiGLU: A gated feed-forward network used instead of the original ReLU-based FFN.
RMSNorm: A normalization method that uses root mean square scaling without explicitly subtracting the mean.
These are common architectural choices, not universal rules.
9. How Does a Transformer Finally Predict the Next Token?
After passing through all Transformer layers, we obtain the final hidden representations.
The model applies a final normalization and a linear projection called the Language Modeling Head.
Suppose:
Hidden dimension = 4096 Vocabulary size = 128000Hidden dimension = 4096 Vocabulary size = 128000
The output projection maps each hidden representation to 128,000 scores:
These scores are called logits. They are unnormalized scores for each token in the vocabulary.
Softmax converts them into probabilities:
A decoding strategy then selects the next token.
During inference:
The prompt is processed by the model.
The model produces logits.
A next token is selected.
That token is appended to the context.
The process repeats until generation stops.
One distinction worth keeping in mind: training updates the model's weights using data and optimization; inference uses the already-trained weights to produce predictions. Calling an LLM API is generally an inference operation, not model training.
10. Why Understanding Transformers Matters for Inference Engineering
Understanding the architecture also explains many of the engineering problems that modern inference systems solve.
| Transformer component | Engineering connection |
|---|---|
| Attention | GPU attention kernels |
| Q/K/V projections | Matrix multiplication |
| Attention heads | KV cache layout |
| GQA | Reduced KV cache memory |
| Sequence length | Attention computation and memory |
| Transformer layers | Repeated GPU computation |
| Decoder-only architecture | Autoregressive generation |
This is where papers like FlashAttention, PagedAttention and Mooncake start becoming relevant.
They aren't solving unrelated problems. They are improving how Transformer computations and their associated memory are handled during inference.
That's the connection I wanted to understand before going deeper into LLM systems engineering.
Quick Revision: Important Equations
| Concept | Equation |
|---|---|
| RNN | |
| Q/K/V | |
| Attention | |
| MHA | |
| Residual | |
| Original FFN | |
| LM Head |
Questions to Test Understanding
Why were RNNs difficult to parallelize?
What problem did attention solve in early Seq2Seq models?
What exactly do Query, Key and Value represent?
Why do we divide attention scores by ?
Why do we need Multi-Head Attention?
Why does a Transformer need positional information?
How does causal masking prevent access to future tokens?
What is the difference between attention and an FFN?
Why do residual connections help deep networks?
What is the difference between the original Transformer and a GPT-style decoder-only model?
Papers Worth Reading
Final Thoughts
The Transformer didn't appear out of nowhere. It was the result of years of research into how machines process sequences and learn relationships between words.
RNNs introduced recurrent sequence processing. LSTMs improved information retention. Attention allowed models to retrieve relevant information from different positions. The Transformer brought these ideas together into an architecture built around attention.
Understanding this progression made the architecture much easier to reason about.
For me, this is the foundation for going deeper into LLMs: understanding not just what architecture a model uses, but what actually happens to the data as it moves through it.
Comments
No comments yet.