Dev Pratap Singh

Transformers Explained: From RNNs to the Architecture Behind Modern LLMs

transformers 12 min

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 → mat

Its basic operation is:

ht=tanh⁡(Wxxt+Whht−1+b)h_t=\tanh(W_x x_t+W_h h_{t-1}+b)

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

If each token embedding has 512 dimensions, we can stack the vectors into an input matrix:

X∈RN×512X\in\mathbb{R}^{N\times512}

Here, NN is the sequence length. This matrix XX 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:

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\quad K=XW_K,\quad V=XW_V

The attention operation is:

Attention(Q,K,V)=softmax(QKTdk)V\boxed{Attention(Q,K,V)=softmax\left(\frac{QK^T}{\sqrt{d_k}}\right)V}

Let's break it down:

  1. QKTQK^T calculates similarity scores between Queries and Keys.

  2. Dividing by dk\sqrt{d_k} controls the magnitude of the scores and helps avoid softmax saturation.

  3. Softmax converts scores into attention weights.

  4. Multiplying by VV 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:

TokenScore
animal2
road1
crossed0

Applying softmax:

softmax([2,1,0])≈[0.665,0.245,0.090]softmax([2,1,0])\approx[0.665,0.245,0.090]

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:

MHA(Q,K,V)=Concat(head1,…,headh)WOMHA(Q,K,V)=Concat(head_1,\ldots,head_h)W_O

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:

(2,4,8)(2,4,8)

After splitting into two heads:

(2,2,4,4)(2,2,4,4)

The dimensions now represent:

Batch × Heads × Sequence × Head dimension

Each head performs its own attention computation. Their outputs are concatenated back into:

(2,4,8)(2,4,8)

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.

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:

PE(pos,2i)=sin⁡(pos100002i/dmodel)PE(pos,2i)=\sin\left(\frac{pos}{10000^{2i/d_{model}}}\right)

PE(pos,2i+1)=cos⁡(pos100002i/dmodel)PE(pos,2i+1)=\cos\left(\frac{pos}{10000^{2i/d_{model}}}\right)

Different dimensions use different frequencies to represent positions.

The positional encoding is added to the token embedding:

Input=TokenEmbedding+PositionalEncodingInput=TokenEmbedding+PositionalEncoding

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:

InputTarget
Thecat
The catsat
The cat saton

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   1

We add a mask to the attention scores before softmax:

Attention=softmax(QKTdk+M)VAttention=softmax\left(\frac{QK^T}{\sqrt{d_k}}+M\right)V

Blocked future positions receive a value of −∞-\infty, 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:

FFN(x)=ReLU(xW1+b1)W2+b2FFN(x)=ReLU(xW_1+b_1)W_2+b_2

For its base configuration, the dimensions are:

512→2048→512512\rightarrow2048\rightarrow512

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:

Output=x+F(x)\boxed{Output=x+F(x)}

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:

LayerNorm(x)=γx−μσ2+ϵ+βLayerNorm(x)=\gamma\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta

Here, the mean and variance are calculated across the hidden dimensions of each token representation.

The original Transformer uses Post-Norm:

Output=LayerNorm(x+F(x))Output=LayerNorm(x+F(x))

Many modern architectures use Pre-Norm:

Output=x+F(LayerNorm(x))Output=x+F(LayerNorm(x))

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:

  1. Multi-Head Self-Attention.

  2. Residual connection and LayerNorm.

  3. Feed-Forward Network.

  4. 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
          Output

The model stacks multiple Transformer blocks to build increasingly contextual representations.

Original Transformer vs Modern GPT

ComponentOriginal TransformerCommon modern LLMs
ArchitectureEncoder-DecoderDecoder-only
PositionSinusoidalOften RoPE
AttentionMHAMHA or GQA
NormalizationLayerNormOften RMSNorm
FFN activationReLUOften SwiGLU
Normalization placementPost-NormOften 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  = 128000

The output projection maps each hidden representation to 128,000 scores:

Logits=HWvocabLogits=HW_{vocab}

These scores are called logits. They are unnormalized scores for each token in the vocabulary.

Softmax converts them into probabilities:

P(tokeni)=ezi∑jezjP(token_i)=\frac{e^{z_i}}{\sum_j e^{z_j}}

A decoding strategy then selects the next token.

During inference:

  1. The prompt is processed by the model.

  2. The model produces logits.

  3. A next token is selected.

  4. That token is appended to the context.

  5. 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 componentEngineering connection
AttentionGPU attention kernels
Q/K/V projectionsMatrix multiplication
Attention headsKV cache layout
GQAReduced KV cache memory
Sequence lengthAttention computation and memory
Transformer layersRepeated GPU computation
Decoder-only architectureAutoregressive 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

ConceptEquation
RNNht=tanh⁡(Wxxt+Whht−1+b)h_t=\tanh(W_xx_t+W_hh_{t-1}+b)
Q/K/VQ=XWQ, K=XWK, V=XWVQ=XW_Q,\ K=XW_K,\ V=XW_V
Attentionsoftmax(QKT/dk)Vsoftmax(QK^T/\sqrt{d_k})V
MHAConcat(head1,…,headh)WOConcat(head_1,\ldots,head_h)W_O
Residualx+F(x)x+F(x)
Original FFNReLU(xW1+b1)W2+b2ReLU(xW_1+b_1)W_2+b_2
LM HeadHWvocabHW_{vocab}

Questions to Test Understanding

  1. Why were RNNs difficult to parallelize?

  2. What problem did attention solve in early Seq2Seq models?

  3. What exactly do Query, Key and Value represent?

  4. Why do we divide attention scores by dk\sqrt{d_k}?

  5. Why do we need Multi-Head Attention?

  6. Why does a Transformer need positional information?

  7. How does causal masking prevent access to future tokens?

  8. What is the difference between attention and an FFN?

  9. Why do residual connections help deep networks?

  10. 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.