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

Speaker 1Speaker 2

Training Neural Networks

15:24
0:00-15:24
  1. Hope

    Welcome to our episode on how neural networks are trained. We’ll start with gradient descent and the challenges of optimization, then build up from computation graphs and backpropagation to a broader idea called differential programming.

  2. Simon

    Let’s begin with the basic training setup. We have an input, like an image of a clownfish, and a ground-truth answer describing what the model should predict. The input passes through layers of a neural network, and a loss measures how far the prediction is from that answer.

  3. Hope

    The model’s parameters—the numbers associated with its layers—are what training changes. We adjust them until the model’s predictions become reasonably good on the data we have. More formally, we want parameters that minimize a cost built from the losses across the training examples.

  4. Simon

    And we can evaluate that cost for a given set of parameters. We can also evaluate its gradient, which gives a local direction of change, and in principle its Hessian, which contains second-order information. In practice, neural-network training usually focuses on first-order methods rather than calculating the Hessian.

  5. Hope

    Gradient descent starts at some current parameter setting and moves downhill on the cost’s loss landscape. The learning rate controls how large each step is. In the usual convention, we subtract the gradient multiplied by the learning rate, since the gradient itself points uphill.

  6. Simon

    There’s an important limitation: a complicated, non-convex landscape can have multiple minima. Gradient descent may find a local minimum rather than the global one, and how much worse that local minimum is can be hard to know.

  7. Hope

    Computing the gradient over every training example for every update can also be too slow or too large to fit in memory. Stochastic gradient descent, or SGD, instead estimates the full-data gradient using a batch—a subset of the data.

  8. Simon

    At batch size one, you update after each example. At the other extreme, a batch containing the entire dataset gives standard gradient descent. Smaller batches make updates more practical, but their gradients can differ from the full-data gradient.

  9. Hope

    That difference introduces noise and variance. It can be especially noticeable when categories are imbalanced: a category might be missing from several batches, then appear and shift the gradient substantially. So the stability of batch gradients can depend on how uniformly the data is distributed.

  10. Simon

    The noise isn’t only a drawback. SGD can be faster, and even small samples can give a useful approximation to the total gradient. The noise can also act as an implicit regularizer and sometimes help the optimization move out of a local minimum.

  11. Hope

    But the same noise can make updates unstable. In practice, SGD’s advantages and disadvantages depend on the data and the training setup; there isn’t a guarantee that every batch points in a helpful direction.

  12. Simon

    Momentum is one way to change how updates behave. The physical analogy is an object gaining speed as it rolls downhill. In optimization, a momentum term carries some influence from the previous direction of movement, so updates can keep moving in a direction that has been consistently useful.

  13. Hope

    The strength of that carry-over is controlled by a hyperparameter. Moderate momentum can reach a minimum faster, but too much can cause the updates to overshoot and oscillate. Adam is a commonly used optimizer that includes a form of momentum.

  14. Simon

    Now consider the shape of the loss landscape. A smooth bowl with one minimum is relatively friendly: gradients point toward the minimum, and they gradually shrink as you approach it. But other shapes can make optimization much harder.

  15. Hope

    A landscape with several local minima makes the starting point matter. A completely flat region provides no gradient signal about where to go. A nearly flat region can make progress very slow, while noisy batches may overwhelm the weak signal.

  16. Simon

    A very steep landscape can cause the opposite problem. Near its minimum, the gradient may become enormous, producing unstable updates that overshoot—what we call exploding gradients. So both very small and very large gradients can make learning difficult.

  17. Hope

    A discontinuity isn’t automatically a problem for a framework like PyTorch. Autograd can provide gradients for functions that aren’t traditionally differentiable everywhere, using conventions such as directional derivatives around discontinuities. But having a computable gradient doesn’t mean the landscape is easy to optimize.

  18. Simon

    Exactly. A flat function can have a defined gradient in PyTorch, but if that gradient is zero everywhere, it gives the optimizer no useful direction. Computationally being able to calculate a gradient and having a useful signal are different things.

  19. Hope

    One practical response to non-convexity is to try different random initializations, or random seeds, and compare the resulting models. How much the performance varies across seeds can tell you something about how sensitive the optimization is to its starting point.

  20. Simon

    There are also alternatives and safeguards. Evolution strategies sample small perturbations around current parameter values and move toward perturbations with lower loss. That can help explore a region even when gradient information is weak or unhelpful.

  21. Hope

    Gradient clipping addresses excessively large gradients. If a gradient exceeds a chosen threshold, you scale it back, limiting how far an update can move. It’s a simple, commonly used way to reduce unstable jumps and oscillation.

  22. Simon

    For activation functions, people often discuss continuity, differentiability, and smoothness as properties that may help optimization. ReLU is continuous and differentiable almost everywhere, but it has a kink, so it isn’t smooth everywhere.

  23. Hope

    GELU, the Gaussian error linear unit, is one smoother alternative. It can be written as the input multiplied by the Gaussian cumulative distribution function evaluated at that input. GELU is continuous, differentiable, and smooth everywhere.

  24. Simon

    Those properties are not a guarantee that one activation always trains better than another. The broader point is that recent designs have tended toward functions with all three properties, while the field still lacks a definitive theory saying exactly which properties are necessary or optimal.

  25. Hope

    Let’s shift from optimization to computation graphs. A computation graph represents functional transformations: nodes perform computations, and edges carry information between them. A neural-network layer can be one node, or a node could represent a larger module.

  26. Simon

    The usual structure in deep learning is a directed acyclic graph, or DAG. Directed means information flows one way along an edge; acyclic means there are no loops. A simple multilayer perceptron is a chain-shaped DAG: input, linear layer, activation, another layer, and then output.

  27. Hope

    A forward pass evaluates those transformations in order. Each layer takes its input and parameters, applies its function, and passes its output onward. At the end, the model’s output is compared with the ground truth to calculate the loss.

  28. Simon

    Training also needs derivatives of that loss with respect to parameters throughout the model. Matrix calculus helps describe those derivatives: for a scalar output and an n-element column-vector input, the derivative with respect to the input is a row vector of n partial derivatives.

  29. Hope

    For a vector output with m elements and a vector input with n elements, the derivative is the Jacobian, an m-by-n matrix. Each entry tells how one output component changes with respect to one input component. For a scalar output and a matrix input, the derivative has the same arrangement of components as that input.

  30. Simon

    The chain rule is what connects derivatives across layers. If one function feeds into another, the derivative of the final result with respect to the original input is the product of the derivatives along the way. The dimensions line up: an m-by-p derivative multiplied by a p-by-n derivative gives an m-by-n derivative.

  31. Hope

    Backpropagation applies that chain rule efficiently. If we calculated every parameter’s derivative independently, we would repeatedly calculate the same intermediate terms. Backprop reuses shared calculations, sending the loss’s gradient backward through the graph.

  32. Simon

    So training has three broad stages: run a forward pass and calculate the loss; run a backward pass to propagate gradients; then update the parameters. Repeat those steps until a chosen stopping signal—for example, performance on a validation set—levels off.

  33. Hope

    For a generic layer, it helps to track how its outputs change with its inputs and how the cost changes with its outputs. Combining those derivatives tells us how the cost changes with the layer’s inputs and parameters, which gives the directions needed for updates.

  34. Simon

    With batches, the objective is usually the average cost across the examples in the batch. The gradient of that average is the average of the individual gradients, so a batch update combines information from multiple data points.

  35. Hope

    A linear layer makes the mechanics especially clear. With column-vector input x and weight matrix W, the output is W times x. In the backward pass, the gradient with respect to the input is obtained by multiplying by the transposed weight matrix, under this column-vector convention.

  36. Simon

    The weight gradient has an equally simple structure: it is the output gradient combined with the input, as an outer product. Then the learning rate scales that gradient, and the weights are adjusted in the direction that reduces the cost.

  37. Hope

    In an MLP, those linear operations are interleaved with activations such as ReLU. During the backward pass through ReLU, the gradient is gated: components that were on ReLU’s zero side receive no gradient through that activation, while the other components can pass one.

  38. Simon

    That gating depends on the activation values from the forward pass, so those intermediate values need to be retained for backpropagation. This is one reason the backward pass is not simply a forward pass in reverse with no extra memory: the computation needs information saved from the forward pass.

  39. Hope

    For a linear layer, forward and backward use closely related matrix operations, with transposes depending on the gradient convention. More broadly, backpropagating a first-order gradient is locally linear: it uses a linear approximation to the loss, even when the full loss landscape is curved.

  40. Simon

    What changes when the graph isn’t just a chain? Many models split information, combine separate paths, or share parameters. The key operations for handling a general DAG are branching and merging.

  41. Hope

    At a merge, gradients need to be routed to the inputs that contributed to the result. The exact operation might be addition or concatenation, for instance, but each path receives the gradient components relevant to its input.

  42. Simon

    At a branch, one value feeds multiple paths. When gradients come back from those paths, you add their contributions and send the combined gradient back through the shared input. If parameters are shared across branches or layers, their gradient contributions are likewise summed.

  43. Hope

    That gives a useful way to understand backpropagation through any DAG: apply the chain rules along the paths, route gradients correctly at merges, and sum them where a computation branches. An MLP is simply the especially straightforward case where the graph is a chain.

  44. Simon

    This leads to differential programming: thinking of a model as a program made of composable operations that support differentiation. Libraries such as PyTorch and JAX provide tools for defining and differentiating these computations; the lecture also mentions TensorFlow.

  45. Hope

    The appeal is that neural networks are compositional, like blocks assembled into a larger system, and their differentiable parts can be optimized together. Some reusable blocks are architectural components such as convolution, pooling, LSTMs, GANs, VAEs, memory units, and routing units.

  46. Simon

    But not every component has to be learned. A system might include a standard parser or human-defined preprocessing, alongside neural components trained by backpropagation. For example, normalization values for natural images can be specified directly rather than learned.

  47. Hope

    That’s related to the idea sometimes called Software 2.0: instead of explicitly writing every behavior, you define a space of possible systems and use training data and a cost function to select behavior within that space. Human-designed components constrain the system; those constraints can help, but they can also limit it.

  48. Simon

    The history of feature engineering illustrates that trade-off. Hand-designed features can encode useful ideas, but they can also impose a bottleneck. In some settings, larger systems learned end-to-end have outperformed systems built around those human-designed constraints.

  49. Hope

    Differentiable programming also broadens what we can optimize. We usually think about changing model parameters to reduce cost, but, for a fixed model, we can also calculate how changing its input changes an output or score.

  50. Simon

    That’s the basis of feature visualization. You can adjust an input image to maximize a model’s cat score, or adjust an input to maximize a particular neuron’s activity at a particular layer. The resulting patterns can offer a way to probe what the model responds to.

  51. Hope

    DeepDream is a familiar example of amplifying patterns that a model responds to, producing striking images. The same principle applies beyond visualization: if a computation is differentiable, we can propagate a signal through it to optimize an input.

  52. Simon

    Consider CLIP, which maps text and images into a shared embedding space so that semantically related text and images are close together. If we connect a fixed CLIP model to a fixed image generator, we can optimize the generator’s input so the resulting image matches a chosen text prompt in that shared space.

  53. Hope

    The networks in that example can all be fixed; the thing being optimized is the input to the image generator. We still backpropagate a signal through the fixed models to work out how that input should change. This shows why modularity matters: components trained separately can be connected for a new task.

  54. Simon

    An embedding, or representation, is the vector produced when an encoder maps a complex, high-dimensional input—such as an image—to a lower-dimensional representation. The fixed encoder can turn an image or a prompt into a vector that another component can use.

  55. Hope

    And loss and cost are sometimes used loosely in conversation. One useful distinction is that loss refers to the measure for examples, while cost can refer to an aggregate, such as the sum or average over data. The essential idea is that the chosen objective defines what counts as better.

  56. Simon

    So the full picture is: choose a cost, compute forward through a graph, propagate gradients backward efficiently, and update parameters—or, when useful, optimize inputs instead. The same principles extend from a simple chain to branching and merging DAGs, which is what makes differentiable, modular systems so powerful.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent