Module contents
Lesson 6 of 27Core 120 min

Lagrangian duality: bounds, certificates and sensitivity

Construct the dual problem and explain why it always provides bounds (weak duality), when they are exact (strong duality under Slater), and how the duality gap certifies solution quality. Introduce convex conjugates and Fenchel duality, alternative theorems such as Farkas' lemma, and multipliers as shadow prices.

After this lesson you can

  • Derive the dual function and dual problem for LPs, QPs, minimum-norm least squares and lasso.
  • Prove weak duality and explain geometrically strong duality under Slater's condition.
  • Use the duality gap as a stopping criterion and suboptimality certificate.
  • Calculate conjugates of norms, quadratics, log-sum-exp and negative entropy and apply Fenchel duality.
  • Interpret optimal multipliers as derivatives of optimal value with respect to constraint perturbations.
  • Apply Farkas' lemma to construct infeasibility certificates.

Before you start

Motivation: how far remains, without knowing the target

A solver returns a point x^\hat{\vb{x}} with f0(x^)=−44.99f_0(\hat{\vb{x}}) = -44.99. Is it optimal? If not, is it close or light-years away? Looking at the last step’s change does not answer: a slow, stuck method also takes tiny steps. To claim “the optimum is in [−47,−44.99][-47, -44.99]” requires a guaranteed lower bound on optimal value p⋆p^\star, a number provably at most f0(x)f_0(\vb{x}) for every feasible point x\vb{x} without solving the problem.

Lower bounds can be constructed. Consider minimizing x2x^2 subject to x≥1x \ge 1. For any number λ≥0\lambda \ge 0 and feasible xx, x2≥x2+λ(1−x)x^2 \ge x^2 + \lambda(1 - x), because the added term is λ\lambda times something nonpositive. The right side is a parabola in xx whose minimum is calculated by hand: at x=λ/2x = \lambda/2 it equals λ−λ2/4\lambda - \lambda^2/4. So for each λ≥0\lambda \ge 0,

p⋆ ≥ λ−λ24.p^\star \ \ge\ \lambda - \frac{\lambda^2}{4}.

With λ=1\lambda = 1 we get p⋆≥0.75p^\star \ge 0.75; with λ=2\lambda = 2, p⋆≥1p^\star \ge 1, and since x=1x = 1 is feasible and gives 11, the optimum is exactly 11: point and bound certify each other. That is the whole idea: constraints are “charged” a price λ\lambda, the relaxed problem is solved without constraints, and the best price gives the best bound. It appears wherever knowing when to stop or a constraint’s cost matters:

  • Guaranteed stopping criteria. scikit-learn’s Lasso iterates by coordinates until the duality gap falls below tol (attribute dual_gap_ stores it); interior-point solvers print primal objective, dual objective and their difference each iteration.
  • Certificates. An infeasibility or optimality result with a proof verifiable in linear time, rather than “the solver said so”.
  • Prices. A budget constraint’s multiplier is the marginal value of one extra budget unit. Shadow prices are the dual’s economic interpretation.
  • Easier problems. For a difficult or nonconvex problem, the dual is always convex and gives a bound (the MAX-CUT relaxation in the convex problems lesson arises this way). For support vector machines, the dual enables the kernel trick.

This lesson constructs the dual of any problem, proves it always gives bounds (weak duality), finds when they are exact (strong duality under the Slater condition of the previous lesson), introduces convex conjugates, interprets multipliers as prices, and concludes with alternative theorems, the same dual applied to “does this system have a solution?”

The dual function: an infimum of lines

Work with the standard-form problem from the KKT lesson, without assuming convexity,

(P)minimize f0(x)subject tofi(x)≤0 (i=1,…,m),hj(x)=0 (j=1,…,p),\text{(P)}\qquad \text{minimize } f_0(\vb{x}) \quad \text{subject to} \quad f_i(\vb{x}) \le 0\ (i = 1, \dots, m), \quad h_j(\vb{x}) = 0\ (j = 1, \dots, p),

with optimal value p⋆∈[−∞,+∞]p^\star \in [-\infty, +\infty] (with +∞+\infty if no feasible points) and functions defined on Rn\R^n unless a domain is stated. The Lagrangian is L(x,λ,ν)=f0(x)+∑iλifi(x)+∑jνjhj(x)L(\vb{x}, \vb{\lambda}, \vb{\nu}) = f_0(\vb{x}) + \sum_i \lambda_i f_i(\vb{x}) + \sum_j \nu_j h_j(\vb{x}).

The two properties making gg useful follow from the definition, but deserve a careful look.

Proof

Fix x\vb{x}. Mapping (λ,ν)↦L(x,λ,ν)(\vb{\lambda}, \vb{\nu}) \mapsto L(\vb{x}, \vb{\lambda}, \vb{\nu}) is affine: the Lagrangian is linear in multipliers. Thus gg is the infimum over all x\vb{x} of a family of affine functions. The pointwise infimum of concave functions is concave (its hypograph is an intersection of convex hypographs), so gg is concave. The domain is the set {g>−∞}\{g > -\infty\} of a concave function, which is convex. ■\blacksquare

∎

It is convexity in reverse, holding without assumptions on f0f_0, fif_i or hjh_j. In the motivation problem each xx contributes line λ↦x2+λ(1−x)\lambda \mapsto x^2 + \lambda(1 - x), and g(λ)=inf⁡x(… )g(\lambda) = \inf_x(\dots) is their lower envelope, the concave parabola λ−λ2/4\lambda - \lambda^2/4 (the orange curve in the lower panel of the figure below).

Weak duality: the dual always gives a bound

Since gg is concave, seeking its best value is a convex problem; only the sign of inequality multipliers must be added.

(D) is convex regardless of (P): maximize a concave function on a convex set. Any dual-feasible point is already a certificate, guaranteed by the lesson’s simplest and most useful result.

The direct three-line proof is the first guided exercise at the end. Here is another, showing why the dual is the “opposite” problem. Fix x\vb{x} and maximize the Lagrangian over admissible multipliers. If x\vb{x} is feasible, each λifi(x)≤0\lambda_i f_i(\vb{x}) \le 0 and each νjhj(x)=0\nu_j h_j(\vb{x}) = 0, so the maximum is attained at λ=0\vb{\lambda} = \vb{0} and equals f0(x)f_0(\vb{x}). If infeasible, some fi(x)>0f_i(\vb{x}) > 0 (let λi→∞\lambda_i \to \infty) or some hj(x)≠0h_j(\vb{x}) \ne 0 (let νj→±∞\nu_j \to \pm\infty) and the maximum is +∞+\infty. Thus,

sup⁡λ⪰0, νL(x,λ,ν)={f0(x)if x is feasible,+∞otherwise.⟹p⋆=inf⁡x sup⁡λ⪰0, νL,d⋆=sup⁡λ⪰0, ν inf⁡xL.\sup_{\vb{\lambda} \succeq \vb{0},\, \vb{\nu}} L(\vb{x}, \vb{\lambda}, \vb{\nu}) = \begin{cases} f_0(\vb{x}) & \text{if } \vb{x} \text{ is feasible},\\ +\infty & \text{otherwise.}\end{cases} \qquad\Longrightarrow\qquad p^\star = \inf_{\vb{x}}\ \sup_{\vb{\lambda} \succeq \vb{0},\, \vb{\nu}} L, \qquad d^\star = \sup_{\vb{\lambda} \succeq \vb{0},\, \vb{\nu}}\ \inf_{\vb{x}} L.

Constraints are an adversarial player punishing any violation with infinite price, and (D) swaps player order. For any function φ(x,y)\varphi(\vb{x}, \vb{y}), sup⁡yinf⁡xφ≤inf⁡xsup⁡yφ\sup_{\vb{y}} \inf_{\vb{x}} \varphi \le \inf_{\vb{x}} \sup_{\vb{y}} \varphi: for every (x′,y′)(\vb{x}', \vb{y}'), inf⁡xφ(x,y′)≤φ(x′,y′)≤sup⁡yφ(x′,y)\inf_{\vb{x}} \varphi(\vb{x}, \vb{y}') \le \varphi(\vb{x}', \vb{y}') \le \sup_{\vb{y}} \varphi(\vb{x}', \vb{y}), and take the supremum over y′\vb{y}' on the left and infimum over x′\vb{x}' on the right. This is the minimax inequality, and weak duality is a special case. Swapping order can only help the second player, and strong duality asks when it does not help at all.

The gap: a quality certificate

Two immediate consequences, including p⋆=−∞p^\star = -\infty or +∞+\infty:

  • If p⋆=−∞p^\star = -\infty, no dual-feasible point exists (any would be a bound ≤−∞\le -\infty). If d⋆=+∞d^\star = +\infty, no primal-feasible point exists.
  • Suboptimality certificate. If x^\hat{\vb{x}} is primal feasible and (λ^,ν^)(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) is dual feasible, then
g(λ^,ν^) ≤ d⋆ ≤ p⋆ ≤ f0(x^),thereforef0(x^)−p⋆ ≤ f0(x^)−g(λ^,ν^)⏟duality gap.g(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) \ \le\ d^\star \ \le\ p^\star \ \le\ f_0(\hat{\vb{x}}), \qquad\text{therefore}\qquad f_0(\hat{\vb{x}}) - p^\star \ \le\ \underbrace{f_0(\hat{\vb{x}}) - g(\hat{\vb{\lambda}}, \hat{\vb{\nu}})}_{\text{duality gap}}.

The primal-dual pair’s duality gap is a verifiable upper bound on error of x^\hat{\vb{x}}. If zero, x^\hat{\vb{x}} is optimal and (λ^,ν^)(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) is optimal for (D). The difference p⋆−d⋆≥0p^\star - d^\star \ge 0 is called the optimal duality gap: what the dual cannot close.

Check against brute force for n=14n = 14 (all 214=163842^{14} = 16384 candidates fit in memory).

[ ]Dual bound versus brute force for a nonconvex problemBrowser
import numpy as np

rng = np.random.default_rng(4)
n = 14
M = rng.normal(size=(n, n))
W = (M + M.T) / 2

# Los 2^14 candidatos x en {-1, 1}^n: se puede comprobar por fuerza bruta
bits = ((np.arange(2 ** n)[:, None] >> np.arange(n)) & 1) * 2 - 1
p_star = np.einsum("ki,ij,kj->k", bits, W, bits).min()

def phi(nu):
    """Cota válida para todo nu, y un supergradiente."""
    w, V = np.linalg.eigh(W + np.diag(nu))
    return n * w[0] - nu.sum(), n * V[:, 0] ** 2 - 1

nu, mejor = np.zeros(n), -np.inf
print("iteración   cota actual   mejor cota")
for k in range(1, 801):
    val, g = phi(nu)
    mejor = max(mejor, val)
    if k in (1, 10, 100, 800):
        print(f"{k:9d}   {val:11.3f}   {mejor:10.3f}")
    nu = nu + g / np.sqrt(k)           # ascenso por supergradiente

# Una solución factible por redondeo del autovector
v = np.linalg.eigh(W)[1][:, 0]
x_h = np.where(v >= 0, 1.0, -1.0)
f_h = x_h @ W @ x_h
print(f"\nheurística de signos: f0 = {f_h:.3f}")
print(f"cota dual inicial n*lambda_min = {n * np.linalg.eigvalsh(W)[0]:.3f}; cota tras el ascenso = {mejor:.3f}")
print(f"certificado: la heurística está a {f_h - mejor:.3f} del óptimo (error relativo {100 * (f_h - mejor) / abs(mejor):.1f} %)")
print(f"verdad (fuerza bruta): p* = {p_star:.3f}, distancia real de la cota al óptimo p* - cota = {p_star - mejor:.3f}")

The first bound (ν=0\vb{\nu} = \vb{0} in φ\varphi, that is nλmin⁡n\lambda_{\min}) is −59.39-59.39, far below, and ascent raises it to −46.935-46.935. The sign heuristic turns out to be exactly optimal (−44.99-44.99), but without knowing that, the certificate already says it is within 1.951.95, or 4.1 %4.1\,\%. The gap p⋆−d⋆p^\star - d^\star is nonzero (the problem is nonconvex): solving the dual SDP with a solver gives d⋆=−46.90d^\star = -46.90, so ascent stopped 0.040.04 from the best possible price and the true gap is 1.911.91. No ν\vb{\nu} closes it: this is a limit of the dual, not the ascent algorithm.

Dual geometry: the (u,t)(u, t) plane

With one constraint, f1(x)≤0f_1(\vb{x}) \le 0, the entire dual fits in one picture. Each point x\vb{x} in space maps to a plane point (u,t)=(f1(x),f0(x))(u, t) = (f_1(\vb{x}), f_0(\vb{x})), and their set is

G={(f1(x), f0(x)):x∈Rn}⊂R2.G = \{ (f_1(\vb{x}),\, f_0(\vb{x})) : \vb{x} \in \R^n \} \subset \R^2.

Both theoretical quantities have direct interpretations. The primal optimum is the lowest point of GG in the feasible half-plane u≤0u \le 0, p⋆=inf⁡{t:(u,t)∈G, u≤0}p^\star = \inf\{t : (u, t) \in G,\ u \le 0\}. And since L(x,λ)=t+λuL(\vb{x}, \lambda) = t + \lambda u at (u,t)(u, t),

g(λ)=inf⁡(u,t)∈G(λu+t),g(\lambda) = \inf_{(u,t) \in G} \big( \lambda u + t \big),

which is the inner product of (λ,1)(\lambda, 1) and (u,t)(u, t) minimized over GG. It is the height of line t=g(λ)−λut = g(\lambda) - \lambda u, of slope −λ-\lambda, lying below GG and touching it (a supporting line): g(λ)g(\lambda) is its intercept on the tt axis. And d⋆d^\star is the highest intercept among supporting lines of nonpositive slope.

InteractiveDuality in the (u, t) plane
  • G={(f1(x),f0(x))}G = \{(f_1(x), f_0(x))\}
  • supporting line, slope −λ-\lambda
  • convex hull of A\mathcal{A}
  • p⋆p^\star
The dual function g(λ)g(\lambda): concave and always below p⋆p^\star
Problem
1.00
λ\lambda1.00
g(λ)g(\lambda) (tt-intercept)0.750
p⋆p^\star (primal optimum)1.000
d⋆=max⁡λgd^\star = \max_\lambda g1.000
gap p⋆−d⋆p^\star - d^\star0.000
Strong duality: the line with λ⋆=2.00\lambda^\star = 2.00 passes through (0,p⋆)(0, p^\star) and d⋆=p⋆d^\star = p^\star. min⁡x2\min x^2 subject to 1−x≤01 - x \le 0. GG is a parabola and A\mathcal{A} is convex: the supporting line at λ⋆=2\lambda^\star = 2 passes through (0,p⋆)(0, p^\star).
What is the dual function in the (u,t)(u,t) plane and when does the best line touch the optimum? The thick, text-colored curve is GG and the gray region is A=G+R+2\mathcal{A} = G + \R^2_+ (everything above and to the right). Rotate the supporting line with λ\lambda: its tt-axis intercept is g(λ)g(\lambda) (lower panel). In “Convex”, λ⋆=2\lambda^\star = 2 raises it to (0,p⋆)(0, p^\star) and gg reaches p⋆p^\star. In “Nonconvex”, the well of f0f_0 at x=0x = 0 (infeasible) makes A\mathcal{A} nonconvex; increase κ\kappa and see the convex envelope (magenta) cross the tt axis below p⋆p^\star: that gap is the duality gap. In “No Slater” the problem is convex but only x=0x = 0 is feasible, and no finite-slope line passes through (0,1)(0, 1).

Three observations about the figure:

  1. Weak duality in one sentence. A supporting line of slope −λ≤0-\lambda \le 0 rises leftward: points of GG with u≤0u \le 0 lie above it, in particular above its height g(λ)g(\lambda) at u=0u = 0. Hence p⋆≥g(λ)p^\star \ge g(\lambda), and λ≥0\lambda \ge 0 is needed: positive slope would make the line decrease leftward and the conclusion fail.
  2. The dual sees only the convex envelope. The infimum of linear function λu+t\lambda u + t is the same over GG, A\mathcal{A} and either convex envelope, so gg and d⋆d^\star depend only on the convex envelope boundary of A\mathcal{A} at u=0u = 0. If A\mathcal{A} is already convex, that boundary is GG‘s and nothing is lost. Otherwise the gap p⋆−d⋆p^\star - d^\star is the vertical distance between GG and its envelope at u=0u = 0.
  3. Convexity alone is not quite enough. In the third case A\mathcal{A} is convex, but the only supporting line at (0,p⋆)(0, p^\star) is vertical and corresponds to no finite λ\lambda. An assumption ruling out vertical lines is needed: Slater’s condition.

Strong duality

Strong duality does not always hold, even for convex problems. It holds with a qualification such as Slater’s, seen in the previous lesson as one condition guaranteeing KKT. Its role here is to rule out the vertical line.

Proof

By Slater, p⋆<+∞p^\star < +\infty; if p⋆=−∞p^\star = -\infty, weak duality gives d⋆=−∞d^\star = -\infty and nothing remains. Let p⋆p^\star be finite. Define two sets in Rm×Rp×R\R^m \times \R^p \times \R:

A={(u,v,t):∃ x, fi(x)≤ui ∀i,  Ax−b=v,  f0(x)≤t},B={(0,0,s):s<p⋆}.\mathcal{A} = \{ (\vb{u}, \vb{v}, t) : \exists\,\vb{x},\ f_i(\vb{x}) \le u_i\ \forall i,\ \ \mat{A}\vb{x} - \vb{b} = \vb{v},\ \ f_0(\vb{x}) \le t \}, \qquad \mathcal{B} = \{ (\vb{0}, \vb{0}, s) : s < p^\star \}.

Both are convex: B\mathcal{B} is an open segment, and if (u,v,t)(\vb{u}, \vb{v}, t) and (u′,v′,t′)(\vb{u}', \vb{v}', t') lie in A\mathcal{A} with witnesses x\vb{x} and x′\vb{x}', witness θx+(1−θ)x′\theta\vb{x} + (1 - \theta)\vb{x}' satisfies inequalities for the convex combination by convexity of fif_i, and equality by affinity. They are disjoint: a common point (0,0,s)(\vb{0}, \vb{0}, s) would have feasible x\vb{x} with f0(x)≤s<p⋆f_0(\vb{x}) \le s < p^\star, impossible.

By the separating hyperplane theorem for two disjoint convex sets (obtained from the point-versus-closed-convex-set version, applied to 0∉A−B0 \notin \mathcal{A} - \mathcal{B}; if 00 lies in the closure, separate points zk→0\vb{z}_k \to \vb{0} outside it and take a limit of unit normals), there are (λ~,ν~,μ)≠0(\tilde{\vb{\lambda}}, \tilde{\vb{\nu}}, \mu) \ne \vb{0} and α\alpha with

λ~⊤u+ν~⊤v+μt ≥ α  ∀(u,v,t)∈A,μs≤α  ∀s<p⋆.\tilde{\vb{\lambda}}\T\vb{u} + \tilde{\vb{\nu}}\T\vb{v} + \mu t \ \ge\ \alpha \ \ \forall (\vb{u}, \vb{v}, t) \in \mathcal{A}, \qquad\qquad \mu s \le \alpha \ \ \forall s < p^\star.

Since uiu_i and tt can increase without limit inside A\mathcal{A}, the first inequality forces λ~⪰0\tilde{\vb{\lambda}} \succeq \vb{0} and μ≥0\mu \ge 0. The second gives μp⋆≤α\mu p^\star \le \alpha. Using points (f1(x),…,fm(x),Ax−b,f0(x))(f_1(\vb{x}), \dots, f_m(\vb{x}), \mat{A}\vb{x} - \vb{b}, f_0(\vb{x})) in the first yields, for every x\vb{x},

∑iλ~ifi(x)+ν~⊤(Ax−b)+μf0(x) ≥ α ≥ μp⋆.(∗)\sum_i \tilde{\lambda}_i f_i(\vb{x}) + \tilde{\vb{\nu}}\T(\mat{A}\vb{x} - \vb{b}) + \mu f_0(\vb{x}) \ \ge\ \alpha \ \ge\ \mu p^\star. \tag{$*$}

Case μ>0\mu > 0. Dividing by μ\mu, L(x,λ~/μ,ν~/μ)≥p⋆L(\vb{x}, \tilde{\vb{\lambda}}/\mu, \tilde{\vb{\nu}}/\mu) \ge p^\star for every x\vb{x}, that is g(λ~/μ,ν~/μ)≥p⋆g(\tilde{\vb{\lambda}}/\mu, \tilde{\vb{\nu}}/\mu) \ge p^\star. Weak duality makes this equality and the dual is attained there.

Case μ=0\mu = 0 (where Slater enters). Then (∗)(*) says ∑iλ~ifi(x)+ν~⊤(Ax−b)≥0\sum_i \tilde{\lambda}_i f_i(\vb{x}) + \tilde{\vb{\nu}}\T(\mat{A}\vb{x} - \vb{b}) \ge 0 for every x\vb{x}. At x^\hat{\vb{x}} the second term vanishes and ∑iλ~ifi(x^)≥0\sum_i \tilde{\lambda}_i f_i(\hat{\vb{x}}) \ge 0 remains with every fi(x^)<0f_i(\hat{\vb{x}}) < 0 and λ~i≥0\tilde{\lambda}_i \ge 0: possible only if λ~=0\tilde{\vb{\lambda}} = \vb{0}. Then ν~⊤(Ax−b)≥0\tilde{\vb{\nu}}\T(\mat{A}\vb{x} - \vb{b}) \ge 0 for every x∈Rn\vb{x} \in \R^n: an affine function bounded below on the whole space is constant, so A⊤ν~=0\mat{A}\T\tilde{\vb{\nu}} = \vb{0} and, by the rank of A\mat{A}, ν~=0\tilde{\vb{\nu}} = \vb{0}. But then (λ~,ν~,μ)=0(\tilde{\vb{\lambda}}, \tilde{\vb{\nu}}, \mu) = \vb{0}, contradicting nonzero. The case μ=0\mu = 0 is impossible. ■\blacksquare

∎

The proof is the figure: separating A\mathcal{A} from B\mathcal{B} means finding the supporting line at (0,p⋆)(0, p^\star), and μ=0\mu = 0 is the vertical line Slater rules out. Four nuances:

  • Slater is sufficient, not necessary. Problems without a strictly feasible point may have strong duality.
  • Affine constraints need not be strict. In the refined version, strict feasibility is needed only for non-affine fif_i, and ordinary feasibility for affine ones. In particular, an LP with finite optimum always has strong duality and the dual attains its optimum, without further checks (Boyd and Vandenberghe, §5.2.3 and §5.2.4).
  • Proper domains. If f0f_0 or fif_i are defined only on a domain, the Slater point must be in its relative interior.
  • Convex without Slater, with a gap. With variables (x,y)(x, y) and domain y>0y > 0, minimizing e−xe^{-x} subject to x2/y≤0x^2/y \le 0 is convex; the constraint forces x=0x = 0 and p⋆=1p^\star = 1. But L=e−x+λx2/yL = e^{-x} + \lambda x^2/y has infimum 00 for every λ≥0\lambda \ge 0 (take y→∞y \to \infty then x→∞x \to \infty), so d⋆=0<1=p⋆d^\star = 0 < 1 = p^\star. This is the figure’s third case.

Strong duality and KKT: the same story

The preceding lesson ended with KKT conditions for deciding optimality. Duality explains them: they are exactly the conditions for zero gap.

Proof

With strong duality, f0(x⋆)=g(λ⋆,ν⋆)=inf⁡xL(x,λ⋆,ν⋆)≤L(x⋆,λ⋆,ν⋆)=f0(x⋆)+∑iλi⋆fi(x⋆)≤f0(x⋆)f_0(\vb{x}^\star) = g(\vb{\lambda}^\star, \vb{\nu}^\star) = \inf_{\vb{x}} L(\vb{x}, \vb{\lambda}^\star, \vb{\nu}^\star) \le L(\vb{x}^\star, \vb{\lambda}^\star, \vb{\nu}^\star) = f_0(\vb{x}^\star) + \sum_i \lambda_i^\star f_i(\vb{x}^\star) \le f_0(\vb{x}^\star), where the last step uses λi⋆≥0\lambda_i^\star \ge 0, fi(x⋆)≤0f_i(\vb{x}^\star) \le 0 and hj(x⋆)=0h_j(\vb{x}^\star) = 0. The chain starts and ends at the same number, so all inequalities are equalities: the first says x⋆\vb{x}^\star attains the infimum of L(⋅,λ⋆,ν⋆)L(\cdot, \vb{\lambda}^\star, \vb{\nu}^\star) (and, if differentiable, ∇xL=0\grad_{\vb{x}} L = \vb{0}: stationarity); the second says ∑iλi⋆fi(x⋆)=0\sum_i\lambda_i^\star f_i(\vb{x}^\star) = 0 with all terms ≤0\le 0, i.e. complementary slackness. The converse is the preceding lesson’s sufficiency argument: with λ⋆⪰0\vb{\lambda}^\star \succeq \vb{0} the Lagrangian is convex in x\vb{x} and its gradient vanishes at x⋆\vb{x}^\star, so g(λ⋆,ν⋆)=L(x⋆,λ⋆,ν⋆)=f0(x⋆)g(\vb{\lambda}^\star, \vb{\nu}^\star) = L(\vb{x}^\star, \vb{\lambda}^\star, \vb{\nu}^\star) = f_0(\vb{x}^\star). ■\blacksquare

∎

Rewriting the gap makes it practical. If x^\hat{\vb{x}} is feasible and minimizes L(⋅,λ^,ν^)L(\cdot, \hat{\vb{\lambda}}, \hat{\vb{\nu}}) (so g=L(x^,λ^,ν^)g = L(\hat{\vb{x}}, \hat{\vb{\lambda}}, \hat{\vb{\nu}})), then

f0(x^)−g(λ^,ν^)=−∑i=1mλ^ifi(x^)=∑iλ^i ∣fi(x^)∣ ≥0.f_0(\hat{\vb{x}}) - g(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) = -\sum_{i=1}^m \hat{\lambda}_i f_i(\hat{\vb{x}}) = \sum_i \hat{\lambda}_i\,\abs{f_i(\hat{\vb{x}})} \ \ge 0.

The gap is total violation of complementary slackness: each inactive constraint with positive multiplier contributes a piece. Interior-point methods exploit this identity: they maintain “controlled” slack λifi=−1/τ\lambda_i f_i = -1/\tau and the gap is m/τm/\tau.

Examples: duals of familiar problems

A good habit when deriving a dual is to follow three steps: write the Lagrangian, minimize over x\vb{x} (recording which multipliers give a finite minimum), and substitute. Four frequently reused cases.

Standard-form linear program. To minimize c⊤x\vb{c}\T\vb{x} with Ax=b\mat{A}\vb{x} = \vb{b} and x⪰0\vb{x} \succeq \vb{0} (inequalities −xk≤0-x_k \le 0 have multipliers λk≥0\lambda_k \ge 0), L=c⊤x−λ⊤x+ν⊤(Ax−b)=(c+A⊤ν−λ)⊤x−b⊤νL = \vb{c}\T\vb{x} - \vb{\lambda}\T\vb{x} + \vb{\nu}\T(\mat{A}\vb{x} - \vb{b}) = (\vb{c} + \mat{A}\T\vb{\nu} - \vb{\lambda})\T\vb{x} - \vb{b}\T\vb{\nu}. It is linear in x\vb{x}: its infimum is −∞-\infty unless the coefficient vanishes, when it equals −b⊤ν-\vb{b}\T\vb{\nu}. Thus

g(λ,ν)={−b⊤νif A⊤ν−λ+c=0,−∞otherwise,y el dual esmax⁡ b⊤y  subject to  A⊤y⪯c,g(\vb{\lambda}, \vb{\nu}) = \begin{cases} -\vb{b}\T\vb{\nu} & \text{if } \mat{A}\T\vb{\nu} - \vb{\lambda} + \vb{c} = \vb{0},\\ -\infty & \text{otherwise,}\end{cases} \qquad\text{y el dual es}\qquad \max\ \vb{b}\T\vb{y} \ \ \text{subject to}\ \ \mat{A}\T\vb{y} \preceq \vb{c},

with y=−ν\vb{y} = -\vb{\nu} (multiplier λ\vb{\lambda} is eliminated: it is slack s=c−A⊤y⪰0\vb{s} = \vb{c} - \mat{A}\T\vb{y} \succeq \vb{0}). The implicit constraint of gg has become the dual constraint. For an inequality-form LP, minimizing c⊤x\vb{c}\T\vb{x} with Ax⪯b\mat{A}\vb{x} \preceq \vb{b}, the same calculation gives maximizing −b⊤λ-\vb{b}\T\vb{\lambda} with A⊤λ+c=0\mat{A}\T\vb{\lambda} + \vb{c} = \vb{0} and λ⪰0\vb{\lambda} \succeq \vb{0}. The production problem, maximizing p⊤x\vb{p}\T\vb{x} with Ax⪯b\mat{A}\vb{x} \preceq \vb{b} and x⪰0\vb{x} \succeq \vb{0} (profits p\vb{p}, resources b\vb{b}), has dual minimizing b⊤y\vb{b}\T\vb{y} with A⊤y⪰p\mat{A}\T\vb{y} \succeq \vb{p} and y⪰0\vb{y} \succeq \vb{0}: set resource prices y\vb{y} so making each product earns no more than its resource cost. This is the shadow price of the sensitivity section. By refined Slater, a finite LP optimum guarantees strong duality, characterized by complementary slackness xksk=0x_k s_k = 0: a product is made only when resource cost equals profit, and a positively priced resource is exhausted.

Quadratic program. To minimize 12x⊤Px+q⊤x\tfrac12\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} with P≻0\mat{P} \succ 0 and Ax⪯b\mat{A}\vb{x} \preceq \vb{b}, L=12x⊤Px+(q+A⊤λ)⊤x−b⊤λL = \tfrac12\vb{x}\T\mat{P}\vb{x} + (\vb{q} + \mat{A}\T\vb{\lambda})\T\vb{x} - \vb{b}\T\vb{\lambda} is strictly convex quadratic in x\vb{x}, minimized at x=−P−1(q+A⊤λ)\vb{x} = -\mat{P}\inv(\vb{q} + \mat{A}\T\vb{\lambda}), so

g(λ)=−12(q+A⊤λ)⊤P−1(q+A⊤λ)−b⊤λ,λ⪰0.g(\vb{\lambda}) = -\tfrac12 (\vb{q} + \mat{A}\T\vb{\lambda})\T\mat{P}\inv(\vb{q} + \mat{A}\T\vb{\lambda}) - \vb{b}\T\vb{\lambda}, \qquad \vb{\lambda} \succeq \vb{0}.

The dual of a QP is another, concave QP with only sign constraint λ⪰0\vb{\lambda} \succeq \vb{0}; recover the primal as x⋆=−P−1(q+A⊤λ⋆)\vb{x}^\star = -\mat{P}\inv(\vb{q} + \mat{A}\T\vb{\lambda}^\star). This is the support vector machine dual form, where quadratic-term matrix AP−1A⊤\mat{A}\mat{P}\inv\mat{A}\T is a Gram matrix of data (inner products), enabling kernels.

Minimum-norm least squares. Minimize ∥x∥22\norm{\vb{x}}_2^2 with Ax=b\mat{A}\vb{x} = \vb{b}, A∈Rm×n\mat{A} \in \R^{m \times n} with m<nm < n and rank mm. Here L=x⊤x+ν⊤(Ax−b)L = \vb{x}\T\vb{x} + \vb{\nu}\T(\mat{A}\vb{x} - \vb{b}) is minimized at x=−12A⊤ν\vb{x} = -\tfrac12\mat{A}\T\vb{\nu} and

g(ν)=−14∥A⊤ν∥22−b⊤ν.g(\vb{\nu}) = -\tfrac14\norm{\mat{A}\T\vb{\nu}}_2^2 - \vb{b}\T\vb{\nu}.

It is concave and its maximum is at ∇g=−12AA⊤ν−b=0\grad g = -\tfrac12\mat{A}\mat{A}\T\vb{\nu} - \vb{b} = \vb{0}, that is ν⋆=−2(AA⊤)−1b\vb{\nu}^\star = -2(\mat{A}\mat{A}\T)\inv\vb{b}. Recovering the primal, x⋆=A⊤(AA⊤)−1b=A+b\vb{x}^\star = \mat{A}\T(\mat{A}\mat{A}\T)\inv\vb{b} = \mat{A}\pinv\vb{b}, the pseudoinverse solution from the pseudoinverse and minimum-norm solution lesson: the dual derives it without knowing the pseudoinverse. Constraints are affine, so strong duality is guaranteed.

[ ]Dual of minimum-norm least squaresBrowser
import numpy as np

rng = np.random.default_rng(2)
A = rng.normal(size=(3, 7)); b = rng.normal(size=3)

g = lambda nu: -0.25 * np.sum((A.T @ nu) ** 2) - b @ nu        # función dual de min ||x||² s.a. Ax = b
nu_star = -2 * np.linalg.solve(A @ A.T, b)                      # su máximo: grad g = 0
x_star = -0.5 * A.T @ nu_star                                   # minimizador de L(·, nu*)

print("g(nu*) =", round(g(nu_star), 8), "  ||x*||² =", round(x_star @ x_star, 8))
print("x* coincide con la pseudoinversa A⁺b:", np.allclose(x_star, np.linalg.pinv(A) @ b))
print("nu* maximiza g (1000 perturbaciones al azar):", all(g(nu_star + rng.normal(size=3)) <= g(nu_star) + 1e-12 for _ in range(1000)))

Lasso. Minimizing P(x)=12∥Ax−b∥22+λ∥x∥1P(\vb{x}) = \tfrac12\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \lambda\norm{\vb{x}}_1 has no constraints, hence no dual until one is created: introduce z=Ax−b\vb{z} = \mat{A}\vb{x} - \vb{b} as a new variable with multiplier ν\vb{\nu}. Then L=12∥z∥2+λ∥x∥1+ν⊤(Ax−b−z)L = \tfrac12\norm{\vb{z}}^2 + \lambda\norm{\vb{x}}_1 + \vb{\nu}\T(\mat{A}\vb{x} - \vb{b} - \vb{z}) separates into z\vb{z} and x\vb{x}:

  • inf⁡z(12∥z∥2−ν⊤z)=−12∥ν∥2\inf_{\vb{z}}\big(\tfrac12\norm{\vb{z}}^2 - \vb{\nu}\T\vb{z}\big) = -\tfrac12\norm{\vb{\nu}}^2 (at z=ν\vb{z} = \vb{\nu});
  • inf⁡x(λ∥x∥1+(A⊤ν)⊤x)\inf_{\vb{x}}\big(\lambda\norm{\vb{x}}_1 + (\mat{A}\T\vb{\nu})\T\vb{x}\big) is 00 if ∥A⊤ν∥∞≤λ\norm{\mat{A}\T\vb{\nu}}_\infty \le \lambda and −∞-\infty otherwise: if any ∣(A⊤ν)k∣>λ\abs{(\mat{A}\T\vb{\nu})_k} > \lambda, take x\vb{x} along that axis with suitable sign and the term decreases without bound; if all satisfy the bound, λ∣xk∣+(A⊤ν)kxk≥0\lambda\abs{x_k} + (\mat{A}\T\vb{\nu})_k x_k \ge 0.

With substitution θ=−ν\vb{\theta} = -\vb{\nu} and adding and subtracting 12∥b∥2\tfrac12\norm{\vb{b}}^2, the dual is

max⁡θ D(θ)=12∥b∥2−12∥θ−b∥2subject to∥A⊤θ∥∞≤λ.\max_{\vb{\theta}}\ D(\vb{\theta}) = \tfrac12\norm{\vb{b}}^2 - \tfrac12\norm{\vb{\theta} - \vb{b}}^2 \qquad \text{subject to}\qquad \norm{\mat{A}\T\vb{\theta}}_\infty \le \lambda.

The lasso dual is a projection: find the point of polytope {θ:∥A⊤θ∥∞≤λ}\{\vb{\theta} : \norm{\mat{A}\T\vb{\theta}}_\infty \le \lambda\} nearest b\vb{b}. Strong duality holds (the problem is convex and constraint z=Ax−b\vb{z} = \mat{A}\vb{x} - \vb{b} affine), and the dual solution is the residual, θ⋆=b−Ax⋆\vb{\theta}^\star = \vb{b} - \mat{A}\vb{x}^\star. This yields three things:

  1. A dual bound for any x\vb{x}. Residual b−Ax\vb{b} - \mat{A}\vb{x} usually violates the θ\vb{\theta} constraint, but scaling fixes it: θ=α(b−Ax)\vb{\theta} = \alpha(\vb{b} - \mat{A}\vb{x}) with α=min⁡{1, λ/∥A⊤(b−Ax)∥∞}\alpha = \min\{1,\ \lambda/\norm{\mat{A}\T(\vb{b} - \mat{A}\vb{x})}_\infty\} is dual feasible. With it, the duality gap at x\vb{x} is P(x)−D(θ)P(\vb{x}) - D(\vb{\theta}).
  2. Complementary slackness. Stationarity says A⊤θ⋆∈λ ∂∥x⋆∥1\mat{A}\T\vb{\theta}^\star \in \lambda\,\partial\norm{\vb{x}^\star}_1, meaning ak⊤θ⋆=λsign⁡(xk⋆)\vb{a}_k\T\vb{\theta}^\star = \lambda\operatorname{sign}(x_k^\star) if xk⋆≠0x_k^\star \ne 0 and ∣ak⊤θ⋆∣≤λ\abs{\vb{a}_k\T\vb{\theta}^\star} \le \lambda if zero (with ak\vb{a}_k column kk of A\mat{A}). In particular, ∣ak⊤θ⋆∣<λ\abs{\vb{a}_k\T\vb{\theta}^\star} < \lambda implies xk⋆=0x_k^\star = 0: inactive variables can be identified from the dual.
  3. Safe variable screening. DD is strongly concave with modulus 11, so for any dual-feasible θ\vb{\theta}, 12∥θ−θ⋆∥2≤D(θ⋆)−D(θ)≤P(x)−D(θ)=gap\tfrac12\norm{\vb{\theta} - \vb{\theta}^\star}^2 \le D(\vb{\theta}^\star) - D(\vb{\theta}) \le P(\vb{x}) - D(\vb{\theta}) = \text{gap}, meaning θ⋆\vb{\theta}^\star lies in a ball of radius 2 gap\sqrt{2\,\text{gap}} around θ\vb{\theta}. If ∣ak⊤θ∣+∥ak∥2 gap<λ\abs{\vb{a}_k\T\vb{\theta}} + \norm{\vb{a}_k}\sqrt{2\,\text{gap}} < \lambda, then ∣ak⊤θ⋆∣<λ\abs{\vb{a}_k\T\vb{\theta}^\star} < \lambda and xk⋆=0x_k^\star = 0 with certainty: the variable can be removed. The smaller the gap, the more variables can be screened. This is the idea of Fercoq, Gramfort and Salmon’s (2015) Gap Safe rules.

The gap as a stopping criterion

We now have everything for a guaranteed solver. The interactive runs proximal descent (iterations xk+1=Sλ/L(xk−1LA⊤(Axk−b))\vb{x}_{k+1} = \mathrm{S}_{\lambda/L}(\vb{x}_k - \tfrac1L\mat{A}\T(\mat{A}\vb{x}_k - \vb{b})), the method of the proximal methods lesson; the choice does not matter) on a lasso with 4040 rows and 6060 columns, and calculates each iteration’s primal value P(xk)P(\vb{x}_k), scaled dual bound DD above, and their difference.

InteractivePrimal and dual converging
  • P(xk)P(\vb{x}_k) primal
  • DD dual bound
  • p⋆p^\star
  • gap P−DP - D
  • true suboptimality P−p⋆P - p^\star
  • tolerance ε\varepsilon
k = 0
−1.50
Dual point
iteration kk0
primal P(xk)P(\vb{x}_k)6.5008
dual bound DD0.7567
gap P−DP - D5.74e0
true suboptimality P−p⋆P - p^\star4.93e0
D≤p⋆D \le p^\star?yes, a bound
A solver with ε=3.2⋅10−2\varepsilon = 3.2\cdot 10^{-2} stops at k=504k = 504: gap =3.1⋅10−2≤ε= 3.1\cdot 10^{-2} \le \varepsilon, and true suboptimality, 1.3⋅10−41.3\cdot 10^{-4}, is no greater. The certificate is conservative but never lies.
When can a solver stop without knowing the optimum? Above, primal value (blue) decreases and dual bound (aqua) increases; optimum p⋆p^\star always lies between them. Below, on a logarithmic scale, gap (magenta) and true suboptimality P−p⋆P - p^\star (blue), calculable only afterward with very precise p⋆p^\star. Move the tolerance: the cursor jumps to the first iteration with gap below ε\varepsilon, and true suboptimality always stays below the gap. “Best so far” stores the best dual bound seen. “Unscaled” uses the raw residual, an infeasible dual point: the “bound” lies above p⋆p^\star (starts at P(0)P(\vb{0}) and decreases toward it), the gap becomes zero or negative, and the solver would stop falsely.

As you interact, see that the gap always bounds true suboptimality. Initially both are of the same order, but as iterations advance the slack grows to several orders of magnitude (at iteration 800800, gap 2⋅10−32\cdot 10^{-3} versus suboptimality 8⋅10−78\cdot 10^{-7}), because the scaled dual point converges more slowly than the primal: the gap is a conservative certificate that never lies but certifies less than the iterate has achieved. With the unscaled point, the dual bound starts exactly at P(0)P(\vb{0}), well above p⋆p^\star: at x0=0\vb{x}_0 = \vb{0} the unscaled residual is −b-\vb{b}, its dual value is 12∥b∥2=P(0)\tfrac12\norm{\vb{b}}^2 = P(\vb{0}) and the “gap” is 00; in later iterations it is negative. A stopping rule based on it would terminate at iteration 00.

Convex conjugate and Fenchel duality

One part of duality needs no constraints. Examining the infimum of LL over x\vb{x} for lasso led to calculating sup⁡x(y⊤x−λ∥x∥1)\sup_{\vb{x}}(\vb{y}\T\vb{x} - \lambda\norm{\vb{x}}_1): the height to which a line of given slope rises without crossing a function. This is the conjugate, and its table of results helps derive duals in sequence.

The geometric interpretation is the dual’s: for each slope y\vb{y}, line (or hyperplane) x↦y⊤x−f∗(y)\vb{x} \mapsto \vb{y}\T\vb{x} - f^*(\vb{y}) is the largest affine function of slope y\vb{y} lying below ff, and −f∗(y)-f^*(\vb{y}) is its intercept. Immediately: f(x)≥y⊤x−f∗(y)f(\vb{x}) \ge \vb{y}\T\vb{x} - f^*(\vb{y}) for every x\vb{x}. Four frequently used properties:

  1. f∗f^* is convex and closed, regardless of ff: it is a supremum of affine functions of y\vb{y} (dual to “the dual function is concave”).
  2. Fenchel-Young inequality. f(x)+f∗(y)≥y⊤xf(\vb{x}) + f^*(\vb{y}) \ge \vb{y}\T\vb{x} for all x,y\vb{x}, \vb{y}, the definition rewritten. Equality holds iff x\vb{x} maximizes y⊤x−f(x)\vb{y}\T\vb{x} - f(\vb{x}), meaning (for convex ff) y∈∂f(x)\vb{y} \in \partial f(\vb{x}), and for differentiable ff, y=∇f(x)\vb{y} = \grad f(\vb{x}).
  3. Biconjugate. f∗∗f^{**} is the largest closed convex function below ff (its closed convex envelope). Indeed f∗∗(x)=sup⁡y(y⊤x−f∗(y))f^{**}(\vb{x}) = \sup_{\vb{y}}(\vb{y}\T\vb{x} - f^*(\vb{y})) is the supremum of affine minorants of ff (one per slope), and a supremum of affine minorants is the largest closed convex function below ff, because a closed convex function is the supremum of its affine minorants (from separating the epigraph from points below). In particular, f∗∗=ff^{**} = f iff ff is convex and closed (Fenchel-Moreau theorem). With nonconvex ff, the conjugate “sees” only what a line can touch from below.
  4. Differentiability and gradient. If ff is strictly convex and differentiable, f∗f^* is differentiable in the interior of its domain and there ∇f∗=(∇f)−1\grad f^* = (\grad f)\inv: the gradient of f∗f^* at y\vb{y} is the contact point. (With f=exf = e^x, f∗f^* is finite at y=0y = 0 but not differentiable there: the horizontal line never touches.)

The figure sweeps the slope and shows the conjugate being traced.

InteractiveThe conjugate as envelope of tangents
The function f(x)=12x2f(x) = \tfrac12 x^2 and the line of slope yy touching it from below
Its conjugate f∗(y)=12y2f^*(y) = \tfrac12 y^2, traced progressively
y = −3.00
  • ff
  • line of slope yy (tangent from below)
  • f∗f^*
  • f(x)+f∗(y)−xy≥0f(x) + f^*(y) - xy \ge 0
  • f∗∗f^{**}
1.50
slope yy−3.00
f∗(y)f^*(y)4.500
line intercept at x=0x = 0 (−f∗-f^*)−4.500
contact x⋆x^\star (with y∈∂f(x⋆)y \in \partial f(x^\star))−3.00
f(x)+f∗(y)−xyf(x) + f^*(y) - xy, at test xx10.125
It is its own conjugate: the only function with f∗=ff^* = f. The line of slope yy touches at x=yx = y.
Which line of slope yy touches ff from below, and what height does it reach at the origin? Play the yy sweep (or drag the timeline): the orange line of slope yy touches ff at the contact point, its intercept at x=0x = 0 is −f∗(y)-f^*(y), and the graph of f∗f^* (below) is traced. The slider's test xx measures vertical distance between ff and the line, f(x)+f∗(y)−xy≥0f(x) + f^*(y) - xy \ge 0 (Fenchel-Young), zero only at contact. With ∣x∣\lvert x\rvert and exe^x, some slopes have no line below (f∗=+∞f^* = +\infty). For the nonconvex double-well function, enable f∗∗f^{**}: no line touches the central peak, and the biconjugate flattens it.

Conjugates to know

f(x)f(\vb{x})f∗(y)f^*(\vb{y})Domain of f∗f^*
12∥x∥22\tfrac12\norm{\vb{x}}_2^212∥y∥22\tfrac12\norm{\vb{y}}_2^2Rn\R^n
12x⊤Qx\tfrac12\vb{x}\T\mat{Q}\vb{x}, Q≻0\mat{Q} \succ 012y⊤Q−1y\tfrac12\vb{y}\T\mat{Q}\inv\vb{y}Rn\R^n
a norm ∥x∥\norm{\vb{x}}00 if ∥y∥∗≤1\norm{\vb{y}}_* \le 1, +∞+\infty otherwisedual norm ball
12x2+∣x∣\tfrac12 x^2 + \abs{x} (on R\R)12(∣y∣−1)+2\tfrac12(\abs{y} - 1)_+^2R\R
exe^xyln⁡y−yy\ln y - y (with 0ln⁡0=00\ln 0 = 0)y≥0y \ge 0
log⁡∑iexi\log\sum_i e^{x_i}∑iyiln⁡yi\sum_i y_i\ln y_iy⪰0\vb{y} \succeq \vb{0}, 1⊤y=1\vb{1}\T\vb{y} = 1
∑ixiln⁡xi\sum_i x_i\ln x_i (negative entropy, x⪰0\vb{x} \succeq \vb{0})∑ieyi−1\sum_i e^{y_i - 1}Rn\R^n
−log⁡x-\log x−1−log⁡(−y)-1 - \log(-y)y<0y < 0
indicator 1C(x)\ind_C(\vb{x})support function sup⁡x∈Cy⊤x\sup_{\vb{x} \in C}\vb{y}\T\vb{x}Rn\R^n if CC is bounded

The dual norm is ∥y∥∗=sup⁡{y⊤x:∥x∥≤1}\norm{\vb{y}}_* = \sup\{\vb{y}\T\vb{x} : \norm{\vb{x}} \le 1\}. For norms on ℓp\ell_p spaces, the dual of ∥⋅∥p\norm{\cdot}_p is ∥⋅∥q\norm{\cdot}_q with 1/p+1/q=11/p + 1/q = 1 (the dual of ∥⋅∥1\norm{\cdot}_1 is ∥⋅∥∞\norm{\cdot}_\infty, and ∥⋅∥2\norm{\cdot}_2 is self-dual). Two representative proofs:

Proof

A norm. Let f(x)=∥x∥f(\vb{x}) = \norm{\vb{x}}. If ∥y∥∗≤1\norm{\vb{y}}_* \le 1, the dual norm definition gives y⊤x≤∥y∥∗∥x∥≤∥x∥\vb{y}\T\vb{x} \le \norm{\vb{y}}_*\norm{\vb{x}} \le \norm{\vb{x}}, so y⊤x−∥x∥≤0\vb{y}\T\vb{x} - \norm{\vb{x}} \le 0, with equality at x=0\vb{x} = \vb{0}: f∗(y)=0f^*(\vb{y}) = 0. If ∥y∥∗>1\norm{\vb{y}}_* > 1, some z\vb{z} has ∥z∥≤1\norm{\vb{z}} \le 1 and y⊤z>1\vb{y}\T\vb{z} > 1, and with x=tz\vb{x} = t\vb{z} we have y⊤x−∥x∥≥t(y⊤z−1)→∞\vb{y}\T\vb{x} - \norm{\vb{x}} \ge t(\vb{y}\T\vb{z} - 1) \to \infty as t→∞t \to \infty: f∗(y)=+∞f^*(\vb{y}) = +\infty.

Log-sum-exp. Let f(x)=log⁡∑iexif(\vb{x}) = \log\sum_i e^{x_i}. If y⪰0\vb{y} \succeq \vb{0} and 1⊤y=1\vb{1}\T\vb{y} = 1, the gradient of y⊤x−f(x)\vb{y}\T\vb{x} - f(\vb{x}) is y−softmax⁡(x)\vb{y} - \softmax(\vb{x}), vanishing at x=log⁡y\vb{x} = \log\vb{y} (with yi>0y_i > 0; take the limit at the boundary), where value is ∑iyiln⁡yi−log⁡∑iyi=∑iyiln⁡yi\sum_i y_i\ln y_i - \log\sum_i y_i = \sum_i y_i\ln y_i, and concavity makes it the maximum. If 1⊤y≠1\vb{1}\T\vb{y} \ne 1, x=t1\vb{x} = t\vb{1} gives t(1⊤y−1)−log⁡nt(\vb{1}\T\vb{y} - 1) - \log n, unbounded as t→±∞t \to \pm\infty. If any yi<0y_i < 0, x=−tei\vb{x} = -t\vb{e}_i gives t∣yi∣−log⁡(n−1+e−t)→∞t\abs{y_i} - \log(n - 1 + e^{-t}) \to \infty. ■\blacksquare

∎

The second proof has a noteworthy consequence: the gradient of log-sum-exp is softmax, and the conjugate lives on the simplex and is negative entropy. (Without the simplex constraint, negative entropy ∑ixiln⁡xi\sum_i x_i\ln x_i has conjugate ∑ieyi−1\sum_i e^{y_i - 1}: maximum of yx−xln⁡xy x - x\ln x occurs at x=ey−1x = e^{y - 1}.) Softmax and entropy are Legendre duals, explaining their appearance together in cross-entropy, maximum entropy, and entropy regularization.

[ ]Numerical conjugates and the Fenchel-Young inequalityBrowser
import numpy as np

xs = np.linspace(-12, 12, 24001)              # rejilla fina: f*(y) = max_x (y x - f(x))

def conjugada(f, y):
    return np.max(y * xs - f(xs))

casos = {
    "½x²":         (lambda x: 0.5 * x**2,                  lambda y: 0.5 * y**2,                         [-2.0, 0.7, 3.0]),
    "½x² + |x|":   (lambda x: 0.5 * x**2 + np.abs(x),      lambda y: 0.5 * max(abs(y) - 1, 0) ** 2,      [-3.0, 0.5, 3.0]),
    "eˣ":          (np.exp,                                lambda y: y * np.log(y) - y,                  [0.5, 1.0, 4.0]),
    "log(1 + eˣ)": (lambda x: np.logaddexp(0, x),          lambda y: y * np.log(y) + (1 - y) * np.log(1 - y), [0.1, 0.5, 0.9]),
}
for nombre, (f, fstar, ys) in casos.items():
    err = max(abs(conjugada(f, y) - fstar(y)) for y in ys)
    print(f"{nombre:12s} f*(y) numérica frente a la fórmula: error máximo {err:.1e}")

f, fstar = casos["½x² + |x|"][0], casos["½x² + |x|"][1]
print("f*(3) para ½x² + |x| =", round(conjugada(f, 3.0), 6))

# Desigualdad de Fenchel-Young: f(x) + f*(y) >= x y, con igualdad solo en el contacto
rng = np.random.default_rng(0)
peor = min(f(x) + fstar(y) - x * y for x, y in rng.uniform(-2, 2, size=(2000, 2)))
print("f(x) + f*(y) - xy >= 0 en 2000 pares al azar:", peor >= -1e-12)
print("en el contacto x* = 2, y = 3 (f'(2) = 3):", f(2.0) + fstar(3.0) - 2.0 * 3.0)

# f** de una función no convexa: su envolvente convexa
g = lambda x: (x**2 - 1) ** 2
yc = np.linspace(-40, 40, 801)
gs = np.array([conjugada(g, y) for y in yc])
for x in (0.0, 0.5, 1.0, 1.5):
    print(f"x = {x}: f(x) = {g(x):.4f},  f**(x) = {np.max(x * yc - gs):.4f}")

The numerical conjugate agrees with the table formulas, f∗(3)=2f^*(3) = 2 for 12x2+∣x∣\tfrac12x^2 + \abs{x} (calculated by hand in an exercise), and Fenchel-Young holds with equality only at contact. For the double well, f∗∗f^{**} is 00 on [−1,1][-1, 1] and agrees with ff outside: only the function sees the central peak (f(0)=1f(0) = 1); no line touches it from below.

Fenchel duality

The conjugate lets us write duals of problems with a sum of two terms without explicit constraints.

Proof

Weak duality is Fenchel-Young used twice: f(x)+f∗(−A⊤y)≥−y⊤Axf(\vb{x}) + f^*(-\mat{A}\T\vb{y}) \ge -\vb{y}\T\mat{A}\vb{x} and h(Ax)+h∗(y)≥y⊤Axh(\mat{A}\vb{x}) + h^*(\vb{y}) \ge \vb{y}\T\mat{A}\vb{x}. Adding, f(x)+h(Ax)≥−f∗(−A⊤y)−h∗(y)f(\vb{x}) + h(\mat{A}\vb{x}) \ge -f^*(-\mat{A}\T\vb{y}) - h^*(\vb{y}) for every x\vb{x} and y\vb{y}. Equality under the qualification is strong duality of the equivalent problem “minimize f(x)+h(z)f(\vb{x}) + h(\vb{z}) with z=Ax\vb{z} = \mat{A}\vb{x}”, whose dual is exactly d⋆d^\star (separation of the Lagrangian in x\vb{x} and z\vb{z} is the lasso construction). For functions finite everywhere this is Slater’s theorem above; for functions equal to +∞+\infty outside a domain, the relative-interior assumption plays the strictly feasible point’s role, and the proof is the same convex separation expressed with relative interiors (Rockafellar, corollary 31.2.1). ■\blacksquare

∎

Lasso is a case with f(x)=λ∥x∥1f(\vb{x}) = \lambda\norm{\vb{x}}_1, whose conjugate is the indicator of {w:∥w∥∞≤λ}\{\vb{w} : \norm{\vb{w}}_\infty \le \lambda\}, and h(z)=12∥z−b∥2h(\vb{z}) = \tfrac12\norm{\vb{z} - \vb{b}}^2, with h∗(y)=12∥y∥2+b⊤yh^*(\vb{y}) = \tfrac12\norm{\vb{y}}^2 + \vb{b}\T\vb{y}. The Fenchel dual maximizes −12∥y∥2−b⊤y-\tfrac12\norm{\vb{y}}^2 - \vb{b}\T\vb{y} with ∥A⊤y∥∞≤λ\norm{\mat{A}\T\vb{y}}_\infty \le \lambda: the same expression from the z\vb{z} construction. With a conjugate table, deriving a dual is mechanical: a norm becomes its dual ball (hence complexity bounds for linear classes, studied in statistical learning theory, use the data’s dual norm), a quadratic becomes its inverse, and entropy becomes log-sum-exp.

Sensitivity: multipliers are prices

So far the dual has bounded values. Its second major interpretation is that multipliers measure how much a constraint costs. Perturb problem (P) and study how the optimum moves: sensitivity analysis:

p⋆(u,v)=inf⁡{f0(x):fi(x)≤ui (i=1,…,m),  hj(x)=vj (j=1,…,p)},p^\star(\vb{u}, \vb{v}) = \inf\{ f_0(\vb{x}) : f_i(\vb{x}) \le u_i\ (i = 1, \dots, m),\ \ h_j(\vb{x}) = v_j\ (j = 1, \dots, p) \},

with p⋆(0,0)=p⋆p^\star(\vb{0}, \vb{0}) = p^\star. A ui>0u_i > 0 relaxes constraint ii (gives more room), and ui<0u_i < 0 tightens it.

Proof

Let x\vb{x} be feasible for the perturbed problem. Then p⋆=g(λ⋆,ν⋆)≤L(x,λ⋆,ν⋆)=f0(x)+∑iλi⋆fi(x)+∑jνj⋆hj(x)≤f0(x)+λ⋆Tu+ν⋆Tvp^\star = g(\vb{\lambda}^\star, \vb{\nu}^\star) \le L(\vb{x}, \vb{\lambda}^\star, \vb{\nu}^\star) = f_0(\vb{x}) + \sum_i\lambda_i^\star f_i(\vb{x}) + \sum_j\nu_j^\star h_j(\vb{x}) \le f_0(\vb{x}) + \vb{\lambda}^{\star\mathsf{T}}\vb{u} + \vb{\nu}^{\star\mathsf{T}}\vb{v}, where the last inequality uses λi⋆≥0\lambda_i^\star \ge 0 and fi(x)≤uif_i(\vb{x}) \le u_i, and hj(x)=vjh_j(\vb{x}) = v_j. Thus f0(x)≥p⋆−λ⋆Tu−ν⋆Tvf_0(\vb{x}) \ge p^\star - \vb{\lambda}^{\star\mathsf{T}}\vb{u} - \vb{\nu}^{\star\mathsf{T}}\vb{v}; the infimum over x\vb{x} gives the result. ■\blacksquare

∎

Function u↦p⋆(u,0)\vb{u} \mapsto p^\star(\vb{u}, \vb{0}) lies above hyperplane p⋆−λ⋆Tup^\star - \vb{\lambda}^{\star\mathsf{T}}\vb{u}, touching it at u=0\vb{u} = \vb{0}; read this carefully:

  • Large λi⋆\lambda_i^\star means tightening constraint ii (ui<0u_i < 0) greatly increases optimal cost: by at least λi⋆∣ui∣\lambda_i^\star\abs{u_i}. Relaxing it (ui>0u_i > 0) may save a lot.
  • Small or zero λi⋆\lambda_i^\star means relaxing it helps little: the optimum cannot improve by more than λi⋆ui\lambda_i^\star u_i. With λi⋆=0\lambda_i^\star = 0 (inactive or degenerate active constraint), nothing is gained to first order.
  • If p⋆(u,v)p^\star(\vb{u}, \vb{v}) is differentiable at the origin, λi⋆=−∂p⋆/∂ui\lambda_i^\star = -\partial p^\star / \partial u_i and νj⋆=−∂p⋆/∂vj\nu_j^\star = -\partial p^\star/\partial v_j: the bound is affine below p⋆(⋅)p^\star(\cdot) and touching at 0\vb{0}, possible only if slopes agree. The minus sign follows convention fi≤uif_i \le u_i: relaxing decreases cost.

In a production problem (maximize profit with limited resources), write −profit-\text{profit} as objective and the sign changes: the multiplier is profit increase per resource unit, λi⋆=∂(profit⋆)/∂bi≥0\lambda_i^\star = \partial(\text{profit}^\star)/\partial b_i \ge 0, resource ii‘s shadow price: the most one should pay for another unit. Its dual, setting prices y\vb{y} to minimize total resource value b⊤y\vb{b}\T\vb{y}, says the same: the market price making production and resource sale equally attractive. The calculation recurs in quantitative finance: in a minimum-variance portfolio with target return, its multiplier gives variance cost of each additional required return point, and an exposure limit’s multiplier gives variance added by maintaining it.

InteractiveShadow prices
  • 6x+4y≤b16x + 4y \le b_1
  • x+2y≤b2x + 2y \le b_2
  • profit level curve
  • c=λ1a1+λ2a2\vb{c} = \lambda_1\vb{a}_1 + \lambda_2\vb{a}_2
Optimal profit p⋆p^\star versus b1b_1 (the other availability is fixed)
Resource shown in curve
24.0
6.0
optimal production (x,y)(x, y)(3.00, 1.50)
optimal profit p⋆p^\star21.00
shadow price λ1\lambda_1 (raw material)0.75
shadow price λ2\lambda_2 (machine hours)0.50
b1λ1+b2λ2b_1\lambda_1 + b_2\lambda_2 (dual objective)21.00
linear segment of p⋆p^\star[12.0, 36.0]
One more unit of raw material is worth 0.750.75 in profit, only up to b=36.0b = 36.0 (or down to 12.012.0 if reduced). Outside this interval the price changes.
How much is an extra unit of resource worth, and how far does that price apply? Production LP: max⁡5x+4y\max 5x + 4y with 6x+4y≤b16x + 4y \le b_1 (raw material) and x+2y≤b2x + 2y \le b_2 (machine hours). Slide b1b_1 or b2b_2: above are the feasible region and optimum, with profit vector c\vb{c} decomposed into the two constraint normals (coefficients are shadow prices). Below, optimal profit versus selected resource: a concave piecewise-linear curve whose slope is the shadow price. Cross a basis change, shown by hollow points, and price jumps: the raw-material slope 0.750.75 holds only between b1=12b_1 = 12 and b1=36b_1 = 36. At the basis change the derivative does not exist and the multiplier is nonunique.

In the figure’s LP, with b=(24,6)\vb{b} = (24, 6) the optimum is (x,y)=(3,1.5)(x, y) = (3, 1.5) with profit 2121, and c=(5,4)=0.75 (6,4)+0.5 (1,2)\vb{c} = (5, 4) = 0.75\,(6, 4) + 0.5\,(1, 2): coefficients λ1⋆=0.75\lambda_1^\star = 0.75 and λ2⋆=0.5\lambda_2^\star = 0.5 are shadow prices, and strong duality is checked with b⊤λ⋆=24⋅0.75+6⋅0.5=21\vb{b}\T\vb{\lambda}^\star = 24 \cdot 0.75 + 6 \cdot 0.5 = 21. The following warning matters as much as the result.

[ ]Shadow prices with HiGHS and finite differencesBrowser
import numpy as np
from scipy.optimize import linprog

c = np.array([5.0, 4.0])                 # beneficio por unidad de A y de B
A = np.array([[6.0, 4.0], [1.0, 2.0]])   # consumo de materia prima y de horas de máquina

def resolver(b):
    # linprog minimiza: se cambia el signo del beneficio
    return linprog(-c, A_ub=A, b_ub=b, bounds=(0, None), method="highs")

r = resolver([24.0, 6.0])
lam = -r.ineqlin.marginals               # con la convención de esta lección, lambda >= 0
print("x* =", r.x, " beneficio =", -r.fun)
print("precios sombra de HiGHS:", lam, " ->  b·lambda =", np.array([24.0, 6.0]) @ lam)

# Derivada numérica del valor óptimo respecto de b1 y de b2 (diferencias centrales)
h = 1e-3
d1 = (-resolver([24 + h, 6]).fun + resolver([24 - h, 6]).fun) / (2 * h)
d2 = (-resolver([24, 6 + h]).fun + resolver([24, 6 - h]).fun) / (2 * h)
print(f"diferencias finitas: dp/db1 = {d1:.4f}, dp/db2 = {d2:.4f}")

# ¿Hasta dónde vale la aproximación lineal en b1?
print("\n   b1   p*(b1)   p*(24) + lambda1 (b1 - 24)   error")
for b1 in (8, 12, 16, 24, 30, 36, 40):
    p = -resolver([b1, 6.0]).fun
    lineal = 21.0 + lam[0] * (b1 - 24)
    print(f"{b1:5.0f} {p:8.3f} {lineal:18.3f} {p - lineal:14.3f}")

HiGHS returns λ⋆=(0.75,0.5)\vb{\lambda}^\star = (0.75, 0.5) (with marginals sign reversed: in linprog the multiplier of a ≤\le constraint in a minimization problem is ≤0\le 0), confirmed by finite differences. The table shows the exact segment: between b1=12b_1 = 12 and b1=36b_1 = 36 the linear approximation has no error; outside, it lies above the true value (as concavity requires).

Alternative theorems: infeasibility can also be certified

An alternative theorem says that, of two systems of equalities and inequalities, exactly one has a solution. It gives a short proof that one system has no solution: exhibit a solution of the other. Farkas’ is the most used.

The geometry is in the figure: (1) says b\vb{b} lies in the cone generated by columns of A\mat{A}, and (2) says there is a hyperplane y⊥\vb{y}^\perp through the origin with all columns on one side (y⊤ak≥0\vb{y}\T\vb{a}_k \ge 0) and b\vb{b} on the other. This is the separating hyperplane theorem applied to a cone. Both cannot hold: b⊤y=x⊤A⊤y≥0\vb{b}\T\vb{y} = \vb{x}\T\mat{A}\T\vb{y} \ge 0 if x⪰0\vb{x} \succeq \vb{0} and A⊤y⪰0\mat{A}\T\vb{y} \succeq \vb{0}. Showing one always holds is the second guided exercise, with one technical detail: the cone generated by finitely many vectors is closed.

InteractiveFarkas' lemma as a certificate
  • cone {Ax:x≥0}\{\mat{A}\vb{x} : \vb{x} \ge \vb{0}\}
  • certificate y\vb{y}
  • hyperplane y⊥\vb{y}^\perp
Does x≥0\vb{x} \ge \vb{0} exist with Ax=b\mat{A}\vb{x} = \vb{b}?no
y⊤a1\vb{y}\T\vb{a}_1 (must be ≥0\ge 0)2.53
y⊤a2\vb{y}\T\vb{a}_2 (must be ≥0\ge 0)0.00
y⊤a3\vb{y}\T\vb{a}_3 (must be ≥0\ge 0)3.64
y⊤b\vb{y}\T\vb{b} (must be <0< 0)−2.37
Alternative (II): the hyperplane y⊥\vb{y}^\perp leaves the three columns on one side (A⊤y≥0\mat{A}\T\vb{y} \ge \vb{0}) and b\vb{b} on the other. It comes from the projection of b\vb{b} onto the cone: y=p−b\vb{y} = \vb{p} - \vb{b}.
How do we prove b\vb{b} is not a conic combination of columns? Drag b\vb{b} and the three columns ak\vb{a}_k. If b\vb{b} is inside the blue cone, the panel gives coefficients x⪰0\vb{x} \succeq \vb{0} with Ax=b\mat{A}\vb{x} = \vb{b}. Outside, certificate y\vb{y} (magenta) appears: hyperplane y⊥\vb{y}^\perp leaves the cone and three columns on one side (y⊤ak≥0\vb{y}\T\vb{a}_k \ge 0), and b\vb{b} on the other (y⊤b<0\vb{y}\T\vb{b} < 0). It is the vector from b\vb{b} to its projection onto the cone. Spread the columns until no half-plane contains them all: the cone becomes the whole plane and no certificate is possible.

Infeasibility certificates and their relation to the dual

Applying Farkas to Ax⪯b\mat{A}\vb{x} \preceq \vb{b} (split x=x+−x−\vb{x} = \vb{x}^+ - \vb{x}^- and add slacks s⪰0\vb{s} \succeq \vb{0}, yielding system [A − ⁣A  I](x+,x−,s)=b[\mat{A}\ -\!\mat{A}\ \ \mat{I}](\vb{x}^+, \vb{x}^-, \vb{s}) = \vb{b} with variables ⪰0\succeq \vb{0}) gives the most useful form:

Ax⪯b  has no solution⟺∃ λ⪰0:  A⊤λ=0,  b⊤λ<0.\mat{A}\vb{x} \preceq \vb{b} \ \text{ has no solution} \quad\Longleftrightarrow\quad \exists\,\vb{\lambda} \succeq \vb{0}:\ \ \mat{A}\T\vb{\lambda} = \vb{0},\ \ \vb{b}\T\vb{\lambda} < 0.

An example with three inequalities: x1+x2≤1x_1 + x_2 \le 1, −x1≤−1-x_1 \le -1, −x2≤−1-x_2 \le -1. Multipliers λ=(1,1,1)\vb{\lambda} = (1, 1, 1) satisfy A⊤λ=0\mat{A}\T\vb{\lambda} = \vb{0} and b⊤λ=1−1−1=−1<0\vb{b}\T\vb{\lambda} = 1 - 1 - 1 = -1 < 0: adding the three inequalities gives 0≤−10 \le -1. This proof takes one line to verify.

The connection to the dual is direct. Feasibility problem “minimize 00 with Ax⪯b\mat{A}\vb{x} \preceq \vb{b}” has dual function g(λ)=−b⊤λg(\vb{\lambda}) = -\vb{b}\T\vb{\lambda} if A⊤λ=0\mat{A}\T\vb{\lambda} = \vb{0} and −∞-\infty otherwise. A λ\vb{\lambda} as in the lemma yields g(tλ)=−t b⊤λ→+∞g(t\vb{\lambda}) = -t\,\vb{b}\T\vb{\lambda} \to +\infty: the dual is unbounded, and weak duality makes the primal infeasible. That is the easy half. The hard half (the lemma) says that for linear systems such a ray always exists: infeasibility is certified by a dual ray without any qualification. Four possible states of an LP and its dual:

PrimalDualComment
finite optimumfinite optimump⋆=d⋆p^\star = d^\star
unbounded (p⋆=−∞p^\star = -\infty)infeasiblethe descent direction certifies unboundedness
infeasibleunboundeda dual ray certifies infeasibility
infeasibleinfeasiblepossible, though rare

A certificate like this appears whenever a solver returns “infeasible” with a Farkas ray. In machine learning, Gordan’s version (previous lesson) answers a classic question: data (x~i,yi)(\tilde{\vb{x}}_i, y_i) are strictly linearly separable iff no nonzero θ⪰0\vb{\theta} \succeq \vb{0} exists with ∑iθiyix~i=0\sum_i\theta_i y_i\tilde{\vb{x}}_i = \vb{0}, meaning the origin is not in the convex hull of yix~iy_i\tilde{\vb{x}}_i. If data are not separable, the certificate is that zero convex combination.

[ ]Infeasibility certificates with HiGHSBrowser
import numpy as np
from scipy.optimize import linprog

# Sistema infactible:  x1 + x2 <= 1,  x1 >= 1,  x2 >= 1   escrito como  G x <= h
G = np.array([[1.0, 1.0], [-1.0, 0.0], [0.0, -1.0]])
h = np.array([1.0, -1.0, -1.0])

print("¿factible?", linprog(np.zeros(2), A_ub=G, b_ub=h, bounds=(None, None), method="highs").status == 0)

# Certificado de Farkas: lambda >= 0, Gᵀlambda = 0, hᵀlambda < 0 (se normaliza hᵀlambda = -1)
cert = linprog(np.zeros(3), A_eq=np.vstack([G.T, h]), b_eq=[0, 0, -1], bounds=(0, None), method="highs")
lam = cert.x
print("lambda =", lam.round(4), " Gᵀlambda =", (G.T @ lam).round(12), " hᵀlambda =", round(h @ lam, 6))

# Misma idea para Ax = b, x >= 0: alternativa  Aᵀy >= 0,  bᵀy < 0
A = np.array([[1.0, 2.0, 1.0], [2.0, 1.0, 1.0]])
for b in (np.array([4.0, 5.0]), np.array([-1.0, 2.0])):
    fact = linprog(np.zeros(3), A_eq=A, b_eq=b, bounds=(0, None), method="highs").status == 0
    if fact:
        print("b =", b, ": existe x >= 0 con Ax = b")
    else:
        y = linprog(b, A_ub=-A.T, b_ub=np.zeros(3), bounds=(-1, 1), method="highs").x   # minimiza bᵀy con Aᵀy >= 0
        print("b =", b, ": no existe x >= 0; certificado y =", y.round(3), " Aᵀy =", (A.T @ y).round(3), " bᵀy =", round(b @ y, 3))

The certificates are exact: λ=(1,1,1)\vb{\lambda} = (1, 1, 1) is the sum of the three inequalities, and for b=(−1,2)\vb{b} = (-1, 2) vector y=(1,−0.5)\vb{y} = (1, -0.5) satisfies A⊤y⪰0\mat{A}\T\vb{y} \succeq \vb{0} with b⊤y=−2<0\vb{b}\T\vb{y} = -2 < 0.

Implementation from scratch

Two pieces: an LP dual derived by hand and solved separately, and the lasso duality gap inside a custom solver that stops with a certificate.

An LP’s dual and feasible pairs

Generate the LP with a strictly positive primal point and y0\vb{y}_0 giving strict dual slack, making both feasible. Solve separately with HiGHS (scipy.optimize.linprog): primal with A_eq, dual derived by hand in the examples section.

[ ]Primal and dual of an LP: strong duality, slack and feasible pairsBrowser
import numpy as np
from scipy.optimize import linprog

rng = np.random.default_rng(11)
m, n = 4, 9
A = rng.normal(size=(m, n))
x0 = rng.uniform(0.5, 2, n)            # un punto estrictamente positivo: el primal es factible
b = A @ x0
y0 = rng.normal(size=m)
c = A.T @ y0 + rng.uniform(0.5, 2, n)  # c - Aᵀy0 > 0: el dual es factible

# Primal:  min cᵀx  s.a.  Ax = b, x >= 0
primal = linprog(c, A_eq=A, b_eq=b, bounds=(0, None), method="highs")
# Dual (derivado a mano):  max bᵀy  s.a.  Aᵀy <= c, y libre
dual = linprog(-b, A_ub=A.T, b_ub=c, bounds=(None, None), method="highs")
x, y = primal.x, dual.x
s = c - A.T @ y                         # holguras duales, s >= 0

print(f"p* = {primal.fun:.6f}   d* = {-dual.fun:.6f}   (diferencia {abs(primal.fun + dual.fun):.1e})")
print(f"holgura complementaria: max |x_i s_i| = {np.abs(x * s).max():.1e}")

# Dualidad débil: pares (x, y) factibles cualesquiera (combinaciones convexas de puntos factibles)
gaps = []
for _ in range(2000):
    t, u = rng.uniform(size=2)
    xf = t * x + (1 - t) * x0           # factible: A xf = b, xf >= 0
    yf = u * y + (1 - u) * y0           # factible: Aᵀyf <= c
    gap = c @ xf - b @ yf
    assert abs(gap - (c - A.T @ yf) @ xf) < 1e-9   # identidad del gap: cᵀx - bᵀy = sᵀx
    gaps.append(gap)
print(f"2000 pares factibles al azar: gap mínimo {min(gaps):.4f} >= 0, y la identidad cᵀx - bᵀy = sᵀx se cumple")

Optimal values agree to machine precision and complementary slackness xksk=0x_k s_k = 0 holds: at optimum, each positive primal variable has zero dual slack and conversely. For arbitrary feasible pairs the gap is c⊤x−b⊤y=s⊤x≥0\vb{c}\T\vb{x} - \vb{b}\T\vb{y} = \vb{s}\T\vb{x} \ge 0, the LP gap form: the gap is the inner product of two nonnegative vectors.

A solver using gap as its stopping criterion

The three pieces are the lasso gap (residual scaled to dual feasibility, as in examples), a primal method (proximal descent), and comparison with true suboptimality, calculable afterward because here p⋆p^\star can be obtained with many iterations.

[ ]Lasso duality gap as a stopping ruleBrowser
import numpy as np

def lasso_primal(x, A, b, lam):
    return 0.5 * np.sum((A @ x - b) ** 2) + lam * np.abs(x).sum()

def lasso_duality_gap(x, A, b, lam):
    """Gap de dualidad del lasso en x: P(x) - D(nu), con nu = alpha (Ax - b) factible."""
    r = A @ x - b
    alpha = min(1.0, lam / max(np.abs(A.T @ r).max(), 1e-300))   # escala hasta ||Aᵀnu||_inf <= lam
    nu = alpha * r
    dual = -0.5 * nu @ nu - b @ nu
    return lasso_primal(x, A, b, lam) - dual

def soft(z, t):
    return np.sign(z) * np.maximum(np.abs(z) - t, 0.0)

rng = np.random.default_rng(7)
m, n = 40, 60
A = (0.7 * rng.normal(size=(m, n)) + 0.7 * rng.normal(size=(m, 1))) / np.sqrt(m)
x_true = np.zeros(n); x_true[rng.choice(n, 5, replace=False)] = rng.choice([-1, 1], 5) * rng.uniform(1, 2, 5)
b = A @ x_true + 0.05 * rng.normal(size=m)
lam = 0.06 * np.abs(A.T @ b).max()
L = np.linalg.norm(A, 2) ** 2

# p* con muchas iteraciones de FISTA (solo para comparar a posteriori)
y, xf, t = np.zeros(n), np.zeros(n), 1.0
for _ in range(4000):
    xn = soft(y - A.T @ (A @ y - b) / L, lam / L)
    tn = (1 + np.sqrt(1 + 4 * t * t)) / 2
    y, xf, t = xn + (t - 1) / tn * (xn - xf), xn, tn
p_star = lasso_primal(xf, A, b, lam)

def ista(tol, max_iter=5000):
    x = np.zeros(n)
    for k in range(max_iter + 1):
        gap = lasso_duality_gap(x, A, b, lam)
        if gap <= tol:
            return x, k, gap
        x = soft(x - A.T @ (A @ x - b) / L, lam / L)
    return x, max_iter, gap

for tol in (1e-1, 1e-2, 1e-3):
    x, k, gap = ista(tol)
    sub = lasso_primal(x, A, b, lam) - p_star
    print(f"tol = {tol:.0e}: parada en k = {k:4d}, gap = {gap:.2e}, subóptimo real = {sub:.2e}  (subóptimo <= gap: {sub <= gap})")

# El criterio ingenuo «el paso es pequeño» no certifica nada
x, k = np.zeros(n), 0
while True:
    xn = soft(x - A.T @ (A @ x - b) / L, lam / L)
    if np.linalg.norm(xn - x) < 1e-3: break
    x, k = xn, k + 1
print(f"criterio ||x_k+1 - x_k|| < 1e-3: parada en k = {k}, subóptimo real = {lasso_primal(x, A, b, lam) - p_star:.2e}, gap = {lasso_duality_gap(x, A, b, lam):.2e}")

For each tolerance the solver stops with the gap below it and true suboptimality, unknown to the solver, is always smaller. The step-size criterion also stops, but does not know how far remains: only the gap, independent of knowing p⋆p^\star, supplies the number. For a worse-conditioned problem a small step and large error can coexist.

The library version

In practice the solver returns the dual. With cvxpy, each constraint carries its multiplier in dual_value (nonnegative under this lesson’s ≤\le convention) and problem.value gives primal value. With HiGHS in scipy.optimize.linprog, multipliers appear in res.ineqlin.marginals and res.eqlin.marginals (with minimization sign: negated for a ≤\le constraint, as in the shadow-price cell). For lasso, sklearn.linear_model.Lasso exposes dual_gap_, the gap at the scale of its own objective 12n∥y−Xw∥2+α∥w∥1\tfrac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 + \alpha\norm{\vb{w}}_1, unlike this lesson’s (which does not divide by nn).

import cvxpy as cp

x = cp.Variable(n)
restr = [G @ x <= h]
prob = cp.Problem(cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), restr)
prob.solve()
lam = restr[0].dual_value          # multiplicadores de las desigualdades, >= 0
print(prob.value, lam)             # valor primal y precios sombra

Common mistakes

Exercises

ProofWeak duality, step by step
Prove: Let (P) be any problem, convex or not, with optimal value p⋆p^\star. For all λ⪰0\vb{\lambda} \succeq \vb{0} and ν\vb{\nu}, g(λ,ν)≤p⋆g(\vb{\lambda}, \vb{\nu}) \le p^\star.
0
If no feasible points exist, p⋆=+∞p^\star = +\infty and nothing remains to prove. Otherwise fix any feasible x~\tilde{\vb{x}} and compare gg with f0(x~)f_0(\tilde{\vb{x}}).

Step 1 of 4. For feasible x~\tilde{\vb{x}} and λ⪰0\vb{\lambda} \succeq \vb{0}, how does ∑iλifi(x~)+∑jνjhj(x~)\sum_i\lambda_i f_i(\tilde{\vb{x}}) + \sum_j\nu_j h_j(\tilde{\vb{x}}) compare with 00?

CodeThe lasso duality gap
Implement lasso_duality_gap(x, A, b, lam) to return duality gap P(x)−D(ν)P(\vb{x}) - D(\vb{\nu}) of lasso P(x)=12∥Ax−b∥22+λ∥x∥1P(\vb{x}) = \tfrac12\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \lambda\norm{\vb{x}}_1 at x. Construct the dual point by scaling the residual r=Ax−b\vb{r} = \mat{A}\vb{x} - \vb{b}: ν=αr\vb{\nu} = \alpha\vb{r} with α=min⁡{1, λ/∥A⊤r∥∞}\alpha = \min\{1,\ \lambda/\norm{\mat{A}\T\vb{r}}_\infty\} (if A⊤r=0\mat{A}\T\vb{r} = \vb{0}, α=1\alpha = 1), satisfying ∥A⊤ν∥∞≤λ\norm{\mat{A}\T\vb{\nu}}_\infty \le \lambda, with dual value D(ν)=−12∥ν∥2−b⊤νD(\vb{\nu}) = -\tfrac12\norm{\vb{\nu}}^2 - \vb{b}\T\vb{\nu}.
import numpy as np

def lasso_duality_gap(x, A, b, lam):
  """Gap de dualidad P(x) - D(nu) del lasso, con nu = alpha (Ax - b) dual factible."""
  # tu código: valor primal, residuo, escala alpha, valor dual y su diferencia
  return 0.0
Shift+Enter to run
NumericA conjugate by hand
Let f(x)=12x2+∣x∣f(x) = \tfrac12 x^2 + \abs{x}. Calculate its convex conjugate at y=3y = 3, that is, f∗(3)=sup⁡x (3x−f(x))f^*(3) = \sup_x\,(3x - f(x)).
NumericHow far the shadow price applies
In production LP max⁡5x+4y\max 5x + 4y subject to 6x+4y≤b16x + 4y \le b_1, x+2y≤6x + 2y \le 6, x,y≥0x, y \ge 0, optimal profit at b1=24b_1 = 24 is 2121, with shadow price λ1=0.75\lambda_1 = 0.75 for b1b_1. How much does optimal profit increase if b1b_1 rises from 2424 to 4040?
ProofFarkas' lemma from a separating hyperplane
Prove: Let A∈Rm×n\mat{A} \in \R^{m \times n} and b∈Rm\vb{b} \in \R^m. Exactly one is true: (I) there exists x⪰0\vb{x} \succeq \vb{0} with Ax=b\mat{A}\vb{x} = \vb{b}; (II) there exists y\vb{y} with A⊤y⪰0\mat{A}\T\vb{y} \succeq \vb{0} and b⊤y<0\vb{b}\T\vb{y} < 0.
0
Let C={Ax:x⪰0}C = \{\mat{A}\vb{x} : \vb{x} \succeq \vb{0}\} be the cone generated by columns of A\mat{A}. (I) means b∈C\vb{b} \in C. First prove both cannot hold, then that failure of (I) implies (II).

Step 1 of 4. Why can (I) and (II) not both hold?

QuizWhat the dual guarantees without convexity
For a nonconvex optimization problem (arbitrary f0,fi,hjf_0, f_i, h_j), which statements about its Lagrange dual are always true?

More than one answer may be correct.

QuizIs strong duality guaranteed?
For which problems is strong duality d⋆=p⋆d^\star = p^\star guaranteed by this lesson's results?

More than one answer may be correct.

QuizReading a certificate
A solver returns feasible x^\hat{\vb{x}} with f0(x^)=10.4f_0(\hat{\vb{x}}) = 10.4 and a dual-feasible point (λ^,ν^)(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) with g(λ^,ν^)=9.7g(\hat{\vb{\lambda}}, \hat{\vb{\nu}}) = 9.7. What can be asserted with certainty?

Summary

Key idea
The dual function g(λ,ν)=inf⁡xLg(\vb{\lambda}, \vb{\nu}) = \inf_{\vb{x}} L is always concave and, with λ⪰0\vb{\lambda} \succeq \vb{0}, always lower-bounds the optimum: d⋆≤p⋆d^\star \le p^\star. Gap f0(x^)−gf_0(\hat{\vb{x}}) - g of a feasible primal-dual pair certifies the quality of x^\hat{\vb{x}} without knowing p⋆p^\star; under convexity and Slater’s condition the gap can be driven to zero. Optimal multipliers are also derivatives of optimal value with respect to constraints: shadow prices.
  • Dual function. Infimum of affine functions in (λ,ν)(\vb{\lambda}, \vb{\nu}): always concave, with a domain to write down because dual constraints live there.
  • Weak duality. d⋆≤p⋆d^\star \le p^\star without assumptions. The dual exchanges inf⁡sup⁡\inf\sup for sup⁡inf⁡\sup\inf; in the (u,t)(u, t) plane it is a supporting line of slope −λ≤0-\lambda \le 0 whose tt-axis intercept lies below every feasible point.
  • Strong duality. With convexity and Slater (or feasible affine constraints), d⋆=p⋆d^\star = p^\star and the dual is attained. The proof separates A\mathcal{A} from B\mathcal{B}; Slater rules out a vertical hyperplane. Without it a gap can occur even when convex, and without convexity the gap measures loss from convexification.
  • KKT as zero gap. With strong duality primal and dual optima satisfy KKT; for convex problems KKT implies zero gap. For feasible x^\hat{\vb{x}} minimizing LL, the gap is ∑iλ^i∣fi(x^)∣\sum_i\hat{\lambda}_i\abs{f_i(\hat{\vb{x}})}: complementary-slackness violation.
  • Useful duals. LP (max⁡b⊤y\max \vb{b}\T\vb{y} with A⊤y⪯c\mat{A}\T\vb{y} \preceq \vb{c}), QP (another QP), minimum norm (gives the pseudoinverse), and lasso (projection onto {∥A⊤θ∥∞≤λ}\{\norm{\mat{A}\T\vb{\theta}}_\infty \le \lambda\}, with gap-based safe screening).
  • Conjugate and Fenchel. f∗(y)=sup⁡x(y⊤x−f(x))f^*(\vb{y}) = \sup_{\vb{x}}(\vb{y}\T\vb{x} - f(\vb{x})) is convex; Fenchel-Young and f∗∗f^{**} = closed convex envelope. Norm ↔\leftrightarrow dual ball, quadratic ↔\leftrightarrow inverse, log-sum-exp ↔\leftrightarrow entropy. Fenchel duality gives max⁡−f∗(−A⊤y)−h∗(y)\max -f^*(-\mat{A}\T\vb{y}) - h^*(\vb{y}) for min⁡f(x)+h(Ax)\min f(\vb{x}) + h(\mat{A}\vb{x}).
  • Sensitivity. p⋆(u)≥p⋆−λ⋆Tup^\star(\vb{u}) \ge p^\star - \vb{\lambda}^{\star\mathsf{T}}\vb{u} and λi⋆=−∂p⋆/∂ui\lambda_i^\star = -\partial p^\star/\partial u_i: a constraint’s price, local until the next basis change.
  • Alternatives and certificates. Farkas: Ax=b\mat{A}\vb{x} = \vb{b}, x⪰0\vb{x} \succeq \vb{0} has a solution or there is y\vb{y} with A⊤y⪰0\mat{A}\T\vb{y} \succeq \vb{0} and b⊤y<0\vb{b}\T\vb{y} < 0. Infeasibility is certified by a dual ray, and every LP solver response (optimal, infeasible or unbounded) can carry a certificate verifiable in linear time.
  • Where it returns. The SVM dual permits the kernel trick; interior-point and augmented Lagrangian and ADMM methods work with primal and dual together; and the dual of an MDP’s linear problem with occupancy measures connects to constrained reinforcement learning.