SAM optimizer: Sharpness-Aware Minimization for Efficiently Improving Generalization
Take each gradient at the highest-loss point near the current weights, and training settles where the loss is flat.
SAM adds one move to every training step. It shifts the weights a short distance ρ in the direction that raises the loss fastest, computes the gradient at that shifted point, and applies that gradient to the original weights. A step costs two gradient computations instead of one.
Explaining the paperSharpness-Aware Minimization for Efficiently Improving GeneralizationA Google Research paper from October 2020 that turned the idea that flat minima generalize into a change of four lines to SGD, with one hyperparameter and a default of ρ = 0.05.
Pierre Foret, Ariel Kleiner, Hossein Mobahi and Behnam Neyshabur posted the paper in October 2020, and it appeared at ICLR 2021. Its starting point is a fact about modern networks: they can fit their training set almost perfectly, even when the labels are random (the result behind Rethinking Generalization), so a low training loss says little about test error. A large network has many weight settings that all reach near-zero training loss and differ in how well they do on new data. SAM chooses among them with a geometric test: prefer weights whose whole neighborhood has low loss.
The name is unrelated to Segment Anything, the 2023 segmentation model also called SAM. This page covers the optimizer in this order:
- what sharp and flat minima are, and why flatness is a plausible proxy for generalization;
- the SAM objective, the worst training loss within a radius ρ of the weights;
- the first-order approximation that turns it into two gradient computations per step;
- m-sharpness, the per-device version the experiments actually ran;
- the results, and how much of them the paper's theory accounts for.
Sharp and flat minima
Write the model's weights as one long vector with entries, and its training loss as the average per-example loss over the training examples:
What we care about is the population loss , the expected loss on a fresh example from the same distribution. Training can only see . For a deep network has many minima of nearly equal depth, and they can differ a lot in .
A minimum is sharp when the training loss rises quickly as the weights move away from it, and flat when the loss stays low over a wide neighborhood. Curvature is the formal version. The Hessian is the matrix of second derivatives of the loss; its largest eigenvalue is the curvature along the steepest direction. Near a minimum the loss grows like along that direction for a step of length , so a minimum with rises 24 times faster than one with (those are the two values the paper measures later, without and with SAM).
There are two standard arguments that flatness should help. The first treats the test loss as the training loss displaced a little, because a finite sample of data does not pin down the landscape exactly. Under a small displacement the bottom of a sharp minimum lands on a steep wall, while a flat minimum is still near its floor. The second, from Hochreiter and Schmidhuber (1997), counts bits: a flat minimum tolerates imprecise weights, so the weights can be written down with fewer bits, which is a description-length notion of a simpler model.
An engineering analogy fits the first argument. A part whose function survives a wide manufacturing tolerance is more likely to work under conditions nobody tested; a part that works only at exactly its nominal dimensions is fragile. The analogy breaks on how distance is measured. A tolerance in millimeters means the same thing for every part, but distance in weight space depends on how the network is parameterized: Dinh et al. (2017) showed that a ReLU network can be rescaled to make any minimum look arbitrarily sharp without changing the function it computes. The theory section comes back to this.
The empirical case predates SAM. Keskar et al. (2016) found that training with very large batches converges to sharper minima and generalizes worse than small-batch training. Jiang et al. (2019) trained more than 10,000 convolutional networks and compared over 40 measures that might predict their generalization; the SAM paper summarizes the finding as a sharpness-based measure having the highest correlation with generalization. The SAM paper's related-work section describes the sharpness measures proposed before it as hard to compute and to differentiate through; SAM needs one extra gradient per step.
Figure 1 is a one-dimensional cartoon of the first argument. The teal curve is a training loss with a narrow pit at and a wide, slightly shallower basin near . The dashed amber curve is the same loss shifted right, standing in for the test loss. At the training minimum is the pit, with training loss 0.16 and test loss 0.67 at the default shift of 0.15. The violet curve is the SAM objective of the next section, the highest training loss within distance ρ. Its minimum moves to the wide basin once ρ passes about 0.06, where training loss is 0.27 and test loss 0.30.
The SAM minimum accepts a higher training loss (0.27 instead of 0.16) in exchange for a neighborhood where no point is much worse. With the shift at 0 the test curve is the training curve and the pit wins on test loss too, 0.16 against 0.27; from a shift of 0.06 upward the wide basin wins, and at 0.15 the gap is 0.67 against 0.30. At the far end of the ρ slider the window covers most of the basin, and the objective's minimum moves to , where training loss is 0.57, higher than at either minimum.
The SAM objective
The paper motivates its objective with a generalization bound, stated informally as Theorem 1. For any , with high probability over the draw of the training set,
where is some strictly increasing function and some technical conditions hold. In words: the test loss is at most the worst training loss anywhere within Euclidean distance ρ of , plus a penalty that grows with the size of the weights. Adding and subtracting splits the right-hand side into three parts:
The bracket is the sharpness at : how much the training loss can rise if the weights move by at most ρ. It is the quantity Figure 1 shades. The second term is the ordinary training loss and the third depends only on . Since the exact form of comes from details of the proof, the authors replace it with the standard L2 penalty (weight decay) and define the SAM problem:
(1) is a min-max problem with the shape of adversarial training, except that the adversary perturbs the weights instead of the input image. It has two hyperparameters. ρ ≥ 0 is the radius of the neighborhood, measured in the same units as the weights. The norm sets its shape: is a round ball, a box in which every weight may move by up to ρ. The paper allows any but its experiments found best, so in practice SAM has one hyperparameter. With a Euclidean ball, ρ = 0.05 is small compared to a network's weights. ResNet-50 has about 25.6 million weights, and a length-0.05 vector spread evenly over them would move each weight by about . SAM's perturbation instead points along the gradient, as the next section shows, so most of its length goes to the weights with the largest gradients.
An obvious alternative is to penalize curvature directly, for example with a term proportional to . That needs Hessian information at every step. For ResNet-50 the Hessian has entries, and even estimating its top eigenvalue takes an iterative method with several Hessian-vector products, each roughly the cost of an extra backward pass. Earlier flatness-seeking methods such as Entropy-SGD (Chaudhari et al., 2016) ran an inner sampling loop per step. The maximum in (1) can be approximated with one extra gradient.
How SAM works: one update, two gradients
The inner maximum in (1) is a non-convex maximization over all weights at once. SAM solves an easier problem in its place. Inside a small ball the loss is close to its first-order Taylor expansion, a linear function of :
does not depend on , so it drops out of the argmax. What remains is to find the vector in the ρ-ball with the largest dot product with the gradient . Hölder's inequality bounds that dot product: , where is the dual exponent, . The bound is reached by
with the sign, absolute value and power applied elementwise. Two cases matter. For the formula reduces to : the gradient rescaled to length ρ, the uphill direction. For , and : every weight moves by exactly ρ in the direction of its own gradient's sign, the same formula the fast gradient sign method uses to build adversarial images. In both cases the linearized loss rises by .
A worked example with two weights fixes the numbers. Take the loss , a valley ten times steeper along than along , at with the paper's default ρ = 0.05:
- the gradient is (10 × 0.1 and 1 × 1.0), with length ;
- the perturbation rescales to length 0.05, giving , so the perturbed weights are ;
- the loss goes from to . The linear estimate is 0.621; the remaining 0.007 is the curvature term that the linearization leaves out.
Next comes the gradient of the SAM objective. Substituting into (1) and differentiating with the chain rule gives two terms, because itself depends on :
The second term contains the derivative of , which is built from the gradient, so it involves the Hessian. Automatic differentiation can compute it through Hessian-vector products without forming the Hessian, but the authors drop it to save the cost and keep only the first term:
Algorithm 1 of the paper combines (2) and (3). Each step takes a minibatch, computes its gradient at the current weights, rescales it to length ρ, computes the gradient of the same minibatch's loss at the perturbed weights, and hands that second gradient to an ordinary optimizer, which applies it at the original weights:
# One SAM step (Algorithm 1). Both gradients use the same minibatch B.
g = grad(L_B, w) # pass 1: gradient at the current weights
e_hat = rho * g / norm(g) # Eq. (2) with p = 2: rescale g to length rho
g_sam = grad(L_B, w + e_hat) # pass 2: gradient at the perturbed weights
w = w - lr * g_sam # update the ORIGINAL weights, not w + e_hatIn the two-weight example the gradient at the perturbed point is . Compared with the plain gradient , the steep coordinate grew by 35% and the shallow one by 3.5%, and the step direction turned by 7.6°. For a quadratic this is exact: the gradient at is , and with the extra term is ten times larger along the steep axis.
Figure 2 draws one update on the same valley. The white dot is , the violet arrow is to the edge of the ρ-ball, the gray arrow is the plain gradient step, and the bright teal arrow is the SAM step computed at and applied at . It opens at ρ = 0.3 so the arrows are visible; at that radius the perturbed loss is 1.222 against a linear estimate of 0.974, because the curvature term grows with .
Move up the shallow axis, to say, and the gradient points straight along ; the perturbation is then along a low-curvature direction, the SAM step barely differs from the SGD step, and the angle readout drops to 0°. Switch to and jumps to a corner of the square. Its length is in two dimensions and in , which is one reason the box perturbation is much larger than the ball for a network with millions of weights.
Why the perturbed gradient favors flat regions
Expanding (3) one more order shows what the update does. For small ρ, the gradient at is the gradient at plus the Hessian times the perturbation:
The second equality uses , which follows from differentiating . So, to first order in ρ, the SAM update is gradient descent on the training loss plus ρ times the length of its gradient, which is the linearized SAM objective from the previous section. This is a reading of (3), not a formula from the paper. A gradient-length penalty favors flat regions because on the walls of a sharp basin the gradient grows quickly with distance from the bottom: at distance along a direction of curvature it has length . SGD noise keeps the weights moving around a minimum rather than sitting on it, and a basin with large charges a large penalty for every such excursion.
At the bottom of a minimum the gradient is zero and the first-order picture breaks down. There the exact sharpness of a quadratic basin is : the worst point in the ball lies along the steepest direction, at distance ρ. The exact SAM objective therefore penalizes the top Hessian eigenvalue directly, which is the quantity Section 4.2 of the paper measures. In practice the minibatch gradient is never exactly zero, so is always defined.
If were the exact maximizer of the inner problem, Danskin's theorem says the gradient of the maximum is the gradient at the maximizer with held fixed, so the dropped term would be exactly zero: a maximizer on the ball's surface can only slide along the surface, perpendicular to the gradient there. maximizes the linearized problem instead, and the term survives. For a quadratic it works out to
which is second order in ρ. It is zero when lies along an eigenvector of , and it has a factor that grows as the gradient shrinks. In the two-weight example it is , so the full gradient would be instead of SAM's , about 4% different along the steep axis. Appendix C.4 of the paper ran both versions on a WideResNet-40-2 on CIFAR-10. The two updates had cosine similarity close to 1 for the first half of training and became less similar near convergence, consistent with the factor, and the cheaper first-order version reached the lower test error. The authors call the reason unclear.
The curve that the button under Figure 1 adds, labeled one-step L(w+ε̂), is the value that the algorithm effectively descends. On smooth stretches it tracks the exact maximum. Just past the ridge that separates the pit from the wide basin (its top is at ), it falls below the exact maximum: there the uphill direction points back over the ridge, so a step of length ρ overshoots onto the pit's wall. At the default and , the step lands at , where the loss is 0.67 against an exact maximum of 1.00.
m-sharpness: one perturbation per slice of the batch
The derivation above maximizes over one for the whole training set. Algorithm 1 already replaces that with one per minibatch, and the experiments go one step further. When a batch is split across accelerators, each accelerator computes the first gradient on its own slice, builds its own from it, and computes the second gradient at its own perturbed weights; only the second gradients are averaged across devices. The official JAX code has a flag to sync the perturbations, and it is off by default. In the CIFAR runs a batch of 256 was split across 8 GPUs, so each perturbation was computed from 32 examples. On ImageNet, 4,096 images over 32 TPU cores gives 128 per core, if the batch is split evenly there too.
The paper calls the resulting quantity m-sharpness, where is the number of examples per independent maximization. Split the training set into disjoint groups of size ; then the objective being minimized is
(the paper defines it in words; this is that definition in symbols). With it is (1). With smaller each group chooses its own worst direction, and since the maximum of a sum is at most the sum of the maxima, is never below .
Figure 3 shows the mechanism on a toy batch of 16 two-dimensional gradients. The dashed white arrow is the batch-mean gradient, which sets the single perturbation of . Under the linear approximation each group's sharpness is ρ times the length of its mean gradient. At that is ρ × 0.41; at , where every example perturbs on its own, the average is ρ × 1.02, two and a half times as large, and the 16 perturbations point all around the circle.
On real models smaller helped. The paper trained a small ResNet on CIFAR-10 over a range of and found that smaller values tended to give lower test error (its Figure 3, middle). It also measured how well m-sharpness predicts a model's generalization gap, using the two public tasks of the NeurIPS 2020 Predicting Generalization in Deep Learning competition, and found the prediction improves as decreases. So the version of SAM that worked best is not the one the bound describes, which is . For a fixed global batch, more devices means a smaller , so the device count changes SAM's test error as well as its speed.
Results
Every experiment swaps the optimizer of an existing training recipe for SAM and changes nothing else. ρ was chosen by grid search over {0.01, 0.02, 0.05, 0.1, 0.2, 0.5} on 10% of the training set held out, and Appendix C.3 reports that the default ρ = 0.05 gives nearly the same numbers. To account for the doubled cost per step, each non-SAM baseline was also trained for twice as many epochs, and the better of its two runs is the one reported. Each number is the mean of five runs, with a 95% confidence interval.
CIFAR from scratch. On a WideResNet-28-10 trained for 1,800 epochs with AutoAugment, SAM gives 1.6% test error on CIFAR-10 against 2.2% for SGD, and 12.8% against 16.1% on CIFAR-100. The improvement holds in all 30 CIFAR settings of Table 1. The smallest CIFAR-100 gain is on the most heavily regularized model: PyramidNet with ShakeDrop and AutoAugment goes from 10.6% to 10.3% on CIFAR-100, which the paper reports as the best result on that dataset without extra data.
ImageNet. ResNet-50, -101 and -152 were trained with batch size 4,096, an initial learning rate of 1.0 on a cosine schedule, momentum 0.9, label smoothing 0.1, weight decay 0.0001 and, for SAM, ρ = 0.05. The headline number is ResNet-152 going from 20.3% top-1 error to 18.4%. That compares standard training's best run (200 epochs) with SAM's best (400 epochs). Figure 4 plots all nine pairs. Standard training gets worse from 200 to 400 epochs (ResNet-101 goes from 20.9% to 22.3%), while SAM keeps improving (19.4% to 19.0%). At equal gradient computations, SAM at 200 epochs against standard training at 400, ResNet-152 is at 18.5% against 20.9%.
Fine-tuning. Starting from public EfficientNet checkpoints, SAM lowered the error on every target dataset in Table 3. The largest model, EfficientNet-L2 (pretrained on ImageNet plus unlabeled JFT, 88.2% ImageNet accuracy before fine-tuning), reaches 11.39% top-1 error on ImageNet with SAM against 11.8% without, and 0.30% and 3.92% error on CIFAR-10 and CIFAR-100. The previous best ImageNet number in the table is 11.45%, from the Vision Transformer. The checkpoints come from the EfficientNet family; for ImageNet the models were fine-tuned for 10 epochs at learning rate 0.1 with ρ = 0.05.
Noisy labels. A ResNet-32 was trained for 200 epochs on CIFAR-10 with 20% to 80% of the training labels replaced at random, and tested on the clean test set. With 80% of labels flipped, plain SGD reaches 26.2% test accuracy and SAM 77.9%. Bootstrapping (training once, then retraining from scratch on the first model's predicted labels) raises SAM to 79.9%, close to MentorMix's 81.0%, a method built for noisy labels. SAM used ρ = 0.1, and 0.05 at 80% noise for more stable training. The paper's explanation is a hypothesis: noise in the labels perturbs the loss landscape, and solutions robust to weight perturbations may also be robust to that.
Curvature. To check that SAM finds flatter minima, the authors estimated the Hessian spectrum of a WideResNet-40-10 on CIFAR-10 with the Lanczos method, training without batch normalization, which they say obscures the interpretation of the Hessian. At convergence was about 24 without SAM and 1.0 with it, and the ratio was up to 11.4 without SAM and 2.6 with it.
The appendix tables contain one row where SAM is worse: Shake-Shake on SVHN with AutoAugment, 1.07% error against 1.03% for the baseline (Table 5).
What the theory does and does not explain
The full version of Theorem 1, in Appendix A, holds with probability over the training set:
where is the number of parameters and the number of training examples. The theorem also assumes that adding Gaussian noise to the weights does not lower the test loss, which the authors expect to hold at a trained solution but not everywhere. It is a PAC-Bayesian bound: it compares a Gaussian distribution of weights centered on with a Gaussian prior centered at zero.
For a real network the bound is vacuous. The loss in the proof is bounded by 1, and with ResNet-50 on ImageNet, parameters against images, the first term under the square root alone exceeds as soon as the logarithm is above 1, which it is for any above 0.07 at ρ = 0.05. The square root is then above 4.4, and the right-hand side is larger than the largest possible loss.
The proof's leading term is first derived as the expected training loss under Gaussian weight noise; the maximum over the ball enters afterward as an upper bound on that expectation. So the same argument supports training with random weight noise. Andriushchenko and Flammarion (2022) tested the variants the bound suggests on ResNet-18 (CIFAR-10) and ResNet-34 (CIFAR-100) at batch size 128. Random perturbations and full-batch n-SAM barely beat standard training; only low-m SAM (m = 128) improved test error substantially. Since is never below (smaller gives a larger maximum), a version of the bound written with m-sharpness has its largest right-hand side at m = 128, so it would predict 128-SAM to generalize worst of the three, the opposite of what was measured.
The sharpness measure itself is not invariant to reparameterization. Multiply one ReLU layer's weights by 100 and divide the next layer's by 100, and the network computes the same function, but the loss now changes 100 times faster along the second layer's weights. A fixed ρ-ball measures different things for the two parameterizations. Adaptive SAM (ASAM, Kwon et al. 2021) scales the ball per weight by to remove this dependence.
Two appendix experiments test the approximations directly. Replacing the single ascent step with several steps of projected gradient ascent (Appendix C.6) finds a perturbed loss about 3% higher near convergence on CIFAR-10 with five steps, but test error barely moves: 2.77% with one step and 2.77% with five on CIFAR-10, 16.72% and 16.60% on CIFAR-100. And the box and a random direction of the same length both did worse than the gradient direction with (Appendix C.5). The measured facts are lower test error across the tables and lower Hessian curvature at convergence. That flatness causes the lower test error is the paper's motivating hypothesis, and later work found that a flatter minimum by SAM's own measure does not always generalize better.
Implementing SAM
SAM wraps a base optimizer: it changes which gradient the optimizer receives and nothing else, so the base optimizer can be SGD with momentum (as in the paper), Adam, or anything else. A minimal PyTorch version of one step, close to the widely used davda54/sam implementation that the paper's acknowledgments mention:
import torch
def sam_step(model, loss_fn, batch, base_opt, rho=0.05):
params = [p for p in model.parameters() if p.requires_grad]
base_opt.zero_grad()
loss_fn(model, batch).backward() # pass 1: gradient at w
with torch.no_grad():
norm = torch.norm(torch.stack([p.grad.norm() for p in params]))
eps = [p.grad * (rho / (norm + 1e-12)) for p in params]
for p, e in zip(params, eps):
p.add_(e) # move to w + e_hat
base_opt.zero_grad()
loss_fn(model, batch).backward() # pass 2: gradient at w + e_hat
with torch.no_grad():
for p, e in zip(params, eps):
p.sub_(e) # back to w
base_opt.step() # base optimizer applies g_samThe function computes the loss twice on the same batch. For a ResNet-50 the second pass costs as much as the first, so wall-clock time per step roughly doubles, and memory grows by one parameter-sized buffer for (25.6 million floats, about 100 MB in fp32). The norm is taken over all parameters at once, one global length over every layer. The official JAX code makes four choices that a reimplementation should match:
- the L2 penalty is part of the loss in both passes, so weight decay contributes to the direction of and is evaluated at the perturbed weights in the second pass;
- batch-norm running statistics are taken from the first, unperturbed forward pass, and the second pass's statistics are discarded;
- perturbations are computed per device and not synchronized, so is the per-device batch;
- the averaged SAM gradient is clipped to global norm 5.0 before the optimizer step, and the momentum is Nesterov momentum.
With data-parallel training in PyTorch, the m-sharpness behavior depends on when gradients are averaged. Under DistributedDataParallel the first backward pass all-reduces gradients across devices by default, which gives one synchronized perturbation ( equal to the global batch). Skipping that synchronization for the first pass (for example with DDP's no_sync() context) restores the per-device perturbations the paper used.
Questions you might still have
Does SAM make training twice as slow?
Per step, yes: every update needs two forward and backward passes on the same batch, plus one extra parameter-sized buffer for the perturbation. The paper charged for this by letting every non-SAM baseline train for twice as many epochs and reporting the better of the two runs. On ImageNet, ResNet-152 with SAM at 200 epochs (18.5% top-1 error) costs the same number of gradient evaluations as standard training at 400 epochs (20.9%).
What value of rho should I start with?
The paper's default is 0.05, used for every ImageNet run and reported in Appendix C.3 as close to the tuned value elsewhere. Its grid was {0.01, 0.02, 0.05, 0.1, 0.2, 0.5}, chosen on 10% of the training set held out. The tuned values on CIFAR-100 were often larger (0.1 or 0.2), and 0.5 was too large in every noisy-label setting. rho is a Euclidean length over all weights at once, so its meaning changes if the parameter count or the weight scale changes a lot.
Is SAM the same as adding random noise to the weights?
No. The perturbation points along the gradient, the direction in which the loss rises fastest, and its length is fixed at rho. Appendix C.5 compares it with a random direction of the same length and the random version is worse; Andriushchenko and Flammarion (2022) found random perturbations give almost no gain over standard training.
Can SAM wrap Adam instead of SGD?
Yes. SAM only changes which gradient is handed to the optimizer: the gradient at w plus e-hat instead of the gradient at w. Any optimizer can apply it. The paper's from-scratch and ImageNet runs used SGD with momentum (Nesterov momentum in the official code), and the code also supports RMSProp for EfficientNet.
Does SAM really find flatter minima?
By the paper's measurement, yes: a WideResNet-40-10 trained on CIFAR-10 without batch norm ended with a largest Hessian eigenvalue of about 24 without SAM and 1.0 with it. Whether flatness is why test error drops is a separate question. Later work found that flatter by SAM's own measure does not always mean better generalization, and that the version of SAM the theory describes barely helps.
Why does the per-GPU batch size change the result?
Each device computes its own perturbation from its own slice of the batch, and the paper found smaller slices (smaller m) give lower test error. Running the same global batch on fewer devices makes m larger and can make SAM less effective. To get a small m on one device, split the batch into micro-batches and perturb each separately, at the cost of less parallel work per pass.
Is this the same SAM as Segment Anything?
No. The name collides. Sharpness-Aware Minimization is a 2020 training method for any network; Segment Anything (Meta, 2023), also called SAM, is a promptable image-segmentation model, covered in its own explainer on this site.
Footnotes & further reading
- The paper: Foret, Kleiner, Mobahi & Neyshabur, Sharpness-Aware Minimization for Efficiently Improving Generalization (ICLR 2021; arXiv v3, April 2021). Official JAX code: google-research/sam; the PyTorch implementation by David Samuel: davda54/sam.
- Flat minima: Hochreiter & Schmidhuber, Flat Minima (Neural Computation, 1997). Large batches and sharp minima: Keskar et al., On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima (ICLR 2017). The large-scale comparison of generalization measures: Jiang et al., Fantastic Generalization Measures and Where to Find Them (ICLR 2020).
- The reparameterization objection: Dinh, Pascanu, Bengio & Bengio, Sharp Minima Can Generalize For Deep Nets (ICML 2017). The scale-invariant variant: Kwon et al., ASAM: Adaptive Sharpness-Aware Minimization for Scale-Invariant Learning of Deep Neural Networks (ICML 2021).
- Andriushchenko & Flammarion, Towards Understanding Sharpness-Aware Minimization (ICML 2022), on why m-sharpness and worst-case perturbations matter and why the PAC-Bayes bound does not explain them.
- The fast gradient sign method, the input-space analogue of the perturbation: Goodfellow, Shlens & Szegedy, Explaining and Harnessing Adversarial Examples (ICLR 2015). Entropy-SGD: Chaudhari et al., Entropy-SGD: Biasing Gradient Descent Into Wide Valleys (2016).
- Danskin's theorem on differentiating a maximum: J. M. Danskin, The Theory of Max-Min and its Application to Weapons Allocation Problems (Springer, 1967); also Bertsekas, Nonlinear Programming, Appendix B. The models in the experiments are covered in the ResNet explainer and its relatives on this site.
How could this explainer be improved? Found an error, or something unclear? I read every message.