The Architecture and Evolution of Large Language Models โ From Transformer to ChatGPT, with Interactive Diagrams
LLMs generate text by repeatedly predicting the next token. This overview traces language models from Word2Vec to GPT-4 and uses interactive diagrams to show how tokenization, the Transformer, self-attention, text generation, and RLHF work.
Introduction
Since the release of ChatGPT, large language models (LLMs) have come into wide use. They write code, summarize papers, and answer complex questions, and all of this comes from repeating one simple operation: predicting the next token.
This article traces the path from Word2Vec to GPT-4, then explains how text is split into tokens, how the Transformer and the self-attention mechanism at its center compute a probability distribution over the next token, how one token is chosen from that distribution, and how training proceeds from pre-training to RLHF.
Show transcript
Where do ChatGPT's fluent answers actually come from? From Word2Vec to Transformers and RLHF, let's trace the full shape of large language models.
One starting point was Word2Vec in 2013: it turned words into vectors, but a word kept the same vector whatever the context. In 2017, the paper "Attention Is All You Need" replaced RNN-style sequential processing with self-attention.
From 2018 onward, three families grew out of the Transformer base. BERT predicts masked tokens, making it strong at understanding tasks. T5 made every task text-to-text, while decoder-only GPT models generate one token at a time from left to right. GPT-3, with 175 billion parameters, showed few-shot learning; today's chat models are the same decoder-only type.
Scaling laws in 2020 showed loss following power laws in parameters, data, and compute. The 2022 Chinchilla paper showed that compute-optimal dense models need far more training tokens than earlier large models used. In that setup, the rule of thumb is roughly 20 tokens per parameter: about 1.4 trillion tokens for a 70B model.
An LLM does not read raw text directly; first, it converts text into a sequence of token IDs. BPE starts from characters or bytes and repeatedly merges the most frequent adjacent pair into a new token. GPT-4's vocabulary has about 100,000 tokens, and a single Japanese character often takes one or more tokens.
Next, token IDs become high-dimensional embeddings, for example vectors with 4096 dimensions. Because Transformers process tokens in parallel, they need positional information injected explicitly. Modern models such as LLaMA, Gemma, and Mistral commonly use RoPE, which rotates pairs of dimensions by position-dependent angles. With RoPE, position affects the query-key dot product only through the two tokens' relative position.
Self-attention gives each token a query for what it seeks, a key for what it offers, and a value it passes on. Dot each query with every key, divide by the square root of the key dimension, then softmax the scores into weights. Mix the values with those weights, and each token becomes a new context-aware representation.
Multi-head attention lets different heads learn patterns like subject-verb agreement and modifier-noun links in parallel. A decoder's causal mask sets scores above the diagonal to negative infinity, so softmax gives future tokens zero weight.
Each Transformer block has two sublayers, self-attention and an FFN, each wrapped by normalization and a residual connection. A residual connection adds the input back, creating a shortcut path for gradients through deep layers. Modern Pre-LN normalizes before each sublayer, which trains more stably at scale. The FFN transforms each token independently and holds roughly two thirds of a Transformer's parameters.
The final layer projects to vocabulary size, and softmax turns it into next-token probabilities. At inference time, sample one token from the distribution, append it to the context, and repeat. Greedy decoding always chooses the most likely token. Lower temperature is more deterministic; higher temperature is more diverse. Top-k keeps only the k most likely tokens; top-p keeps tokens until cumulative probability exceeds p.
Training begins with pre-training: next-token prediction over trillions of tokens from web text, books, and code. This model can continue text but not answer questions, so SFT trains it on about 100,000 high-quality instruction-response pairs. In RLHF, humans rank multiple answers, and those rankings train a reward model. Then PPO maximizes reward while a KL penalty keeps the model from drifting too far from the original.
That fluency comes from one simple principle, scaled up: predict the next token. The article goes deeper with interactive demos of self-attention, text generation, and a full Transformer block.
The LLM Genealogy โ A Decade of Evolution
The Word2Vec Era (2013)
Mikolov et al. (2013) proposed Word2Vec, which converts words into fixed-dimensional vectors (embeddings). In the famous example king - man + woman โ queen, relationships between word meanings show up as vector arithmetic. However, each word gets the same vector regardless of context (a static embedding).
The Arrival of the Transformer (2017)
The Transformer, proposed by Vaswani et al. (2017) in "Attention Is All You Need," replaced the sequential processing of RNNs with self-attention, which lets all positions in a sequence be computed in parallel. This architecture is the foundation of today's LLMs.
The Pre-training Era (2018โ)
Three architecture families grew out of the Transformer:
Encoder-Only (BERT Family)
BERT (2018) is pre-trained with Masked Language Modeling (MLM), predicting masked tokens. Because it captures bidirectional context, it does well on understanding tasks like classification, named-entity recognition, and similarity computation.
Encoder-Decoder (T5 Family)
T5 (2019) treats every task, including translation, summarization, and question answering, in the same text-to-text format: text in, text out.
Decoder-Only (GPT Family)
The GPT series uses autoregressive language models, generating one token at a time from left to right. Performance improved substantially as parameter counts grew, and GPT-3 (175B parameters) demonstrated few-shot learning: performing a new task from a few examples given in the prompt. Today's ChatGPT, Claude, and Gemini all belong to this decoder-only, autoregressive family, though they are separate product and model lineages.
Scaling Laws
Kaplan et al. (2020) discovered that language model loss follows a power law with respect to parameters , data , and compute :
Here is one of , , or , and the law holds when the other two are not the bottleneck. The exponent differs for each quantity.
Hoffmann et al. (2022) (the Chinchilla paper) showed that compute-optimal dense language models, which use all their parameters for every token, need far more training tokens than many earlier large models used โ roughly 20 training tokens per parameter in their setup. A 70B-parameter model, for example, corresponds to about 1.4 trillion training tokens.
Tokenization โ Converting Text to Numbers
LLMs split text into units called tokens and process it as a sequence of integer token IDs.
BPE (Byte Pair Encoding)
Many LLMs, including the GPT series and LLaMA, use BPE (Sennrich et al., 2016) for tokenization. BPE builds its vocabulary as follows:
- Split text into characters (or bytes)
- Find the pair that appears next to each other most often in the corpus
- Merge that pair into a new token
- Repeat steps 2โ3 until the vocabulary reaches the target size
# Simplified BPE pseudocode
vocab = set(all_characters)
for i in range(num_merges):
# Find the most frequent pair
pair = most_frequent_pair(corpus)
# Merge into new token
new_token = pair[0] + pair[1]
vocab.add(new_token)
corpus = merge_in_corpus(corpus, pair, new_token)GPT-4 has a vocabulary of approximately 100,000 tokens (cl100k_base in tiktoken). In languages with many distinct characters, such as Japanese, byte-level BPE often splits a less frequent character into more than one token.
Why Subwords?
A word-level vocabulary is large and cannot represent words unseen during training (out-of-vocabulary words). A character-level vocabulary is small and can represent any word, but sequences become long. Subwords sit between the two: the vocabulary stays at a target size, and unseen words can still be represented as combinations of subwords. The same BPE tokenizer can also handle text in multiple languages.
Transformer Architecture
Most LLMs process the sequence of token IDs with a decoder-only Transformer.
A decoder-only Transformer consists of input embeddings, a stack of N Transformer blocks (self-attention, residual connections with normalization, and an FFN), and an output layer.
1. Input Embedding + Positional Encoding
The embedding layer converts token IDs into high-dimensional vectors (e.g., 4096 dimensions). An RNN reads its input one token at a time, so order is built into the computation. Self-attention processes all tokens in parallel and by itself does not distinguish their order, so positional information must be added explicitly via positional encoding.
Sinusoidal Positional Encoding (Original)
The Transformer of Vaswani et al. (2017) used sinusoidal positional encoding, where is the position, is the dimension index, and is the embedding dimension:
In the heatmap below, lower dimensions (left) oscillate quickly with position (high frequency), while higher dimensions (right) change slowly (low frequency).
With sinusoids, can be expressed as a linear function of for any fixed offset . The original paper hypothesized that this property would make it easy for the model to learn relative positions.
RoPE (Rotary Position Embedding)
Many current LLMs, including LLaMA, Gemma, and Mistral, use RoPE. RoPE groups the dimensions of the query and key vectors into pairs and rotates each pair in its 2D plane by an angle that depends on the position.
RoPE's key property is that the dot product of the rotated query and key depends on position only through the relative position . Each token is rotated according to its absolute position, but the attention score reflects only the distance between the two tokens.
In the formula, is the rotation frequency, which takes a different value for each pair of dimensions. When RoPE is applied unchanged to sequences longer than those seen in training, performance tends to drop, but adjusting these frequencies lets the model handle longer sequences. Context-extension methods such as NTK-aware scaling and YaRN are based on this adjustment.
2. Multi-Head Self-Attention
The attention computation itself is covered later, in the "Self-Attention" section.
A single attention head computes only one set of attention weights for each token. With multiple heads, different heads can learn different relationships in parallel, such as subject-verb agreement, adjective-noun modification, and coreference.
where . GPT-3 uses 96 heads; LLaMA 2 70B uses 64 heads.
MQA / GQA โ Shrinking the KV Cache
In standard multi-head attention (MHA), each head has its own K and V projections. The KV cache stored during inference (described later) therefore grows with the number of heads. Multi-query attention (MQA) shrinks this cache by sharing a single K and V across all Q heads. Grouped-query attention (GQA) divides the Q heads into groups of and shares K and V within each group. According to Ainslie et al. (2023), MQA speeds up inference substantially but can lower quality, whereas GQA achieves quality close to MHA at a speed close to MQA's.
| Method | K, V Heads | Model Examples | Characteristics |
|---|---|---|---|
| MHA | = Q heads | GPT-3 | Highest quality, largest KV cache |
| MQA | 1 | PaLM, StarCoder | All heads share K and V; fastest inference |
| GQA | Q heads / g | LLaMA 2 70B, Mistral | Between MHA and MQA |
LLaMA 2 uses GQA in its 34B and 70B models. In the paper's comparison of 30B models, GQA performed comparably to MHA on most evaluation tasks and, because it could run larger batches, achieved higher inference throughput.
3. Residual Connections & Layer Normalization
In each sublayer (self-attention and FFN), the input is added to the output (a residual connection) and combined with normalization. Where the normalization goes differs between Post-LN and Pre-LN, described below.
Why Residual Connections Are Essential
Without residual connections, backpropagated gradients tend to decay (or explode) exponentially as they pass through layers. A residual connection adds each layer's input directly to its output, so gradients from the output side can flow back through this shortcut straight to the layers near the input.
This makes it possible to train networks approaching 100 layers, such as GPT-3 (96 layers) and LLaMA 2 70B (80 layers).
Post-LN vs Pre-LN
| Post-LN (Original) | Pre-LN (Modern) | |
|---|---|---|
| Norm placement | After sublayer | Before sublayer |
| Norm method | LayerNorm | LayerNorm (GPT-3) โ RMSNorm (LLaMA onward) |
| Training stability | Requires learning-rate warmup | Stable; converges easily even at scale |
| Adopted by | Original Transformer, BERT | GPT-3, LLaMA, Mistral |
RMSNorm (Root Mean Square Layer Normalization) is a simplified LayerNorm that skips mean subtraction:
Skipping the mean makes it cheaper to compute, and the original paper's experiments showed performance comparable to LayerNorm, so it has become standard from LLaMA onward.
4. Feed-Forward Network (FFN)
The FFN is a fully connected network applied to each token's vector independently. Attention captures relationships between tokens; the FFN transforms the features of each token. In the standard configuration, where the intermediate layer is four times as wide as the input, the FFN has twice as many weights as self-attention's four projection matrices combined, so FFN parameters make up roughly 2/3 of a Transformer's parameters (excluding embeddings). The FFN is thought to store much of the knowledge the model learns.
Standard FFN
The original Transformer (Vaswani et al., 2017) used ReLU; GPT and BERT switched to GELU:
The intermediate dimension is typically (e.g., when ).
SwiGLU โ The Modern Standard
Shazeer (2020) proposed SwiGLU, which combines a Gated Linear Unit with Swish activation. LLaMA and PaLM, among others, use it.
In Shazeer's experiments, models with SwiGLU in place of the standard FFN achieved higher quality, and two properties may explain why. First, acts as a gate that controls, depending on the input, how much of each component of passes through. Second, is smooth, unlike ReLU, and returns small nonzero values for negative inputs, so gradients are less likely to vanish.
Because SwiGLU uses three matrices (), the intermediate dimension is set to to keep the parameter count equal to a standard FFN (which uses ).
5. Output Layer
The output of the last Transformer block is normalized (with RMSNorm in LLaMA-family models) and projected to vocabulary size by a linear transformation (unembedding). Softmax then converts the result to a probability distribution over the next token.
Some models, such as GPT-2 and Gemma, use weight tying: , sharing the embedding matrix with the output weight . This removes parameters and makes the input and output use the same semantic space.
Causal Mask in Decoders
In decoder-only models like GPT, a causal mask blocks attention to future tokens. The token at position can attend only to positions .
In practice, the entries above the diagonal of the score matrix are set to , which become zero after softmax. Because each position sees only itself and earlier tokens during training as well, training matches the conditions of autoregressive generation, which produces one token at a time from left to right.
Full Transformer Block Data Flow
The demo below steps through the data flow of a single Transformer block, one component at a time.
Transformer Block Forward Pass
The three tokens of "I love cats" passing through one Transformer block, step by step (d_model = 4, illustrative values).
| I | 0.82 | โ0.15 | 0.44 | 0.91 |
| love | 0.33 | 0.78 | โ0.22 | 0.56 |
| cats | 0.61 | 0.42 | 0.73 | โ0.08 |
Token IDs are first converted to vectors by the embedding matrix, and positional encoding is added. Each token becomes a vector with d_model = 4 (real LLMs use, for example, 4096 dimensions).
Self-Attention โ The Core of Transformers
Self-attention computes, from the input, how relevant each token is to every other token, and uses those scores to build context-aware representations.
Formula
- (Query): What each token is "looking for"
- (Key): What each token "contains" (how it wants to be found)
- (Value): The actual information each token passes along
- : Scaling factor, where is the dimension of the key vectors; it prevents dot products from growing too large, which would saturate softmax
Interactive Demo
Self-Attention Mechanism
Self-attention on the three tokens of "The cat sat", computed step by step (d_k = 2, no causal mask, illustrative values).
| The | 1.0 | 0.2 | 0.5 | 0.8 |
| cat | 0.3 | 0.9 | 0.1 | 0.6 |
| sat | 0.7 | 0.4 | 0.8 | 0.2 |
The input is X, the embeddings of the three tokens in "The cat sat". Each row is the 4-dimensional vector of one token, and Q, K, and V are computed from X.
Advantages of Self-Attention over RNNs
- Long-range dependencies: In an RNN, information from distant tokens fades; self-attention accesses every token directly
- Parallel computation: An RNN processes tokens one after another; self-attention is a set of matrix operations that GPUs compute in parallel
- Interpretability: Visualizing attention weights shows which tokens each token weighted most heavily
Computational Complexity
Self-attention computes a score for every pair of tokens, so its cost is in the sequence length , which becomes expensive for long contexts. The techniques below speed up this computation, reduce its memory use, or split it across devices.
| Technique | Complexity | Summary |
|---|---|---|
| Standard attention | Computes all token pairs | |
| Flash Attention | (memory ) | Reduces reads and writes to GPU memory (HBM) |
| Multi-Query Attention | Shares K and V heads to speed up inference | |
| Grouped-Query Attention | Between MQA and MHA; used in LLaMA 2 70B and others | |
| Ring Attention | per device | Splits the sequence across devices and computes in parallel |
Text Generation โ Next-Token Prediction
Given a context (an input token sequence), an LLM outputs a probability distribution over the next token. It picks one token from this distribution, appends it to the context, and repeats the process to generate text. This is autoregressive generation.
Generation Strategies
Greedy decoding: Always pick the highest-probability token. The output is deterministic but tends to be monotonous.
Temperature scaling: Divide the logits (the scores that softmax converts into probabilities) by temperature before applying softmax.
- : Distribution sharpens โ more deterministic (good for factual tasks)
- : Distribution flattens โ more diverse/creative (good for creative writing)
- : Converges to greedy decoding
Top-k sampling: Keep only the top tokens by probability, zero out the rest, and renormalize.
Top-p (Nucleus) sampling: Keep the most probable tokens, in order, until their cumulative probability exceeds (e.g., 0.95). A sharp distribution leaves few candidates and a flat one leaves many, which makes top-p more flexible than top-k with its fixed candidate count.
Interactive Demo
Text Generation Demo
Text generated one token at a time with temperature and top-k sampling (top five candidates shown, illustrative values).
Given the context "The cat", the model's final layer outputs a logit (a score before softmax) for each candidate next token.
Training Pipeline โ From Raw Model to Conversational AI
Stage 1: Pre-training
To acquire general language knowledge, the model learns to predict the next token on a corpus of trillions of tokens, including web text, books, and code. The loss sums, over all positions, the negative log of the probability the model assigned to the correct next token .
At this stage the model can continue a piece of text, but it has not been trained to answer questions or follow instructions.
Stage 2: Supervised Fine-Tuning (SFT)
To teach the model to follow instructions, SFT fine-tunes it on a dataset of high-quality (instruction, response) pairs (about 13,000 in InstructGPT). From this it learns the format of answering a user's question.
[Instruction] What is the capital of Japan?
[Response] The capital of Japan is Tokyo.Stage 3: Reinforcement Learning from Human Feedback (RLHF)
A model after SFT can still produce answers not grounded in fact, or harmful output. RLHF uses human judgments of which answer is better to align the model's output with human preferences and reduce such output.
- Train a reward model: Human annotators rank several answers to the same prompt, and that data is used to train a reward model that scores how good an answer is
- PPO (Proximal Policy Optimization): Update the policy (LLM) to maximize the reward model's score, with a KL penalty that keeps it from drifting too far from the original model
Here is the reward model's score for answer to prompt , is the policy being updated, is the original (post-SFT) model, and is a coefficient that sets the strength of the KL penalty.
DPO (Direct Preference Optimization) simplifies RLHF by optimizing the policy directly from preference data without explicitly training a reward model. LLaMA 2 used PPO-based RLHF, but DPO has since been widely adopted in open models such as Zephyr and LLaMA 3.
Modern LLM Techniques
KV Cache
In autoregressive generation, the K and V of earlier tokens do not change as generation proceeds. The K and V computed once are therefore stored in a KV cache and reused at later steps. Each step then only has to compute the new token, which speeds up inference considerably, but the cache's memory use grows linearly with sequence length.
Quantization
Quantization converts LLM parameters from 32/16-bit floating point to 4/8-bit integers to reduce memory and compute costs. Methods such as GPTQ and AWQ keep the accuracy loss small on many workloads. As a result, a 70B model, whose weights take about 35 GB at 4 bits, becomes practical to run on a single high-memory GPU. Whether it works in a given setting depends on the KV-cache size for the context length and on latency requirements.
MoE (Mixture of Experts)
MoE splits the FFN layers into multiple "experts," and a router selects a few of them for each token (2 of 8 in Mixtral). The total parameter count is large, but each token uses only part of the parameters at inference time, so the model can grow without a matching growth in compute.
Context Length Extension
Early Transformer-based models such as BERT had context lengths of about 512 tokens; some models today, such as Gemini 1.5, can process over 1 million tokens. Techniques used to extend context length include the RoPE frequency adjustments described earlier (NTK-aware scaling and YaRN) and Ring Attention.
Summary
The main points of each section:
- History: Word2Vec โ Transformer โ BERT/GPT โ scaling laws driving larger models
- Tokenization: BPE subword splitting converts arbitrary text to numerical sequences
- Transformer: N stacked layers of self-attention + FFN + residual connections
- Self-attention: computes relevance across all tokens from the input
- Text generation: Temperature, top-k, top-p sampling for stochastic autoregressive generation
- Training pipeline: Pre-training โ SFT โ RLHF/DPO turns a "next-token predictor" into a "conversational AI"
At every stage, what the model outputs is a probability distribution over the next token. Scaled up far enough, this simple-looking mechanism makes possible the code writing and question answering mentioned at the start.
References
- A. Vaswani et al. Attention Is All You Need. NeurIPS 2017.
- J. Devlin et al. BERT: Pre-training of Deep Bidirectional Transformers. NAACL 2019.
- T. Brown et al. Language Models are Few-Shot Learners. NeurIPS 2020 (GPT-3).
- J. Kaplan et al. Scaling Laws for Neural Language Models. 2020.
- J. Hoffmann et al. Training Compute-Optimal Large Language Models. NeurIPS 2022 (Chinchilla).
- L. Ouyang et al. Training language models to follow instructions with human feedback. NeurIPS 2022 (InstructGPT / RLHF).
- R. Rafailov et al. Direct Preference Optimization. NeurIPS 2023.