Inside Transformer Architecture: Multi-Head Attention, Feed-Forward Networks, and Tokenization
A deep dive into the Transformer architecture: tokenization, Rotary Positional Embeddings, Scaled Dot-Product Attention, GQA, and autoregressive generation.
On this page
Every modern frontier language model, from open-weight architectures like Llama and Mistral to proprietary systems, traces its lineage back to a single 2017 research paper from Google Brain: “Attention Is All You Need”.
Before the Transformer, Natural Language Processing (NLP) was dominated by Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks. RNNs processed text sequentially, token by token from left to right. This sequential dependency created a severe hardware bottleneck: you could not compute the representation of the 50th word until the 49th word had finished traversing the recurrent hidden state. Furthermore, as sequence lengths grew past a few hundred tokens, gradients vanished, and models suffered catastrophic forgetting.
The Transformer eradicated sequential recurrence. By replacing recurrent loops with Self-Attention mechanisms, the Transformer processes all tokens in a sequence simultaneously in parallel across thousands of GPU cores.
Understanding how a Transformer converts raw strings into semantic understanding, attention matrices, and autoregressive tokens is essential for any modern systems engineer.
+-------------------------------------------------------------------------------+
| THE TRANSFORMER DECODER PIPELINE |
+-------------------------------------------------------------------------------+
[Raw Prompt: "The cat sat on the mat because it was tired"]
|
v
1. Tokenizer (Byte-Pair Encoding -> Discrete Token IDs: [464, 3797, 3332...])
|
v
2. Token Embeddings + Rotary Positional Embeddings (RoPE)
|
v
3. N Stacked Transformer Decoder Blocks (e.g., 32 layers)
|
+---> Root-Mean-Square Normalization (RMSNorm)
|
+---> Multi-Head Attention / Grouped-Query Attention (GQA)
| |-- Query (Q), Key (K), Value (V) Projections
| |-- Scaled Dot-Product Attention: Softmax((Q * K^T) / sqrt(d_k)) * V
| \-- Causal Masking (Prevents attending to future tokens)
|
+---> Residual Add Connection
|
+---> RMSNorm
|
+---> Feed-Forward Network (SwiGLU Activation / MLP Expansion)
|
\---> Residual Add Connection
|
v
4. Final RMSNorm + Unembedding Projection Matrix (Hidden Dim -> Vocab Logits)
|
v
5. Softmax & Sampling (Temperature, Top-p) -> Next Token Generated!
1. Input Processing: Tokenization and Embeddings
Computers cannot perform matrix multiplication on raw text strings. The input pipeline transforms human language into continuous numerical vectors.
Step 1: Subword Tokenization (BPE)
Models use subword tokenization algorithms such as Byte-Pair Encoding (BPE). Common words become individual tokens ("cat" -> 3797), while rare words or code identifiers are broken into subword pieces ("unbelievable" -> ["un", "believ", "able"]).
A modern model vocabulary typically holds between 32,000 and 128,000 distinct tokens.
Step 2: Vector Embeddings
Each token ID maps to a high-dimensional vector via an embedding lookup table:
Token ID: 3797 ("cat") ---> Embedding Matrix Lookup ---> [0.024, -0.891, 0.412, ..., 0.055]
In a model with hidden dimension d_{\text{model}} = 4096, every token is represented as a point in a 4,096-dimensional continuous geometric space. In this space, geometric proximity represents semantic relationship: words sharing semantic contexts cluster together, and vector arithmetic reflects conceptual relationships (the classic vector equivalence: \text{King} - \text{Man} + \text{Woman} \approx \text{Queen}).
Step 3: Positional Encoding (RoPE)
Because the Transformer processes all tokens in parallel, the self-attention operation is order-invariant (permutation-invariant). The model cannot inherently tell whether "dog bites man" is different from "man bites dog".
Modern LLMs solve this using Rotary Positional Embeddings (RoPE). Rather than adding fixed positional vectors to token embeddings, RoPE rotates the Query and Key vectors in complex two-dimensional chunks by an angle proportional to the token’s index in the sequence:
RoPE Rotation:
For coordinate pair (x_1, x_2) at position m with frequency theta:
[ x_1' ] = [ cos(m*theta) -sin(m*theta) ] [ x_1 ]
[ x_2' ] [ sin(m*theta) cos(m*theta) ] [ x_2 ]
RoPE ensures that the inner product between Query and Key depends purely on the relative distance (m - n) between two tokens, enabling superior extrapolation to long context windows.
2. The Core Engine: Scaled Dot-Product Attention
Self-Attention allows every token in a sequence to look across all other tokens, weigh their relevance, and update its own representation accordingly.
For each token, the model projects its embedding into three distinct vectors using learned weight matrices:
- Query (
Q): “What kind of information am I looking for?” - Key (
K): “What kind of information do I contain?” - Value (
V): “If I am relevant to you, what information do I give you?”
SCALED DOT-PRODUCT ATTENTION MECHANISM
Query (Q) Key (K)
\ /
\ /
v v
[ Matrix Multiply: Q * K^T ] (Raw Alignment Scores)
|
v
[ Scale: Divide by sqrt(d_k) ] (Prevents Gradient Saturation)
|
v
[ Apply Causal Mask ] (Zero out future positions)
|
v
[ Softmax ] (Normalize into Probabilities: sum to 1.0)
|
+--------------+
|
v
[ Multiply by Value (V) ]
|
v
[ Contextualized Output ]
The Attention Formula
Attention(Q, K, V) = Softmax((Q * K^T) / sqrt(d_k)) * V
- Dot Product (
Q \times K^T): Computes the geometric alignment (similarity) between every Query and every Key. If token A’s Query aligns with token B’s Key, the score is high. - Scaling Factor (
\sqrt{d_k}): As dimensiond_kgrows (e.g.,d_k = 128), dot products grow large, pushing the Softmax function into regions with near-zero gradients. Dividing by\sqrt{d_k}stabilizes backpropagation. - Causal Masking: In decoder models, token
Nmust not peek into tokenN+1. Future positions are set to-\inftybefore Softmax, converting their probabilities to absolute zero. - Softmax: Converts scores into a normalized probability distribution where rows sum to
1.0. - Weighted Value Sum: Each token’s new representation is a weighted sum of all Value vectors in the sequence, weighted by their attention probabilities.
Worked Example: Resolving Ambiguity
Consider the sentence: “The animal didn’t cross the street because it was too tired.”
When computing attention for the token "it":
- The Query vector for
"it"asks for a singular antecedent noun. - The Key vector for
"animal"signals animate subject capable of fatigue. - The Key vector for
"street"signals inanimate physical roadway. - Result: The attention score between
"it"and"animal"is 0.88, while the score between"it"and"street"is 0.03. - The Value vector of
"animal"is mixed into the representation of"it", allowing subsequent layers to understand that"it"is tired, not the pavement.
3. From MHA to Grouped-Query Attention (GQA)
Early architectures used standard Multi-Head Attention (MHA), allocating an independent set of Query, Key, and Value heads for each attention head (e.g., 32 Q heads, 32 K heads, 32 V heads).
During autoregressive inference, the model must store all past Key and Value vectors in GPU High Bandwidth Memory (HBM) so it does not recompute them for every newly generated token. This cache is known as the KV-Cache.
Under MHA with long contexts (128k tokens) and high concurrency, the KV-Cache consumes dozens of gigabytes of VRAM per user, hitting the hardware memory wall.
+-----------------------------------------------------------------------+
| ATTENTION HEAD MEMORY TOPOLOGY COMPARISON |
+-----------------------------------------------------------------------+
Multi-Head Attention (MHA):
Q Heads: [Q1] [Q2] [Q3] [Q4] [Q5] [Q6] [Q7] [Q8]
K Heads: [K1] [K2] [K3] [K4] [K5] [K6] [K7] [K8] (1:1 Ratio - Heavy Memory)
V Heads: [V1] [V2] [V3] [V4] [V5] [V6] [V7] [V8]
Multi-Query Attention (MQA):
Q Heads: [Q1] [Q2] [Q3] [Q4] [Q5] [Q6] [Q7] [Q8]
K Heads: [ Single K Head ] (8:1 Ratio - Max Memory Save, Quality Loss)
V Heads: [ Single V Head ]
Grouped-Query Attention (GQA - Modern Standard):
Q Heads: [Q1] [Q2] | [Q3] [Q4] | [Q5] [Q6] | [Q7] [Q8]
K Heads: [ K1 ] | [ K2 ] | [ K3 ] | [ K4 ] (4:1 Ratio - Optimal Quality & Speed!)
V Heads: [ V1 ] | [ V2 ] | [ V3 ] | [ V4 ]
Modern models (such as Llama 3) adopt Grouped-Query Attention (GQA). GQA groups multiple Query heads (e.g., 8 Q heads) to share a single Key and Value head. This slashes KV-cache memory bandwidth by 4\times to 8\times with negligible impact on output reasoning quality.
4. Feed-Forward Networks (FFN) and SwiGLU
Attention only routes and mixes information between tokens; it does not store deep factual knowledge or perform complex non-linear synthesis. That work happens in the Feed-Forward Network (FFN).
Each Transformer layer passes the output of self-attention into an MLP block that expands the hidden dimension (typically by 8/3 \times or 4\times, e.g., expanding from 4,096 to 14,336 dimensions) and contracts it back down.
Modern architectures replace traditional ReLU or GELU activations with SwiGLU (Swish-Gated Linear Unit):
SwiGLU(x) = (x * W_gate * Sigmoid(beta * x * W_gate)) * (x * W_up) * W_down
The gating mechanism acts as a dynamic filter, allowing the network to suppress or amplify features before projecting them back down to the model dimension.
5. Output Projection: From Hidden Vectors to Words
After traversing all 32 or 80 Transformer layers, the final representation of the last token passes into the Unembedding Projection:
- RMSNorm: Normalizes vector variance to prevent gradient explosions.
- Linear Head (Unembedding Matrix): Multiplies the
d_{\text{model}}vector by the vocabulary matrix, producing a raw score (logit) for every word in the dictionary (e.g., 128,000 logits). - Softmax: Converts logits into probabilities:
Probability(Token_i) = exp(Logit_i / Temperature) / Sum(exp(Logit_j / Temperature)) - Sampling:
- Greedy: Always pick the highest probability token (deterministic).
- Temperature: Scaling logits prior to Softmax. Higher temperature flattens probabilities, producing more creative, diverse choices; lower temperature concentrates probability on top candidates.
- Top-p (Nucleus): Accumulates tokens until cumulative probability hits
P(e.g., 0.90), discarding the long tail of improbable hallucinated tokens.
Once the next token is sampled, it is appended to the input sequence, and the cycle repeats autoregressively until an <end_of_text> token is generated.
Training vs Inference Comparison
| Characteristic | Model Training | Model Inference |
|---|---|---|
| Compute Pattern | Massively parallel over sequence length | Autoregressive (sequential token by token) |
| Model Weights | Continuously mutated via backward pass | Completely frozen; zero weight updates |
| KV-Cache | Not required (all tokens known up front) | Mandatory to prevent O(N^2) recomputation |
| Hardware Bottleneck | Compute bound (FLOPS on Tensor Cores) | Memory bandwidth bound (HBM read speeds) |
| Execution Scale | Thousands of GPUs across weeks | Single GPU / cluster serving user tokens |
Summary and Key Takeaways
- Transformers eliminated sequential recurrence: Self-attention allows all tokens to be processed concurrently across parallel GPU cores, overcoming the RNN scaling bottleneck.
- Embeddings encode geometry and position: High-dimensional vectors capture semantic relationships, while Rotary Positional Embeddings (RoPE) encode relative word distances.
- Attention is dynamic routing: The Scaled Dot-Product mechanism matches Queries against Keys to route contextual Value information between tokens.
- GQA solves the inference memory wall: Grouping Query heads to share Key-Value pairs reduces KV-cache memory consumption by up to
8\times. - Inference is autoregressive and memory-bound: While training is compute-bound over parallel sequences, inference generates one token at a time and is fundamentally throttled by GPU memory bandwidth.



/* Comments */
Comments are offline right now — we reconnect automatically, nothing is lost.