Zeroth-order and derivative-free optimization
Optimize functions available only through evaluations, from simulators to models without gradient access, using gradient estimators, evolutionary strategies, CMA-ES and direct search.
After this lesson you can
- Derive the two-point Gaussian-smoothing gradient estimator and analyze its bias and variance as dimension changes.
- Implement evolutionary strategies with antithetic sampling and rank normalization.
- Explain covariance and step-size adaptation in CMA-ES and implement a simplified version.
- Implement Nelder-Mead and recognize its known failures.
- Choose between zeroth-order methods, finite differences and Bayesian optimization based on dimension, noise and evaluation cost.
Before you start
- 06Stochastic gradient descentSGD convergence for convex problemsMinibatch gradient variance and gradient noise scaleConvergence orders and ratesL-smoothness
- 04Multivariate Gaussian distributionCovariance matrixGaussian sampling via Cholesky
- 09Finite differencesOptimal finite-difference step
- 00Complete seeding of a training run
Motivation: optimizing what you can only evaluate
Until now the entire module has assumed that, in addition to , you can request . With automatic differentiation that is almost free: reverse mode returns the entire gradient for a small multiple of the cost of evaluating , whatever the dimension. But real problems exist where that question has no answer:
- Simulators. A physics, traffic or market simulator is a program of thousands of lines, often with discrete steps (collisions, thresholds, queues), sometimes written in another language or purchased as a binary. You can run it; you cannot differentiate it.
- Backtests. The performance of a trading strategy as a function of its parameters (windows, thresholds, position sizes) goes through buy-or-not decisions: it is piecewise constant, with jumps. Its gradient is zero almost everywhere and tells you nothing.
- Hyperparameters. Validation accuracy as a function of learning rate, weight decay or network width is a function of a few numbers that costs a whole training run to evaluate.
- Episode rewards. In reinforcement learning, a policy’s total return depends on a non-differentiable environment. Evolutionary strategies optimize that return directly, without the policy gradient theorem.
- Models accessible only through forward passes. A model behind an API, a quantized model or an LLM so large that backpropagation does not fit in memory: you can only make forward passes.
In all these cases access to the function is a zeroth-order oracle: give it and it returns , sometimes with noise, and nothing more. Algorithm cost is measured in number of evaluations, because each evaluation may cost a millisecond (a small-network forward pass) or ten minutes (a backtest), and that difference determines which method to use.
This lesson covers three families that work in practice. First, estimate the gradient from value differences, using finite differences or random directions, and understand why the price is a dimension factor. Second, evolutionary strategies and their more refined version CMA-ES, which estimate a gradient not of but of a search distribution that learns the problem geometry. Third, direct search (Nelder-Mead and pattern search), which only compares values in a geometric template. Finally you will see how the first idea scales to fine-tuning LLMs with inference memory (MeZO), and when it is better to abandon these methods for Bayesian optimization.
Finite differences and random directions
The most direct way to recover a gradient is to approximate each partial derivative by a difference quotient. With forward finite differences,
If is -smooth, each component has truncation error at most , and if each evaluation has error of size (roundoff or noise), a term is added. The optimal step balances the two, , leaving per-component error on the order of . Centered differences, , reduce truncation to at the cost of twice as many evaluations.
The problem is not accuracy, but cost: a forward-difference gradient requires evaluations. For a model with parameters that is forward passes per descent step, compared with a few using backpropagation. When the gradient exists and automatic differentiation is available, zeroth-order methods are simply the wrong tool.
One random direction instead of coordinates
Finite differences reconstruct by probing the basis directions. The alternative is to probe one random direction and retain the directional derivative along it:
It costs two evaluations, whatever . Why does it point somewhere useful? Because , the covariance matrix of a standard Gaussian, and therefore : in the limit the estimator is unbiased. A single sample points almost anywhere, but its mean points exactly along the gradient, like a stochastic gradient.
There is a second, less obvious and very useful property: . Each estimate, however poor, makes an angle of at most with the gradient, so is never an ascent direction. What costs us is variance, and here is the central theorem of the lesson.
Proof
We have already seen the expectation. For the second moment, . Fourth-order moments of a standard Gaussian are given by Isserlis’ formula, . With and summing over ,
so . Then . For the mean of independent copies, the component variances are divided by , as is the trace of the covariance.
∎The relative squared error of one estimate is : in dimension , noise is roughly times larger than signal. To reduce it to a fixed level one must average directions, spending on the order of evaluations, just as with finite differences. Another way to see it is the angle: the cosine between and is , and its expectation is . In , a random direction is on average from the gradient.
For a quadratic , the centered difference is exact for any : , because the second-order terms cancel. The theorem then describes the antithetic estimator exactly, not just its limit.
Gaussian smoothing: which gradient is actually estimated
With finite , no longer estimates but the gradient of another function. That function is key to understanding what these methods do and why they work on rough or non-differentiable functions.
is the convolution of with a bell of width : it averages in a fuzzy ball of radius . It erases details on scales smaller than (noise, roughness, jumps) and preserves the shape on larger scales. The estimator does not differentiate : it samples around , sees which side is higher and averages directions weighted by that difference.
For this function everything can be calculated by hand, because (the characteristic function of the Gaussian) and :
The quadratic part only shifts by a constant and roughness is attenuated by . With , at , of the roughness survives, and at , . Details with wavelength below die exponentially; those on a much larger scale barely change.
The proof writes as an integral against the Gaussian density and differentiates the density, not ; you will do it step by step in the exercises. If is also differentiable, Stein’s lemma, , applied to gives another interpretation: , the average gradient in the fuzzy ball. Subtracting , or using the antithetic pair, does not change the expectation (because and and have the same law), but does change the variance: it removes the term from the estimator, which can be enormous if takes large values far from zero. This has the same role as the baseline in policy gradients.
Bias and variance
How far is from ? If is -smooth, the descent lemma gives . Taking expectations, the linear term disappears and :
If is also convex, by Jensen’s inequality and inherits convexity. Nesterov and Spokoiny (2017) complete the picture for convex or nonconvex with -Lipschitz gradient:
Both bounds say the same as the variance theorem, now with finite : the second moment is on the order of times the squared gradient, plus a curvature term that grows with . Bias also grows with and dimension, because the fuzzy ball has typical radius , not .
Choosing
With exact evaluations, should be small: bias vanishes and variance remains at the minimum . But evaluations are never exact. If is observed with noise of standard deviation , each quotient carries error of size , which explodes when . This is the same trade-off as the optimal finite-difference step: in the antithetic quotient truncation error is (even Taylor terms cancel) and noise error is , so the optimum is ; in the forward quotient truncation is and the optimum is . The part of the forward quotient, , has zero mean once multiplied by (it is odd in ): it does not bias the estimate of , but makes it noisier. There is a third reason for a large , seen in the figure: if is rough at small scales, determines the scale at which you look, and too small an pursues uninteresting local minima.
The factor: rates and effective rank
Use the estimator as if it were a gradient: . How much is lost relative to gradient descent? The following result quantifies this in one line and also shows what the loss factor actually depends on.
Proof
By Taylor’s theorem with integral remainder and , for all . With and , the linear term is , with expectation . The quadratic term is , and by Isserlis
Substitution gives the bound; the quadratic in is minimized at the indicated .
∎Compare with gradient descent using step , which decreases by at least per step. Their ratio is
where is the effective rank of curvature. In the worst case, , and one zeroth-order step is worth gradient steps; since it costs two evaluations, matching one gradient step costs about evaluations, roughly twice the of finite differences. But if curvature is concentrated in few directions, , the factor no longer depends on dimension. This observation, with measured locally, is Malladi et al. (2023) explanation for why zeroth-order fine-tuning of an LLM with billions of parameters works: near a pretrained model, the loss barely curves except in a few directions.
Iterating the inequality with the usual convergence-rate arguments, Nesterov and Spokoiny obtain for the forward-estimator method and small the same rates as gradient methods with a dimension factor in front (up to constants):
| Class of | With gradient | Zeroth order, two evaluations per step |
|---|---|---|
| convex, -smooth | ||
| -strongly convex, -smooth | ||
| nonconvex, -smooth () | ||
| convex, nonsmooth -Lipschitz |
Here , and . The first row is the gradient descent rate for smooth convex functions multiplied by . The factor is not a defect of the analysis: Duchi, Jordan, Wainwright and Wibisono (2015) proved that, in stochastic convex optimization with two evaluations per query, losing a factor in the rate (that is, in the number of evaluations) compared with the SGD rate is unavoidable.
Evolution strategies
Change perspective. Instead of a point and an estimate of its gradient, think of a search distribution over and average objective . Minimizing pushes the distribution toward regions where is low, and its gradient is obtained with the score function trick, without differentiating :
ES with weights is literally descent with the antithetic estimator of the previous section. Three engineering ingredients make it robust, each for a precise reason.
Antithetic sampling. Evaluating and with the same cancels all even terms in the Taylor expansion of around : the value (a free baseline) and curvature . Without it, that curvature term enters the variance even though its mean is zero.
Rank normalization. Replace the values of with their ranks, rescaled to (the smallest value receives and the largest ). The estimator no longer depends on the scale of : it behaves exactly the same with , or , because strictly increasing transformations do not change the order. An outlier (an episode with an absurd reward, a backtest with a data error) weighs the same as any other extreme. The price is that no longer estimates but the gradient of a quantile-transformed version of ; it remains a descent direction for the probability of improvement, but its magnitude no longer decreases near the minimum, and with fixed the method keeps oscillating in a ball of radius proportional to .
Parallelism with shared seeds. Each worker generates its from a seed known to all (the seeding strategy applied to a cluster) and communicates only a scalar, the value of . Everyone reconstructs the others’ perturbations and applies the same update. With this scheme, Salimans et al. solved 3D MuJoCo humanoid locomotion in about 10 minutes with about 1440 CPU cores, competitively with policy gradients: ES does not need backpropagation through time, ignores action frequency and does not suffer from very delayed rewards.
If instead of fixed you also let the distribution adapt its shape and follow the natural gradient in distribution space (the gradient preconditioned by Fisher information, covered as the natural gradient), you obtain natural evolution strategies (NES). CMA-ES, designed earlier and by another route, turns out to be very similar to this idea.
CMA-ES: learning geometry through comparisons
Isotropic ES has the same flaw as unpreconditioned gradient descent: in a narrow oblique valley, the that does not cross the walls is too small to advance along the valley. The first- and second-order remedy was a preconditioner (Newton, BFGS); in zeroth order it is to let the search distribution be a general Gaussian and learn .
The coefficients are not tuned: Hansen (2016) gives defaults depending only on and , such as , , , , and (with large ), and . They result from decades of experiments and invariance arguments, and changing them almost never helps. Each of the three mechanisms has a direct interpretation.
- Rank : covariance of successful steps. is the empirical covariance (centered at the old mean) of selected samples. If good samples appear far away in a direction, grows in that direction; if only nearby samples survive, it shrinks. On a convex quadratic, eventually becomes proportional to : CMA-ES learns a Newton preconditioner without evaluating a single derivative. No general theorem guarantees it, but it is systematically observed and you will see it in the figure.
- Rank one: path memory. accumulates mean steps with exponential forgetting. Since , the rank- update loses the signs of steps; the path preserves them: if several consecutive steps go in the same direction, grows in it and term stretches along the valley well before empirical covariance would.
- Cumulative step-size adaptation (CSA). is the same path, but measured in coordinates where the distribution is a sphere (). If selection were random, would be distributed as and its norm would average . If it is longer, steps reinforce one another: fewer larger steps could have reached the same point, and grows. If shorter, steps cancel, oscillation occurs, and decreases.
The plot below has two phases. While does not resemble , falls slowly and rises toward . Once the shape is learned, and fall in a straight line on a logarithmic scale, with the slope isotropic ES would have on a sphere: adaptation has turned an ill-conditioned problem into a well-conditioned one. With “Step only”, the same quadratic takes on average about twice as many generations; the difference grows with condition number and dimension, and in with condition number it exceeds an order of magnitude, as you will measure in the lab.
Three properties explain why CMA-ES is the reference method for moderate-dimensional black-box problems (from a few to a few hundred variables):
- Invariance to monotonic transformations of . It uses only sample order, like rank-based ES.
- Invariance to affine changes of search space. If , CMA-ES on with transformed initial mean and covariance generates exactly the same transformed samples. Condition number stops mattering once is learned.
- Few parameters. Only and need choosing (approximately one quarter of the reasonable variable range). For multimodal functions, the restart variant that doubles (IPOP-CMA-ES) explores at an increasingly coarse scale.
Its limitations are also clear. Sampling costs per sample and decomposing costs (done every certain number of generations), and learning a full requires on the order of evaluations. Above a few thousand variables, diagonal or limited-memory variants, or isotropic ES itself, are used.
Direct search
The third family estimates nothing: it compares values of on a geometric template of points and moves, stretches or shrinks it according to the outcome.
Nelder-Mead
Nelder and Mead (1965) maintain a simplex of ordered vertices, , and seek to replace the worst. With the centroid of the others, , they try points on the line joining the worst vertex to , :
- Reflection, . If , accept it.
- Expansion, , if reflection improved on the best (): accept the better of and .
- Outside contraction, , if ; inside contraction, , if . Accept if it improves on the point being compared.
- Shrink: if contraction fails, move all vertices halfway toward the best.
The simplex stretches in directions where decreases and shrinks when it finds nothing. In two or three dimensions and with smooth functions it works surprisingly well, needs no parameters and is the default method of fminsearch in MATLAB and one of those in scipy.optimize.minimize. Its theory, by contrast, is almost nonexistent. Lagarias, Reeds, Wright and Wright (1998) proved convergence to the minimizer for strictly convex functions in dimension 1; in dimension 2, only that values at the three vertices converge to the same number. That same year McKinnon constructed the counterexample showing that one cannot demand more.
The failure has two structural causes. Nelder-Mead accepts any improvement, however small, without a sufficient decrease condition relating it to step size; and it does not control simplex geometry, which may degenerate almost into a line and stop exploring an entire direction of space. In McKinnon, the simplex flattens in a nearly horizontal direction while falls vertically. In high dimension the problem worsens: with standard coefficients reflections become increasingly ineffective, and in the lab you will see Nelder-Mead stall on a well-conditioned 32-dimensional quadratic. Gao and Han’s (2012) adaptive variant, with coefficients depending on (adaptive=True in SciPy), greatly alleviates this effect, but does not change the lack of guarantees.
Pattern search and its guarantee
Pattern search (Hooke and Jeeves, 1961; analyzed by Torczon in 1997) replaces the template with a fixed set of directions and adds a step-control rule: if any , move there; if none improves, the iteration fails and . The simplest example is coordinate search (compass search), with . The only requirement on is that it positively spans : every vector must be a combination of its elements with nonnegative coefficients. This is equivalent to its cosine measure
being positive: for any direction , some pattern direction makes an acute angle with it. For , (the worst case is ).
Proof
If there is nothing to prove. Otherwise, by the definition of with there exists with . By the descent lemma and the failure of the iteration,
Dividing by gives the bound.
∎The theorem turns into a certificate: at every failure, the gradient is at most proportional to the step. If the level set is bounded, iterates live on a lattice (with steps divided by 2) and there can be only finitely many successes at each value of , so and, along failed iterations, : (Torczon, 1997; Kolda, Lewis and Torczon, 2003). This is exactly what Nelder-Mead lacks. The price is slowness: with fixed directions, advancing along an oblique valley requires a staircase of small steps. Modern versions (GPS, MADS) add a free search phase, which can use a model or any heuristic, before the polling phase that gives the guarantee.
Implementation from scratch
First, the Gaussian smoothing estimator and the two quantitative claims from the previous section: relative error and mean cosine with the gradient.
import numpy as np
from math import lgamma, exp, pi, sqrt
def zo_grad(f, x, sigma, n_dirs, rng, kind="central"):
"""Estimador de suavizado gaussiano con n_dirs direcciones u ~ N(0, I)."""
U = rng.standard_normal((n_dirs, x.size))
if kind == "forward": # n_dirs + 1 evaluaciones
fx = f(x)
d = np.array([(f(x + sigma * u) - fx) / sigma for u in U])
else: # 2 n_dirs evaluaciones (antitético)
d = np.array([(f(x + sigma * u) - f(x - sigma * u)) / (2 * sigma) for u in U])
return d @ U / n_dirs
def cos_medio(d):
"""E|cos(u, a)| = Gamma(d/2) / (sqrt(pi) Gamma((d+1)/2)), en logaritmos para d grande."""
return exp(lgamma(d / 2) - lgamma((d + 1) / 2)) / sqrt(pi)
rng = np.random.default_rng(0)
print("cuadrática f = x^T diag(1..10) x / 2, N = 10 direcciones, 100 repeticiones")
print(" d error relativo medido (d+1)/N coseno medio (1 dir.) teoría")
for d in [2, 10, 100, 1000]:
A = np.linspace(1, 10, d)
f = lambda x: 0.5 * np.dot(A * x, x)
x = rng.standard_normal(d)
grad = A * x
errs = [np.sum((zo_grad(f, x, 1e-3, 10, rng) - grad) ** 2) / np.sum(grad ** 2) for _ in range(100)]
coss = []
for _ in range(100):
g1 = zo_grad(f, x, 1e-3, 1, rng)
coss.append(g1 @ grad / (np.linalg.norm(g1) * np.linalg.norm(grad)))
print(f"{d:5d} {np.mean(errs):14.2f} {(d + 1) / 10:7.2f} {np.mean(coss):10.3f} {cos_medio(d):.3f}")
print("coseno nunca negativo:", min(coss) >= 0)The measured error follows across three orders of magnitude and the mean cosine matches the exact formula. No cosine is negative: as proved, is never an ascent direction.
Now the trade-off with noise. To isolate it from directional error, the same directions are fixed for all and compared with the ideal estimator that those same directions would give without noise and with .
import numpy as np
rng = np.random.default_rng(1)
d, nu, N = 20, 1e-4, 50 # dimensión, ruido de las evaluaciones, direcciones
x0 = np.linspace(-1, 1, d)
grad = np.tanh(x0) # f(x) = sum log cosh(x_i)
U = rng.standard_normal((N, d))
g_ideal = (U @ grad) @ U / N
def f_ruidosa(x):
return np.sum(np.log(np.cosh(x))) + nu * rng.standard_normal()
print("error ||g - g_ideal|| / ||grad|| (media de 10 repeticiones)")
print(" sigma hacia delante antitético")
for sigma in [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 0.3, 1.0]:
e_del, e_ant = [], []
for _ in range(10):
fx = f_ruidosa(x0)
g_del = np.array([(f_ruidosa(x0 + sigma * u) - fx) / sigma for u in U]) @ U / N
g_ant = np.array([(f_ruidosa(x0 + sigma * u) - f_ruidosa(x0 - sigma * u)) / (2 * sigma) for u in U]) @ U / N
e_del.append(np.linalg.norm(g_del - g_ideal) / np.linalg.norm(grad))
e_ant.append(np.linalg.norm(g_ant - g_ideal) / np.linalg.norm(grad))
print(f" {sigma:7.0e} {np.mean(e_del):11.4f} {np.mean(e_ant):10.4f}")
print(f"escala del óptimo: nu^(1/2) = {nu ** 0.5:.0e} (hacia delante), nu^(1/3) = {nu ** (1 / 3):.0e} (antitético)")Both curves are U-shaped. On the left noise dominates, growing as ; on the right, truncation bias. The forward estimator has its minimum near , where predicts; the antithetic estimator is an order of magnitude more accurate at its optimum, between and , because its truncation error is and it tolerates a larger . The same happens with exact floating-point evaluations, with .
Now the evaluation count for descent: exact gradient, finite differences and two random points with the theorem step size, . Then a problem with effective rank 5 in increasing dimensions.
import numpy as np
def descenso(f, estimador, x0, eta, presupuesto, tol):
"""Itera x <- x - eta g hasta f(x) <= tol f(x0); devuelve las evaluaciones gastadas en estimar."""
x, usadas, f0 = x0.copy(), 0, f(x0)
while usadas < presupuesto:
g, coste = estimador(x)
x = x - eta * g
usadas += coste
if f(x) <= tol * f0: # comprobación de parada: no se cuenta
return usadas
return np.inf
rng = np.random.default_rng(0)
print("cuadrática con autovalores 1..10, hasta f <= 1e-6 f0")
print(" d GD (gradientes) dif. finitas (evals) dos puntos (evals) cociente")
for d in [5, 20, 80]:
lam = np.linspace(1, 10, d)
f = lambda x: 0.5 * np.dot(lam * x, x)
L, trH = lam.max(), lam.sum()
x0 = np.ones(d)
gd = descenso(f, lambda x: (lam * x, 1), x0, 1 / L, 10**6, 1e-6)
def finitas(x, h=1e-6):
fx = f(x)
return np.array([(f(x + h * e) - fx) / h for e in np.eye(d)]), d + 1
fd = descenso(f, finitas, x0, 1 / L, 10**6, 1e-6)
def dos_puntos(x, s=1e-4):
u = rng.standard_normal(d)
return (f(x + s * u) - f(x - s * u)) / (2 * s) * u, 2
zo = np.mean([descenso(f, dos_puntos, x0, 1 / (trH + 2 * L), 10**6, 1e-6) for _ in range(3)])
print(f"{d:4d} {gd:8.0f} {fd:10.0f} {zo:10.0f} {zo / fd:.2f}")
print("\nrango efectivo 5: cinco autovalores 1 y el resto 1e-4; hasta f <= 0.05 f0")
print(" d tr H / ||H|| paso 1/(tr H + 2||H||) paso 1/((d+2) ||H||)")
for d in [10, 100, 1000, 3000]:
lam = np.full(d, 1e-4); lam[:5] = 1.0
f = lambda x: 0.5 * np.dot(lam * x, x)
x0 = np.zeros(d); x0[:5] = 1.0
def dos_puntos(x, s=1e-4):
u = rng.standard_normal(d)
return (f(x + s * u) - f(x - s * u)) / (2 * s) * u, 2
efectivo = np.mean([descenso(f, dos_puntos, x0, 1 / (lam.sum() + 2), 10**5, 0.05) for _ in range(3)])
# el paso ingenuo en d = 3000 costaría unas 9000 evaluaciones: se omite para no alargar la celda
ingenuo = f"{np.mean([descenso(f, dos_puntos, x0, 1 / (d + 2), 10**5, 0.05) for _ in range(3)]):10.0f} evals" if d <= 1000 else " (omitido)"
print(f"{d:6d} {lam.sum():9.2f} {efectivo:12.0f} evals {ingenuo}")In the first table, gradient-descent step count does not depend on (it depends on the condition number, which is 10), while both zeroth-order variants spend evaluations proportional to , and random directions need 1.3 to 1.7 times more than finite differences: with smooth noiseless functions they do not beat them. Here , so the theorem predicts about evaluations per equivalent gradient step versus for finite differences: a ratio of 1.1, somewhat below the measured value because the bound is for one step and convergence also depends on low-curvature directions. In the second table, with effective rank , the theorem step makes cost a few dozen evaluations in both and , whereas the worst-case step scales with .
The evolution strategy with antithetic sampling, with and without ranks, against monotonic transformations and heavy-tailed noise:
import numpy as np
def rangos_centrados(v):
"""Rangos reescalados a [-0.5, 0.5]: el menor valor recibe -0.5 y el mayor +0.5 (sin tratar empates)."""
r = np.empty(len(v))
r[np.argsort(v)] = np.arange(len(v))
return r / (len(v) - 1) - 0.5
def es(f, x0, sigma, eta, n_pares, n_iter, rng, rangos=True):
"""ES con muestreo antitético: x <- x - eta g. Devuelve el punto final y f(x) en cada iteración."""
x = np.array(x0, dtype=float)
hist = []
for _ in range(n_iter):
eps = rng.standard_normal((n_pares, x.size))
fp = np.array([f(x + sigma * e) for e in eps])
fm = np.array([f(x - sigma * e) for e in eps])
if rangos:
r = rangos_centrados(np.concatenate([fp, fm]))
w = r[:n_pares] - r[n_pares:]
else:
w = fp - fm
x = x - eta * (w @ eps) / (2 * n_pares * sigma)
hist.append(f(x))
return x, np.array(hist)
d = 10
x_opt = np.ones(d)
esfera = lambda x: np.sum((x - x_opt) ** 2)
ruido = np.random.default_rng(5)
casos = {
"f": esfera,
"1e6 f": lambda x: 1e6 * esfera(x),
"exp(f)": lambda x: np.exp(min(esfera(x), 700.0)),
"f + Cauchy": lambda x: esfera(x) + 0.3 * ruido.standard_cauchy(),
}
print("distancia final al óptimo tras 300 iteraciones (6000 evaluaciones)")
with np.errstate(all="ignore"):
for nombre, fn in casos.items():
fila = []
for rangos, eta in [(False, 0.05), (True, 0.1)]:
x, _ = es(fn, np.zeros(d), sigma=0.1, eta=eta, n_pares=10, n_iter=300, rng=np.random.default_rng(3), rangos=rangos)
fila.append(np.linalg.norm(x - x_opt))
print(f" {nombre:11s} sin rangos: {fila[0]:9.3g} con rangos: {fila[1]:.3g}")Without ranks, ES converges to machine precision on the sphere, because vanishes near the minimum; but the same makes it diverge with or , and the heavy tail of Cauchy noise derails it. With ranks, the result is identical with , and (the three functions order any set of points identically) and withstands Cauchy noise; in exchange, it oscillates at a distance from the optimum proportional to , because the size of no longer decreases. CMA-ES solves both at once: it uses ranks and adapts step size.
import numpy as np
def cma_es(f, m0, sigma0, rng, max_evals=20000, f_target=1e-10, lam=None, adaptar_C=True):
"""(mu/mu_w, lambda)-CMA-ES con los parámetros por defecto de Hansen (2016), sin reinicios."""
n = len(m0)
m, sigma = np.array(m0, dtype=float), float(sigma0)
lam = lam or 4 + int(3 * np.log(n))
mu = lam // 2
w = np.log((lam + 1) / 2) - np.log(np.arange(1, mu + 1))
w /= w.sum()
mu_eff = 1 / np.sum(w ** 2)
c_sig = (mu_eff + 2) / (n + mu_eff + 5)
d_sig = 1 + 2 * max(0.0, np.sqrt((mu_eff - 1) / (n + 1)) - 1) + c_sig
c_c = (4 + mu_eff / n) / (n + 4 + 2 * mu_eff / n)
c_1 = 2 / ((n + 1.3) ** 2 + mu_eff) if adaptar_C else 0.0
c_mu = min(1 - c_1, 2 * (mu_eff - 2 + 1 / mu_eff) / ((n + 2) ** 2 + mu_eff)) if adaptar_C else 0.0
chi_n = np.sqrt(n) * (1 - 1 / (4 * n) + 1 / (21 * n ** 2)) # E||N(0, I)||
p_sig, p_c = np.zeros(n), np.zeros(n)
C, B, D = np.eye(n), np.eye(n), np.ones(n)
evals, gen, hist = 0, 0, []
while evals < max_evals:
Z = rng.standard_normal((lam, n))
Y = (Z * D) @ B.T # y_k = B D z_k ~ N(0, C)
X = m + sigma * Y
fx = np.array([f(x) for x in X])
evals += lam
sel = np.argsort(fx)[:mu]
y_w = w @ Y[sel]
m = m + sigma * y_w # recombinación ponderada
p_sig = (1 - c_sig) * p_sig + np.sqrt(c_sig * (2 - c_sig) * mu_eff) * (B @ ((B.T @ y_w) / D))
h_sig = np.linalg.norm(p_sig) / np.sqrt(1 - (1 - c_sig) ** (2 * (gen + 1))) < (1.4 + 2 / (n + 1)) * chi_n
p_c = (1 - c_c) * p_c + h_sig * np.sqrt(c_c * (2 - c_c) * mu_eff) * y_w
rango_mu = (Y[sel].T * w) @ Y[sel]
C = (1 - c_1 - c_mu) * C + c_1 * (np.outer(p_c, p_c) + (1 - h_sig) * c_c * (2 - c_c) * C) + c_mu * rango_mu
sigma *= np.exp((c_sig / d_sig) * (np.linalg.norm(p_sig) / chi_n - 1))
C = (C + C.T) / 2
autoval, B = np.linalg.eigh(C)
D = np.sqrt(np.maximum(autoval, 1e-30))
gen += 1
hist.append((evals, f(m), sigma))
if hist[-1][1] <= f_target:
break
return m, C, sigma, np.array(hist)
def elipsoide(n, kappa, rng):
"""Cuadrática rotada al azar con número de condición kappa: f(x) = x^T H x / 2."""
Q, _ = np.linalg.qr(rng.standard_normal((n, n)))
H = Q @ np.diag(np.logspace(0, np.log10(kappa), n)) @ Q.T
return (lambda x: 0.5 * x @ H @ x), H
f, H = elipsoide(10, 1e3, np.random.default_rng(0))
for adaptar in [True, False]:
m, C, s, h = cma_es(f, np.ones(10), 0.5, np.random.default_rng(1), max_evals=30000, adaptar_C=adaptar)
print(f"adaptar C = {adaptar!s:5} evaluaciones = {int(h[-1, 0]):6d} f(m) = {h[-1, 1]:.1e}")
m, C, s, h = cma_es(f, np.ones(10), 0.5, np.random.default_rng(1))
Lh = np.linalg.cholesky(H)
espectro = np.linalg.eigvalsh(Lh.T @ C @ Lh) # mismos autovalores que C H
print(f"cond(H) = {np.linalg.cond(H):.0f} cond(C) = {np.linalg.cond(C):.0f} cond(C H) = {espectro.max() / espectro.min():.2f}")In with condition number , full CMA-ES reaches in about 3200 evaluations; with only control, after evaluations it remains far away. And the last line confirms what the figure showed: has condition number close to that of and product has condition number of only a few units, that is, .
Finally, Nelder-Mead from scratch, McKinnon’s counterexample and comparison with SciPy:
import numpy as np
from scipy.optimize import minimize
def nelder_mead(f, simplex, max_evals=5000, tol=1e-10):
"""Nelder-Mead con coeficientes (1, 2, 1/2, 1/2) y las reglas de Lagarias et al. (1998)."""
S = np.array(simplex, dtype=float)
F = np.array([f(s) for s in S])
evals, ops = len(S), []
while evals < max_evals:
orden = np.argsort(F, kind="stable")
S, F = S[orden], F[orden]
if np.max(np.abs(S[1:] - S[0])) < tol:
break
c = S[:-1].mean(axis=0) # centroide de todos menos el peor
xr = c + (c - S[-1]); fr = f(xr); evals += 1
if F[0] <= fr < F[-2]: # reflexión
S[-1], F[-1] = xr, fr; ops.append("r"); continue
if fr < F[0]: # expansión
xe = c + 2 * (c - S[-1]); fe = f(xe); evals += 1
S[-1], F[-1] = (xe, fe) if fe < fr else (xr, fr)
ops.append("e" if fe < fr else "r"); continue
if fr < F[-1]: # contracción exterior
xc = c + 0.5 * (xr - c); fc = f(xc); evals += 1
if fc <= fr:
S[-1], F[-1] = xc, fc; ops.append("o"); continue
else: # contracción interior
xc = c + 0.5 * (S[-1] - c); fc = f(xc); evals += 1
if fc < F[-1]:
S[-1], F[-1] = xc, fc; ops.append("i"); continue
S[1:] = S[0] + 0.5 * (S[1:] - S[0]) # encogimiento hacia el mejor vértice
F[1:] = [f(s) for s in S[1:]]; evals += len(S) - 1; ops.append("s")
orden = np.argsort(F, kind="stable")
return S[orden], F[orden], evals, "".join(ops)
def mckinnon(p, theta=6.0, phi=60.0):
x, y = p
return (theta * phi * x ** 2 if x <= 0 else theta * x ** 2) + y + y ** 2
l1, l2 = (1 + np.sqrt(33)) / 8, (1 - np.sqrt(33)) / 8
S0 = [[0.0, 0.0], [1.0, 1.0], [l1, l2]]
S, F, ev, ops = nelder_mead(mckinnon, S0, max_evals=200)
print("operaciones:", ops[:40], "...")
print("mejor vértice:", S[0], " f =", F[0], " diámetro:", f"{np.max(np.linalg.norm(S - S[0], axis=1)):.1e}")
print("gradiente en él:", np.array([0.0, 1 + 2 * S[0][1]]), " mínimo real: (0, -0.5) con f = -0.25")
r = minimize(mckinnon, S0[0], method="Nelder-Mead", options={"initial_simplex": np.array(S0), "xatol": 1e-10, "fatol": 1e-12})
print("SciPy, mismo símplex:", np.round(r.x, 8), r.fun, "|", r.message)
r = minimize(mckinnon, [0.0, 0.0], method="Nelder-Mead")
print("SciPy, su símplex por defecto:", np.round(r.x, 5), round(r.fun, 6))
print("\ncuadrática con autovalores 1..10, presupuesto 1000 d evaluaciones")
for n in [2, 8, 16, 32]:
lam = np.linspace(1, 10, n)
f = lambda x: 0.5 * np.dot(lam * x, x)
for adaptive in [False, True]:
r = minimize(f, np.ones(n), method="Nelder-Mead", options={"maxfev": 1000 * n, "xatol": 1e-12, "fatol": 1e-14, "adaptive": adaptive})
print(f" d = {n:2d} adaptive = {adaptive!s:5} evaluaciones = {r.nfev:6d} f / f0 = {r.fun / f(np.ones(n)):.1e}")Both implementations, ours and SciPy’s, terminate “successfully” at , where : the Nelder-Mead stopping criterion looks at simplex size and value dispersion, and both are satisfied without the point being stationary. With another initial simplex, SciPy finds the minimum: the failure is fragile, and that is precisely why it is dangerous, because it gives no warning. The final table shows the other problem: with standard coefficients cost grows very rapidly with dimension and at the method stalls; the adaptive version succeeds in every case.
Comparison by number of evaluations
Using the functions from previous cells, compare four methods with the same budget of 4000 evaluations, on Rosenbrock and on a quadratic with Gaussian noise of standard deviation , in dimensions 2 to 50. The true (noise-free) value of at each method’s returned point is reported.
import numpy as np
from scipy.optimize import minimize
def rosen(x):
return np.sum(100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2)
def esfera(x):
return 0.5 * np.dot(x, x)
def dos_puntos(f, x0, presupuesto, eta, sigma, rng):
x = np.array(x0, dtype=float)
for _ in range(presupuesto // 2):
u = rng.standard_normal(x.size)
x = x - eta * (f(x + sigma * u) - f(x - sigma * u)) / (2 * sigma) * u
return x
B = 4000
ruido = np.random.default_rng(7)
ruidosa = lambda x: esfera(x) + 0.01 * ruido.standard_normal()
problemas = [
("Rosenbrock d=2", rosen, rosen, np.array([-1.2, 1.0]), 1e-3),
("Rosenbrock d=10", rosen, rosen, np.zeros(10), 1e-4),
("esfera ruidosa d=10", ruidosa, esfera, np.ones(10), 1 / 12),
("esfera ruidosa d=50", ruidosa, esfera, np.ones(50), 1 / 52),
]
print(f"{'problema':21s} {'dos puntos':>11s} {'ES rangos':>10s} {'CMA-ES':>10s} {'Nelder-Mead':>12s}")
for nombre, f, f_verdadera, x0, eta in problemas:
d = x0.size
x_zo = dos_puntos(f, x0, B, eta, 0.1, np.random.default_rng(0))
n_pares = 4 + d // 2
x_es, _ = es(f, x0, sigma=0.1, eta=0.05, n_pares=n_pares, n_iter=B // (2 * n_pares) - 1, rng=np.random.default_rng(0))
x_cma, _, _, _ = cma_es(f, x0, 0.5, np.random.default_rng(0), max_evals=B, f_target=-np.inf)
x_nm = minimize(f, x0, method="Nelder-Mead", options={"maxfev": B, "adaptive": True}).x
print(f"{nombre:21s} " + " ".join(f"{f_verdadera(x):10.2e}" for x in [x_zo, x_es, x_cma, x_nm]))There is no universal winner, and the table shows why. On noiseless Rosenbrock, methods adapting to geometry make use of each evaluation: CMA-ES solves to machine precision and adaptive Nelder-Mead reaches even in , where CMA-ES has not yet finished learning a covariance of . The two fixed-step estimated-gradient methods advance at the speed of gradient descent in an ill-conditioned valley, that is, very slowly. With noise and increasing dimension the order reverses: Nelder-Mead gets lost in because it compares noisy values and its simplex degenerates, while both gradient estimators, which average noise over hundreds of steps like SGD, are most robust. CMA-ES is in the middle: noise eventually slows the reduction of , and noisy problems use variants with explicit noise handling or larger populations.
Zeroth order at scale: MeZO
Fine-tuning an LLM with Adam requires, in addition to parameters, their gradients, the two Adam moments and intermediate activations saved by backpropagation, about four times parameter memory plus activations (the fine-tuning memory accounting). Malladi et al. (2023) observed that the two-point estimator only needs forward passes and proposed MeZO (memory-efficient zeroth-order), a version of zeroth-order SGD (SPSA, by Spall) with an implementation trick that makes it fit in inference memory:
- Choose a seed and use it to perturb parameters in place: , generating tensor by tensor. Evaluate .
- Regenerate from the same seed and perform . Evaluate . Regenerate and undo: .
- The estimated directional derivative is a single scalar, . Regenerate one last time and update .
never exists in full in memory: the seed suffices. Memory is that of inference, without saved activations, gradients or optimizer state. According to the paper, this reduces memory up to 12-fold and allows a 30-billion-parameter model to be fine-tuned on a single 80 GB A100 GPU, where backpropagation fine-tuning only reaches 2700 million (2.7 billion). And it works despite gigantic because of the expected-descent theorem: what matters is local effective curvature rank, which is small when fine-tuning a pretrained model (especially with prompts framing the task as one the model already knows). The price is many more steps than Adam, although each is cheap.
The following miniature compares MeZO with Adam on a small MLP, on CPU. It measures memory saved by autograd for the backward pass with saved_tensors_hooks, exactly what MeZO saves.
import time
import torch
from torch import nn
torch.set_num_threads(2)
device = "cpu" # MeZO solo hace pasadas hacia delante: la CPU basta para la demostración
g = torch.Generator().manual_seed(0)
n, d_in = 512, 16
X = torch.randn(n, d_in, generator=g)
w_true = torch.randn(d_in, 1, generator=g)
y = torch.tanh(X @ w_true) + 0.05 * torch.randn(n, 1, generator=g)
def make_model():
torch.manual_seed(1)
return nn.Sequential(nn.Linear(d_in, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1)).to(device)
loss_fn = nn.MSELoss()
n_params = sum(p.numel() for p in make_model().parameters())
def saved_bytes(fn):
"""Bytes que autograd guarda para la pasada hacia atrás mientras se ejecuta fn()."""
total = [0]
def pack(t):
total[0] += t.numel() * t.element_size()
return t
with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
fn()
return total[0]
# Adam con retropropagación
model = make_model()
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
act_adam = saved_bytes(lambda: loss_fn(model(X), y).backward())
t = time.perf_counter()
for step in range(300):
opt.zero_grad()
loss = loss_fn(model(X), y)
loss.backward()
opt.step()
adam_loss, adam_t = loss.item(), time.perf_counter() - t
estado = sum(s.numel() * s.element_size() for st in opt.state.values() for s in st.values() if torch.is_tensor(s) and s.dim() > 0)
grads = sum(p.grad.numel() * p.grad.element_size() for p in model.parameters())
# MeZO: dos puntos con la perturbación regenerada desde la semilla
model = make_model()
params = list(model.parameters())
def perturb(seed, scale):
gen = torch.Generator(device=device).manual_seed(seed)
for p in params:
p.data.add_(scale * torch.randn(p.shape, generator=gen, device=device))
@torch.no_grad()
def mezo_step(seed, eps, lr):
perturb(seed, +eps); lp = loss_fn(model(X), y).item()
perturb(seed, -2 * eps); lm = loss_fn(model(X), y).item()
perturb(seed, +eps) # vuelta a theta (salvo redondeo)
proj = (lp - lm) / (2 * eps) # derivada direccional estimada: un escalar
perturb(seed, -lr * proj) # theta <- theta - lr * proj * z
return (lp + lm) / 2
act_mezo = saved_bytes(lambda: mezo_step(10**6, 1e-3, 0.0))
t = time.perf_counter()
hist = [mezo_step(step, 1e-3, 5e-3) for step in range(3000)]
mezo_t = time.perf_counter() - t
with torch.no_grad():
mezo_loss = loss_fn(model(X), y).item()
base = loss_fn(make_model()(X), y).item()
kb = lambda b: f"{b / 1024:.0f} KB"
print(f"parámetros: {n_params} ({kb(4 * n_params)} en float32) pérdida inicial: {base:.4f}")
print(f"Adam, 300 pasos ( 300 pasadas hacia delante y atrás): pérdida {adam_loss:.4f} en {adam_t:.2f} s")
print(f"MeZO, 3000 pasos (6000 pasadas solo hacia delante): pérdida {mezo_loss:.4f} en {mezo_t:.2f} s")
print("MeZO, pérdida media en los pasos 1-100, 1451-1550 y 2901-3000:",
", ".join(f"{sum(hist[a:a + 100]) / 100:.4f}" for a in (0, 1450, 2900)))
print(f"memoria extra de Adam: activaciones guardadas {kb(act_adam)}, gradientes {kb(grads)}, momentos {kb(estado)}")
print(f"memoria extra de MeZO: activaciones guardadas {kb(act_mezo)}, sin gradientes ni momentos")npm run lab and open the connection link.MeZO loss decreases steadily, but with ten times as many steps it remains far from Adam’s: the effective dimension factor in action, in a small problem where backpropagation is very cheap. Memory accounting matters at scale: Adam’s saved activations grow with batch size and sequence length, and dominate in an LLM; MeZO saves none, and memory for parameters plus gradients plus moments becomes just parameters.
The professional version and when to use Bayesian optimization
| Tool | Method | When |
|---|---|---|
scipy.optimize.minimize(method="Nelder-Mead", options={"adaptive": True}) | Nelder-Mead | , noiseless, as a quick first attempt |
scipy.optimize.minimize(method="Powell") | derivative-free line searches | small , smooth functions |
cma package (Hansen), pycma | CMA-ES with restarts and box constraints | from 2 to a few hundred, multimodal, cheap or moderately expensive evaluations |
nevergrad (Meta) | collection (CMA, ES, DE, PSO) with automatic selector | compare black-box methods without implementing them |
| custom implementation, Salimans style | ES with shared seeds | thousands of cores, large , RL |
| Optuna (TPE), BoTorch, scikit-optimize | Bayesian optimization | expensive evaluations, , budgets of tens to hundreds |
When each evaluation is expensive, the question changes: algorithm cost per iteration no longer matters as much as extracting maximum information from each evaluation. Bayesian optimization fits a probabilistic model of (a Gaussian process or a density estimator such as TPE) to all evaluations and chooses the next by maximizing an acquisition function balancing exploration and exploitation. Each decision costs seconds of computation, negligible compared with a ten-minute backtest; in exchange, the model scales poorly with number of evaluations (an exact Gaussian process costs ) and dimension (above about 20 variables models become uninformative).
The practical rule summarizing the lesson:
| Situation | Recommendation |
|---|---|
| gradient exists and automatic differentiation is available | always use the gradient |
| huge , cheap parallel evaluations, or limited memory | random estimators (ES, ZO-SGD, MeZO) |
| from 2 to a few hundred, no gradient, cheap or moderate evaluations | CMA-ES |
| , no noise, something needed now | adaptive Nelder-Mead, with multiple starts |
| derivative-free stationarity guarantee needed | pattern search or MADS |
| expensive evaluations (minutes or hours), | Bayesian optimization |
Common mistakes
Exercises
Step 1 of 4. How do you write so it can be differentiated without differentiating ?
es_gradient(f, x, sigma, n_pairs, rng), an evolution strategy estimator for minimizing (the step is x - eta * g). Exact conventions: (1) generate all perturbations with one call eps = rng.standard_normal((n_pairs, x.size)); (2) evaluate f(x + sigma * eps[i]) for all i and then f(x - sigma * eps[i]), concatenating values in that order (first the +, then the -); (3) replace the 2 n_pairs values by their centered ranks: the smallest receives −0.5, the largest +0.5, uniformly spaced, and ties receive the mean of their ranks; (4) return g = sum_i (r_plus[i] - r_minus[i]) * eps[i] / (2 * n_pairs * sigma).import numpy as np
def es_gradient(f, x, sigma, n_pairs, rng):
"""Estimador ES antitético con rangos centrados (para minimizar f)."""
x = np.asarray(x, dtype=float)
# tu código: perturbaciones, evaluaciones, rangos centrados con empates promediados, combinación
return np.zeros_like(x)More than one answer may be correct.
Summary
- The two-point estimator is unbiased for the gradient of Gaussian smoothing , which exists even if is not differentiable. Its relative squared error is with directions.
- is the resolution at which is viewed: small amplifies noise as , large biases toward . The value bias of smoothing is at most .
- Zeroth-order rates are gradient rates multiplied by , and that factor is unavoidable in general; with effective curvature rank , the factor is . This is why MeZO works for LLMs.
- Evolution strategies follow the gradient of a search distribution; antithetic sampling cancels even terms, ranks provide invariance to monotonic transformations and shared seeds enable parallelism by communicating only scalars.
- CMA-ES adapts using the covariance of successful steps (rank ) and path memory (rank one), and by comparing path length to that of a random walk. On quadratics, tends to be proportional to .
- Nelder-Mead is useful in low dimension but has no guarantees: McKinnon’s counterexample takes it to a nonstationary point of a smooth convex function. Pattern search does converge, because every failure bounds .