Unit 2 of 8 · about 6 hours · derive, implement

Gradient descent, stochastic gradients and momentum

A controlled quadratic separates curvature-driven instability from gradient noise. It gives you predictions to test before trying an optimizer on a network.

You'll be able to

  • Derive the stable step-size interval and optimal fixed-step contraction for a positive definite quadratic.
  • Implement gradient descent and heavy-ball momentum with explicit initial state and trajectory tests.
  • Derive unbiased minibatch gradients and their covariance under independent sampling with replacement.

Covers

Gradient descent on quadratic and general objectivesStochastic gradients, minibatches and noiseMomentum and acceleration intuition
1

Read

In this order, only the parts listed

0 of 4 done

  1. EE364a: descent and line searchStanford EE364a - Convex Optimization

    Lectures 15 and 16 notes: Descent methods (slide 10-5), Line search types (10-6), and Gradient descent method (10-7)

    Stop before steepest descent and Newton's method.

  2. Descent on smooth objectivesConvex Optimization

    Sections 9.2 and 9.3.1 (pp. 463 to 469)

    Use the upper quadratic model to derive . Distinguish this descent guarantee from the exact quadratic contraction below.

  3. GD, stochastic updates and minibatch noiseD2L - Optimization Algorithms

    Sections 12.3.1 to 12.3.2 (Gradient Descent), 12.4.1 to 12.4.2 and 12.4.4 (Stochastic Gradient Descent; 12.4.4 compares sampling with and without replacement), and 12.5.2 (Minibatches)

    Follow the adjacent GD and minibatch pages. Use the PyTorch tab for update cells only; skip datasets, training loops and timing claims.

  4. Heavy-ball dynamics on quadraticsD2L - Optimization Algorithms

    Sections 12.6.1.2 to 12.6.1.4 and 12.6.3.1 to 12.6.3.2; PyTorch momentum_2d cell

2

Focus on

  • In the eigenbasis, GD errors obey . Uniform convergence for all starts requires ; minimizes the worst factor to .
  • Heavy-ball uses . Each eigenmode has characteristic polynomial ; repeated roots can produce a transient factor.
  • For and independent uniform indices, the minibatch average gradient is unbiased and has covariance . Sampling without replacement has a finite-population correction; reshuffling is not independent sampling.
  • On a general -smooth lower-bounded objective, the descent lemma controls objective decrease, not global optimality. Report full-objective residuals separately from noisy minibatch gradients.
Common mistakes · 3
  • Including in the convergent interval. The largest-curvature mode has multiplier -1 there.
  • Claiming momentum contracts by its asymptotic spectral radius at every step. Repeated roots and initial state affect transients.
  • Calling the squared-gradient moment a noise variance, or assuming four correlated gradients reduce variance by four. Independence matters.
3

Try it yourself

Closed-book, before checking anything

By hand derive the GD eigenmode recurrence and heavy-ball polynomial. In NumPy float64 use , , . After ten updates, GD with has and in exact arithmetic (measured absolute discrepancy 1.4e-17, allow 1e-12). Heavy-ball with and has . At GD's second coordinate alternates without shrinking; at its magnitude after ten steps is 1.96715136. Then create rng=np.random.default_rng(5); make its only draw noise=rng.standard_normal((10000,4),dtype=np.float64), in array row order. np.var(noise[:,0],ddof=1) is 0.984311 and np.var(noise.mean(axis=1),ddof=1) is 0.251557. Derive the theoretical variances 1 and 1/4; these measured values are not exact theoretical equalities. Allow absolute 1e-6 for the displayed simulation values.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why is the quadratic rate a Euclidean error rate, not the same objective-gap rate?Answer

    Symmetry gives an orthonormal eigenbasis; positivity gives eigenvalues in . Every error multiplier has magnitude at most , hence , including the base case . The quadratic gap weights squared errors, so it contracts by at most .

  2. 2.What happens at if the initial error has no largest-eigenvalue component?Answer

    It may still converge in the remaining modes. The strict bound guarantees convergence for every initial error, rather than claiming every start fails at the boundary.

  3. 3.Why does minibatch covariance divide by B?Answer

    Center each gradient and expand the covariance of their average. Independence makes cross-covariances zero; identical sampling gives diagonal terms , divided by . Unbiasedness follows from uniform sampling of the average objective.

  4. 4.Does constant-step SGD converge exactly when additive gradient noise persists?Answer

    Generally no. For scalar curvature , independent zero-mean noise variance and give limiting error variance . The variance recurrence adds at every step.

5

Practice

  • D2L: momentum on multiple eigenvalues

    Section 12.6.5, Exercise 2: , ,

    Use and record all hyperparameters and initial velocity. Compare equal gradient-evaluation budgets; include an unstable GD step and explain the transient rather than claiming universal momentum acceleration. The section mini-project extends this to minibatch noise.

You're done when

Your trajectories match the eigenmode predictions within 1e-12 in Euclidean norm, you explain one boundary failure, and you derive the minibatch covariance with its sampling assumptions.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 8 more in the 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.

  • Convex OptimizationBoyd & Vandenberghe · required

    Read Chapters 1-5 and 9 with the course; use Chapter 10 only for equality-constrained Newton steps.

  • D2L - Optimization AlgorithmsD2L authors · required

    Use the convexity, GD, SGD, minibatch, momentum, AdaGrad, RMSProp, Adam and scheduler sections for ML derivations and code.

Also in this section

  • 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. Inspect state_dict for optimizer restart; no network training is assigned.

  • SciPy minimize: BFGSSciPy · reference

    Read the BFGS method description and gtol, maxiter, c1 and c2 options. Supply an analytic gradient and compare residuals and evaluation counts, not just iterations.

  • PyTorch numerical type informationPyTorch · reference

    Read torch.finfo's eps, max and smallest_normal fields and its subnormal note; inspect float64, float32, float16 and bfloat16 on 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.