Modules
04/30
GPT Pretraining

Contents

GPT Pretraining

How a pile of text becomes a next-token predictor, one gradient update at a time.

The Training Example Hidden in Text

GPT pretraining looks complicated because a serious run involves enormous datasets, thousands of accelerators, and weeks of coordination. The learning problem at the center is much smaller. Take a piece of text, hide the next token, and ask the model to predict it from the tokens on its left.

inputAmodellearnsonetokenata
targetmodellearnsonetokenatatime

The target row is just the input row shifted one place to the left. Seven input positions become seven supervised predictions. No one had to annotate a subject, write a question, or choose a label. The text provides both the context and the answer.

The entire objective in one sentence

Increase the probability of the token that actually came next, at every position in every training sequence.

What Pretraining Means

GPT stands for Generative Pre-trained Transformer. Generative means the model defines a probability distribution over continuations. Transformer names the neural architecture. Pre-trained means these weights are learned before the model is adapted to a narrower job such as following instructions, answering in a chat format, or writing code in a house style.

The original GPT work used a two-stage recipe: learn a general language model from unlabeled text, then fine-tune it on labeled tasks. GPT-2 pushed harder on the first stage and showed that a larger next-token model could perform some tasks from text alone. GPT-3 scaled the same broad autoregressive setup further and studied zero-shot, one-shot, and few-shot behavior without changing weights at evaluation time.

Before training

Weights are random. Token probabilities are effectively useless.

During pretraining

The model repeatedly predicts real text and corrects its weights.

After pretraining

The base model can score and continue text, but it is not automatically a chat assistant.

1. The Data Pipeline

Pretraining starts before the first GPU sees a batch. A corpus is assembled from documents, code, books, reference material, or other licensed and permitted sources. The exact mixture is part of the model design. It decides which patterns the model sees often, which languages receive capacity, and which errors will be repeated enough to learn.

1
Collect

Acquire documents and preserve source metadata.

2
Extract

Remove navigation, markup, and broken text.

3
Filter

Apply language, quality, safety, and policy rules.

4
Deduplicate

Remove exact and near-duplicate passages.

5
Mix

Choose source weights and create train and validation splits.

Deduplication has two jobs. It stops frequently copied pages from consuming a disproportionate share of updates, and it reduces overlap between training data and evaluation sets. GPT-2 already treated n-gram overlap as a measurement problem. At larger scales, weak deduplication can make a benchmark look like reasoning when part of the answer was present in the training corpus.

Data errors become model behavior

The optimizer cannot tell whether a repeated pattern is useful, false, private, toxic, or copied. It only sees whether predicting that pattern lowers loss. Filtering and provenance are not cleanup around the training job. They are part of the training job.

2. Text Becomes Tokens

A transformer does not receive words. It receives integer IDs from a fixed vocabulary. The tokenizer converts a string into a sequence of tokens, and an embedding table converts each ID into a learned vector.

“unbelievable”
unbelievable
[403, 11291, 540]

The split above is illustrative because the exact pieces depend on the tokenizer. GPT-2 used byte-level BPE. It begins from bytes, then learns frequent adjacent merges. Common strings can become one token, while unusual strings fall back to smaller pieces without requiring an unknown-token escape hatch for ordinary byte sequences.

Words only

Short sequences, but an unmanageably large vocabulary and unknown words.

tensorization → <UNK>
Characters or bytes

Tiny vocabulary and broad coverage, but much longer sequences.

t e n s o r ...
Subwords

A compromise: common spans stay compact and rare strings decompose.

tensor + ization

Tokenization is not cosmetic. It sets the sequence length seen by the model, the size of the input and output matrices, and the unit used by cross-entropy. Perplexities from two different tokenizers are therefore not directly comparable.

3. Inputs and Shifted Labels

Tokenized documents are separated by an end-of-document token and packed into fixed-length windows. If a training sample contains T+1T+1 tokens, the first TT are the model input and the last TT are the target.

X=[x1,x2,,xT]X = [x_1, x_2, \ldots, x_T]
Y=[x2,x3,,xT+1]Y = [x_2, x_3, \ldots, x_{T+1}]

This is often called teacher forcing. At position tt, the model receives the real prefix from the dataset, not tokens sampled from its own earlier predictions. That makes training parallel and stable, but it also creates a difference from generation, where the model must condition on whatever it generated a moment ago.

Document boundaries still matter

Packing makes GPU work dense, but unrelated documents should not silently look like one continuous paragraph. An explicit boundary token tells the model that one document ended and another began. Some training setups also prevent attention across packed boundaries.

4. The Causal Mask

The full target sequence is in GPU memory during training. Without a mask, self-attention at position tt could read position t+1t+1, which contains the answer it is supposed to predict. Training loss would collapse for the wrong reason.

Attention(Q,K,V)=softmax ⁣(QKdk+M)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V
Mt,j=0 if jt,Mt,j= if j>tM_{t,j}=0 \text{ if } j\le t, \qquad M_{t,j}=-\infty \text{ if } j>t

After softmax, entries receiving -\infty have probability zero. The attention matrix is lower triangular: a token can use itself and its left context, never its right context.

Interactive: Causal Mask

Select a query row to see which keys it can read and which next token it must predict. Notice that later rows receive more context, but none can see its target.

Causal self-attention

Choose a query row. Green cells are visible to that position. Future tokens stay blocked.

k1A
k2model
k3learns
k4one
k5token
k6at
k7a
Current query
q4 = “one
Visible context
4 of 7 positions
Training target
token

5. Every Position Predicts

GPT generates sequentially, but it does not pretrain sequentially. During generation, token t+1t+1 does not exist until token tt has been sampled. During pretraining, the complete ground-truth sequence already exists. The causal mask preserves the legal information boundary, so all positions can run through the transformer together.

Pretraining

[B, T] → [B, T, V]

All B×TB\times T target positions contribute loss in one forward pass.

Autoregressive generation

[B, 1] → [B, 1, V]

Only the newest position is needed, then one token is selected and appended.

This distinction is easy to miss and it explains why training hardware is built around large matrix multiplications, while serving has a separate set of problems around KV cache memory, batching, and per-token latency.

6. Through the GPT Stack

Each token ID indexes a row in the embedding matrix. Positional information is added or applied, then the sequence passes through a stack of decoder blocks. A modern block usually contains causal self-attention, an MLP, normalization, residual connections, and dropout during training.

1
Token and position representation
[B, T] → [B, T, d]
2
Causal multi-head self-attention
tokens exchange information only from left to right
3
Residual addition and normalization
preserve a stable path through many layers
4
Position-wise MLP
expand, transform, and project each position independently
5
Repeat for L blocks
the same sequence becomes a deeper contextual representation
6
Final normalization and language-model head
[B, T, d] → [B, T, V]

The model has no separate grammar table, fact store, or code parser. The same weights are reused at every sequence position. Whatever structure helps next-token prediction must be represented inside those shared matrices and the activations they produce.

7. Logits and Softmax

The final hidden vector at each position has width dd. The language-model head projects it to VV numbers, one for every vocabulary token. These raw scores are logits.

zt=htWvocab+bz_t = h_t W_{\text{vocab}}^\top + b
p(xt+1=vxt)=ezt,vu=1Vezt,up(x_{t+1}=v\mid x_{\le t}) = \frac{e^{z_{t,v}}}{\sum_{u=1}^{V} e^{z_{t,u}}}

Softmax turns the logits into a probability distribution. Increasing one logit increases that token's probability and decreases the share left for the rest. The output matrix is often tied to the input embedding matrix, which reuses the same learned token geometry on both sides of the network.

Training does not sample here

Sampling choices such as temperature and top-p belong to generation. Pretraining keeps the full probability distribution and asks how much probability it assigned to the known target token.

8. Cross-Entropy Loss

For one position, the loss is the negative natural logarithm of the probability assigned to the correct next token:

t=logpθ(xt+1xt)\ell_t = -\log p_\theta(x_{t+1}\mid x_{\le t})
L=1N(b,t)validlogpθ(yb,txb,t)\mathcal{L} = -\frac{1}{N}\sum_{(b,t)\in\text{valid}} \log p_\theta(y_{b,t}\mid x_{b,\le t})

If the correct token receives probability 0.9, its loss is about 0.105. At probability 0.1, the loss is about 2.303. At probability 0.001, the loss is about 6.908. The logarithm punishes confident mistakes sharply and gives the optimizer a useful signal even when the correct token is not the top prediction.

Padding tokens and sometimes cross-document positions are removed from the average with a loss mask. What remains is one scalar, even though it summarizes thousands or millions of token predictions across the effective batch.

Interactive: Token Loss

Move the probability assigned to the true next token. The other candidate bars share the remaining probability mass. Watch how slowly loss falls near certainty and how quickly it rises near zero.

Cross-entropy under a microscope
The capital of France is [Paris]
Paris
62.0%
Lyon
15.2%
the
10.3%
located
7.6%
France
4.9%
Target lookup
p(y) = 0.62
Token loss
-ln p(y) = 0.478
Perplexity
exp(loss) = 1.61

9. Backpropagation and Update

Cross-entropy tells us how wrong the batch was. Backpropagation tells us which parameters contributed to that error. Automatic differentiation applies the chain rule from the scalar loss, through the vocabulary head, every transformer block, and back to the embeddings.

g=θLg = \nabla_\theta \mathcal{L}
θAdamW(θ,g,η)\theta \leftarrow \operatorname{AdamW}(\theta, g, \eta)

AdamW does more than subtract the raw gradient. It keeps moving averages of first and second moments, rescales updates, applies weight decay to selected parameters, and uses a learning rate schedule. Large GPT runs commonly warm the learning rate up, then decay it over training. Gradient clipping, mixed precision, and loss scaling are engineering safeguards around the same update.

tokens = next_batch()
inputs = tokens[:, :-1]
targets = tokens[:, 1:]

logits = model(inputs)
loss = cross_entropy(logits, targets)

optimizer.zero_grad(set_to_none=True)
loss.backward()
clip_grad_norm_(model.parameters(), max_norm)
optimizer.step()
scheduler.step()

Real systems add distributed collectives, gradient accumulation, checkpointing, fused kernels, and failure recovery. They do not change the conceptual loop shown above.

Interactive: Training Step

Adjust the batch and sequence dimensions, then step through the five phases. A batch of BB sequences with length TT supplies B×TB\times T next-token targets before masking.

One optimizer step

Change the batch shape, then walk through the work performed before the next batch begins.

Supervised predictions per step
4,096
B × T = 8 × 512
Stage 1 of 5

Read token IDs and their one-position-shifted targets.

No human labels are loaded. The sequence itself supplies every target.

10. Validation and Perplexity

Training loss measures fit on batches used for updates. Validation loss runs the same objective on held-out text without changing the weights. If training loss keeps falling while validation loss stalls or rises, the model is memorizing the training distribution faster than it is improving on unseen text.

perplexity=exp(Lvalidation)\operatorname{perplexity} = \exp(\mathcal{L}_{\text{validation}})

A loss of 2.0 corresponds to perplexity 7.39. A loss of 1.5 corresponds to 4.48.

Perplexity can be read as an effective number of equally plausible choices, but only as an intuition. A vocabulary contains tens of thousands of uneven choices, and tokenization changes the units. Compare perplexity only when the dataset, tokenization, context treatment, and loss masking are aligned.

A low held-out language-model loss is useful, but it is not a complete evaluation. Teams also measure downstream capabilities, memorization, bias, factuality, safety, multilingual behavior, code behavior, and performance across document sources.

11. Model, Data, and Compute

Once the training loop works, the main allocation question is how to spend a fixed compute budget. More parameters increase capacity. More training tokens provide more evidence. More compute lets the optimizer apply more updates. Starve any one of the three and the other two hit diminishing returns.

ModelParametersContextPretraining dataWhat changed
GPT117M512BooksCorpusGeneral pretraining followed by task fine-tuning
GPT-21.5B1,02440 GB WebTextByte-level BPE and stronger zero-shot transfer
GPT-3175B2,048300B training tokensFew-shot tasks expressed in the prompt

The early scaling-law work found smooth power-law relationships between loss and model size, dataset size, and training compute. Chinchilla later showed that many large models were undertrained for their parameter count. With the same compute budget as the 280B-parameter Gopher model, a 70B-parameter model trained on 1.4 trillion tokens performed better across the reported evaluation suite.

Bigger is not one number

Parameter count by itself says little about whether a run used its compute well. The useful unit is the joint choice of architecture, parameter count, training tokens, data quality, batch schedule, and total compute.

12. Training Across GPUs

A large GPT model may not fit on one accelerator, and one accelerator may take years to process the planned tokens. Distributed training splits the work along several axes.

Data parallelism

Replicas process different microbatches, then synchronize gradients.

Tensor parallelism

Large weight matrices and their multiplications are partitioned across devices.

Pipeline parallelism

Different groups own different layer ranges and pass activations between stages.

Gradient accumulation adds another lever. Several microbatches run forward and backward before one optimizer update, which creates a larger effective batch without storing every activation at once. Activation checkpointing saves memory by discarding selected intermediate activations and recomputing them during backward.

The difficulty is no longer the loss formula. It is keeping expensive hardware busy while communication, memory, numerical stability, checkpoint writes, and failed workers all compete with useful matrix multiplication.

13. What the Objective Learns

Next-token prediction sounds narrow, but a good prediction often requires structure. To complete a sentence, the model benefits from syntax. To continue a function, it benefits from tracking variables and indentation. To finish a paragraph about a historical event, it benefits from associations between names, dates, places, and typical explanations.

Local form

spelling, punctuation, syntax, and common phrase structure

Longer context

topic, entities, references, document format, and narrative state

Task patterns

translation pairs, question-answer formats, code-docstring pairs, and worked examples

Uncertainty

multiple plausible continuations represented as a probability distribution

This does not mean the objective verifies truth, discovers causal models, or stores knowledge like rows in a database. It rewards predictive usefulness on the training distribution. A fluent falsehood can lower loss if similar falsehoods are common in the data. An obscure fact may never receive enough signal to be represented reliably.

Prediction is not verification

Pretraining optimizes the probability of text, not the correctness of claims. Retrieval, tools, citations, post-training, and external checks address problems that the next-token objective does not solve by itself.

14. Pretraining Is Not Chat Training

A base GPT model continues text. If the prompt looks like an article, it continues an article. If it looks like source code, it continues code. If it looks like a conversation, it may continue any participant because pretraining alone does not define which role it should play.

StageTypical dataWhat changes
PretrainingLarge collections of text and codeGeneral continuation ability and broad representations
Instruction tuningPrompt and desired-response pairsFollowing requests and producing an assistant response
Preference and safety trainingRankings, critiques, policies, or reward signalsWhich valid responses are preferred or disallowed

These stages may still use a token-level loss somewhere in the implementation, but their data and objective are different. Saying that a chat assistant is “just next-token prediction” skips the post-training that determines how the base model is presented and controlled.

15. What Can Go Wrong

01
Bad mixture

A source can dominate simply because it is easy to collect or heavily duplicated.

02
Evaluation leakage

Benchmark questions or close variants can enter the training corpus and inflate reported scores.

03
Tokenizer imbalance

Some languages and domains require many more tokens for the same amount of content.

04
Optimization instability

Loss spikes, overflow, poor initialization, or an aggressive learning rate can damage a run.

05
Undertraining

A model may have more parameters than the available tokens and compute can train effectively.

06
Overfitting and memorization

Repeated or rare strings can be reproduced even while average validation loss looks healthy.

07
Hardware failure

A single bad checkpoint, silent data corruption, or worker divergence can waste a large amount of compute.

The Whole Pipeline

  1. 1Collect, filter, deduplicate, and mix documents.
  2. 2Train or select a tokenizer, then convert text to token IDs.
  3. 3Insert document boundaries and pack fixed-length sequences.
  4. 4Shift each sequence by one position to make inputs and targets.
  5. 5Run the input through a decoder-only transformer with a causal mask.
  6. 6Project every final hidden state to vocabulary logits.
  7. 7Compute mean cross-entropy on the correct next tokens.
  8. 8Backpropagate gradients and update the shared weights.
  9. 9Repeat across distributed hardware while validating on held-out data.
  10. 10Stop with a base model, then run separate post-training if an assistant is the goal.

That is GPT pretraining. The scale changes, the architecture details evolve, and the systems engineering becomes harder. The central contract stays fixed: given the tokens on the left, assign more probability to the token that came next.