Inversion strategies
Bisection against Newton, the safeguarded hybrid, the gradient of a root, and a whole batch at once
04 · Inversion strategies¶
Every smooth marginal of this part inverts the same way: given a level , solve the root problem (4) for . Part 0, notebook 02 solved it by bisection and showed that sample pays for it. This notebook asks how to solve it well, how to differentiate the answer, and how to run it on a whole batch.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
from collections.abc import Callable
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.scipy.stats as jstats
import matplotlib.pyplot as plt
import numpy as np
import optimistix as optx
from jaxtyping import ArrayLike, Bool, Float
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import style_ax, use_compact_figures
from gauss_flows_maps.bijections import MixtureGaussianCDF
from gauss_flows_maps.monotone import Chandrupatla, monotone_inverse
# Root finds and their gradients get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(14)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "optimistix", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
matplotlib : 3.11.2
optimistix : 0.1.0
gauss_flows_maps: 0.3.0
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
We reuse the three-component mixture CDF of notebook 02, (2), with weights , means and scales . Its derivative is the mixture density, which Newton’s method needs and bisection does not.
# Shapes: component (M) = 3
PerComponent = Float[ArrayLike, " component"]
# wₘ, the mixture weights, (component)
weights: PerComponent = jnp.array([0.4, 0.35, 0.25])
# μₘ, the component means, (component)
means: PerComponent = jnp.array([-1.5, 0.3, 2.0])
# σₘ, the component scales, (component)
scales: PerComponent = jnp.array([0.4, 0.6, 0.5])
# a₀ = −12, the lower end of the bracket every solver starts from
LOWER: float = -12.0
# b₀ = 12, its upper end
UPPER: float = 12.0Scalar = Float[ArrayLike, ""]
# user
# F(x) = ∑ₘ wₘ Φ((x − μₘ) / σₘ)
def mixture_cdf(point: Scalar, component_means: PerComponent = means) -> Scalar:
"""The mixture CDF F at a scalar ``point``."""
# ∑ₘ wₘ Φ((x − μₘ) / σₘ)
return jnp.sum(weights * jstats.norm.cdf(point, component_means, scales))
# user
# F'(x) = ∑ₘ wₘ φ((x − μₘ) / σₘ) / σₘ, Newton's slope
def mixture_pdf(point: Scalar, component_means: PerComponent = means) -> Scalar:
"""The mixture density F' at a scalar ``point``."""
# ∑ₘ wₘ φ((x − μₘ) / σₘ) / σₘ
return jnp.sum(weights * jstats.norm.pdf(point, component_means, scales))1. Bisection against Newton¶
Bisection halves a bracket around the root at every step, so its error bound (5) falls by a factor of two per step: linear convergence, about one bit of the answer per step. It needs only the sign of , and for an increasing it cannot fail.
Newton’s method uses the slope as well. From the iterate it follows the tangent of to the level ,
and near a root with the error roughly squares at every step,
where is about . Quadratic convergence doubles the number of correct digits per step. The catch is the word “near”: (1) has no bracket, and where the density is tiny, in a flat tail of the CDF, one tangent step can throw the iterate far away.
We record the residual of both methods at , and of Newton aiming at the extreme level from the start , deep in the left tail.
# Shapes: step = solver steps, as many as each solver is given
PerStep = Float[ArrayLike, " step"]
# user
# bisection: halve the bracket towards the side where F(x) − τ changes sign
def bisection_residuals(tau: float, n_steps: int = 55) -> PerStep:
"""The residual |F(x⁽ⁿ⁾) − τ| of bisection at each of ``n_steps`` steps."""
# a₀ = −12
low_end: float = LOWER
# b₀ = 12
high_end: float = UPPER
# |F(x⁽ⁿ⁾) − τ| at each step
residuals: list[float] = []
for _ in range(n_steps):
# x⁽ⁿ⁾, the midpoint of the bracket
midpoint: float = 0.5 * (low_end + high_end)
# user
# |F(x⁽ⁿ⁾) − τ|
residuals.append(abs(float(mixture_cdf(midpoint) - tau)))
# user
# F(x⁽ⁿ⁾) < τ: the root lies above the midpoint
below: Bool[ArrayLike, ""] = mixture_cdf(midpoint) < tau
# keep the half that holds the root
low_end, high_end = (midpoint, high_end) if below else (low_end, midpoint)
return np.array(residuals)Newton’s path also records each iterate, so we can see where a bad start sends it.
# user
# Newton from x⁽⁰⁾, recording each iterate and its residual
def newton_path(
tau: float, start: float = 0.0, n_steps: int = 12
) -> tuple[PerStep, PerStep]:
"""The residuals |F(x⁽ⁿ⁾) − τ| and iterates x⁽ⁿ⁾ of ``n_steps`` Newton steps."""
# x⁽⁰⁾
iterate: Scalar = start
# |F(x⁽ⁿ⁾) − τ| at each step
residuals: list[float] = []
# x⁽ⁿ⁾ at each step
iterates: list[float] = []
for _ in range(n_steps):
# user
# |F(x⁽ⁿ⁾) − τ|
residuals.append(abs(float(mixture_cdf(iterate) - tau)))
iterates.append(float(iterate))
# user
# x⁽ⁿ⁺¹⁾ = x⁽ⁿ⁾ − (F(x⁽ⁿ⁾) − τ) / F'(x⁽ⁿ⁾)
iterate = iterate - (mixture_cdf(iterate) - tau) / mixture_pdf(iterate)
return np.array(residuals), np.array(iterates)We count the steps each method needs to bring the residual below 10-12.
# user
# the first step n with |F(x⁽ⁿ⁾) − τ| < 10⁻¹²
def first_step_below(residuals: PerStep, tol: float = 1e-12) -> int:
"""The 1-based index of the first residual below ``tol``."""
return int(np.argmax(residuals < tol)) + 1# Shapes: step = 55 for bisection, 12 for Newton, 8 in the tail
# user
# |F(x⁽ⁿ⁾) − τ| of bisection at τ = 0.7
res_bisection: PerStep = bisection_residuals(0.7)
# user
# |F(x⁽ⁿ⁾) − τ| of Newton at τ = 0.7, from x⁽⁰⁾ = 0
res_newton: PerStep
res_newton, _ = newton_path(0.7)
# user
# Newton at τ = 0.999 from x⁽⁰⁾ = −8, deep in the left tail, (step), (step)
res_tail: PerStep
tail_iterates: PerStep
res_tail, tail_iterates = newton_path(0.999, start=-8.0, n_steps=8)# user
# the first bisection step with |F(x⁽ⁿ⁾) − τ| < 10⁻¹²
step_bisection: int = first_step_below(res_bisection)
# user
# the first Newton step with |F(x⁽ⁿ⁾) − τ| < 10⁻¹²
step_newton: int = first_step_below(res_newton)
# the tail iterates x⁽ⁿ⁾ as text
tail_text: str = ", ".join(f"{value:.3g}" for value in tail_iterates)
print(f"τ = 0.7, bisection reaches a residual below 1e-12 at step {step_bisection}")
print(f"τ = 0.7, Newton reaches a residual below 1e-12 at step {step_newton}")
print("Newton residuals:", ", ".join(f"{r:.0e}" for r in res_newton[:6]))
print("τ = 0.999 from x⁽⁰⁾ = -8, Newton iterates:", tail_text)τ = 0.7, bisection reaches a residual below 1e-12 at step 41
τ = 0.7, Newton reaches a residual below 1e-12 at step 5
Newton residuals: 2e-01, 3e-03, 3e-05, 3e-09, 1e-16, 1e-16
τ = 0.999 from x⁽⁰⁾ = -8, Newton iterates: -8, 1.54e+42, -inf, nan, nan, nan, nan, nan
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
steps = np.arange(1, len(res_bisection) + 1)
axes[0].semilogy(steps, np.maximum(res_bisection, 1e-17), "-o", ms=3, color="C0")
axes[0].lines[-1].set_label("bisection, linear")
steps = np.arange(1, len(res_newton) + 1)
axes[0].semilogy(steps, np.maximum(res_newton, 1e-17), "-s", ms=4, color="C2")
axes[0].lines[-1].set_label("Newton, quadratic")
axes[0].set(xlabel="step $n$", ylabel=r"residual $|F(x^{(n)}) - \tau|$")
axes[0].set_title(r"$\tau = 0.7$")
axes[0].legend()
style_ax(axes[0])
steps = np.arange(1, len(res_tail) + 1)
finite = np.isfinite(res_tail)
axes[1].semilogy(
steps[finite], np.maximum(res_tail[finite], 1e-17), "-s", ms=5, color="C3"
)
axes[1].lines[-1].set_label("Newton from $x^{(0)} = -8$")
axes[1].axvspan(steps[finite][-1], steps[-1], color="C3", alpha=0.1)
axes[1].set(xlabel="step $n$", ylabel="residual")
axes[1].set_title(r"$\tau = 0.999$: the residual turns into nan")
axes[1].legend()
style_ax(axes[1])
fig.tight_layout()
Figure 1:Left: at Newton’s residual (green) falls to machine precision in a handful of steps, while bisection (blue) gains about one bit per step. Right: Newton aiming at from , where the density is almost zero; the first tangent step overshoots to about 1042 and the iteration ends in nan (shaded).
The two panels are the whole trade-off. Bisection is slow and certain; Newton is fast and conditional on a good start. A good start is exactly what a flow cannot promise, because its sampling direction feeds the inverse every level of , extreme ones included.
2. The safeguarded hybrid¶
The standard fix keeps both: a bisection bracket that always contains the root, and a Newton proposal , the right-hand side of (1), that is accepted only if it lands strictly inside the bracket Brent, 1973:
After each step the bracket shrinks to the side of where changes sign. The bracket always contains the root, so the hybrid cannot diverge, and once the iterate is near the root every proposal is accepted and convergence is quadratic. The rule does not promise bisection’s rate, though: a Newton step that lands inside the bracket need not halve it, so on a CDF with a long flat stretch, such as on at , accepted Newton steps creep towards the root and the hybrid takes about twice as many evaluations as bisection. Brent’s method Brent, 1973 closes this gap with a sufficient-progress check that bisects whenever the interpolation steps stop shrinking the bracket fast enough.
# user
# keep the side of x⁽ⁿ⁾ where F(x) − τ changes sign
def tighten(
bracket: tuple[float, float], iterate: float, residual: float
) -> tuple[float, float]:
"""The bracket [aₙ₊₁, bₙ₊₁] once the residual F(x⁽ⁿ⁾) − τ is known."""
if residual < 0:
return iterate, bracket[1]
return bracket[0], iterate
# user
# x⁽ⁿ⁺¹⁾ = x̃⁽ⁿ⁺¹⁾ if it lands inside [aₙ, bₙ], else the midpoint
def newton_or_bisect(
bracket: tuple[float, float], iterate: float, residual: float
) -> tuple[float, str]:
"""The next iterate, and its kind: N for Newton, B for bisection."""
# user
# x̃⁽ⁿ⁺¹⁾ = x⁽ⁿ⁾ − (F(x⁽ⁿ⁾) − τ) / F'(x⁽ⁿ⁾)
proposal: Scalar = iterate - residual / mixture_pdf(iterate)
if bracket[0] < proposal < bracket[1]:
return float(proposal), "N"
return 0.5 * (bracket[0] + bracket[1]), "B"The hybrid then tries Newton at every step and falls back to the midpoint whenever the proposal leaves the bracket, for at most 40 steps or until the residual is below 10-14.
# user
# the safeguarded hybrid: accept x̃⁽ⁿ⁺¹⁾ inside [aₙ, bₙ], else bisect
def safeguarded_newton(tau: float, start: float) -> tuple[PerStep, str]:
"""The residuals and step kinds (N = Newton, B = bisection) of the hybrid."""
# [a₀, b₀] = [−12, 12]
bracket: tuple[float, float] = (LOWER, UPPER)
# x⁽⁰⁾
iterate: float = start
# |F(x⁽ⁿ⁾) − τ| and the kind of each step
residuals, kinds = [], []
for _ in range(40):
# user
# F(x⁽ⁿ⁾) − τ
residual: float = float(mixture_cdf(iterate) - tau)
residuals.append(abs(residual))
if abs(residual) < 1e-14:
break
# user
# [aₙ₊₁, bₙ₊₁], the side of x⁽ⁿ⁾ that holds the root
bracket = tighten(bracket, iterate, residual)
# user
# x⁽ⁿ⁺¹⁾ and whether Newton or bisection produced it
kind: str
iterate, kind = newton_or_bisect(bracket, iterate, residual)
kinds.append(kind)
return np.array(residuals), "".join(kinds)# Shapes: step = 10 hybrid steps
# user
# |F(x⁽ⁿ⁾) − τ| and the step kinds, at τ = 0.999 from x⁽⁰⁾ = −8
res_safe: PerStep
kinds: str
res_safe, kinds = safeguarded_newton(0.999, start=-8.0)
print(f"safeguarded Newton, τ = 0.999 from x⁽⁰⁾ = -8: residual {res_safe[-1]:.1e}")
print(f"after {len(kinds)} steps, step kinds (B = bisection, N = Newton): {kinds}")safeguarded Newton, τ = 0.999 from x⁽⁰⁾ = -8: residual 1.1e-16
after 10 steps, step kinds (B = bisection, N = Newton): BNNNNNNNNN
gauss_flows ships a derivative-free member of the same family. monotone_inverse defaults to Chandrupatla Chandrupatla, 1997, an optimistix solver that keeps a bracket like bisection but proposes inverse quadratic interpolation steps through the last three iterates instead of Newton steps, and falls back to bisection whenever the interpolation is not trustworthy. We count the steps each optimistix solver takes to a tolerance of 10-12 at the easy level and at the hard one.
# user
# steps and final residual of an optimistix solver for F(x) = τ
def root_steps(solver: optx.AbstractRootFinder, tau: float) -> tuple[int, float]:
"""The number of steps ``solver`` takes, and its final |F(x⋆) − τ|."""
# today (optimistix)
# x⋆ with F(x⋆) − τ = 0, started inside the bracket [−12, 12]
solution: optx.Solution = optx.root_find(
lambda point, level: mixture_cdf(point) - level,
solver,
0.0,
args=tau,
options={"lower": LOWER, "upper": UPPER},
max_steps=200,
throw=False,
)
# the number of solver steps
n_steps: int = int(solution.stats["num_steps"])
# user
# |F(x⋆) − τ|
residual: float = abs(float(mixture_cdf(solution.value) - tau))
return n_steps, residualWe run both solvers at the easy level and at the hard one.
# today (optimistix, gauss_flows)
# bisection and Chandrupatla, both to a tolerance of 10⁻¹²
solvers = {
"Bisection": optx.Bisection(rtol=1e-12, atol=1e-12),
"Chandrupatla": Chandrupatla(rtol=1e-12, atol=1e-12),
}
for name, solver in solvers.items():
for tau in (0.7, 0.999):
# user
# the steps to the root, and its residual |F(x⋆) − τ|
n_steps: int
residual: float
n_steps, residual = root_steps(solver, tau)
print(f"{name:>12} τ = {tau:<5} steps {n_steps:3d} residual {residual:.1e}") Bisection τ = 0.7 steps 44 residual 9.5e-14
Bisection τ = 0.999 steps 43 residual 2.1e-15
Chandrupatla τ = 0.7 steps 11 residual 1.1e-16
Chandrupatla τ = 0.999 steps 14 residual 1.1e-16
res_bisection_tail = bisection_residuals(0.999)
fig, ax = plt.subplots(figsize=(8, 4.2))
steps = np.arange(1, len(res_safe) + 1)
ax.semilogy(steps, np.maximum(res_safe, 1e-17), "-o", ms=4, color="C4")
ax.lines[-1].set_label("safeguarded Newton")
steps = np.arange(1, len(res_bisection_tail) + 1)
ax.semilogy(steps, np.maximum(res_bisection_tail, 1e-17), "--", lw=1, color="C0")
ax.lines[-1].set_label("bisection")
ax.set(xlabel="step $n$", ylabel=r"residual $|F(x^{(n)}) - \tau|$")
ax.set_title(r"$\tau = 0.999$ from $x^{(0)} = -8$")
ax.legend()
style_ax(ax)
fig.tight_layout()
Figure 2:The level and the start that sent plain Newton to nan in Figure 1. The safeguarded hybrid (3) (purple) stays finite: its first proposal falls outside the bracket and is replaced by a bisection step, after which every Newton step is accepted and the residual collapses within ten steps. Bisection (dashed) is shown for reference.
3. Differentiating the inverse¶
Training a flow through its sampling direction, or fitting a marginal whose inverse sits inside a loss, needs the derivative of the root with respect to the level and to the parameters of (its weights, means and scales). The root satisfies for every and , and differentiating that identity gives the implicit-function gradients Blondel et al., 2022,
Why
How a program reaches these numbers depends on the solver, and there are four common routes.
| Route | What is differentiated | Gradient | Memory |
|---|---|---|---|
| unroll bisection | every where(F(mid) < τ) step | zero, wrong | grows with the steps |
| unroll Newton | every step (1) | correct | grows with the steps |
| one step | one Newton step from the detached root (6) | correct | constant |
| implicit adjoint | the identity , by a linear solve | correct | constant |
Unrolled bisection fails because its output depends on and only through comparisons, which are piecewise constant, so automatic differentiation sees a derivative of zero everywhere. The one-step route repairs it cheaply. Write for the stop-gradient operator, which passes a value through and blocks its derivative, and take one Newton step from the detached root:
Why one step is enough
We differentiate all four routes in on a grid of levels and compare with (4).
# user
# x⋆ by optimistix bisection, differentiated by the implicit adjoint
def root(tau: Scalar) -> Scalar:
"""The converged root x⋆, by optimistix bisection with the implicit adjoint."""
# today (optimistix)
# x⋆ with F(x⋆) − τ = 0 on [−12, 12]
solution: optx.Solution = optx.root_find(
lambda point, level: mixture_cdf(point) - level,
optx.Bisection(rtol=1e-12, atol=1e-14),
0.0,
args=tau,
options={"lower": LOWER, "upper": UPPER},
max_steps=200,
throw=False,
)
return solution.valueThe two unrolled routes trace every step of their loop, so automatic differentiation follows each comparison or tangent step.
# user
# bisection unrolled for automatic differentiation
def inverse_unrolled_bisection(tau: Scalar, n_steps: int = 60) -> Scalar:
"""The root after ``n_steps`` traced bisection steps."""
# a₀ = −12
low_end: Scalar = LOWER
# b₀ = 12
high_end: Scalar = UPPER
for _ in range(n_steps):
# x⁽ⁿ⁾, the midpoint of the bracket
midpoint: Scalar = 0.5 * (low_end + high_end)
# user
# F(x⁽ⁿ⁾) < τ, a comparison whose derivative is zero
below: Bool[ArrayLike, ""] = mixture_cdf(midpoint) < tau
# aₙ₊₁ = x⁽ⁿ⁾ if F(x⁽ⁿ⁾) < τ, else aₙ
low_end = jnp.where(below, midpoint, low_end)
# bₙ₊₁ = bₙ if F(x⁽ⁿ⁾) < τ, else x⁽ⁿ⁾
high_end = jnp.where(below, high_end, midpoint)
# the midpoint of the last bracket
return 0.5 * (low_end + high_end)# user
# Newton unrolled for automatic differentiation
def inverse_unrolled_newton(tau: Scalar, n_steps: int = 30) -> Scalar:
"""The root after ``n_steps`` traced Newton steps from x⁽⁰⁾ = 0."""
# x⁽⁰⁾ = 0
iterate: Scalar = 0.0
for _ in range(n_steps):
# user
# x⁽ⁿ⁺¹⁾ = x⁽ⁿ⁾ − (F(x⁽ⁿ⁾) − τ) / F'(x⁽ⁿ⁾)
iterate = iterate - (mixture_cdf(iterate) - tau) / mixture_pdf(iterate)
return iterate
# user
# one Newton step from the detached root
def inverse_one_step(tau: Scalar) -> Scalar:
"""The root x̂, one Newton step from sg(x⋆)."""
# user
# sg(x⋆), the root with its derivative blocked
detached_root: Scalar = jax.lax.stop_gradient(root(tau))
# user
# F(sg(x⋆)) − τ
residual: Scalar = mixture_cdf(detached_root) - tau
# user
# the Newton step (F(sg(x⋆)) − τ) / F'(sg(x⋆))
step: Scalar = residual / mixture_pdf(detached_root)
# x̂ = sg(x⋆) − (F(sg(x⋆)) − τ) / F'(sg(x⋆))
return detached_root - stepWe differentiate each route at 40 levels and keep the implicit-function value as the reference.
# Shapes: quantile = 40 levels τ
PerQuantile = Float[ArrayLike, " quantile"]
# τ from 0.03 to 0.97, (quantile)
taus: PerQuantile = jnp.linspace(0.03, 0.97, 40)
# user
# ∂x⋆/∂τ = 1 / F'(x⋆), (quantile)
grad_exact: PerQuantile = jax.vmap(lambda tau: 1.0 / mixture_pdf(root(tau)))(taus)
# user
# the four routes to x⋆(τ)
routes = {
"unrolled bisection": inverse_unrolled_bisection,
"unrolled Newton": inverse_unrolled_newton,
"one step": inverse_one_step,
"implicit adjoint": root,
}
# user
# ∂x⋆/∂τ of each route, by automatic differentiation
grads: dict[str, PerQuantile] = {
name: jax.vmap(jax.grad(route))(taus) for name, route in routes.items()
}for name, grad in grads.items():
# max over τ of |∂x⋆/∂τ − 1 / F'(x⋆)|
error: float = float(jnp.max(jnp.abs(grad - grad_exact)))
# max over τ of |∂x⋆/∂τ|
largest: float = float(jnp.max(jnp.abs(grad)))
print(
f"{name:>18}: max |∂x⋆/∂τ - 1/F'(x⋆)| = {error:.1e}, "
f"max |∂x⋆/∂τ| = {largest:.2f}"
)unrolled bisection: max |∂x⋆/∂τ - 1/F'(x⋆)| = 1.0e+01, max |∂x⋆/∂τ| = 0.00
unrolled Newton: max |∂x⋆/∂τ - 1/F'(x⋆)| = 6.0e-12, max |∂x⋆/∂τ| = 9.99
one step: max |∂x⋆/∂τ - 1/F'(x⋆)| = 0.0e+00, max |∂x⋆/∂τ| = 9.99
implicit adjoint: max |∂x⋆/∂τ - 1/F'(x⋆)| = 3.6e-15, max |∂x⋆/∂τ| = 9.99
markers = {
"implicit adjoint": ("o", "C2"),
"one step": ("s", "C1"),
"unrolled Newton": ("^", "C4"),
}
fig, ax = plt.subplots(figsize=(8, 4.4))
ax.plot(taus, grad_exact, "-", color="k", lw=2.5, label=r"$1 / F'(x^\star)$")
for name, (marker, color) in markers.items():
ax.plot(taus, grads[name], marker, color=color, ms=5, mfc="none", label=name)
ax.plot(taus, grads["unrolled bisection"], "--", color="C3", label="unrolled bisection")
ax.set(xlabel=r"level $\tau$", ylabel=r"$\partial x^\star / \partial \tau$")
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
Figure 3:The derivative of the inverse in the level, , by each route, against the implicit-function value (4) (black). The adjoint, the one-step route and unrolled Newton lie on the curve; unrolled bisection (red, dashed) is zero everywhere.
Unrolled Newton is correct here but keeps every iterate for the backward pass, and it inherits Newton’s fragility from section 1. The one-step and adjoint routes cost one evaluation of at the root whatever the number of solver steps, which is why libraries use them.
What gauss_flows does today¶
Both inverses in gauss_flows differentiate correctly. MixtureGaussianCDF.inverse brackets the root by bisection and then takes the one step (6) from the detached root; monotone_inverse runs Chandrupatla through optimistix.root_find with the implicit adjoint. Older versions returned the bare unrolled bisection and so a zero gradient, which gauss_flows#111 reported and fixed. We check both: the level derivative of a fitted MixtureGaussianCDF, against the reciprocal of its forward derivative, and the derivative of a monotone_inverse root in the means , against (5).
# Shapes: sample (N) = 2,000; state (D_x) = 1
# x ~ 𝒩(0, 1.5²), (sample, state)
fit_data: Float[ArrayLike, "sample state"] = jnp.asarray(
rng.normal(0.0, 1.5, (2000, 1))
)
# today (gauss_flows)
# a six-component mixture CDF initialised from the data
marginal: MixtureGaussianCDF = MixtureGaussianCDF.from_data(fit_data, n_components=6)We invert one latent value and compare the derivative through the inverse with the reciprocal of the forward derivative at the root.
# Shapes: latent = 1; state = 1
PerLatent = Float[ArrayLike, " latent"]
PerState = Float[ArrayLike, " state"]
# a latent value z, (latent)
latent: PerLatent = jnp.array([0.7])
# today (gauss_flows)
# x = T⁻¹(z), by bisection and then one Newton step, (state)
recovered: PerState = marginal.inverse(latent)
# today (gauss_flows)
# ∂x/∂z through the inverse, (latent)
grad_inverse: PerLatent = jax.grad(lambda point: marginal.inverse(point).sum())(latent)
# today (gauss_flows)
# ∂z/∂x of the forward map at the root, (state)
grad_forward: PerState = jax.grad(lambda point: marginal.transform(point).sum())(
recovered
)
print(f"MixtureGaussianCDF: ∂x/∂z through .inverse = {float(grad_inverse[0]):.6f}")
print(
f" 1 / (∂z/∂x) at the root = {1.0 / float(grad_forward[0]):.6f}"
)MixtureGaussianCDF: ∂x/∂z through .inverse = 1.161899
1 / (∂z/∂x) at the root = 1.161899
The same inverse must also pass gradients to every parameter of the mixture.
# θ, split from the static structure of the layer
params: eqx.Module
static: eqx.Module
params, static = eqx.partition(marginal, eqx.is_inexact_array)
# today (gauss_flows)
# ∂x/∂θ through the inverse
grad_params: MixtureGaussianCDF = jax.grad(
lambda theta: eqx.combine(theta, static).inverse(latent).sum()
)(params)
# whether each leaf of ∂x/∂θ has a nonzero entry
nonzero: list[bool] = [
float(jnp.max(jnp.abs(leaf))) > 0 for leaf in jax.tree.leaves(grad_params)
]
print(f" every parameter gradient nonzero: {all(nonzero)}") every parameter gradient nonzero: True
For monotone_inverse we differentiate the root in the means and compare with the implicit-function value.
# the level τ
tau: float = 0.7
# today (gauss_flows)
# x⋆ = F⁻¹(τ), by Chandrupatla with the implicit adjoint
x_star: Scalar = monotone_inverse(
mixture_cdf, tau, LOWER, UPPER, rtol=1e-12, atol=1e-12
)
# user
# x⋆(μ), the root as a function of the means
def root_in_means(component_means: PerComponent) -> Scalar:
"""The root x⋆ = F⁻¹(τ; μ), by ``monotone_inverse``, as a function of μ."""
# user
# F(x; μ) with the means μ held as an argument
def cdf(point: Scalar) -> Scalar:
return mixture_cdf(point, component_means)
# today (gauss_flows)
# x⋆ = F⁻¹(τ; μ)
return monotone_inverse(cdf, tau, LOWER, UPPER, rtol=1e-12, atol=1e-12)# user
# ∂x⋆/∂μ, by automatic differentiation through the solve, (component)
grad_mu: PerComponent = jax.grad(root_in_means)(means)
# user
# ∂_μ F(x⋆; μ), (component)
cdf_grad_mu: PerComponent = jax.grad(
lambda component_means: mixture_cdf(x_star, component_means)
)(means)
# user
# ∂x⋆/∂μ = −∂_μ F(x⋆; μ) / F'(x⋆), (component)
grad_mu_exact: PerComponent = -cdf_grad_mu / mixture_pdf(x_star)
print(f"monotone_inverse: ∂x⋆/∂μ = {np.round(np.asarray(grad_mu), 6)}")
print(f"eq-inv-dtheta: ∂x⋆/∂μ = {np.round(np.asarray(grad_mu_exact), 6)}")monotone_inverse: ∂x⋆/∂μ = [0. 0.880307 0.119693]
eq-inv-dtheta: ∂x⋆/∂μ = [0. 0.880307 0.119693]
The two pairs agree to the printed digits. The derivative in the means also reads naturally: at the root sits near the second component, so moving its mean moves the root most, and the first component, far to the left, barely matters.
4. A whole batch at once¶
A flow inverts every coordinate of every sample in one call. We write the scalar solve once and jax.vmap it, which traces it once and compiles the batch into one kernel, and compare with a Python loop that calls the same compiled scalar solve once per level. monotone_inverse needs no vmap at all, since it takes an elementwise and an array of levels.
# Shapes: quantile = 4,000 levels τ
# user
# one scalar solve, the unit that vmap batches
def solve_one(tau: Scalar) -> Scalar:
"""The root x⋆ at a single level ``tau``."""
# user
# x⋆ = F⁻¹(τ)
return root(tau)
# user
# x⋆ at a batch of levels, traced once into one kernel
solve_batch: Callable[[PerQuantile], PerQuantile]
solve_batch = jax.jit(jax.vmap(solve_one))
# user
# x⋆ at one level, compiled
solve_scalar: Callable[[Scalar], Scalar]
solve_scalar = jax.jit(solve_one)
# today (gauss_flows)
# x⋆ at a batch of levels by monotone_inverse on an elementwise F
solve_library: Callable[[PerQuantile], PerQuantile]
solve_library = jax.jit(
lambda levels: monotone_inverse(jax.vmap(mixture_cdf), levels, LOWER, UPPER)
)
# τ ~ 𝒰(0.01, 0.99), (quantile)
levels: PerQuantile = jnp.asarray(rng.uniform(0.01, 0.99, 4000))Each solve is compiled once before we time it.
# user
# compile each solve once
solve_batch(levels).block_until_ready()
solve_scalar(levels[0]).block_until_ready()
solve_library(levels).block_until_ready()
# user
# mean wall time per level, in microseconds
def per_level_us(
fn: Callable[..., object], args: tuple, n_levels: int, repeats: int = 5
) -> float:
"""The mean time of ``fn(*args)`` per level, over ``repeats`` calls, in µs."""
# the start time
start: float = time.perf_counter()
for _ in range(repeats):
fn(*args)
# elapsed / (repeats × n_levels), in µs
return (time.perf_counter() - start) / repeats / n_levels * 1e6# Shapes: quantile = 4,000 levels τ, of which the slow loop takes the first 200
# user
# time per level of the vmapped solve
t_batch: float = per_level_us(
lambda u: solve_batch(u).block_until_ready(), (levels,), 4000
)
# user
# time per level of monotone_inverse on the array
t_library: float = per_level_us(
lambda u: solve_library(u).block_until_ready(), (levels,), 4000
)
# the first 200 levels, for the slow loop, (quantile)
subset: PerQuantile = levels[:200]
# user
# time per level of a Python loop over the scalar solve
t_loop: float = per_level_us(
lambda u: [solve_scalar(level).block_until_ready() for level in u],
(subset,),
200,
1,
)# user
# x⋆ for every level, (quantile)
batch_roots: PerQuantile = solve_batch(levels)
# user
# max |F(x⋆) − τ| over the batch
error: float = float(jnp.max(jnp.abs(jax.vmap(mixture_cdf)(batch_roots) - levels)))
print(f"vmap, one kernel: {t_batch:7.2f} µs per level")
print(f"monotone_inverse, array: {t_library:7.2f} µs per level")
print(f"Python loop, per element: {t_loop:7.2f} µs per level")
print(f"the loop is {t_loop / t_batch:.0f} times slower per level than vmap")
print(f"batched accuracy: max |F(x⋆) - τ| = {error:.1e}")vmap, one kernel: 4.09 µs per level
monotone_inverse, array: 1.84 µs per level
Python loop, per element: 1392.55 µs per level
the loop is 340 times slower per level than vmap
batched accuracy: max |F(x⋆) - τ| = 2.7e-13
fig, ax = plt.subplots(figsize=(7, 4))
labels = ["vmap", "monotone_inverse", "Python loop"]
bars = ax.bar(labels, [t_batch, t_library, t_loop], color=["C2", "C0", "C3"])
ax.bar_label(bars, fmt="%.1f µs", padding=3)
ax.set(ylabel="time per level (µs)", yscale="log")
style_ax(ax)
fig.tight_layout()
Figure 4:Time per inversion on this machine, log scale. The vmapped solve and monotone_inverse on an array each run as one compiled kernel; the Python loop pays a dispatch per level for the same compiled scalar solve. The absolute numbers depend on the hardware; the gap does not go away.
The loop is slower per level by the factor printed above, for exactly the same arithmetic. A marginal layer on coordinates does the same thing with one more batch axis, so the inverse of a whole flow layer is still one kernel.
Recap¶
| Concept | Equation | In code |
|---|---|---|
| the root problem and bisection | (4), (5) | optimistix.Bisection |
| Newton, quadratic near the root | (1), (2) | Figure 1 |
| the safeguarded hybrid | (3) | Chandrupatla, monotone_inverse |
| gradient of the root | (4), (5) | optimistix.ImplicitAdjoint |
| one Newton step from the detached root | (6) | MixtureGaussianCDF.inverse |
| a batch in one kernel | none | jax.vmap, monotone_inverse on an array |
Next. Part 1 can now build, fit, train and invert a single one-dimensional marginal. Part 2 puts rotations between the marginals, so that a stack of them can remove dependence between coordinates, the second half of the layer (3).
- Brent, R. P. (1973). Algorithms for Minimization Without Derivatives. Prentice-Hall.
- Chandrupatla, T. R. (1997). A new hybrid quadratic/bisection algorithm for finding the zero of a nonlinear function without using derivatives. Advances in Engineering Software, 28(3), 145–149. 10.1016/S0965-9978(96)00051-8
- Blondel, M., Berthet, Q., Cuturi, M., Frostig, R., Hoyer, S., Llinares-López, F., Pedregosa, F., & Vert, J.-P. (2022). Efficient and Modular Implicit Differentiation. Advances in Neural Information Processing Systems (NeurIPS).