LESSON 10 · UNDERSTANDING LLMs

Pre-training

Pre-training is the large-scale learning stage where a language model learns broad patterns from a huge collection of text. The core task is simple: predict the next token, measure the error, and update the model repeatedly.

25 min readBeginnerGenerative AI

By the end of this lesson, you will be able to:

  • Explain what pre-training means and why it comes before task-specific adaptation.
  • Trace raw text through tokenization, sequences, next-token targets, loss, and parameter updates.
  • Understand why scale, data quality, compute, and training duration matter.
  • Run a tiny Python language-model pre-training example and inspect its predictions.
  • Distinguish pre-training from inference, fine-tuning, and instruction tuning.
1

Pre-training in one picture

Think of pre-training as building the model's general language foundation. The model is not initially taught “answer customer emails” or “write Python.” It is exposed to enormous amounts of token sequences and learns statistical relationships that can later support many tasks.

1Large text corpusbooks, web pages, code, documents, and other permitted data
2Tokenizeconvert text into token IDs
3Predict next tokenproduce a probability distribution
4Calculate losscompare prediction with target
5Update parametersrepeat across many batches
Simple idea: pre-training teaches a model general-purpose representations by making it practice next-token prediction over and over.
2

Why do we pre-train a model?

Starting from random parameters gives the model no useful language knowledge. Pre-training lets it discover patterns such as word relationships, syntax, common facts, code structures, and relationships between pieces of text.

Language patternsGrammar, word relationships, phrasing, and long-range dependencies.
World patternsRecurring facts, concepts, entities, and relationships present in the training data.
Useful representationsInternal features that later tasks can reuse instead of learning everything from scratch.

Important: pre-training does not guarantee truth. A model learns patterns from its training data; it does not receive a built-in database of verified facts.

3

Step 1: build a training corpus

A pre-training run starts with a very large collection of data. A production pipeline may combine multiple sources, apply quality filters, remove duplicates, manage permissions, and construct a mixture with deliberate proportions.

Useful signalClear, diverse, relevant text with strong linguistic or technical content.
Potential problemDuplicates, corrupted text, spam, unsafe content, or data that should not be included.
Think like a data engineer: every token processed by the model consumes compute. Low-quality or duplicated data can spend that compute without adding equivalent learning value.
4

Step 2: turn text into prediction examples

The tokenizer maps text to token IDs. A sequence can then be shifted by one position so the model receives an input and a target at every position.

INPUTThe model learns
TARGETlanguage patterns
Input tokensThe · model · learns · language
Target tokensmodel · learns · language · patterns

One sequence therefore supplies several training positions. Across millions or billions of sequences, this creates an enormous number of prediction opportunities.

5

The pre-training objective: next-token prediction

At each position, the model produces probabilities for possible next tokens. The training target tells it which token actually followed in the dataset. The loss function turns the difference into a number that optimization can minimize.

Context“The sky is”
blue0.72
green0.08
cloud0.05
other0.15
Training targetblue

If the target token receives a high probability, the loss is relatively small. If the model assigns it very little probability, the loss is larger and the gradient provides a stronger learning signal.

6

Step 3: repeat the learning loop

Pre-training is not one pass through the corpus. The system processes batches, runs forward passes, calculates loss, backpropagates gradients, updates parameters, records metrics, and periodically saves checkpoints.

Batchtoken sequences
Forward passmodel predictions
Lossprediction error
Backward passgradients
Optimizerparameter update
Training lossIs the model improving on the training objective?
Validation lossDoes the learned pattern transfer to held-out data?
ThroughputHow many tokens can the system process efficiently?
CheckpointCan the long-running job resume safely?
7

Why scale changes everything

The learning algorithm can remain conceptually simple while the engineering becomes enormous. Larger models, more tokens, and more compute can improve capability, but they also increase memory, communication, storage, and reliability requirements.

Small experimentOne GPU or CPU

Thousands of examples can be enough to understand the mechanics.

Production pre-trainingMany accelerators

Huge token datasets require distributed training, efficient input pipelines, monitoring, and recovery.

Key distinction: “pre-training” describes the learning stage and objective. It does not mean every pre-trained model has the same architecture, dataset, compute budget, or training recipe.
8

Build a tiny pre-training model in Python

We can reproduce the core idea on a tiny scale. This model learns to predict the next word from the previous word. It is not an LLM, but the objective mirrors the essential next-token learning loop.

import torch
from torch import nn

sentences = [
    "cats chase mice",
    "cats like milk",
    "dogs chase balls",
    "dogs like walks",
]

words = sorted({word for sentence in sentences for word in sentence.split()})
word_to_id = {word: i for i, word in enumerate(words)}

pairs = []
for sentence in sentences:
    ids = [word_to_id[word] for word in sentence.split()]
    pairs.extend((ids[i], ids[i + 1]) for i in range(len(ids) - 1))

x = torch.tensor([a for a, _ in pairs])
y = torch.tensor([b for _, b in pairs])

model = nn.Sequential(
    nn.Embedding(len(words), 16),
    nn.Linear(16, len(words))
)

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.03)

for step in range(400):
    logits = model(x)
    loss = loss_fn(logits, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

context = torch.tensor([word_to_id["cats"]])
probs = model(context).softmax(dim=-1)[0]

for word, score in sorted(zip(words, probs.tolist()), key=lambda item: item[1], reverse=True):
    print(f"{word:8} {score:.3f}")
What you should noticecats → chase / likeThe model has learned distributional patterns from the tiny corpus. With more data and a richer architecture, the same objective can be scaled dramatically.
9

Change the data and watch the learned distribution change

This is one of the most useful pre-training experiments: change the corpus, train again, and compare the model's predictions. The learned behavior changes because the training signal changed.

BASELINEcats chase mice

“cats” receives probability for words that frequently follow it.

ADD DATAcats drink water

Now “drink” and the resulting patterns become part of the learned distribution.

COMPAREsame architecture

The difference comes from the training examples, not from changing the model structure.

Try it: add five sentences about a different topic. Retrain and inspect the predictions. This demonstrates why the training corpus strongly influences what a model learns.
10

Pre-training vs fine-tuning vs instruction tuning

Pre-trainingLearn broad patterns from a large corpus using a general training objective.Foundation
Fine-tuningContinue training on a narrower dataset or objective to adapt the model.Adaptation
Instruction tuningTrain on instruction-and-response examples so the model better follows requested tasks.Behavior

These stages can be combined in different system designs, but they answer different questions: What broad patterns can the model learn?How should it adapt?How should it respond to instructions?

11

Common misconceptions

“Pre-training stores a copy of every document.”Parameters encode learned statistical patterns; they are not simply a searchable file system of the corpus.
“Lower training loss means the model knows everything.”Loss measures the training objective. It does not prove factual accuracy, safety, or performance on every task.
“More raw data is always better.”Quality, diversity, duplication, permissions, filtering, and mixture design all affect the value of the data.
“Calling an API is pre-training.”Sending a prompt to an already-trained model is normally inference. The model's base parameters are not being updated by your request.
12

Mini-project: build a tiny pre-training experiment

Use the notebook with this lesson to train the small next-word model and then deliberately change its training corpus.

Task 1Run the baseline and record the top three predictions after “cats”.
Task 2Add “cats drink water” and retrain. Compare the predictions.
Task 3Add unrelated sentences about databases. Check whether the model's distribution changes.
ChallengeExplain why the data changed the model's behavior even though the architecture stayed the same.
PRACTICE

Check your understanding

Answer first, then reveal the explanation.

1What is the central objective of autoregressive pre-training?Predict the next token from the tokens that came before it, then use the prediction error as a learning signal.
2Why is data quality important?Training compute is limited and valuable. Poor, duplicated, or unsuitable data can waste compute or teach undesirable patterns.
3What changes during optimization?The optimizer uses gradients to update the model parameters so future predictions can better match the training targets.
4Is sending a prompt to an API pre-training?No. That is normally inference: you are using parameters that were already trained.
QUICK QUIZ

Which statement best describes pre-training?

30-second recap

  • Pre-training builds a broad language foundation before task-specific adaptation.
  • Large corpora are cleaned, filtered, deduplicated, tokenized, and arranged into training sequences.
  • The common autoregressive objective is next-token prediction.
  • Loss, backpropagation, and optimization repeatedly improve the model's parameters.
  • Scale introduces major data, compute, memory, networking, evaluation, and reliability challenges.
  • Pre-training, fine-tuning, and instruction tuning are different stages with different goals.