Numerical Computation
Machine learning runs on finite-precision arithmetic, where every number is approximated and every operation rounds. This lesson sets the numerical ground rules: overflow and underflow and the standard stabilizations, the condition number that measures how much a problem amplifies error, and the gradient-based optimization (first and second order, constrained and unconstrained) that every training loop runs.
╌╌╌╌
A learning algorithm is a continuous-mathematics object (gradients, integrals, matrix inverses) executed on a machine that stores real numbers in a finite number of bits. The translation is lossy. Every real is rounded to the nearest representable float, and the gap between adjacent floats grows with magnitude, so arithmetic accumulates rounding error that a careless formula can amplify without bound. Two failures dominate, and each has a standard remedy.1
Overflow and underflow
A 64-bit float represents a number as a sign, a mantissa, and an exponent. The exponent is bounded, so the representable magnitudes occupy a finite window: below it numbers collapse to , above it they saturate to .
For IEEE-754 double precision the boundaries are concrete: the largest finite value is about and the smallest positive normal value about . The function reaches these limits at tiny arguments ( overflows for and underflows for ), and that fragility makes softmax, a tower of exponentials, the canonical place where numerical care is mandatory.2
The softmax stability trick
The softmax turns a vector of scores into a probability distribution,
Two ways this breaks: if every is large and positive, each overflows; if every is large and negative, every underflows to and the denominator becomes . The fix exploits a shift-invariance. For any constant ,
Subtracting a constant from every logit leaves the softmax unchanged. Choose :
The log-sum-exp trick
A second hazard hides downstream. Cross-entropy needs , and computing the softmax first then taking its log underflows: a correctly computed but tiny probability rounds to , and . Fold the log into the exponentials instead. Starting from the definition and pulling the shift through the logarithm,
The recurring quantity is the log-sum-exp function, and the same shift makes it safe:
The shifted form also reveals as a smooth maximum: , so it never exceeds the true max by more than , and equals it when one logit dominates. Library softmax/cross-entropy implementations fuse all of this into a single numerically stable kernel; never compute softmax and its log as two separate steps.3
| Quantity | Naive form | Stable form () | Failure avoided |
|---|---|---|---|
| over/underflow | |||
| overflow of |
For example, take logits . The naive denominator asks for , and each term overflows to in double precision (recall saturates near ), so the ratio returns . Subtracting first,
which is exact and never leaves the safe window. The shift changed nothing mathematically — only which intermediate values the machine had to hold.
Poor conditioning
Even arithmetic that never overflows can be untrustworthy if the underlying problem amplifies small input changes into large output changes. The amplifier is the condition number.
When is large the matrix is ill-conditioned, and the solution is highly sensitive to perturbations in (and to the rounding error already present in ). Decompose ; the inverse stretches the component of along eigenvector by , so the direction of smallest eigenvalue is magnified most:
A perturbation aligned with the small-eigenvalue direction is amplified by while itself may only be of size , giving a worst-case relative error blowup of exactly :
Gradient-based optimization
Most deep-learning algorithms reduce to optimization: choosing to minimize (or maximize) an objective function . When the goal is minimization we call the cost, loss, or error function, and write the target as .
In one dimension the derivative gives the slope, and the update steps downhill: where the slope is positive we decrease , where negative we increase it. The generalization to many variables replaces the derivative with the gradient , the vector of partial derivatives .
To descend fastest we pick the direction that minimizes this slope:
minimized at , i.e. points opposite the gradient. This is the method of steepest descent: step against the gradient,
with the learning rate (step size).5
The full procedure is the base every later optimizer refines.
- 1initialize
- 2repeat
- 3gradient at the current point
- 4step against the gradient
- 5untilconverged: gradient near zero
- 6return
The Jacobian and the Hessian
When is vector-valued, , its first derivatives form a matrix.
For a scalar objective , the gradient's own derivative (the matrix of second partials) is the Hessian, and it encodes curvature.
The Hessian sharpens the critical-point test. The second-derivative test reads curvature off the eigenvalues of at a critical point:
| Hessian at critical point | Curvature | Classification |
|---|---|---|
| (all ) | bowl up in every direction | local minimum |
| (all ) | dome down in every direction | local maximum |
| eigenvalues of mixed sign | up some ways, down others | saddle point |
| some | flat direction | test inconclusive |
Curvature sets the step size
Approximate near the current point by its second-order Taylor expansion in the gradient direction. Writing and the Hessian at , a step of size along gives
The middle term is the gain we want; the last term is the curvature penalty. If the quadratic in is minimized by setting its derivative to zero, , giving the optimal step size
High curvature ( large) shrinks : a steep, narrow valley demands tiny steps; low curvature permits large ones.
The condition number of the Hessian
When the Hessian's eigenvalues differ wildly, a single scalar learning rate cannot serve every direction at once.
A step large enough to make progress along the gentle (small-) direction overshoots and oscillates along the steep (large-) direction; a step small enough to be stable on the steep direction barely moves on the gentle one. Gradient descent is forced to compromise and zig-zags down the valley, taking many steps to cross what is geometrically a short distance.
Newton's method
Second-order methods address this by using to rescale the step per-direction. Expand to second order around and minimize the approximation exactly. The quadratic model is
Setting the gradient of the right-hand side to zero,
yields the Newton step
The power comes at a cost: forming and inverting is in the parameter count , intractable for deep networks with millions of parameters, which is why practice relies on cheaper approximations. A second problem is subtler.
| Method | Step | Cost / iter | Conditioning | Saddle behavior |
|---|---|---|---|---|
| Gradient descent | steps to converge | steps away (slowly) | ||
| Newton's method | 1 step on a quadratic | attracted to saddles |
Constrained optimization
Often we minimize not over all of but over a feasible set carved out by constraints. The standard form has equality and inequality constraints,
The method of Lagrange multipliers converts this constrained problem into an unconstrained one by folding each constraint into the objective with its own multiplier.
At an equality-constrained optimum the objective's gradient must be parallel to the constraint's, ; otherwise a move along the constraint surface would still decrease . The general first-order optimality conditions are the Karush–Kuhn–Tucker (KKT) conditions.
Complementary slackness encodes a clean dichotomy: each inequality is either inactive (, and its multiplier — the constraint does not bind) or active (, and — the constraint pins the solution to the boundary).7 The figure shows the active case, where the optimum leaves the unconstrained minimum and rests against the boundary.
Mixed precision and low-bit training
The overflow/underflow window this lesson treats for double precision has become a front-line engineering concern, because modern training deliberately uses fewer bits.
Mixed precision and the two 16-bit formats. Training in 16-bit floats halves memory and roughly doubles throughput on modern accelerators, but the choice of format comes down to an overflow/underflow tradeoff. IEEE fp16 has a 10-bit mantissa and only 5 exponent bits, so its representable window stops around and — small gradients underflow to zero. bfloat16 keeps 8 exponent bits (the same dynamic range as fp32, up to ) at the cost of a 7-bit mantissa, trading precision for range precisely because underflow, not rounding, is what breaks training. This is the window diagram of this lesson made into a hardware decision (Micikevicius et al., 2017).
Loss scaling. When fp16 is unavoidable, loss scaling multiplies the loss by a large constant before back-propagation, shifting every gradient up into the representable window, then divides by before the weight update. It is the softmax shift trick in reverse: rescale to dodge the boundary, then undo the rescale, changing nothing mathematically while keeping every intermediate in the safe range.
Cheap curvature. The Newton step this lesson rules out for large has practical stand-ins. K-FAC (Martens and Grosse, 2015) approximates the Hessian (really the Fisher information) as a Kronecker product of two small per-layer factors, each cheap to invert, capturing the conditioning that plain gradient descent ignores without ever forming the full matrix — the standard way second-order ideas reach real networks.89
Takeaways
- Underflow (nonzero , deadly in denominators and logs) and overflow () are the two finite-precision failures; hits both at modest arguments.
- Softmax is stabilized by subtracting from every logit (leaving the result unchanged); the log-sum-exp identity keeps finite; always fuse them, never compute softmax then log.
- The condition number measures how much a problem amplifies error; ill-conditioned Hessians make gradient descent zig-zag.
- Steepest descent steps against the gradient; critical points classify by the Hessian eigenvalues (the second-derivative test), and curvature sets the optimal step .
- Newton's method jumps to the minimum of a quadratic in one step but costs and is attracted to saddle points.
- Constrained problems fold constraints into the Lagrangian; the KKT conditions (stationarity, feasibility, dual feasibility, complementary slackness) characterize the optimum, which an active inequality pins to the feasible boundary.
Footnotes
- Goodfellow, Deep Learning, Ch. 4 — Numerical Computation: finite-precision arithmetic as the substrate of every learning algorithm, where rounding, overflow, and underflow are first-class concerns. ↩
- Goodfellow, Deep Learning, §4.1 — Overflow and Underflow: how saturates at modest arguments and why softmax is the canonical site demanding numerical care. ↩
- Stevens, Deep Learning with PyTorch, Ch. 7 — softmax and cross-entropy are fused into a single stable kernel (
log_softmax+nll_loss); never compose softmax and its log as separate ops. ↩ - Goodfellow, Deep Learning, §4.2 — Poor Conditioning: the condition number as the amplifier of input error, and the Hessian's as the cause of zig-zagging descent. ↩
- Goodfellow, Deep Learning, §4.3 — Gradient-Based Optimization: steepest descent as stepping against , the directional derivative minimized opposite the gradient. ↩
- Goodfellow, Deep Learning, §4.3.1 — Beyond the Gradient: in high-dimensional non-convex losses saddle points dominate, making naive Newton steps hazardous because they are attracted to critical points of any type. ↩
- Goodfellow, Deep Learning, §4.4 — Constrained Optimization: the Lagrangian and the KKT conditions (stationarity, primal/dual feasibility, complementary slackness) characterizing a constrained optimum. ↩
- Micikevicius, Narang, Alben, Diamos, Elsen, Garcia, Ginsburg, Houston, Kuchaiev, Venkatesh, Wu (2017), Mixed Precision Training, arXiv:1710.03740 — fp16 vs. bf16 dynamic-range tradeoffs and loss scaling to keep gradients inside the representable window. ↩
- Martens and Grosse (2015), Optimizing Neural Networks with Kronecker-factored Approximate Curvature, ICML — a Kronecker-product approximation to the Fisher/Hessian that makes an approximate second-order step tractable for deep networks. ↩
╌╌ END ╌╌