16.5 Optimization problem set, part a: convexity, GD rates, momentum, Adam
Every model in this series after the count-based bigram is trained by an optimizer you build in this chapter: gradient descent with a line search, SGD with momentum, and AdamW, which trains everything from the encoder-decoder of AI Engineering to its capstone. Those optimizers must match PyTorch’s trajectories step by step, and implementations go wrong on exactly the details this set drills: a step size past that oscillates, momentum that is summed one step off, a bias correction applied to the wrong moment, weight decay coupled into the adaptive step. When a training run diverges, the first questions you will ask are the ones here: what is the curvature, what is the condition number, and is the learning rate under the stability limit?
Concepts from other sections (17)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- Bias correction: dividing and by and to undo the zero initialization. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Heavy-ball momentum: the update , . Read more: 16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
- Characteristic polynomial: , whose roots are the eigenvalues of . Read more: Chapter 9: Linear Algebra
- First moment (,
exp_avg): the EMA of the gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay - Second moment (,
exp_avg_sq): the EMA of the elementwise squared gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay - Convex function: a function whose chords lie above its graph; every stationary point is a global minimum. Read more: 16.1 Convexity, smoothness, gradient descent, and Armijo line search
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Covariance: , a measure of linear co-movement; zero does not imply independence. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Backtracking: depth-first search over a tree of partial solutions that makes a choice, recurses, and undoes the choice, abandoning any branch that cannot lead to a valid solution; it enumerates subsets, permutations, and solutions to constraint problems. Read more: Chapter 11: Backtracking in Programming and Algorithms
- Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
- Geometric sum: the sum of the first terms, for and for . Read more: 6.3 Sequences, geometric series, and frequency ladders
- DPO: minimizing over preference pairs, equivalent to fitting the KL-regularized reward objective. Read more: 18.2 Direct preference optimization and IPO in AI Engineering
The set has 17 problems (24 numeric or symbolic parts and 2 proofs), grouped into convexity and the condition number, gradient descent rates and step size, momentum, and Adam. It is pen-and-paper work and supplies the analysis behind Convexity, smoothness, gradient descent, and Armijo line search, The Optimizer protocol: SGD, momentum, Nesterov, weight decay, and Adam and AdamW: bias correction and decoupled weight decay. You will want the proof habits of the Discrete math 1 problem set for q4 and q17, and the gradients and Hessians of the Calculus 3 problem set.
Work each problem on paper first, then open the answer and compare not just the result but the derivation. Each answer names the common wrong answer and why it is wrong, because those are exactly the mistakes that show up later as bugs in an optimizer. Each problem also carries a tag for the kind of answer it wants ([number], [interval], [expr in ...], [bool], [proof]); rates and steps are exact fractions.
Learning objectives
- Decide convexity from second derivatives and Hessians, and compute , , and for a quadratic.
- Derive the stable step-size interval, the optimal constant step, and the step count for a target accuracy.
- Analyze heavy-ball momentum through its velocity sum and its characteristic polynomial.
- Compute Adam and AdamW steps by hand, and prove that bias correction makes the first moment unbiased.
The toolkit
Section titled “The toolkit”The problems use a small set of symbols, collected here:
| Symbol | Meaning | Type / shape |
|---|---|---|
| the objective (loss) | ||
| a minimizer and the minimum value | ||
| gradient and Hessian | , | |
| smoothness: (largest curvature) | scalar | |
| strong convexity: (smallest curvature) | scalar | |
| condition number | scalar | |
(eta) | step size, the learning rate | scalar |
(beta), | momentum and Adam’s moment decay rates | in |
| Adam’s first and second moment estimates | like | |
| AdamW weight decay | scalar |
Convexity
Section titled “Convexity”A function is convex if every chord lies on or above it: for . For twice-differentiable this is equivalent to in one variable, and to a positive semidefinite Hessian ( for every ) in several. Convexity matters because every local minimum of a convex function is global. Sums and nonnegative multiples of convex functions are convex (q4); is concave; is convex, so cross-entropy in the logits is convex, while the loss of a whole network in its weights is not.
Smoothness, strong convexity, and the condition number
Section titled “Smoothness, strong convexity, and the condition number”is -smooth when its gradient changes by at most per unit of distance, which for twice-differentiable means every Hessian eigenvalue is at most ; it is -strongly convex when every eigenvalue is at least . For a quadratic with symmetric , and are the largest and smallest eigenvalues of . The condition number measures how elongated the level sets are: is a round bowl, a long narrow valley. It sets how many steps a digit of accuracy costs: about at .
Gradient descent on a quadratic
Section titled “Gradient descent on a quadratic”In the eigenbasis of , gradient descent acts on each coordinate separately: coordinate is multiplied by every step. It converges from every start exactly when for every , that is . The worst factor is smallest when the extreme eigenvalues balance, , giving and rate . The safe default gives rate . With rate , reducing the error by a factor takes steps. Without strong convexity, an -smooth convex still satisfies at .
Backtracking (Armijo) line search avoids knowing : start with and shrink by until the step decreases by at least a fraction of what the linear model predicts, .
Momentum
Section titled “Momentum”Heavy-ball momentum keeps a velocity and steps . Unrolled, : an exponentially weighted sum of past gradients, which for a constant gradient approaches , so steps are times larger. On a one-dimensional quadratic with curvature the iterates satisfy the linear recurrence ; substituting gives a quadratic in , and the iterates shrink like the larger root’s modulus. When the roots are complex their product is the squared modulus, so both shrink by per step, independent of . Choosing so that this holds for every eigenvalue gives and a rate of about instead of .
Adam and AdamW
Section titled “Adam and AdamW”Adam keeps exponential averages of the gradient and of its elementwise square, and , starting from 0. Because they start at 0, early averages are too small by the factor (q17), and dividing by it gives and . The step is per-coordinate: dividing by the root mean square of recent gradients makes it roughly in size whatever the gradient’s scale. On the first step and , so the step is when . AdamW adds weight decay as a separate multiplication of the weights by , instead of adding to the gradient where would rescale it.
Two problems worked in full
Section titled “Two problems worked in full”Before the set itself, here are two siblings of q5 and q16, worked completely, so you can see the level of detail the answers expect.
Consider step sizes on . The Hessian is , so , , . Gradient descent converges for . The best constant step is , where the factors are and : both coordinates shrink by per step, the rate . At the factors are and , so the rate is : slower, though the stiff coordinate converges in one step. From with : , .
Now take one AdamW step with , , , , . Then , , the adaptive step is , and the decay is . So : this step’s push upward and the decay cancel exactly.
The problems
Section titled “The problems”The problems are grouped by topic. Each group builds on the toolkit above; open an answer only after you have one of your own.
Convexity and the condition number
Section titled “Convexity and the condition number”q1. Is the function convex on the given domain? (a) on . (b) on . (c) on . [bool]
Answer
(a) true, (b) false, (c) true.
- (a) everywhere, so is convex. A common mistake is to answer false because : convexity needs , not (that would be strict convexity, and is strictly convex anyway).
- (b) on , so is concave, not convex.
- (c) The Hessian of is with , the covariance matrix of a one-hot draw from , so . This is why cross-entropy, which is of the logits minus a linear term, is convex in the logits.
q2. with . Give (a) the smoothness constant , (b) the strong convexity constant , and (c) the condition number . [number]
Answer
(a) , (b) , (c) .
The Hessian of is itself, and its eigenvalues are the diagonal entries 1 and 10. is the largest, the smallest, so . A common mistake is , which is : the condition number is at least 1 by definition. This is the kind of quadratic on which the gradient descent of Convexity, smoothness, gradient descent, and Armijo line search shows the gap.
q3. On which interval is convex? Give the largest one. [interval]
Answer
.
and , which is nonnegative exactly when . A common mistake is : that is where , where is increasing, which says nothing about curvature. Another is , the concave side.
q4. Prove: if and are convex on , then is convex. [proof]
Answer
Proof. Let and . By convexity of and of at the same , , :
Adding the two inequalities gives
which is the definition of convexity for .
What makes the proof work: both inequalities are taken at the same points and the same , so the right-hand sides add term by term. The same argument with a factor shows nonnegative multiples are convex; with the inequality flips, which is why the condition is needed.
Gradient descent rates and step size
Section titled “Gradient descent rates and step size”q5. Gradient descent with a constant step .
(a) For (so ), give the set of for which from every start. [interval]
For :
(b) give the step that minimizes the worst per-coordinate contraction ; [number]
(c) give that worst contraction factor; [number]
(d) give the worst contraction factor with . [number]
Answer
(a) , (b) , (c) , (d) .
- (a) , so . This converges from every start iff , i.e. . A common mistake is , the condition : it is sufficient but not the whole set. Another is : at the factor is exactly and the iterate flips sign forever without shrinking.
- (b) The eigenvalues are and . The worst factor is smallest where the two balance, , so and . Not : that is the safe default, not the optimum.
- (c) At both factors have magnitude .
- (d) At the factors are and , so the worst is . A common mistake is , which would predict absurdly fast convergence.
q6. The error shrinks by a factor per step. What is the smallest number of steps with ? [number]
Answer
132.
Take logs: , and since dividing flips the inequality: . The smallest integer is 132. A common mistake is 131, rounding down: after 131 steps the error is still slightly above . This matches the rule of thumb from the toolkit above: at with , each digit costs about steps (the exact figure is ).
q7. Run gradient descent on from with . Give . [number]
Answer
.
, so . From : , , . A common mistake is , which comes from using (dropping the 2), so the factor becomes .
q8. Backtracking (Armijo) line search accepts the first with . For at with , , , , which is accepted? [number]
Answer
.
At : , , , and .
- : , . The test needs . It fails: the step overshoots to the mirror point with no decrease.
- : , . The test needs . It holds, so is accepted.
A common mistake is , accepting without testing it; another is , backtracking once more after the test already passed.
q9. For convex, -smooth , gradient descent with satisfies . Give the bound for , , . [number]
Answer
.
. A common mistake is , dropping the 2 in the denominator. Note the rate: without strong convexity, halving the gap costs twice as many steps, not a constant number.
Momentum
Section titled “Momentum”Heavy-ball momentum: , , with .
q10. Suppose the gradient is a constant . (a) Give . [expr in g, beta] (b) For , by what factor is the long-run step larger than plain gradient descent’s step ? [number]
Answer
(a) , (b) 10.
- (a) With : , , and in general . A common mistake is , which sums from the second term only and forgets that the current gradient enters with weight 1.
- (b) The long-run step is , so the factor is . A common mistake is 9, which is . This factor is why a learning rate tuned for plain SGD must shrink by about when momentum is turned on.
q11. On the iterates satisfy .
(a) Give the monic characteristic polynomial in whose roots are the modes . [expr in r, beta, eta, h]
(b) When its two roots are complex, both have modulus . Give that modulus for . [number]
Answer
(a) , (b) .
- (a) Substitute into and divide by : , i.e. . A common mistake is , the wrong sign on the term; the product of the roots would then be and the analysis would predict a mode of modulus above 1. Another is , plain gradient descent with a spurious root at 0.
- (b) For a monic quadratic the product of the roots is the constant term, . Complex roots are conjugates, so and . A common mistake is , which is itself rather than its square root.
q12. The best heavy-ball momentum on a quadratic with condition number is . Give for . [number]
Answer
.
, so . A common mistake is , forgetting the square; another is , using where belongs. The convergence rate is then , which for beats plain gradient descent’s best rate of by a wide margin: that is the speed-up.
q13. With and gradient at every step, give . [number]
Answer
.
, , . A common mistake is () or (): an off-by-one in where the sum starts. With , has exactly terms.
Adam keeps and from , corrects and , and steps . AdamW also decays the weights: .
q14. If every gradient equals the same , give . [expr in g, beta1, t]
Answer
.
Unroll: . A common mistake is , which is the bias-corrected , not . With , : without the correction the first step would be ten times too small, which is the bias that Adam and AdamW removes.
q15. Take . On the first step the gradient is and . Give . [number]
Answer
.
- and .
- and , so .
- .
The first step is whatever the size of the gradient. A common mistake is (moving with the gradient instead of against it); another is (using the raw gradient size, as plain SGD would).
q16. AdamW with , , , , . Give . [number]
Answer
.
- The adaptive step is , by the same argument as q15.
- The decoupled decay is .
- .
A common mistake is (forgot the decay) or (forgot the Adam step). Had the decay been added to the gradient instead (), Adam’s normalization would have divided it by and the first step would still be exactly , the decay would vanish into the sign: that is why AdamW keeps it outside.
q17. Prove that if every has the same expectation , then , so is an unbiased estimate of . [proof]
Answer
Proof. From and , induction on gives
(Base case : . Step: .) Taking expectations and using linearity with for every :
Dividing by the constant gives , so is unbiased.
The same argument with shows . The assumption that every has the same mean is what makes the geometric sum factor out; in training the mean drifts slowly, which is why the correction is exact only in this idealization but matters most in the first few hundred steps, where is still far from 0.
Mistakes to watch for
Section titled “Mistakes to watch for”The common wrong answers in the set fall into a handful of patterns, and each one has a counterpart bug in optimizer code:
| Pitfall | Symptom | How to avoid it |
|---|---|---|
| Confusing where increases with where it is convex | a wrong region of convexity | test , not (q3) |
| Taking as the stability limit, or including | needlessly small learning rates, or a run that oscillates forever | require strictly, giving the open interval (q5(a)) |
| Rate instead of | absurd step-count estimates | compute the factor per eigenvalue (q5(d)) |
| Rounding a step count down | one step short of the target accuracy | take the ceiling of (q6) |
| Dropping the factor 2 in | half-speed descent | differentiate before iterating (q7) |
| Accepting without the Armijo test | a step that increases the loss | evaluate the sufficient-decrease test at every candidate, including (q8) |
| Summing momentum from the wrong index | velocity off by one term | start from so has exactly terms (q10, q13) |
| Wrong sign of the term | a momentum analysis that predicts divergence | derive the polynomial from the recurrence; the root product is (q11) |
| Forgetting the bias correction is about ‘s start at 0 | first steps 10 times too small | unroll to get the factor (q14, q17) |
| Decay inside the adaptive step, or omitted | AdamW trajectories that drift from torch’s | apply separately from (q16) |
Where this leads
Section titled “Where this leads”The convexity and rate problems (q1 to q9) are the theory behind gradient_descent and armijo_step in Convexity, smoothness, gradient descent, and Armijo line search, whose convergence follows the bound of q5. The momentum problems (q10 to q13) analyze SGD with momentum and Nesterov in The Optimizer protocol, and the Adam problems (q14 to q17) check AdamW with bias correction and decoupled decay in Adam and AdamW. Learning-rate schedules (cosine, WSD, Noam) and gradient clipping then changes over time and bounds the step, and Training loop and the autograd bigram in AI Engineering is the first training loop that calls these optimizers. Beyond this book, the top Hessian eigenvalue during training and the edge of stability, where , apply q5’s analysis to real networks. Part b of the set, Optimization problem set, part b, turns to constrained optimization and the derivation behind DPO.
Further reading
Section titled “Further reading”- Boyd and Vandenberghe, Convex Optimization (free), chapters 3 and 9.
- Goh, Why Momentum Really Works (Distill, 2017).
- Kingma and Ba, “Adam” (2015), sections 2 and 3.
- Loshchilov and Hutter, “Decoupled Weight Decay Regularization” (2019).
Summary
Section titled “Summary”- On a quadratic, gradient descent multiplies each eigen-direction by , so it converges exactly when , and its best rate is (q5).
- The condition number sets how many steps a digit of accuracy costs: about at (q2, q6).
- Momentum averages gradients with weights , so a constant gradient produces steps times larger; on a quadratic its modes shrink by per step (q10, q11).
- Adam’s moments start at zero and are biased toward it by a factor ; the bias correction removes exactly that, and the first step is times the sign of the gradient (q14, q15, q17).
- AdamW’s decay multiplies the weights by outside the adaptive step, so it is not rescaled by (q16).