LESSON 9 · UNDERSTANDING LLMs

Training an LLM

An LLM becomes useful by learning statistical patterns from a very large collection of text. Training repeatedly shows the model examples, measures how wrong its predictions are, and updates millions or billions of parameters to reduce that error.

25 min readBeginnerGenerative AI

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

  • Describe the main stages of an LLM training pipeline.
  • Explain the training objective using next-token prediction.
  • Understand batches, forward passes, loss, gradients, and parameter updates.
  • Explain epochs, checkpoints, validation, and why training is expensive.
  • Run a tiny Python training example and connect it to the larger LLM workflow.
1

The big picture: training is learning from prediction errors

Training an LLM is an optimization loop. The model sees token sequences, predicts what should come next, compares those predictions with the known next tokens, calculates a loss, and adjusts its parameters so that future predictions are better.

1Collect datalarge text datasets
2Tokenizetext → token IDs
3Predictnext-token probabilities
4Measure losshow wrong was it?
5Updateadjust parameters
The key idea: the model is not given a table saying “this is the correct rule.” It learns useful statistical patterns by repeatedly trying to predict training examples and reducing its prediction error.
2

Step 1: prepare training data

Training starts with a large corpus of text. Before the model sees it, the data must be collected, cleaned, filtered, deduplicated, normalized where appropriate, and converted into a form suitable for training.

Example A — useful training signal“Python lists are ordered collections that can contain multiple values.”The model can learn patterns about language and technical explanations.
Example B — poor training signalRepeated, corrupted, or irrelevant content.Low-quality data can waste compute or teach undesirable patterns.

Important: “more data” is not automatically “better data.” Data quality, diversity, duplication, licensing, safety filtering, and mixture design all matter.

3

Step 2: convert text into training sequences

The tokenizer converts text into token IDs. Those IDs are arranged into sequences that can be processed in batches. For next-token prediction, each position provides a target for the following token.

INPUT TOKENSThe cat sat on the
TARGETmat
InputThe · cat · sat · on · the
Targetcat · sat · on · the · mat

That one-token shift is the basic teaching signal behind next-token prediction. Real training uses many sequences and many positions at once.

4

Step 3: run a forward pass

The model receives a batch of token IDs and computes predictions. Inside the network, embeddings, attention, feed-forward layers, normalization, and other operations transform the representations until the model produces output scores for the vocabulary.

Token IDs[12, 48, 91, 7]
LLMmany neural-network layers
Logitsscores for possible next tokens
Mental model: a forward pass is simply “put the training examples through the model and ask what it predicts.”
5

Step 4: calculate the loss

The training system compares the model's predicted distribution with the correct target tokens. A loss function turns that difference into a number that tells us how well the model performed on the batch.

MODEL PREDICTION“dog” → 0.10   “mat” → 0.70   other → 0.20
CORRECT TARGET“mat”
LOSSLower is betterThe exact loss value depends on the model's probability distribution and the training objective.

For language-model training, cross-entropy is a common loss family. You do not need to memorize the formula yet; understand what the loss is doing: turning prediction quality into a signal the optimizer can use.

6

Step 5: backpropagation finds how parameters contributed to the error

The model contains parameters—learned numerical values such as weights. Backpropagation uses the loss to calculate gradients, which indicate how changing those parameters would affect the loss.

LossHow wrong?
GradientsWhich direction reduces loss?
OptimizerHow large a step?
Gradient

A mathematical signal describing the direction and sensitivity of the loss with respect to parameters.

Parameter

A learned number inside the network that is updated during training.

7

Step 6: the optimizer updates the parameters

An optimizer uses gradients to change the parameters. A simplified update looks like:

new_parameter = old_parameter − learning_rate × gradient

The learning rate controls how large the update steps are. Too large can make training unstable; too small can make learning painfully slow.

OLD PARAMETER0.80
UPDATE0.02
=
NEW PARAMETER0.78
This is a toy illustration. Real LLMs have enormous parameter sets, and optimizers maintain additional state and use more sophisticated numerical details.
8

The training loop repeats—many, many times

One batch produces one set of predictions, loss values, gradients, and updates. Training repeats this process over many batches.

BatchGet token sequences
ForwardPredict
LossMeasure error
BackwardCalculate gradients
UpdateChange parameters
BatchA group of training sequences processed together.
StepOne optimizer update after processing a batch.
EpochOne pass through the chosen training dataset.
CheckpointA saved snapshot of model state during training.
9

See the idea in Python

You can observe the core training loop with a tiny neural network. This is not an LLM—it is deliberately small so you can see the mechanics without needing a large GPU.

</> Python
import torch
from torch import nn

# Tiny dataset: learn y = 2x
x = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y = torch.tensor([[2.0], [4.0], [6.0], [8.0]])

model = nn.Linear(1, 1)
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for step in range(500):
    prediction = model(x)          # forward pass
    loss = loss_fn(prediction, y)  # measure error

    optimizer.zero_grad()
    loss.backward()                 # gradients
    optimizer.step()                # update parameters

print(model(torch.tensor([[5.0]])))
What to notice: the code contains the same four ideas used in much larger training systems—forward pass, loss calculation, backpropagation, and optimizer update. The scale is radically different, but the learning loop is recognizable.
10

How this scales to an LLM

An LLM training run applies the same basic loop to a vastly larger model and dataset. Instead of four tiny examples and one parameterized layer, there may be huge datasets, many layers, very large batches, distributed hardware, mixed-precision arithmetic, optimizer state, checkpoints, and carefully designed evaluation pipelines.

Tiny demo1 model · 4 examples · one machine
LLM trainingLarge model · huge token corpus · many accelerators

The algorithmic pattern is still the same: predict → measure error → compute gradients → update parameters → repeat.

11

Training is not just “make the loss smaller”

A model can become very good at the training data without generalizing well. Training systems therefore monitor held-out validation data and other evaluations.

Training dataUsed to update parameters.
Validation dataUsed to monitor generalization while developing the run.
EvaluationTests capabilities, safety, and other target behaviors.
Break it

Imagine training loss keeps falling while validation performance stops improving.

Fix the reasoning

Do not assume “lower training loss = better model.” Inspect generalization and broader evaluations.

12

Why training an LLM is expensive

Large-scale training requires substantial compute, memory, storage, networking, data processing, experimentation, and engineering. The model parameters must be updated across enormous numbers of training examples.

ComputeAccelerators perform billions or more numerical operations repeatedly.
MemoryParameters, activations, gradients, and optimizer state require substantial memory.
Data pipelineData must be prepared, shuffled, batched, and delivered efficiently.
ReliabilityLong training runs need checkpoints and recovery from failures.
13

Training, inference, and fine-tuning are different

TrainingLearn or update model parameters from a training objective.
InferenceUse an already-trained model to generate predictions or outputs.
Fine-tuningContinue training a model on a narrower dataset or objective to adapt its behavior.

For example, when your Python application sends a prompt to an existing LLM API, you are normally doing inference, not training the base model.

14

Mini-project: watch a model learn

Use the notebook with this lesson to train the tiny regression model, print the loss during training, and change the learning rate.

Task 1Run the baseline training loop and record the final loss.
Task 2Change the learning rate from 0.01 to 0.1. Observe the training behavior.
Task 3Change it to 0.0001. Compare how quickly the loss changes.
ChallengePrint the learned weight and bias. Explain why they approach the target relationship.
PRACTICE

Check your understanding

Answer first, then reveal the explanation.

1What is the purpose of the loss?It summarizes how different the model's predictions are from the training targets so optimization can use that signal.
2What does backpropagation calculate?It computes gradients of the loss with respect to the model's parameters.
3What does an optimizer do?It uses gradients and its update rules to change model parameters in an attempt to reduce future loss.
4Why keep validation data separate from training data?It gives a less biased view of how well the model generalizes beyond the examples used to update its parameters.
QUICK QUIZ

Which sequence best describes one basic training step?

30-second recap

  • Training teaches a model by repeatedly exposing it to examples and measuring prediction error.
  • For next-token training, input tokens are shifted against target tokens.
  • A forward pass produces predictions; a loss function measures error.
  • Backpropagation calculates gradients, and an optimizer updates parameters.
  • Batches and steps repeat many times; checkpoints and validation help manage long training runs.
  • Inference uses an already-trained model; fine-tuning is additional training for adaptation.