Inverse and implicit function theorems and implicit differentiation
When an equation F(x, θ) = 0 locally defines x as a differentiable function of θ, and how to differentiate that function without solving it explicitly. The inverse function theorem is proved using Banach's fixed point theorem, the implicit function theorem is derived from it, and both are applied at today's practical frontier: differentiation through solutions of equations and optimization problems (equilibrium layers, hypergradients, implicit meta-learning).
After this lesson you can
- Prove the inverse function theorem using Banach's fixed point theorem and derive the implicit function theorem.
- Compute derivatives of implicitly defined functions and solutions of nonlinear systems.
- Derive argmin sensitivity, dx*/dθ = -[∇²ₓₓg]⁻¹∇²ₓθg, and apply it without matrix inversion using an adjoint linear system.
- Describe regular level sets as submanifolds and compute their tangent and normal spaces.
- Implement hypergradients using implicit differentiation and an equilibrium layer with implicit backward pass.
Before you start
- 03Banach fixed-point theoremComplete metric spaceFréchet derivativeJacobian matrixC1 differentiability criterionMean value inequalityMultivariable chain ruleVector-Jacobian productHessian matrixLevel setsGradient
- 02Matrix inverseDeterminantNull spaceColumn spaceSystem of linear equationsGaussian elimination
- 00Custom autograd functions and gradcheckautograd dynamic graph
Motivation: layers as equations
A neural network layer is usually a formula: . Given , it is evaluated; for training, autograd saves intermediates and applies the chain rule. But increasingly, parts of modern systems are not formulas but solutions of something:
- Equilibrium layers. A deep equilibrium model (DEQ) defines its output as a layer’s fixed point , as if stacking infinitely many copies with the same weights. Nobody writes as a formula: it is computed iteratively.
- Optimization layers. OptNet returns the solution of a quadratic problem whose coefficients depend on the input. A projector onto a set, an optimal-transport problem or a physical system at equilibrium work the same way.
- Hyperparameters. Ridge regression weights are . To tune by gradient, you need , the derivative of an argmin.
- Meta-learning. In implicit MAML, the model adapted to a task is the minimum of a regularized loss, and the meta-gradient passes through that minimum.
- Robotics and inverse problems. Inverse kinematics solves for joints taking the end effector to position ; tomography solves a system of equations yielding physical parameters.
In every case an equation determines unknown as a function of parameters , and there are two questions. When does the equation actually define a differentiable function ? And how do we compute its derivative without knowing a formula or backpropagating through the hundred iterations of the method solving it? The answers are the implicit function theorem and its practical consequence, implicit differentiation. Both rest on the inverse function theorem, which we will prove using the Banach fixed point theorem: the proof is literally an algorithm.
Intuition: when a curve is a graph
Start with the smallest case: one equation in two unknowns, . Its solution set is a plane curve, a level set of . The question “does this equation define as a function of ?” is geometric: near a point, is the curve a function’s graph?
Globally, almost never. Circle is not a function’s graph because each has two heights. But locally, almost always: near the circle is the graph of . Only two points fail, , where the tangent is vertical. There, on one side of the point the curve has two heights and on the other none.
The key in the figure is what controls the change. The orange branch dies exactly where , and the slope readout explodes there. The reason fits on one line: if is differentiable and for all , differentiation by the chain rule gives
Where , the formula gives slope without solving for anything: we need not even know how to write . Where but , the roles switch and the curve is locally with . And where , as at the lemniscate crossing, neither formula makes sense and in fact two branches pass through the origin. In every regular case the tangent is perpendicular to , as you already knew from level sets.
The general version replaces “” with “matrix is invertible”. To get there, first understand when a map can be inverted.
The inverse function theorem
In one variable the answer seems easy: if and is continuous, has constant sign near , is strictly monotone there and therefore injective, with differentiable inverse of derivative . Continuity of is not a detail. Function , with , is differentiable everywhere and , but takes negative values arbitrarily close to 0. So is not injective in any neighborhood of the origin, however small.
In several variables monotonicity does not exist and another idea is needed. The idea is the lesson’s central one: the differential is the best linear approximation of near . If that linear map is invertible, nonlinearity is a small perturbation of something invertible, and a small perturbation of an isomorphism remains invertible. Banach’s fixed point theorem turns this into a theorem.
This is the inverse function theorem. A bijective map with inverse is called a diffeomorphism; the theorem says suffices for to be a local diffeomorphism around . The formula for is what you would guess: if , the chain rule gives . What is not automatic is that exists and is differentiable, which is what the proof shows.
Proof using a contraction
Proof
Write and , and use the matrix operator norm.
Step 1: a working radius. Since is continuous, there exists such that closed ball lies in and
Step 2: solving means finding a fixed point. For each define
Its fixed points are exactly the solutions of , because is injective. Its differential is , of norm on the ball. Since the ball is convex, the mean value inequality gives
Step 3: quantitative injectivity. Write . With the previous bound,
In particular, is injective on .
Step 4: surjectivity onto a ball. Let and . If and ,
Thus maps the closed ball, a complete metric space because it is closed in , into itself and is a contraction with constant . By Banach it has a unique fixed point, also in open ball . Define , open by continuity of and with . Then is bijective, and its inverse maps each to the fixed point of .
Step 5: is Lipschitz. Applying to , . In particular, is continuous.
Step 6: is differentiable. For , , and the parenthesis is invertible because (Neumann series). Fix , write and, for small , , tending to with by step 5. By differentiability of at ,
so . Since , relative error satisfies
so is differentiable at with .
Step 7: regularity. , composition of (continuous), (continuous), and matrix inversion, which is continuous, indeed , on the open set of invertible matrices because its entries are ratios of polynomials (Cramer’s rule). Hence . If , induction gives : if with , then is , that is, .
∎Two observations make the proof a tool. First, the contraction is an algorithm. Iterating is Newton’s method with Jacobian frozen at (the chord method). It converges linearly with asymptotic rate , bounded by norm , whereas Newton, updating the Jacobian each step, converges quadratically (see Newton for systems). Second, radii and are explicit. For we have , of norm , and . Step 1 asks : the proof guarantees an inverse on the ball of radius onto the ball of radius around . The closer to the origin, where is singular, the smaller both neighborhoods.
Local, not global
That is the complex map written in real coordinates, the best laboratory for seeing what “local” means. Its Jacobian has determinant , vanishing only at the origin. Thus is a local diffeomorphism around every point except the origin. Yet it is not injective on any open set containing two opposite points, because .
The figure shows both sides of the theorem. Near a point with , behaves like its invertible differential and the patch transforms bijectively. The size of the neighborhood depends on how long nonlinearity takes to dominate the linear part: the remainder of is , of size , versus the linear part of size . Once is comparable to , linearization no longer dominates. This does not mean ceases to be injective: only if , and a convex set containing and contains their midpoint, the origin. Thus is injective on any convex patch not containing the origin in its interior, however large: the answer to the figure’s question is no. Radius from the proof is a guarantee, not the actual neighborhood size. At the origin, and no neighborhood has an inverse, large or small.
Global failure can occur even without singular points. The map , which is , has everywhere in the plane and is not injective because it is periodic in . The global theorem that does exist (Hadamard) requires another hypothesis: a is a diffeomorphism from to if and only if everywhere and when . The complex exponential fails the second condition: along the imaginary axis, .
The implicit function theorem
Now separate variables into unknowns and parameters , with as many equations as unknowns: . The Jacobian of splits into two blocks,
This is the implicit function theorem. It follows from the inverse function theorem applied to augmented map , which leaves parameters alone and has block-triangular Jacobian: the complete proof is the first guided exercise. Once is known to be differentiable, the derivative formula is the chain rule applied to identity :
Three readings of the statement, each with a lesson:
- Count dimensions. equations fix unknowns and leave parameters free: the solution set near is a “surface” of dimension , the graph of . Invertibility of says the equations are independent in the unknown directions.
- Linearize. If were linear, , the solution would be , exactly the derivative formula. The theorem says that near a solution the nonlinear case behaves like its linearization.
- Local. Like the inverse function theorem, the theorem says nothing about how far extends. Branch may end at a point where becomes singular, or merge with another branch.
Plane curves: the lemniscate and folium
With and instead of , the theorem says: if and , near the point the curve is the graph of a differentiable with . Return to the curves in the opening figure with this lens.
Implicit differentiation
The theorem’s formula is the part used daily. Let be the solution of , computed by any method (Newton, fixed point, a commercial solver), and abbreviate and , evaluated at the solution. Implicit differentiation obtains derivatives of without solving explicitly:
Nobody forms this matrix , just as nobody forms a network’s Jacobian to train it. What is needed is one of its two products, both reducible to solving a linear system with :
- Tangent mode (the JVP). For parameter direction , solves
One system per direction: useful when is small.
- Adjoint mode (the VJP). For scalar loss , . Grouping from the right,
One linear system, regardless of , followed by a VJP with .
Vector is called the adjoint variable and is the exact analog of the gradient backpropagated by autograd. If also depends directly on , add . This cost is what matters in machine learning: with millions of parameters and a scalar loss, adjoint mode costs one system and two VJPs, no more and no less.
| Cost | Memory | |
|---|---|---|
| Finite differences | complete nonlinear problem solves | one solve |
| Unroll solver with autograd | a backward pass through all iterations | proportional to the number of iterations |
| Implicit, tangent mode | one linear system per direction | one system |
| Implicit, adjoint mode | one linear system with and one VJP | one system |
Two practical details. The adjoint system does not need in memory: an iterative method such as conjugate gradient (if is symmetric positive definite) or GMRES only needs products , provided by autograd as VJPs. And when is a fixed-point equation, with , the adjoint system is solved using the same iteration , converging at the forward rate .
The formula uses only the solution, not the path to it. Whether comes from Newton, bisection or a table, the derivative is the same. This algorithm independence makes implicit differentiation modular, and is also its weakness, because it assumes you have the exact solution.
Argmin sensitivity
The most important case in learning is when solves not an arbitrary equation but an optimization problem: . The idea is to view the first-order condition as an equation. At an interior minimum, : this is , and its Jacobian with respect to is the Hessian .
This argmin sensitivity formula underlies bilevel optimization and optimization layers. Its proof—apply the implicit function theorem to and verify that the resulting branch remains a branch of minima—is the second guided exercise. Two hypotheses do all the work: the positive-definite Hessian provides both the invertibility required by the theorem and that the branch consists of minima (by continuity, the Hessian remains positive definite nearby). If the Hessian is singular or there are multiple minimizers, the formula does not make sense; a final exercise gives an explicit example.
Hypergradients: ridge without magic formulas
Ridge regression with training data minimizes
and the choice of is judged by validation loss on other data. This is bilevel optimization: minimize subject to minimizing . The outer function’s gradient, , is called a hypergradient.
With and , the first-order condition is the normal equations . Hessian is positive definite for , and the cross-derivative is . The argmin formula gives
and the hypergradient in adjoint mode,
Note the intermediate form: the hypergradient is the inner product of the validation gradient and the path velocity . It vanishes when the path is tangent to a validation level curve.
The path does not pass through the validation minimum (gray circle): a single parameter cannot reach every point in the plane, and the best offers is the path point touching the lowest level curve. With one scalar hyperparameter, a grid search would suffice. Implicit differentiation becomes indispensable with many: one regularization coefficient per weight, per-training-example weights, parameters of a network generating data augmentations. Lorraine, Vicol and Duvenaud (2020) tune millions of hyperparameters this way, approximating the inverse-Hessian product with a truncated Neumann series; the gradient-free alternative is Bayesian optimization.
Regular level sets
The implicit function theorem has a geometric interpretation beyond solving for variables. A sphere , the rotation group, the set of fixed-rank matrices or the manifold of permitted positions of a constrained robot are level sets , and what enables calculus on them is that near each point they are graphs of smooth functions.
Proof
Since has rank , it has linearly independent columns. Reorder coordinates to make them first and write with and : block is invertible. The implicit function theorem applied to , with as unknown and as parameter, gives a neighborhood where is the graph of a function . Thus is a submanifold of dimension .
If is a curve in with , then for all and, differentiating at , : . Conversely, for each , curve lies in and has velocity . These velocities form a subspace of dimension (the second component already spans all ) contained in , and by the rank-nullity theorem . Equality holds throughout. The final assertion is that the orthogonal complement of a matrix’s null space is the column space of its transpose, whose columns are gradients .
∎This result, regular level sets as submanifolds, is the gateway to calculus on manifolds. Three examples clarify:
- The sphere. has on the unit sphere: is a submanifold of dimension , with and normal generated by .
- The orthogonal group. maps to the space of symmetric matrices, dimension , and . It is surjective at each orthogonal : given symmetric , satisfies . Thus has dimension , and its tangent at consists of skew-symmetric matrices, . These are infinitesimal rotation generators used in robotics.
- A counterexample. Cone is not a submanifold at its vertex, where the gradient vanishes. Again the condition is only sufficient: describes the circle, which is a submanifold, although the gradient of that vanishes everywhere on it.
Spheres, rotation groups and robot configuration manifolds, all regular level sets, are the spaces on which geometric learning works; they generalize there to abstract manifolds and their tangent spaces.
Frontier: implicit layers
All of the above has become a way to design networks in which the forward pass solves a problem and the backward pass applies the implicit function theorem.
Deep equilibrium models. Bai, Kolter and Koltun (2019) observed that a network with the same weights in every layer, , often converges to a fixed point, and proposed defining output directly as , computed using a root-finding method (Broyden in the original paper). With , adjoint mode gives
Backward memory does not depend on forward iteration count: it is that of a single layer. The paper reports memory reductions of up to 88% with the same quality as similarly sized explicit language models.
The figure isolates two distinct conditions needed by a DEQ. For the implicit gradient to exist, it suffices that be invertible, i.e. 1 is not an eigenvalue of . For the iterative forward pass to work, more is needed: at the fixed point for local convergence, and something like for global contraction, because is 1-Lipschitz. Practical DEQs therefore control weight norms (with spectral normalization or Jacobian regularization) and use more robust root-finding methods than simple iteration, such as Anderson acceleration.
Optimization layers. OptNet (Amos and Kolter, 2017) uses as a layer the solution of a quadratic problem with linear constraints, subject to and , with coefficients depending on the preceding layer. The backward pass implicitly differentiates the KKT system at the solution, which is , using a batched GPU interior-point solver. In one experiment the network learns rules of sudoku solely from examples.
Implicit meta-learning. iMAML (Rajeswaran, Finn, Kakade and Levine, 2019) adapts meta-parameters to each task using regularized problem . The argmin formula gives , and the meta-gradient is computed using conjugate gradients and Hessian-vector products. Memory does not depend on the number of inner-loop steps, precisely what limited MAML.
Modular implicit differentiation. Blondel et al. (2022) show that specifying the optimality condition (zero gradient, a proximal-step fixed point, KKT) suffices for a library to differentiate any solver with adjoint mode and autograd on ; their JAX implementation was JAXopt.
Implementation from scratch
First, the inverse function theorem proof as an algorithm, for around : contraction versus Newton, and verification that the inverse derivative is the inverse of the derivative.
import numpy as np
def f(p):
x, y = p
return np.array([x * x - y * y, 2 * x * y])
def Df(p):
x, y = p
return np.array([[2 * x, -2 * y], [2 * y, 2 * x]])
a = np.array([1.0, 0.5])
A = Df(a)
nA_inv = np.linalg.norm(np.linalg.inv(A), 2) # solo para imprimir la constante
r = 1 / (4 * nA_inv) # paso 1: ‖Df(x) − A‖ = 2‖x − a‖ ≤ 1/(2‖A⁻¹‖)
print(f"‖A⁻¹‖ = {nA_inv:.4f} radio r = {r:.4f} (= |a|/2) radio de V = {r / (2 * nA_inv):.4f} (= |a|²/2)")
def inversa_local(y, x0, A, tol=1e-14, max_iter=100):
"""Punto fijo de φ(x) = x + A⁻¹(y − f(x)): la contracción de la demostración."""
x, hist = x0.copy(), []
for _ in range(max_iter):
x = x + np.linalg.solve(A, y - f(x))
hist.append(np.linalg.norm(f(x) - y))
if hist[-1] < tol:
break
return x, hist
def newton(y, x0, tol=1e-14, max_iter=50):
x, hist = x0.copy(), []
for _ in range(max_iter):
x = x + np.linalg.solve(Df(x), y - f(x))
hist.append(np.linalg.norm(f(x) - y))
if hist[-1] < tol:
break
return x, hist
y = f(a) + np.array([0.3, -0.2]) # un punto de V: ‖y − f(a)‖ = 0.36 < 0.625
x_c, h_c = inversa_local(y, a, A)
x_n, h_n = newton(y, a)
print("preimagen (contracción):", x_c, " iteraciones:", len(h_c))
print("preimagen (Newton): ", x_n, " iteraciones:", len(h_n))
print("cocientes de errores sucesivos (contracción):", np.round(np.array(h_c[1:6]) / np.array(h_c[:5]), 3))
print("residuos de Newton:", ["%.1e" % e for e in h_n])
print("‖I − A⁻¹Df(x*)‖ =", round(np.linalg.norm(np.eye(2) - np.linalg.solve(A, Df(x_c)), 2), 4), "(tasa asintótica)")
# la derivada de la inversa es la inversa de la derivada
g = lambda yy: inversa_local(yy, a, A)[0]
h = 1e-6
Dg_fd = np.column_stack([(g(y + h * e) - g(y - h * e)) / (2 * h) for e in np.eye(2)])
print("Dg(y) por diferencias:\n", np.round(Dg_fd, 6))
print("Df(g(y))⁻¹:\n", np.round(np.linalg.inv(Df(x_c)), 6))Contraction needs 16 iterations and Newton 4, with Newton residuals squaring at each step. The ratio of successive contraction errors stabilizes at , exactly (here norm equals spectral radius because the matrix is a multiple of a rotation): the rate the proof bounds by throughout the ball is much better near . The inverse Jacobian, measured with finite differences on the algorithm itself, matches to all six printed digits. Note that the matrix is a multiple of a rotation, as befits the inverse of , a complex square root.
Now Kepler’s equation: implicit derivative versus finite differences and algorithm independence.
import numpy as np
def kepler_newton(M, e, tol=1e-15):
"""Resuelve E − e·sin E = M por Newton (0 ≤ e < 1)."""
E = M if e < 0.8 else np.pi
for _ in range(50):
dE = (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
E -= dE
if abs(dE) < tol:
break
return E
def kepler_biseccion(M, e):
"""El mismo problema con otro algoritmo: bisección en [M − e, M + e]."""
lo, hi = M - e, M + e
for _ in range(80):
mid = 0.5 * (lo + hi)
if mid - e * np.sin(mid) - M > 0:
hi = mid
else:
lo = mid
return 0.5 * (lo + hi)
M, e = 1.0, 0.6
E = kepler_newton(M, e)
F_E = 1 - e * np.cos(E) # ∂F/∂E
dE_dM = 1 / F_E # −(∂F/∂E)⁻¹ ∂F/∂M, con ∂F/∂M = −1
dE_de = np.sin(E) / F_E # con ∂F/∂e = −sin E
h = 1e-6
fd_M = (kepler_newton(M + h, e) - kepler_newton(M - h, e)) / (2 * h)
fd_e = (kepler_newton(M, e + h) - kepler_newton(M, e - h)) / (2 * h)
print(f"E = {E:.12f} (bisección: {kepler_biseccion(M, e):.12f})")
print(f"dE/dM: implícita {dE_dM:.10f} diferencias {fd_M:.10f}")
print(f"dE/de: implícita {dE_de:.10f} diferencias {fd_e:.10f}")
# la fórmula solo usa la solución: da lo mismo con qué algoritmo se haya obtenido
Eb = kepler_biseccion(M, e)
print(f"dE/de con la solución de bisección: {np.sin(Eb) / (1 - e * np.cos(Eb)):.10f}")The ridge hypergradient, now with 30 correlated features and 40 examples. There is still only one hyperparameter, so a fine grid will provide an optimum reference. Compare with finite differences and the alternative without this theorem: unroll gradient-descent steps on training loss and differentiate through them (here in forward mode, propagating together with ).
import numpy as np
rng = np.random.default_rng(0)
n, n_val, d = 40, 400, 30
w_true = rng.normal(size=d) * (rng.random(d) < 0.3) # pocos coeficientes no nulos
Sigma = 0.7 ** np.abs(np.subtract.outer(np.arange(d), np.arange(d))) # características correladas
Lc = np.linalg.cholesky(Sigma)
X = rng.normal(size=(n, d)) @ Lc.T
Xv = rng.normal(size=(n_val, d)) @ Lc.T
y = X @ w_true + 1.0 * rng.normal(size=n)
yv = Xv @ w_true + 1.0 * rng.normal(size=n_val)
H, b = X.T @ X, X.T @ y
def w_star(lam):
return np.linalg.solve(H + lam * np.eye(d), b)
def val_loss(w):
r = Xv @ w - yv
return 0.5 * r @ r / n_val
def hipergradiente(lam):
"""dL_val/dλ con un único sistema adjunto: (H + λI) v = ∇L_val(w*), dL/dλ = −vᵀw*."""
w = w_star(lam)
g = Xv.T @ (Xv @ w - yv) / n_val
v = np.linalg.solve(H + lam * np.eye(d), g)
return -v @ w, w
lam = 3.0
hg, w = hipergradiente(lam)
eps = 1e-5 * lam
fd = (val_loss(w_star(lam + eps)) - val_loss(w_star(lam - eps))) / (2 * eps)
print(f"λ = {lam}: hipergradiente implícito {hg:.10f} diferencias finitas {fd:.10f}")
# desenrollar T pasos de descenso por gradiente sobre la pérdida de entrenamiento (modo directo)
def hipergradiente_desenrollado(lam, T):
A = H + lam * np.eye(d)
alpha = 1.0 / np.linalg.eigvalsh(A)[-1]
w, dw = np.zeros(d), np.zeros(d)
for _ in range(T):
w, dw = w - alpha * (A @ w - b), dw - alpha * (A @ dw + w) # derivada de la recurrencia
g = Xv.T @ (Xv @ w - yv) / n_val
return g @ dw
ev = np.linalg.eigvalsh(H + lam * np.eye(d))
print(f"número de condición de H + λI: {ev[-1] / ev[0]:.0f} tasa de GD 1 − μ/L = {1 - ev[0] / ev[-1]:.4f}")
for T in [10, 100, 1000, 5000]:
hu = hipergradiente_desenrollado(lam, T)
print(f"T = {T:5d}: desenrollado {hu: .8f} error relativo {abs(hu - hg) / abs(hg):.1e}")
# optimizar log λ con el hipergradiente
t, pasos = np.log(1e-2), 0
for it in range(100):
g, _ = hipergradiente(np.exp(t))
paso = np.clip(3.0 * np.exp(t) * g, -0.5, 0.5) # dL/d log λ = λ dL/dλ, paso acotado
t -= paso
pasos += 1
if abs(paso) < 1e-8:
break
lam_opt = np.exp(t)
print(f"descenso en log λ: {pasos} pasos")
grid = np.logspace(-3, 3, 601)
lam_grid = grid[np.argmin([val_loss(w_star(l)) for l in grid])]
print(f"λ por hipergradiente: {lam_opt:.4f} λ por rejilla de 601 valores: {lam_grid:.4f}")
print(f"pérdida de validación: λ = 0.01 → {val_loss(w_star(1e-2)):.4f}, óptimo → {val_loss(w_star(lam_opt)):.4f}")The implicit hypergradient agrees with finite differences except for the final printed digit (relative error , that of the differences themselves). Unrolling is instructive: with 10 steps the hypergradient has the wrong sign, and with 100 it has the right sign but is almost ten times too small, because it differentiates , which for small has barely begun to move, not . With condition number 90, descent rate is per step, and roughly a thousand steps are needed for unrolling to resemble implicit, which costs one linear system. Descent in reaches the optimum in 44 hypergradient evaluations and matches the 601-point grid within its resolution.
Finally, a fixed-point layer with hidden dimension 40, its implicit backward pass (by linear system and adjoint iteration), and comparison with backpropagation through unrolled iterations.
import numpy as np
rng = np.random.default_rng(1)
d, p = 40, 10 # dimensión oculta y de entrada
W = rng.normal(size=(d, d))
W *= 0.9 / np.linalg.norm(W, 2) # ‖W‖₂ = 0.9: contracción garantizada
U = rng.normal(size=(d, p)) / np.sqrt(p)
bias = 0.1 * rng.normal(size=d)
x = rng.normal(size=p)
target = rng.normal(size=d) * 0.5
def f(z, W, x):
return np.tanh(W @ z + U @ x + bias)
def forward(W, x, tol=1e-12, max_iter=1000):
z = np.zeros(d)
for k in range(max_iter):
z_new = f(z, W, x)
if np.linalg.norm(z_new - z) < tol:
return z_new, k + 1
z = z_new
return z, max_iter
def loss(z):
return 0.5 * np.sum((z - target) ** 2)
def backward_implicito(z, W, gz, metodo="solve", tol=1e-12):
"""u = (I − Jᵀ)⁻¹ gz con J = diag(1 − z²) W; devuelve dL/dW, dL/dx y las iteraciones usadas."""
Dg = 1 - z ** 2
J = Dg[:, None] * W
if metodo == "solve":
u, its = np.linalg.solve(np.eye(d) - J.T, gz), 0
else: # punto fijo u ← Jᵀu + gz, misma tasa que el forward
u, its = gz.copy(), 0
while True:
u_new = J.T @ u + gz
its += 1
if np.linalg.norm(u_new - u) < tol:
u = u_new
break
u = u_new
a = Dg * u # gradiente respecto de la preactivación
return np.outer(a, z), U.T @ a, its
z, k_fw = forward(W, x)
gW, gx, _ = backward_implicito(z, W, z - target)
_, gx_fp, k_bw = backward_implicito(z, W, z - target, metodo="punto fijo")
print(f"forward: {k_fw} iteraciones backward por punto fijo: {k_bw} iteraciones")
print(f"|gx(solve) − gx(punto fijo)| = {np.linalg.norm(gx - gx_fp):.1e}")
# comprobación con diferencias finitas (re-resolviendo el punto fijo)
h = 1e-6
fd_x = np.array([(loss(forward(W, x + h * e)[0]) - loss(forward(W, x - h * e)[0])) / (2 * h) for e in np.eye(p)])
E = np.zeros_like(W); E[3, 7] = 1
fd_W37 = (loss(forward(W + h * E, x)[0]) - loss(forward(W - h * E, x)[0])) / (2 * h)
print(f"dL/dx: error relativo frente a diferencias {np.linalg.norm(gx - fd_x) / np.linalg.norm(fd_x):.1e}")
print(f"dL/dW[3, 7]: implícito {gW[3, 7]:.10f} diferencias {fd_W37:.10f}")
# desenrollar K iteraciones y retropropagar a través de todas ellas
def desenrollado(W, x, K):
zs = [np.zeros(d)]
for _ in range(K):
zs.append(f(zs[-1], W, x)) # guarda K activaciones de tamaño d
gz, gx = zs[-1] - target, np.zeros(p)
for k in range(K, 0, -1):
a = gz * (1 - zs[k] ** 2)
gx += U.T @ a
gz = W.T @ a
return gx, K * d
rho = max(abs(np.linalg.eigvals((1 - z ** 2)[:, None] * W)))
print(f"radio espectral de J en z*: {rho:.3f}")
for K in [5, 10, 20, 40, 80]:
g_u, mem = desenrollado(W, x, K)
print(f"K = {K:3d}: error relativo {np.linalg.norm(g_u - gx) / np.linalg.norm(gx):.1e} activaciones guardadas {mem:5d} (implícito: {d})")Forward and adjoint iteration need almost the same number of iterations (27 and 29), as predicted by both converging at rate , and give the same gradient as the linear system to . Finite differences confirm it. Unrolling converges to the implicit gradient at the same rate, but stores activations instead of ; here is small and 30 iterations suffice to reach , but near the stability edge, with , about 600 would be needed ().
With libraries: a DEQ layer in PyTorch
In PyTorch the pattern is a custom autograd function. Forward solves the fixed point without a graph (torch.no_grad), so the dynamic graph stores no iterations. Backward reconstructs one layer application with a graph and solves adjoint system by fixed point, obtaining each as an autograd VJP without ever forming . Finally another VJP carries to parameters. The cell checks backward with gradcheck, compares memory with unrolling 60 iterations, and trains the model on a synthetic classification problem.
import math
import time
import warnings
import numpy as np
import torch
import torch.nn as nn
warnings.filterwarnings("ignore", message="Attempting to run cuBLAS")
torch.manual_seed(0)
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def solve_punto_fijo(g, z0, tol=1e-6, max_iter=200):
"""Itera z ← g(z) hasta que el residuo relativo baja de tol."""
z = z0
for k in range(max_iter):
z_new = g(z)
if (z_new - z).norm() <= tol * (1e-8 + z_new.norm()):
return z_new, k + 1
z = z_new
return z, max_iter
ITERS = [] # iteraciones de cada forward y cada backward
class PuntoFijo(torch.autograd.Function):
"""z* = tanh(z* Wᵀ + inj): forward sin grafo, backward implícito resolviendo u = g + Jᵀu."""
@staticmethod
def forward(ctx, inj, W):
with torch.no_grad():
z, k = solve_punto_fijo(lambda z: torch.tanh(z @ W.T + inj), torch.zeros_like(inj))
ctx.save_for_backward(z, inj, W)
ITERS.append(k)
return z
@staticmethod
def backward(ctx, grad_z):
z, inj, W = ctx.saved_tensors
with torch.enable_grad():
z = z.detach().requires_grad_()
inj_ = inj.detach().requires_grad_()
W_ = W.detach().requires_grad_()
fz = torch.tanh(z @ W_.T + inj_) # una sola aplicación de la capa, con grafo
# u = grad_z + Jᵀu, con Jᵀu calculado como VJP de f respecto de z
vjp = lambda u: torch.autograd.grad(fz, z, u, retain_graph=True)[0]
u, k = solve_punto_fijo(lambda u: grad_z + vjp(u), grad_z)
ITERS.append(k)
g_inj, g_W = torch.autograd.grad(fz, (inj_, W_), u)
return g_inj, g_W
class DEQ(nn.Module):
def __init__(self, d_in, d, n_cls, implicito=True, K=None):
super().__init__()
self.U = nn.Linear(d_in, d)
self.W = nn.Parameter(torch.randn(d, d) * 0.5 / math.sqrt(d))
self.head = nn.Linear(d, n_cls)
self.implicito, self.K = implicito, K
def capa(self, x):
inj = self.U(x)
if self.implicito:
return PuntoFijo.apply(inj, self.W)
z = torch.zeros_like(inj)
for _ in range(self.K): # desenrollado: autograd guarda las K iteraciones
z = torch.tanh(z @ self.W.T + inj)
return z
def forward(self, x):
return self.head(self.capa(x))
@torch.no_grad()
def proyectar(self, cota=0.9):
"""Mantiene ‖W‖₂ ≤ cota para que la capa siga siendo una contracción."""
s = torch.linalg.matrix_norm(self.W, ord=2)
if s > cota:
self.W.mul_(cota / s)
# 1) el backward implícito pasa gradcheck (en doble precisión)
m = DEQ(2, 16, 3).double().to(dev)
x = torch.randn(8, 2, dtype=torch.double, device=dev)
inj = m.U(x).detach().requires_grad_()
W = m.W.detach().clone().requires_grad_()
ok = torch.autograd.gradcheck(lambda a, b: PuntoFijo.apply(a, b), (inj, W), eps=1e-6, atol=1e-4)
print("gradcheck del backward implícito:", ok)
# 2) memoria: implícito frente a desenrollar K = 60 iteraciones (lote 1024, d = 1024)
def pico_memoria(implicito):
torch.manual_seed(0)
net = DEQ(64, 1024, 10, implicito=implicito, K=60).to(dev)
xb = torch.randn(1024, 64, device=dev)
yb = torch.randint(0, 10, (1024,), device=dev)
torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
t0 = time.perf_counter()
loss = nn.functional.cross_entropy(net(xb), yb)
loss.backward()
torch.cuda.synchronize()
dt = time.perf_counter() - t0
pico = (torch.cuda.max_memory_allocated() - base) / 2**20
return pico, dt, net.W.grad.clone()
if dev.type == "cuda":
pico_memoria(True) # calentamiento
mem_i, t_i, g_i = pico_memoria(True)
mem_u, t_u, g_u = pico_memoria(False)
cos = torch.nn.functional.cosine_similarity(g_i.flatten(), g_u.flatten(), dim=0).item()
print(f"memoria pico: implícito {mem_i:.0f} MiB desenrollado K=60 {mem_u:.0f} MiB")
print(f"tiempo forward+backward: implícito {t_i*1e3:.0f} ms desenrollado {t_u*1e3:.0f} ms")
print(f"similitud coseno entre los dos gradientes de W: {cos:.6f}")
else:
print("sin GPU: se omite la medida de memoria")
# 3) entrenar en tres espirales entrelazadas (datos sintéticos)
def espirales(n, ruido=0.15, seed=0):
g = np.random.default_rng(seed)
X, Y = [], []
for c in range(3):
t = np.sqrt(g.random(n)) * 3.5
ang = t + 2 * np.pi * c / 3
X.append(np.c_[t * np.cos(ang), t * np.sin(ang)] + ruido * g.normal(size=(n, 2)))
Y.append(np.full(n, c))
return torch.tensor(np.vstack(X), dtype=torch.float32), torch.tensor(np.concatenate(Y))
Xtr, Ytr = espirales(400, seed=0)
Xte, Yte = espirales(400, seed=1)
Xtr, Ytr, Xte, Yte = Xtr.to(dev), Ytr.to(dev), Xte.to(dev), Yte.to(dev)
torch.manual_seed(0)
net = DEQ(2, 64, 3).to(dev)
opt = torch.optim.Adam(net.parameters(), lr=1e-2)
t0 = time.perf_counter()
ITERS.clear()
for it in range(300):
opt.zero_grad()
loss = nn.functional.cross_entropy(net(Xtr), Ytr)
loss.backward()
opt.step()
net.proyectar()
iters = ITERS[::2] # forward y backward se registran alternados
with torch.no_grad():
acc = (net(Xte).argmax(1) == Yte).float().mean().item()
s = torch.linalg.matrix_norm(net.W, ord=2).item()
print(f"300 pasos en {time.perf_counter() - t0:.1f} s iteraciones del forward: {iters[0]} al principio, {iters[-1]} al final")
print(f"pérdida final {loss.item():.3f} exactitud en test {acc:.3f} ‖W‖₂ = {s:.3f}")npm run lab and open the connection link.Three things to observe in the output. Peak memory for unrolling is around 60 times one activation ( four-byte numbers, 4 MiB each), whereas implicit memory does not depend on iteration count. The two gradients agree (cosine similarity 1 to six digits), because with small 60 iterations are more than enough. During training forward goes from about 15 iterations to about 40, because the optimizer pushes against the projection bound: the layer becomes more expressive and simultaneously slower to solve, the tension real DEQs manage by regularizing the Jacobian.
Common mistakes
Exercises
Step 1 of 5. Why can the inverse function theorem be applied to at ?
Step 1 of 4. Which equation does the minimizer satisfy?
More than one answer may be correct.
implicit_grad(F, x_star, theta, dL_dx). F(x, theta) returns an array of shape (n,), x_star (shape (n,)) satisfies F(x_star, theta) = 0, and dL_dx is the gradient of a scalar loss with respect to x. Return (shape (p,)) for implicit function , computing Jacobians and by centered finite differences and solving one adjoint linear system without inverting matrices. Tests compare with finite differences of loss obtained by re-solving the system with scipy.optimize.root, in linear and nonlinear systems with .import numpy as np
def implicit_grad(F, x_star, theta, dL_dx):
"""dL/dθ para x*(θ) definido por F(x*, θ) = 0, con un único sistema lineal adjunto."""
x_star = np.asarray(x_star, dtype=float)
theta = np.asarray(theta, dtype=float)
# tu código: jacobianos numéricos ∂F/∂x (n×n) y ∂F/∂θ (n×p), sistema adjunto y VJP
return np.zeros_like(theta)Summary
- Inverse function. If is and invertible, is a local diffeomorphism around with . The proof is a contraction, , also Newton’s method with a frozen Jacobian. The result is local: and show this.
- Implicit function. If and is invertible, the equation defines a unique of class near . It follows from the previous theorem applied to . In the plane, curve is locally where , with slope ; the condition is sufficient, not necessary.
- Implicit differentiation. Tangent mode solves with and adjoint mode with . The matrix is never inverted or formed: Jacobian-vector products suffice, and solutions must converge or the gradient is biased.
- Argmin. Applied to with positive-definite Hessian: . This is the hypergradient of ridge, iMAML and bilevel optimization; optimal value is even easier to differentiate (envelope).
- Regular level sets. If has maximal rank on , the set is a submanifold of dimension with tangent and normal generated by gradients: the basis of Lagrange multipliers.
- Implicit layers. DEQ, OptNet and hypergradients trade iteration-proportional memory for a linear system at the solution. Gradient existence requires invertible; iterative forward convergence also requires .