Penalties, augmented Lagrangian and ADMM
Explore methods that move constraints into the objective: quadratic penalties, ill-conditioning, multipliers, dual decomposition and ADMM.
After this lesson you can
- Explain the ill-conditioning of quadratic penalties as ρ approaches infinity.
- Derive the method of multipliers as dual ascent on the augmented Lagrangian.
- Implement dual ascent and dual decomposition for separable problems.
- Derive ADMM for lasso, distributed consensus and box-constrained regression, stopping on primal and dual residuals.
- Tune ρ and recognize slow convergence.
Before you start
Motivation: when the solver does not fit on one machine
The methods in earlier lessons assume the entire problem is in one place: a parameter vector, an objective and a gradient computed in one go. Many real problems do not look like that.
- Distributed data. A bank wants to fit a risk model using data from eight subsidiaries which, by law, cannot leave their countries. Each can compute on its own data, but nobody has the complete loss function.
- Huge structured problems. A lasso with ten million features, MRI reconstruction or power allocation in an electricity grid has one easy term (a norm or a box) and one difficult term (data fitting or physics), coupled together. Each piece can be solved in one line separately; together they cannot.
- General-purpose solvers. OSQP, a quadratic programming solver included with CVXPY and used in embedded model predictive controllers, solves problems with thousands of constraints in milliseconds without a single interior-point step.
The three situations have the same form: an objective decomposed into simple pieces, plus constraints coupling them. This lesson builds the family of methods that handles constraints by moving them into the objective. There are two ways, and the useful one combines both:
- Penalize constraint violation with a term . This is simple, but forces to infinity and makes the problem intractable through ill-conditioning.
- Price the constraint with a Lagrange multiplier and adjust it by ascent on the dual function. If the objective is separable, the problem breaks into independent pieces that can be solved in parallel, but the method is fragile.
- Both at once: the augmented Lagrangian. From it come the method of multipliers and ADMM, which splits a large problem into two blocks solved in turn and powers OSQP, SCS and much of distributed and federated learning.
Throughout the lesson, the model problem is
with convex unless stated otherwise. Inequality constraints are handled similarly (using or slack variables); barriers that keep them strictly inside are the topic of the interior-point lesson.
Penalties: charging for violations
The most direct idea is to forget the constraint and charge for violating it.
A one-dimensional example shows everything. Minimize subject to . Clearly the optimum is , and the KKT condition gives multiplier . The penalized problem is , a parabola whose minimum follows by differentiation:
With the error is ; with , . An error of requires . Notice the error’s numerator: it is . This is no coincidence.
What a penalty guarantees
Proof
Write . Since is feasible, , that is, , giving (1). By strong duality, , so by Cauchy–Schwarz. Combining the inequalities,
For (3), the optimality condition for is , saying precisely that minimizes the convex Lagrangian . Thus .
∎Point (2) is the heart of the problem. At the penalty optimum, the gradient of must be balanced by something, and all it has is . That “something” must resemble , so : the constraint holds exactly only if , when it was unnecessary. To achieve infeasibility , must be on the order of .
The price: ill-conditioning
Increasing has a cost. The penalized problem’s Hessian is
If , the term acts only on the row space of and leaves its null space intact. By the Courant–Fischer minimax principle applied to the null space of (of dimension at least ), at least eigenvalues of lie below , while the largest exceeds . Therefore
The condition number grows linearly with , as does the iteration count of any first-order method: gradient descent takes on the order of steps (see GD dynamics on a quadratic). Together, achieving infeasibility with a penalty and gradient descent costs on the order of iterations. Geometrically, contours become a narrow valley around the constraint, and the method bounces between its walls while creeping along the bottom.
In the figure, with infeasibility is and the condition number is : gradient descent with step takes over one hundred thousand steps to converge to . For a two-variable problem. Newton’s iteration count barely suffers, since Newton is invariant to linear rescaling, but its linear system at each step is just as ill-conditioned, limiting attainable floating-point accuracy (as the sphere lab shows).
Exact penalties
Is there a penalty that does not need ? Yes, if we give up smoothness.
Proof
For every , Hölder’s inequality gives , strictly less than if . Hence , with the first inequality strict at infeasible points. At feasible points, the penalty equals , with equality at solutions. Thus the penalty minimum is and is attained only at original solutions.
∎The cost is nondifferentiability: has a corner exactly on the feasible set, and nonsmooth methods such as the subgradient method are slow. Moreover, a bound on is needed in advance. Exact penalties are mainly used as merit functions to decide whether another method’s step is acceptable (for example in SQP), rather than as a method themselves.
Dual ascent and dual decomposition: setting prices
The other route comes from duality. The model problem’s Lagrangian is and its dual function, , is concave. Under strong duality, maximizing gives , and then is recovered by minimizing (if that minimizer is unique). Dual ascent maximizes by gradient ascent:
The second line is a gradient step because, when is differentiable, , the constraint residual at the Lagrangian minimizer . You will prove it in the exercises; it takes one line. The economic interpretation is immediate: are prices, the step is what each agent does at those prices, and the step raises prices for over-demanded resources and lowers them for excess resources.
When does it work? If is -strongly convex, in terms of the conjugate, and has a -Lipschitz gradient. Then is -Lipschitz and dual ascent with converges like any gradient descent. If is not strictly convex, everything breaks: with and constraint , the Lagrangian is unbounded below except at , and the step is undefined.
Dual decomposition
What makes dual ascent interesting is not its mediocre speed but its structure. Suppose the objective is separable, with , and constraints couple blocks: . Then the Lagrangian also separates,
and minimizing it over means independent problems.
The problem with dual decomposition is its assumptions: each must be strictly convex (or the step is undefined), the step must be small and well chosen, and convergence is slow. In the consensus lab you will see that with the safe step it remains 2.5% from optimum after 150 iterations, while ADMM reaches . The solution is to augment the Lagrangian.
The augmented Lagrangian and the method of multipliers
It is the usual Lagrangian plus a quadratic penalty, and also the ordinary Lagrangian of the equivalent problem subject to , which has the same solutions because the added term vanishes at feasible points. Two details distinguish it from the earlier methods.
The multiplier step is exactly . This is not arbitrary. The optimality condition for is
and the parenthesized expression is . Thus the pair satisfies the KKT stationarity condition exactly at every iteration. Only feasibility remains, and the loop corrects it.
We no longer need . In the example with , the step gives , so , and the multiplier step gives
The multiplier error is divided by at each iteration. With and , the first iteration agrees with the penalty (), but the second gives , the third , and at the fifth the error is . The pure penalty would need for the same result, and in higher dimensions that means a condition number roughly ten thousand times worse than with (recall grows as ). In the figure above, “augmented Lagrangian” mode does the same in two dimensions: the contraction factor is and the condition number is that of the penalty at the same moderate .
Why it works: proximal point on the dual
The deeper reason is that the method of multipliers is a known algorithm applied to the dual function.
Proof
The function is strongly concave, so has at most one maximizer, and is one if and only if is a supergradient of at . Set , so . The optimality condition for for is , saying minimizes the convex Lagrangian . Therefore and, for every ,
which is precisely the supergradient inequality.
∎The proximal point algorithm converges for any fixed , requiring neither differentiability nor strict convexity: if a maximizer of exists, (Güler, 1991), and convergence is linear when is strongly convex, as in the example. A larger accelerates convergence, but is not necessary for exactness. Proximal regularization also makes the step well defined where dual ascent failed: with and , the augmented Lagrangian is a parabola with a minimum for any .
ADMM: splitting the problem into two blocks
The method of multipliers solves the conditioning problem but destroys separability: mixes all the blocks, so the step can no longer be distributed. ADMM recovers the best of both with a simple idea: minimize the augmented Lagrangian by blocks in a single pass, rather than exactly.
Consider the problem in two-block form
with and convex, closed and proper (they may take , so constraints can be indicators). Its augmented Lagrangian is
The scaled form comes from completing the square: , and the last term depends on neither nor . You will reconstruct this step by step in an exercise. Notice : the scaled multiplier is the cumulative sum of residuals, like a PID controller’s integral term.
The most important case is , , : the constraint just says the two copies agree. Each step is then a proximal operator,
and ADMM works for any where each term has a cheap proximal, even when their sum does not. This is the same situation as proximal gradient, with two differences: ADMM requires neither function to be differentiable, and treats by its proximal rather than its gradient, allowing large steps when is ill-conditioned but its proximal is a linear system factored once.
Douglas–Rachford, the close relative
With constraint , ADMM is a classical algorithm in disguise. Define . Since and , we get , that is, and . Substituting into the iterations,
which is Douglas–Rachford (1956, devised for heat equations) applied to . For the general problem with and , Gabay (1983) proved that ADMM is Douglas–Rachford applied to the dual. This connection enables analysis of ADMM using monotone operator theory and is the thread of Ryu and Yin’s book in the sources: almost all splitting methods (proximal gradient, Douglas–Rachford, ADMM, Chambolle–Pock) are fixed-point iterations of averaged operators.
Canonical examples
Lasso
Lasso, , splits into and with . The two proximals are:
where is soft thresholding. The step is a linear system with the same matrix at every iteration, symmetric positive definite. Factor it once by Cholesky, , at cost , and each iteration becomes two triangular solves costing . If features greatly outnumber examples (), the Woodbury identity,
reduces the factorization to an matrix. This is ADMM’s structural advantage over ISTA and FISTA: all second-order information in enters the step and is paid for only once.
Consensus
To minimize when each lives on a different machine, give each node its own copy and require all copies to agree with a global variable:
The block contains all copies and the block is the global variable. ADMM gives
Each node solves its local problem with a quadratic pull toward current consensus, corrected by its own multiplier; data never leave the node, only parameter vectors travel. The mean of vanishes after the first iteration, so is simply the mean of . If a regularizer is added, the step becomes a proximal of that mean.
The figure shows two lessons independent of the example. First, information from one node may be nearly useless alone and decisive together, and ADMM combines it without moving data. Second, less comfortably, ADMM faithfully solves the global problem, so if one node has biased data, consensus inherits that bias, weighted by how informative that node is in each direction. Making consensus robust requires changing the problem (robust losses, medians, anomaly detection), not the algorithm.
Box-constrained least squares
For subject to , take as the box indicator. The step is the same linear system as lasso, and the step is a projection, which for a box clips coordinate by coordinate: . This is “Box” mode in the two-block figure. The pattern is general: any convex set with cheap projection (balls, simplices, the semidefinite cone via eigendecomposition) can be incorporated into ADMM without changing the rest.
Resource allocation with ADMM
The data center example also has an ADMM version, the exchange problem: subject to (what one gives up another receives). With a little algebra (Boyd and coauthors, section 7.3), ADMM becomes and , with the mean request. This is dual decomposition with two changes: the price is , and each agent adds a pull preventing a sudden reaction to the price. This pull removes the need for strict convexity and step-size fragility.
Convergence, residuals and tuning ρ
Proof
Proof sketch from appendix A of Boyd and coauthors. Let . Combine three inequalities (the saddle-point inequality ; the one from the optimality conditions of the and steps; and monotonicity of the subdifferential of between consecutive iterations) to obtain
is a Lyapunov function: it does not increase and, summing the inequality, . Thus and , and bounds on in terms of those two terms give (2). Boundedness of bounds , and a limit-point argument gives (3).
∎The theorem is generous in assumptions (no differentiability, strict convexity or large needed) and modest in conclusions: it does not guarantee that and converge, only the residual, value and multiplier (under additional assumptions, such as strictly convex , the primal iterates also converge). For speed, averaged errors decay as generally (He and Yuan, 2012), and convergence is linear if one function is strongly convex and smooth and the matrices have full rank (Deng and Yin, 2016).
Primal and dual residuals
The two-block problem has three optimality conditions: primal feasibility, , and two dual feasibility conditions, and . Which does ADMM satisfy each iteration?
- The step gives : the dual condition for always holds exactly.
- The step gives . Adding and subtracting ,
Thus two residuals remain to monitor: the primal residual and the dual residual , measuring the failure of ‘s dual condition. For lasso and consensus, with and , the dual is simply times the movement of . The standard stopping criterion (Boyd and coauthors, section 3.3) compares them with tolerances combining absolute and relative parts:
where is the number of constraints and the dimension of . Typical values: or and or , depending on accuracy required. In scaled form, .
The role of ρ and adaptive tuning
In ADMM, no longer determines whether the method converges, but determines how fast; its effect appears in the residuals. Large heavily penalizes disagreement: and quickly stick together (small primal residual), but each step moves them little and the dual residual, containing a factor , dominates. Small does the opposite: each block pursues its objective almost ignoring the other. In the two-block figure you saw a U, with a minimum near , the scale of ‘s curvature (its eigenvalues are and ). For a quadratic, the rule of thumb is to choose on the order of the geometric mean of the extreme eigenvalues of the curvature entering the step.
When that scale is unknown, adapt it during iteration with residual balancing (He, Yang and Wang, 2000):
with typical values and . Two easily forgotten details: changing requires rescaling the scaled multiplier ( if is multiplied by ), because is conserved; and if the step uses a cached factorization, it must be refactored. Solvers therefore change only a few times. OSQP also compares residuals normalized by their scales (the same ones in the tolerances), not absolute residuals, because poorly scaled data make absolute comparisons misleading, as the lab shows.
Another standard improvement is over-relaxation: replace by in the and steps, with (Boyd and coauthors, section 3.4.3). It costs the same per iteration and often appreciably reduces iteration count; OSQP defaults to .
ADMM as a solver engine: OSQP and SCS
OSQP solves quadratic programs in the form
(Here and are bounds, using OSQP’s notation, not the scaled multiplier.) The splitting is this lesson’s: a variable carrying constraints as the indicator of the box , and a copy of carrying the quadratic. The step clips coordinate by coordinate. The step solves a linear system with the quasi-definite matrix
which is factored once with a sparse and reused at every iteration (refactored only when adaptive tuning changes ). Add data prescaling (Ruiz equilibration) so makes sense for all constraints at once, over-relaxation with , infeasibility detection from differences between iterates, and final polishing that, once the active set is identified, solves an equality system for a high-accuracy solution. This is the full recipe for industrial ADMM, explaining why it runs on microcontrollers, where each iteration is a few triangular solves.
SCS (O’Donoghue and coauthors, 2016) does the same for conic programs: it writes primal and dual optimality conditions as a linear system plus a cone (the “homogeneous self-dual embedding”) and applies ADMM to that form. Each iteration solves with a fixed matrix and projects onto the cone (an eigendecomposition for the semidefinite cone). It thus solves enormous SOCPs and SDPs to moderate accuracy, and also detects infeasibility or unboundedness.
Implementation from scratch
Augmented Lagrangian on a sphere
Start with a nonconvex problem with a nonlinear equality constraint: minimize the indefinite quadratic on the sphere , with . This is the trust-region subproblem when the solution lies on the boundary, and has a reference solution: KKT gives with and semidefinite, a one-variable equation in . The inner solver is damped Newton (with Hessian eigenvalues replaced by their absolute values so the direction always descends).
import numpy as np
from scipy.optimize import brentq
rng = np.random.default_rng(1)
n = 10
Qr, _ = np.linalg.qr(rng.normal(size=(n, n)))
evals = np.linspace(-2, 3, n) # B indefinida
Bm = Qr @ np.diag(evals) @ Qr.T
g = rng.normal(size=n)
f = lambda x: 0.5 * x @ Bm @ x + g @ x
# referencia: (B + 2 nu I) x = -g con ||x|| = 1 y nu > -lambda_min / 2 (ecuación secular)
c = Qr.T @ g
nu_star = brentq(lambda nu: np.sum((c / (evals + 2 * nu)) ** 2) - 1, -evals[0] / 2 + 1e-9, 100)
x_star = -Qr @ (c / (evals + 2 * nu_star))
print(f"nu* = {nu_star:.10f} ||x*|| = {np.linalg.norm(x_star):.12f} f* = {f(x_star):.10f}")
def newton_inner(x, nu, rho, tol=1e-12, max_iter=100):
"""min_x f(x) + nu h(x) + rho/2 h(x)^2 con h(x) = ||x||^2 - 1, por Newton amortiguado."""
def F(x):
h = x @ x - 1
return f(x) + nu * h + 0.5 * rho * h * h
for its in range(1, max_iter + 1):
h = x @ x - 1
grad = Bm @ x + g + 2 * (nu + rho * h) * x
if np.linalg.norm(grad) <= tol * max(1.0, rho):
break
H = Bm + 2 * (nu + rho * h) * np.eye(n) + 4 * rho * np.outer(x, x)
w, V = np.linalg.eigh(H)
d = -V @ ((V.T @ grad) / np.maximum(np.abs(w), 1e-8)) # siempre de descenso
t = 1.0
if w[0] <= 0 or np.linalg.norm(grad) > 1e-4: # lejos: Armijo; cerca: Newton puro
while F(x + t * d) > F(x) + 1e-4 * t * grad @ d and t > 1e-10:
t *= 0.5
x = x + t * d
h = x @ x - 1
H = Bm + 2 * (nu + rho * h) * np.eye(n) + 4 * rho * np.outer(x, x)
return x, its, np.linalg.cond(H)
x0 = np.ones(n) / np.sqrt(n)
print("\nPENALIZACIÓN CRECIENTE (cada problema parte de la solución del anterior)")
x, total = x0.copy(), 0
for rho in [1e1, 1e2, 1e3, 1e4, 1e6, 1e8, 1e10]:
x, its, kappa = newton_inner(x, 0.0, rho)
total += its
print(f" rho = {rho:7.0e} Newton: {its:3d} (total {total:3d}) |h| = {abs(x @ x - 1):.1e} "
f"||x - x*|| = {np.linalg.norm(x - x_star):.1e} rho*h = {rho * (x @ x - 1):.8f} kappa = {kappa:.1e}")
print("\nMÉTODO DE MULTIPLICADORES con rho = 10 fijo")
x, nu, total = x0.copy(), 0.0, 0
for k in range(15):
x, its, kappa = newton_inner(x, nu, 10.0)
total += its
h = x @ x - 1
nu += 10.0 * h
print(f" k = {k:2d} Newton: {its:3d} (total {total:3d}) |h| = {abs(h):.1e} "
f"||x - x*|| = {np.linalg.norm(x - x_star):.1e} nu = {nu:.10f} kappa = {kappa:.1e}")
if abs(h) < 1e-12:
breakThe two columns to compare are accuracy and . The penalty needs to bring infeasibility to , with Hessian condition number , and even so the error in remains . Penalty bias at that is on the order of (the column falls by a factor of 10 for each factor of 10 in up to ), so the actual error is roughly forty times larger than expected. Conditioning is responsible, through the stopping criterion. The gradient contains , and comes from subtraction with cancellation whose absolute error is on the order of ; multiplied by , it leaves gradient noise of order . Hence the inner tolerance must grow with (in the cell, ), and with a minimum eigenvalue around 1, a gradient of that size no longer guarantees small error in flat directions: Newton stops after two steps, far from theoretical bias. (If forced to take thirty steps, it does reach the theoretical bias, , but the gradient can no longer certify it.) The same noise spoils the multiplier estimate: rho*h stops improving from , and at even worsens because the inner tolerance, , is already loose. The method of multipliers reaches with and at every iteration, and error is divided by about 23 on each pass (linear convergence, as in the one-dimensional example). Also notice the penalty’s rho*h column: while rounding does not interfere, it approaches as , as predicted by the theorem. Total Newton steps are similar for both methods because Newton is insensitive to conditioning in exact arithmetic; with a first-order inner solver requiring on the order of iterations, the penalty would be impractical.
ADMM for lasso with cached factorization
import numpy as np
from scipy.linalg import cho_factor, cho_solve
def soft(v, k):
return np.sign(v) * np.maximum(np.abs(v) - k, 0.0)
def admm_lasso(A, b, lam, rho=1.0, abstol=1e-6, reltol=1e-4, max_iter=5000, adapt=False):
"""min 1/2 ||Ax - b||^2 + lam ||z||_1 s.a. x - z = 0, en forma escalada."""
m, n = A.shape
Atb = A.T @ b
def factor(rho):
if m >= n: # A^T A + rho I, n x n
F = cho_factor(A.T @ A + rho * np.eye(n))
return lambda q: cho_solve(F, q)
F = cho_factor(np.eye(m) + (A @ A.T) / rho) # Woodbury: solo m x m
return lambda q: q / rho - A.T @ cho_solve(F, A @ q) / rho**2
solve = factor(rho)
x = z = u = np.zeros(n)
hist = []
for k in range(1, max_iter + 1):
x = solve(Atb + rho * (z - u)) # dos sustituciones triangulares
z_old = z
z = soft(x + u, lam / rho)
u = u + x - z
r = np.linalg.norm(x - z)
s = rho * np.linalg.norm(z - z_old)
eps_pri = np.sqrt(n) * abstol + reltol * max(np.linalg.norm(x), np.linalg.norm(z))
eps_dual = np.sqrt(n) * abstol + reltol * rho * np.linalg.norm(u)
hist.append((r, s, eps_pri, eps_dual, rho))
if r <= eps_pri and s <= eps_dual:
break
if adapt: # balance de residuos normalizados
rp, sd = r / eps_pri, s / eps_dual
if rp > 10 * sd or sd > 10 * rp:
tau = 2.0 if rp > 10 * sd else 0.5
rho, u = rho * tau, u / tau # nu = rho u se conserva
solve = factor(rho) # hay que refactorizar
return z, np.array(hist)
def lasso_obj(A, b, lam, x):
return 0.5 * np.sum((A @ x - b) ** 2) + lam * np.sum(np.abs(x))
def fista(A, b, lam, iters):
L = np.linalg.norm(A, 2) ** 2
x = y = np.zeros(A.shape[1]); t = 1.0
for _ in range(iters):
x_new = soft(y - A.T @ (A @ y - b) / L, lam / L)
t_new = (1 + np.sqrt(1 + 4 * t * t)) / 2
y = x_new + (t - 1) / t_new * (x_new - x)
x, t = x_new, t_new
return x
rng = np.random.default_rng(0)
m, n = 300, 100
A = rng.normal(size=(m, n)) / np.sqrt(m)
x_true = np.zeros(n); x_true[rng.choice(n, 8, replace=False)] = rng.normal(0, 3, 8)
b = A @ x_true + 0.05 * rng.normal(size=m)
lam = 0.1 * np.max(np.abs(A.T @ b))
z, hist = admm_lasso(A, b, lam, rho=1.0)
x_ref = fista(A, b, lam, 5000)
f_ref = lasso_obj(A, b, lam, x_ref)
print(f"ADMM, m = {m} > n = {n}: {len(hist)} iteraciones")
print(f" gap relativo frente a FISTA (5000 it.): {(lasso_obj(A, b, lam, z) - f_ref) / f_ref:.1e}")
print(" soporte ADMM: ", np.flatnonzero(z))
print(" soporte FISTA:", np.flatnonzero(np.abs(x_ref) > 1e-8))
r, s, ep, ed, _ = hist[-1]
print(f" al parar: r = {r:.1e} <= {ep:.1e}, s = {s:.1e} <= {ed:.1e}")
# n > m: el paso x usa Woodbury (sistema 80 x 80 en lugar de 400 x 400)
A2 = rng.normal(size=(80, 400)) / np.sqrt(80)
x2 = np.zeros(400); x2[:6] = [3, -2, 2.5, -3, 1.5, 2]
b2 = A2 @ x2 + 0.02 * rng.normal(size=80)
z2, hist2 = admm_lasso(A2, b2, 0.1 * np.max(np.abs(A2.T @ b2)), rho=1.0)
print(f"\nADMM, m = 80 < n = 400: {len(hist2)} iteraciones, coeficientes no nulos: {np.flatnonzero(z2)}")ADMM’s solution support matches FISTA run for 5000 iterations, and the objective value matches to one part in in 19 iterations. (The support not matching x_true exactly is a property of lasso, not the algorithm: at this , the smallest true coefficient is below the threshold.) With , the Woodbury identity avoids factoring a matrix, and ADMM recovers exactly the six coefficients that generated the data.
ρ, scale and accuracy
Now for what makes ADMM struggle in practice: the choice of , data scale and high accuracy.
import numpy as np
import matplotlib.pyplot as plt
print(f"{'rho':>8} {'iteraciones':>12} {'datos x100':>12}")
for rho in [0.01, 0.1, 1.0, 10.0, 100.0]:
it1 = len(admm_lasso(A, b, lam, rho=rho, max_iter=2000)[1])
it2 = len(admm_lasso(100 * A, 100 * b, 1e4 * lam, rho=rho, max_iter=2000)[1])
print(f"{rho:8.2f} {it1:12d} {it2:12d}")
print("\nrho adaptativo (balance de residuos normalizados):")
for rho in [0.01, 1.0, 100.0]:
it1 = len(admm_lasso(A, b, lam, rho=rho, adapt=True)[1])
it2 = len(admm_lasso(100 * A, 100 * b, 1e4 * lam, rho=rho, adapt=True)[1])
print(f" desde rho = {rho:6.2f}: {it1:4d} iteraciones datos x100: {it2:4d}")
# precisión moderada frente a alta en un problema mal condicionado (kappa(A) = 100)
rng = np.random.default_rng(1)
U, _ = np.linalg.qr(rng.normal(size=(300, 100))); V, _ = np.linalg.qr(rng.normal(size=(100, 100)))
Ac = U @ np.diag(np.logspace(0, -2, 100)) @ V.T
bc = Ac @ x_true + 0.01 * rng.normal(size=300)
lc = 0.05 * np.max(np.abs(Ac.T @ bc))
z_ref, _ = admm_lasso(Ac, bc, lc, rho=0.1, abstol=1e-13, reltol=1e-13, max_iter=5000)
fc = lasso_obj(Ac, bc, lc, z_ref)
def trayectoria(rho, K):
F = cho_factor(Ac.T @ Ac + rho * np.eye(100))
x = z = u = np.zeros(100); gaps = []
for _ in range(K):
x = cho_solve(F, Ac.T @ bc + rho * (z - u)); z = soft(x + u, lc / rho); u = u + x - z
gaps.append(max((lasso_obj(Ac, bc, lc, z) - fc) / fc, 1e-16))
return np.array(gaps)
for rho in [0.01, 0.1, 1.0]:
gaps = trayectoria(rho, 800)
hitos = [int(np.argmax(gaps < t)) + 1 if (gaps < t).any() else None for t in [1e-2, 1e-4, 1e-6, 1e-8]]
print(f"rho = {rho:5.2f}: iteraciones hasta gap 1e-2, 1e-4, 1e-6, 1e-8 = {hitos}")
plt.semilogy(gaps, label=f"ρ = {rho}")
plt.xlabel("iteración"); plt.ylabel("gap relativo del objetivo"); plt.legend(); plt.show()The table tells three stories. With well-scaled data there is a clear U around , and being wrong by two orders of magnitude costs 55 to 66 times more iterations. Multiplying data by 100 does not change the solution (the entire objective is multiplied by ), but shifts the good to : with any “reasonable” the method does not finish (2000 is the table’s iteration cap). Adaptive tuning fixes this only if it compares residuals normalized by their tolerances; with absolute comparison, it remains stuck for over a thousand iterations on rescaled data (check by changing rp, sd to r, s).
The final part shows the accuracy pattern. With well-chosen for this problem (), ADMM reaches in about 50 iterations. With it reaches in 26, but needs 79 for , 188 for and 326 for : each pair of digits costs more than the last. With , which was good in the previous problem, it takes 137 iterations just to reach , because here ‘s curvature is much lower (eigenvalues of fall to ) and good falls with it. This is typical of ADMM: a few dozen iterations give a useful solution, and the last digits are costly. In machine learning moderate accuracy usually suffices; otherwise ADMM finds the active set and a second-order method finishes, as in OSQP polishing.
Consensus for logistic regression in eight blocks
Now for distributed data: regularized logistic regression with 800 examples split across 8 nodes with different distributions. Each local step is a small logistic regression with a quadratic pull, solved using a few Newton iterations starting from the previous solution.
import numpy as np
from scipy.special import expit
rng = np.random.default_rng(0)
N, mi, d = 8, 100, 20
w_true = rng.normal(size=d)
bloques = []
for i in range(N):
Ai = rng.normal(size=(mi, d)) + 0.5 * i / N # cada nodo ve datos desplazados
yi = np.where(rng.random(mi) < expit(Ai @ w_true), 1.0, -1.0)
bloques.append((Ai, yi))
gamma = 1.0 # (gamma/2)||w||^2 repartido entre los nodos
def newton_local(Ai, yi, v, rho, x, lin=None, tol=1e-10):
"""argmin_x sum log(1 + exp(-y a^T x)) + gamma/(2N) ||x||^2 + rho/2 ||x - v||^2 (+ lin^T x)."""
for _ in range(50):
p = expit(-yi * (Ai @ x))
grad = -Ai.T @ (yi * p) + (gamma / N) * x + rho * (x - v)
if lin is not None:
grad = grad + lin
if np.linalg.norm(grad) < tol:
break
H = (Ai.T * (p * (1 - p))) @ Ai + (gamma / N + rho) * np.eye(len(x))
x = x - np.linalg.solve(H, grad)
return x
# referencia centralizada (lo que haría quien tuviera todos los datos)
A_all = np.vstack([B[0] for B in bloques]); y_all = np.concatenate([B[1] for B in bloques])
w_star = np.zeros(d)
for _ in range(30):
p = expit(-y_all * (A_all @ w_star))
H = (A_all.T * (p * (1 - p))) @ A_all + gamma * np.eye(d)
w_star -= np.linalg.solve(H, -A_all.T @ (y_all * p) + gamma * w_star)
def admm_consenso(rho, iters):
X = np.zeros((N, d)); U = np.zeros((N, d)); z = np.zeros(d); hist = []
for k in range(iters):
for i, (Ai, yi) in enumerate(bloques): # en un clúster, en paralelo
X[i] = newton_local(Ai, yi, z - U[i], rho, X[i])
z_old = z
z = (X + U).mean(axis=0) # all-reduce
U += X - z
hist.append((np.linalg.norm(X - z), rho * np.sqrt(N) * np.linalg.norm(z - z_old),
np.linalg.norm(z - w_star) / np.linalg.norm(w_star)))
return z, np.array(hist)
z, h_admm = admm_consenso(rho=5.0, iters=150)
for k in [10, 30, 60, 150]:
r, s, e = h_admm[k - 1]
print(f"k = {k:3d} r = {r:.1e} s = {s:.1e} error relativo frente al centralizado = {e:.1e}")
for rho in [0.5, 50.0]:
_, h = admm_consenso(rho, 60)
print(f"rho = {rho:4.1f}: error relativo tras 60 iteraciones = {h[-1, 2]:.1e}")With , consensus agrees with the centralized solution to ten digits after 150 communication rounds, and no node has revealed its data. With or , after 60 rounds error is three to four orders of magnitude worse than with : the same U as before.
For comparison, dual decomposition of the same problem. Without the quadratic term, each node minimizes , and multipliers ascend along the dual gradient projected onto (the condition for the infimum over to be finite). Each is -strongly convex with , so the safe step is .
import numpy as np
def ascenso_dual(alpha, iters):
Nu = np.zeros((N, d)); X = np.zeros((N, d)); hist = []
for k in range(iters):
for i, (Ai, yi) in enumerate(bloques):
X[i] = newton_local(Ai, yi, np.zeros(d), 0.0, X[i], lin=Nu[i])
xbar = X.mean(axis=0)
if not np.all(np.isfinite(X)) or np.abs(X).max() > 1e6:
hist.append(np.inf); break
Nu += alpha * (X - xbar) # conserva sum(nu_i) = 0
hist.append(np.linalg.norm(xbar - w_star) / np.linalg.norm(w_star))
return np.array(hist)
mu = gamma / N
for fac in [1, 4, 8, 12]:
h = ascenso_dual(fac * mu, 150)
if np.isfinite(h[-1]):
print(f"alpha = {fac:2d} mu: " + ", ".join(f"k={k}: {h[k - 1]:.1e}" for k in [10, 60, 150]))
else:
print(f"alpha = {fac:2d} mu: diverge en la iteración {len(h)}")
print(f"ADMM, rho = 5: k=10: {h_admm[9, 2]:.1e}, k=60: {h_admm[59, 2]:.1e}, k=150: {h_admm[149, 2]:.1e}")Dual ascent with the safe step remains 2.5% from the solution after 150 rounds. Larger steps improve it (with it reaches ), but diverges within a few iterations: the best step is at the edge of divergence, and that edge is not known in advance. ADMM, at the same cost per round and without tuning, is six orders of magnitude ahead of the best dual ascent and eight ahead of the safe one. The difference is : it prevents each node from overreacting to prices.
Using libraries
In practice, ADMM is rarely hand-coded for standard problems: formulate the problem in a modeling language and pass it to a solver using ADMM internally. Checking lasso with scikit-learn ties things together (beware its scale: it minimizes , so ).
import numpy as np
from sklearn.linear_model import Lasso
m_, n_ = A.shape
sk = Lasso(alpha=lam / m_, fit_intercept=False, tol=1e-12, max_iter=100000).fit(A, b)
z_admm, _ = admm_lasso(A, b, lam, rho=1.0, abstol=1e-10, reltol=1e-10)
print("max |ADMM - scikit-learn| =", np.max(np.abs(z_admm - sk.coef_)))
print("objetivos:", lasso_obj(A, b, lam, z_admm), lasso_obj(A, b, lam, sk.coef_))Outside the browser, the same lasso is solved with CVXPY, which translates the problem into OSQP standard form (quadratic program) or SCS form (conic program). The relevant parameters are exactly those of this lesson:
import cvxpy as cp
import osqp, scipy.sparse as sp
x = cp.Variable(n)
prob = cp.Problem(cp.Minimize(0.5 * cp.sum_squares(A @ x - b) + lam * cp.norm1(x)))
prob.solve(solver=cp.OSQP, eps_abs=1e-6, eps_rel=1e-6, polish=True) # ADMM + pulido final
prob.solve(solver=cp.SCS, eps=1e-6) # ADMM sobre el embebido homogéneo
# OSQP directamente: min 1/2 x'Px + q'x s.a. l <= Ax <= u
# (P, q, Acons, l, u son los datos de tu programa cuadrático)
solver = osqp.OSQP()
solver.setup(P=sp.csc_matrix(P), q=q, A=sp.csc_matrix(Acons), l=l, u=u,
rho=0.1, adaptive_rho=True, alpha=1.6, eps_abs=1e-5, eps_rel=1e-5,
scaling=10, warm_start=True)
res = solver.solve()
print(res.info.iter, res.info.status, res.info.rho_estimate)
adaptive_rho is normalized residual balancing, alpha over-relaxation, scaling the Ruiz equilibration passes and polish the final high-accuracy phase. For problems solved repeatedly with similar data (model predictive control, portfolio backtesting), warm_start reuses the previous solution and multiplier, and this is where ADMM shines: a few iterations per problem.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What bound do you obtain for at another point ?
Step 1 of 4. How do you rewrite ?
admm_lasso(A, b, lam, rho, abstol=1e-6, reltol=1e-4, max_iter=5000) in scaled form for subject to . Factor once (Cholesky) and reuse it. At each iteration compute , , and , save the row (r, s, eps_pri, eps_dual) in the history and stop as soon as and . Return (z, hist) with hist as a NumPy array of shape (iteraciones, 4).import numpy as np
from scipy.linalg import cho_factor, cho_solve
def admm_lasso(A, b, lam, rho, abstol=1e-6, reltol=1e-4, max_iter=5000):
m, n = A.shape
x = np.zeros(n)
z = np.zeros(n)
u = np.zeros(n)
hist = []
# tu código: factoriza una vez, itera x, z, u, calcula residuos y tolerancias, para
return z, np.array(hist)Summary
- Quadratic penalty leaves infeasibility on the order of and a Hessian with . The penalty is exact for but nonsmooth.
- Dual ascent is gradient ascent on , whose gradient is the constraint residual. A separable objective decomposes into independent problems (dual decomposition), but requires strict convexity and small steps.
- The method of multipliers, and , is proximal point on the dual: it converges for any and satisfies KKT stationarity each iteration.
- ADMM alternates an step, a step and a multiplier step. In scaled form these are two proximals and a residual sum; with it is Douglas–Rachford. It converges with convex , and any , and stops when primal and dual residuals fall below their tolerances.
- decides speed: iteration count forms a U, flattened by normalized residual balancing and well-scaled data. ADMM is fast to moderate accuracy and slow afterward; it cannot naively be extended to three blocks.
- Lasso, consensus, box constraints and resource allocation follow the same pattern, and OSQP and SCS are ADMM with cached factorization, scaling, over-relaxation, adaptive and polishing.