Neural Network Gradients


Neural Network Gradients

Hope
Today we’re tackling a central question in neural networks: how do we train a network with many weights and hidden layers when changing one weight can affect a loss all the way at the output? Gradient-based methods worked well for models like logistic regression and linear SVMs, but a neural network is a much more complicated composition of functions.

Corey
The key is to find the gradient of the loss with respect to each weight. That tells us how the loss changes when a weight changes, and an optimizer can use that information to update the weights. The challenge is calculating all those gradients efficiently.

Hope
One straightforward option is a numerical gradient. Take the parameter you’re interested in, change it by a small amount, run the function again, and estimate the derivative from the change in output divided by the change in the parameter. It’s an approximation to the derivative’s limiting definition.

Corey
And numerical gradients are broadly applicable: you don’t need to work out a symbolic derivative, only evaluate the function at the original and slightly changed inputs. But for a neural network, you’d have to do this separately for every weight, running the network again each time. With many weights, that becomes incredibly slow, so it’s generally impractical for training large networks.

Hope
At the other extreme, we could derive the gradients analytically by hand, as we’ve done for simpler models. When that’s manageable, analytic gradients are direct and efficient to evaluate. But for a large composition of operations, the algebra becomes unwieldy and error-prone; one small mistake can throw off the gradients throughout the model.

Corey
Fortunately, those derivatives are built from a rule we already know: the chain rule. In its simplest form, if y depends on u and u depends on x, then dy by dx equals dy by du times du by dx. In other words, the gradients multiply along a chain of functions.

Hope
The evaluation points matter. If the combined function is f of g of x, its derivative is f prime evaluated at g of x, multiplied by g prime evaluated at x. The input to one function is the output of the preceding function, and the derivatives are evaluated at those corresponding values.

Corey
And that extends to any number of functions. For f of g of h of x, we multiply f prime evaluated at g of h of x, by g prime evaluated at h of x, by h prime evaluated at x. It’s a mechanical rule, which makes it a good candidate for automation.

Hope
A useful way to picture a composition is as a directed graph. Each node represents an operation, and each edge represents data flowing from one operation to another. For example, x can flow into f, f of x can flow into g, and the final result is g of f of x.

Corey
Each node has a local derivative: f’s derivative at its input, and g’s derivative at its input, which is f of x. To get the derivative of the whole graph, we multiply those local derivatives. We can think of the gradients as flowing backward from the final output toward the input, even though multiplication itself doesn’t impose a direction.

Hope
Take sine followed by exponential. The input x goes through sine, and then sin of x goes through the exponential, so the output is exp of sin x. The local derivative of sine is cos x, and the derivative of the exponential is its output, exp of sin x. Multiplying gives cos x times exp of sin x.

Corey
A longer example is the sigmoid, or logistic, function. It can be built from four operations: negate x, exponentiate, add one, and take the reciprocal. That gives one over one plus e to the minus x.

Hope
Each operation has a simple local derivative. Negation has derivative minus one; exponentiation has derivative equal to its output; adding one has derivative one; and taking a reciprocal has derivative minus one over the input squared. Multiply those local derivatives, evaluated at the values passing through the operations, and you get the overall derivative.

Corey
We don’t need to simplify that product into a particularly elegant symbolic expression. The point is to calculate the answer, and the same sequence of multiplications can give us gradients at intermediate stages as well as the gradient with respect to the original input.

Hope
Graphs can branch, too. Suppose x and w go into a multiplication node, and the product xw goes into a sigmoid node. The output is sigmoid of xw. The local derivatives of the multiplication are w with respect to x and x with respect to w, while the sigmoid node contributes the sigmoid derivative evaluated at xw.

Corey
So the overall derivative with respect to x is w times the sigmoid derivative at xw, and the derivative with respect to w is x times that same sigmoid derivative. A branch means we track a gradient for each input; it doesn’t change the basic idea of combining local derivatives with the gradient coming back from downstream.

Hope
For computation, we can make this even more practical by working with numerical values rather than carrying around full symbolic expressions. We only need the gradient’s value for the particular example we’re evaluating, because that’s what will eventually be used to update parameters.

Corey
For instance, if x is 2 in the sine-then-exponential example, sin of 2 is about 0.91, and its exponential is about 2.48. The local derivative of the exponential is therefore about 2.48, while the local derivative of sine is cos of 2, about minus 0.42. Multiply them and the overall derivative is about minus 1.04.

Hope
For the four-step sigmoid example, use x equals 1.5. Negation gives minus 1.5, exponentiation gives about 0.22, adding one gives about 1.22, and the reciprocal gives about 0.82. The local derivatives are approximately minus one, 0.22, one, and minus 0.67, respectively; their product gives an overall derivative of about 0.15.

Corey
And for the branched example, let x equal minus 1.2 and w equal 0.3. Their product is minus 0.36, and the sigmoid output is about 0.41. The sigmoid derivative there is about 0.24, so the overall gradients are about 0.07 with respect to x and minus 0.29 with respect to w.

Hope
In a program, each operation can save its intermediate output: out one equals f one of x, out two equals f two of out one, and so forth. On the backward calculation, start at the end. Multiply the local derivative of the last operation by the gradient arriving from downstream, then pass the resulting gradient to the preceding operation. Continue until you reach the input.

Corey
That gives each operation a useful kind of independence. A node needs its own inputs and outputs and a way to calculate its local derivative. It passes data forward without needing to know the whole network, then receives a downstream gradient and uses it to calculate what to pass backward.

Hope
We can choose where node boundaries go. We might make a sigmoid out of simple arithmetic nodes, as in that example, or treat sigmoid as one node if we already know its derivative. The choice is about organizing the computation in a useful way.

Corey
Neural networks also work with vectors and matrices, not just scalars. The same broad principle applies, but gradients are vectors or matrices of partial derivatives. Their shape matches the corresponding data or parameter vector or matrix, with each partial derivative associated with the corresponding element.

Hope
Two vector operations are especially important. A linear layer can use the inner product of an input vector x and a weight vector w. If z is their dot product, the gradient of z with respect to x is w, and the gradient with respect to w is x.

Corey
Both are useful: the gradient with respect to x is passed back to earlier layers, and the gradient with respect to w is used to update that layer’s weights. For an elementwise activation, each output element is the scalar function applied to the corresponding input element, so the gradient vector contains the individual scalar derivatives.

Hope
Layer boundaries can also help avoid unnecessary complexity. Softmax by itself has a Jacobian because each output can depend on every input. But when softmax is combined with cross-entropy loss, many of those extra terms disappear, leaving a simpler gradient vector. In that situation, it can make sense to treat softmax and cross-entropy together as a single layer.

Corey
If a layer has multiple outputs, its weights may form a matrix, and we need a gradient for every entry, so the weight gradient has the same matrix shape. With matrix-valued data, such as a batch or mini-batch, we can pass around the full data gradient or take a sum or mean across examples. Using the mean is generally more stable and makes gradients more comparable across different batch sizes.

Hope
The layers may handle their local computations, but something still has to manage the overall network and the order in which information moves. A data structure or class can keep track of the network and coordinate the layers, either through a traversal function or through methods that manage the work internally.

Corey
That coordination happens in two passes. First comes the forward pass: each operation runs only after its inputs have been calculated, and data moves from the network’s inputs through to the output. At the end, the network calculates the loss.

Hope
Then the backward pass starts with that loss and propagates its gradients back through the network. Each layer receives the gradients from downstream, combines them with its own local derivatives, and sends gradients to earlier layers. By the time this reaches the inputs, the gradients throughout the network have been calculated.

Corey
It’s important to separate backpropagation from optimization. Backpropagation calculates gradients; it does not itself decide how to update the weights. An optimizer, such as gradient descent or one of its variants, uses the gradients to update the weights, after which we can run another forward pass and backward pass.

Hope
That cycle repeats until a stopping criterion is reached: forward pass, calculate loss, backward pass, update weights, and repeat. The gradients tell the optimizer how the loss changes with respect to the parameters, while the learning algorithm determines what to do with that information.

Corey
There’s one more difference from many simpler models: neural networks with hidden layers usually have non-convex loss functions. A very simple network without hidden layers can represent logistic or softmax regression, which have convex losses, but adding hidden layers generally removes that guarantee.

Hope
A non-convex loss can raise the concern that optimization will get stuck in a local minimum. How serious that is depends on the data, the network structure, and the task. For some deep-learning problems, including some in computer vision, evidence suggests local minima may not be a significant obstacle.

Corey
The idea of a “bad” local minimum helps clarify that point. A problem can have local minima without those minima being poor approximations of the global minimum. So non-convexity matters, but its practical consequences depend on the problem rather than following automatically from the word “local.”

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