Unit 7 of 8 · about 6 hours · derive, implement
Stable log-sum-exp, online reductions and mixed precision
Long reductions can fail even when each individual input is representable. Stable identities and explicit accumulator dtypes give you independent checks beneath probability losses and mixed-precision training.
You'll be able to
- Derive log-sum-exp's shift identity, max bounds and convexity without relying on a loss implementation.
- Implement naive, balanced pairwise and Kahan reductions and distinguish an error bound from a measured error.
- Prove online mean and centered-sum invariants and test low-precision storage with higher-precision accumulation.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Log-sum-exp as a smooth convex maximumConvex Optimization
Section 3.1.5: Log-sum-exp bounds on p. 72 and the Hessian/Cauchy-Schwarz proof on p. 74
Read only the log-sum-exp passages. Derive the max-shift identity yourself; leave gradients of a classification loss to the linked later unit.
- Summation trees and compensationThe Accuracy of Floating Point Summation
Section 2 (pp. 784 to 786), especially equations 2.1 to 2.6; Section 3's general error expression and pairwise summation (pp. 787 to 788) and Kahan's compensated summation (pp. 790 to 791, equation 3.10 on p. 791)
Skip Section 2's sorting examples and Section 3's insertion and +/- methods. Derive the basic recursive bound, then inspect the balanced-tree and compensated algorithms; no probabilistic rounding model is assigned.
- Online mean and centered second momentAccurately computing running variance
Opening cancellation example and recurrence formulas for , and sample variance
Stop before the C++
RunningStatclass. Prove the invariant in exact arithmetic before translating it to NumPy. A variance can be zero, and overflow can still occur. - Precision budget for inputs and accumulatorsPyTorch numerical type information
torch.finfo:eps,maxandsmallest_normalforfloat16,bfloat16,float32andfloat64
Focus on
- For finite nonempty , , . Every exponential is and at least one is 1, giving . The Hessian is PSD by a weighted-variance argument.
- With unit roundoff , no overflow or underflow and , recursive summation has absolute error , . A balanced tree shortens rounding paths; it does not remove conditioning from cancellation.
- Online mean uses and . The centered sum updates . Check with base case , and divide by only for sample variance with .
- Higher-precision accumulation can prevent repeated rounding of the running total. It cannot restore detail lost when input values were quantized; distinguish operand, product and accumulator precision.
Common mistakes · 3
- Using
np.sumas a claimed naive left-to-right baseline. Its reduction strategy depends onaxisand layout; implement the order you claim to test. - Rearranging Kahan's compensation into algebraically equivalent operations. Reassociation changes the rounding errors the correction is meant to retain.
- Ignoring empty inputs, infinities or the sample-variance denominator. The finite nonempty contract and variance contract need explicit checks.
Try it yourself
Closed-book, before checking anything
[1,2,3]: mean=2, M2=2, sample variance=1. In NumPy float64 use x=[1000,1001,999]; the shifted formula gives 1001.4076059644, allowing 1e-10 absolute error for this displayed rounding. Compare the unrounded result with scipy.special.logsumexp on SciPy 1.18.1: measured absolute difference is 0; require , not exact equality. Implement a left-to-right sum with float64 accumulator zero, a balanced sum splitting each array at len(a)//2 recursively (empty sum zero, singleton returns its value), and Kahan with s=c=0; for each v use y=v-c, t=s+y, c=(t-s)-y, s=t. On np.concatenate((np.array([1e16],dtype=np.float64),np.ones(1024,dtype=np.float64),np.array([-1e16],dtype=np.float64))), the outputs are 0, 1022 and 1024. Against math.fsum's 1024 the measured absolute errors are 1024, 2 and 0; allow 1e-12 for these displayed checks. Run the online recurrence on [1e8+1,1e8+2,1e8+3] in that order in float64: sample variance is 1, while gives 0. The absolute difference from np.var(x,ddof=1) for the online result is 0, allowed . Finally sum 4096 float16 ones left-to-right, explicitly casting every updated accumulator to np.float16: the total stalls at 2048. np.sum on those same inputs with dtype=np.float32 gives 4096; measured absolute errors against the integer count are 2048 and 0. No random draws are needed. These examples do not establish that Kahan or an online variance algorithm wins for every input.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why is the LSE Hessian positive semidefinite but not positive definite?Answer
For finite , are positive and sum to one. . Positivity makes this a weighted variance; constant gives zero, so the all-ones direction is a null direction.
2.Where does the online centered-sum proof use its assumptions?Answer
At , and . For , the old centered deviations sum to zero, so recentering the first values adds with no cross term. The new deviation is ; adding its square gives . Division uses ; the algebra assumes exact arithmetic, not an exact floating-point invariant.
3.Why can a small absolute summation error be a large relative one?Answer
Cancellation can make tiny while is large. The relative error bound contains their ratio, the summation condition number. At a zero exact sum use an absolute criterion instead.
4.Does
float32accumulation makefloat16inputs equivalent to originalfloat32inputs?AnswerNo. It improves the accumulation of already rounded inputs. Any distinction erased by conversion to
float16is still gone, even if every later addition were exact.
You're done when
Your reduction and online-state tests reproduce the stated absolute errors, and you can prove the bounds and centered-sum invariant while explaining which precision losses cannot be repaired.
Only when you can do this without notes.
Leads to
- Stable softmax, cross-entropy and loss reductionsApply the log-partition identity to stable probability losses.
- Precision formats, autocast and gradient scalingApply the distinction between storage precision and accumulation precision.
- Likelihood and perplexity, and their limitsUse stable log probabilities and controlled reductions when aggregating likelihoods.
Notes
Resources · 4 for this unit, 7 more in the section
- Convex OptimizationBoyd & Vandenberghe · required
Read Chapters 1-5 and 9 with the course; use Chapter 10 only for equality-constrained Newton steps.
- PyTorch numerical type informationPyTorch · reference
Read
torch.finfo'seps,maxandsmallest_normalfields and its subnormal note; inspectfloat64,float32,float16andbfloat16on CPU. - The Accuracy of Floating Point SummationNicholas J. Higham · reference
Read Section 2's recursive-sum error bound and Section 3's pairwise and compensated summation algorithms. Leave the statistical error models and historical machine details aside.
- Accurately computing running varianceJohn D. Cook · support
Read the Welford mean and centered-sum recurrences. Prove the centered-sum invariant and translate the recurrence to NumPy; skip the C++ class.
Also in this section
- Stanford EE364a - Convex OptimizationStanford Engineering Everywhere · primary
Follow lectures 1-9 and 15-16; use lecture 17 only for KKT systems. Leave full interior-point treatment for later.
- D2L - Optimization AlgorithmsD2L authors · required
Use the convexity, GD, SGD, minibatch, momentum, AdaGrad, RMSProp, Adam and scheduler sections for ML derivations and code.
- Fundamentals of Numerical ComputationDriscoll & Braun · required
Study §§1.1-1.4, 2.7-2.8, 3.2-3.4 and 4.2-4.3 for floating point, conditioning, stability, least squares and iteration error, in the Python edition.
- CVXPY basic and DCP tutorialsCVXPY documentation · support
Use as the solver oracle after deriving a constrained problem and its KKT conditions by hand.
- Proximal AlgorithmsNeal Parikh and Stephen Boyd · reference
Read Sections 1.1, 4.2 and the elementwise soft-thresholding formula in 6.5.2, then the lasso formulation on p. 196. Skip 7.1.1's penalty-scaling and Gram-rewrite errors on p. 197; derive the update from 4.2 and 6.5.2.
- PyTorch optimizer and gradient-clipping contractsPyTorch · reference
Use AdamW's algorithm and
clip_grad_norm_'s parameters to locate weight decay and clipping precisely. Inspectstate_dictfor optimizer restart; no network training is assigned. - SciPy minimize: BFGSSciPy · reference
Read the BFGS method description and
gtol,maxiter,c1andc2options. Supply an analytic gradient and compare residuals and evaluation counts, not just iterations.