Beyond minimization: min-max and bilevel problems
Study two structures central to modern machine learning that defy minimization intuition: saddle-point problems (GANs, adversarial training and Lagrangians) and bilevel problems (hyperparameters, meta-learning and optimization layers). See why simultaneous descent-ascent cycles, how extragradient and optimistic gradient correct it, and how to differentiate through an optimum.
After this lesson you can
- State the minimax theorem for convex-concave functions and connect it to Lagrangian duality.
- Prove simultaneous descent-ascent diverges in the bilinear game f(x, y) = xy and alternating descent-ascent fails to converge.
- Implement extragradient and optimistic gradient and explain their convergence on monotone problems.
- Formulate bilevel problems and calculate hypergradients by unrolling and implicit differentiation.
- Differentiate a convex problem solution with respect to parameters through KKT conditions.
Before you start
- 06LagrangianStrong duality and Slater's conditionKarush-Kuhn-Tucker conditionsGradient descentGradient descent dynamics on quadraticsInexact Newton (Newton-CG)Convex function
- 03Implicit function theoremVector-Jacobian product
- 09Reverse-mode automatic differentiation
- 00autograd dynamic graphbackward semantics
Motivation: objectives with two owners
The module has studied one problem, , with variations: constraints, noise, nonsmoothness and scale. But several central pieces of modern machine learning are not minimizations. Their objective has two owners: one wants to decrease what the other wants to increase, or one optimization depends on what the other has already optimized.
- Generative adversarial networks. Generator and discriminator play : the GAN minimax game. Nobody minimizes alone.
- Adversarial robustness. Adversarial training solves : the inner problem seeks the worst perturbation and the outer defends against it.
- Lagrangians. A constrained problem is because the inner maximum equals if violates a constraint and if it satisfies them. Strong duality asks whether the order can be swapped.
- Hyperparameters. Choosing regularization coefficient is with : one optimization inside another. Meta-learning, data reweighting and architecture search share this form.
The first two structures differ. In a min-max problem both players move simultaneously on one function, and the natural solution is equilibrium. A bilevel problem has a hierarchy: the outer level chooses, the inner responds optimally, and the outer pays according to that response. This lesson studies both. Minimization intuition fails spectacularly in games (the obvious method spirals around the solution without approaching it); we fix it by anticipating a step, and differentiate through an without storing the path to it.
Saddle points and the minimax theorem
Define value functions (the worst that can happen to ) and (the minimum can secure). The min-max problem minimizes and its mirror, max-min, maximizes . The two values always have an order.
Proof
For any , . The left side does not depend on and the right does not depend on : taking the supremum over on the left and infimum over on the right gives the inequality.
∎Playing second is never worse: choosing after seeing the opponent’s choice is advantageous. The difference is the minimax gap, and saddle points are exactly what closes it.
Proof
() The definition says and . Chaining with weak inequality gives , so all are equalities and extrema are attained at and . () If then , hence , which is for every ; the other half follows similarly with .
∎Three examples fix the ideas.
The last example illustrates the first existence theorem.
Von Neumann’s version has a two-line proof using known tools. For fixed , , because a linear function attains its maximum on a simplex at a vertex. Thus the left side is linear program and the right is . Writing the first’s dual gives exactly the second, and linear-programming strong duality gives equality. Sion requires far less (quasiconvexity, compactness on only one side), but the message is the same: with convexity for the minimizer and concavity for the maximizer, order does not matter. Without it, as in , it does.
The Lagrangian is a game
For subject to and , Lagrangian satisfies if is feasible and otherwise. Thus the primal problem is , and the dual, maximizing dual function , is . Weak duality, , is literally the weak minimax inequality, and by the preceding theorem:
is a saddle point of iff is primal optimal, is dual optimal, and strong duality holds.
In a differentiable convex problem those three conditions are the KKT conditions. Thus lesson 17’s primal-dual methods alternate a descent step in with an ascent step in multipliers: they find saddle points. The Lagrangian is linear (concave) in and convex in if the problem is convex: convex-concave, the good case.
The game field
To treat both players in one notation, combine variables into and define the game field
Each player wants to move in direction in their coordinates: descends its gradient and ascends its own. An interior saddle satisfies , as a minimum satisfies . The difference is the structure of . Its Jacobian is
In minimization and is a symmetric Hessian: no antisymmetric part. In a game, cross term , measuring how each player’s decision changes the other’s gradient, enters the two blocks with opposite signs, producing an antisymmetric matrix generating rotations: for every , so flow preserves and only rotates. This is the Helmholtz decomposition of a linear field: a potential part (gradient of something) and a rotational part. If is convex in and concave in , symmetric part is positive semidefinite and pushes toward the solution; rotation only circles it.
This positivity has a global version without second derivatives.
Proof
With and , write the four first-order inequalities for convexity in (at and ) and concavity in (at the same points):
Adding all four cancels the left sides entirely and leaves , which is . Strong convexity and concavity add term to each inequality and to the sum.
∎If is a function’s gradient, monotonicity of is exactly convexity of . For a bilinear game , with antisymmetric and always : monotone, but at the boundary, with no force pushing toward the solution.
Descent-ascent: simultaneous and alternating
This is the obvious algorithm and the default when training a GAN with two optimizers. Follow it by hand on the bilinear game. With , and , the simultaneous step is
Matrix is times a rotation: its complex eigenvalues are , of magnitude . Each step rotates by and moves away from the origin.
The proof uses two properties of and is a guided exercise. No step size fixes this: small merely slows the spiral. The cause is geometric. Continuous flow follows circles centered at the origin because . GDA is explicit Euler for that flow, and explicit Euler steps along a circle’s tangent, always landing outside.
The alternating version behaves differently. Its step is , , and the quantity
is exactly conserved: substitution gives and, since , follows. For , is positive definite and its level sets are ellipses: alternating GDA neither diverges nor converges, circling forever. Its iteration matrix has determinant 1 and eigenvalues of magnitude exactly 1. This is symplectic Euler, which preserves energy in mechanics.
The linear criterion: eigenvalues in the complex plane
The bilinear game is extreme, but the diagnosis is general. Near a stationary point with , GDA behaves as and converges locally iff for every eigenvalue of (except equality at the boundary). With ,
In minimization is a symmetric Hessian, eigenvalues are real, and the condition reduces to familiar for gradient descent on quadratics. In a game the antisymmetric part gives eigenvalues imaginary components. The larger relative to , the smaller the step must be, and with purely imaginary eigenvalues (rotation without restoring force) no works. This quantifies the spiral: GDA converges only thanks to the game’s potential part, which rotation erodes.
In the figure, eigenvalue location is what matters. For , trace is and discriminant , vanishing at . Above it the eigenvalues’ real part is , decreasing to 0, and the imaginary part increases to 1. GDA’s maximum step falls from at to 0 at .
When the game is strongly monotone
If the potential part dominates everywhere, GDA converges globally, at a price visible in the constant.
Proof
Expand , bound the cross term by strong monotonicity and the last by the Lipschitz constant, and minimize over .
∎Compare gradient descent on an -strongly convex and -smooth function, with factor : there smoothness gives a bound like (cocoercivity) absent from a rotating field. In a game GDA needs on the order of iterations where minimization needs . With , that is ten thousand versus one hundred.
Extragradient and optimistic gradient
If GDA uses the starting field for a step that should account for rotation, the solution is to look ahead. The proximal point method does so implicitly: , implicit rather than explicit Euler. In the bilinear game, , whose eigenvalues have magnitude : it converges for every . But each step must solve an equation in , a problem of the same nature as the original (better conditioned, but equally implicit). The next two methods approximate it with explicit gradients.
Expand in to see why they work. Linear proximal point is ; extragradient is , agreeing through second order; GDA is , only through first. Term cancels rotation: for the bilinear game, and extragradient is , with eigenvalues and
The best step is , with factor per iteration. In the preceding figure’s stability region, the GDA disk touches the imaginary axis only at the origin, while extragradient’s region contains the whole imaginary segment between and except the origin itself. For bilinear OGDA the two-step recurrence has characteristic polynomial with ; numerically it is stable for , and with its factor is , better than extragradient per gradient evaluation.
Convergence on monotone problems
The linear analysis is local. The global result uses only monotonicity and the Lipschitz constant; its proof shows exactly what the exploratory step gains.
Proof
Let , and . Expanding,
Split the inner product into . The first is by monotonicity and the second is because . Thus
by completing the square. Lipschitz continuity gives and the inequality follows. Summing from to telescopes the distance side and yields the sum bound; the minimum of terms is at most their mean.
∎Comparison with GDA takes one line. For GDA, , and in a bilinear game the middle term is zero (rotation is orthogonal to the radius): only remains, pushing outward. Extragradient converts into . In the bilinear game, with and , the inequality is equality and reproduces factor exactly.
Two standard refinements follow. If is -strongly monotone, combining the proof above with and , using yields : on the order of iterations, not . In the merely monotone case, the mean exploratory point has duality gap on bounded sets, Nemirovski’s (2004) result for mirror-prox, extragradient in Bregman geometry. For OGDA, Daskalakis, Ilyas, Syrgkanis and Zeng (2018) proved last-iterate convergence in bilinear games and proposed it for GAN training.
The variational inequality view
The preceding sections never used that came from a function : only monotonicity and Lipschitz continuity. This suggests the right framework, also connecting to constraints.
Three special cases make this natural. With , the variational inequality is first-order optimality for minimizing over : no feasible direction descends, i.e. does not point into the set. With it is . With and the game field, solutions are saddle points of convex-concave : the inequality in coordinates is optimality of for and in coordinates optimality of for . With constraints, each step is projected onto as in projected gradient, and projected extragradient is , . The previous theorem’s inequality retains the same constant by replacing equality with projection’s variational characterization, for all , and nonexpansiveness.
Gidel, Berard, Vignoud, Vincent and Lacoste-Julien (2019) used this framework to transfer variational-inequality results to GANs: averaged extragradient, extrapolation from the past (OGDA) and stochastic variants. A GAN objective is not convex-concave, so guarantees do not directly apply, but its local structure (Jacobian eigenvalues with large imaginary parts) is exactly this lesson’s, as the lab shows.
Without convexity: what remains
When is not convex-concave, no saddle point may exist, globally or locally, and “does GDA converge?” has no clean answer. Two results guide practice.
- Danskin’s theorem. If is compact, and are continuous in and, for every , maximizer of is unique, then is differentiable with . No derivative of appears: if the maximizer is interior and differentiable, the chain rule multiplies it by (the envelope theorem), and Danskin proves the formula even without differentiability and with a boundary maximizer. Thus if the inner maximizer is solved well, the outer problem minimizes : Madry et al.’s adversarial training does this with a PGD attack as inner maximizer.
- Two timescales. Lin, Jin and Jordan (2020) proved that if is nonconvex in but strongly concave in , GDA with on the order of finds an -stationary point of in iterations. The inner player moves quickly and stays near its best response; the outer descends slowly on . Equal rates have no such guarantee.
Min-max order matters here too: simultaneous-game equilibrium (Nash) and sequential-game equilibrium where commits first (Stackelberg) may differ, and a stationary point of need not be a local saddle. This leads to the lesson’s second half: min-max is a bilevel problem where the inner level maximizes the same objective the outer minimizes.
Lab: games from scratch
First, five methods on the bilinear game, with closed formulas alongside.
import numpy as np
# f(x, y) = x·y. Campo del juego F(z) = (∂f/∂x, −∂f/∂y) = (y, −x)
F = lambda z: np.array([z[1], -z[0]])
grad_x = lambda x, y: y
grad_y = lambda x, y: x
def gda_simultaneo(F, z0, eta, iters):
z = np.array(z0, float); tray = [z.copy()]
for _ in range(iters):
z = z - eta * F(z); tray.append(z.copy())
return np.array(tray)
def gda_alternado(grad_x, grad_y, z0, eta, iters):
x, y = map(float, z0); tray = [(x, y)]
for _ in range(iters):
x = x - eta * grad_x(x, y) # el minimizador mueve primero
y = y + eta * grad_y(x, y) # el maximizador responde al x nuevo
tray.append((x, y))
return np.array(tray)
def extragradiente(F, z0, eta, iters):
z = np.array(z0, float); tray = [z.copy()]
for _ in range(iters):
z_medio = z - eta * F(z) # exploración
z = z - eta * F(z_medio) # paso real con el campo del punto explorado
tray.append(z.copy())
return np.array(tray)
def optimista(F, z0, eta, iters):
z = np.array(z0, float); F_ant = F(z); tray = [z.copy()]
for _ in range(iters):
Fz = F(z)
z = z - 2 * eta * Fz + eta * F_ant # extrapola con el campo del paso anterior
F_ant = Fz; tray.append(z.copy())
return np.array(tray)
def punto_proximal(M, z0, eta, iters): # solo campos lineales F(z) = M z: (I + ηM) z⁺ = z
z = np.array(z0, float); tray = [z.copy()]; A = np.eye(len(z)) + eta * M
for _ in range(iters):
z = np.linalg.solve(A, z); tray.append(z.copy())
return np.array(tray)
eta, K, z0 = 0.1, 100, (1.0, 0.5)
J = np.array([[0.0, 1.0], [-1.0, 0.0]])
trays = {
"GDA simultáneo": (gda_simultaneo(F, z0, eta, K), (1 + eta**2) ** K),
"GDA alternado": (gda_alternado(grad_x, grad_y, z0, eta, K), None),
"extragradiente": (extragradiente(F, z0, eta, K), (1 - eta**2 + eta**4) ** K),
"optimista": (optimista(F, z0, eta, K), None),
"punto proximal": (punto_proximal(J, z0, eta, K), (1 + eta**2) ** -K),
}
print(f"‖z_K‖² / ‖z_0‖² tras K = {K} pasos con η = {eta}")
for nombre, (t, teoria) in trays.items():
r = (t[-1] @ t[-1]) / (t[0] @ t[0])
print(f" {nombre:15s} {r:9.5f}" + (f" fórmula cerrada {teoria:.5f}" if teoria else ""))
t = trays["GDA alternado"][0]
Q = t[:, 0] ** 2 + t[:, 1] ** 2 - eta * t[:, 0] * t[:, 1]
print(f"\nGDA alternado: x² + y² − ηxy entre {Q.min():.12f} y {Q.max():.12f}")
xy = trays["extragradiente"][0].prod(axis=1)
print("extragradiente: signo de f(x_k, y_k) = x_k·y_k en los 40 primeros pasos:", "".join("+" if v > 0 else "−" for v in xy[:40]))Simultaneous GDA multiplies by , exactly as the formula predicts. Alternating preserves up to rounding. Extragradient and proximal point differ in the fourth decimal, versus , because they agree through second order in ; optimistic is comparable with one field evaluation per step. Extragradient value changes sign each quarter turn while converging: the loss warning live.
The next experiment measures the effect of . A quadratic game with and singular values of distributed between and (one zero: no coupling in that direction, only potential force toward the solution) is -strongly monotone and has linear field , so each method’s rate is its iteration matrix’s spectral radius. For each, search a grid for the best and count iterations reducing error by .
import numpy as np
def juego(mu, n=10, seed=0):
r = np.random.default_rng(seed)
Q1, _ = np.linalg.qr(r.normal(size=(n, n))); Q2, _ = np.linalg.qr(r.normal(size=(n, n)))
B = Q1 @ np.diag(np.linspace(0.0, 1.0, n)) @ Q2.T # acoplamiento entre los jugadores
return np.block([[mu * np.eye(n), B], [-B.T, mu * np.eye(n)]]) # F(z) = M z
def factor(lam, metodo, eta):
"""Radio espectral de la iteración lineal, a partir de los autovalores de M."""
w = eta * lam
if metodo == "GDA":
return np.abs(1 - w).max()
if metodo == "EG":
return np.abs(1 - w + w**2).max()
return max(np.abs(np.roots([1, -(1 - 2 * wi), -wi])).max() for wi in w) # OGDA
etas = np.linspace(0.005, 1.5, 300)
print(" μ κ método mejor η factor iteraciones para 1e-6")
for mu in [0.1, 0.03, 0.01]:
M = juego(mu)
lam = np.linalg.eigvals(M)
kappa = np.abs(lam).max() / mu
for metodo in ["GDA", "EG", "OGDA"]:
rho = np.array([factor(lam, metodo, e) for e in etas])
i = rho.argmin()
print(f"{mu:5.2f} {kappa:5.0f} {metodo:5s} {etas[i]:6.3f} {rho[i]:.5f} {np.log(1e6) / -np.log(rho[i]):9.0f}")Dividing by 10, from to , takes GDA from about 2800 iterations to 280000: the factor 100 of . Extragradient goes from about 135 to 1400 and OGDA from 250 to 2400: the factor 10 of . GDA’s best step is exactly , predicted by with : the weaker the potential, the smaller the step needed to keep rotation from winning. Game methods instead keep on the order of regardless of (near 1 for extragradient and for OGDA). An experiment worth trying: change singular values to np.linspace(0.2, 1.0, n); extragradient and OGDA hardly worsen as falls because bilinear coupling without null directions suffices for convergence (in the pure bilinear game their rate depends on , not ); GDA, which diverges there, still needs the potential and pays .
Now a toy 1D GAN. Data are a mixture . The generator has two parameters, positions of its two modes (same width as data), and the discriminator is with nine fixed Gaussians as features. The game is the original GAN’s . Expectations use Gauss–Hermite quadrature, making dynamics deterministic rather than sampling noise.
import numpy as np
import matplotlib.pyplot as plt
nodos, pesos = np.polynomial.hermite_e.hermegauss(16); pesos = pesos / pesos.sum()
sd, centros, ancho = 0.5, np.linspace(-4, 4, 9), 0.8
modos_reales = np.array([-2.0, 2.0])
phi = lambda x: np.exp(-(x[..., None] - centros) ** 2 / (2 * ancho**2))
dphi = lambda x: phi(x) * (-(x[..., None] - centros) / ancho**2)
sigma = lambda t: 1 / (1 + np.exp(-t))
x_real = (modos_reales[:, None] + sd * nodos).ravel(); p_real = np.tile(pesos, 2) / 2
Phi_real = phi(x_real)
def F_gan(z):
"""Campo del juego: F = (∇_m f, −∇_ψ f), con z = (m1, m2, ψ1, ..., ψ9)."""
m, psi = z[:2], z[2:]
xg = m[:, None] + sd * nodos; pg = np.tile(pesos, (2, 1)) / 2
Dr, Dg = sigma(Phi_real @ psi), sigma(phi(xg) @ psi)
grad_psi = (p_real * (1 - Dr)) @ Phi_real - ((pg * Dg)[..., None] * phi(xg)).sum((0, 1))
grad_m = -((pg * Dg) * (dphi(xg) @ psi)).sum(1)
return np.concatenate([grad_m, -grad_psi])
def entrenar(metodo, eta, pasos, z0):
z, F_ant, tray = z0.copy(), F_gan(z0), [z0[:2].copy()]
for _ in range(pasos):
if metodo == "GDA":
z = z - eta * F_gan(z)
elif metodo == "EG":
z = z - eta * F_gan(z - eta * F_gan(z))
else: # OGDA
Fz = F_gan(z); z = z - 2 * eta * Fz + eta * F_ant; F_ant = Fz
tray.append(z[:2].copy())
return np.array(tray)
# jacobiano del campo en el equilibrio (m = ±2, ψ = 0), por diferencias centradas
z_eq = np.concatenate([modos_reales, np.zeros(9)])
Jac = np.column_stack([(F_gan(z_eq + 1e-6 * e) - F_gan(z_eq - 1e-6 * e)) / 2e-6 for e in np.eye(11)])
lam = np.linalg.eigvals(Jac)
lam_c = lam[np.argmax(np.abs(lam.imag))]
print(f"autovalor más rotacional del jacobiano: {lam_c.real:.4f} ± {abs(lam_c.imag):.4f}i")
print(f"GDA estable si η < min 2·Re λ/|λ|² = {min(2 * l.real / abs(l)**2 for l in lam if abs(l) > 1e-8):.3f}")
z0 = np.concatenate([[-0.5, 0.5], np.zeros(9)])
fig, ax = plt.subplots(figsize=(7, 3.2))
for metodo, eta in [("GDA", 0.5), ("GDA", 2.0), ("EG", 2.0), ("OGDA", 2.0)]:
tray = entrenar(metodo, eta, 2000, z0)
err = np.abs(tray - modos_reales).max(axis=1)
print(f"{metodo:4s} η = {eta}: modos finales {np.round(tray[-1], 3)} error {err[-1]:.1e} "
f"oscilación en los 300 últimos pasos {np.ptp(err[-300:]):.1e}")
ax.semilogy(err, label=f"{metodo}, η = {eta}")
ax.set_xlabel("paso"); ax.set_ylabel("error de los modos"); ax.legend(); plt.show()The dominant Jacobian eigenvalue at equilibrium is : imaginary part nine times real, almost pure rotation damped only by discriminator curvature. The linear criterion gives maximum GDA step . With GDA converges slowly with damped oscillations; with it enters a cycle and generator modes dance around without settling, with oscillation . At the same , extragradient and OGDA converge to error . Neither player is poorly designed: the game’s rotational structure is responsible, and the remedy is the method.
Bilevel problems
Almost everything tuned around training has this form:
- Hyperparameters. is training loss regularized by (regularization coefficients, augmentations, even learning rate), and validation loss. Maclaurin, Duvenaud and Adams (2015) tuned thousands of hyperparameters of a full training program this way, and Lorraine, Vicol and Duvenaud (2020) millions.
- Meta-learning. In MAML is shared initialization, the inner problem is a few gradient steps per task, and post-adaptation loss. Here the inner level is defined by an algorithm, not an .
- Data selection and reweighting. are per-example training-loss weights and measures performance on a clean set.
- Architecture search. In DARTS are continuous mixtures between operations and network weights.
- Stackelberg games and min-max. If , the bilevel problem is : the preceding min-max viewed as a leader committing and follower responding.
The outer problem is hard even if the inner is convex: is generally nonconvex, and if inner is nonunique it is not even well-defined (one must choose an optimistic or pessimistic solution). Assume the regular case: for each , has a unique minimizer and an invertible inner Hessian there. Then is differentiable and can be optimized with gradients. The problem reduces to computing the hypergradient :
where derivatives of are evaluated at . The first term is easy; the hard one is solution Jacobian with respect to hyperparameters. Two ways obtain it: differentiate the algorithm computing , or differentiate its defining condition.
Hypergradients: unroll or differentiate implicitly
Unrolling the optimizer
Replace by the result of optimizer steps, from , and differentiate like any computation graph. With reverse-mode differentiation, the backward pass traverses the steps in reverse, propagating adjoint :
Each backward step is a Hessian-vector product, costing about two gradients. Memory is the issue: backward needs at each , so the whole trajectory must be stored, copies of . In PyTorch this happens if the inner loop uses create_graph=True: the dynamic graph retains iterates and intermediates until backward. Three alternatives each have a price: checkpointing stores some iterates and recomputes the rest (binomial checkpointing uses logarithmic memory in in exchange for recomputation); Maclaurin et al.’s reversible learning exactly reverses momentum SGD by storing only bits lost to finite arithmetic; and forward mode propagates forward with memory and no trajectory, but cost proportional to hyperparameter count (Franceschi et al., 2017).
The second issue is subtler. Unrolling gives the exact derivative of , a different function. If is small, is far from , and truncation itself regularizes (early stopping): the truncated objective’s hypergradient may look nothing like the true objective’s.
Differentiating the optimum
The other route ignores the algorithm. The optimum satisfies for every , and differentiating that identity gives the Jacobian.
Existence and regularity follow from the implicit function theorem applied to equation , whose Jacobian in is ; the formula follows by differentiating the identity via the chain rule, reconstructed in the guided exercise. This is implicit differentiation of the optimum. Two highlights:
- How was reached does not matter. Newton, L-BFGS, SGD with tricks, or a closed solution are all possible. Only the endpoint is used.
- Operation order determines cost. Never form or Jacobian . First solve adjoint system (one linear system regardless of hyperparameter count), then compute with one vector-Jacobian product, differentiating with respect to the scalar .
Solve without forming using conjugate gradient over Hessian-vector products, exactly as in Newton-CG. Memory is a few vectors the size of , independent of inner optimizer steps. A cheaper, cruder alternative is the Neumann series: if is positive definite and , , and truncating at terms gives , needing only Hessian-vector products without inner products (used by Lorraine et al. for millions of hyperparameters).
The Neumann series connects both approaches. If GD unrolling starts at the optimum, , every iterate is and Jacobian recursion after steps gives : Neumann truncation. Unrolling steps from the optimum matches the order- Neumann approximation. Unrolling from mixes that error with not having reached .
A complete example: ridge
With , the inner problem has closed solution with and . The Hessian is and mixed derivative , so
with the mean squared validation loss. The sign makes sense: increasing shrinks in the metric, and validation improves if shrinking opposes its gradient. The figure compares this exact formula with unrolled GD steps from (fixed step ), and the implicit formula evaluated at instead of .
Three observations. First, the orange curve is below gray throughout the left side, around versus ridge’s minimum . Ten GD steps from zero regularize better than any , and near the truncated objective barely depends on : its slope is small and positive. Unrolling measures that slope exactly; it is simply another problem’s slope. Second, the relative-error chart: implicit error closely tracks inner-problem error (first-order proportional), while unrolled error falls more slowly because it also inherits the Jacobian accumulated from . Third, cost: at similar accuracy reverse-mode unrolling stores parameter-vector copies. For a float32 model with parameters each copy occupies GB, and with the trajectory alone takes 40 GB; implicit CG fits in a few copies.
From scratch: four hypergradients
The cell implements exact implicit differentiation, unrolling with a hand-written backward pass (storing the trajectory like autodiff), and implicit differentiation with the system solved by CG or Neumann, comparing them with finite differences.
import numpy as np
r = np.random.default_rng(3)
n, d, nv = 30, 12, 200
w_real = r.normal(size=d) * np.linspace(1.5, 0.1, d)
X = r.normal(size=(n, d)); y = X @ w_real + 1.5 * r.normal(size=n)
Xv = r.normal(size=(nv, d)); yv = Xv @ w_real + 1.5 * r.normal(size=nv)
A, b = X.T @ X / n, X.T @ y / n
H = lambda lam: A + lam * np.eye(d) # hessiana del problema interior
val = lambda w: 0.5 * np.mean((Xv @ w - yv) ** 2) # F(w): pérdida de validación
gval = lambda w: Xv.T @ (Xv @ w - yv) / nv
w_opt = lambda lam: np.linalg.solve(H(lam), b)
def hg_implicito(lam, w, resolver):
v = resolver(H(lam), gval(w)) # sistema adjunto H v = ∇_w F
return -(w @ v) # ∂²g/∂λ∂w = w
exacto = lambda M, g: np.linalg.solve(M, g)
def cg(M, g, m):
x = np.zeros_like(g); res = g.copy(); p = res.copy()
for _ in range(m):
Mp = M @ p; a = (res @ res) / (p @ Mp)
x += a * p; nr = res - a * Mp
p = nr + (nr @ nr) / (res @ res) * p; res = nr
return x
def neumann(M, g, m, alfa):
x = np.zeros_like(g); t = g.copy()
for _ in range(m):
x += alfa * t; t = t - alfa * (M @ t)
return x
def hg_desenrollado(lam, K, alfa):
# hacia delante: guarda la trayectoria entera (K + 1 copias de w)
ws = [np.zeros(d)]
for _ in range(K):
ws.append(ws[-1] - alfa * (H(lam) @ ws[-1] - b))
# hacia atrás: adjunto de w y acumulador del hipergradiente
w_bar, lam_bar = gval(ws[-1]), 0.0
for t in range(K - 1, -1, -1):
lam_bar += -alfa * (ws[t] @ w_bar) # ∂w_{t+1}/∂λ = −α w_t
w_bar = w_bar - alfa * (H(lam) @ w_bar) # ∂w_{t+1}/∂w_t = I − α H
return lam_bar, ws[-1]
lam = 0.1
dif = (val(w_opt(lam + 1e-6)) - val(w_opt(lam - 1e-6))) / 2e-6
ref = hg_implicito(lam, w_opt(lam), exacto)
print(f"λ = {lam}: diferencias finitas {dif:.6f} implícito exacto {ref:.6f}")
alfa = 1 / (np.linalg.eigvalsh(A).max() + 10)
print("\n K desenrollado err. rel. implícito en w_K err. rel. floats guardados")
for K in [10, 30, 100, 300, 1000]:
u, wK = hg_desenrollado(lam, K, alfa)
im = hg_implicito(lam, wK, exacto)
print(f"{K:5d} {u:+.5f} {abs(u - ref) / abs(ref):.1e} {im:+.5f} {abs(im - ref) / abs(ref):.1e} {(K + 1) * d:6d}")
print("\nsistema adjunto con m pasos (w exacto):")
alfa_n = 1 / np.linalg.eigvalsh(H(lam)).max()
for m in [2, 5, 10, 20, 50]:
c = hg_implicito(lam, w_opt(lam), lambda M, g: cg(M, g, m))
nn = hg_implicito(lam, w_opt(lam), lambda M, g: neumann(M, g, m, alfa_n))
print(f" m = {m:2d} CG {abs(c - ref) / abs(ref):.1e} Neumann {abs(nn - ref) / abs(ref):.1e}")
print(f"número de condición de H: {np.linalg.cond(H(lam)):.2f}")With other data the story matches the figure: with and both estimators have errors from 70 % to 500 %; with implicit is already at and unrolled at ; unrolling memory grows with . In the second table the inner solution is exact and only the adjoint system is approximated: CG with steps is exact (in exact arithmetic it terminates in steps), while Neumann converges at linear rate and with still has error . Thus CG is default when is symmetric positive definite, and Neumann is reserved for when it is not or fixed per-step cost is desired.
PyTorch version: one λ per variable group
One hyperparameter permits grid search. With several the grid explodes and hypergradients shine. The next cell tunes logistic regression with 40 variables in 4 groups of 10 (only the first two carry signal, the second weak), and one regularization coefficient per group. Newton solves the inner problem (the logistic Hessian is cheap at ); CG solves hypergradients using double-backprop Hessian-vector products without forming the Hessian. It runs on CPU in seconds.
import time, numpy as np, torch
torch.manual_seed(0); torch.set_default_dtype(torch.float64)
t_inicio = time.time() # todo en la CPU: el problema es pequeño
d, G = 40, 4
grupo = torch.arange(d) // 10
w_real = torch.zeros(d); w_real[:10] = 1.0; w_real[10:20] = 0.3
def muestra(n):
X = torch.randn(n, d)
y = (torch.rand(n) < torch.sigmoid(X @ w_real)).double()
return X, y
Xtr, ytr = muestra(80); Xva, yva = muestra(400); Xte, yte = muestra(4000)
perdida = lambda w, X, y: torch.nn.functional.binary_cross_entropy_with_logits(X @ w, y)
def g(w, s): # interior: logística + L2 por grupo
return perdida(w, Xtr, ytr) + 0.5 * (torch.exp(s)[grupo] * w * w).sum()
def resolver_interior(s, w0=None, iters=8):
"""Newton con la hessiana de la logística, Xᵀ diag(p(1 − p)) X / n + diag(λ)."""
w = torch.zeros(d) if w0 is None else w0.clone()
lam = torch.exp(s)[grupo]
for _ in range(iters):
p = torch.sigmoid(Xtr @ w)
gr = Xtr.T @ (p - ytr) / len(ytr) + lam * w
H = (Xtr.T * (p * (1 - p))) @ Xtr / len(ytr) + torch.diag(lam)
w = w - torch.linalg.solve(H, gr)
return w
def hvp(w, s, v): # producto hessiana-vector por doble backward
w = w.detach().requires_grad_(True)
gw, = torch.autograd.grad(g(w, s), w, create_graph=True)
Hv, = torch.autograd.grad(gw @ v, w)
return Hv
def cg(mv, b, iters=30, tol=1e-12):
x = torch.zeros_like(b); r = b.clone(); p = r.clone(); rr = r @ r
for _ in range(iters):
Ap = mv(p); a = rr / (p @ Ap); x = x + a * p; r = r - a * Ap
rr_nuevo = r @ r
if rr_nuevo.sqrt() < tol: break
p = r + (rr_nuevo / rr) * p; rr = rr_nuevo
return x
def hipergradiente_implicito(s, w):
w = w.detach().requires_grad_(True)
gF, = torch.autograd.grad(perdida(w, Xva, yva), w) # ∇_w F (F no depende de s directamente)
v = cg(lambda u: hvp(w, s, u), gF) # v = H⁻¹ ∇_w F sin formar H
s_ = s.detach().requires_grad_(True)
gw, = torch.autograd.grad(g(w, s_), w, create_graph=True)
mezcla, = torch.autograd.grad(gw @ v, s_) # ∇²_{s w} g · v con un solo VJP
return -mezcla
def hipergradiente_desenrollado(s, K, alfa=0.5):
s_ = s.detach().requires_grad_(True); w = torch.zeros(d, requires_grad=True)
for _ in range(K): # el grafo retiene los K iterados
gw, = torch.autograd.grad(g(w, s_), w, create_graph=True)
w = w - alfa * gw
hg, = torch.autograd.grad(perdida(w, Xva, yva), s_)
return hg
# 1) el hipergradiente en un punto, contra diferencias finitas y contra el desenrollado
s0 = torch.full((G,), np.log(0.05))
w0 = resolver_interior(s0)
hg = hipergradiente_implicito(s0, w0)
h = 1e-5; dif = torch.zeros(G)
for k in range(G):
e = torch.zeros(G); e[k] = h
dif[k] = (perdida(resolver_interior(s0 + e, w0), Xva, yva) - perdida(resolver_interior(s0 - e, w0), Xva, yva)) / (2 * h)
print("implícito :", np.round(hg.numpy(), 5))
print("dif. finitas :", np.round(dif.numpy(), 5))
for K in [10, 50, 200]:
u = hipergradiente_desenrollado(s0, K)
print(f"desenrollado K={K:3d}:", np.round(u.numpy(), 5), f" error rel. {((u - hg).norm() / hg.norm()).item():.1e}")
# 2) optimizar los 4 hiperparámetros (en escala logarítmica) con Adam sobre el hipergradiente
s = s0.clone().requires_grad_(True); w = w0
opt = torch.optim.Adam([s], lr=0.2)
for it in range(60):
w = resolver_interior(s.detach(), w, iters=3) # arranque en caliente
opt.zero_grad(); s.grad = hipergradiente_implicito(s.detach(), w); opt.step()
s = s.detach(); w = resolver_interior(s, w)
print("\nhipergradiente final:", np.round(hipergradiente_implicito(s, w).numpy(), 5))
print("λ por grupo aprendidos:", np.round(torch.exp(s).numpy(), 4))
# 3) búsqueda en rejilla con un único λ compartido
mejor = None
for lam in np.logspace(-3, 1, 25):
wl = resolver_interior(torch.full((G,), np.log(lam)))
v = perdida(wl, Xva, yva).item()
if mejor is None or v < mejor[0]: mejor = (v, lam, wl)
print(f"rejilla (λ común): λ = {mejor[1]:.4f} validación {mejor[0]:.4f} prueba {perdida(mejor[2], Xte, yte).item():.4f}")
print(f"λ por grupo: validación {perdida(w, Xva, yva).item():.4f} prueba {perdida(w, Xte, yte).item():.4f}")
print(f"tiempo total: {time.time() - t_inicio:.1f} s")npm run lab and open the connection link.The implicit hypergradient matches finite differences to all five printed decimals; unrolling from with has 84 % error, with 26 %, and with %. After 60 Adam steps on , the hypergradient is on the order of and learned coefficients tell the data’s story: for strong signal, for weak, and around 4 for both noise groups, nearly suppressing them. Test-set loss, unseen by the procedure, drops from with the best shared grid to . Four hyperparameters already make a grid of points; the hypergradient costs the same for four as four million.
Differentiable optimization layers
Implicit differentiation is not limited to conditions of form . Any optimum characterization as the solution of an equation system works: if Jacobian is invertible, . Blondel et al. (2022) made this generic: users write optimality conditions (stationarity, proximal fixed point, KKT), and the library obtains derivatives by autodiff of plus a linear solver. For constraints, KKT is natural.
Consider a parametric quadratic program, OptNet’s layer (Amos and Kolter, 2017):
where groups , potentially network outputs. KKT conditions with multipliers and are , (complementary slackness as an equation) and . Differentiating,
The middle rows explain the derivative. For an inactive constraint (, ), the row says : it does not count. For an active one with it says : the constraint stays active after perturbation. The derivative is that of the equality-constrained QP on the active set. Matrix is invertible under LICQ constraint qualification, strict complementarity (no active constraint with zero multiplier), and second-order sufficient conditions; where a constraint is about to activate, the solution is continuous but nondifferentiable.
Backward does not need the full Jacobian. Given gradient , solve once and obtain gradients for all parameters from products with those vectors: for example , and . This is the same adjoint system as hypergradient , now constrained. OptNet solves QP batches with a primal-dual interior-point method on GPU and reuses the factorization for backward, almost for free.
The cell implements KKT differentiation for a general QP and tests Euclidean projection onto the simplex, , called sparsemax in learning (a softmax alternative producing exactly zero probabilities). Its Jacobian has closed form , with the indicator of support .
import numpy as np
def sparsemax(theta):
"""Proyección euclídea sobre el símplex: z = max(θ − τ, 0) con el umbral τ que hace sumar 1."""
s = np.sort(theta)[::-1]; cs = np.cumsum(s)
k = np.arange(1, len(theta) + 1)
kz = k[1 + k * s > cs][-1]
tau = (cs[kz - 1] - 1) / kz
return np.maximum(theta - tau, 0), tau
def matriz_kkt(Q, G, h, A, z, lam):
ni, ne = len(h), A.shape[0]
return np.block([
[Q, G.T, A.T],
[np.diag(lam) @ G, np.diag(G @ z - h), np.zeros((ni, ne))],
[A, np.zeros((ne, ni)), np.zeros((ne, ne))],
])
def jacobianos_kkt(Q, G, h, A, z, lam):
"""dz/dq, dz/dh y dz/db del QP min ½zᵀQz + qᵀz s.a. Gz ≤ h, Az = b."""
nz, ni, ne = len(z), len(h), A.shape[0]
K = matriz_kkt(Q, G, h, A, z, lam)
Rq = np.vstack([np.eye(nz), np.zeros((ni + ne, nz))]) # ∂KKT/∂q
Rh = np.vstack([np.zeros((nz, ni)), -np.diag(lam), np.zeros((ne, ni))]) # ∂KKT/∂h
Rb = np.vstack([np.zeros((nz + ni, ne)), -np.eye(ne)]) # ∂KKT/∂b
sol = np.linalg.solve(K, -np.hstack([Rq, Rh, Rb]))
return sol[:nz, :nz], sol[:nz, nz:nz + ni], sol[:nz, nz + ni:]
theta = np.array([1.2, 0.9, -0.3, 0.7, 0.1])
n = len(theta)
z, tau = sparsemax(theta)
Q, G, h, A = np.eye(n), -np.eye(n), np.zeros(n), np.ones((1, n)) # q = −θ, b = 1
lam = np.where(z == 0, tau - theta, 0.0) # estacionariedad: z − θ − λ + τ·1 = 0
dz_dq, dz_dh, dz_db = jacobianos_kkt(Q, G, h, A, z, lam)
J_kkt = -dz_dq # dz/dθ = −dz/dq
sop = (z > 0).astype(float)
J_cerrado = np.diag(sop) - np.outer(sop, sop) / sop.sum()
J_fd = np.column_stack([(sparsemax(theta + 1e-6 * e)[0] - sparsemax(theta - 1e-6 * e)[0]) / 2e-6 for e in np.eye(n)])
print("z* =", np.round(z, 4), " soporte:", np.flatnonzero(sop), " τ =", round(tau, 4), " multiplicadores λ =", np.round(lam, 4))
print("|J_kkt − J_cerrado| =", f"{np.abs(J_kkt - J_cerrado).max():.1e}", " |J_kkt − J_dif.finitas| =", f"{np.abs(J_kkt - J_fd).max():.1e}")
print(np.round(J_kkt, 3) + 0.0)
print("dz/db (más masa total):", np.round(dz_db.ravel(), 4) + 0.0)
# punto degenerado: θ_5 justo en el umbral, restricción activa con multiplicador nulo
theta_d = theta.copy(); theta_d[4] = tau
z_d, tau_d = sparsemax(theta_d)
lam_d = np.where(z_d == 0, tau_d - theta_d, 0.0)
K_d = matriz_kkt(Q, G, h, A, z_d, lam_d)
print("\nθ_5 = τ: z* =", np.round(z_d, 4), " rango de la matriz KKT:", np.linalg.matrix_rank(K_d), "de", K_d.shape[0])The KKT Jacobian matches the closed formula to rounding and finite differences to . Coordinates outside support have zero derivative (their constraints are active with positive multiplier and remain so after a small perturbation); inside support the Jacobian projects onto zero-sum vectors: raising one component removes mass equally from the other supported ones. At the exact threshold the KKT matrix loses rank and the derivative does not exist: the fold between active sets.
The professional version
For general convex problems, cvxpylayers (Agrawal et al., 2019) turns a parameterized CVXPY problem into a PyTorch or JAX layer. It must satisfy disciplined parametrized programming (DPP) rules, ensuring conversion to a conic program whose data depend affinely on parameters; the layer solves the conic program and differentiates its solution.
import cvxpy as cp
import torch
from cvxpylayers.torch import CvxpyLayer
n, m = 5, 3
x = cp.Variable(n)
A = cp.Parameter((m, n)); b = cp.Parameter(m)
problema = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b) + 0.1 * cp.norm1(x)), [x >= 0])
assert problema.is_dpp()
capa = CvxpyLayer(problema, parameters=[A, b], variables=[x])
A_t = torch.randn(m, n, requires_grad=True); b_t = torch.randn(m, requires_grad=True)
x_opt, = capa(A_t, b_t) # resuelve el problema convexo
x_opt.sum().backward() # gradientes respecto a A y b a través del óptimo
| Tool | What it differentiates | When |
|---|---|---|
| Hand-derived implicit formula + CG | Unconstrained | Continuous hyperparameters, smooth large inner problems |
Unrolling with create_graph=True | Inner algorithm step by step | Few steps (MAML), intentionally unconverged inner solve |
| OptNet | KKT of a QP | Batches of small or medium QPs on GPU |
| cvxpylayers | Conic-program solution | Any DPP problem: LP, QP, SOCP, SDP |
| Generic implicit differentiation (Blondel et al.) | Any written | Proximal operators, fixed points, custom problems |
Common mistakes
Exercises
Step 1 of 4. How is the step written as a matrix?
Step 1 of 4. Which identity do you differentiate with respect to to obtain ?
More than one answer may be correct.
extragradient(F, z0, eta, iters, proj=None) for generic game operator F (array to array). Return (z, z_medio): final iterate and mean exploratory point . If proj is not None, it projects onto the feasible set and applies to both steps: and . Tests check the exact bilinear factor, convergence in a bilinear game in and a box-constrained game whose solution is on the boundary.import numpy as np
def extragradient(F, z0, eta, iters, proj=None):
"""Extragradiente (proyectado si proj no es None). Devuelve (último iterado, media de los puntos de exploración)."""
z = np.array(z0, dtype=float)
# tu código: paso de exploración, paso real y acumulación de la media
return z, zSummary
- A saddle closes the gap between and ; one exists in compact convex-concave games (von Neumann, Sion) but may not otherwise. Lagrangian duality is the special case where the game is the Lagrangian.
- Game field is monotone in the convex-concave case. Its Jacobian has symmetric (potential) and antisymmetric (rotational) parts; GDA converges locally only if for every eigenvalue, impossible for purely imaginary eigenvalues.
- In , simultaneous GDA multiplies by , alternating preserves and extragradient multiplies it by . For strongly monotone games, GDA needs on the order of iterations and extragradient .
- Variational inequalities unify minimization, games and constraints; projection can be added without changing analysis.
- In bilevel optimization hypergradient uses an adjoint system (CG over Hessian-vector products) and a vector-Jacobian product, with memory independent of inner steps. Unrolling differentiates the truncated objective and stores the trajectory.
- Differentiating KKT turns optimization into a differentiable layer (OptNet, cvxpylayers): the derivative is that of the active-constraint problem, and backward is another adjoint system.