1. Home
  2. Explore
  3. Computer Science
  4. Backpropagation and LLM Training

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Backpropagation and LLM Training

Backpropagation and Neural Network Training

What a neural network learns

A neural network learns by adjusting weights: numerical parameters that control how strongly different inputs and internal signals affect its output.

For example, a simple house-price model might combine house size, bedroom count, location, and building age:

predicted price=(size×w1)+(bedrooms×w2)+(location×w3)+(age×w4)\text{predicted price} = (\text{size}\times w_1) + (\text{bedrooms}\times w_2) + (\text{location}\times w_3) + (\text{age}\times w_4)predicted price=(size×w1​)+(bedrooms×w2​)+(location×w3​)+(age×w4​)

The weights w1,w2,w3,w_1, w_2, w_3,w1​,w2​,w3​, and w4w_4w4​ determine how much each input contributes to the prediction. Changing a weight can change the model’s behavior. Real neural networks may contain millions or billions of such parameters.

This creates the central training problem: when the model makes an error, which weights should change, in what direction, and by how much? Backpropagation helps answer that question.

The adjustable-knob analogy

A weight can be imagined as a knob controlling part of a model’s behavior. In a recipe, the corresponding knobs might be the amount of tea, sugar, and milk, and the brewing time. If the result tastes too sweet, feedback that merely says “the tea is bad” is not enough. The recipe needs more specific information about which choices contributed to the result and how they should change.

The analogy maps to training as follows:

  • Recipe choices: weights or parameters

  • Preparing the tea: forward propagation

  • Taste rating: loss

  • Tracing the result back to recipe choices: backpropagation

  • Changing the recipe: optimization

  • Repeating the process: training

The idea is not to assign literal blame to a parameter. It is to measure how sensitive the result is to changes in that parameter.


The training loop

Training repeatedly processes examples and uses the resulting errors to improve the model.

  1. Forward propagation sends an input through the network to produce a prediction.

  2. Loss calculation measures how different the prediction is from the desired answer.

  3. Backpropagation computes how changes to the parameters would affect the loss.

  4. Optimization uses that information to update the parameters.

  5. The process repeats across many examples.

A compact summary is:

Guess → score → trace → adjust → repeat.

Here, “trace” is a helpful analogy for calculating gradients; it does not mean that an error is literally passed backward as an object.


Forward propagation: producing a prediction

Forward propagation, or a forward pass, is the calculation that takes an input through the network and produces an output. Information moves from the input, through successive layers, to the prediction.

Examples include:

  • A cat-image classifier receiving an image and outputting probabilities such as cat at 30%30\%30% and dog at 70%70\%70%.

  • A language model receiving “Paris is the capital of” and assigning probabilities to possible next tokens, such as France, London, and Rome.

A forward pass by itself is not learning. It produces a guess using the model’s current weights. Learning requires comparing that guess with an appropriate target and changing the weights.


Loss: measuring prediction error

The loss is a numerical measure of how wrong a prediction is relative to the desired result. A better prediction generally produces a lower loss; a worse prediction generally produces a higher loss.

Loss is useful because training needs a quantity it can optimize. Instead of relying on a vague judgment such as “the model did poorly,” training uses a mathematical objective that provides a numerical signal.

For example, if the correct image label is “cat” but the model assigns a higher probability to “dog,” the loss reflects that mismatch. In language-model pretraining, the model’s predicted next-token distribution is compared with the correct next token to calculate a loss.


Backpropagation and gradients

What backpropagation does

Backpropagation starts with the loss and works backward through the network’s computational graph. It calculates how changing each parameter would affect the loss.

  • The forward direction answers: What prediction did the model make?

  • The backward direction answers: How would parameter changes affect the error?

Backpropagation does not itself decide or perform every weight update. It calculates gradient information that an optimizer can use.

What a gradient means

A gradient measures how sensitively the loss responds to a parameter’s change. For a single weight, its gradient indicates:

  • Which direction the loss would move if the weight changed.

  • How strongly the loss would respond to that change.

If increasing a weight makes the loss worse, training generally needs to move the weight in the opposite direction. If a small change has a large effect on the loss, the gradient’s magnitude reflects that stronger sensitivity.

For a parameter www, the derivative of loss LLL with respect to that parameter is written:

∂L∂w\frac{\partial L}{\partial w}∂w∂L​

It can be read as: “If this weight changes slightly, how does the loss change?”

Backpropagation versus optimization

These terms describe different jobs:

  • Backpropagation calculates gradients.

  • The optimizer uses gradients to update weights.

The distinction can be pictured as walking downhill in fog. The gradient describes the slope and indicates a downhill direction. The optimizer takes the step. Knowing which way is downhill does not, by itself, move the learner.

For a basic gradient-descent update, a parameter can be adjusted according to:

w←w−η∂L∂ww \leftarrow w-\eta\frac{\partial L}{\partial w}w←w−η∂w∂L​

Here, η\etaη is the learning rate, which controls the scale of the step. This equation illustrates the general idea; practical optimizers may modify how gradients are used.


Optimizers and learning rate

Common optimizers

An optimizer is the procedure that turns gradient information into parameter updates.

  • Stochastic gradient descent (SGD): takes steps based on gradients, often using individual examples or batches of examples.

  • Adam: adapts updates using running estimates of gradient information.

  • AdamW: modifies Adam’s handling of weight decay, a technique that can help regulate parameter values.

Different optimizers make updates in different ways, but they all have a role distinct from backpropagation: backpropagation provides gradient information, while the optimizer uses it to change the parameters.

Learning rate

The learning rate controls how large an update is. It is a hyperparameter chosen by the system designer or engineer rather than learned directly from the training examples.

  • If the learning rate is too small, updates are tiny and progress may be very slow.

  • If it is too large, updates may overshoot useful values, causing the loss to jump around or fail to settle.

  • A suitable learning rate supports more stable progress toward lower loss.


A one-weight example

Consider a model with one input xxx and one weight www. Its output is:

output=xw\text{output}=xwoutput=xw

Suppose the input is 555, the expected output is 101010, and the initial weight is 111. The forward pass gives:

5×1=55\times 1=55×1=5

The output is too low. Increasing the weight increases the output:

  • At w=1.2w=1.2w=1.2, the output is 666.

  • At w=1.5w=1.5w=1.5, the output is 7.57.57.5.

  • At w=2w=2w=2, the output is 101010.

This shows what it means for a model to learn a weight: the weight changes so that the model’s outputs better match the desired outputs. Real systems do not normally find the right value by trying arbitrary increments. They use gradients and an optimizer to guide updates.


Why backward calculation works: the chain rule

A neural network is a sequence of dependent computations. In a simple physical analogy, a tap position affects water flow, and water flow affects a tank’s level. The tap affects the tank indirectly through the flow.

To determine how the tap affects the tank level, the effects along the chain can be combined:

change in tank levelchange in tap position=change in tank levelchange in water flow×change in water flowchange in tap position\frac{\text{change in tank level}}{\text{change in tap position}} = \frac{\text{change in tank level}}{\text{change in water flow}} \times \frac{\text{change in water flow}}{\text{change in tap position}}change in tap positionchange in tank level​=change in water flowchange in tank level​×change in tap positionchange in water flow​

This illustrates the chain rule: the effect of an early quantity on a later quantity can be calculated by linking the effects of each intermediate computation.

A neural network works similarly:

  • The loss depends on the output.

  • The output depends on the last layer.

  • That layer depends on the preceding layer.

  • The dependencies continue backward through the network to earlier parameters.

Backpropagation is an efficient application of the chain rule across the computational graph. It reuses intermediate results rather than recalculating the effect of each parameter from scratch.


Why backpropagation scales

Suppose a model has a billion weights. A naive approach would change one weight, run the model to measure the effect, then repeat that process for every other weight. That would require roughly a billion separate full evaluations just to assess the parameters for an update.

Backpropagation provides a much more efficient alternative:

  1. Run one forward calculation.

  2. Calculate the loss.

  3. Compute gradients through a backward pass.

Because it reuses shared intermediate calculations, the cost is much closer to that of a small number of model passes than to a separate full evaluation for every parameter. This efficiency helped make the training of deep, large neural networks practical.

Weights are what a model learns; backpropagation helps determine how those weights should change.


Backpropagation in the history of neural networks

The mathematics behind backpropagation comes from calculus, especially the chain rule, and predates modern neural networks. Related ideas for accumulating derivatives through chains of computations developed over time, including in control theory and optimization.

  • In 1974, Paul Werbos described using backpropagation-style ideas for neural networks in his doctoral thesis.

  • In 1986, David Rumelhart, Geoffrey Hinton, and Ronald Williams published influential work demonstrating how backpropagation could train multilayer neural networks.

The method was not a sudden, isolated invention. It emerged from a longer history of mathematical and computational work, and became widely influential when it offered a practical way to train networks with multiple layers.


AI and neural networks do not require backpropagation in every case

Artificial intelligence is broader than neural networks, and neural networks are not structurally dependent on backpropagation.

Some AI approaches that do not require backpropagation include:

  • Rule-based systems and expert systems.

  • Search algorithms.

  • Decision trees and random forests.

  • Evolutionary algorithms.

  • Some reinforcement-learning approaches.

A neural network can still perform its forward computation if its weights were selected by hand, by random search, or through an evolutionary process. The difficult problem is finding useful values efficiently for millions or billions of weights. Backpropagation became the dominant practical method for training differentiable neural networks because it calculates gradients efficiently.

Alternative approaches to training

Alternatives include:

  • Evolutionary strategies and genetic algorithms: evaluate a population of candidate systems, retain better-performing candidates, and create new candidates through mutation or related operations.

  • Zeroth-order optimization: estimates useful update directions by probing how outcomes change under parameter variations.

  • Numerical gradient estimation: perturbs parameters and estimates their effects directly.

  • Local learning rules and Hebbian-style methods: update connections using local information about activity.

  • Feedback alignment: uses fixed random feedback connections rather than traditional backward weights.

  • Target propagation: sends target activations through a network instead of relying on conventional gradients.

  • Forward-mode differentiation: can be useful in settings where there are many outputs but relatively few inputs.

These approaches show that backpropagation is not the only possible training method. Its importance comes from its computational usefulness, especially for large differentiable networks.


Backpropagation in language-model training

Next-token prediction

A useful conceptual model of language-model pretraining is next-token prediction. Given a context such as “the sky is,” the model assigns probabilities to possible next tokens. If the correct next token is “blue,” the model’s prediction is compared with that target to calculate a loss.

A training step therefore follows the familiar sequence:

  1. The model processes the context and predicts a distribution over next tokens.

  2. The prediction is compared with the correct next token.

  3. The loss is calculated.

  4. Backpropagation calculates gradients through the model.

  5. An optimizer updates the parameters.

The example repeats across large numbers of tokens. The exact objective and details may vary, but next-token prediction captures the basic pattern of language-model pretraining.

The path through a transformer

A transformer processes information through multiple stages:

  1. Input tokens are converted into embeddings, numerical representations.

  2. Self-attention allows information from different positions to be combined.

  3. Feed-forward networks transform representations at each position.

  4. Repeated transformer blocks create depth.

  5. An output projection produces logits, which are converted into token probabilities.

  6. Those probabilities are compared with the correct token to calculate the loss.

During backpropagation, gradient information travels from the loss backward through the output projection, transformer blocks, attention and feed-forward operations, and ultimately into earlier representations and embeddings. It moves backward through the operations that produced the prediction.


Training versus inference

Training and inference are different processes.

Training

During training:

  • A forward pass produces a prediction.

  • A loss measures the prediction error.

  • Backpropagation calculates gradients.

  • An optimizer updates the weights.

The weights change over the course of training.

Inference

During standard inference:

  • A prompt is processed through the model.

  • The model performs forward computations and produces output tokens.

  • It continues generating tokens as needed.

There is typically no training loss, backward pass, or update to the model’s weights during ordinary inference. Thus, using a deployed language model to answer a question is not the same as training that model.

A model can generate reasoning-like text, revise an answer, or retry a task without performing backpropagation. Backpropagation is a training mechanism, not a synonym for thinking, reasoning, reflection, or self-correction.


Why training is more expensive than inference

Training generally requires substantially more memory and computation per token than inference because it must support the backward update process.

Training may need to store or compute:

  • The model weights and forward computation.

  • The loss.

  • Intermediate activations, which are needed to calculate gradients.

  • The backward computation itself.

  • Gradients for parameters.

  • Optimizer state.

For example, Adam keeps additional values for each parameter. Those values add to training memory requirements.

Inference is not cost-free. It still requires substantial computation, and systems may need a key-value cache to support generation. However, standard inference mainly performs forward computation, while training adds backward computation, gradient storage, and optimizer state.

The role of GPUs

Neural networks rely heavily on large numbers of matrix operations. Both forward propagation and backpropagation use these operations, and training adds further work. GPUs are well suited to this kind of parallel numerical computation because they can execute many small operations simultaneously.

Training demands rise with factors such as:

  • The number of model parameters.

  • The number of training tokens.

  • Forward-pass computation.

  • Backward-pass computation.

  • Optimizer state.

Together, these requirements help explain why training large models requires substantial hardware and compute resources.


Training instabilities: vanishing and exploding gradients

Vanishing gradients

In a deep computation graph, gradients can become extremely small as they are propagated backward. This is the vanishing gradient problem.

When gradients reaching early layers are very small, the weights in those layers change very little. As a result, early parts of the network may learn slowly, even when they are important to the final output.

Exploding gradients

Gradients can also become excessively large. This is the exploding gradient problem. Large gradients can cause unstable updates, making the loss jump dramatically or causing calculations to become invalid.

Common remedies

Training systems use several techniques to improve stability:

  • Careful parameter initialization helps put parameters in useful starting ranges.

  • Normalization layers can help control the scale of internal values.

  • Residual connections provide architectural paths that can support information and gradient flow.

  • Gradient clipping limits the size of gradients or updates to reduce the effect of extreme values.


Why neural networks use nonlinear activation functions

If every layer were purely linear, stacking layers would still produce a linear function. A sequence of linear transformations cannot, just by adding more layers, represent genuinely complex nonlinear relationships.

Nonlinear activation functions prevent this collapse and allow a network to represent more complicated patterns. Historically, sigmoid and tanh activations were common. ReLU made deeper networks easier to train, and modern transformers often use smoother or related variants such as GELU and SwiGLU-style feed-forward blocks.

For gradients to guide learning, a network must also have operations for which useful derivatives can be computed. Neural networks therefore use structures that combine useful nonlinear transformations with differentiable operations.


Fine-tuning and LoRA

Fine-tuning

A pretrained model may already contain broad knowledge about language but lack expertise in a particular domain, such as telecom incident data, operational terminology, or specialized documentation.

Fine-tuning is additional training on domain-specific examples. It uses the same basic loop:

  1. The model processes examples in a forward pass.

  2. The loss measures how well its predictions match the examples.

  3. Backpropagation calculates gradients.

  4. An optimizer updates parameters so that the model adapts.

Fine-tuning changes model parameters. It is therefore a form of training.

LoRA: parameter-efficient fine-tuning

LoRA, or low-rank adaptation, is a parameter-efficient way to fine-tune a large model. Most pretrained parameters are kept frozen, while smaller trainable adapter parameters are added and optimized.

This can reduce the amount of trainable state and the associated resource requirements. The training mechanism remains the same: forward pass, loss, backpropagation, and optimizer update. The key difference is that only selected added parameters are trained rather than updating all the original model parameters.

Fine-tuning versus retrieval

  • Fine-tuning changes model parameters through additional training.

  • Retrieval supplies relevant information as context without retraining the base weights.

This distinction helps determine whether a system needs the model itself to adapt or simply needs access to information when responding.


Practical knowledge and engineering decisions

The depth of backpropagation knowledge needed depends on a person’s responsibilities.

AI application development

An application developer working mainly with prompts, tool-calling agents, retrieval-augmented generation, integrations, or orchestration pipelines can often be productive without deriving the mathematics. A conceptual understanding of forward passes, weights, loss, gradients, optimizers, and training versus inference still helps connect common technical terms.

AI or machine-learning engineering

An AI or machine-learning engineer benefits from understanding:

  • How gradients are computed.

  • How optimizers and learning rates affect training.

  • How training stability is managed.

  • How fine-tuning works.

  • How memory is affected by batch size, gradient accumulation, and gradient clipping.

Model and research engineering

Model and research engineers may need deeper mathematical and systems knowledge, including derivatives, the chain rule, Jacobians, automatic differentiation, optimization theory, numerical stability, and distributed training.

Understanding the basic training loop helps with practical decisions, including:

  • Choosing between training and inference infrastructure.

  • Deciding between full fine-tuning and parameter-efficient fine-tuning.

  • Comparing fine-tuning with retrieval.

  • Deciding whether model weights should be frozen or trained.

  • Estimating why training uses more GPU memory than serving.

  • Diagnosing slow learning or unstable optimization.

  • Understanding gradient accumulation and gradient clipping.

  • Choosing among hosted models, retrieval, prompt engineering, fine-tuning, and training.

The value is not that every AI practitioner must derive every equation. It is that the concepts give technical vocabulary a coherent structure.


A unified example: classifiers and language models

A cat classifier might initially classify a cat image as dog at 70%70\%70% and cat at 30%30\%30%. During training, it performs a forward pass, calculates loss, uses backpropagation to compute gradients, and applies an optimizer update. After many examples, the model may assign much higher probability to “cat.”

A language model follows the same structural loop. Given a sequence such as “once upon a,” it predicts a next token, calculates a loss against the correct token, computes gradients through its network, and updates its parameters.

The tasks differ, but the underlying pattern is the same:

Forward propagation makes a prediction. Loss measures the error. Backpropagation calculates how parameter changes affect that error. The optimizer updates the parameters. Repetition produces learning.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent