AI Wiki中文/EN

Real NVP: invertible coupling with a tractable density

Real NVP

Train twenty parameters, verify the Jacobian and keep an honest held-out failure.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Leave half unchanged so the other half can be recovered

Suppose a two-number measurement (u,v) is encoded as (u,2v+u²). Recovery is easy: copy u, subtract u² from the second number and divide by two. The nonlinear u² operation does not need an inverse because u is still available. This is the useful asymmetry of a coupling layer.

Real NVP, introduced by Dinh, Sohl-Dickstein and Bengio in a 2016 preprint and published at ICLR2017, stacks such transformations to model densities. NVP stands for non-volume preserving: scaling may change local volume, but the change is tractable. Read normalizing flows for the general density rule and gradient checking before inspecting the training code.

Affine coupling and numerical inversion remain correct while this fitted model worsens held-out likelihood.
Affine coupling and numerical inversion remain correct while this fitted model worsens held-out likelihood.

A complex conditioner inside a simple inverse

We follow the paper’s encoding direction: f maps observed x to latent z, which has a standard-normal base density. Split an input into copied coordinates xa and transformed coordinates xb. The conditioner produces scale logits s and shifts t from xa alone:

ya=xa,yb=xb⊙exp⁡(s(xa))+t(xa).y_a=x_a,\qquad y_b=x_b\odot\exp(s(x_a))+t(x_a).

Here the exponential and multiplication act elementwise. The partition sizes need not be equal. Since ya supplies the same conditioner input, inversion requires no solution of a nonlinear equation:

xa=ya,xb=(yb−t(ya))⊙exp⁡(−s(ya)).x_a=y_a,\qquad x_b=(y_b-t(y_a))\odot\exp(-s(y_a)).

Neither s nor t must be invertible. A neural network with dimensionality changes or noninvertible activations can be a conditioner while the whole coupling transformation remains invertible. The finite scale outputs must give nonzero finite scales in the numerical implementation.

The copied block has identity derivative and no dependence on xb. Thus the Jacobian is block triangular:

Df=(I0∗diag⁡(es(xa))),log⁡∣det⁡Df∣=∑jsj(xa).Df=\begin{pmatrix}I&0\\ *&\operatorname{diag}(e^{s(x_a)})\end{pmatrix},\qquad \log|\det Df|=\sum_j s_j(x_a).

The asterisk can be expensive or complicated, but it does not enter the determinant. This is the construction in Sections 3.2–3.3, not an approximation that discards important determinant terms.

Why the masks must change

One layer never changes its copied coordinates. Repeating the same partition would keep those coordinates unchanged throughout. Alternate the partition so a later layer can change what an earlier layer copied. The paper describes checkerboard and channel-wise partitions for images; our example alternates two scalar coordinates. It omits the paper’s multiscale image architecture.

For L encoding layers, each evaluated at its own input, the total log-determinant is a sum. With a D-dimensional standard Gaussian base, one observation contributes:

ℓ(x)=12∥f(x)∥2+D2log⁡(2π)−∑k=1Llog⁡∣det⁡Dfk∣.\ell(x)=\tfrac12\|f(x)\|^2+\tfrac D2\log(2\pi)-\sum_{k=1}^{L}\log|\det Df_k|.

The last sign is negative because this is negative log density in the encoding direction. Inversion reverses the layer order and negates each layer’s log-determinant. A permutation, if inserted, has absolute determinant one even when its determinant is negative.

Our original model has four layers and five parameters per layer. For copied coordinate u, let:

q=tanh⁡(au+b),s=.8q,t=du2+eu+f,v′=ves+t.q=\tanh(au+b),\qquad s=.8q,\qquad t=du^2+eu+f,\qquad v'=ve^s+t.

The letter f in this last polynomial is a scalar parameter, distinct from the complete encoding map f(x). The tanh bound keeps each scale between exp(−.8) and exp(.8); the shift can still produce large intermediate values. It does not bound the full Jacobian’s condition number.

To derive the training gradient, let gv′ be the derivative arriving from subsequent layers or the base density. For a batch mean over N observations, the direct negative-logdet contribution must also be included:

gt=gv′,gs=gv′ves−1N,gpre=.8(1−q2)gs.g_t=g_{v'},\qquad g_s=g_{v'}ve^s-\frac1N,\qquad g_{\rm pre}=.8(1-q^2)g_s.

The five parameter derivatives follow by summing over observations. The copied coordinate also receives indirect derivatives through both conditioners:

∇(a,b,d,e,f)L=(∑gpreu,∑gpre,∑gtu2,∑gtu,∑gt),guin=guout+agpre+(2du+e)gt,gv=gv′es.\nabla_{(a,b,d,e,f)}L=\left(\sum g_{\rm pre}u,\sum g_{\rm pre},\sum g_tu^2,\sum g_tu,\sum g_t\right),\quad g_u^{\rm in}=g_u^{\rm out}+a g_{\rm pre}+(2du+e)g_t,\quad g_v=g_{v'}e^s.

Omitting −1/N trains toward a small encoded norm without the compensating volume term. The result is no longer the intended maximum-likelihood objective.

Twenty parameters, a density and a training loop

Save as realnvp.py; use Python3.12 and NumPy1.26.4. A fixed teacher flow transforms Gaussian noise backward to create synthetic observations. The fitted model starts as the identity and uses explicit backpropagation and Adam, without a neural-library autograd engine.

For these fixed two-dimensional conditioners, N observations and L layers cost O(NL) time; storing the reverse-mode cache costs O(NL) space. Sampling uses the same number of conditioner evaluations in reverse order. For a larger network, include its actual evaluation and activation-storage cost; “easy determinant” does not mean the whole operation is free.

The maintained nflows implementation is a useful comparison, not the original author implementation. Its SimpleRealNVP uses alternating feature masks and omits multiscale processing. At the pinned commit, its default affine scale activation is sigmoid(raw+2)+.001. Our exp(.8tanh(…)) scale is an explicitly different teaching choice. No upstream source code is copied or executed.

"""Original 20-parameter 2D affine-coupling density model. f maps data to noise."""
import json
import numpy as np

TEACHER = np.array([[.35, -.1, .32, 0, .05], [-.1, .05, -.12, .1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])


def checked(x, p):
    x, p = np.asarray(x, float), np.asarray(p, float)
    if x.ndim != 2 or x.shape[1] != 2 or not 1 <= len(x) <= 2048 or not np.all(np.isfinite(x)) or np.max(np.abs(x)) > 16:
        raise ValueError('Expected 1..2048 finite 2D points of magnitude <= 16.')
    if p.shape != (4, 5) or not np.all(np.isfinite(p)) or np.max(np.abs(p)) > 3:
        raise ValueError('Expected finite 4x5 parameters of magnitude <= 3.')
    return x.copy(), p


def transform(x, p, inverse=False):
    h, p = checked(x, p)
    logdet = np.zeros(len(h))
    cache = []
    for layer in (range(3, -1, -1) if inverse else range(4)):
        axis, other = layer % 2, 1-layer % 2
        u, v = h[:, axis].copy(), h[:, other].copy()
        a, b, d, e, f = p[layer]
        q = np.tanh(a*u+b)
        s, t = .8*q, d*u*u+e*u+f
        h[:, other] = (v-t)*np.exp(-s) if inverse else v*np.exp(s)+t
        logdet += -s if inverse else s
        cache.append((layer, u, v, q, np.exp(s)))
        if not np.all(np.isfinite(h)) or np.max(np.abs(h)) > 1e6:
            raise ValueError('Intermediate result exceeds the teaching implementation range.')
    return h, logdet, cache


def objective(x, p):
    z, logdet, cache = transform(x, p)
    n = len(z)
    loss = np.mean(.5*np.sum(z*z, axis=1)+np.log(2*np.pi)-logdet)
    gradient = np.zeros((4, 5))
    upstream = z/n
    for layer, u, v, q, scale in reversed(cache):
        axis, other = layer % 2, 1-layer % 2
        a, _, d, e, _ = p[layer]
        gt = upstream[:, other].copy()
        gs = gt*v*scale-1/n
        gpre = gs*.8*(1-q*q)
        gradient[layer] = [gpre@u, gpre.sum(), gt@(u*u), gt@u, gt.sum()]
        upstream[:, axis] += gpre*a + gt*(2*d*u+e)
        upstream[:, other] = gt*scale
    return float(loss), gradient


def fit(x, steps=600):
    if not isinstance(steps, int) or not 0 <= steps <= 2000:
        raise ValueError('steps must be an integer in [0,2000].')
    p = np.zeros((4, 5))
    m, v = np.zeros_like(p), np.zeros_like(p)
    history = [objective(x, p)[0]]
    # Adam; no hidden gradient clipping, parameter clipping or validation selection.
    for step in range(1, steps+1):
        _, g = objective(x, p)
        m, v = .9*m+.1*g, .999*v+.001*g*g
        p -= .015*(m/(1-.9**step))/(np.sqrt(v/(1-.999**step))+1e-8)
        if step % 100 == 0:
            history.append(objective(x, p)[0])
    return p, history


def demo():
    rng = np.random.default_rng(1204)
    train = transform(rng.normal(size=(128, 2)), TEACHER, inverse=True)[0]
    heldout = transform(rng.normal(size=(512, 2)), TEACHER, inverse=True)[0]
    p, history = fit(train)
    encoded, ld, _ = transform(train, p)
    restored, ild, _ = transform(encoded, p, inverse=True)
    return {'training_nll': history, 'heldout_nll_initial': objective(heldout, np.zeros((4, 5)))[0],
            'heldout_nll_final': objective(heldout, p)[0],
            'roundtrip_error': float(np.max(np.abs(restored-train))),
            'logdet_cancel_error': float(np.max(np.abs(ld+ild))), 'parameters': p.tolist()}


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

The inverse works even when generalization gets worse

With seed1204, the teacher produces 128 training points followed by 512 independent held-out points. Adam uses learning rate .015 for 600 updates. Training average NLL decreases from 3.20210885926 to 2.81218893715. Held-out average NLL increases from 3.04091174072 to 3.11503133382: the fitted model is worse than the initial Gaussian baseline on this particular held-out sample.

This outcome is retained rather than removed by changing the seed. The held-out data does not choose parameters, step counts or hyperparameters here. It exposes the difference between fitting observations and learning a useful distribution. If it were used to choose an early-stopping point, it would become validation data; a separate final test would then be needed for an untouched evaluation.

Forward–inverse error is about 1.78×10⁻¹⁵ and forward/inverse logdet cancellation error about 5.55×10⁻¹⁶ on the training inputs. All twenty gradients match centered finite differences at a nonzero parameter vector. Another check builds the full two-by-two Jacobian numerically and compares its determinant with the accumulated logdet. These establish the small computation’s consistency, not good held-out likelihood.

Invertibility is not a quality certificate

Only one partition is transformed per layer; information must travel through alternating layers. Expressiveness depends on the conditioners, partition schedule and depth. Large shifts, extreme scales or long compositions can make inversion numerically inaccurate despite mathematical invertibility. This program rejects excessive intermediate magnitudes rather than silently clipping them and breaking the declared inverse.

The original image model includes additional structure absent here. These two-coordinate polynomials do not constitute a reproduction of its convolutional multiscale network, image preprocessing or benchmarks. They also do not justify comparing a continuous density score with a discrete image probability without the missing conversion.

Real NVP makes a useful tradeoff: a restrictive layer form provides a simple inverse and determinant, while composition supplies flexibility. The finite-flow framework explains the shared probability accounting; changing the conditioner or scale parameterization changes the model family and numerical behavior, not that accounting rule.

Predict the calculation before running it

  1. Hand inverse. For (u,v)→(u,2v+u²), encode (2,3), recover it, and find the determinant. Answer: The output is (2,10). Recovery gives (10−4)/2=3. The Jacobian is triangular with diagonal (1,2), so the determinant is two; the derivative of u² belongs to the off-diagonal entry.
  2. Missing term. What is lost if the gradient gs omits −1/N? Answer: The derivative of the negative log-determinant. Optimizing only the encoded Gaussian energy can favor compression without paying for its volume change, so it is not the stated likelihood objective.
  3. Boundary case. If all s values are zero, is the model necessarily the identity? Answer: No. Nonzero shifts still change observations. Each additive layer has determinant one, and so does their composition, but volume preservation does not imply pointwise identity.
  4. Evaluation. Which is proved by a round trip below 10⁻¹²: a correct inverse, a correct density, or good generalization? Answer: It supplies numerical evidence about the tested inverse. Density additionally needs a correct Jacobian and base distribution. Generalization needs held-out evaluation; this example passes inverse checks while its held-out NLL gets worse.

Reading the sources

The paper supplies the encoding convention and coupling construction; the fixed nflows files show a later library variant. Their scale parameterizations differ. The original NumPy model here is separately specified and does not reproduce image benchmarks.

Make a prediction, then check

Must the scale and shift networks themselves be invertible?

Choose one answer

Learning objectives

  • Derive coupling inversion without inverting its conditioner.
  • Calculate a triangular log-determinant.
  • Train all parameters with explicit gradients.
  • Evaluate invertibility and generalization separately.

Prerequisites & connections

Explore related knowledge →

References

  1. Density estimation using Real NVP (v3)
    Laurent Dinh; Jascha Sohl-Dickstein; Samy Bengio · 2017
  2. Variational Inference with Normalizing Flows
    Danilo Jimenez Rezende; Shakir Mohamed · 2015
  3. nflows SimpleRealNVP at 5d22344
    Conor Durkan; Artur Bekasov; Iain Murray; George Papamakarios and nflows contributors · 2024
  4. nflows affine coupling scale at 5d22344
    nflows contributors · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked Real NVP v3 coupling/inverse/masks and fixed later nflows variant. Seven paired equations and four explained exercises; original20-parameter 2D flow, full manual gradients, numerical Jacobian, inverse and retained held-out NLL failure. No original image architecture or benchmark reproduction.

  • Checked all20 gradients including direct negative-logdet derivative, full finite-difference Jacobian, inverse/logdet cancellation, alternating masks, additive case and batch averaging. Held-out NLL worsens in the retained deterministic experiment.
  • 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:

  • 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.
  • 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.
  • nflows SimpleRealNVP at 5d22344 · Read complete small file, README first45lines and full root MIT license; commit2024-12-27. Alternating feature masks without multiscale. Later-maintained library, not original-author code. Reference only.
  • nflows affine coupling scale at 5d22344 · Read lines210–250, default sigmoid(raw+2)+.001 scale and forward/inverse arithmetic; same2024-12-27 commit and root MIT license. No upstream execution or copying.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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