โ†All posts

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.

LLMTransformerNLPDeep LearningInteractive

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.

Watch the video explainer4:31Synthesized narration ยท burned-in captions
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

2013Word2VecWord embeddings2017TransformerAttention Is All You Need2018BERT / GPT-1Pre-training era begins2020GPT-3175B parameters2022ChatGPTSFT + RLHF2024โ€“GPT-4o / Gemini / ClaudeMultimodal, reasoning

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:

Transformer2017 โ€” Vaswani et al.Encoder-onlyBERT (2018)Masked language modelRoBERTa (2019)BERT with improved trainingDeBERTa (2020)Disentangled attentionEncoder-decoderT5 (2019)Text-to-textBART (2019)Denoising autoencoderFlan-T5 (2022)Instruction tuningDecoder-onlyGPT-2/3 (2019โ€“20)Autoregressive language modelLLaMA (2023)Open weightsGPT-4 / Claude (2023โ€“)Frontier modelsClassification, entity recognition, embeddingsTranslation, summarizationChat, code generation, reasoning

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

log x (x is N, D, or C)log L (loss)L(x) โˆ x^(โˆ’ฮฑ)Parameters (N)Data (D)Compute (C)Kaplan et al. 2020, Hoffmann et al. 2022

Kaplan et al. (2020) discovered that language model loss follows a power law with respect to parameters NN, data DD, and compute CC:

L(x)โˆxโˆ’ฮฑL(x) \propto x^{-\alpha}

Here xx is one of NN, DD, or CC, and the law holds when the other two are not the bottleneck. The exponent ฮฑ\alpha 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.

Input text"The cat sat on the mat"โ†“ GPT-2 BPE tokenizer (ฤ  = space before a word)Tokens (subwords)TheID: 464ฤ catID: 3797ฤ satID: 3332ฤ onID: 319ฤ theID: 262ฤ matID: 2603

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:

  1. Split text into characters (or bytes)
  2. Find the pair that appears next to each other most often in the corpus
  3. Merge that pair into a new token
  4. 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.

ร— NInput Embedding + Positional EncodingMulti-Head Self-AttentionAdd & Layer NormFeed-Forward NetworkAdd & Layer NormLinear + Softmax โ†’ ProbabilitiesToken IDsNext-token prediction

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 pospos is the position, ii is the dimension index, and dd is the embedding dimension:

PE(pos,2i)=sinโกโ€‰โฃ(pos100002i/d),PE(pos,2i+1)=cosโกโ€‰โฃ(pos100002i/d)\text{PE}(pos, 2i) = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \quad \text{PE}(pos, 2i+1) = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)

In the heatmap below, lower dimensions (left) oscillate quickly with position (high frequency), while higher dimensions (right) change slowly (low frequency).

Sinusoidal Positional EncodingPE(pos, 2i) = sin(pos / 10000^(2i/d)), PE(pos, 2i+1) = cos(pos / 10000^(2i/d))PositionDimension012345670123456789101112131415Blue = positive Red = negative (sin for even dimensions, cos for odd dimensions)High frequencyLow frequency

With sinusoids, PE(pos+k)\text{PE}(pos + k) can be expressed as a linear function of PE(pos)\text{PE}(pos) for any fixed offset kk. 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 (Rotary Position Embedding)Pairs of dimensions are rotated by position-dependent anglespos = 0ฮธยทpos = 0ยฐdโ‚€dโ‚pos = 1ฮธยทpos = 30ยฐdโ‚€dโ‚pos = 2ฮธยทpos = 60ยฐdโ‚€dโ‚q_m ยท k_n depends on position only through the relative position (m โˆ’ n)โ†’ Rotations use absolute positions; the score keeps only their difference

RoPE's key property is that the dot product of the rotated query qmq_m and key knk_n depends on position only through the relative position (mโˆ’n)(m - n). Each token is rotated according to its absolute position, but the attention score reflects only the distance between the two tokens.

RoPE(x,pos)=(x0cosโก(ฮธโ‹…pos)โˆ’x1sinโก(ฮธโ‹…pos)x0sinโก(ฮธโ‹…pos)+x1cosโก(ฮธโ‹…pos)โ‹ฎ)\text{RoPE}(x, pos) = \begin{pmatrix} x_0 \cos(\theta \cdot pos) - x_1 \sin(\theta \cdot pos) \\ x_0 \sin(\theta \cdot pos) + x_1 \cos(\theta \cdot pos) \\ \vdots \end{pmatrix}

In the formula, ฮธ\theta 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.

Input X (d_model = 512)Head 1d_k = 128QยทKแต€/โˆšd_k โ†’ Vsubject-verbHead 2d_k = 128QยทKแต€/โˆšd_k โ†’ Vadjective-nounHead 3d_k = 128QยทKแต€/โˆšd_k โ†’ VcoreferenceHead 4d_k = 128QยทKแต€/โˆšd_k โ†’ VsyntaxConcat (d_k ร— h = 512)Linear W_O โ†’ OutputMulti-Head Output (d_model = 512)MultiHead(Q,K,V) = Concat(headโ‚, โ€ฆ, headโ‚•) ยท W_O
MultiHead(Q,K,V)=Concat(head1,โ€ฆ,headh)โ‹…WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) \cdot W_O

where headi=Attention(QWQ(i),KWK(i),VWV(i))\text{head}_i = \text{Attention}(Q W_Q^{(i)}, K W_K^{(i)}, V W_V^{(i)}). 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 gg 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.

MethodK, V HeadsModel ExamplesCharacteristics
MHA= Q headsGPT-3Highest quality, largest KV cache
MQA1PaLM, StarCoderAll heads share K and V; fastest inference
GQAQ heads / gLLaMA 2 70B, MistralBetween 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 NN 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.

xl+1=xl+F(xl)x_{l+1} = x_l + F(x_l)

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)xSelf-AttentionAdd (residual)LayerNormFFNAdd (residual)LayerNormPre-LN (Modern)xRMSNormSelf-AttentionAdd (residual)RMSNormFFNAdd (residual)
Post-LN (Original)Pre-LN (Modern)
Norm placementAfter sublayerBefore sublayer
Norm methodLayerNormLayerNorm (GPT-3) โ†’ RMSNorm (LLaMA onward)
Training stabilityRequires learning-rate warmupStable; converges easily even at scale
Adopted byOriginal Transformer, BERTGPT-3, LLaMA, Mistral

RMSNorm (Root Mean Square Layer Normalization) is a simplified LayerNorm that skips mean subtraction:

RMSNorm(x)=xRMS(x)โ‹…ฮณ,RMS(x)=1dโˆ‘i=1dxi2\text{RMSNorm}(x) = \frac{x}{\text{RMS}(x)} \cdot \gamma, \quad \text{RMS}(x) = \sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2}

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:

FFN(x)=GELU(xW1+b1)W2+b2\text{FFN}(x) = \text{GELU}(x W_1 + b_1) W_2 + b_2

The intermediate dimension dffd_{\text{ff}} is typically 4ร—dmodel4 \times d_{\text{model}} (e.g., dff=16384d_{\text{ff}} = 16384 when dmodel=4096d_{\text{model}} = 4096).

SwiGLU โ€” The Modern Standard

Shazeer (2020) proposed SwiGLU, which combines a Gated Linear Unit with Swish activation. LLaMA and PaLM, among others, use it.

SwiGLU Feed-Forward Networkx (d_model)x ยท Wโ‚ (d_ff)Swish(x) = x ยท ฯƒ(x)x ยท Wโ‚ƒ (d_ff)(gate)โŠ™element-wise productยท Wโ‚‚ โ†’ output (d_model)SwiGLU(x) = (Swish(x ยท Wโ‚) โŠ™ (x ยท Wโ‚ƒ)) ยท Wโ‚‚
SwiGLU(x)=(Swish(xW1)โŠ™(xW3))W2\text{SwiGLU}(x) = \bigl(\text{Swish}(x W_1) \odot (x W_3)\bigr) W_2

In Shazeer's experiments, models with SwiGLU in place of the standard FFN achieved higher quality, and two properties may explain why. First, xW3x W_3 acts as a gate that controls, depending on the input, how much of each component of Swish(xW1)\text{Swish}(x W_1) passes through. Second, Swish(x)=xโ‹…ฯƒ(x)\text{Swish}(x) = x \cdot \sigma(x) is smooth, unlike ReLU, and returns small nonzero values for negative inputs, so gradients are less likely to vanish.

Because SwiGLU uses three matrices (W1,W2,W3W_1, W_2, W_3), the intermediate dimension is set to dff=83dmodeld_{\text{ff}} = \frac{8}{3} d_{\text{model}} to keep the parameter count equal to a standard FFN (which uses 4ร—dmodel4 \times d_{\text{model}}).

5. Output Layer

The output of the last Transformer block is normalized (with RMSNorm in LLaMA-family models) and projected to vocabulary size โˆฃVโˆฃ|V| 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: WU=WETW_U = W_E^T, sharing the embedding matrix WEW_E with the output weight WUW_U. This removes โˆฃVโˆฃร—d|V| \times d 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 ii can attend only to positions 1,2,โ€ฆ,i1, 2, \ldots, i.

Causal Mask (Attention Matrix)Green = can attend, red = masked (โˆ’โˆž)Key โ†’ThecatsatontheQuery โ†’Thecatsatontheโœ“โˆ’โˆžโˆ’โˆžโˆ’โˆžโˆ’โˆžโœ“โœ“โˆ’โˆžโˆ’โˆžโˆ’โˆžโœ“โœ“โœ“โˆ’โˆžโˆ’โˆžโœ“โœ“โœ“โœ“โˆ’โˆžโœ“โœ“โœ“โœ“โœ“"sat" (row 3) can attend to "The", "cat", and "sat" but not to "on" or "the"

In practice, the entries above the diagonal of the score matrix are set to โˆ’โˆž-\infty, 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).

๐Ÿ“ฅEmbed+PE
โ†’
๐Ÿ“RMSNorm
โ†’
๐Ÿ”€Q,K,V
โ†’
๐ŸŽฏAttn weights
โ†’
โœจAttn output
โ†’
โž•Residual
โ†’
๐Ÿ“RMSNorm
โ†’
โšกFFN
โ†’
โž•Residual
โ†’
๐Ÿ“คOutput
Step 0: Input Embedding + Positional Encoding
Tokens:Ilovecats
X = Embed + PE
I0.82โˆ’0.150.440.91
love0.330.78โˆ’0.220.56
cats0.610.420.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).

1 / 10

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

Attention(Q,K,V)=softmaxโ€‰โฃ(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right) V
  • QQ (Query): What each token is "looking for"
  • KK (Key): What each token "contains" (how it wants to be found)
  • VV (Value): The actual information each token passes along
  • dk\sqrt{d_k}: Scaling factor, where dkd_k 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).

Tokens:Thecatsat
X (Input)
The1.00.20.50.8
cat0.30.90.10.6
sat0.70.40.80.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.

1 / 8

Advantages of Self-Attention over RNNs

  1. Long-range dependencies: In an RNN, information from distant tokens fades; self-attention accesses every token directly
  2. Parallel computation: An RNN processes tokens one after another; self-attention is a set of matrix operations that GPUs compute in parallel
  3. 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 O(n2)O(n^2) in the sequence length nn, which becomes expensive for long contexts. The techniques below speed up this computation, reduce its memory use, or split it across devices.

TechniqueComplexitySummary
Standard attentionO(n2)O(n^2)Computes all token pairs
Flash AttentionO(n2)O(n^2) (memory O(n)O(n))Reduces reads and writes to GPU memory (HBM)
Multi-Query AttentionO(n2)O(n^2)Shares K and V heads to speed up inference
Grouped-Query AttentionO(n2)O(n^2)Between MQA and MHA; used in LLaMA 2 70B and others
Ring AttentionO(n2/p)O(n^2 / p) per deviceSplits the sequence across pp 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 ziz_i (the scores that softmax converts into probabilities) by temperature TT before applying softmax.

pi=expโก(zi/T)โˆ‘jexpโก(zj/T)p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}
  • T<1T < 1: Distribution sharpens โ†’ more deterministic (good for factual tasks)
  • T>1T > 1: Distribution flattens โ†’ more diverse/creative (good for creative writing)
  • Tโ†’0T \to 0: Converges to greedy decoding

Top-k sampling: Keep only the top kk 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 pp (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).

Context:Thecatโ–Œ
sat
logit: 3.20%
is
logit: 2.80%
ran
logit: 1.50%
the
logit: 0.90%
very
logit: 0.40%

Given the context "The cat", the model's final layer outputs a logit (a score before softmax) for each candidate next token.

1 / 8

Training Pipeline โ€” From Raw Model to Conversational AI

Pre-trainingNext-token predictionTrillions of tokensSFTSupervised fine-tuning~13K examples (InstructGPT)RLHF / DPOAlign with human preferencesReward model + PPO, or DPODeploymentAPI / chat interfaceQuantization, efficient inference

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

Lpretrain=โˆ’โˆ‘t=1TlogโกP(xtโˆฃx<t;ฮธ)\mathcal{L}_{\text{pretrain}} = -\sum_{t=1}^{T} \log P(x_t | x_{<t}; \theta)

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.

  1. 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
  2. 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
JRLHF=E[R(x,y)โˆ’ฮฒโ€‰KL(ฯ€ฮธโˆฅฯ€ref)]\mathcal{J}_{\text{RLHF}} = \mathbb{E}\bigl[R(x, y) - \beta \, \text{KL}\bigl(\pi_\theta \| \pi_{\text{ref}}\bigr)\bigr]

Here R(x,y)R(x, y) is the reward model's score for answer yy to prompt xx, ฯ€ฮธ\pi_\theta is the policy being updated, ฯ€ref\pi_{\text{ref}} is the original (post-SFT) model, and ฮฒ\beta 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:

  1. History: Word2Vec โ†’ Transformer โ†’ BERT/GPT โ†’ scaling laws driving larger models
  2. Tokenization: BPE subword splitting converts arbitrary text to numerical sequences
  3. Transformer: N stacked layers of self-attention + FFN + residual connections
  4. Self-attention: softmax(QKT/dk)V\text{softmax}(QK^T/\sqrt{d_k})V computes relevance across all tokens from the input
  5. Text generation: Temperature, top-k, top-p sampling for stochastic autoregressive generation
  6. 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