Module contents
Lesson 22 of 27Advanced 100 min

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

Motivation: optimizing what you can only evaluate

Until now the entire module has assumed that, in addition to f(x)f(\vb{x}), you can request ∇f(x)\grad f(\vb{x}). With automatic differentiation that is almost free: reverse mode returns the entire gradient for a small multiple of the cost of evaluating ff, 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 x\vb{x} and it returns f(x)f(\vb{x}), 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 ff 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,

∂f∂xi(x)≈f(x+hei)−f(x)h,i=1,…,d.\pd{f}{x_i}(\vb{x}) \approx \frac{f(\vb{x} + h\vb{e}_i) - f(\vb{x})}{h}, \qquad i = 1, \dots, d.

If ff is LL-smooth, each component has truncation error at most Lh/2Lh/2, and if each evaluation has error of size εf\eps_f (roundoff or noise), a term 2εf/h2\eps_f/h is added. The optimal step balances the two, h⋆=2εf/Lh^\star = 2\sqrt{\eps_f/L}, leaving per-component error on the order of Lεf\sqrt{L\eps_f}. Centered differences, (f(x+hei)−f(x−hei))/(2h)(f(\vb{x} + h\vb{e}_i) - f(\vb{x} - h\vb{e}_i))/(2h), reduce truncation to O(h2)\bigO(h^2) at the cost of twice as many evaluations.

The problem is not accuracy, but cost: a forward-difference gradient requires d+1d + 1 evaluations. For a model with 10610^6 parameters that is 10610^6 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 dd coordinates

Finite differences reconstruct ∇f\grad f by probing the dd basis directions. The alternative is to probe one random direction u\vb{u} and retain the directional derivative along it:

g=f(x+σu)−f(x−σu)2σ u  ≈  (u⊤∇f(x)) u,u∼N(0,Id).\vb{g} = \frac{f(\vb{x} + \sigma\vb{u}) - f(\vb{x} - \sigma\vb{u})}{2\sigma}\,\vb{u} \;\approx\; (\vb{u}\T\grad f(\vb{x}))\,\vb{u}, \qquad \vb{u} \sim \Normal(\vb{0}, \mat{I}_d).

It costs two evaluations, whatever dd. Why does it point somewhere useful? Because E[uu⊤]=I\E[\vb{u}\vb{u}\T] = \mat{I}, the covariance matrix of a standard Gaussian, and therefore E[(u⊤∇f)u]=E[uu⊤]∇f=∇f\E[(\vb{u}\T\grad f)\vb{u}] = \E[\vb{u}\vb{u}\T]\grad f = \grad f: in the limit σ→0\sigma \to 0 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: ∇f⊤g=(u⊤∇f)2≥0\grad f\T\vb{g} = (\vb{u}\T\grad f)^2 \ge 0. Each estimate, however poor, makes an angle of at most 90°90° with the gradient, so −g-\vb{g} 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, ∥g∥2=(a⊤u)2∥u∥2=∑i,j,kaiaj uiujuk2\norm{\vb{g}}^2 = (\vb{a}\T\vb{u})^2\norm{\vb{u}}^2 = \sum_{i, j, k} a_i a_j\, u_i u_j u_k^2. Fourth-order moments of a standard Gaussian are given by Isserlis’ formula, E[uiujukul]=δijδkl+δikδjl+δilδjk\E[u_i u_j u_k u_l] = \delta_{ij}\delta_{kl} + \delta_{ik}\delta_{jl} + \delta_{il}\delta_{jk}. With k=lk = l and summing over kk,

∑kE[uiujuk2]=∑k(δij+2δikδjk)=(d+2) δij,\sum_k \E[u_i u_j u_k^2] = \sum_k (\delta_{ij} + 2\delta_{ik}\delta_{jk}) = (d + 2)\,\delta_{ij},

so E∥g∥2=(d+2)∑iai2\E\norm{\vb{g}}^2 = (d + 2)\sum_i a_i^2. Then E∥g−a∥2=E∥g∥2−∥a∥2=(d+1)∥a∥2\E\norm{\vb{g} - \vb{a}}^2 = \E\norm{\vb{g}}^2 - \norm{\vb{a}}^2 = (d + 1)\norm{\vb{a}}^2. For the mean of NN independent copies, the component variances are divided by NN, as is the trace of the covariance.

∎

The relative squared error of one estimate is d+1d + 1: in dimension 10001000, noise is roughly 3232 times larger than signal. To reduce it to a fixed level one must average N∝dN \propto d directions, spending on the order of dd evaluations, just as with finite differences. Another way to see it is the angle: the cosine between g\vb{g} and a\vb{a} is ∣a⊤u∣/(∥a∥∥u∥)\abs{\vb{a}\T\vb{u}}/(\norm{\vb{a}}\norm{\vb{u}}), and its expectation is Γ(d/2)/(π Γ((d+1)/2))≈2/(πd)\Gamma(d/2)/(\sqrt{\pi}\,\Gamma((d + 1)/2)) \approx \sqrt{2/(\pi d)}. In d=106d = 10^6, a random direction is on average 89.95°89.95° from the gradient.

For a quadratic f(x)=12x⊤Ax+b⊤xf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} + \vb{b}\T\vb{x}, the centered difference is exact for any σ\sigma: f(x+σu)−f(x−σu)=2σ u⊤(Ax+b)f(\vb{x} + \sigma\vb{u}) - f(\vb{x} - \sigma\vb{u}) = 2\sigma\,\vb{u}\T(\mat{A}\vb{x} + \vb{b}), 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 σ\sigma, g\vb{g} no longer estimates ∇f\grad f 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.

fσf_\sigma is the convolution of ff with a bell of width σ\sigma: it averages ff in a fuzzy ball of radius σ\sigma. It erases details on scales smaller than σ\sigma (noise, roughness, jumps) and preserves the shape on larger scales. The estimator does not differentiate ff: it samples around x\vb{x}, sees which side is higher and averages directions weighted by that difference.

InteractiveEstimate a gradient without differentiating
Cargando el interactivo…
A bowl with high-frequency roughness, f(x)=12(a1x12+a2x22)+A(2−cos⁡ωx1−cos⁡ωx2)f(\vb{x}) = \tfrac12(a_1x_1^2 + a_2x_2^2) + A(2 - \cos\omega x_1 - \cos\omega x_2), whose smoothed version is known in closed form. Around point x\vb{x} (drag it) are samples x±σui\vb{x} \pm \sigma\vb{u}_i: red for the higher ff of each pair, blue for the lower. The magenta arrow is the estimated descent direction, −g^-\hat{\vb{g}}; dashed gray is the exact one, −∇fσ(x)-\grad f_\sigma(\vb{x}); the magenta cloud shows the tips of 60 independent estimates. With σ=0.12\sigma = 0.12 two thirds of the roughness survives: move x\vb{x} and you will see −g^-\hat{\vb{g}} point to the bottom of the nearest dip. Increase σ\sigma to 0.40.4: roughness disappears from fσf_\sigma (enable it in contours) and the arrow, with the whole cloud, points toward the bowl's bottom (the cosine of −∇fσ-\grad f_\sigma with the direction to the global minimum rises from 0.440.44 to 0.880.88; each estimate fluctuates around it). Increase NN and the cloud shrinks as 1/N1/\sqrt{N}: the variance theorem fixes its relative size. Below is the price of dimension: relative error grows as (d+1)/N(d + 1)/N, exactly as the theorem predicts.

For this function everything can be calculated by hand, because E[cos⁡ω(x+σu)]=e−ω2σ2/2cos⁡ωx\E[\cos\omega(x + \sigma u)] = e^{-\omega^2\sigma^2/2}\cos\omega x (the characteristic function of the Gaussian) and E[(x+σu)2]=x2+σ2\E[(x + \sigma u)^2] = x^2 + \sigma^2:

fσ(x)=12(a1(x12+σ2)+a2(x22+σ2))+A(2−e−ω2σ2/2(cos⁡ωx1+cos⁡ωx2)).f_\sigma(\vb{x}) = \tfrac12\big(a_1(x_1^2 + \sigma^2) + a_2(x_2^2 + \sigma^2)\big) + A\big(2 - e^{-\omega^2\sigma^2/2}(\cos\omega x_1 + \cos\omega x_2)\big).

The quadratic part only shifts by a constant and roughness is attenuated by e−ω2σ2/2e^{-\omega^2\sigma^2/2}. With ω=2.4π\omega = 2.4\pi, at σ=0.12\sigma = 0.12, 66 %66\,\% of the roughness survives, and at σ=0.4\sigma = 0.4, 1 %1\,\%. Details with wavelength below σ\sigma die exponentially; those on a much larger scale barely change.

The proof writes fσf_\sigma as an integral against the Gaussian density and differentiates the density, not ff; you will do it step by step in the exercises. If ff is also differentiable, Stein’s lemma, E[h(u)u]=E[∇h(u)]\E[h(\vb{u})\vb{u}] = \E[\grad h(\vb{u})], applied to h(u)=f(x+σu)h(\vb{u}) = f(\vb{x} + \sigma\vb{u}) gives another interpretation: ∇fσ(x)=E[∇f(x+σu)]\grad f_\sigma(\vb{x}) = \E[\grad f(\vb{x} + \sigma\vb{u})], the average gradient in the fuzzy ball. Subtracting f(x)f(\vb{x}), or using the antithetic pair, does not change the expectation (because E[u]=0\E[\vb{u}] = \vb{0} and u\vb{u} and −u-\vb{u} have the same law), but does change the variance: it removes the term f(x)uf(\vb{x})\vb{u} from the estimator, which can be enormous if ff takes large values far from zero. This has the same role as the baseline in policy gradients.

Bias and variance

How far is fσf_\sigma from ff? If ff is LL-smooth, the descent lemma gives ∣f(x+σu)−f(x)−σ∇f(x)⊤u∣≤L2σ2∥u∥2\abs{f(\vb{x} + \sigma\vb{u}) - f(\vb{x}) - \sigma\grad f(\vb{x})\T\vb{u}} \le \tfrac{L}{2}\sigma^2\norm{\vb{u}}^2. Taking expectations, the linear term disappears and E∥u∥2=d\E\norm{\vb{u}}^2 = d:

∣fσ(x)−f(x)∣≤Lσ2d2.\abs{f_\sigma(\vb{x}) - f(\vb{x})} \le \frac{L\sigma^2 d}{2}.

If ff is also convex, fσ≥ff_\sigma \ge f by Jensen’s inequality and fσf_\sigma inherits convexity. Nesterov and Spokoiny (2017) complete the picture for convex or nonconvex ff with LL-Lipschitz gradient:

Both bounds say the same as the variance theorem, now with finite σ\sigma: the second moment is on the order of dd times the squared gradient, plus a curvature term that grows with σ\sigma. Bias also grows with σ\sigma and dimension, because the fuzzy ball has typical radius σd\sigma\sqrt{d}, not σ\sigma.

Choosing σ\sigma

With exact evaluations, σ\sigma should be small: bias vanishes and variance remains at the minimum (d+1)/N(d + 1)/N. But evaluations are never exact. If ff is observed with noise of standard deviation ν\nu, each quotient (f(x+σu)−f(x−σu))/(2σ)(f(\vb{x} + \sigma\vb{u}) - f(\vb{x} - \sigma\vb{u}))/(2\sigma) carries error of size ν/σ\nu/\sigma, which explodes when σ→0\sigma \to 0. This is the same trade-off as the optimal finite-difference step: in the antithetic quotient truncation error is O(σ2)\bigO(\sigma^2) (even Taylor terms cancel) and noise error is O(ν/σ)\bigO(\nu/\sigma), so the optimum is σ∼ν1/3\sigma \sim \nu^{1/3}; in the forward quotient truncation is O(σ)\bigO(\sigma) and the optimum is σ∼ν1/2\sigma \sim \nu^{1/2}. The σ\sigma part of the forward quotient, σ2u⊤∇2f(x) u\tfrac{\sigma}{2}\vb{u}\T\hess f(\vb{x})\,\vb{u}, has zero mean once multiplied by u\vb{u} (it is odd in u\vb{u}): it does not bias the estimate of ∇fσ\grad f_\sigma, but makes it noisier. There is a third reason for a large σ\sigma, seen in the figure: if ff is rough at small scales, σ\sigma determines the scale at which you look, and too small an σ\sigma pursues uninteresting local minima.

The dd factor: rates and effective rank

Use the estimator as if it were a gradient: xk+1=xk−η gk\vb{x}_{k+1} = \vb{x}_k - \eta\,\vb{g}_k. 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 ∇2f⪯H\hess f \preceq \mat{H}, f(x+s)≤f(x)+∇f(x)⊤s+12s⊤Hsf(\vb{x} + \vb{s}) \le f(\vb{x}) + \grad f(\vb{x})\T\vb{s} + \tfrac12\vb{s}\T\mat{H}\vb{s} for all s\vb{s}. With a=∇f(x)\vb{a} = \grad f(\vb{x}) and s=−ηg\vb{s} = -\eta\vb{g}, the linear term is −η(a⊤u)2-\eta(\vb{a}\T\vb{u})^2, with expectation −η∥a∥2-\eta\norm{\vb{a}}^2. The quadratic term is η22(a⊤u)2 u⊤Hu\tfrac{\eta^2}{2}(\vb{a}\T\vb{u})^2\,\vb{u}\T\mat{H}\vb{u}, and by Isserlis

E[(a⊤u)2 u⊤Hu]=∑i,j,k,laiajHkl (δijδkl+δikδjl+δilδjk)=∥a∥2tr⁡H+2 a⊤Ha≤(tr⁡H+2∥H∥2)∥a∥2.\E\big[(\vb{a}\T\vb{u})^2\,\vb{u}\T\mat{H}\vb{u}\big] = \sum_{i,j,k,l} a_i a_j H_{kl}\,(\delta_{ij}\delta_{kl} + \delta_{ik}\delta_{jl} + \delta_{il}\delta_{jk}) = \norm{\vb{a}}^2\tr\mat{H} + 2\,\vb{a}\T\mat{H}\vb{a} \le (\tr\mat{H} + 2\norm{\mat{H}}_2)\norm{\vb{a}}^2.

Substitution gives the bound; the quadratic in η\eta is minimized at the indicated η\eta.

∎

Compare with gradient descent using step 1/∥H∥21/\norm{\mat{H}}_2, which decreases ff by at least ∥∇f∥2/(2∥H∥2)\norm{\grad f}^2/(2\norm{\mat{H}}_2) per step. Their ratio is

tr⁡H+2∥H∥2∥H∥2=r+2,r=tr⁡H∥H∥2∈[1,d],\frac{\tr\mat{H} + 2\norm{\mat{H}}_2}{\norm{\mat{H}}_2} = r + 2, \qquad r = \frac{\tr\mat{H}}{\norm{\mat{H}}_2} \in [1, d],

where rr is the effective rank of curvature. In the worst case, H=L I\mat{H} = L\,\mat{I}, r=dr = d and one zeroth-order step is worth 1/(d+2)1/(d + 2) gradient steps; since it costs two evaluations, matching one gradient step costs about 2(d+2)2(d + 2) evaluations, roughly twice the d+1d + 1 of finite differences. But if curvature is concentrated in few directions, r≪dr \ll d, the factor no longer depends on dimension. This observation, with rr 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 σ\sigma the same rates as gradient methods with a dimension factor in front (up to constants):

Class of ffWith gradientZeroth order, two evaluations per step
convex, LL-smoothO(LR2/ε)\bigO(LR^2/\eps)O(d LR2/ε)\bigO(d\,LR^2/\eps)
μ\mu-strongly convex, LL-smoothO(κlog⁡(1/ε))\bigO(\kappa\log(1/\eps))O(d κlog⁡(1/ε))\bigO(d\,\kappa\log(1/\eps))
nonconvex, LL-smooth (E∥∇f∥≤ε\E\norm{\grad f} \le \eps)O(LΔ0/ε2)\bigO(L\Delta_0/\eps^2)O(d LΔ0/ε2)\bigO(d\,L\Delta_0/\eps^2)
convex, nonsmooth L0L_0-LipschitzO(L02R2/ε2)\bigO(L_0^2R^2/\eps^2)O(d2L02R2/ε2)\bigO(d^2L_0^2R^2/\eps^2)

Here R=∥x0−x⋆∥R = \norm{\vb{x}_0 - \vb{x}^\star}, Δ0=f(x0)−inf⁡f\Delta_0 = f(\vb{x}_0) - \inf f and κ=L/μ\kappa = L/\mu. The first row is the gradient descent rate for smooth convex functions multiplied by dd. 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 d\sqrt{d} in the rate (that is, dd in the number of evaluations) compared with the SGD rate is unavoidable.

Evolution strategies

Change perspective. Instead of a point x\vb{x} and an estimate of its gradient, think of a search distribution pθp_\theta over Rd\R^d and average objective J(θ)=Ex∼pθ[f(x)]J(\theta) = \E_{\vb{x} \sim p_\theta}[f(\vb{x})]. Minimizing JJ pushes the distribution toward regions where ff is low, and its gradient is obtained with the score function trick, without differentiating ff:

∇θJ(θ)=∇θ∫f(x) pθ(x) ⁣dx=Ex∼pθ[f(x) ∇θlog⁡pθ(x)].\grad_\theta J(\theta) = \grad_\theta\int f(\vb{x})\,p_\theta(\vb{x})\dd\vb{x} = \E_{\vb{x} \sim p_\theta}\big[f(\vb{x})\,\grad_\theta\log p_\theta(\vb{x})\big].

ES with weights w=fw = f 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 m+σε\vb{m} + \sigma\vb{\eps} and m−σε\vb{m} - \sigma\vb{\eps} with the same ε\vb{\eps} cancels all even terms in the Taylor expansion of ff around m\vb{m}: the value f(m)f(\vb{m}) (a free baseline) and curvature σ22ε⊤∇2f ε\tfrac{\sigma^2}{2}\vb{\eps}\T\hess f\,\vb{\eps}. Without it, that curvature term enters the variance even though its mean is zero.

Rank normalization. Replace the 2n2n values of ff with their ranks, rescaled to [−12,12][-\tfrac12, \tfrac12] (the smallest value receives −12-\tfrac12 and the largest +12+\tfrac12). The estimator no longer depends on the scale of ff: it behaves exactly the same with ff, 106f10^6 f or efe^f, 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 g^\hat{\vb{g}} no longer estimates ∇fσ\grad f_\sigma but the gradient of a quantile-transformed version of ff; it remains a descent direction for the probability of improvement, but its magnitude no longer decreases near the minimum, and with fixed η\eta the method keeps oscillating in a ball of radius proportional to η\eta.

Parallelism with shared seeds. Each worker generates its εi\vb{\eps}_i from a seed known to all (the seeding strategy applied to a cluster) and communicates only a scalar, the value of ff. 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 σ\sigma 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 σ\sigma 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 N(m,σ2C)\Normal(\vb{m}, \sigma^2\mat{C}) and learn C\mat{C}.

The coefficients are not tuned: Hansen (2016) gives defaults depending only on dd and λ\lambda, such as λ=4+⌊3ln⁡d⌋\lambda = 4 + \lfloor 3\ln d\rfloor, μ=⌊λ/2⌋\mu = \lfloor\lambda/2\rfloor, wi∝ln⁡λ+12−ln⁡iw_i \propto \ln\frac{\lambda + 1}{2} - \ln i, cσ=μeff+2d+μeff+5c_\sigma = \frac{\mu_{\text{eff}} + 2}{d + \mu_{\text{eff}} + 5}, c1≈2/d2c_1 \approx 2/d^2 and cμ≈2μeff/d2c_\mu \approx 2\mu_{\text{eff}}/d^2 (with large dd), and E∥N(0,I)∥≈d (1−14d+121d2)\E\norm{\Normal(\vb{0}, \mat{I})} \approx \sqrt{d}\,(1 - \frac{1}{4d} + \frac{1}{21d^2}). 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 μ\mu: covariance of successful steps. ∑iwiyi:λyi:λ⊤\sum_i w_i\vb{y}_{i:\lambda}\vb{y}_{i:\lambda}\T is the empirical covariance (centered at the old mean) of selected samples. If good samples appear far away in a direction, C\mat{C} grows in that direction; if only nearby samples survive, it shrinks. On a convex quadratic, C\mat{C} eventually becomes proportional to H−1\mat{H}^{-1}: 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. pc\vb{p}_c accumulates mean steps with exponential forgetting. Since yy⊤=(−y)(−y)⊤\vb{y}\vb{y}\T = (-\vb{y})(-\vb{y})\T, the rank-μ\mu update loses the signs of steps; the path preserves them: if several consecutive steps go in the same direction, pc\vb{p}_c grows in it and term pcpc⊤\vb{p}_c\vb{p}_c\T stretches C\mat{C} along the valley well before empirical covariance would.
  • Cumulative step-size adaptation (CSA). pσ\vb{p}_\sigma is the same path, but measured in coordinates where the distribution is a sphere (C−1/2yw\mat{C}^{-1/2}\vb{y}_w). If selection were random, pσ\vb{p}_\sigma would be distributed as N(0,I)\Normal(\vb{0}, \mat{I}) and its norm would average E∥N(0,I)∥\E\norm{\Normal(\vb{0}, \mat{I})}. If it is longer, steps reinforce one another: fewer larger steps could have reached the same point, and σ\sigma grows. If shorter, steps cancel, oscillation occurs, and σ\sigma decreases.
InteractiveCMA-ES learns the valley's shape
Cargando el interactivo…
Each generation shows the λ\lambda samples (the μ\mu selected ones filled), the N(m,σ2C)\Normal(\vb{m}, \sigma^2\mat{C}) ellipse at one and two standard deviations, and the mean-step arrow. On the rotated quadratic (condition number 30), the dashed gray ellipse is the shape of H−1\mat{H}^{-1} with the same area. Play the animation: initially σ=0.25\sigma = 0.25 is too small, the path lengthens and σ\sigma grows; then the ellipse stretches and rotates until it matches H−1\mat{H}^{-1}, and convergence becomes linear. Switch to ‘Step only’ and compare generation counts. On Rosenbrock the ellipse continually reorients to follow the curved valley; enable ‘Follow mean’ at the end to see the distribution at microscopic scale. Change λ\lambda: large populations adapt C\mat{C} in fewer generations but spend more evaluations per generation.

The plot below has two phases. While C\mat{C} does not resemble H−1\mat{H}^{-1}, f(m)f(\vb{m}) falls slowly and κ(C)\kappa(\mat{C}) rises toward κ(H)\kappa(\mat{H}). Once the shape is learned, σ\sigma and f(m)−f⋆f(\vb{m}) - f^\star 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 d=10d = 10 with condition number 10310^3 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 ff. It uses only sample order, like rank-based ES.
  • Invariance to affine changes of search space. If f~(x)=f(Ax+b)\tilde f(\vb{x}) = f(\mat{A}\vb{x} + \vb{b}), CMA-ES on f~\tilde f with transformed initial mean and covariance generates exactly the same transformed samples. Condition number stops mattering once C\mat{C} is learned.
  • Few parameters. Only m0\vb{m}_0 and σ0\sigma_0 need choosing (approximately one quarter of the reasonable variable range). For multimodal functions, the restart variant that doubles λ\lambda (IPOP-CMA-ES) explores at an increasingly coarse scale.

Its limitations are also clear. Sampling costs O(d2)\bigO(d^2) per sample and decomposing C\mat{C} costs O(d3)\bigO(d^3) (done every certain number of generations), and learning a full C\mat{C} requires on the order of d2d^2 evaluations. Above a few thousand variables, diagonal or limited-memory variants, or isotropic ES itself, are used.

The third family estimates nothing: it compares values of ff 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 d+1d + 1 ordered vertices, f(x1)≤⋯≤f(xd+1)f(\vb{x}_1) \le \cdots \le f(\vb{x}_{d+1}), and seek to replace the worst. With the centroid of the others, xˉ=1d∑i≤dxi\bar{\vb{x}} = \frac1d\sum_{i \le d}\vb{x}_i, they try points on the line joining the worst vertex to xˉ\bar{\vb{x}}, x(t)=xˉ+t(xˉ−xd+1)\vb{x}(t) = \bar{\vb{x}} + t(\bar{\vb{x}} - \vb{x}_{d+1}):

  1. Reflection, xr=x(1)\vb{x}_r = \vb{x}(1). If f1≤fr<fdf_1 \le f_r < f_d, accept it.
  2. Expansion, xe=x(2)\vb{x}_e = \vb{x}(2), if reflection improved on the best (fr<f1f_r < f_1): accept the better of xe\vb{x}_e and xr\vb{x}_r.
  3. Outside contraction, x(12)\vb{x}(\tfrac12), if fd≤fr<fd+1f_d \le f_r < f_{d+1}; inside contraction, x(−12)\vb{x}(-\tfrac12), if fr≥fd+1f_r \ge f_{d+1}. Accept if it improves on the point being compared.
  4. Shrink: if contraction fails, move all vertices halfway toward the best.

The simplex stretches in directions where ff 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 ff values at the three vertices converge to the same number. That same year McKinnon constructed the counterexample showing that one cannot demand more.

InteractiveThe creeping simplex
Cargando el interactivo…
Each Nelder-Mead step shows the previous simplex (dashed), trial points on the line through the centroid (r, e, c; rejected ones hollow), the accepted operation in its color and the new simplex, with a trail of earlier ones. The arrow is −∇f-\grad f at the best vertex. Start at McKinnon: all operations are inside contractions, the diameter falls geometrically and ∥∇f∥\norm{\grad f} stays at 1. Enable ‘Follow simplex’ and advance: when the simplex is smaller than one thousandth, contours are nearly horizontal lines and −∇f-\grad f points downward, but the flattened simplex never explores that direction. Switch to pattern search from the same point and compare. Then try Rosenbrock and the quadratic, where Nelder-Mead behaves as expected.

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 ff 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 dd (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 D\mathcal{D} and adds a step-control rule: if any f(x+Δd)<f(x)f(\vb{x} + \Delta\vb{d}) < f(\vb{x}), move there; if none improves, the iteration fails and Δ←Δ/2\Delta \leftarrow \Delta/2. The simplest example is coordinate search (compass search), with D={±e1,…,±ed}\mathcal{D} = \{\pm\vb{e}_1, \dots, \pm\vb{e}_d\}. The only requirement on D\mathcal{D} is that it positively spans Rd\R^d: every vector must be a combination of its elements with nonnegative coefficients. This is equivalent to its cosine measure

κ(D)=min⁡v≠0 max⁡d∈Dv⊤d∥v∥∥d∥\kappa(\mathcal{D}) = \min_{\vb{v} \neq \vb{0}}\ \max_{\vb{d} \in \mathcal{D}} \frac{\vb{v}\T\vb{d}}{\norm{\vb{v}}\norm{\vb{d}}}

being positive: for any direction v\vb{v}, some pattern direction makes an acute angle with it. For {±ei}\{\pm\vb{e}_i\}, κ=1/d\kappa = 1/\sqrt{d} (the worst case is v=(1,…,1)\vb{v} = (1, \dots, 1)).

Proof

If ∇f(x)=0\grad f(\vb{x}) = \vb{0} there is nothing to prove. Otherwise, by the definition of κ\kappa with v=−∇f(x)\vb{v} = -\grad f(\vb{x}) there exists d∈D\vb{d} \in \mathcal{D} with −∇f(x)⊤d≥κ(D)∥∇f(x)∥-\grad f(\vb{x})\T\vb{d} \ge \kappa(\mathcal{D})\norm{\grad f(\vb{x})}. By the descent lemma and the failure of the iteration,

0≤f(x+Δd)−f(x)≤Δ ∇f(x)⊤d+LΔ22≤−Δ κ(D)∥∇f(x)∥+LΔ22.0 \le f(\vb{x} + \Delta\vb{d}) - f(\vb{x}) \le \Delta\,\grad f(\vb{x})\T\vb{d} + \frac{L\Delta^2}{2} \le -\Delta\,\kappa(\mathcal{D})\norm{\grad f(\vb{x})} + \frac{L\Delta^2}{2}.

Dividing by Δ κ(D)>0\Delta\,\kappa(\mathcal{D}) > 0 gives the bound.

∎

The theorem turns Δ\Delta into a certificate: at every failure, the gradient is at most proportional to the step. If the level set {f≤f(x0)}\{f \le f(\vb{x}_0)\} is bounded, iterates live on a lattice (with steps divided by 2) and there can be only finitely many successes at each value of Δ\Delta, so Δk→0\Delta_k \to 0 and, along failed iterations, ∥∇f(xk)∥→0\norm{\grad f(\vb{x}_k)} \to 0: lim inf⁡k∥∇f(xk)∥=0\liminf_k\norm{\grad f(\vb{x}_k)} = 0 (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 (d+1)/N(d + 1)/N and mean cosine with the gradient.

[ ]The estimator and its cost in dimensionBrowser
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 (d+1)/N(d + 1)/N across three orders of magnitude and the mean cosine matches the exact formula. No cosine is negative: as proved, −g-\vb{g} is never an ascent direction.

Now the σ\sigma trade-off with noise. To isolate it from directional error, the same NN directions are fixed for all σ\sigma and compared with the ideal estimator 1N∑i(ui⊤∇f)ui\frac1N\sum_i(\vb{u}_i\T\grad f)\vb{u}_i that those same directions would give without noise and with σ→0\sigma \to 0.

[ ]Choosing sigma: bias versus noiseBrowser
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 ν/σ\nu/\sigma; on the right, truncation bias. The forward estimator has its minimum near σ≈10−2\sigma \approx 10^{-2}, where ν1/2\nu^{1/2} predicts; the antithetic estimator is an order of magnitude more accurate at its optimum, between 10−210^{-2} and 10−110^{-1}, because its truncation error is O(σ2)\bigO(\sigma^2) and it tolerates a larger σ\sigma. The same happens with exact floating-point evaluations, with ν≈10−16∣f∣\nu \approx 10^{-16}\abs{f}.

Now the evaluation count for descent: exact gradient, finite differences and two random points with the theorem step size, η=1/(tr⁡H+2∥H∥2)\eta = 1/(\tr\mat{H} + 2\norm{\mat{H}}_2). Then a problem with effective rank 5 in increasing dimensions.

[ ]The d factor and effective rankBrowser
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 dd (it depends on the condition number, which is 10), while both zeroth-order variants spend evaluations proportional to dd, and random directions need 1.3 to 1.7 times more than finite differences: with smooth noiseless functions they do not beat them. Here r=tr⁡H/∥H∥2=0.55 dr = \tr\mat{H}/\norm{\mat{H}}_2 = 0.55\,d, so the theorem predicts about 2(r+2)≈1.1 d2(r + 2) \approx 1.1\,d evaluations per equivalent gradient step versus d+1d + 1 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 r≈5r \approx 5, the theorem step makes cost a few dozen evaluations in both d=10d = 10 and d=3000d = 3000, whereas the worst-case step 1/((d+2)∥H∥2)1/((d + 2)\norm{\mat{H}}_2) scales with dd.

The evolution strategy with antithetic sampling, with and without ranks, against monotonic transformations and heavy-tailed noise:

[ ]Antithetic ES and centered ranksBrowser
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 g^\hat{\vb{g}} vanishes near the minimum; but the same η\eta makes it diverge with 106f10^6 f or efe^f, and the heavy tail of Cauchy noise derails it. With ranks, the result is identical with ff, 106f10^6 f and efe^f (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 η\eta, because the size of g^\hat{\vb{g}} no longer decreases. CMA-ES solves both at once: it uses ranks and adapts step size.

[ ]Simplified CMA-ESBrowser
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 d=10d = 10 with condition number 10310^3, full CMA-ES reaches f<10−10f < 10^{-10} in about 3200 evaluations; with only σ\sigma control, after 30 00030\,000 evaluations it remains far away. And the last line confirms what the figure showed: C\mat{C} has condition number close to that of H\mat{H} and product CH\mat{C}\mat{H} has condition number of only a few units, that is, C≈c H−1\mat{C} \approx c\,\mat{H}^{-1}.

Finally, Nelder-Mead from scratch, McKinnon’s counterexample and comparison with SciPy:

[ ]Nelder-Mead and McKinnon’s counterexampleBrowser
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 (0,0)(0, 0), where ∥∇f∥=1\norm{\grad f} = 1: 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 d=32d = 32 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 0.010.01, in dimensions 2 to 50. The true (noise-free) value of ff at each method’s returned point is reported.

[ ]Four methods, one budgetBrowser
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 d=2d = 2 to machine precision and adaptive Nelder-Mead reaches 10−810^{-8} even in d=10d = 10, where CMA-ES has not yet finished learning a covariance of 10×1010 \times 10. 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 d=50d = 50 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 σ\sigma, 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:

  1. Choose a seed ss and use it to perturb parameters in place: θ←θ+εz\theta \leftarrow \theta + \eps\vb{z}, generating z∼N(0,I)\vb{z} \sim \Normal(\vb{0}, \mat{I}) tensor by tensor. Evaluate ℓ+\ell_+.
  2. Regenerate z\vb{z} from the same seed and perform θ←θ−2εz\theta \leftarrow \theta - 2\eps\vb{z}. Evaluate ℓ−\ell_-. Regenerate and undo: θ←θ+εz\theta \leftarrow \theta + \eps\vb{z}.
  3. The estimated directional derivative is a single scalar, p=(ℓ+−ℓ−)/(2ε)p = (\ell_+ - \ell_-)/(2\eps). Regenerate z\vb{z} one last time and update θ←θ−η p z\theta \leftarrow \theta - \eta\,p\,\vb{z}.

z\vb{z} 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 dd 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.

[ ]MeZO in miniatureLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ToolMethodWhen
scipy.optimize.minimize(method="Nelder-Mead", options={"adaptive": True})Nelder-Meadd≲10d \lesssim 10, noiseless, as a quick first attempt
scipy.optimize.minimize(method="Powell")derivative-free line searchessmall dd, smooth functions
cma package (Hansen), pycmaCMA-ES with restarts and box constraintsdd from 2 to a few hundred, multimodal, cheap or moderately expensive evaluations
nevergrad (Meta)collection (CMA, ES, DE, PSO) with automatic selectorcompare black-box methods without implementing them
custom implementation, Salimans styleES with shared seedsthousands of cores, large dd, RL
Optuna (TPE), BoTorch, scikit-optimizeBayesian optimizationexpensive evaluations, d≲20d \lesssim 20, 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 ff (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 O(n3)\bigO(n^3)) and dimension (above about 20 variables models become uninformative).

The practical rule summarizing the lesson:

SituationRecommendation
gradient exists and automatic differentiation is availablealways use the gradient
huge dd, cheap parallel evaluations, or limited memoryrandom estimators (ES, ZO-SGD, MeZO)
dd from 2 to a few hundred, no gradient, cheap or moderate evaluationsCMA-ES
d≤5d \le 5, no noise, something needed nowadaptive Nelder-Mead, with multiple starts
derivative-free stationarity guarantee neededpattern search or MADS
expensive evaluations (minutes or hours), d≲20d \lesssim 20Bayesian optimization

Common mistakes

Exercises

ProofThe gradient of the smoothed function
Prove: If ff is measurable with polynomial growth and fσ(x)=E[f(x+σu)]f_\sigma(\vb{x}) = \E[f(\vb{x} + \sigma\vb{u})] with u∼N(0,Id)\vb{u} \sim \Normal(\vb{0}, \mat{I}_d), then ∇fσ(x)=E[(f(x+σu)−f(x))u]/σ\grad f_\sigma(\vb{x}) = \E[(f(\vb{x} + \sigma\vb{u}) - f(\vb{x}))\vb{u}]/\sigma.
0
Let φσ(z)=(2πσ2)−d/2exp⁡(−∥z∥2/(2σ2))\varphi_\sigma(\vb{z}) = (2\pi\sigma^2)^{-d/2}\exp(-\norm{\vb{z}}^2/(2\sigma^2)) denote the density of N(0,σ2I)\Normal(\vb{0}, \sigma^2\mat{I}).

Step 1 of 4. How do you write fσf_\sigma so it can be differentiated without differentiating ff?

NumericThe price of dimension
The variance of the two-point estimator grows proportionally to dimension dd. To obtain the same accuracy in the estimated gradient, how many times more evaluations does a problem with d=104d = 10^4 need than one with d=100d = 100?
CodeES with antithetic sampling and ranks
Implement es_gradient(f, x, sigma, n_pairs, rng), an evolution strategy estimator for minimizing ff (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)
Shift+Enter to run
QuizFive parameters, ten minutes
You want to tune 5 continuous hyperparameters of a strategy. Each backtest takes 10 minutes and you have about 24 hours of computation on one machine. Which method is appropriate?
QuizWhy Nelder-Mead fails
In McKinnon's example, Nelder-Mead converges to (0,0)(0, 0), which is not stationary, although ff is strictly convex and continuously differentiable. What is the underlying reason?
NumericThe default population
How many samples per generation (λ\lambda) does CMA-ES use by default in dimension d=100d = 100?
NumericThe certificate of a failure
A coordinate search with directions {±e1,…,±e4}\{\pm\vb{e}_1, \dots, \pm\vb{e}_4\} in R4\R^4 fails with step Δ=10−3\Delta = 10^{-3} on a function with 1010-Lipschitz gradient. What upper bound does the theorem give for ∥∇f(x)∥\norm{\grad f(\vb{x})}?
QuizWhat ranks cannot see
An ES with antithetic sampling and centered ranks minimizes ff. Which replacements of ff produce exactly the same sequence of iterates (with the same seeds)?

More than one answer may be correct.

Summary

Key idea
Without a gradient, every method pays for information with evaluations: an estimated gradient costs on the order of dd evaluations (or the effective rank of curvature), CMA-ES invests evaluations in learning a preconditioner, direct search compares values on a template, and Bayesian optimization extracts the most from each costly evaluation using a model. Choosing well depends on dimension, noise and cost per evaluation.
  • The two-point estimator f(x+σu)−f(x−σu)2σu\frac{f(\vb{x} + \sigma\vb{u}) - f(\vb{x} - \sigma\vb{u})}{2\sigma}\vb{u} is unbiased for the gradient of Gaussian smoothing fσf_\sigma, which exists even if ff is not differentiable. Its relative squared error is (d+1)/N(d + 1)/N with NN directions.
  • σ\sigma is the resolution at which ff is viewed: small amplifies noise as ν/σ\nu/\sigma, large biases toward fσf_\sigma. The value bias of smoothing is at most Lσ2d/2L\sigma^2d/2.
  • Zeroth-order rates are gradient rates multiplied by dd, and that factor is unavoidable in general; with effective curvature rank rr, the factor is r+2r + 2. 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 C\mat{C} using the covariance of successful steps (rank μ\mu) and path memory (rank one), and σ\sigma by comparing path length to that of a random walk. On quadratics, C\mat{C} tends to be proportional to H−1\mat{H}^{-1}.
  • 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 ∥∇f∥≤LΔ/(2κ)\norm{\grad f} \le L\Delta/(2\kappa).