AI Wiki中文/EN

Normalizing flows: keeping probability while reshaping samples

归一化流

Derive both Jacobian directions, fit a nonlinear density and expose a missing-preimage error.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Stretching a distribution changes its height

Imagine a synthetic sensor whose readings are obtained by stretching a Gaussian random variable. Doubling every reading doubles the width of each interval. Its probability mass has not doubled, so its density must become half as high. Moving points without adjusting density would create probability out of nowhere.

A normalizing flow builds a distribution by composing invertible transformations. It can generate a sample and evaluate its density when both the inverse and the required derivatives are tractable. Rezende and Mohamed use finite flows to make variational posteriors more flexible; Real NVP constructs transformations suitable for density estimation. These are related uses, not a claim that every flow is a variational autoencoder. Read probability densities, determinants and the Jacobian first.

Computed densities, generating derivatives and two-preimage correction accompany an independently checked sample fit.
Computed densities, generating derivatives and two-preimage correction accompany an independently checked sample fit.

Choose a direction before choosing a sign

Let Z have known density pZ on a region of D-dimensional Euclidean space. Let g map that region bijectively onto the data region, with a differentiable inverse f and a nonsingular Jacobian on the region of interest. Write x=g(z) and z=f(x). A density is probability per unit volume; the absolute determinant measures the local volume change.

x=g(z),z=f(x),f=g−1,pX(x)=pZ(f(x))∣det⁡Df(x)∣=pZ(z)∣det⁡Dg(z)∣.x=g(z),\quad z=f(x),\quad f=g^{-1},\qquad p_X(x)=p_Z(f(x))\left|\det Df(x)\right|=\frac{p_Z(z)}{|\det Dg(z)|}.

An orientation reversal gives a negative determinant but cannot give negative probability. That is why the absolute value matters. The two expressions use opposite directions of the same map; adding a forward log-determinant where an inverse one is needed changes the distribution. The change-of-variable rule and finite composition appear in Section 3.1.

For generating maps g1 through gK, set z0=z and zk=gk(zk−1). The chain rule turns a product of determinants into a sum of log absolute determinants:

log⁡pX(zK)=log⁡pZ(z0)−∑k=1Klog⁡∣det⁡Dgk(zk−1)∣.\log p_X(z_K)=\log p_Z(z_0)-\sum_{k=1}^{K}\log\left|\det Dg_k(z_{k-1})\right|.

For density fitting, the data x stays fixed while parameters change. Minimize the average negative log density. “Exact likelihood” here means that the model density has a tractable expression, subject to floating-point error; it does not mean that the model equals the unknown data distribution.

L(θ)=−1N∑i=1Nlog⁡pθ(xi).L(\theta)=-\frac1N\sum_{i=1}^{N}\log p_\theta(x_i).

A flow with an independent answer

Our original one-dimensional example uses a monotone sinh transformation. The scale exp(ρ) is positive for every finite ρ, and sinh is a bijection from the real line to itself. μ controls location before the nonlinear stretch; it is not generally the mean of X.

Z∼N(0,1),X=sinh⁡(eρZ+μ),z=(asinh⁡x−μ)e−ρ,dzdx=e−ρ1+x2.Z\sim\mathcal N(0,1),\quad X=\sinh(e^\rho Z+\mu),\quad z=(\operatorname{asinh}x-\mu)e^{-\rho},\quad \frac{dz}{dx}=\frac{e^{-\rho}}{\sqrt{1+x^2}}.

Substitution gives a density whose tail behavior differs from a Gaussian in data space. The logarithm separates the base-density term and the two volume corrections:

log⁡pX(x)=−12z2−12log⁡(2π)−ρ−12log⁡(1+x2).\log p_X(x)=-\tfrac12z^2-\tfrac12\log(2\pi)-\rho-\tfrac12\log(1+x^2).

Differentiate while keeping each observed x fixed. The asinh Jacobian term contains no μ or ρ, while z depends on both:

∂L∂μ=−e−ρz‾,∂L∂ρ=1−z2‾.\frac{\partial L}{\partial\mu}=-e^{-\rho}\overline z,\qquad \frac{\partial L}{\partial\rho}=1-\overline{z^2}.

There is also an analytic solution. Transform the observations to yi=asinh(xi), then fit their Gaussian mean and variance. This provides an answer independent of the iterative optimizer:

μ^=y‾,ρ^=12log⁡ ⁣[1N∑i(yi−y‾)2].\widehat\mu=\overline y,\qquad \widehat\rho=\tfrac12\log\!\left[\frac1N\sum_i(y_i-\overline y)^2\right].

The variance must be positive. If every transformed observation is identical, the unconstrained likelihood grows without bound as scale approaches zero. A lower scale bound defines a different constrained problem; silently clipping the estimate would hide that distinction.

Now deliberately break invertibility: X=Z² merges z and −z. For x>0, adding the contributions of both preimages gives:

pX(x)=ϕ(x)2x+ϕ(−x)2x=e−x/22πx,x>0.p_X(x)=\frac{\phi(\sqrt x)}{2\sqrt x}+\frac{\phi(-\sqrt x)}{2\sqrt x}=\frac{e^{-x/2}}{\sqrt{2\pi x}},\qquad x>0.

Here φ is the standard-normal density. A single inverse branch accounts for only half the mass. The density diverges at zero, yet the distribution remains integrable. This counterexample is not a regular invertible flow; it explains why bijectivity was an assumption rather than decoration.

Fit, integrate and check the direction

Save the following as normalizing_flows.py, using Python 3.12 and NumPy 1.26.4. It fits two parameters, evaluates a CDF independently through erf, and includes a two-dimensional affine density and the folded-square counterexample. No upstream implementation is copied.

Each density or gradient evaluation costs O(N) time and O(N) array space. T fitting steps cost O(TN). A general dense D-by-D determinant or linear solve costs O(D³); the inverse and the parameterized transformation have their own costs. Structured flow architectures such as Real NVP address this bottleneck rather than making arbitrary determinants cheap.

The program bounds numerical inputs and parameters to keep the small demonstration well behaved. Those checks do not turn the mathematical distribution into a bounded-support distribution. The analytic MLE is returned without clipping; evaluation rejects parameters outside the implementation’s declared range.

"""Original one-dimensional density lesson; NumPy only, synthetic data."""
import json
import math
import numpy as np


def vector(x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 1 or not 1 <= x.size <= 2048 or not np.all(np.isfinite(x)) or np.max(np.abs(x)) > 1e4:
        raise ValueError('Expected 1..2048 finite values with magnitude <= 10000.')
    return x


def parameters(p):
    p = np.asarray(p, dtype=float)
    if p.shape != (2,) or not np.all(np.isfinite(p)) or not (-2 <= p[0] <= 2 and -2 <= p[1] <= 1):
        raise ValueError('Expected [mu, rho] in [-2,2] x [-2,1].')
    return p


def generate(z, p):
    z, (mu, rho) = vector(z), parameters(p)
    argument = np.exp(rho) * z + mu
    if np.max(np.abs(argument)) > 9:
        raise ValueError('Teaching implementation limits the sinh argument to [-9,9].')
    return np.sinh(argument)


def log_density(x, p):
    x, (mu, rho) = vector(x), parameters(p)
    z = (np.arcsinh(x) - mu) * np.exp(-rho)
    return -.5*z*z - .5*np.log(2*np.pi) - rho - .5*np.log1p(x*x)


def objective(x, p):
    x, (mu, rho) = vector(x), parameters(p)
    z = (np.arcsinh(x) - mu) * np.exp(-rho)
    return float(-log_density(x, p).mean()), np.array([-z.mean()*np.exp(-rho), 1-np.mean(z*z)])


def maximum_likelihood(x):
    y = np.arcsinh(vector(x))
    variance = y.var()
    if variance <= 1e-14:
        raise ValueError('A collapsed sample has no finite unconstrained scale MLE.')
    # This is the unconstrained analytic optimum, not a clipped estimate.
    return np.array([y.mean(), .5*np.log(variance)])


def cdf(x, p):
    x, (mu, rho) = vector(x), parameters(p)
    z = (np.arcsinh(x) - mu)*np.exp(-rho)
    return np.array([.5*(1+math.erf(v/np.sqrt(2))) for v in z])


def affine_log_density(x, matrix, shift):
    x, matrix, shift = np.asarray(x, float), np.asarray(matrix, float), np.asarray(shift, float)
    if x.shape != (2,) or matrix.shape != (2, 2) or shift.shape != (2,) or not all(np.all(np.isfinite(v)) for v in (x, matrix, shift)):
        raise ValueError('Expected finite 2D point, 2x2 matrix and shift.')
    sign, logabsdet = np.linalg.slogdet(matrix)
    if sign == 0:
        raise ValueError('The generating map must be invertible.')
    z = np.linalg.solve(matrix, x-shift)
    return float(-.5*z@z-np.log(2*np.pi)-logabsdet)


def square_density(x):
    x = vector(x)
    if np.any(x <= 0):
        raise ValueError('This two-branch formula requires x > 0; density diverges at zero.')
    return np.exp(-x/2)/np.sqrt(2*np.pi*x)


def demo():
    x = generate(np.random.default_rng(1203).normal(size=128), [.45, -.2])
    p = np.zeros(2)
    start = objective(x, p)[0]
    for _ in range(300):
        p -= .08*objective(x, p)[1]
    return {'initial_nll': start, 'final_nll': objective(x, p)[0], 'fit': p.tolist(),
            'analytic_mle': maximum_likelihood(x).tolist(),
            'density_at_0': float(np.exp(log_density([0], p))[0]),
            'square_density_at_1': float(square_density([1])[0])}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2))

A gradient result you can check without trusting the gradient

The seed-1203 experiment generates 128 observations using μ=.45 and ρ=−.2. Starting from zero, 300 gradient steps with learning rate .08 lower average NLL from 1.57343794055 to 1.46442513250. The fitted values, μ=.342378217896 and ρ=−.242637329241, match the sample’s analytic MLE. They need not equal the generating parameters: this is one finite sample.

The accompanying checks compare every parameter gradient with centered finite differences, integrate the density over [−12,12] in data space and compare that mass with a Gaussian CDF calculation. They also differentiate the CDF numerically. These checks test separate routes to the same probability; merely verifying that a function inverts itself would not establish a correct density formula.

For a generating affine map with A=diag(−2,.5), |det A|=1 despite the orientation reversal. With A=diag(2,3), density at the origin is divided by six. Predict those changes before running the helper.

Tractable density leaves modeling choices open

The example has only two parameters and cannot fit arbitrary multimodal data. In higher dimensions, easy inversion, expressive transformations and cheap Jacobians impose competing architectural demands. A continuous bijection also preserves connectedness of support: mapping a fully supported Gaussian through such a map cannot produce truly disconnected support, although very low-density bridges can approximate separation.

Discrete pixels are not continuous observations with infinitesimal volume. Dequantization and preprocessing require their own probability accounting; this program implements neither and reports no image bits-per-dimension score. Likewise, comparing log densities across differently scaled measurement units without the associated Jacobian is misleading.

The 2015 paper uses flows inside variational inference, while Real NVP uses a tractable density model. A model can serve either role when its computational properties fit the objective. Our calculation covers finite smooth transformations; it does not implement continuous-time flows or reproduce either paper’s benchmark.

Four ways to catch a density mistake

  1. Volume. If X=3Z in one dimension, what is pX(0)? Answer: pZ(0)/3. A threefold interval expansion preserves its probability by dividing density by three; multiplying would give total mass nine rather than one.
  2. Hand calculation. For μ=ρ=0 in the sinh flow, find pX(0) and its generating Jacobian at z=0. Answer: sinh′(0)=cosh(0)=1, so pX(0)=1/√(2π)≈.39894228. Away from zero the Jacobian changes, so the entire density is not Gaussian.
  3. Counterexample. Why is φ(√x)/(2√x) wrong as the full density of Z²? Answer: It includes only positive z. Negative z produces the same x and contributes equally. Adding both gives .241970724519 at x=1, twice the single-branch result.
  4. Method choice. An optimizer finds a lower training NLL but a higher held-out NLL. Does that disprove the change-of-variable formula? Answer: No. It may reveal overfitting or an unsuitable model. Check the formula with independent mass/gradient tests, and judge generalization on held-out data. See the concrete result in the Real NVP article.

Reading the sources

Read the finite-flow construction in Rezende and Mohamed, then the coupling sections of Real NVP. The source reading covers those methods, not full benchmark replication. The example and counterexamples here are original teaching calculations.

Make a prediction, then check

For X=3Z, how does density at zero change?

Choose one answer

Learning objectives

  • Track density under an invertible map.
  • Derive likelihood gradients and an analytic check.
  • Handle negative determinants and multiple preimages.
  • Separate likelihood computation from model quality.

Prerequisites & connections

Explore related knowledge →

References

  1. Variational Inference with Normalizing Flows
    Danilo Jimenez Rezende; Shakir Mohamed · 2015
  2. Density estimation using Real NVP (v3)
    Laurent Dinh; Jascha Sohl-Dickstein; Samy Bengio · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read finite-flow construction and Real NVP change-of-variable sections. Eight paired equations and four explained exercises; original sinh density, both gradients, analytic sample MLE, independent CDF/quadrature and two-preimage counterexample. No continuous-flow or image benchmark reproduction.

  • Checked two parameter gradients, analytic MLE, independent CDF derivative and data-space quadrature, determinant sign/volume and folded-square density. Degenerate variance and numerical bounds stated.
  • Four SVG variants bind each actual bilingual program. Group passed14 numerical/geometry checks and18 responsive cases at390/768/1536 with four fallback fonts; six final representative screenshots actually viewed. Coupling-axis and title corrections and explicit style difference plot preserve original evidence. Full article acceptance is separate.

Source locations checked:

  • Variational Inference with Normalizing Flows · Read Section3 and3.1, Equations5–8; inspected PDF pages3–4. ICML2015, PMLR37:1530–1538. Finite bijective flows and variational use; no continuous-flow or benchmark replication.
  • Density estimation using Real NVP (v3) · Read selected Sections3.1–3.5: encoding direction, coupling, inverse, alternating masks and composition; inspected PDF page4. First2016-05-27; v3 dated2017-02-27, ICLR2017. No image preprocessing or benchmark review.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.