Backpropagation and LLM Training


Backpropagation and LLM Training

Simon
You hear words like neural networks, gradients, weights, fine-tuning, Adam, and learning rates all the time. Behind many of them is one important mechanism: backpropagation. It is central to understanding how modern neural networks are trained, though AI as a whole is much broader than backpropagation.

Corey
So today we’re tackling the big questions: how does a model learn, what changes inside it, and how do gradients and gradient descent fit in? We’ll also distinguish training from inference, explain why training costs more, and answer a question people often ask: does ChatGPT backpropagate while it answers you?

Simon
Let’s start with a house-price model. Give it the house’s size, number of bedrooms, location score, and age. In a simple model, it multiplies each input by a weight and adds the results to produce a predicted price.

Corey
Think of each weight as a knob. One controls how much size matters, another how much bedrooms matter, and so on. Turn a knob and the model’s behavior changes. Real networks may have millions or billions of these adjustable parameters, so if a prediction is wrong, the challenge is knowing which knobs to turn, which direction, and by how much.

Simon
A tea recipe makes that challenge easier to picture. You choose how much tea, sugar, and milk to use, and how long to brew it. Someone tastes the result and gives it a rating. If they say it is too sweet and too strong, just hearing “the tea is bad” is not enough—you need feedback about which choices contributed and how to adjust them.

Corey
In that analogy, the recipe choices are weights. Making the tea is forward propagation. The taste rating is the loss, or measure of how unsatisfactory the result was. Tracing the feedback back to the recipe is backpropagation, changing the recipe is optimization, and repeating the process is training. A sequence of attempts might improve from four out of ten to six, then eight, then nine and a half.

Simon
Now let’s make the first step technical. Forward propagation means sending an input through the network, layer by layer, to produce an output—a prediction. Show a network a cat image and it might predict cat at thirty percent and dog at seventy percent. That is a forward pass, but no learning has happened yet.

Corey
The same thing happens with a language model. Give it “Paris is the capital of” and it might assign probabilities to possible next words, such as France, London, or Rome. It has made a prediction. If the correct answer is cat but the image model predicts dog, we need to measure how wrong that prediction was.

Simon
That measurement is the loss. A perfect prediction would have very low loss; a poor prediction would have high loss. Loss turns the question “How wrong was the model?” into a number that the training process can use.

Corey
And now the billion-knob problem returns. We have a loss, but which of all those parameters contributed to it? Backpropagation starts from the loss and works backward through the network to calculate how changing each parameter would affect the error.

Simon
Forward, information travels from the input through the layers to a prediction. Backward, gradient information travels from the loss through the same computational graph. It is not a literal object called “the error” being copied backward. Backpropagation calculates gradients through the graph.

Corey
So the short version is: forward asks, “What did I predict?” Backward asks, “How would parameter changes affect the loss?” Another analogy is a company pipeline: research informs design, design informs engineering, and engineering informs the customer experience. If the experience gets a poor score, you trace influences back through the pipeline rather than blaming every department equally.

Simon
That company example is only an analogy. Backpropagation does not assign human blame; it calculates mathematical sensitivity. It asks: if this value changed a little, how much would the final loss change? That sensitivity is what we call a gradient.

Corey
Picture one weight set to five. If we nudge it to five point one and the loss gets worse, increasing it was the wrong direction, so an update should push it the other way. A gradient tells us how the loss changes as a parameter changes, including the direction and strength of that response.

Simon
One important distinction: the gradient does not update the weight by itself. It is information. An optimizer uses that information to choose and apply an update. Backpropagation calculates the gradient; the optimizer uses it to change the weights.

Corey
Imagine standing on a hill in fog, where your height represents the loss. Backpropagation works out the slope and tells you which way is downhill. The optimizer takes the step. Stochastic gradient descent, or SGD, takes a straightforward step in the downhill direction. Adam keeps running estimates of the slope and adapts its steps over time; AdamW is a refinement of Adam that handles weight decay differently.

Simon
Then there’s the learning rate: how large each update step should be. If it is too small, progress is very slow. If it is too large, the updates can overshoot, the loss can jump around, and it may not settle. The learning rate is a hyperparameter chosen by people rather than learned from the data, and engineers tune it.

Corey
Put the training loop together: data goes in, forward propagation makes a prediction, loss measures the mistake, backpropagation calculates gradients, and the optimizer updates the weights. Then the process repeats across examples. In the tea shorthand: guess, score, trace, adjust, repeat. “Trace the blame” is just a memory aid—the mathematical operation is calculating gradients.

Simon
Here’s a tiny numerical example. Suppose output equals input times one weight. The input is five, the expected output is ten, and the starting weight is one. The forward pass gives five, so the result is too low. Increasing the weight makes the output larger: at one point two, the output is six; at one point five, it is seven point five; at two, it is ten.

Corey
Real training does not usually try arbitrary increments like that. It uses gradient-based updates to choose steps. The example just shows what it means for a weight to change: the model’s output changes with it.

Simon
Why can the system work backward through so many layers? Because the calculations depend on one another. A tap position affects water flow, and water flow affects a tank level. To work out how the tap affects the level, combine how the level depends on flow with how flow depends on the tap.

Corey
That is the chain rule: it links dependent effects one step at a time. A neural network is a longer chain. The loss depends on the output, the output depends on the last layer, and that layer depends on earlier layers, all the way back to the first weights. Backpropagation applies the chain rule efficiently across this computational graph and reuses shared intermediate results instead of recalculating them.

Simon
So if you see notation that means “the loss with respect to a weight,” read it as a question: if that weight changes slightly, how does the loss change? The calculus beneath this idea predates neural networks, but applying it efficiently is what made training large networks practical.

Corey
The history developed over time. The underlying mathematics comes from calculus and the chain rule, and reverse accumulation of derivatives was used in control theory and optimization. In 1974, Paul Werbos described backpropagation-style ideas for neural networks in his doctoral thesis. The work received little attention for about a decade.

Simon
Then in 1986, David Rumelhart, Geoffrey Hinton, and Ronald Williams published a landmark paper showing how to train multilayer neural networks with backpropagation. It helped make the method practical and popular. So this was not one sudden invention; it was a long line of mathematical and computational work.

Corey
The practical breakthrough was efficiency. Imagine changing one weight at a time in a billion-weight model, running the model to measure each change. That would mean a billion full evaluations just to make one update. It does not scale.

Simon
Backpropagation instead uses a forward calculation to build the graph and produce the loss, then computes the gradients in a backward pass, reusing intermediate results across the network. The cost stays close to the cost of a forward pass rather than becoming a billion times larger. That efficiency is a major reason deep networks became practical.

Corey
Here’s the central relationship: weights are what a neural network learns, and backpropagation helps determine how those weights should change. A prediction produces a loss; backpropagation calculates gradients for the weights; and the optimizer uses those gradients to update them. Repeat that throughout the network and the weights improve.

Simon
But backpropagation is not a requirement for AI in general. Rule-based systems, search algorithms, expert systems, decision trees, random forests, evolutionary algorithms, and many reinforcement-learning approaches do not require it. AI is a much broader field.

Corey
And a neural network can exist without backpropagation too. It is a computational structure that can perform a forward calculation regardless of how its weights were found. You could set weights by hand, search for them randomly, or evolve them. The difficult part is efficiently finding useful values for millions or billions of weights.

Simon
Backpropagation became the dominant practical answer for differentiable networks, but there are alternatives. With evolutionary strategies, for example, you can score a population of networks, keep the better performers, mutate their weights, and repeat across generations.

Corey
Other approaches include zeroth-order optimization, which probes to estimate gradients; numerical gradient estimation, which perturbs parameters; local learning rules and Hebbian-style methods; feedback alignment, which uses fixed random feedback connections; target propagation, which sends target activations instead of gradients; and forward-mode differentiation, which can be useful when there are many outputs and few inputs.

Simon
So backpropagation is not the only possible approach. Its advantage is that, for huge differentiable networks, it exploits known mathematical relationships rather than blindly testing changes. Modern large transformers are overwhelmingly trained with gradient-based optimization, with gradients computed through automatic differentiation using backpropagation.

Corey
Let’s watch a language-model training example. The model sees “the sky is” and predicts possible next tokens: perhaps blue at twenty percent, green at thirty-five percent, and cloud at ten percent. If the correct next token is blue, we compute the loss, propagate gradient information backward through the transformer, and use the optimizer to update parameters.

Simon
Then that process repeats over many tokens. In practice, the exact numbers and objectives can vary, but predicting the next token is a useful conceptual model for pretraining. Over training, the model’s predictions can become more aligned with the examples.

Corey
Inside a transformer, tokens become embeddings. Self-attention mixes information between positions, and a feed-forward network transforms each position. Those components form a transformer block; stack many blocks to create depth. At the end, an output projection produces logits, which are turned into token probabilities and compared with the correct token to calculate loss.

Simon
The backward path follows those operations in reverse: from the loss through the output projection, through each transformer block’s attention and feed-forward layers, back through earlier blocks, and finally to the embeddings. We do not need every equation to see the pattern: gradients flow back through the operations that produced the prediction.

Corey
Now the distinction that clears up a lot: training and inference are different. During training, the model makes a prediction, the loss measures its mistake, backpropagation computes gradients, and the optimizer updates weights. The weights change.

Simon
During inference, a prompt goes in and the model performs forward computations to produce a token, then another token, and so on. There is no training loss, backward pass, or weight update in that ordinary answering process. Talking to an LLM is not the same as training it.

Corey
That distinction helps explain why training is more expensive than inference. Inference mainly needs the forward computation and model weights. Training also needs the loss, intermediate activations for gradient calculations, the backward computation, stored gradients, and optimizer state. Adam, for example, keeps additional values for every parameter.

Simon
So training generally requires substantially more compute and memory per token than inference. Inference still has real costs, including the key-value cache, but training has all that extra work. GPUs matter because neural networks rely heavily on large amounts of matrix multiplication, and GPUs handle many small numerical operations in parallel.

Corey
Training requires forward computation and backward computation, alongside optimizer state. Add more parameters and more training tokens, and the compute requirement grows substantially. That is a big part of the connection between GPUs and modern AI.

Simon
Gradients can also cause difficulties. In a very deep network, a gradient signal can become smaller and smaller as it travels backward. That is the vanishing gradient problem: early parts of the network may learn very slowly because their weights barely change.

Corey
The opposite problem is exploding gradients, where gradient values grow excessively and updates become unstable. The loss might jump wildly or even become “not a number.” Common remedies include careful initialization, normalization layers, residual connections, and gradient clipping, which caps the size of an update.

Simon
Activation functions matter for another reason. If every layer were purely linear, stacking layers would still give you a linear function. No matter how many layers you added, the network could not represent genuinely complex shapes.

Corey
Nonlinear activation functions prevent that collapse and let a network represent more complicated relationships. Sigmoid and tanh were common historically; ReLU helped make deep networks easier to train. Modern transformers commonly use smoother variants such as GELU and SwiGLU-style feed-forward blocks. The basic principle is that networks need useful nonlinear, differentiable structure so gradients can guide learning.

Simon
This also explains fine-tuning. Suppose a pretrained seven-billion-parameter model already knows a lot about language but lacks your domain’s telecom incidents, documentation, and terminology. You can give it domain examples and run another training loop: forward pass, loss, backpropagation, and optimizer updates. Fine-tuning is additional training, so backpropagation returns.

Corey
There is also a more parameter-efficient option called LoRA, or low-rank adaptation. Most of the pretrained model’s parameters stay frozen, while smaller attached adapters are trainable. That reduces the amount of trainable state substantially, but the learning loop still includes a forward pass, loss, backpropagation, and an optimizer.

Simon
How deeply do you need to understand backpropagation? If you build prompt workflows, tool-calling agents, retrieval-augmented generation, integrations, or orchestration pipelines, you do not need to derive the mathematics to be productive. But knowing the concepts—forward pass, weights, loss, gradients, optimizer, and training versus inference—gives the terminology a useful structure.

Corey
For an AI or ML engineer, it becomes useful to understand gradient computation, optimizer behavior, learning rates, training stability, fine-tuning, memory, batch size, gradient accumulation, and gradient clipping. Model and research engineers go deeper into derivatives, the chain rule, Jacobians, automatic differentiation, optimization theory, numerical stability, and distributed training. The right depth depends on your responsibilities.

Simon
That knowledge helps with practical choices. You can reason about why training infrastructure differs from inference infrastructure, and why full fine-tuning is more expensive than parameter-efficient fine-tuning. You can distinguish fine-tuning, which changes model parameters, from retrieval, which changes the context supplied without retraining the base weights.

Corey
You can also reason about whether weights should be frozen or trainable, why training needs more GPU memory than serving, and why an unsuitable learning rate can make optimization diverge or progress slowly. Gradient accumulation and clipping make more sense too: one accumulates gradients across micro-batches, while the other stabilizes updates that are too large.

Simon
Those ideas inform broader architecture decisions: when to use a hosted API, retrieval, prompt engineering, fine-tuning, or training. You can still build useful AI applications without knowing backpropagation, but without the conceptual model, terms like gradients, frozen layers, optimizer, and LoRA can feel like disconnected jargon.

Corey
With the model, the pieces connect: prediction, loss, backpropagation, gradient, optimizer, weight update. This is not gatekeeping. It is a way to make technical decisions clearer.

Simon
One misconception is worth clearing up: backpropagation does not mean the AI is thinking backward. When you ask a model a question, it performs a forward computation to produce an answer. Backpropagation is a training mechanism for computing gradients, not the same thing as reasoning, reflection, chain of thought, self-correction, or an agent retrying a task.

Corey
An agent can go back and retry something without backpropagating through the model’s weights. That matters when you are learning about agents: repeating an action or revising an answer is not, by itself, neural-network training.

Simon
Let’s finish with the same loop in two settings. A cat classifier sees a cat image and initially predicts dog at seventy percent and cat at thirty percent. The training example supplies the correct answer; the model computes loss, backpropagation calculates gradients, and the optimizer updates weights. After many examples, it might predict cat at ninety-seven percent and dog at two percent.

Corey
Now replace the cat image with the phrase “once upon a.” A transformer predicts the next token, computes loss, backpropagates gradients, and updates weights. Structurally, it is the same training loop—a cat classifier and a large language model differ in scale and task, but the core process is the same.

Simon
So here is the simplest summary: guess, score, trace, adjust, repeat. Guess is forward propagation. Score is the loss. Trace is backpropagation calculating how parameter changes affect that loss. Adjust is the optimizer updating the weights. Repeat is training.

Corey
Weights are what the model learns. Forward propagation makes a prediction. Loss measures the mistake. Backpropagation calculates gradients, and the optimizer uses them to update parameters. Repeating that process creates learning—and, importantly, ordinary inference while a model answers you does not perform that weight-updating loop.

Ask anything
We've read this whole study set, so questions about it get the best answers.