Module contents
Lesson 25 of 27Advanced 120 min

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

Motivation: objectives with two owners

The module has studied one problem, min⁡xf(x)\min_{\vb{x}} f(\vb{x}), 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 GθG_\theta and discriminator DψD_\psi play min⁡θmax⁡ψ Ex∼p[log⁡Dψ(x)]+Ez[log⁡(1−Dψ(Gθ(z)))]\min_\theta \max_\psi\ \E_{x \sim p}[\log D_\psi(x)] + \E_{z}[\log(1 - D_\psi(G_\theta(z)))]: the GAN minimax game. Nobody minimizes alone.
  • Adversarial robustness. Adversarial training solves min⁡θE[max⁡∥δ∥≤εℓ(fθ(x+δ),y)]\min_\theta \E\big[\max_{\norm{\delta} \le \eps} \ell(f_\theta(x + \delta), y)\big]: the inner problem seeks the worst perturbation and the outer defends against it.
  • Lagrangians. A constrained problem is min⁡xmax⁡λ≥0,νL(x,λ,ν)\min_{\vb{x}} \max_{\lambda \ge 0, \nu} L(\vb{x}, \lambda, \nu) because the inner maximum equals +∞+\infty if x\vb{x} violates a constraint and f0(x)f_0(\vb{x}) if it satisfies them. Strong duality asks whether the order can be swapped.
  • Hyperparameters. Choosing regularization coefficient λ\lambda is min⁡λLval(w⋆(λ))\min_\lambda \Loss_{\text{val}}(\vb{w}^\star(\lambda)) with w⋆(λ)=arg min⁡wLtrain(w)+λR(w)\vb{w}^\star(\lambda) = \argmin_{\vb{w}} \Loss_{\text{train}}(\vb{w}) + \lambda R(\vb{w}): 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 arg min⁡\argmin without storing the path to it.

Saddle points and the minimax theorem

Define value functions Φ(x)=sup⁡yf(x,y)\Phi(\vb{x}) = \sup_{\vb{y}} f(\vb{x}, \vb{y}) (the worst that can happen to x\vb{x}) and Ψ(y)=inf⁡xf(x,y)\Psi(\vb{y}) = \inf_{\vb{x}} f(\vb{x}, \vb{y}) (the minimum y\vb{y} can secure). The min-max problem minimizes Φ\Phi and its mirror, max-min, maximizes Ψ\Psi. The two values always have an order.

Proof

For any x′,y′\vb{x}', \vb{y}', Ψ(y′)=inf⁡xf(x,y′)≤f(x′,y′)≤sup⁡yf(x′,y)=Φ(x′)\Psi(\vb{y}') = \inf_{\vb{x}} f(\vb{x}, \vb{y}') \le f(\vb{x}', \vb{y}') \le \sup_{\vb{y}} f(\vb{x}', \vb{y}) = \Phi(\vb{x}'). The left side does not depend on x′\vb{x}' and the right does not depend on y′\vb{y}': taking the supremum over y′\vb{y}' on the left and infimum over x′\vb{x}' 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

(⇒\Rightarrow) The definition says Φ(x⋆)=sup⁡yf(x⋆,y)=f(x⋆,y⋆)\Phi(\vb{x}^\star) = \sup_{\vb{y}} f(\vb{x}^\star, \vb{y}) = f(\vb{x}^\star, \vb{y}^\star) and Ψ(y⋆)=inf⁡xf(x,y⋆)=f(x⋆,y⋆)\Psi(\vb{y}^\star) = \inf_{\vb{x}} f(\vb{x}, \vb{y}^\star) = f(\vb{x}^\star, \vb{y}^\star). Chaining with weak inequality gives Ψ(y⋆)≤sup⁡Ψ≤inf⁡Φ≤Φ(x⋆)=Ψ(y⋆)\Psi(\vb{y}^\star) \le \sup \Psi \le \inf \Phi \le \Phi(\vb{x}^\star) = \Psi(\vb{y}^\star), so all are equalities and extrema are attained at x⋆\vb{x}^\star and y⋆\vb{y}^\star. (⇐\Leftarrow) If Φ(x⋆)=Ψ(y⋆)\Phi(\vb{x}^\star) = \Psi(\vb{y}^\star) then Φ(x⋆)=Ψ(y⋆)≤f(x⋆,y⋆)≤Φ(x⋆)\Phi(\vb{x}^\star) = \Psi(\vb{y}^\star) \le f(\vb{x}^\star, \vb{y}^\star) \le \Phi(\vb{x}^\star), hence f(x⋆,y⋆)=Φ(x⋆)f(\vb{x}^\star, \vb{y}^\star) = \Phi(\vb{x}^\star), which is f(x⋆,y)≤f(x⋆,y⋆)f(\vb{x}^\star, \vb{y}) \le f(\vb{x}^\star, \vb{y}^\star) for every y\vb{y}; the other half follows similarly with Ψ\Psi.

∎

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 p\vb{p}, max⁡q∈Δnp⊤Aq=max⁡j(A⊤p)j\max_{\vb{q} \in \Delta_n} \vb{p}\T\mat{A}\vb{q} = \max_j (\mat{A}\T\vb{p})_j, because a linear function attains its maximum on a simplex at a vertex. Thus the left side is linear program min⁡{t:A⊤p≤t1, p∈Δm}\min\{t : \mat{A}\T\vb{p} \le t\vb{1},\ \vb{p} \in \Delta_m\} and the right is max⁡{s:Aq≥s1, q∈Δn}\max\{s : \mat{A}\vb{q} \ge s\vb{1},\ \vb{q} \in \Delta_n\}. 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 (x−y)2(x - y)^2, it does.

The Lagrangian is a game

For min⁡f0(x)\min f_0(\vb{x}) subject to fi(x)≤0f_i(\vb{x}) \le 0 and hj(x)=0h_j(\vb{x}) = 0, Lagrangian L(x,λ,ν)=f0(x)+∑iλifi(x)+∑jνjhj(x)L(\vb{x}, \lambda, \nu) = f_0(\vb{x}) + \sum_i \lambda_i f_i(\vb{x}) + \sum_j \nu_j h_j(\vb{x}) satisfies sup⁡λ≥0,νL(x,λ,ν)=f0(x)\sup_{\lambda \ge 0, \nu} L(\vb{x}, \lambda, \nu) = f_0(\vb{x}) if x\vb{x} is feasible and +∞+\infty otherwise. Thus the primal problem is p⋆=inf⁡xsup⁡λ≥0,νLp^\star = \inf_{\vb{x}} \sup_{\lambda \ge 0, \nu} L, and the dual, maximizing dual function inf⁡xL\inf_{\vb{x}} L, is d⋆=sup⁡λ≥0,νinf⁡xLd^\star = \sup_{\lambda \ge 0, \nu} \inf_{\vb{x}} L. Weak duality, d⋆≤p⋆d^\star \le p^\star, is literally the weak minimax inequality, and by the preceding theorem:

(x⋆,λ⋆,ν⋆)(\vb{x}^\star, \lambda^\star, \nu^\star) is a saddle point of LL iff x⋆\vb{x}^\star is primal optimal, (λ⋆,ν⋆)(\lambda^\star, \nu^\star) 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 x\vb{x} with an ascent step in multipliers: they find saddle points. The Lagrangian is linear (concave) in (λ,ν)(\lambda, \nu) and convex in x\vb{x} if the problem is convex: convex-concave, the good case.

The game field

To treat both players in one notation, combine variables into z=(x,y)\vb{z} = (\vb{x}, \vb{y}) and define the game field

F(z)=[∇xf(x,y)−∇yf(x,y)].F(\vb{z}) = \begin{bmatrix} \grad_{\vb{x}} f(\vb{x}, \vb{y}) \\ -\grad_{\vb{y}} f(\vb{x}, \vb{y}) \end{bmatrix}.

Each player wants to move in direction −F-F in their coordinates: x\vb{x} descends its gradient and y\vb{y} ascends its own. An interior saddle satisfies F(z⋆)=0F(\vb{z}^\star) = \vb{0}, as a minimum satisfies ∇f=0\grad f = \vb{0}. The difference is the structure of FF. Its Jacobian is

DF=[∇xx2f∇xy2f−∇yx2f−∇yy2f]=[∇xx2f00−∇yy2f]⏟parte simeˊtrica S+[0B−B⊤0]⏟parte antisimeˊtrica A,B=∇xy2f.\mat{D}F = \begin{bmatrix} \hess_{\vb{x}\vb{x}} f & \hess_{\vb{x}\vb{y}} f \\ -\hess_{\vb{y}\vb{x}} f & -\hess_{\vb{y}\vb{y}} f \end{bmatrix} = \underbrace{\begin{bmatrix} \hess_{\vb{x}\vb{x}} f & \mat{0} \\ \mat{0} & -\hess_{\vb{y}\vb{y}} f \end{bmatrix}}_{\text{parte simétrica } \mat{S}} + \underbrace{\begin{bmatrix} \mat{0} & \mat{B} \\ -\mat{B}\T & \mat{0} \end{bmatrix}}_{\text{parte antisimétrica } \mat{A}}, \qquad \mat{B} = \hess_{\vb{x}\vb{y}} f.

In minimization F=∇fF = \grad f and DF\mat{D}F is a symmetric Hessian: no antisymmetric part. In a game, cross term B\mat{B}, measuring how each player’s decision changes the other’s gradient, enters the two blocks with opposite signs, producing an antisymmetric matrix generating rotations: z⊤Az=0\vb{z}\T\mat{A}\vb{z} = 0 for every z\vb{z}, so flow z˙=−Az\dot{\vb{z}} = -\mat{A}\vb{z} preserves ∥z∥\norm{\vb{z}} and only rotates. This is the Helmholtz decomposition of a linear field: a potential part (gradient of something) and a rotational part. If ff is convex in x\vb{x} and concave in y\vb{y}, symmetric part S\mat{S} is positive semidefinite and pushes toward the solution; rotation only circles it.

This positivity has a global version without second derivatives.

Proof

With z=(x,y)\vb{z} = (\vb{x}, \vb{y}) and z′=(x′,y′)\vb{z}' = (\vb{x}', \vb{y}'), write the four first-order inequalities for convexity in x\vb{x} (at (x,y)(\vb{x}, \vb{y}) and (x′,y′)(\vb{x}', \vb{y}')) and concavity in y\vb{y} (at the same points):

f(x′,y)−f(x,y)≥⟨∇xf(z),x′−x⟩,f(x,y′)−f(x′,y′)≥⟨∇xf(z′),x−x′⟩,f(x,y)−f(x,y′)≥⟨∇yf(z),y−y′⟩,f(x′,y′)−f(x′,y)≥⟨∇yf(z′),y′−y⟩.\begin{aligned} f(\vb{x}', \vb{y}) - f(\vb{x}, \vb{y}) &\ge \inner{\grad_{\vb{x}} f(\vb{z})}{\vb{x}' - \vb{x}}, & f(\vb{x}, \vb{y}') - f(\vb{x}', \vb{y}') &\ge \inner{\grad_{\vb{x}} f(\vb{z}')}{\vb{x} - \vb{x}'}, \\ f(\vb{x}, \vb{y}) - f(\vb{x}, \vb{y}') &\ge \inner{\grad_{\vb{y}} f(\vb{z})}{\vb{y} - \vb{y}'}, & f(\vb{x}', \vb{y}') - f(\vb{x}', \vb{y}) &\ge \inner{\grad_{\vb{y}} f(\vb{z}')}{\vb{y}' - \vb{y}}. \end{aligned}

Adding all four cancels the left sides entirely and leaves 0≥−⟨∇xf(z)−∇xf(z′),x−x′⟩+⟨∇yf(z)−∇yf(z′),y−y′⟩0 \ge -\inner{\grad_{\vb{x}} f(\vb{z}) - \grad_{\vb{x}} f(\vb{z}')}{\vb{x} - \vb{x}'} + \inner{\grad_{\vb{y}} f(\vb{z}) - \grad_{\vb{y}} f(\vb{z}')}{\vb{y} - \vb{y}'}, which is ⟨F(z)−F(z′),z−z′⟩≥0\inner{F(\vb{z}) - F(\vb{z}')}{\vb{z} - \vb{z}'} \ge 0. Strong convexity and concavity add term μ2∥⋅∥2\tfrac{\mu}{2}\norm{\cdot}^2 to each inequality and μ∥x−x′∥2+μ∥y−y′∥2\mu\norm{\vb{x} - \vb{x}'}^2 + \mu\norm{\vb{y} - \vb{y}'}^2 to the sum.

∎

If F=∇ϕF = \grad\phi is a function’s gradient, monotonicity of FF is exactly convexity of ϕ\phi. For a bilinear game f=x⊤Byf = \vb{x}\T\mat{B}\vb{y}, F(z)=AzF(\vb{z}) = \mat{A}\vb{z} with antisymmetric A\mat{A} and always ⟨F(z)−F(z′),z−z′⟩=0\inner{F(\vb{z}) - F(\vb{z}')}{\vb{z} - \vb{z}'} = 0: 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 f(x,y)=xyf(x, y) = xy, ∇xf=y\grad_x f = y and ∇yf=x\grad_y f = x, the simultaneous step is

[xk+1yk+1]=[1−ηη1][xkyk]=(I−ηJ) zk,J=[01−10].\begin{bmatrix} x_{k+1} \\ y_{k+1} \end{bmatrix} = \begin{bmatrix} 1 & -\eta \\ \eta & 1 \end{bmatrix} \begin{bmatrix} x_k \\ y_k \end{bmatrix} = (\mat{I} - \eta\mat{J})\,\vb{z}_k, \qquad \mat{J} = \begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}.

Matrix I−ηJ\mat{I} - \eta\mat{J} is 1+η2\sqrt{1 + \eta^2} times a rotation: its complex eigenvalues are 1±iη1 \pm i\eta, of magnitude 1+η2>1\sqrt{1 + \eta^2} > 1. Each step rotates by arctan⁡η\arctan\eta and moves away from the origin.

The proof uses two properties of J\mat{J} and is a guided exercise. No step size fixes this: small η\eta merely slows the spiral. The cause is geometric. Continuous flow z˙=−F(z)=(−y,x)\dot{\vb{z}} = -F(\vb{z}) = (-y, x) follows circles centered at the origin because  ⁣d ⁣dt∥z∥2=−2 z⊤Jz=0\tfrac{\dd}{\dd t}\norm{\vb{z}}^2 = -2\,\vb{z}\T\mat{J}\vb{z} = 0. 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 xk+1=xk−ηykx_{k+1} = x_k - \eta y_k, yk+1=yk+ηxk+1y_{k+1} = y_k + \eta x_{k+1}, and the quantity

Q(x,y)=x2+y2−η xyQ(x, y) = x^2 + y^2 - \eta\,xy

is exactly conserved: substitution gives Q(xk+1,yk+1)=xk+12+yk2+ηxk+1ykQ(x_{k+1}, y_{k+1}) = x_{k+1}^2 + y_k^2 + \eta x_{k+1}y_k and, since xk+1(xk+1+ηyk)=xk+1xk=xk2−ηxkykx_{k+1}(x_{k+1} + \eta y_k) = x_{k+1}x_k = x_k^2 - \eta x_k y_k, Q(xk,yk)Q(x_k, y_k) follows. For η<2\eta < 2, QQ is positive definite and its level sets are ellipses: alternating GDA neither diverges nor converges, circling forever. Its iteration matrix [1−ηη1−η2]\begin{bmatrix} 1 & -\eta \\ \eta & 1 - \eta^2 \end{bmatrix} has determinant 1 and eigenvalues of magnitude exactly 1. This is symplectic Euler, which preserves energy in mechanics.

InteractiveThe descent-ascent spiral
  • field −F(z)=(−y,x)-F(\vb{z}) = (-y, x)
  • continuous-flow orbit
Distance to saddle point, ∥zk∥/∥z0∥\|\vb{z}_k\| / \|\vb{z}_0\| on a logarithmic scale
0.25
Methods
k = 60
∥zk∥/∥z0∥\|\vb{z}_k\| / \|\vb{z}_0\| · per-step factor ρ\rho
Simultaneous GDA, ρ=1+η2\rho = \sqrt{1 + \eta^2}6.164 · 1.0308
Alternating GDA, ρ=1\rho = 10.925 · 1.0000
Extragradient, ρ=1−η2+η4\rho = \sqrt{1 - \eta^2 + \eta^4}0.163 · 0.9703
Optimistic gradient0.135 · 0.9659
The game f(x,y)=xyf(x, y) = xy with unique saddle z⋆=0\vb{z}^\star = \vb{0}. Gray arrows are −F(z)=(−y,x)-F(\vb{z}) = (-y, x), the players' desired direction: pure swirl with no component toward the center. From the same z0\vb{z}_0, simultaneous GDA (red) spirals outward; alternating GDA (orange) circles an ellipse without approaching; extragradient (aqua) and optimistic gradient (violet) spiral inward. The distance chart shows ∥zk∥/∥z0∥\norm{\vb{z}_k}/\norm{\vb{z}_0} logarithmically: each method is a line whose slope is the log of its per-step factor, shown in readings (alternating oscillates around 1 because it preserves an ellipse, not a circle). Increase η\eta: red shoots up, and above η≈0.58\eta \approx 0.58 violet diverges too. Enable the proximal point (blue) and compare extragradient.

The linear criterion: eigenvalues in the complex plane

The bilinear game is extreme, but the diagnosis is general. Near a stationary point z⋆\vb{z}^\star with M=DF(z⋆)\mat{M} = \mat{D}F(\vb{z}^\star), GDA behaves as zk+1−z⋆≈(I−ηM)(zk−z⋆)\vb{z}_{k+1} - \vb{z}^\star \approx (\mat{I} - \eta\mat{M})(\vb{z}_k - \vb{z}^\star) and converges locally iff ∣1−ηλ∣<1\abs{1 - \eta\lambda} < 1 for every eigenvalue λ\lambda of M\mat{M} (except equality at the boundary). With λ=a+bi\lambda = a + bi,

∣1−ηλ∣2=1−2ηa+η2(a2+b2)<1  ⟺  a>0  y  η<2aa2+b2=2Re⁡λ∣λ∣2.\abs{1 - \eta\lambda}^2 = 1 - 2\eta a + \eta^2(a^2 + b^2) < 1 \iff a > 0 \ \text{ y } \ \eta < \frac{2a}{a^2 + b^2} = \frac{2\operatorname{Re}\lambda}{\abs{\lambda}^2}.

In minimization M\mat{M} is a symmetric Hessian, eigenvalues are real, and the condition reduces to familiar η<2/λmax⁡\eta < 2/\lambda_{\max} for gradient descent on quadratics. In a game the antisymmetric part gives eigenvalues imaginary components. The larger ∣Im⁡λ∣\abs{\operatorname{Im}\lambda} relative to Re⁡λ\operatorname{Re}\lambda, the smaller the step must be, and with purely imaginary eigenvalues (rotation without restoring force) no η>0\eta > 0 works. This quantifies the spiral: GDA converges only thanks to the game’s potential part, which rotation erodes.

InteractivePotential versus rotation
Game plane: field and trajectories
Complex plane: ηλ\eta\lambda and stability regions
  • GDA: region ∣1−ηλ∣<1|1 - \eta\lambda| < 1
  • extragradient: ∣1−ηλ+η2λ2∣<1|1 - \eta\lambda + \eta^2\lambda^2| < 1
  • ηλ\eta\lambda for α∈[0,1]\alpha \in [0, 1]
  • current eigenvalues
0.600
0.50
Trajectories
Eigenvalues of Mα\mat{M}_\alpha0.250 + 0.581i, 0.250 − 0.581i
GDA per-step factor0.9220
Extragradient per-step factor0.8352
Largest stable η\eta for GDA1.250
Eigenvalue collision atα* = 0.2727
Complex eigenvalues: trajectories rotate. GDA converges only if η<1.250\eta < 1.250.
The game fα(x,y)=(1−α)(12x2−18y2)+α xyf_\alpha(x, y) = (1 - \alpha)\big(\tfrac12 x^2 - \tfrac18 y^2\big) + \alpha\,xy mixes a potential game (α=0\alpha = 0: the field is the gradient of 12x2+18y2\tfrac12 x^2 + \tfrac18 y^2) with the bilinear game (α=1\alpha = 1). Its field is F(z)=MαzF(\vb{z}) = \mat{M}_\alpha\vb{z}. In game space, the field and GDA (red) and extragradient (aqua) trajectories; in the complex plane, eigenvalues of Mα\mat{M}_\alpha multiplied by η\eta, against each method's convergence region. At α=0\alpha = 0 eigenvalues are real, 11 and 0.250.25, and trajectories are straight without rotation. Increase α\alpha: at α⋆=3/11\alpha^\star = 3/11 eigenvalues collide and leave the real axis as a complex pair, and paths start rotating. At initial α=0.6\alpha = 0.6, GDA still converges (factor 0.9220.922); increase η\eta above 1.251.25 and the red point leaves the disk. Set α\alpha to 1: the pair reaches the imaginary axis, outside the disk for every η\eta, but inside the extragradient region while η<1\eta < 1.

In the figure, eigenvalue location is what matters. For Mα=[1−αα−α14(1−α)]\mat{M}_\alpha = \begin{bmatrix} 1 - \alpha & \alpha \\ -\alpha & \tfrac14(1 - \alpha) \end{bmatrix}, trace is 54(1−α)\tfrac54(1 - \alpha) and discriminant 916(1−α)2−4α2\tfrac{9}{16}(1 - \alpha)^2 - 4\alpha^2, vanishing at α⋆=3/11\alpha^\star = 3/11. Above it the eigenvalues’ real part is 58(1−α)\tfrac58(1 - \alpha), decreasing to 0, and the imaginary part increases to 1. GDA’s maximum step 2Re⁡λ/∣λ∣22\operatorname{Re}\lambda/\abs{\lambda}^2 falls from 1.251.25 at α=0.6\alpha = 0.6 to 0 at α=1\alpha = 1.

When the game is strongly monotone

If the potential part dominates everywhere, GDA converges globally, at a price visible in the constant.

Proof

Expand ∥zk−ηF(zk)−z⋆∥2=∥zk−z⋆∥2−2η⟨F(zk)−F(z⋆),zk−z⋆⟩+η2∥F(zk)−F(z⋆)∥2\norm{\vb{z}_k - \eta F(\vb{z}_k) - \vb{z}^\star}^2 = \norm{\vb{z}_k - \vb{z}^\star}^2 - 2\eta\inner{F(\vb{z}_k) - F(\vb{z}^\star)}{\vb{z}_k - \vb{z}^\star} + \eta^2\norm{F(\vb{z}_k) - F(\vb{z}^\star)}^2, bound the cross term by strong monotonicity and the last by the Lipschitz constant, and minimize 1−2ημ+η2L21 - 2\eta\mu + \eta^2L^2 over η\eta.

∎

Compare gradient descent on an μ\mu-strongly convex and LL-smooth function, with factor 1−1/κ1 - 1/\kappa: there smoothness gives a bound like ⟨∇f(x)−∇f(y),x−y⟩≥1L∥∇f(x)−∇f(y)∥2\inner{\grad f(\vb{x}) - \grad f(\vb{y})}{\vb{x} - \vb{y}} \ge \tfrac1L\norm{\grad f(\vb{x}) - \grad f(\vb{y})}^2 (cocoercivity) absent from a rotating field. In a game GDA needs on the order of κ2\kappa^2 iterations where minimization needs κ\kappa. With κ=100\kappa = 100, 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: zk+1=zk−ηF(zk+1)\vb{z}_{k+1} = \vb{z}_k - \eta F(\vb{z}_{k+1}), implicit rather than explicit Euler. In the bilinear game, zk+1=(I+ηJ)−1zk\vb{z}_{k+1} = (\mat{I} + \eta\mat{J})\inv\vb{z}_k, whose eigenvalues have magnitude 1/1+η2<11/\sqrt{1 + \eta^2} < 1: it converges for every η\eta. But each step must solve an equation in zk+1\vb{z}_{k+1}, 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 η\eta to see why they work. Linear proximal point is (I+ηM)−1=I−ηM+η2M2−⋯(\mat{I} + \eta\mat{M})\inv = \mat{I} - \eta\mat{M} + \eta^2\mat{M}^2 - \cdots; extragradient is I−ηM(I−ηM)=I−ηM+η2M2\mat{I} - \eta\mat{M}(\mat{I} - \eta\mat{M}) = \mat{I} - \eta\mat{M} + \eta^2\mat{M}^2, agreeing through second order; GDA is I−ηM\mat{I} - \eta\mat{M}, only through first. Term η2M2\eta^2\mat{M}^2 cancels rotation: for the bilinear game, J2=−I\mat{J}^2 = -\mat{I} and extragradient is (1−η2)I−ηJ(1 - \eta^2)\mat{I} - \eta\mat{J}, with eigenvalues 1−η2±iη1 - \eta^2 \pm i\eta and

∣1−η2±iη∣2=1−η2+η4<1para 0<η<1.\abs{1 - \eta^2 \pm i\eta}^2 = 1 - \eta^2 + \eta^4 < 1 \quad \text{para } 0 < \eta < 1.

The best step is η=1/2\eta = 1/\sqrt2, with factor 3/2≈0.866\sqrt3/2 \approx 0.866 per iteration. In the preceding figure’s stability region, the GDA disk touches the imaginary axis only at the origin, while extragradient’s region ∣1−w+w2∣<1\abs{1 - w + w^2} < 1 contains the whole imaginary segment between −i-i and ii except the origin itself. For bilinear OGDA the two-step recurrence has characteristic polynomial ρ2−(1−2ηλ)ρ−ηλ\rho^2 - (1 - 2\eta\lambda)\rho - \eta\lambda with λ=±i\lambda = \pm i; numerically it is stable for η<1/3≈0.577\eta < 1/\sqrt3 \approx 0.577, and with η=1/2\eta = 1/2 its factor is 1/2≈0.7071/\sqrt2 \approx 0.707, 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 z=zk\vb{z} = \vb{z}_k, w=zk+1/2=z−ηF(z)\vb{w} = \vb{z}_{k+1/2} = \vb{z} - \eta F(\vb{z}) and z+=z−ηF(w)\vb{z}^+ = \vb{z} - \eta F(\vb{w}). Expanding,

∥z+−z⋆∥2=∥z−z⋆∥2−2η⟨F(w),z−z⋆⟩+η2∥F(w)∥2.\norm{\vb{z}^+ - \vb{z}^\star}^2 = \norm{\vb{z} - \vb{z}^\star}^2 - 2\eta\inner{F(\vb{w})}{\vb{z} - \vb{z}^\star} + \eta^2\norm{F(\vb{w})}^2.

Split the inner product into ⟨F(w),w−z⋆⟩+⟨F(w),z−w⟩\inner{F(\vb{w})}{\vb{w} - \vb{z}^\star} + \inner{F(\vb{w})}{\vb{z} - \vb{w}}. The first is ⟨F(w)−F(z⋆),w−z⋆⟩≥0\inner{F(\vb{w}) - F(\vb{z}^\star)}{\vb{w} - \vb{z}^\star} \ge 0 by monotonicity and the second is η⟨F(w),F(z)⟩\eta\inner{F(\vb{w})}{F(\vb{z})} because z−w=ηF(z)\vb{z} - \vb{w} = \eta F(\vb{z}). Thus

∥z+−z⋆∥2≤∥z−z⋆∥2−2η2⟨F(w),F(z)⟩+η2∥F(w)∥2=∥z−z⋆∥2+η2∥F(w)−F(z)∥2−η2∥F(z)∥2,\norm{\vb{z}^+ - \vb{z}^\star}^2 \le \norm{\vb{z} - \vb{z}^\star}^2 - 2\eta^2\inner{F(\vb{w})}{F(\vb{z})} + \eta^2\norm{F(\vb{w})}^2 = \norm{\vb{z} - \vb{z}^\star}^2 + \eta^2\norm{F(\vb{w}) - F(\vb{z})}^2 - \eta^2\norm{F(\vb{z})}^2,

by completing the square. Lipschitz continuity gives ∥F(w)−F(z)∥≤L∥w−z∥=ηL∥F(z)∥\norm{F(\vb{w}) - F(\vb{z})} \le L\norm{\vb{w} - \vb{z}} = \eta L\norm{F(\vb{z})} and the inequality follows. Summing from k=0k = 0 to N−1N - 1 telescopes the distance side and yields the sum bound; the minimum of NN terms is at most their mean.

∎

Comparison with GDA takes one line. For GDA, ∥z+−z⋆∥2=∥z−z⋆∥2−2η⟨F(z),z−z⋆⟩+η2∥F(z)∥2\norm{\vb{z}^+ - \vb{z}^\star}^2 = \norm{\vb{z} - \vb{z}^\star}^2 - 2\eta\inner{F(\vb{z})}{\vb{z} - \vb{z}^\star} + \eta^2\norm{F(\vb{z})}^2, and in a bilinear game the middle term is zero (rotation is orthogonal to the radius): only +η2∥F(z)∥2+\eta^2\norm{F(\vb{z})}^2 remains, pushing outward. Extragradient converts +η2∥F∥2+\eta^2\norm{F}^2 into −η2(1−η2L2)∥F∥2-\eta^2(1 - \eta^2L^2)\norm{F}^2. In the bilinear game, with L=1L = 1 and ∥F(z)∥=∥z∥\norm{F(\vb{z})} = \norm{\vb{z}}, the inequality is equality and reproduces factor 1−η2+η41 - \eta^2 + \eta^4 exactly.

Two standard refinements follow. If FF is μ\mu-strongly monotone, combining the proof above with ⟨F(w),w−z⋆⟩≥μ∥w−z⋆∥2\inner{F(\vb{w})}{\vb{w} - \vb{z}^\star} \ge \mu\norm{\vb{w} - \vb{z}^\star}^2 and ∥w−z⋆∥2≥12∥z−z⋆∥2−η2∥F(z)∥2\norm{\vb{w} - \vb{z}^\star}^2 \ge \tfrac12\norm{\vb{z} - \vb{z}^\star}^2 - \eta^2\norm{F(\vb{z})}^2, using η=1/(4L)\eta = 1/(4L) yields ∥zk+1−z⋆∥2≤(1−14κ)∥zk−z⋆∥2\norm{\vb{z}_{k+1} - \vb{z}^\star}^2 \le (1 - \tfrac{1}{4\kappa})\norm{\vb{z}_k - \vb{z}^\star}^2: on the order of κ\kappa iterations, not κ2\kappa^2. In the merely monotone case, the mean exploratory point zˉN=1N∑kzk+1/2\bar{\vb{z}}_N = \tfrac1N\sum_k \vb{z}_{k+1/2} has duality gap O(1/N)\bigO(1/N) 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 FF came from a function ff: only monotonicity and Lipschitz continuity. This suggests the right framework, also connecting to constraints.

Three special cases make this natural. With F=∇fF = \grad f, the variational inequality is first-order optimality for minimizing ff over ZZ: no feasible direction z−z⋆\vb{z} - \vb{z}^\star descends, i.e. −∇f(z⋆)-\grad f(\vb{z}^\star) does not point into the set. With Z=RdZ = \R^d it is F(z⋆)=0F(\vb{z}^\star) = \vb{0}. With Z=X×YZ = X \times Y and the game field, solutions are saddle points of convex-concave ff: the inequality in x\vb{x} coordinates is optimality of x⋆\vb{x}^\star for f(⋅,y⋆)f(\cdot, \vb{y}^\star) and in y\vb{y} coordinates optimality of y⋆\vb{y}^\star for f(x⋆,⋅)f(\vb{x}^\star, \cdot). With constraints, each step is projected onto ZZ as in projected gradient, and projected extragradient is zk+1/2=ΠZ(zk−ηF(zk))\vb{z}_{k+1/2} = \Pi_Z(\vb{z}_k - \eta F(\vb{z}_k)), zk+1=ΠZ(zk−ηF(zk+1/2))\vb{z}_{k+1} = \Pi_Z(\vb{z}_k - \eta F(\vb{z}_{k+1/2})). The previous theorem’s inequality retains the same constant by replacing equality z−w=ηF(z)\vb{z} - \vb{w} = \eta F(\vb{z}) with projection’s variational characterization, ⟨u−ΠZ(u),v−ΠZ(u)⟩≤0\inner{\vb{u} - \Pi_Z(\vb{u})}{\vb{v} - \Pi_Z(\vb{u})} \le 0 for all v∈Z\vb{v} \in Z, 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 ff 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 YY is compact, ff and ∇xf\grad_{\vb{x}} f are continuous in X×YX \times Y and, for every x\vb{x}, maximizer y⋆(x)\vb{y}^\star(\vb{x}) of f(x,⋅)f(\vb{x}, \cdot) is unique, then Φ(x)=max⁡yf(x,y)\Phi(\vb{x}) = \max_{\vb{y}} f(\vb{x}, \vb{y}) is differentiable with ∇Φ(x)=∇xf(x,y⋆(x))\grad\Phi(\vb{x}) = \grad_{\vb{x}} f(\vb{x}, \vb{y}^\star(\vb{x})). No derivative of y⋆\vb{y}^\star appears: if the maximizer is interior and differentiable, the chain rule multiplies it by ∇yf=0\grad_{\vb{y}} f = \vb{0} (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 Φ\Phi: 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 ff is nonconvex in x\vb{x} but strongly concave in y\vb{y}, GDA with ηx\eta_x on the order of ηy/κ2\eta_y/\kappa^2 finds an ε\eps-stationary point of Φ\Phi in O(κ2ε−2)\bigO(\kappa^2\eps^{-2}) iterations. The inner player moves quickly and stays near its best response; the outer descends slowly on Φ\Phi. Equal rates have no such guarantee.

Min-max order matters here too: simultaneous-game equilibrium (Nash) and sequential-game equilibrium where x\vb{x} commits first (Stackelberg) may differ, and a stationary point of Φ\Phi 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.

[ ]Five methods on the bilinear gameBrowser
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 ∥z∥2\norm{\vb{z}}^2 by 1.01100=2.70481.01^{100} = 2.7048, exactly as the formula predicts. Alternating preserves x2+y2−ηxyx^2 + y^2 - \eta xy up to rounding. Extragradient and proximal point differ in the fourth decimal, (1−η2+η4)100(1 - \eta^2 + \eta^4)^{100} versus (1+η2)−100(1 + \eta^2)^{-100}, because they agree through second order in η\eta; optimistic is comparable with one field evaluation per step. Extragradient value f(xk,yk)f(x_k, y_k) changes sign each quarter turn while converging: the loss warning live.

The next experiment measures the effect of κ\kappa. A quadratic game f(x,y)=μ2∥x∥2+x⊤By−μ2∥y∥2f(\vb{x}, \vb{y}) = \tfrac\mu2\norm{\vb{x}}^2 + \vb{x}\T\mat{B}\vb{y} - \tfrac\mu2\norm{\vb{y}}^2 with x,y∈R10\vb{x}, \vb{y} \in \R^{10} and singular values of B\mat{B} distributed between 00 and 11 (one zero: no coupling in that direction, only potential force toward the solution) is μ\mu-strongly monotone and has linear field F(z)=MzF(\vb{z}) = \mat{M}\vb{z}, so each method’s rate is its iteration matrix’s spectral radius. For each, search a grid for the best η\eta and count iterations reducing error by 10610^6.

[ ]A quadratic game: κ² versus κBrowser
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 μ\mu by 10, from 0.10.1 to 0.010.01, takes GDA from about 2800 iterations to 280000: the factor 100 of κ2\kappa^2. Extragradient goes from about 135 to 1400 and OGDA from 250 to 2400: the factor 10 of κ\kappa. GDA’s best step is exactly η=μ\eta = \mu, predicted by η=μ/L2\eta = \mu/L^2 with L≈1L \approx 1: the weaker the potential, the smaller the step needed to keep rotation from winning. Game methods instead keep η\eta on the order of 1/L1/L regardless of μ\mu (near 1 for extragradient and 0.5750.575 for OGDA). An experiment worth trying: change singular values to np.linspace(0.2, 1.0, n); extragradient and OGDA hardly worsen as μ\mu falls because bilinear coupling without null directions suffices for convergence (in the pure bilinear game their rate depends on σmin⁡(B)/σmax⁡(B)\sigma_{\min}(\mat{B})/\sigma_{\max}(\mat{B}), not μ\mu); GDA, which diverges there, still needs the potential and pays κ2\kappa^2.

Now a toy 1D GAN. Data are a mixture 12N(−2,0.52)+12N(2,0.52)\tfrac12\Normal(-2, 0.5^2) + \tfrac12\Normal(2, 0.5^2). The generator has two parameters, positions m1,m2m_1, m_2 of its two modes (same width as data), and the discriminator is D(x)=σ(ψ⊤ϕ(x))D(x) = \sigmoid(\psi\T\phi(x)) with nine fixed Gaussians as features. The game is the original GAN’s f(m,ψ)=Edatoslog⁡D+Egenlog⁡(1−D)f(\vb{m}, \psi) = \E_{\text{datos}}\log D + \E_{\text{gen}}\log(1 - D). Expectations use Gauss–Hermite quadrature, making dynamics deterministic rather than sampling noise.

[ ]A toy GAN: the Jacobian governsBrowser
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 0.0234±0.2125i0.0234 \pm 0.2125i: imaginary part nine times real, almost pure rotation damped only by discriminator curvature. The linear criterion gives maximum GDA step 2⋅0.0234/(0.02342+0.21252)≈1.022 \cdot 0.0234/(0.0234^2 + 0.2125^2) \approx 1.02. With η=0.5\eta = 0.5 GDA converges slowly with damped oscillations; with η=2\eta = 2 it enters a cycle and generator modes dance around ±2\pm 2 without settling, with oscillation 0.160.16. At the same η=2\eta = 2, extragradient and OGDA converge to error 10−510^{-5}. 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. gg is training loss regularized by λ\lambda (regularization coefficients, augmentations, even learning rate), and FF 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 λ\lambda is shared initialization, the inner problem is a few gradient steps per task, and FF post-adaptation loss. Here the inner level is defined by an algorithm, not an arg min⁡\argmin.
  • Data selection and reweighting. λ\lambda are per-example training-loss weights and FF measures performance on a clean set.
  • Architecture search. In DARTS λ\lambda are continuous mixtures between operations and w\vb{w} network weights.
  • Stackelberg games and min-max. If g=−Fg = -F, the bilevel problem is min⁡λmax⁡wF\min_\lambda \max_{\vb{w}} F: the preceding min-max viewed as a leader committing and follower responding.

The outer problem is hard even if the inner is convex: F\mathcal{F} is generally nonconvex, and if inner arg min⁡\argmin is nonunique it is not even well-defined (one must choose an optimistic or pessimistic solution). Assume the regular case: for each λ\lambda, g(⋅,λ)g(\cdot, \lambda) has a unique minimizer and an invertible inner Hessian there. Then F\mathcal{F} is differentiable and can be optimized with gradients. The problem reduces to computing the hypergradient ∇F(λ)\grad\mathcal{F}(\lambda):

∇F(λ)=∇λF+(∂w⋆∂λ)⊤∇wF,\grad\mathcal{F}(\lambda) = \grad_\lambda F + \Big(\pd{\vb{w}^\star}{\lambda}\Big)\T\grad_{\vb{w}} F,

where derivatives of FF are evaluated at (w⋆(λ),λ)(\vb{w}^\star(\lambda), \lambda). The first term is easy; the hard one is solution Jacobian ∂w⋆∂λ∈Rd×m\pd{\vb{w}^\star}{\lambda} \in \R^{d \times m} with respect to hyperparameters. Two ways obtain it: differentiate the algorithm computing w⋆\vb{w}^\star, or differentiate its defining condition.

Hypergradients: unroll or differentiate implicitly

Unrolling the optimizer

Replace w⋆(λ)\vb{w}^\star(\lambda) by the result of KK optimizer steps, wk+1=wk−α∇wg(wk,λ)\vb{w}_{k+1} = \vb{w}_k - \alpha\grad_{\vb{w}} g(\vb{w}_k, \lambda) from w0\vb{w}_0, and differentiate F(wK(λ),λ)F(\vb{w}_K(\lambda), \lambda) like any computation graph. With reverse-mode differentiation, the backward pass traverses the KK steps in reverse, propagating adjoint wˉk=∂F/∂wk\bar{\vb{w}}_k = \partial F/\partial\vb{w}_k:

wˉK=∇wF,wˉk=(I−α∇ww2g(wk,λ))wˉk+1,λˉ+=−α ∇λw2g(wk,λ) wˉk+1.\bar{\vb{w}}_K = \grad_{\vb{w}} F, \qquad \bar{\vb{w}}_k = \big(\mat{I} - \alpha\hess_{\vb{w}\vb{w}} g(\vb{w}_k, \lambda)\big)\bar{\vb{w}}_{k+1}, \qquad \bar\lambda \mathrel{+}= -\alpha\,\hess_{\lambda\vb{w}} g(\vb{w}_k, \lambda)\,\bar{\vb{w}}_{k+1}.

Each backward step is a Hessian-vector product, costing about two gradients. Memory is the issue: backward needs wk\vb{w}_k at each kk, so the whole trajectory must be stored, KK copies of w\vb{w}. In PyTorch this happens if the inner loop uses create_graph=True: the dynamic graph retains KK 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 KK 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 ∂wk∂λ\pd{\vb{w}_k}{\lambda} forward with O(dm)\bigO(dm) memory and no trajectory, but cost proportional to hyperparameter count mm (Franceschi et al., 2017).

The second issue is subtler. Unrolling gives the exact derivative of F(wK(λ))F(\vb{w}_K(\lambda)), a different function. If KK is small, wK\vb{w}_K is far from w⋆\vb{w}^\star, 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 ∇wg(w⋆(λ),λ)=0\grad_{\vb{w}} g(\vb{w}^\star(\lambda), \lambda) = \vb{0} for every λ\lambda, and differentiating that identity gives the Jacobian.

Existence and regularity follow from the implicit function theorem applied to equation G(w,λ)=∇wg(w,λ)=0G(\vb{w}, \lambda) = \grad_{\vb{w}} g(\vb{w}, \lambda) = \vb{0}, whose Jacobian in w\vb{w} is H\mat{H}; 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 w⋆\vb{w}^\star 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 H−1\mat{H}\inv or Jacobian d×md \times m. First solve adjoint system Hv=∇wF\mat{H}\vb{v} = \grad_{\vb{w}} F (one linear system regardless of hyperparameter count), then compute ∇λw2g v=∇λ(∇wg⊤v)\hess_{\lambda\vb{w}} g\,\vb{v} = \grad_\lambda\big(\grad_{\vb{w}} g\T\vb{v}\big) with one vector-Jacobian product, differentiating with respect to λ\lambda the scalar ∇wg⋅v\grad_{\vb{w}} g \cdot \vb{v}.

Solve Hv=∇wF\mat{H}\vb{v} = \grad_{\vb{w}} F without forming H\mat{H} using conjugate gradient over Hessian-vector products, exactly as in Newton-CG. Memory is a few vectors the size of w\vb{w}, independent of inner optimizer steps. A cheaper, cruder alternative is the Neumann series: if H\mat{H} is positive definite and 0<α<2/λmax⁡(H)0 < \alpha < 2/\lambda_{\max}(\mat{H}), H−1=α∑j≥0(I−αH)j\mat{H}\inv = \alpha\sum_{j \ge 0}(\mat{I} - \alpha\mat{H})^j, and truncating at JJ terms gives v≈α∑j<J(I−αH)j∇wF\vb{v} \approx \alpha\sum_{j < J}(\mat{I} - \alpha\mat{H})^j\grad_{\vb{w}} F, 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, w0=w⋆\vb{w}_0 = \vb{w}^\star, every iterate is w⋆\vb{w}^\star and Jacobian recursion ∂wk+1∂λ=(I−αH)∂wk∂λ−α∇wλ2g\pd{\vb{w}_{k+1}}{\lambda} = (\mat{I} - \alpha\mat{H})\pd{\vb{w}_k}{\lambda} - \alpha\hess_{\vb{w}\lambda} g after JJ steps gives −α∑j<J(I−αH)j∇wλ2g-\alpha\sum_{j < J}(\mat{I} - \alpha\mat{H})^j\hess_{\vb{w}\lambda} g: Neumann truncation. Unrolling JJ steps from the optimum matches the order-JJ Neumann approximation. Unrolling from w0=0\vb{w}_0 = \vb{0} mixes that error with not having reached w⋆\vb{w}^\star.

A complete example: ridge

With g(w,λ)=12n∥Xw−y∥2+λ2∥w∥2g(\vb{w}, \lambda) = \tfrac{1}{2n}\norm{\mat{X}\vb{w} - \vb{y}}^2 + \tfrac\lambda2\norm{\vb{w}}^2, the inner problem has closed solution w⋆=(A+λI)−1b\vb{w}^\star = (\mat{A} + \lambda\mat{I})\inv\vb{b} with A=X⊤X/n\mat{A} = \mat{X}\T\mat{X}/n and b=X⊤y/n\vb{b} = \mat{X}\T\vb{y}/n. The Hessian is H=A+λI\mat{H} = \mat{A} + \lambda\mat{I} and mixed derivative ∇wλ2g=w\hess_{\vb{w}\lambda} g = \vb{w}, so

∂w⋆∂λ=−(A+λI)−1w⋆, ⁣dF ⁣dλ=−∇wF(w⋆)⊤(A+λI)−1w⋆,\pd{\vb{w}^\star}{\lambda} = -(\mat{A} + \lambda\mat{I})\inv\vb{w}^\star, \qquad \frac{\dd\mathcal{F}}{\dd\lambda} = -\grad_{\vb{w}} F(\vb{w}^\star)\T(\mat{A} + \lambda\mat{I})\inv\vb{w}^\star,

with FF the mean squared validation loss. The sign makes sense: increasing λ\lambda shrinks w⋆\vb{w}^\star in the (A+λI)−1(\mat{A} + \lambda\mat{I})\inv metric, and validation improves if shrinking opposes its gradient. The figure compares this exact formula with KK unrolled GD steps from w0=0\vb{w}_0 = \vb{0} (fixed step α\alpha), and the implicit formula evaluated at wK\vb{w}_K instead of w⋆\vb{w}^\star.

InteractiveUnrolled or implicit hypergradient
Validation loss and tangents at selected λ\lambda
Relative hypergradient error versus KK
0.03
10
Exact dF/dλ\mathrm{d}F/\mathrm{d}\lambda−5.2347
Unrolled (relative error)0.3722 (1.07)
Implicit at wK\vb{w}_K (relative error)0.0909 (1.02)
Inner problem error0.309
Unrolling memory with d=108d = 10^810 copies of w, 4.0 GB
Implicit memory with CGabout 4 copies, 1.6 GB
Ridge with 30 training examples, 12 variables and 200 validation examples. First panel: validation loss F(λ)F(\lambda) with exact optimum (gray) and truncated objective FK(λ)=F(wK(λ))F_K(\lambda) = F(\vb{w}_K(\lambda)) after KK gradient-descent steps from 0\vb{0} (dashed orange), with logarithmic λ\lambda and three tangents at selected λ\lambda (vertical line): exact (gray), unrolled (orange), exactly tangent to the orange curve, and implicit evaluated at wK\vb{w}_K (aqua). Second: relative hypergradient-estimate error against KK, alongside inner-problem error. Initially, λ=0.03\lambda = 0.03 and K=10K = 10, exact hypergradient is −5.23-5.23 and both estimates are positive: both send λ\lambda the wrong way. Raise KK to 100: implicit is within 1 % and unrolled within 4 %. Above 300 both are exact, but unrolling stored 300 copies of w\vb{w}. Move λ\lambda right, where the inner problem is better conditioned, and watch convergence accelerate.

Three observations. First, the orange K=10K = 10 curve is below gray throughout the left side, around 1.721.72 versus ridge’s minimum 1.861.86. Ten GD steps from zero regularize better than any λ\lambda, and near λ=0\lambda = 0 the truncated objective barely depends on λ\lambda: 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 w0=0\vb{w}_0 = \vb{0}. Third, cost: at similar accuracy reverse-mode unrolling stores KK parameter-vector copies. For a float32 model with 10810^8 parameters each copy occupies 0.40.4 GB, and with K=100K = 100 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.

[ ]Ridge hypergradients: implicit, unrolled, CG and NeumannBrowser
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 K=10K = 10 and K=30K = 30 both estimators have errors from 70 % to 500 %; with K=300K = 300 implicit is already at 7×10−57 \times 10^{-5} and unrolled at 8×10−48 \times 10^{-4}; unrolling memory grows with KK. In the second table the inner solution is exact and only the adjoint system is approximated: CG with m=20>d=12m = 20 > d = 12 steps is exact (in exact arithmetic it terminates in dd steps), while Neumann converges at linear rate 1−1/κ(H)1 - 1/\kappa(\mat{H}) and with m=50m = 50 still has error 4×10−44 \times 10^{-4}. Thus CG is default when H\mat{H} 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 λg=esg\lambda_g = e^{s_g} per group. Newton solves the inner problem (the logistic Hessian is cheap at d=40d = 40); CG solves hypergradients using double-backprop Hessian-vector products without forming the Hessian. It runs on CPU in seconds.

[ ]One λ per group with implicit hypergradients in PyTorchLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The implicit hypergradient matches finite differences to all five printed decimals; unrolling from w=0\vb{w} = \vb{0} with K=10K = 10 has 84 % error, with K=50K = 50 26 %, and with K=200K = 200 0.20.2 %. After 60 Adam steps on ss, the hypergradient is on the order of 10−410^{-4} and learned coefficients tell the data’s story: λ≈0.016\lambda \approx 0.016 for strong signal, 0.270.27 for weak, and around 4 for both noise groups, nearly suppressing them. Test-set loss, unseen by the procedure, drops from 0.5780.578 with the best shared grid λ\lambda to 0.4410.441. Four hyperparameters already make a grid of 254≈4×10525^4 \approx 4 \times 10^5 points; the hypergradient costs the same for four as four million.

Differentiable optimization layers

Implicit differentiation is not limited to conditions of form ∇wg=0\grad_{\vb{w}} g = \vb{0}. Any optimum characterization as the solution of an equation system R(w,θ)=0R(\vb{w}, \theta) = \vb{0} works: if Jacobian ∂R/∂w\partial R/\partial\vb{w} is invertible, ∂w⋆∂θ=−(∂R/∂w)−1 ∂R/∂θ\pd{\vb{w}^\star}{\theta} = -(\partial R/\partial\vb{w})\inv\,\partial R/\partial\theta. Blondel et al. (2022) made this generic: users write optimality conditions (stationarity, proximal fixed point, KKT), and the library obtains derivatives by autodiff of RR plus a linear solver. For constraints, KKT is natural.

Consider a parametric quadratic program, OptNet’s layer (Amos and Kolter, 2017):

z⋆(θ)=arg min⁡z 12z⊤Qz+q⊤zsujeto aGz≤h,Az=b,\vb{z}^\star(\theta) = \argmin_{\vb{z}}\ \tfrac12\vb{z}\T\mat{Q}\vb{z} + \vb{q}\T\vb{z} \quad \text{sujeto a} \quad \mat{G}\vb{z} \le \vb{h}, \quad \mat{A}\vb{z} = \vb{b},

where θ\theta groups Q,q,G,h,A,b\mat{Q}, \vb{q}, \mat{G}, \vb{h}, \mat{A}, \vb{b}, potentially network outputs. KKT conditions with multipliers λ≥0\lambda \ge 0 and ν\nu are Qz+q+G⊤λ+A⊤ν=0\mat{Q}\vb{z} + \vb{q} + \mat{G}\T\lambda + \mat{A}\T\nu = \vb{0}, diag⁡(λ)(Gz−h)=0\diag(\lambda)(\mat{G}\vb{z} - \vb{h}) = \vb{0} (complementary slackness as an equation) and Az=b\mat{A}\vb{z} = \vb{b}. Differentiating,

[QG⊤A⊤diag⁡(λ)Gdiag⁡(Gz−h)0A00]⏟K[ ⁣dz ⁣dλ ⁣dν]=−[ ⁣dQ z+ ⁣dq+ ⁣dG⊤λ+ ⁣dA⊤νdiag⁡(λ)( ⁣dG z− ⁣dh) ⁣dA z− ⁣db].\underbrace{\begin{bmatrix} \mat{Q} & \mat{G}\T & \mat{A}\T \\ \diag(\lambda)\mat{G} & \diag(\mat{G}\vb{z} - \vb{h}) & \mat{0} \\ \mat{A} & \mat{0} & \mat{0} \end{bmatrix}}_{\mat{K}} \begin{bmatrix} \dd\vb{z} \\ \dd\lambda \\ \dd\nu \end{bmatrix} = -\begin{bmatrix} \dd\mat{Q}\,\vb{z} + \dd\vb{q} + \dd\mat{G}\T\lambda + \dd\mat{A}\T\nu \\ \diag(\lambda)(\dd\mat{G}\,\vb{z} - \dd\vb{h}) \\ \dd\mat{A}\,\vb{z} - \dd\vb{b} \end{bmatrix}.

The middle rows explain the derivative. For an inactive constraint (λi=0\lambda_i = 0, (Gz−h)i<0(\mat{G}\vb{z} - \vb{h})_i < 0), the row says  ⁣dλi=0\dd\lambda_i = 0: it does not count. For an active one with λi>0\lambda_i > 0 it says gi⊤ ⁣dz= ⁣dhi− ⁣dgi⊤z\vb{g}_i\T\dd\vb{z} = \dd h_i - \dd\vb{g}_i\T\vb{z}: the constraint stays active after perturbation. The derivative is that of the equality-constrained QP on the active set. Matrix K\mat{K} 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 zˉ=∂ℓ/∂z⋆\bar{\vb{z}} = \partial\ell/\partial\vb{z}^\star, solve K⊤(dz,dλ,dν)=(zˉ,0,0)\mat{K}\T(\vb{d}_z, \vb{d}_\lambda, \vb{d}_\nu) = (\bar{\vb{z}}, \vb{0}, \vb{0}) once and obtain gradients for all parameters from products with those vectors: for example ∂ℓ/∂q=−dz\partial\ell/\partial\vb{q} = -\vb{d}_z, ∂ℓ/∂b=dν\partial\ell/\partial\vb{b} = \vb{d}_\nu and ∂ℓ/∂h=diag⁡(λ)dλ\partial\ell/\partial\vb{h} = \diag(\lambda)\vb{d}_\lambda. This is the same adjoint system as hypergradient Hv=∇wF\mat{H}\vb{v} = \grad_{\vb{w}} F, now constrained. OptNet solves QP batches with a primal-dual interior-point method on GPU and reuses the K\mat{K} factorization for backward, almost for free.

The cell implements KKT differentiation for a general QP and tests Euclidean projection onto the simplex, z⋆(θ)=arg min⁡{12∥z−θ∥2:1⊤z=1, z≥0}\vb{z}^\star(\theta) = \argmin\{\tfrac12\norm{\vb{z} - \theta}^2 : \vb{1}\T\vb{z} = 1,\ \vb{z} \ge \vb{0}\}, called sparsemax in learning (a softmax alternative producing exactly zero probabilities). Its Jacobian has closed form diag⁡(s)−ss⊤/∣S∣\diag(\vb{s}) - \vb{s}\vb{s}\T/\abs{S}, with s\vb{s} the indicator of support SS.

[ ]Differentiate through KKT: sparsemaxBrowser
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 10−1010^{-10}. 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
ToolWhat it differentiatesWhen
Hand-derived implicit formula + CGUnconstrained ∇wg=0\grad_{\vb{w}} g = \vb{0}Continuous hyperparameters, smooth large inner problems
Unrolling with create_graph=TrueInner algorithm step by stepFew steps (MAML), intentionally unconverged inner solve
OptNetKKT of a QPBatches of small or medium QPs on GPU
cvxpylayersConic-program solutionAny DPP problem: LP, QP, SOCP, SDP
Generic implicit differentiation (Blondel et al.)Any written R(w,θ)=0R(\vb{w}, \theta) = \vb{0}Proximal operators, fixed points, custom problems

Common mistakes

Exercises

ProofGDA multiplies squared norm by 1 + η²
Prove: For f(x,y)=xyf(x, y) = xy and any η>0\eta > 0, simultaneous step xk+1=xk−ηykx_{k+1} = x_k - \eta y_k, yk+1=yk+ηxky_{k+1} = y_k + \eta x_k satisfies xk+12+yk+12=(1+η2)(xk2+yk2)x_{k+1}^2 + y_{k+1}^2 = (1 + \eta^2)(x_k^2 + y_k^2).
0
Write zk=(xk,yk)\vb{z}_k = (x_k, y_k).

Step 1 of 4. How is the step written as a matrix?

NumericOne hundred GDA steps
In f(x,y)=xyf(x, y) = xy with simultaneous GDA and η=0.1\eta = 0.1, by what factor is x2+y2x^2 + y^2 multiplied after 100 steps?
NumericExtragradient's best step
In f(x,y)=xyf(x, y) = xy, extragradient multiplies ∥z∥\norm{\vb{z}} by 1−η2+η4\sqrt{1 - \eta^2 + \eta^4} each step. What is the smallest per-step factor achievable by choosing η\eta?
NumericGDA's maximum step
A game field's Jacobian at its saddle has eigenvalues 0.1±i0.1 \pm i. What is the largest η\eta for which simultaneous GDA converges locally?
NumericA minimax gap
For f(x,y)=(x−y)2f(x, y) = (x - y)^2 with x,y∈[0,1]x, y \in [0, 1], calculate min⁡xmax⁡yf(x,y)−max⁡ymin⁡xf(x,y)\min_x \max_y f(x, y) - \max_y \min_x f(x, y).
QuizWhat do losses say?
You train a convex-concave game with extragradient and an appropriate step. During training minimizing-player loss f(xk,yk)f(\vb{x}_k, \vb{y}_k) rises and falls without a clear trend. What conclusion is valid?
QuizThe gradient of a maximum
Let Φ(x)=max⁡y∈Yf(x,y)\Phi(\vb{x}) = \max_{\vb{y} \in Y} f(\vb{x}, \vb{y}) with compact YY, differentiable ff and unique maximizer y⋆(x)\vb{y}^\star(\vb{x}) in the interior of YY. What is ∇Φ(x)\grad\Phi(\vb{x})?
ProofThe implicit hypergradient formula
Prove: If gg is C2C^2, ∇wg(w⋆(λ),λ)=0\grad_{\vb{w}} g(\vb{w}^\star(\lambda), \lambda) = \vb{0} near λ0\lambda_0, and H=∇ww2g\mat{H} = \hess_{\vb{w}\vb{w}} g is invertible at (w⋆(λ0),λ0)(\vb{w}^\star(\lambda_0), \lambda_0), then F(λ)=F(w⋆(λ),λ)\mathcal{F}(\lambda) = F(\vb{w}^\star(\lambda), \lambda) satisfies ∇F=∇λF−∇λw2g H−1∇wF\grad\mathcal{F} = \grad_\lambda F - \hess_{\lambda\vb{w}} g\,\mat{H}\inv\grad_{\vb{w}} F.
0
By the implicit function theorem, w⋆(λ)\vb{w}^\star(\lambda) is C1C^1 near λ0\lambda_0. Evaluate all derivatives at (w⋆(λ),λ)(\vb{w}^\star(\lambda), \lambda).

Step 1 of 4. Which identity do you differentiate with respect to λ\lambda to obtain ∂w⋆∂λ\pd{\vb{w}^\star}{\lambda}?

QuizImplicit versus unrolled
Compared with reverse-mode unrolling through the inner optimizer's KK steps, which statements about implicit differentiation are true?

More than one answer may be correct.

CodeExtragradient for a generic operator
Implement extragradient(F, z0, eta, iters, proj=None) for generic game operator F (array to array). Return (z, z_medio): final iterate zK\vb{z}_{K} and mean exploratory point zˉ=1K∑k<Kzk+1/2\bar{\vb{z}} = \tfrac1K\sum_{k<K}\vb{z}_{k+1/2}. If proj is not None, it projects onto the feasible set and applies to both steps: zk+1/2=Π(zk−ηF(zk))\vb{z}_{k+1/2} = \Pi(\vb{z}_k - \eta F(\vb{z}_k)) and zk+1=Π(zk−ηF(zk+1/2))\vb{z}_{k+1} = \Pi(\vb{z}_k - \eta F(\vb{z}_{k+1/2})). Tests check the exact bilinear factor, convergence in a bilinear game in R10\R^{10} 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, z
Shift+Enter to run

Summary

Key idea
In a min-max problem the players’ field has a rotational component descent-ascent cannot cancel: GDA rotates or diverges, and anticipating a step (extragradient, optimistic gradient) makes it a proximal-point approximation converging on any monotone problem. In a bilevel problem, the hyperparameter gradient comes from differentiating the inner optimum condition, not the path to it.
  • A saddle closes the gap between min⁡max⁡\min\max and max⁡min⁡\max\min; 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 F=(∇xf,−∇yf)F = (\grad_{\vb{x}} f, -\grad_{\vb{y}} f) is monotone in the convex-concave case. Its Jacobian has symmetric (potential) and antisymmetric (rotational) parts; GDA converges locally only if η<2Re⁡λ/∣λ∣2\eta < 2\operatorname{Re}\lambda/\abs{\lambda}^2 for every eigenvalue, impossible for purely imaginary eigenvalues.
  • In f=xyf = xy, simultaneous GDA multiplies ∥z∥2\norm{\vb{z}}^2 by 1+η21 + \eta^2, alternating preserves x2+y2−ηxyx^2 + y^2 - \eta xy and extragradient multiplies it by 1−η2+η41 - \eta^2 + \eta^4. For strongly monotone games, GDA needs on the order of κ2\kappa^2 iterations and extragradient κ\kappa.
  • Variational inequalities unify minimization, games and constraints; projection can be added without changing analysis.
  • In bilevel optimization hypergradient ∇λF−∇λw2g H−1∇wF\grad_\lambda F - \hess_{\lambda\vb{w}} g\,\mat{H}\inv\grad_{\vb{w}} F 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.