import torch
@torch.no_grad()
def coordinate_pattern_search(
objective,
initial_point,
initial_step=1.0,
shrink=0.5,
tolerance=1e-5,
max_sweeps=200,
):
"""Greedy coordinate search using function comparisons only."""
point = initial_point.clone()
value = float(objective(point))
step = initial_step
for _ in range(max_sweeps):
improved = False
for index in range(point.numel()):
for sign in (-1.0, 1.0):
candidate = point.clone()
candidate[index] += sign * step
candidate_value = float(objective(candidate))
if candidate_value < value:
point, value = candidate, candidate_value
improved = True
if not improved:
step *= shrink
if step < tolerance:
break
return point, value
target = torch.tensor([0.5, -1.0, 2.0])
solution, value = coordinate_pattern_search(
lambda x: (x - target).square().sum(),
initial_point=torch.tensor([4.0, 3.0, -2.0]),
)
torch.testing.assert_close(solution, target, atol=2e-5, rtol=0.0)Zeroth-, First-, and Second-Order Optimization
Optimization Setup
Training seeks parameters \(\theta\) that minimize an empirical objective:
\[ \min_\theta L(\theta) = \frac{1}{N}\sum_{i=1}^{N}\ell(f_\theta(x_i),y_i). \]
Most deep-learning optimizers use a stochastic gradient from a mini-batch:
\[ g_t=\nabla_\theta L_{\mathcal B_t}(\theta_t), \]
This is an estimate of the full-dataset gradient. A first-order optimizer converts that gradient and its accumulated state into a parameter update. Zeroth-order methods receive only evaluations of \(L(\theta)\). Some estimate a gradient-like direction; others compare candidate points, move a simplex, fit a surrogate, or evolve a population without constructing any gradient estimate.
Optimization quality depends on more than the optimizer name:
- learning rate and schedule
- batch size and gradient noise
- initialization and normalization
- gradient clipping
- regularization and weight decay
- numerical precision
The “order” of an optimizer refers to the highest derivative of the objective available to it:
| Order | Oracle information | Examples |
|---|---|---|
| Zeroth | function values \(L(\theta)\) | pattern search, Nelder–Mead, Powell, CMA-ES, Bayesian optimization, finite differences |
| First | gradients \(\nabla L(\theta)\) | SGD, AdamW, AdaGrad, linearized FTRL-Proximal |
| Second | Hessian or curvature information | Newton, quasi-Newton, Hessian-free methods |
Preconditioning and regularization are separate axes. A method can transform a first-order gradient using matrix geometry, and weight decay can be attached to an optimizer without changing its derivative order.
Derivative order is only one taxonomy. The learning protocol asks a different question:
| Protocol | Objective or evaluation | Meaning of the example index |
|---|---|---|
| Static empirical risk | minimize one fixed dataset average | examples are usually treated as exchangeable |
| Stochastic optimization | estimate the static objective from sampled mini-batches | sampled order is mainly an optimization device |
| Online learning | predict, reveal the next loss, then update | \(t\) is a causal decision round |
SGD and FTRL can both use first-order information while solving differently organized problems. This distinction becomes important below.
Zeroth-Order and Derivative-Free Optimization
A zeroth-order oracle returns function values but no derivatives. The broader term derivative-free optimization emphasizes algorithms designed to work without gradients. These algorithms are useful for black-box APIs, nondifferentiable simulators, physical experiments, hyperparameter tuning, mixed/discrete decisions, and objectives whose implementation cannot be differentiated.
Two families should be distinguished:
- Direct/model-based search: choose candidates from comparisons, geometric rules, populations, or a fitted response surface. No gradient is estimated.
- Zeroth-order gradient estimation: use function differences to construct a gradient-like vector, then apply an SGD-style update.
The first family is the traditional meaning of “optimization without derivatives.”
Family 1: direct and model-based search
| Method | State and move | Best fit | Main limitation |
|---|---|---|---|
| Grid/random search | evaluate independent candidate points | baselines, discrete spaces, embarrassingly parallel search | ignores information from earlier evaluations |
| Coordinate/pattern search | test a finite set of directions; accept improvements and shrink step size | low-dimensional local optimization, nonsmooth objectives | evaluations grow with dimension and coordinate alignment can be poor |
| Nelder–Mead | transform a simplex of \(d+1\) points by reflection, expansion, contraction, and shrinkage | small, deterministic continuous problems | weak scaling and limited convergence guarantees in general dimensions |
| Powell direction-set | repeated one-dimensional line searches; update the direction set | smooth low-dimensional continuous problems | line searches can be expensive and noise-sensitive |
| Simulated annealing | sometimes accept worse moves with a temperature-dependent probability | multimodal or combinatorial search | slow schedules and many evaluations |
| Evolution strategies / CMA-ES | sample a population and update its search distribution | nonconvex, rugged continuous objectives | population evaluations and covariance state are expensive |
| Bayesian optimization | fit a probabilistic surrogate and optimize an acquisition function | very expensive objectives with modest dimension | surrogate/acquisition overhead and poor high-dimensional scaling |
Coordinate and pattern search
At point \(x_t\) with step size \(\Delta_t\), a coordinate search evaluates
\[ x_t\pm\Delta_t e_i, \qquad i=1,\ldots,d. \]
It moves to an improving candidate. If none improves the objective, it shrinks \(\Delta_t\). More general pattern-search methods use a set of directions that positively spans the space. Their convergence arguments come from ensuring that failure to improve at progressively smaller scales implies a local stationarity condition—not from approximating a gradient.
Nelder–Mead and Powell
Nelder–Mead maintains a simplex rather than a direction estimate. It reflects the worst vertex through the centroid of the others, then may expand, contract, or shrink based only on function comparisons. Do not confuse this geometric simplex with the simplex algorithm for linear programming.
Powell’s method performs derivative-free one-dimensional minimizations along a set of directions and periodically replaces a direction using the net movement over a cycle. It can learn useful conjugate-like directions on smooth quadratic problems without evaluating derivatives.
Both are valuable classical local methods for modest dimension. Neither is a good default for optimizing billions of neural-network parameters.
Simulated annealing and evolutionary search
For a proposed move with objective change \(\Delta=L(x')-L(x)\), simulated annealing accepts improvements and may accept a worse move with probability
\[ P(\text{accept}) = \exp\left(-\frac{\Delta}{T}\right), \qquad \Delta>0. \]
High temperature \(T\) encourages exploration; cooling gradually makes the search greedy. The method targets global exploration rather than local gradient reconstruction.
CMA-ES samples a population from a Gaussian search distribution and adapts its mean, overall scale, and covariance from ranked candidates. It learns the shape of successful search directions statistically, but does not approximate the objective gradient by finite differences.
Bayesian optimization
When each evaluation takes minutes, hours, or a physical experiment, evaluation count matters more than optimizer arithmetic. Bayesian optimization fits a surrogate distribution over the objective and chooses the next point by an acquisition function:
\[ x_{t+1} = \arg\max_x a(x\mid\mathcal D_t), \]
where \(a\) may be expected improvement, probability of improvement, an upper confidence bound, or an information-gain criterion. It explicitly trades off promising predictions against uncertainty. Classical Gaussian-process BO is most natural in relatively low-dimensional continuous spaces.
Family 2: estimate a gradient from function values
This is only one branch of zeroth-order optimization, but it connects most directly to neural-network training. For \(d\) parameters, sample a random unit direction \(u\) and evaluate the loss on both sides of the current point:
\[ \widehat g(\theta;u) = \frac{d}{2\mu} \left[ L(\theta+\mu u)-L(\theta-\mu u) \right]u. \]
Although \(\widehat g\) looks like a gradient, it was constructed only from two function values. It estimates the gradient of a smoothed objective. The update can then reuse a familiar first-order rule:
\[ \theta_{t+1}=\theta_t-\eta\widehat g_t. \]
The smoothing radius \(\mu\) has a numerical tradeoff. A large value introduces bias because it averages over a wider neighborhood; a very small value makes the loss difference vulnerable to evaluation noise and floating-point error.
Why zeroth-order methods are expensive in high dimensions
One random direction contains little information about a \(d\)-dimensional gradient, so the estimator can have high variance that worsens with dimension. Using \(q\) directions requires \(2q\) loss evaluations per update. Backpropagation, by contrast, computes all parameter partial derivatives in roughly a small constant multiple of one forward-pass cost.
This is why zeroth-order optimization is usually a fallback for black-box or nondifferentiable problems rather than the default way to train a large neural network. Structure helps: coordinate sampling, antithetic evaluations, shared randomness, low-dimensional subspaces, and variance reduction can lower the query cost.
Minimal two-point implementation
This educational implementation optimizes one tensor without calling backward() or reading .grad:
import torch
@torch.no_grad()
def two_point_zo_step(
parameter,
loss_fn,
lr=0.05,
smoothing=1e-2,
num_directions=16,
):
estimate = torch.zeros_like(parameter)
dimension = parameter.numel()
for _ in range(num_directions):
direction = torch.randn_like(parameter)
direction.div_(direction.norm().clamp_min(1e-12))
parameter.add_(direction, alpha=smoothing)
loss_plus = float(loss_fn())
parameter.add_(direction, alpha=-2.0 * smoothing)
loss_minus = float(loss_fn())
# Restore the original point before accumulating the estimate.
parameter.add_(direction, alpha=smoothing)
estimate.add_(
direction,
alpha=dimension * (loss_plus - loss_minus) / (2.0 * smoothing),
)
estimate.div_(num_directions)
parameter.add_(estimate, alpha=-lr)
torch.manual_seed(0)
point = torch.tensor([3.0, -2.0, 1.0, 4.0])
target = torch.tensor([0.5, 0.5, 0.5, 0.5])
def black_box_loss():
return (point - target).square().sum()
initial_loss = black_box_loss().item()
for _ in range(120):
two_point_zo_step(point, black_box_loss)
assert black_box_loss() < 1e-3 * initial_loss
pointtensor([0.5000, 0.5000, 0.5000, 0.5000])
Local Stochastic First-Order Methods
These methods start from the current parameter, current stochastic gradient, and a compact optimizer state. They do not explicitly re-solve an objective over the entire observed prefix.
Stochastic Gradient Descent
Vanilla SGD updates
\[ \theta_{t+1}=\theta_t-\eta g_t, \]
where \(\eta\) is the learning rate.
Full-batch gradient descent uses the entire dataset per step. SGD historically means one example per step; in deep learning, “SGD” commonly means mini-batch SGD.
Why stochasticity can help
- mini-batches make each update cheaper
- gradient noise can help leave saddle points or narrow regions
- many updates can be made before one full pass through the data
But noisy gradients may oscillate, especially in directions of high curvature.
Momentum
Momentum maintains an exponential moving average of gradients:
\[ v_t=\beta v_{t-1}+g_t, \]
\[ \theta_{t+1}=\theta_t-\eta v_t. \]
Some texts instead define \(v_t=\beta v_{t-1}-\eta g_t\) and then add \(v_t\) to \(\theta\). Always inspect the convention before comparing equations.
Momentum:
- accelerates movement along consistently aligned gradients
- damps oscillation when gradients repeatedly change sign
- introduces one state scalar per parameter
Nesterov momentum
Nesterov accelerated gradient evaluates the gradient at an approximate look-ahead position:
\[ g_t=\nabla L(\theta_t-\eta\beta v_{t-1}). \]
The exact update form depends on the momentum convention and framework.
Online and Cumulative Optimization
Online optimization makes the prediction/update boundary part of the problem. The central object is not a shuffled approximation to one fixed batch objective, but the sequence of losses revealed after successive decisions.
FTRL: Online and Proximal First-Order Optimization
Start with native Follow the Leader
Online learning changes the order of events. At round \(t\):
- choose parameters \(w_t\) using only rounds \(1,\ldots,t-1\)
- make the current prediction
- observe the outcome and incur the revealed loss \(\ell_t(w_t)\)
- use \(\ell_t(\cdot)\) to choose \(w_{t+1}\)
Follow the Leader (FTL) chooses the parameter that would have performed best on all previous rounds:
\[ w_{t+1} = \arg\min_w \sum_{s=1}^{t}\ell_s(w). \]
This is the native idea: follow the leader of the cumulative actual losses. It does not begin with gradients, proximal terms, or a special “FTRL loss.” If a finite dataset is replayed, FTL resembles refitting empirical risk minimization after every new example.
For online logistic regression,
\[ p_t(w)=\sigma(w^Tx_t), \]
\[ \ell_t(w) = -y_t\log p_t(w) -(1-y_t)\log[1-p_t(w)]. \]
Native FTL would minimize the accumulated logistic losses after every example. That gives the clean conceptual starting point, but repeatedly solving a growing nonlinear problem can be expensive.
What FTRL preserves about the data axis
The important insight is that FTRL preserves the causal prefix structure of the data. The model \(w_t\) can depend only on losses revealed before round \(t\). Its natural evaluation is therefore regret:
\[ \operatorname{Regret}_T = \sum_{t=1}^{T}\ell_t(w_t) - \min_w\sum_{t=1}^{T}\ell_t(w). \]
The first term evaluates the decisions that were actually made through time. The second asks how well the best single fixed parameter would have performed in hindsight.
This differs from the usual static empirical-risk objective
\[ L(w)=\frac1N\sum_{i=1}^{N}\ell_i(w). \]
In ordinary shuffled training, the example index \(i\) is assumed to be exchangeable. SGD samples a mini-batch to estimate \(\nabla L(w)\) cheaply:
\[ g_t \approx \nabla L(w_t). \]
Random shuffling deliberately treats the observed ordering as a nuisance rather than as part of the statistical problem.
| Property | Shuffled SGD/Adam | Online FTRL |
|---|---|---|
| Information available at step \(t\) | sampled examples from a fixed dataset | only the revealed prefix \(1{:}t-1\) |
| Meaning of order | usually randomized to reduce sampling bias | causal prediction order |
| Main target | minimize static empirical risk | minimize cumulative online loss or regret |
| History state | current parameters and optimizer moments | cumulative loss/gradient statistics and regularizer |
| Standard assumption | data are often treated as IID or exchangeable | sequence need not be IID |
FTRL preserves when a decision must be made relative to the revealed data, not every historical example or its timestamp. Practical FTRL-Proximal compresses the prefix into statistics such as
\[ z_t, \qquad n_t=\sum_{s=1}^{t}g_s^2. \]
Within a fixed prefix, these accumulators do not reveal when each contribution arrived. Temporal meaning comes from the predict–reveal–update protocol and from evaluating every decision \(w_t\).
SGD and Adam are also path-dependent: changing mini-batch order changes the parameters encountered, and Adam’s exponential moments weight recent gradients more heavily. The difference is conceptual intent. Shuffled batch training tries to make order an irrelevant Monte Carlo detail; online learning makes the information boundary at each round explicit.
Finally, cumulative FTRL does not automatically forget old evidence. Under concept drift, one may need discounted losses, sliding windows, restarts, or time-decayed statistics. This connects online optimization to continual adaptation, but respecting causal order alone is not enough to track a changing environment.
A solvable native example
Suppose each round reveals a scalar target \(y_t\) and uses squared loss
\[ \ell_t(w)=\frac12(w-y_t)^2. \]
Plain FTL chooses
\[ w_{t+1} = \arg\min_w \frac12\sum_{s=1}^{t}(w-y_s)^2 = \frac1t\sum_{s=1}^{t}y_s. \]
The current leader is simply the empirical mean. Adding the quadratic regularizer \(R(w)=\lambda w^2/2\) gives native FTRL:
\[ w_{t+1} = \arg\min_w \left[ \frac12\sum_{s=1}^{t}(w-y_s)^2 +\frac{\lambda}{2}w^2 \right] = \frac{\sum_{s=1}^{t}y_s}{t+\lambda}. \]
This example contains no loss linearization. Regularization shrinks an uncertain early estimate toward zero; the data gradually dominates as \(t\) grows.
Why plain FTL can be unstable
FTL assumes the current cumulative winner is a safe next decision. If a small change in history changes the winner, it can jump sharply between parameters. An adversarial sequence can exploit those jumps and cause linear regret.
The first repair is Follow the Regularized Leader:
\[ w_{t+1} = \arg\min_w \left[ \sum_{s=1}^{t}\ell_s(w)+R_t(w) \right]. \]
For example, \(R_t(w)=\lVert w\rVert_2^2/(2\eta)\) makes extreme leaders costly. The regularizer is not the predictive loss: it controls stability, geometry, and possibly sparsity.
From actual losses to linearized losses
Even regularized FTL may require solving a nonlinear problem each round. For a differentiable convex loss, construct its tangent surrogate at the point that was actually played:
\[ \widetilde\ell_s(w) = \ell_s(w_s)+g_s^T(w-w_s), \qquad g_s=\nabla\ell_s(w_s). \]
Terms independent of candidate \(w\) disappear inside the argmin:
\[ w_{t+1} = \arg\min_w \left[ \left(\sum_{s=1}^{t}g_s\right)^Tw+R_t(w) \right]. \]
This is FTRL applied to linearized surrogate losses. The previous note started at this equation and therefore hid the native follow-the-leader idea.
| Method | Objective used to choose \(w_{t+1}\) | What changed? |
|---|---|---|
| FTL | \(\sum_{s\le t}\ell_s(w)\) | cumulative actual losses |
| Regularized FTL | \(\sum_{s\le t}\ell_s(w)+R_t(w)\) | stabilize the leader |
| Linearized FTRL | \(\sum_{s\le t}g_s^Tw+R_t(w)\) | replace each loss by its tangent surrogate |
| FTRL-Proximal | linearized losses plus proximal, L1, and L2 terms | efficient adaptive updates and exact sparsity |
With \(R_t(w)=\lVert w\rVert_2^2/(2\eta)\), the minimizer is
\[ w_{t+1} = -\eta\sum_{s=1}^{t}g_s. \]
For a constant learning rate and \(w_1=0\), this is exactly the sequence produced by online gradient descent:
\[ w_{t+1}=w_t-\eta g_t. \]
One form recomputes an argmin over cumulative gradients; the other writes the same change incrementally.
FTRL-Proximal
FTRL-Proximal combines gradient-descent-like behavior with effective L1 sparsity by centering quadratic penalties at parameters used on past rounds:
\[ w_{t+1} = \arg\min_w \left[ g_{1:t}^Tw +\frac{A_0}{2}\lVert w\rVert_2^2 +\frac12\sum_{s=1}^{t}\sigma_s\lVert w-w_s\rVert_2^2 +\lambda_1\lVert w\rVert_1 +\frac{\lambda_2}{2}\lVert w\rVert_2^2 \right], \]
where \(g_{1:t}=\sum_{s=1}^{t}g_s\). The nonnegative \(\sigma_s\) encode increases in the inverse learning rate. Expanding the quadratic terms for coordinate \(i\) gives, up to constants,
\[ z_{t,i}w_i +\frac12(A_{t,i}+\lambda_2)w_i^2 +\lambda_1|w_i|, \]
where
\[ A_{t,i}=A_{0,i}+\sum_{s=1}^{t}\sigma_{s,i}, \qquad z_{t,i} = g_{1:t,i}-\sum_{s=1}^{t}\sigma_{s,i}w_{s,i}. \]
This one-dimensional convex objective has the soft-thresholded solution
\[ w_{t+1,i} = \begin{cases} 0, & |z_{t,i}|\le\lambda_1,\\[4pt] -\dfrac{z_{t,i}-\operatorname{sign}(z_{t,i})\lambda_1} {A_{t,i}+\lambda_2}, & |z_{t,i}|>\lambda_1. \end{cases} \]
The zero is the exact minimizer whenever accumulated evidence \(|z_{t,i}|\) has not crossed the L1 threshold. This is why FTRL-Proximal creates exact sparsity while merely adding an L1 subgradient to SGD almost never lands exactly at zero.
Adaptive per-coordinate FTRL
Large-scale click-through-rate data is extremely sparse: each event touches only a tiny subset of a huge feature space. A common schedule accumulates
\[ n_{t,i}=\sum_{s=1}^{t}g_{s,i}^2 \]
and chooses
\[ \eta_{t,i} = \frac{\alpha}{\beta+\sqrt{n_{t,i}}}. \]
A frequently updated coordinate becomes conservative, while a rare coordinate retains a larger step. Setting
\[ A_{t,i}=\frac{1}{\eta_{t,i}} = \frac{\beta+\sqrt{n_{t,i}}}{\alpha} \]
amounts to choosing \(A_{0,i}=\beta/\alpha\) and the increments below. It yields the familiar implementation:
\[ w_{t+1,i} = \begin{cases} 0, & |z_{t,i}|\le\lambda_1,\\[4pt] -\dfrac{z_{t,i}-\operatorname{sign}(z_{t,i})\lambda_1} {(\beta+\sqrt{n_{t,i}})/\alpha+\lambda_2}, & |z_{t,i}|>\lambda_1. \end{cases} \]
After observing \(g_{t,i}\), update the two stored statistics:
\[ \sigma_{t,i} = \frac{\sqrt{n_{t-1,i}+g_{t,i}^2}-\sqrt{n_{t-1,i}}}{\alpha}, \]
\[ z_{t,i} = z_{t-1,i}+g_{t,i}-\sigma_{t,i}w_{t,i}, \qquad n_{t,i}=n_{t-1,i}+g_{t,i}^2. \]
Only active coordinates need to be touched. Here \(\lambda_1\) controls exact sparsity, \(\lambda_2\) supplies smooth shrinkage, and \(\alpha,\beta\) control the adaptive learning rate.
Native FTRL is an online decision template: minimize past revealed losses plus a regularizer. It is not inherently classified by a derivative oracle. The practical FTRL-Proximal algorithm derived here replaces each loss with a gradient-based linear surrogate, so that algorithm is first-order.
Adaptive Gradient Lineage: AdaGrad to AdamW
These methods are easiest to understand as a sequence of choices about how much gradient history to retain:
| Method | First-moment state | Second-moment state | Core change |
|---|---|---|---|
| SGD | none | none | use the current gradient |
| Momentum | EMA of \(g_t\) | none | smooth the update direction |
| AdaGrad | none | cumulative sum of \(g_t^2\) | shrink frequently active coordinates |
| RMSProp | none | EMA of \(g_t^2\) | forget stale squared gradients |
| Adam | EMA of \(g_t\) | EMA of \(g_t^2\) | combine momentum-like direction with RMSProp-like scaling |
| AdamW | EMA of \(g_t\) | EMA of \(g_t^2\) | Adam plus separately applied parameter decay |
Thus, Adam is approximately RMSProp plus momentum, with bias correction and specific normalization details. It is not literally obtained by composing two optimizer objects, but its two state variables play those two roles.
AdaGrad
AdaGrad accumulates squared gradients:
\[ s_t=s_{t-1}+g_t^2, \]
\[ \theta_{t+1} = \theta_t-\eta\frac{g_t}{\sqrt{s_t}+\epsilon}. \]
Parameters with frequent large gradients receive smaller effective learning rates. This can work well for sparse features, but \(s_t\) only grows, so the learning rate may decay too aggressively.
RMSProp
RMSProp replaces AdaGrad’s cumulative sum with an exponential moving average:
\[ s_t=\beta_2s_{t-1}+(1-\beta_2)g_t^2, \]
\[ \theta_{t+1} = \theta_t-\eta\frac{g_t}{\sqrt{s_t}+\epsilon}. \]
Old squared gradients decay, preventing the denominator from growing forever. This makes RMSProp more responsive when the gradient distribution changes.
Adam
Adam adds a momentum-like exponential first moment to the RMSProp-like exponential second moment:
\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t, \]
\[ v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2. \]
The lineage shorthand is:
\[ \underbrace{\widehat m_t}_{\text{momentum-like direction}} \quad\Big/\quad \underbrace{(\sqrt{\widehat v_t}+\epsilon)}_{\text{RMSProp-like scale}}. \]
It is only a shorthand. Momentum conventions may omit the factor \(1-\beta_1\); Adam bias-corrects both moving averages; and the numerator and denominator interact in one normalized update.
Because both moving averages start at zero, early estimates are biased toward zero. Adam corrects this:
\[ \widehat m_t=\frac{m_t}{1-\beta_1^t}, \qquad \widehat v_t=\frac{v_t}{1-\beta_2^t}. \]
The update is
\[ \theta_{t+1} = \theta_t - \eta \frac{\widehat m_t}{\sqrt{\widehat v_t}+\epsilon}. \]
Adam stores two state values per parameter, in addition to gradients and parameters. Optimizer state is therefore a major training-memory cost.
Why bias correction matters
If \(m_0=0\) and the expected gradient is constant \(\mu\), then
\[ \mathbb E[m_t]=(1-\beta_1^t)\mu. \]
Dividing by \(1-\beta_1^t\) recovers an unbiased first-moment estimate under this simplified assumption. The same argument applies to \(v_t\).
AdamW and Weight Decay
Coupled L2 regularization
First define the gradient of the data loss:
\[ g_t=\nabla_\theta L_{\text{data}}(\theta_t). \]
If an L2 penalty is explicitly added to that loss,
\[ L_{\text{total}}(\theta) = L_{\text{data}}(\theta) +\frac{\lambda}{2}\|\theta\|_2^2, \]
then automatic differentiation returns
\[ g_t^{\text{total}} = g_t+\lambda\theta_t. \]
Ordinary Adam treats this entire quantity as its gradient. The penalty therefore enters both moment accumulators:
\[ m_t = \beta_1m_{t-1} +(1-\beta_1)(g_t+\lambda\theta_t), \]
\[ v_t = \beta_2v_{t-1} +(1-\beta_2)(g_t+\lambda\theta_t)^2. \]
The \(\lambda\theta_t\) term is mixed with the data gradient, momentum, and coordinate-wise second-moment scaling. This is called coupled L2 regularization.
AdamW: decay outside the gradient path
In the defining AdamW update, the loss passed to automatic differentiation does not include the L2 weight penalty:
\[ g_t=\nabla_\theta L_{\text{data}}(\theta_t). \]
AdamW computes its moments from this data-loss gradient alone:
\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t, \]
\[ v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2. \]
It then applies uniform parameter shrinkage as a separate optimizer operation:
\[ \theta_{t+1} = (1-\eta\lambda)\theta_t - \eta \frac{\widehat m_t}{\sqrt{\widehat v_t}+\epsilon}. \]
“Decoupled” means that weight decay is excluded from the loss gradient, first moment, second moment, and adaptive denominator. It does not mean that AdamW has no regularizing effect.
For plain SGD, coupled L2 and weight decay are algebraically equivalent:
\[ \theta_{t+1} = \theta_t-\eta(g_t+\lambda\theta_t) = (1-\eta\lambda)\theta_t-\eta g_t. \]
For Adam they are not equivalent because \(g_t+\lambda\theta_t\) would pass through the adaptive moment machinery.
| Mechanism | Gradient seen by moments | Separate shrinkage |
|---|---|---|
| Adam + explicit L2 loss | \(g_t+\lambda\theta_t\) | no |
| AdamW weight decay | \(g_t\) | \((1-\eta\lambda)\theta_t\) |
The standard AdamW recipe computes the backward pass from the data loss and sets the weight-decay option on the optimizer. If the same parameters also receive an explicit \(\lambda\lVert\theta\rVert^2/2\) term in the loss, they get both coupled L2 regularization and decoupled weight decay.
Common practice excludes biases and normalization scale parameters from weight decay, though this remains a modeling choice rather than a mathematical law.
The shrinkage term \((1-\eta\lambda)\theta_t\) does not require a new gradient evaluation, but AdamW still uses \(\nabla L\) to optimize the data loss. Weight decay is a regularization/update mechanism, so it does not determine whether the underlying optimizer is zeroth-, first-, or second-order.
Matrix Geometry and Curvature-Aware Methods
The terminology is easy to blur:
- A zeroth-order method receives objective values but no derivatives.
- A first-order method uses gradients \(g=\nabla L(\theta)\).
- A classical second-order method uses the Hessian \(H=\nabla^2L(\theta)\) or an approximation to its curvature.
- A preconditioned method transforms the gradient with a matrix chosen to improve the optimization geometry.
Newton’s method uses
\[ \Delta\theta=-H^{-1}g. \]
The Hessian rescales directions according to local curvature, which can correct ill-conditioning. For a model with \(P\) parameters, however, a dense Hessian has \(P^2\) entries and solving the Newton system is generally impractical.
Modern methods therefore use structured approximations. Shampoo constructs preconditioners from gradient covariance matrices and is commonly grouped with second-order or second-order-inspired optimizers. Muon is also sometimes called second-order-inspired, but it does not estimate the loss Hessian: it orthogonalizes matrix momentum using the parameter’s matrix geometry.
Linearized FTRL-Proximal is first-order because it accumulates gradients. AdamW also remains first-order after decoupled weight decay. Neither classification is changed by the presence of a proximal regularizer or direct parameter shrinkage.
Shampoo
Shampoo preserves the tensor structure of a parameter instead of flattening every dimension into one vector. For a matrix parameter \(W\in\mathbb R^{m\times n}\) with gradient \(G_t\), it accumulates
\[ L_t=\epsilon I_m+\sum_{s=1}^{t}G_sG_s^T, \]
\[ R_t=\epsilon I_n+\sum_{s=1}^{t}G_s^TG_s. \]
The preconditioned direction is
\[ \widetilde G_t = L_t^{-1/4}G_tR_t^{-1/4}. \]
Why the exponent is \(-1/4\)
Vector AdaGrad applies the inverse square root of one second-moment matrix. A matrix parameter has a left and right preconditioner. Giving each side a \(-1/4\) power makes their combined action analogous to an inverse square root.
For an order-\(k\) tensor, Shampoo maintains one preconditioner per tensor axis; the corresponding exponent is \(-1/(2k)\).
Why Shampoo is more structured than Adam
Adam keeps an element-wise second moment:
\[ v_{ij}\approx\mathbb E[G_{ij}^2]. \]
Shampoo’s \(L\) and \(R\) retain correlations between rows and between columns. This can produce a better-conditioned update, but matrix inverse roots cost more than element-wise division.
Minimal matrix Shampoo direction
import torch
def symmetric_matrix_power(matrix, power, eps=1e-12):
"""Apply a scalar power to a symmetric positive-definite matrix."""
eigenvalues, eigenvectors = torch.linalg.eigh(matrix.float())
powered = eigenvalues.clamp_min(eps).pow(power)
return (eigenvectors * powered.unsqueeze(0)) @ eigenvectors.T
def shampoo_direction(gradient, left_state, right_state, eps=1e-4):
"""One educational Shampoo update for a 2D parameter gradient."""
rows, columns = gradient.shape
g = gradient.float()
left_state.add_(g @ g.T)
right_state.add_(g.T @ g)
left = left_state + eps * torch.eye(rows, device=g.device)
right = right_state + eps * torch.eye(columns, device=g.device)
left_root = symmetric_matrix_power(left, -0.25)
right_root = symmetric_matrix_power(right, -0.25)
return left_root @ g @ right_root
gradient = torch.randn(8, 4)
left_state = torch.zeros(8, 8)
right_state = torch.zeros(4, 4)
direction = shampoo_direction(gradient, left_state, right_state)
assert direction.shape == gradient.shape
assert torch.isfinite(direction).all()Production Shampoo implementations typically add momentum, weight decay, blocking for large dimensions, distributed state, infrequent inverse-root updates, and grafting. Grafting borrows the update magnitude from a simpler optimizer such as SGD or AdaGrad while using Shampoo’s matrix direction.
Shampoo costs
For an \(m\times n\) parameter, Shampoo stores \(m^2+n^2\) preconditioner scalars, not \(m^2n^2\). This is far smaller than a full preconditioner over all \(mn\) parameters, but can still be expensive for very wide matrices. Matrix inverse roots are also substantially more expensive than Adam’s element-wise update.
Muon
Muon stands for MomentUm Orthogonalized by Newton–Schulz. For a 2D weight matrix, first form momentum
\[ M_t=\beta M_{t-1}+(1-\beta)G_t, \]
then replace its singular values by approximately one:
\[ M_t=U\Sigma V^T \quad\Longrightarrow\quad \operatorname{orth}(M_t)=UV^T. \]
Equivalently, for the appropriate full-rank case,
\[ \operatorname{orth}(M) = M(M^TM)^{-1/2}. \]
Muon then steps in this orthogonalized direction, with implementation-specific scaling and weight decay:
\[ W_{t+1}=W_t-\eta\,s(W_t)\operatorname{orth}(M_t). \]
The polar factor prevents a few large singular directions in the raw momentum matrix from dominating the update. It can also be interpreted as a steepest- descent direction under a matrix spectral-norm geometry.
Muon versus full-matrix AdaGrad
For a parameter with \(p\) scalar entries, full-matrix AdaGrad flattens its gradient into \(g_t\in\mathbb R^p\) and accumulates
\[ H_t = \epsilon I_p+\sum_{s=1}^{t}g_sg_s^T. \]
It then preconditions the current gradient:
\[ \widetilde g_t=H_t^{-1/2}g_t. \]
The inverse root uses a historical uncentered gradient second moment to reduce directions that have repeatedly carried large gradients and to rotate correlated coordinates. Its prohibitive cost is a dense \(p\times p\) state. For an \(m\times n\) matrix parameter, \(p=mn\), so this state contains \(m^2n^2\) entries.
Muon performs a superficially similar inverse-square-root operation,
\[ \operatorname{orth}(M_t) = M_t(M_t^TM_t)^{-1/2}, \]
but \(M_t\) is only the current momentum matrix. The Gram matrix \(M_t^TM_t\) is formed from that momentum’s matrix axes; it is not the cumulative outer product of vectorized gradients. Muon normalizes the singular values of the update direction instead of estimating a historical covariance preconditioner.
| Property | Full-matrix AdaGrad | Muon |
|---|---|---|
| Historical statistic | cumulative gradient outer products | EMA-like first-moment matrix |
| Matrix being inverse-rooted | \(p\times p\) second moment over vectorized coordinates | row- or column-space Gram matrix of current momentum |
| Result | rotate and scale by historical gradient geometry | approximately set nonzero momentum singular values to one |
| Persistent state | \(O(p^2)\) | \(O(p)\) momentum |
| Main interpretation | adaptive covariance preconditioning | spectral-norm steepest-descent geometry |
Shampoo is the closer scalable relative of full-matrix AdaGrad: it approximates the enormous vectorized second moment through per-axis matrix statistics. Muon instead replaces second-moment tracking with a cheaper geometric transformation of momentum.
Newton–Schulz orthogonalization
Computing an SVD for every matrix at every step is expensive. Muon instead uses a small number of matrix-multiplication iterations. A simple Newton–Schulz polar iteration is
\[ X_{k+1} = \frac{3}{2}X_k - \frac{1}{2}X_kX_k^TX_k, \]
after scaling \(X_0\) so its singular values lie in the convergence region. Each singular value approximately follows
\[ \sigma_{k+1} = \frac{3}{2}\sigma_k-\frac{1}{2}\sigma_k^3, \]
which drives nonzero singular values toward one.
def newton_schulz_orthogonalize(matrix, num_steps=10, eps=1e-7):
"""Educational polar-factor approximation for a 2D matrix."""
x = matrix.float()
x = x / (x.norm() + eps)
for _ in range(num_steps):
x = 1.5 * x - 0.5 * (x @ x.T) @ x
return x.to(matrix.dtype)
momentum = torch.randn(8, 4)
orthogonal_momentum = newton_schulz_orthogonalize(momentum)
# For a tall full-rank matrix, columns of the polar factor are orthonormal.
gram = orthogonal_momentum.T @ orthogonal_momentum
torch.testing.assert_close(gram, torch.eye(4), atol=2e-3, rtol=2e-3)The code shows the mathematical idea, not a production Muon kernel. Practical implementations often use tuned higher-order Newton–Schulz polynomials, lower- precision matrix multiplies, Nesterov-style momentum, explicit update scaling, and distributed communication strategies.
Which parameters use Muon?
Muon is designed for matrix-structured hidden weights such as attention and MLP projections. A common recipe uses AdamW for:
- embedding tables
- the output language-model head
- biases and scalar parameters
- normalization scales
- other parameters that are not suitable 2D hidden-weight matrices
Thus “training with Muon” commonly means a hybrid Muon + AdamW optimizer setup.
As a production example, Cursor reports using distributed Muon during Composer 2.5 continued pretraining, orthogonalizing attention projections per head and stacked MoE weights per expert. This is an optimizer/system choice inside the pretraining phase; the subsequent online policy objective remains conceptually separate. See Cursor’s Continual Training Loop.
Is Muon a second-order optimizer?
There are two conventions:
- In a broad geometry-aware sense, Muon is often described as second-order or Shampoo-like because it applies a matrix inverse-square-root-style transform.
- In the classical optimization sense, it is not Hessian-based: the Newton–Schulz name refers to the numerical method used to compute a polar factor, not Newton’s method on the loss.
For interviews, state which definition you are using rather than simply calling Muon “Newton’s method.”
Shampoo versus Muon
| Property | Shampoo | Muon |
|---|---|---|
| Input state | gradient second moments | momentum matrix |
| Matrix operation | left/right inverse roots | polar-factor orthogonalization |
| Tracks row/column covariance over time | yes | no explicit covariance matrices |
| State for an \(m\times n\) matrix | typically \(m^2+n^2\) before blocking | typically one \(mn\) momentum buffer |
| Typical expensive operation | eigendecomposition or inverse root | repeated matrix multiplications |
| Parameter coverage | general tensors, with practical restrictions | mainly 2D hidden weights |
| Hessian estimate | no explicit Hessian | no |
Optimizer Comparison
Derivative-free methods are better compared by objective evaluations and search state than by optimizer-state bytes per parameter:
| Optimizer | Search state / evaluations | Main idea | Common weakness |
|---|---|---|---|
| Coordinate/pattern search | point, step size; up to \(2d\) tests per sweep | accept improving directions | query cost grows with dimension |
| Nelder–Mead | \(d+1\) vertices | geometrically transform a simplex | poor scaling in high dimension |
| CMA-ES | population, mean, scale, covariance | evolve a ranked search distribution | many evaluations and potentially \(O(d^2)\) covariance state |
| Bayesian optimization | evaluation history and surrogate | optimize an exploration–exploitation acquisition rule | surrogate methods struggle in high dimension |
| Two-point ZO | two evaluations per sampled direction | estimate a direction from loss differences | high variance in high dimension |
Local stochastic methods
| Optimizer | State per parameter | How history is summarized | Common weakness |
|---|---|---|---|
| SGD | 0 | only the current mini-batch gradient | sensitive to conditioning and learning rate |
| SGD + momentum | 1 | EMA of gradient direction | still uses one global learning-rate scale |
| AdaGrad | 1 | cumulative squared gradients | effective rate can vanish |
| RMSProp | 1 | EMA of squared gradients | no first-moment estimate in basic form |
| Adam | 2 | EMAs of gradients and squared gradients | coupled L2 is not uniform weight decay |
| AdamW | 2 | Adam moments plus decoupled shrinkage | high optimizer-state memory |
Online cumulative methods
| Optimizer | State per parameter | How history is summarized | Common weakness |
|---|---|---|---|
| FTRL-Proximal | typically 2 for sparse coordinates | cumulative prefix statistics plus proximal regularization | old evidence is not forgotten automatically |
Matrix-geometry methods
| Optimizer | State | How history is summarized | Common weakness |
|---|---|---|---|
| Shampoo | structured matrices | cumulative row/column gradient covariances | inverse roots and matrix state are expensive |
| Muon | one buffer for selected matrices | EMA-like momentum followed by orthogonalization | special parameter routing and matrix multiplies |
Persistent memory alone does not identify the learning protocol. AdaGrad and FTRL both accumulate squared gradients, while Adam explicitly emphasizes recent gradients, but only online FTRL makes the predict–reveal boundary part of its objective and regret analysis.
Minimal AdamW Implementation
The implementation below is educational and omits parameter groups, sparse gradients, fused kernels, capturable state, and mixed-precision concerns.
import math
import torch
class MinimalAdamW:
def __init__(
self,
parameters,
lr=1e-3,
betas=(0.9, 0.999),
eps=1e-8,
weight_decay=0.0,
):
self.parameters = list(parameters)
self.lr = lr
self.beta1, self.beta2 = betas
self.eps = eps
self.weight_decay = weight_decay
self.step_count = 0
self.first_moments = [torch.zeros_like(p) for p in self.parameters]
self.second_moments = [torch.zeros_like(p) for p in self.parameters]
@torch.no_grad()
def step(self):
self.step_count += 1
correction1 = 1.0 - self.beta1 ** self.step_count
correction2 = 1.0 - self.beta2 ** self.step_count
for parameter, first, second in zip(
self.parameters, self.first_moments, self.second_moments
):
if parameter.grad is None:
continue
# This gradient came from the caller's data loss. AdamW does not
# add weight_decay * parameter to it.
gradient = parameter.grad
# Shrink the parameter outside the first/second-moment updates.
parameter.mul_(1.0 - self.lr * self.weight_decay)
first.mul_(self.beta1).add_(gradient, alpha=1.0 - self.beta1)
second.mul_(self.beta2).addcmul_(
gradient, gradient, value=1.0 - self.beta2
)
first_hat = first / correction1
second_hat = second / correction2
parameter.addcdiv_(
first_hat,
second_hat.sqrt().add_(self.eps),
value=-self.lr,
)
def zero_grad(self):
for parameter in self.parameters:
parameter.grad = Noneparameter = torch.nn.Parameter(torch.tensor([3.0, -4.0]))
target = torch.tensor([1.0, -1.0])
optimizer = MinimalAdamW([parameter], lr=0.1, weight_decay=0.01)
initial_error = (parameter.detach() - target).norm()
for _ in range(100):
data_loss = (parameter - target).square().sum()
data_loss.backward() # No explicit L2 penalty is added to this loss.
optimizer.step()
optimizer.zero_grad()
assert (parameter - target).norm() < 0.02 * initial_error
parameterParameter containing:
tensor([ 0.9875, -1.0084], requires_grad=True)
Learning-Rate Schedules
The learning-rate schedule can matter as much as the optimizer.
Warmup
Early gradients and optimizer moments can be poorly calibrated. Linear warmup increases the learning rate from zero to a peak over \(T_w\) steps:
\[ \eta_t=\eta_{\max}\frac{t}{T_w}, \qquad t\le T_w. \]
Cosine decay
After warmup, cosine decay commonly uses
\[ \eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max}-\eta_{\min}) \left[ 1+\cos\left(\pi\frac{t-T_w}{T-T_w}\right) \right]. \]
Other choices include constant-with-warmup, linear decay, inverse-square-root decay, one-cycle schedules, and loss- or validation-triggered schedules.
Gradient Clipping
Global-norm clipping rescales all gradients together when their norm exceeds \(c\):
\[ g \leftarrow g\min\left(1,\frac{c}{\|g\|_2+\epsilon}\right). \]
This preserves the joint gradient direction while bounding its magnitude. Element-wise value clipping changes the direction and is a different operation.
Clipping can contain rare gradient spikes, but persistent clipping may indicate an excessive learning rate or a deeper stability problem.
Large-Scale Training Considerations
- Mixed precision: optimizer moments are often maintained in higher precision than forward weights or activations.
- Loss scaling: prevents small FP16 gradients from underflowing before the optimizer sees them.
- Gradient accumulation: simulates a larger batch but changes the number of optimizer steps per token unless the schedule is adjusted.
- State sharding: ZeRO/FSDP-style methods distribute parameters, gradients, and optimizer states across devices.
- Fused optimizers: combine many small element-wise operations to reduce kernel launches and memory traffic.
- Adafactor and low-rank state methods: reduce second-moment memory by factorizing or approximating optimizer state.
Interview Questions
- Why can mini-batch gradients be useful despite being noisy?
- What information does a zeroth-order oracle expose?
- Contrast direct search with zeroth-order gradient estimation. Which classical methods never construct a gradient-like vector?
- When would you choose Nelder–Mead, CMA-ES, or Bayesian optimization?
- Why is Bayesian optimization evaluation-efficient but usually difficult to scale to a neural network’s parameter dimension?
- Why does derivative-free query cost tend to worsen with dimension?
- How do the smoothing radius and number of sampled directions affect a two-point gradient estimator?
- Contrast FTL over actual losses with FTRL over linearized losses.
- Derive the regularized running-mean solution for squared-loss FTRL.
- In what sense does FTRL preserve the causal data prefix, and in what sense does it compress or discard the time axis?
- If SGD and Adam are path-dependent, why do we still say shuffled training treats example order as a nuisance?
- Why does cumulative FTRL need modification under concept drift?
- Why is FTRL-Proximal first-order even though its update is written as a regularized argmin?
- Why is weight decay orthogonal to the derivative-order taxonomy?
- How does momentum reduce oscillation?
- Why does AdaGrad’s effective learning rate continually shrink?
- In what precise sense is Adam “RMSProp plus momentum,” and what details does that shorthand omit?
- Derive Adam’s bias-correction terms.
- Why are L2 regularization and weight decay different for Adam?
- How much optimizer-state memory does Adam require?
- Why do large Transformer runs use learning-rate warmup?
- Compare global-norm clipping with element-wise clipping.
- How does gradient accumulation affect optimization and scheduling?
- Why might SGD generalize differently from AdamW?
- How does Shampoo preserve matrix or tensor structure that Adam discards?
- Why does matrix Shampoo use \(-1/4\) powers on both sides?
- What does Muon’s Newton–Schulz iteration compute, and why is it not Newton’s method on the training loss?
- Why is Muon’s \(M(M^TM)^{-1/2}\) not a full-matrix AdaGrad preconditioner?
- Why is Muon commonly paired with AdamW for the remaining parameters?
- Compare the optimizer-state and computation costs of AdamW, Shampoo, and Muon.
Exercises
Primary References
- A Simplex Method for Function Minimization
- An Efficient Method for Finding the Minimum of a Function of Several Variables Without Calculating Derivatives
- The CMA Evolution Strategy: A Tutorial
- A Tutorial on Bayesian Optimization
- Random Gradient-Free Minimization of Convex Functions
- Ad Click Prediction: A View from the Trenches
- Adaptive Subgradient Methods for Online Learning and Stochastic Optimization
- Adam: A Method for Stochastic Optimization
- Decoupled Weight Decay Regularization
- Shampoo: Preconditioned Stochastic Tensor Optimization
- Muon Is Scalable for LLM Training
- Practical Efficiency of Muon for Pretraining