Skip to content
USFlowsPublic

Repository files navigation

CJD-Flows: Constant-Jacobian-Determinant Flows

CJD-Flows is a PyTorch library of normalizing flows whose Jacobian determinant is constant: log|det J_f(x)| does not depend on x. We call this model class uniformly scaling flows (US flows).

A constant determinant gives three things:

  • Exact, cheap likelihoods. log p(x) = log p_Z(f(x)) + C, where C is a single learnable scalar.
  • Density level-set preservation. Data-space density level sets are exactly the pre-images of latent level sets. With a radial base whose profile decreases with the radius, the latent norm ranks inputs by density, which gives faithful anomaly scores and verifiable density constraints.
  • Constant volume change. Every region of the data space is stretched by the same factor, a single learnable scalar. (This does not bound the conditioning of the flow: an additive coupling can still be an ill-conditioned shear.)

The library's main ingredient is the learnable radial base distribution of VeriFlow, first presented at AISoLA 2023 (Abu Zaid, Diekmann, Neider): an Lp-radial base whose 1-D norm distribution is learned jointly with the flow. A uniformly scaling flow changes the density values of its base only by one global factor (its constant Jacobian determinant), so with a fixed base its expressivity is limited (Draxler et al., ICML 2024, prove that volume-preserving flows with a fixed base are not universal). The learnable norm distribution removes exactly this limitation while keeping the latent level-set geometry intact.

PyTorch ONNX Docs

Documentation: https://usflows.github.io/cjd-flows/ (API reference and tutorials).

Installation

pip install cjd-flows                 # core: torch + numpy only
pip install "cjd-flows[eval,onnx]"    # + scipy/sklearn/matplotlib, ONNX export
pip install "cjd-flows[legacy]"       # + the pyro-based 0.9 API

For development (uses uv):

uv sync                      # dev environment incl. pytest/ruff
uv run pytest -m "not slow"

Quickstart

import torch
from cjd_flows import USFlow, fit
from cjd_flows.data.toy import make_toy

x = make_toy("two_moons", 20_000)
flow = USFlow((2,), blocks=8, base="ggmix")      # learnable radial base (generalized-gamma mixture)
fit(flow, x, epochs=30, lr=1e-3, ema_decay=0.999)

flow.log_prob(x[:5])          # exact log-density
flow.sample((1000,))          # samples
flow.log_abs_det()            # THE Jacobian log-determinant -- one scalar for all inputs

Images use the same builder (ConvNet conditioners by default):

flow = USFlow((1, 28, 28), blocks=8, hidden=(128, 128), base="ggmix")

and a verification-friendly preset gives piecewise-affine flows with an L1-radial base whose density level sets are polytopes:

from cjd_flows import VeriFlow
flow = VeriFlow((1, 10, 10))           # ReLU conditioners, adjoint LU blocks, monotone L1 base
assert flow.is_piecewise_affine()

Saving and loading

Flows built with USFlow / VeriFlow remember their builder arguments, so a saved file is enough to rebuild them:

from cjd_flows import load, save

save(flow, "flow.pt", metadata={"epochs": 30})
flow = load("flow.pt")                   # rebuilt from the stored configuration, eval mode

The file holds tensors, strings and numbers only and is read with torch.load(..., weights_only=True). Flows with a custom conditioner factory or your own architecture are loaded into a model you construct: load(path, model=my_flow). Register your own builder functions with cjd_flows.io.register_builder to make them rebuildable as well.

Core concepts

Concept API
Bijection contract Bijection.forward(x, context) -> z (data → latent), .inverse(z, context), .log_abs_det() returns a 0-dim tensor that is constant in x
Composition Chain(*bijections), b.inv
Flow Flow(bijection, base): log_prob, sample, rsample, transform, generate, log_abs_det
Training cjd_flows.fit(...): AdamW, warmup + cosine, EMA, validation and early stopping, bf16, noise augmentation and soft training
Testing cjd_flows.testing.check_bijection(layer, x): inverse, log-det vs autograd, constancy and gradients for your own layers
Save / load cjd_flows.save(flow, path), cjd_flows.load(path): weights plus the builder configuration; see below

Building blocks (cjd_flows.bijections)

Block Determinant Piecewise affine* Notes
SplitAdditiveCoupling 1 ✓ NICE/Jet-style split (channel, checkerboard, row/col, random)
MaskedAdditiveCoupling 1 ✓ Masked formulation of the original USFlows
GINCoupling 1 ✗ Affine coupling with zero-sum, bounded log-scale (Sorrenson et al. 2020)
ShiftAutoregressive 1 ✓ MADE shifts: more expressive than coupling; inverse is sequential
MaskedConvAutoregressive 1 ✓ PixelCNN-style shift layer (experimental)
TransformerAutoregressive 1 ✗ Causal transformer over tokens (TarFlow-style); shift or zero-sum scale + shift; KV-cached inverse
LULinear free / 1 (unit_det=True) ✓ One-star (1×1) channel mixing; log-normal prior on the diagonal
HouseholderLinear, OrthogonalLinear (Cayley / exp) ±1 ✓ Isometric mixing, condition number 1
ActNorm free / 1 (zero_sum=True) ✓ Data-dependent initialization
GlobalScale s^D ✓ The single "uniform scaling" parameter
Shift 1 ✓ Per-coordinate bias, initialized to centre the latents of the first batch
Squeeze, HaarWavelet, Patchify, Permutation ±1 ✓ Reshapes and orthonormal transforms

*Given piecewise-affine (ReLU) conditioners. merge_linear collapses consecutive linear layers for export.

Conditioners (cjd_flows.conditioners) are MLP, ConvNet (1–3D, optionally gated), MADE and JetConditioner (ViT with adaLN-zero context). All of them zero-initialize their output, so every coupling starts as the identity. They optionally use spectral normalization. For MLP and ungated ConvNet conditioners without normalization layers, lipschitz_upper_bound gives an upper bound L on the conditioner's Lipschitz constant (evaluation mode), and hence bi-Lipschitz bounds 1 + L for additive couplings; MADE and JetConditioner are not supported.

Base distributions (cjd_flows.radial)

An Lp-radial base is p(z) = p_R(‖z‖_p) / (d V_p ‖z‖_p^{d-1}), valid for any p > 0, with a learnable norm distribution p_R:

Norm distribution Radial profile Notes
GeneralizedGamma(Mixture) monotone iff a ≤ d (monotone=True ties a = d) contains Gamma, Weibull, Chi and the p-generalized normal
KhinchineNorm always monotone R = C·U^{1/d}: every radially decreasing density is a mixture of uniform balls
MonotoneProfileNorm always monotone −log h is a learnable increasing function
SplineNorm flexible rational-quadratic spline on the standardized log-radius
StudentTNorm monotone heavy tails
LogNormalMixture never monotone ("shell") kept for compatibility

Because the determinant is constant, the flow maps the modes of the base one to one onto the modes of the data density, so their number is set by the base. A single-centre radial base has its maxima at the centre (decreasing profile) or on a shell around it; RadialMixture places several radial components at independently located, learnable centres.

cjd_flows.radial.levelsets computes the latent level sets that verification and calibrated anomaly scores need. For monotone profiles the level sets are exactly norm balls; only their radii and masses are computed numerically (udl_radius, density_threshold_radius, hdr_pvalue). The accuracy depends on the norm distribution: the generalized-gamma family has an analytic CDF (quantiles by bisection), while KhinchineNorm and MonotoneProfileNorm use quadrature or tabulated CDFs on a grid (KhinchineNorm: about 1e-5 in log p with the default grid). For non-monotone ("shell") profiles, udl_intervals and hdr_pvalue classify a log-radius grid (65,536 cells by default) and can miss narrow shells or threshold crossings inside a cell. For certified verification, use a monotone profile and account for the numerical error of the radius, or prefer a norm law with an analytic CDF.

Why monotone profiles matter. Upper density level sets are norm balls (polytopes for p = 1 and p = ∞) only if the radial profile is decreasing. LogNormal norm distributions, for example, produce ring-shaped level sets. By rearrangement theory, monotone profiles lose no expressivity in the approximation sense.

Latent-space alignment

Uniformly scaling flows preserve density level sets: {x : p(x) ≥ t} = f⁻¹({z : p_Z(z) ≥ t / |det J_f|}), i.e. only the threshold is rescaled by the global volume factor. For a radial base the latent level sets are norm spheres, and the upper level sets are norm balls when the radial profile decreases. The 2D GMM example below colours latent representations by the data density.

US flow Non-US flow
US Non-US

With a radially decreasing base, the density of a US flow decreases monotonically with the latent norm (left). For a non-US flow, high-density regions are skewed against the latent geometry (right).

Evaluation suite

cjd_flows.evaluation.RadialFlowEvaluator (needs the eval extra) checks how well the latents of a trained flow match the radial structure of its base:

  • norm-distribution diagnostics (KS, Wasserstein, PP/QQ/KDE),
  • radiality diagnostics (sign symmetry and simplex-uniformity tests),
  • calibration-oriented latent-space analysis,
  • fine-grained mismatch diagnostics that help distinguish over- vs. under-approximation of density level sets.
from cjd_flows.evaluation import RadialFlowEvaluator

ev = RadialFlowEvaluator(flow, x_test)   # p, norm law and centre are read from the base
ev.ks_norm_statistic()                   # latent norms vs. the base norm distribution
ev.pp_plot_norms()
ev.test_l1_radial_symmetry()             # L1 bases: sign symmetry + simplex uniformity

It works with v1 flows (radial or Gaussian base) and with the 0.9 flows.

Overview of the evaluation suite

Applications

  • Density estimation with exact likelihoods: fit, evaluate_nll, bits/dim utilities in cjd_flows.data.preprocess. Affine preprocessing keeps the constant determinant; logit preprocessing does not.
  • Anomaly / OOD detection: cjd_flows.scores.anomaly_scores returns NLL, latent norm, typicality −log p_R(‖z‖) and the HDR p-value, together with AUROC, AUPR and FPR@95 metrics. Uniformly scaling flows for one-class classification are studied in Abu Zaid et al. (2025), arXiv:2510.09452.
  • Neural network verification (VeriFlow): train a piecewise-affine US flow as a proxy density, take a latent upper density level set, which is a norm ball, and verify properties over its image. cjd_flows.export.to_onnx exports log_prob / forward / inverse graphs.

Benchmarks

benchmarks/ contains the scripts used to evaluate the library: a CPU density suite (benchmarks/density/run.py: toy 2-D data, the asymmetric GMM of the USF paper and the MAF tabular suite) and a CIFAR-10 study (benchmarks/cifar/). Run outputs go to benchmarks/runs/; benchmarks/report.py aggregates them into Markdown tables. The toy and GMM suites need no extras; the MAF tabular suite needs the [tabular] extra (pandas, h5py) for the first preprocessing of GAS, HEPMASS and BSDS300. The CIFAR study needs Pillow for the sample grids ([vision] or [eval] extra) and logs to TensorBoard if tensorboard is installed.

Legacy API

The pyro-based API of v0.9 (cjd_flows.flows.USFlow, cjd_flows.transforms, cjd_flows.distributions) is still available with the [legacy] extra, and its known bugs are fixed. New code should use the v1 API above.

The YAML/Ray experiment framework of v0.9 (cjd_flows.explib, scripts/, experiments/) was removed in 1.0. Experiments for papers live in their own repositories; the last state of the framework is tagged archive/explib-final.

Citation

If you use this library, please cite the VeriFlow paper:

Zaid, F. A., Neider, D., and Yalciner, M. (2026). VeriFlow: Modeling Distributions for Neural Network Verification. Proceedings of the AAAI Conference on Artificial Intelligence, 40(33), 28050-28058. https://doi.org/10.1609/aaai.v40i33.40030

For uniformly scaling flows in anomaly detection and one-class classification, please also cite:

Abu Zaid, F., Katzke, T., Müller, E., and Neider, D. (2025). On Uniformly Scaling Flows: A Density-Aligned Approach to Deep One-Class Classification. arXiv:2510.09452. https://arxiv.org/abs/2510.09452

GitHub citation support and downloadable formats:

BibTeX
@article{Zaid_Neider_Yalciner_2026,
  title   = {VeriFlow: Modeling Distributions for Neural Network Verification},
  author  = {Zaid, Faried Abu and Neider, Daniel and Yal{\c{c}}iner, Mustafa},
  journal = {Proceedings of the AAAI Conference on Artificial Intelligence},
  volume  = {40},
  number  = {33},
  pages   = {28050--28058},
  year    = {2026},
  month   = mar,
  doi     = {10.1609/aaai.v40i33.40030},
  url     = {https://ojs.aaai.org/index.php/AAAI/article/view/40030}
}

@misc{AbuZaid_Katzke_Mueller_Neider_2025,
  title         = {On Uniformly Scaling Flows: A Density-Aligned Approach to Deep One-Class Classification},
  author        = {Abu Zaid, Faried and Katzke, Tim and M{\"u}ller, Emmanuel and Neider, Daniel},
  year          = {2025},
  eprint        = {2510.09452},
  archivePrefix = {arXiv},
  url           = {https://arxiv.org/abs/2510.09452}
}

References

  • Abu Zaid, Diekmann, Neider (2023). Distribution-aware neuro-symbolic verification. AISoLA 2023, LNCS, pp. 445–447.
  • Abu Zaid, Neider, Yalciner (2026). VeriFlow: Modeling Distributions for Neural Network Verification. AAAI.
  • Abu Zaid, Katzke, Müller, Neider (2025). On Uniformly Scaling Flows: A Density-Aligned Approach to Deep One-Class Classification. arXiv:2510.09452.
  • Draxler, Wahl, Schnörr, Köthe (2024). On the Universality of Volume-Preserving and Coupling-Based Normalizing Flows. ICML.
  • Dinh, Krueger, Bengio (2015). NICE: Non-linear Independent Components Estimation.
  • Sorrenson, Rother, Köthe (2020). Disentanglement by Nonlinear ICA with General Incompressible-flow Networks (GIN). ICLR.
  • Kolesnikov, Susano Pinto, Tschannen (2024). Jet: A Modern Transformer-Based Normalizing Flow.
  • Zhai et al. (2025). Normalizing Flows are Capable Generative Models (TarFlow). ICML.
  • Kingma & Dhariwal (2018). Glow. NeurIPS. Papamakarios et al. (2017). MAF. NeurIPS.

Acknowledgment

Bavarian AI Act Accelerator

The Bavarian AI Act Accelerator is a two-year project funded by the Bavarian State Ministry of Digital Affairs to support SMEs, start-ups, and the public sector in Bavaria in complying with the EU AI Act. Under the leadership of the appliedAI Institute for Europe and in collaboration with Ludwig Maximilian University, the Technical University of Munich, and the Technical University of Nuremberg, training, resources, and events are being offered. The project objectives include reducing compliance costs, shortening the time to compliance, and strengthening AI innovation. To achieve these objectives, the project is divided into five work packages: project management, research, education, tools and infrastructure, and community.

Releases

Packages

Used by

Contributors

Languages