A correct gradient is only one ingredient of training. The data have to be split and shuffled, the weights need starting values, an optimizer turns gradients into updates, and progress has to be judged on data the updates never saw. This lesson follows a small constructed experiment, a two-feature classifier trained with two learning rates, and uses it to define the training loop. It then explains how initialization and depth decide whether gradients stay usable, how momentum and Adam use past gradients, and why batch normalization behaves differently in training and in evaluation.
Key terms
Training loop
Definition A training loop fits the parameters of a model to a training set of examples by repeating epochs, where an epoch is one pass through the training data. In each epoch it does the following.
- Shuffle the order of the training examples and split it into mini-batches.
- For each mini-batch of examples, run the forward pass, compute the mean loss over the batch, clear any stored gradients, run the backward pass, and let the optimizer update every parameter with the gradients from this same forward pass.
- After the epoch, compute the loss on the full training set and on the validation set with the model in evaluation mode and without any update.
- When the validation loss is the best so far, save a copy of the parameters as a checkpoint, with the epoch number and, if training may resume, the optimizer state.
Validation examples never enter a gradient, and the test set is not used inside the loop. For a binary label in and a logit , the loss of one example computed directly from the logit is
which equals the binary cross-entropy . The derivative of the batch mean with respect to the logit of example is . Evaluating in a numerically stable way avoids taking the logarithm of a probability that has rounded to or .
In plain words The loop is the experiment written as code, and each line has one job. Many failed runs come from a line doing the wrong job, such as gradients left over from the previous batch, a loss summed where the learning rate assumes a mean, or validation run in training mode. A learning-rate schedule, if used, belongs to the loop as well and must say whether it advances per update or per epoch. A fixed random seed makes the shuffles and the initialization repeatable on the same software, but other hardware or library versions can still change the floating-point results.
Example In a constructed problem two features are drawn uniformly from , and the label is when , that is, in the first and third quadrants including the axes. No straight line separates the classes. Separate random draws give training and validation examples. The network has inputs, hidden units and logit, both runs start from the same initialization, and plain mini-batch gradient descent with batches of makes updates per epoch for epochs, with a constant learning rate of or . With the examples of a batch stored as the rows of a array, the hidden array is , the logits form a vector of length , and every gradient array has the shape of its parameter. The validation results were
| Run | Epoch | Validation loss | Correct of 48 |
|---|---|---|---|
| Both rates, before training | 0 | 0.7129 | 24 |
| Rate 0.03 | 250 | 0.6549 | 34 |
| Rate 3, best checkpoint | 91 | 0.3641 | 43 |
| Rate 3, last epoch | 250 | 0.4205 | 42 |
Predicting for everyone gives a validation loss of , and predicting class for everyone gets of right, so the slow run made only modest progress in updates. The fast run did much better, but its validation loss fluctuated, for example at epoch , and its last state is worse than the checkpoint from epoch , which is the model kept. This is one seed on one small constructed problem, so it does not show that large learning rates are better in general. The checkpoint was chosen for its validation loss, so is an optimistic estimate of its loss on new data, and an untouched test set gives the honest final number.
Weight initialization
Definition Weight initialization is the rule that sets the parameters before the first update. It has two jobs. The first is to break symmetry. If two hidden units of a layer start with the same incoming weights, the same bias and the same outgoing weights, they compute the same value on every input and receive the same gradients, so gradient descent, momentum and Adam keep them identical forever. Random initial weights break this symmetry, and biases can then start at . The second job is to set the scale. Suppose a preactivation is with weights drawn independently of each other and of the inputs, each with mean and variance . Then, over the random draw,
The choice keeps equal to the average of the . Glorot initialization, also called Xavier initialization, uses and was derived for activations such as that are close to linear near . He initialization uses for ReLU layers. The factor makes up for ReLU setting the negative half of a preactivation that is symmetric around to zero, which halves its mean square.
In plain words Units that start identical stay copies of each other. Weights that start too large push and sigmoid units into their flat regions, where the derivative is nearly , and weights that start too small shrink the signal layer after layer. Scale rules aim to keep typical preactivations and gradients at similar sizes in every layer. They are sensible defaults, not optimal values.
Example The experiment drew first-layer weights with standard deviation , for two inputs, and output weights with standard deviation , for eight hidden units, with all biases . Features uniform on have , so averaged over the random draw each first-layer preactivation starts with variance . If instead every weight and bias starts at , every hidden value is . The output weights then get the gradient , where holds the hidden values and the derivatives of the loss with respect to the logits, and the first-layer gradients are multiples of the output weights, which are . Only the output bias ever changes, so the network remains a constant predictor at every learning rate. Rerun this way at rate , the experiment ends with a validation loss of about , essentially that of predicting for everyone.
Vanishing and exploding gradients
Definition Consider hidden layers for , and write for the Jacobian of layer with respect to its input. The chain rule gives, for ,
so the gradient reaching an early layer is a product of many factors, and in the spectral norm
A vanishing gradient is one whose size shrinks roughly geometrically toward the early layers, so their parameters barely change. An exploding gradient grows roughly geometrically and produces huge or nonfinite updates. If , as for , and every , the bound falls at least like , and for the sigmoid . No norm bound forces an explosion, but factors larger than along the directions the gradient actually takes make one happen. Gradient clipping by norm with a threshold replaces by , which limits the length of a step and keeps its direction.
In plain words Each layer multiplies the backward signal by its own factor. Many factors a little below starve the early layers of signal, and many factors above blow it up. Watching the gradient norm of each layer and checking for nonfinite values often shows the problem earlier than the loss does. Scale-aware initialization, ReLU-type activations, normalization layers and smaller learning rates all help. Clipping tames an explosion but cannot restore a gradient that has vanished, and it does not repair a wrong loss.
Example A chain of ten scalar factors equal to multiplies a gradient by , and ten factors equal to multiply it by . The derivative is at , about at and about at , so a saturated unit passes back less than of the gradient it receives. In a chain of ten sigmoid units joined by weights equal to , the gradient is multiplied by at most . Clipping the gradient , whose norm is , at gives .
Momentum
Definition Gradient descent with momentum keeps a running average of past gradients. With a momentum constant in , a learning rate and , step computes the mini-batch gradient at and sets
With this is plain stochastic gradient descent. Unrolling gives , a weighted sum of past gradients whose weights decay geometrically. Many libraries use instead and . Since , the two produce the same iterates when , so a learning rate means something only together with its convention. The vector is part of the state of the run.
In plain words Momentum keeps a running direction. Gradients that keep pointing the same way build up, and gradients that flip sign from step to step largely cancel. In a long narrow valley this damps the zigzag across the valley and keeps progress along it. The memory can also carry the parameters past a minimum, so and are tuned together on validation data.
Example With and a constant gradient , the running average is , , and in general , which approaches . With gradients alternating it is , , , and settles into swinging between about . The consistent signal passes through at full size and the oscillating one shrinks by a factor of . Under the library convention a constant gradient builds up toward , which is why the two conventions need different learning rates.
Adam optimizer
Definition Adam has a learning rate , decay rates and in and a small constant , with common defaults , , and . Starting from , step takes the gradient at and computes
and then
The square, the square root and the division act entry by entry, so every parameter gets its own effective step size. The second moment averages squared gradients, which is not the square of the averaged gradient. The bias corrections undo the pull of the zero starting states, and for a constant gradient they give exactly and . The vectors and and the counter are part of the state of the run. Adam guarantees neither convergence nor good accuracy on new data, and simple convex problems are known on which it does not converge to the minimizer.
In plain words Adam combines momentum with a separate scale for every parameter. Dividing the averaged gradient by the root of the averaged squared gradient makes typical steps about in size, whatever the scale of each parameter’s gradient, which helps when gradients differ greatly between layers. It is a common default for networks, but it still needs a tuned learning rate and validation checks.
Example At the first step and , so each entry moves by , almost exactly against the sign of its gradient. With , the default decay rates and a gradient of , the raw states are and , the corrected ones are and , and the parameter moves by . A gradient of moves another parameter by about , nearly the same, while a gradient of , smaller than , moves it by only about . The state matters when a run resumes. If the second gradient of the first parameter is , the saved state gives and , a step of about . A run restarted with fresh zero states would instead step by , about nineteen times as far.
Batch normalization
Definition Let a layer’s values for a mini-batch of examples form an array with entry for example and feature . In training mode batch normalization computes, for each feature over the batch axis,
and outputs
where is a small constant and the scale and the shift are learned parameters, usually started at and . This shift has nothing to do with the decay rates of an optimizer. The backward pass differentiates through and , so each example’s gradient depends on the other examples of its batch. Training also keeps running estimates of each feature’s mean and variance, typically exponential moving averages of the batch statistics. In evaluation mode the layer uses those stored estimates instead of the current batch, so it applies a fixed affine map to each feature and a prediction depends only on its own input. Libraries differ in details such as the averaging rate and whether the running variance divides by or .
In plain words Batch normalization rescales each feature to mean about and variance about within the batch and then lets the network learn a new scale and shift. It often permits larger learning rates and makes training less sensitive to the initialization. Its two modes really compute different functions, so validation and prediction must run in evaluation mode, and the running estimates should come from training batches only.
Example One feature takes the values , , and in a batch of four. Then and , and with , and the outputs are about , , and . In a batch with the values , , and the same input value becomes about , so in training mode an example’s output changes with its batch mates. If the stored estimates were mean and variance , evaluation mode would map the value to in every batch. A training-mode batch of one example has , so every output equals whatever the input, and the layer erases the information, which is why batch normalization needs batches of at least two and works poorly with very small ones.
Check yourself
- Adam starts with , , and , and the first gradient of a parameter is . Find the raw and the corrected moments and the change of the parameter. Compare with plain gradient descent at the same rate, and with a first gradient of .
Show the answer
The raw moments are and . The corrections divide by and , giving and . The update is , so the parameter increases by about . Moving against a negative derivative raises the parameter and lowers the loss to first order.
Plain gradient descent at rate would move the parameter by . With a first gradient of , Adam still moves it by about , while plain gradient descent would move it by only . The first Adam step depends on the sign of the gradient and hardly on its size, as long as the gradient is much larger than .
- A model has one parameter and the training objective , whose gradient is . Gradient descent starts at with rate . The framework adds each new gradient into a stored buffer, and the loop never clears it. Compute the first three updates with and without the bug, and describe the trace of the loss.
Show the answer
The correct loop multiplies by at every step, giving , and , and after steps about . With the bug the update uses the sum of all gradients so far. The first step uses and gives . The buffer then holds , so . Next it holds , so .
The values continue , , and keep swinging between about and without settling. Subtracting consecutive updates gives , whose characteristic roots are complex with modulus , so the oscillation never decays, and the loss keeps climbing back to about . A loss that falls at first and then oscillates or rises at a learning rate that should be safe is a typical sign of this bug. The fix is to clear the gradients before every backward pass, or, when several batches are accumulated on purpose, to scale the loss by the number of batches, update once and then clear.
- A network with dropout and batch normalization is trained by a loop with the following evaluation step. After each epoch the code turns off gradient recording and computes the validation loss with the model still in training mode. It also computes the test loss, and whenever the test loss is the lowest so far it stores
best = params, whereparamsis the list of the live parameter arrays. Find the problems and fix them.
Show the answer
Validation in training mode is wrong. Dropout randomly removes units, so the validation loss is noisy and is not the loss of the model that will be used. Batch normalization uses the statistics of each validation batch instead of the stored ones, and in common libraries a training-mode pass also updates the running estimates, so validation data leak into the model. Switch to evaluation mode for validation and back to training mode afterward. Turning off gradient recording only saves memory and time and does not change how these layers behave, so both settings are needed.
Choosing the checkpoint by test loss makes the test set part of model selection, and its loss is then an optimistic estimate. Select the checkpoint by validation loss and evaluate the test set once, at the end.
Storing best = params keeps references to the arrays that later updates keep changing, so the saved model silently becomes the final model. Save copies of the parameters, together with the epoch and, if training may resume, the optimizer state.