1. Home
  2. Explore
  3. Computer Science
  4. Training Neural Networks

Study methods

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

Training Neural Networks

Training Neural Networks: Optimization, Backpropagation, and Differential Programming

1. The neural-network training problem

A neural network maps an input xxx to a prediction. It consists of connected computational components, often called layers, each of which has parameters such as weights and biases. During training, the model’s prediction is compared with a target value yyy, and a loss function measures the discrepancy.

For a model with parameters θ\thetaθ, the training objective is to find parameters that minimize the loss over the available training examples. If the loss for example iii is ℓi(θ)\ell_i(\theta)ℓi​(θ), a dataset-level objective can be written as

J(θ)=∑i=1Nℓi(θ),J(\theta) = \sum_{i=1}^{N} \ell_i(\theta),J(θ)=∑i=1N​ℓi​(θ),

or as the average of those losses. The parameters are said to be learned because their numerical values are repeatedly adjusted to reduce this objective.

The terms loss and cost are sometimes used differently. A common convention is that a loss is defined for an individual example, while a cost or objective aggregates losses across a batch or dataset. In practice, the distinction is not always used consistently; both refer to a quantity that measures model performance and can be optimized.


2. Gradient descent and stochastic gradient descent

Gradient descent

The objective J(θ)J(\theta)J(θ) can be viewed as a landscape over parameter space. Each point represents a possible setting of the model parameters, and its height represents the objective value at that setting.

The gradient points in the direction of greatest local increase in the objective. To reduce the objective, gradient descent moves in the opposite direction:

θk+1=θk−η∇θJ(θk),\theta_{k+1} = \theta_k - \eta \nabla_\theta J(\theta_k),θk+1​=θk​−η∇θ​J(θk​),

where:

  • θk\theta_kθk​ is the parameter vector at step kkk,

  • ∇θJ(θk)\nabla_\theta J(\theta_k)∇θ​J(θk​) is the gradient at that point,

  • η\etaη is the learning rate, which controls the step size.

A large learning rate can make updates overshoot useful regions or diverge. A very small learning rate can make training slow. The goal is to make a sequence of updates that reaches a low-value region of the objective.

In neural networks, the objective is generally non-convex: it may have many local minima, saddle points, and other irregularities. Gradient descent is therefore not guaranteed to find the global minimum. The outcome can depend on the initialization and the path followed during optimization.

Stochastic gradient descent

Computing the gradient over every training example at every step can be prohibitively expensive, especially for large datasets. Stochastic gradient descent (SGD) estimates the full-data gradient using a subset of examples called a batch.

For a batch BBB containing ∣B∣|B|∣B∣ examples, a common update is

θk+1=θk−η1∣B∣∑i∈B∇θℓi(θk).\theta_{k+1} = \theta_k - \eta \frac{1}{|B|} \sum_{i \in B} \nabla_\theta \ell_i(\theta_k).θk+1​=θk​−η∣B∣1​∑i∈B​∇θ​ℓi​(θk​).

Batch size determines how much data contributes to each update:

  • Batch size 111: Parameters are updated after each example. These updates are inexpensive individually but can be noisy.

  • Intermediate batch size: Each update averages information from a subset of the data. This is the common mini-batch setting.

  • Full-dataset batch: The update uses all training examples, corresponding to standard full-batch gradient descent. This may be too slow or require too much memory.

A batch gradient is an estimate of the full-dataset gradient, not necessarily an exact match. Its variability depends partly on the batch size and how representative the batch is. If examples are unevenly distributed across categories, a batch may omit some categories and then include them later, causing abrupt changes in the gradient.

Benefits and drawbacks of SGD

SGD is usually more computationally practical than repeatedly evaluating the entire dataset. Even relatively small batches can provide useful approximations to the full gradient. The randomness in the estimates can also act as an implicit regularizer: noisy steps may help the optimizer escape some local minima or narrow regions.

The same randomness can be a drawback. Small or unrepresentative batches can produce high-variance gradients and unstable updates. This is especially likely when the training data is imbalanced or when important categories appear infrequently.


3. Momentum and optimization landscapes

Momentum

Momentum adds information from previous updates to the current update. The physical analogy is an object rolling downhill: its motion builds speed in a consistent direction rather than being determined only by the slope at its current position.

One common formulation is

vk+1=αvk+∇θJ(θk),θk+1=θk−ηvk+1,v_{k+1} = \alpha v_k + \nabla_\theta J(\theta_k), \qquad \theta_{k+1} = \theta_k - \eta v_{k+1},vk+1​=αvk​+∇θ​J(θk​),θk+1​=θk​−ηvk+1​,

where vkv_kvk​ tracks a smoothed history of gradients and α\alphaα controls how strongly past updates influence the current one.

Momentum can speed progress along a consistent descent direction. However, if its strength is too large, updates can overshoot a minimum and oscillate around it. The momentum coefficient is a hyperparameter that must be chosen as part of the optimization setup.

The Adam optimizer is a widely used optimizer that combines momentum-like moving averages with adaptive scaling of updates. It is related to the momentum idea but includes additional mechanisms.

Different loss-landscape shapes

The shape of an objective affects how easy it is to optimize:

  • A smooth, bowl-shaped landscape with one minimum: Gradients tend to point toward the same minimum, and their magnitude can shrink as the minimum is approached. This is a favorable situation for gradient descent.

  • A landscape with multiple local minima: The result can depend on the initialization. A run may reach a local minimum without reaching the lowest one.

  • A flat landscape: If the gradient is zero or nearly zero over a region, the optimizer receives little or no signal about how to make progress. A nearly flat region can cause very slow learning, especially if batch noise dominates the gradient signal.

  • A very steep region: A large gradient can produce a large update that overshoots the minimum. This is one form of the exploding-gradient problem.

  • A discontinuity or kink: A function may have derivatives on either side of a discontinuity without having a derivative at the discontinuity itself. Gradient-based optimization can still be used with suitable derivative conventions or approximations, but the landscape may be difficult to optimize.

A useful intuition is to imagine water flowing across the landscape. If the landscape has a single basin, water from many starting points tends to flow toward that basin. If it has multiple basins, the starting position can determine which one receives the water. This analogy helps distinguish landscapes with multiple minima from those with a single broad minimum, although it does not describe every detail of gradient-based optimization.

Differentiability versus ease of optimization

A function being differentiable, or having a gradient available in a software library, does not guarantee that it is easy to optimize. A flat function can have a well-defined zero gradient, which gives no useful direction for improvement. A steep function can have a gradient so large that updates become unstable. A function with multiple minima can be differentiable everywhere yet still lead optimization to a suboptimal minimum.

Automatic differentiation systems such as PyTorch compute derivatives for supported operations. For operations that are not differentiable at every point, the system may use a defined convention or derivative-like rule. This makes gradient computation practical for many functions, but it does not remove the underlying optimization challenges.

Random restarts

Because a non-convex objective may have multiple minima, training can be repeated from different random initializations, or random seeds. Comparing performance across runs gives information about how sensitive the result is to initialization and about the variability of the optimization process.


4. Additional optimization techniques

Evolution strategies

Evolution strategies are gradient-like search methods that explore parameter space by sampling perturbations around current parameter values. The method evaluates the objective for perturbed candidates and moves toward candidates with lower loss.

For example, a candidate may be formed by adding a random perturbation ϵ\epsilonϵ to parameters θ\thetaθ and evaluating J(θ+ϵ)J(\theta + \epsilon)J(θ+ϵ). Rather than relying only on the local gradient, the method uses the outcomes of sampled perturbations to identify promising directions.

This kind of search can be useful when a gradient is weak or uninformative, or when the objective is difficult to optimize by ordinary gradient steps. Its perturbation scale and other settings generally need to be tuned for the particular model and dataset; there is no single universally optimal choice.

Gradient clipping

Gradient clipping limits the size of an update when gradients become excessively large. A simple value-based approach caps individual gradient values. A common norm-based approach rescales the entire gradient when its norm exceeds a chosen threshold.

For a gradient ggg and maximum norm ccc, norm clipping can be written as

g~=gmin⁡(1,c∥g∥).\tilde{g} = g \min\left(1,\frac{c}{\|g\|}\right).g~​=gmin(1,∥g∥c​).

The update then uses g~\tilde{g}g~​ instead of ggg. Clipping helps prevent a single large gradient from causing an excessively large parameter change. It is a practical stabilizing technique, particularly in settings where gradients may explode.


5. Desirable properties of activation functions

An activation function introduces a nonlinearity into a neural network. Its mathematical properties can affect how easily the network can be optimized.

Three properties often discussed are:

  • Continuity: Small changes in the input do not cause sudden jumps in the function value.

  • Differentiability: A derivative exists at the relevant points.

  • Smoothness: The function and its derivatives change smoothly, rather than having abrupt kinks.

The ReLU activation is

ReLU⁡(x)=max⁡(0,x).\operatorname{ReLU}(x) = \max(0,x).ReLU(x)=max(0,x).

It is continuous and differentiable everywhere except at x=0x=0x=0, where it has a kink. It is therefore differentiable almost everywhere but not smooth at the kink. In backpropagation, the gradient is masked for inputs in ReLU’s inactive, negative region.

The Gaussian error linear unit (GELU) is commonly written as

GELU⁡(x)=xΦ(x),\operatorname{GELU}(x) = x\Phi(x),GELU(x)=xΦ(x),

where Φ(x)\Phi(x)Φ(x) is the cumulative distribution function of the standard Gaussian distribution. GELU is smooth and differentiable everywhere, and it is continuous everywhere.

Smoothness and differentiability can make optimization easier in some settings, but they do not guarantee better performance for every model or task. The relative merits of activation functions remain dependent on the architecture, data, and optimization procedure.


6. Computation graphs

A computation graph represents a computation as a collection of functional operations:

  • Each node applies a function or transformation.

  • Each edge carries values from one operation to another.

A node may represent a small operation, such as a matrix multiplication or activation, or a larger component, such as an entire neural network. The graph describes how inputs are transformed into outputs.

A directed acyclic graph (DAG) has directed edges and no cycles. Information flows in the direction of the edges, and the absence of cycles means that the operations can be arranged in a forward order without returning to an earlier node. Neural-network computations are commonly represented this way.

A multilayer perceptron as a graph

A multilayer perceptron (MLP) can be represented as a chain-shaped DAG:

  1. The input xxx enters a linear layer.

  2. The linear layer produces an intermediate representation.

  3. An activation function, such as ReLU, transforms that representation.

  4. Another linear layer produces the output.

  5. A loss function compares the output with the target.

The MLP is one simple kind of computation graph. More complex models can branch, merge, reuse parameters, or combine outputs from multiple components.


7. Forward computation and matrix calculus

Forward pass

For a computational layer with input xxx, parameters θ\thetaθ, and function fff, the forward computation is

y=f(x;θ).y = f(x;\theta).y=f(x;θ).

The layer’s output yyy becomes the input to a subsequent layer. A forward pass evaluates these operations in graph order until the model produces a prediction and its loss.

Vector and Jacobian derivatives

Suppose x∈Rnx \in \mathbb{R}^nx∈Rn is a column vector.

  • If yyy is a scalar function of xxx, its partial derivatives with respect to the entries of xxx can be written as a row vector of length nnn.

  • If y∈Rmy \in \mathbb{R}^my∈Rm is a vector, the Jacobian of yyy with respect to xxx is an m×nm \times nm×n matrix. Each entry records how one output component changes with respect to one input component.

  • If the input is a matrix, the derivative with respect to its entries can be arranged in a matrix matching the input’s dimensions, although conventions for matrix derivatives vary.

Derivative notation for more complicated combinations of vectors and matrices is not universally standardized. The essential point is to keep the dimensions and the dependency structure clear.

The chain rule

For a composition z=f(u)z = f(u)z=f(u), where u=g(x)u = g(x)u=g(x), the chain rule gives

∂z∂x=∂z∂u∂u∂x.\frac{\partial z}{\partial x} = \frac{\partial z}{\partial u} \frac{\partial u}{\partial x}.∂x∂z​=∂u∂z​∂x∂u​.

If xxx has dimension nnn, uuu has dimension ppp, and zzz has dimension mmm, then the Jacobian dimensions are

∂z∂u∈Rm×p,∂u∂x∈Rp×n,∂z∂x∈Rm×n.\frac{\partial z}{\partial u} \in \mathbb{R}^{m \times p}, \qquad \frac{\partial u}{\partial x} \in \mathbb{R}^{p \times n}, \qquad \frac{\partial z}{\partial x} \in \mathbb{R}^{m \times n}.∂u∂z​∈Rm×p,∂x∂u​∈Rp×n,∂x∂z​∈Rm×n.

The dimensions match because multiplying the first Jacobian by the second gives an m×nm \times nm×n matrix.


8. Backpropagation

The central idea

A neural network can be evaluated forward to produce a loss, then differentiated backward to determine how each parameter contributed to that loss. Backpropagation applies the chain rule through the computation graph while reusing intermediate derivatives.

If the same downstream portion of a network contributes to the gradients of several earlier parameters, computing that portion repeatedly would be wasteful. Backpropagation computes shared derivative terms once and propagates them backward through the graph. This reuse makes gradient computation practical for large models.

The backward pass carries an error signal, represented by gradients, from the loss toward earlier layers and parameters. The resulting gradients indicate how the loss changes when the parameters change.

Generic layer quantities

For a layer with input xxx, output yyy, parameters θ\thetaθ, and a scalar objective JJJ, the backward computation needs:

  • The gradient of the objective with respect to the layer output, such as ∂J/∂y\partial J/\partial y∂J/∂y.

  • The derivative of the layer output with respect to its input, ∂y/∂x\partial y/\partial x∂y/∂x.

  • The derivative of the layer output with respect to its parameters, ∂y/∂θ\partial y/\partial \theta∂y/∂θ.

Using the chain rule gives gradients for the layer input and parameters. These gradients are then passed to earlier layers.

The training loop

A basic neural-network training iteration follows this sequence:

  1. Forward pass: Compute predictions and the loss.

  2. Backward pass: Propagate derivatives from the loss backward through the graph.

  3. Parameter update: Adjust parameters using an optimizer, such as gradient descent or an SGD variant.

  4. Repeat: Continue over batches and training iterations.

Training can be stopped according to a chosen criterion, such as a lack of improvement on held-out validation data.

Batches and the average gradient

If a batch contains multiple examples, the batch objective is commonly the average of their losses. The gradient of this average is the average of the individual gradients:

∇θ(1∣B∣∑i∈Bℓi(θ))=1∣B∣∑i∈B∇θℓi(θ).\nabla_\theta \left( \frac{1}{|B|}\sum_{i \in B}\ell_i(\theta) \right) = \frac{1}{|B|} \sum_{i \in B}\nabla_\theta \ell_i(\theta).∇θ​(∣B∣1​∑i∈B​ℓi​(θ))=∣B∣1​∑i∈B​∇θ​ℓi​(θ).

Thus, the batch gradient combines information from all examples in the batch.


9. Backpropagation through a linear layer

Consider a linear layer with column-vector input xxx, weight matrix WWW, and output yyy:

y=Wx.y = Wx.y=Wx.

Suppose the backward pass receives an output gradient gy=∂J/∂yg_y = \partial J/\partial ygy​=∂J/∂y, also represented as a column vector. Then the input gradient is

gx=W⊤gy.g_x = W^\top g_y.gx​=W⊤gy​.

The gradient with respect to the weight matrix is

∂J∂W=gyx⊤.\frac{\partial J}{\partial W} = g_y x^\top.∂W∂J​=gy​x⊤.

This outer product combines the output gradient with the input. A gradient-descent update is therefore

Wnew=W−ηgyx⊤.W_{\text{new}} = W - \eta g_y x^\top.Wnew​=W−ηgy​x⊤.

The forward pass multiplies the input by WWW. The backward pass multiplies the output gradient by W⊤W^\topW⊤ to obtain the input gradient. These simple matrix operations make the linear layer’s role in backpropagation explicit. Bias terms, when included, receive their own gradients.


10. Backpropagation through an MLP and ReLU

For an MLP with linear layers and activations, the backward pass follows the chain rule through each operation.

Linear layers

A linear layer propagates gradients using the transpose of its weight matrix. The same weight matrix also receives a gradient based on the layer’s input and the gradient arriving from downstream.

ReLU layers

A ReLU activation does not apply ReLU to the backward gradient. Instead, its derivative gates the gradient according to the forward activation:

  • A positive pre-activation passes the gradient through.

  • A negative pre-activation blocks the gradient.

  • At zero, a convention is used for the derivative.

For a vector of activations, this behavior can be represented by a diagonal mask whose entries indicate which components were active during the forward pass. The mask is applied to the incoming gradient.

Saved intermediate values

Backpropagation generally needs information from the forward pass, such as intermediate activations or masks. These values are used to calculate derivatives later. Consequently, training often requires storing intermediate representations in memory until the backward pass has used them. The forward and backward passes are therefore not perfectly symmetric in their memory requirements.

Why the backward operation is linear locally

Even when the overall network is nonlinear, backpropagation computes local derivatives and combines them through the chain rule. For a small change around the current parameter values, this is a first-order, linear approximation to how the loss changes. This local linearization is why gradients describe a direction of change even when the full loss landscape is highly curved.


11. Backpropagation through general DAGs

A computation graph need not be a simple chain. Models often contain branches, merges, and repeated uses of the same parameters. Two basic graph structures explain how gradients pass through these more general DAGs.

Merging paths

A merge combines information from multiple inputs. It might be addition, concatenation, or another differentiable operation. During the backward pass, the gradient is routed back to the input components according to the derivative of the merge operation.

For concatenation, for example, the gradient is divided into the parts corresponding to each concatenated input. For addition, each input receives the gradient of the sum with respect to that input.

Branching paths

A branch sends one value to multiple downstream operations. When gradients return along those paths, their contributions are added at the shared upstream value. If a scalar objective depends on a variable through multiple paths, the total derivative is the sum of the derivative contributions from each path.

This sum rule lets the chain-rule procedure used for a simple MLP extend to arbitrary DAGs: gradients are routed through merges and accumulated at branches.

Shared parameters

A parameter may be used by more than one component or at multiple points in a model. Each use contributes to the total objective, so the gradient for the shared parameter is the sum of the gradient contributions from all of its uses. Parameter sharing therefore fits naturally into the DAG view.


12. Differential programming

Differential programming views a model as a program composed of operations for which derivatives can be computed. Neural-network training is one important instance: a model’s operations are connected in a graph, and automatic differentiation propagates derivatives through that graph to optimize parameters.

Frameworks such as PyTorch, TensorFlow, and JAX provide tools for building these computations and calculating gradients. In general, operations that are intended to participate in gradient-based learning must have suitable derivative rules available. Some processing steps, such as data preprocessing, can instead occur outside the differentiable computation.

Modularity and reusable components

A model can combine components with different origins and roles:

  • Some components may be learned from data.

  • Some may be fixed after being trained elsewhere.

  • Some may be explicitly programmed rather than learned.

  • Components may be connected into a larger system.

For example, a model may use a fixed preprocessing transformation and a learned neural network. A pretrained component may also be reused in multiple places. Differentiable programming emphasizes that these components can be composed and, when appropriate, optimized together.

Human-defined structure can constrain a model’s behavior. Such constraints can be useful, but they can also restrict the model too much. Earlier approaches often relied heavily on hand-designed features; learned systems can sometimes perform better when more of the representation is learned from data. The balance between explicit structure and learned components depends on the problem.

Fixed and learned portions of a program

A component can be held fixed while gradients update another part of the system. For instance, an already-trained encoder can produce representations while another component is trained. In software frameworks, this generally involves controlling which parameters receive updates, while still computing any gradients required to pass a signal through the system.

A custom operation that has no gradient rule may not be suitable for direct gradient-based training. One option is to place it in preprocessing and treat its output as the model input. Another is to define a differentiable rule for it. Even when a gradient can be defined, calculating it may be computationally expensive or impractical.


13. Optimizing parameters versus optimizing inputs

Gradient-based optimization is not limited to model parameters. Any variable that influences a differentiable objective can be optimized, including the input to a fixed model.

Parameter optimization

The standard training procedure changes model parameters to reduce the objective:

θ⟶lower J(θ).\theta \longrightarrow \text{lower } J(\theta).θ⟶lower J(θ).

Input optimization

An input can instead be changed while the model parameters remain fixed. For example, an image can be optimized to increase a selected model output. This approach is used to inspect what a model responds to or to synthesize inputs with desired properties.

For classification models, the choice of what to optimize can matter. Optimizing a class probability after a softmax may increase the target probability by making competing classes less likely, rather than by strongly increasing the target class’s raw score. Optimizing the pre-softmax class logits can behave differently and may be more stable in some settings.

Feature visualization and DeepDream

A trained network can be probed by optimizing an input to increase a chosen neuron’s activation. The resulting input gives an approximate visualization of the patterns that activate that neuron or layer. Such visualizations are interpretations of the learned model’s responses, not necessarily literal descriptions of how a human would understand the feature.

DeepDream is an example of this general idea: repeatedly adjusting an image to amplify patterns that a trained network detects can produce highly patterned or surreal images.


14. Embeddings and combining pretrained models

An embedding, also called a representation, is a lower-dimensional vector produced from a more complex input. An encoder maps an input such as an image or text sequence into a compact representation. For example, an image encoder might map an image to a vector in a space of hundreds or thousands of dimensions.

A shared embedding space can make it possible to compare different kinds of inputs. A text encoder and an image encoder can be trained so that semantically related text and images have similar representations. Cosine similarity is one measure of similarity between vectors, though it is only one component of larger mechanisms such as transformer attention.

A model such as CLIP produces text and image representations in a shared space. Once its encoders have been trained, they can be held fixed while another part of a system is optimized.

For example, a fixed image generator can produce an image from a latent input zzz. The generated image can then be encoded by a fixed image encoder, and its representation can be compared with the representation of a text prompt. The optimization can adjust zzz to make the generated image more compatible with the text, while keeping the encoders and generator fixed. Gradients still need to pass through the fixed components to compute how changing zzz changes the final similarity.

This illustrates a general principle of differential programming: a system can be assembled from pretrained or fixed modules, and a selected input or parameter set can be optimized with respect to an objective defined across the combined system.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent