Pretraining
Pretraining is the first and by far the biggest stage of building a language model. The model reads a huge amount of text and, at every position, tries to predict the next token. Each wrong guess produces a loss, and backpropagation nudges the parameters so the right token becomes a little more likely next time. Repeated over trillions of tokens, this one simple task teaches grammar, facts, reasoning patterns and styles of writing.
The result is a base model: very good at continuing text, but not yet an assistant that follows instructions. That comes next, in "Instruction Tuning and RLHF".
The Pretraining Recipe
| Step | Description |
|---|---|
| Collect text | Web pages, books, papers and code, often trillions of tokens; SmolLM2 used educational web text, general web text and code |
| Clean it | It is used to remove duplicates, spam, low-quality pages and personal data |
| Tokenize it | Split everything into tokens with the model's tokenizer |
| Predict the next token | At every position, score all tokens and compute the cross-entropy loss for the real one |
| Update the weights | Backpropagation and an optimizer such as AdamW, as in "Training a Network in PyTorch" |
| Repeat | Over all the data once or a few times, on hundreds or thousands of GPUs for weeks |
No one labels anything: the text itself is the answer key, because the next token is always known. This is called self-supervised learning.
Example: How Good Is a Pretrained Model at Predicting?
The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown.
This program asks SmolLM2-135M how likely it found each real next token in a sentence, then compares a normal sentence with the same words shuffled.
import math
import random
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model.eval()
def token_probs(text):
ids = tokenizer(text, return_tensors="pt").input_ids
with torch.no_grad():
logits = model(ids).logits[0, :-1] # the prediction made at each position
probs = logits.softmax(dim=-1)
actual = ids[0, 1:] # the token that really came next
return [tokenizer.decode(t) for t in actual], probs[range(len(actual)), actual]
text = "Students should bring a pencil and a calculator to the math exam."
tokens, p = token_probs(text)
print("How likely the model found each real next token:")
for t, q in zip(tokens, p):
print(f" {t!r:14} {q:6.1%} loss {-math.log(q):.2f}")
def perplexity(text):
_, p = token_probs(text)
loss = -p.log().mean().item() # the pretraining loss: average -log probability
return loss, math.exp(loss)
words = text.split()
random.Random(0).shuffle(words)
for name, t in [("Normal", text), ("Shuffled", " ".join(words))]:
loss, ppl = perplexity(t)
print(f"\n{name}: {t!r}\n loss {loss:.2f}, perplexity {ppl:.1f}")How likely the model found each real next token:
' should' 1.8% loss 4.03
' bring' 0.1% loss 6.78
' a' 16.8% loss 1.78
' pencil' 1.6% loss 4.15
' and' 32.6% loss 1.12
' a' 28.3% loss 1.26
' calculator' 0.6% loss 5.11
' to' 28.3% loss 1.26
' the' 20.6% loss 1.58
' math' 0.3% loss 5.87
' exam' 0.2% loss 6.36
'.' 56.2% loss 0.58
Normal: 'Students should bring a pencil and a calculator to the math exam.'
loss 3.33, perplexity 27.9
Shuffled: 'should the to and math bring a calculator pencil Students exam. a'
loss 8.69, perplexity 5928.3Explanation:
logits[0, :-1]are the predictions made at each position, andids[0, 1:]are the tokens that actually came next: the text shifted by one. This is exactly how pretraining lines up inputs and targets.- Easy tokens get high probability: "and" after "a pencil" (32.6%) and the final period (56.2%). Surprising tokens get low probability: "bring" (0.1%) and "exam" (0.2%; the model expected "center", "test" or "class" after "the math").
- The loss for a token is
-log(probability): 0.58 for the period, 6.78 for "bring". The pretraining loss is the average over all tokens: 3.33 for this sentence. - Perplexity is
eto the power of the loss: 27.9 means the model was, on average, about as unsure as choosing among 28 equally likely tokens. The shuffled sentence has a perplexity of 5,928.3: the model clearly knows what normal English looks like.
Example: Pretraining a Tiny GPT from Scratch
Real pretraining needs huge computers, but the method fits in one program. This one makes up 2,000 school announcements, then pretrains a tiny GPT-style model (2 Transformer blocks, about 109,000 parameters) to predict the next character.
import random
import torch
from torch import nn
# 1. Training text: 2,000 made-up school announcements
rng = random.Random(0)
events = ["science fair", "book sale", "spring concert", "math club", "field trip", "art show"]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
places = ["library", "gym", "cafeteria", "music room"]
text = "".join(f"The {rng.choice(events)} is on {rng.choice(days)} at {rng.randint(1, 12)} in the {rng.choice(places)}.\n"
for _ in range(2000))
chars = sorted(set(text)) # a character-level vocabulary
data = torch.tensor([chars.index(c) for c in text])
print(f"Training text: {len(text):,} characters, vocabulary of {len(chars)} characters")
# 2. A tiny GPT: embeddings + positions, 2 Transformer blocks, a layer that scores the next character
class TinyGPT(nn.Module):
def __init__(self, vocab, context=64, d=64, heads=4, layers=2):
super().__init__()
self.tok = nn.Embedding(vocab, d)
self.pos = nn.Embedding(context, d)
block = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True, norm_first=True)
self.blocks = nn.TransformerEncoder(block, layers, enable_nested_tensor=False)
self.out = nn.Linear(d, vocab)
def forward(self, x):
n = x.shape[1]
h = self.tok(x) + self.pos(torch.arange(n))
causal = nn.Transformer.generate_square_subsequent_mask(n) # no peeking at later characters
return self.out(self.blocks(h, mask=causal, is_causal=True))
torch.manual_seed(0)
model = TinyGPT(len(chars))
print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
optimizer = torch.optim.AdamW(model.parameters(), lr=0.003)
def sample(length=60):
model.eval()
x = torch.tensor([[chars.index("T")]])
for _ in range(length):
with torch.no_grad():
probs = model(x[:, -64:])[0, -1].softmax(dim=0)
x = torch.cat([x, torch.multinomial(probs, 1)[None]], dim=1)
model.train()
return "".join(chars[i] for i in x[0]).split("\n")[0]
# 3. Pretraining: predict every next character, again and again
for step in range(1, 1501):
starts = torch.randint(len(data) - 65, (32,))
x = torch.stack([data[s:s + 64] for s in starts]) # 32 pieces of 64 characters
y = torch.stack([data[s + 1:s + 65] for s in starts]) # the same pieces shifted by one
loss = nn.functional.cross_entropy(model(x).reshape(-1, len(chars)), y.reshape(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step in (1, 100, 300, 1500):
print(f"\nstep {step:4} loss {loss.item():.3f}\n sample: {sample()}")Training text: 101,823 characters, vocabulary of 38 characters
Parameters: 108,966
step 1 loss 4.016
sample: TourfTdllt8koppdTiaM1ca32wgfg.7Tlo m mTiy bha8ib3p9.n 3Wa7cr3
step 100 loss 0.453
sample: Thesday at at 1 4 1 in We the musiciom.
step 300 loss 0.194
sample: The math club is on Wednesday at 2 in the cafeteria.
step 1500 loss 0.167
sample: The science fair is on Thursday at 7 in the gym.Explanation:
- The training text is 101,823 characters with only 38 different characters, so this model's vocabulary is characters instead of BPE tokens.
TinyGPThas the same plan as SmolLM2 at a tiny size: token and position embeddings, 2 Transformer blocks with a causal mask, and an output layer that scores every character.- Each step takes 32 random pieces of 64 characters, and the targets are the same pieces shifted by one character. The loss is cross-entropy over every position at once.
- Step 1: the weights are random, the loss is 4.016 (a little above
log 38 = 3.64, the loss of guessing all 38 characters equally), and the sample is noise. - Step 100: it has learned the shape of an announcement and some words, but mixes them up: "Thesday at at 1 4 1 in We the musiciom."
- Step 300 and 1,500: correct announcements. The loss stops near 0.17 rather than 0, because the event, day, time and place were chosen at random and can't be predicted.
With the seeds in the program, it gives the same output every run on the same machine and PyTorch version.
What Pretraining Produces
| A base model is | A base model is not |
|---|---|
| Good at continuing text in the style it is given | An assistant that answers questions directly |
| Full of knowledge from its training text, up to its cutoff date | Always correct; it learned what is likely, not what is true |
| The starting point for instruction tuning and fine-tuning | Updated by your conversations; see "Does AI Learn from Every Conversation?" |
Common Mistakes
Thinking pretraining stores documents. The model stores patterns in its weights; it can sometimes repeat text it saw many times, but it has no library to look things up in.
Judging a model by training loss alone. Like any model, it must be tested on text it did not train on.
Thinking more data always helps. Low-quality or duplicated text can make a model worse; data cleaning is a large part of the work.
Forgetting the shift by one. Inputs and targets are the same text offset by one token; getting this wrong trains the model to copy, not predict.
Interview Corner
What is the pretraining objective of a GPT-style model?
Next-token prediction: at every position, minimize the cross-entropy loss of the real next token given all earlier tokens. It is self-supervised, since the text provides its own labels.
What is perplexity?
The exponential of the average loss per token. It is roughly the number of equally likely choices the model is unsure between; lower is better.
Practice
Exercise: a new kind of announcement. Add a second template to the tiny GPT's training text, such as "Bring your {item} on {day}." with a list of items. How many steps does it take before samples use both templates correctly?
Check your understanding:
- Why does pretraining not need anyone to label the data?
- What did a perplexity of 27.9 versus 5,928.3 show?
- Why did the tiny GPT's loss stop near 0.17 instead of reaching 0?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Inputs and targets | x = data[s:s + n], y = data[s + 1:s + n + 1] |
| Next-token loss | cross_entropy(logits.reshape(-1, vocab), y.reshape(-1)) |
| Probability of each real token | logits[0, :-1].softmax(-1)[range(n), ids[0, 1:]] |
| Perplexity | math.exp(average_loss) |
| Causal mask | nn.Transformer.generate_square_subsequent_mask(n) |
| Sample a token | torch.multinomial(probs, 1) |
Was this tutorial helpful?