cjd_flows.data

Datasets and preprocessing for CJD flows.

  • preprocess – dequantization, constant-det scalings, standardization, bits/dim conversion.

  • toy – 2-D toy datasets and an n-D asymmetric GMM.

  • tabular – MAF benchmarks (POWER, GAS, HEPMASS, MINIBOONE, BSDS300).

  • images – MNIST, Fashion-MNIST, CIFAR-10.

Downloads go to $CJD_FLOWS_DATA or ~/.cache/cjd_flows.

The main functions and classes are also importable from cjd_flows.data.

Preprocessing

Data preprocessing with tracked log-determinants.

CJD flows have a constant Jacobian determinant. To report likelihoods in the original data space (e.g. bits/dim on 8-bit images) the change of variables of the preprocessing must be accounted for. All preprocessing steps here record log|det ∂y/∂x| per sample:

  • affine steps (AffineScale, ToUnitInterval, ToSymmetric, Standardize) have a constant log-det and therefore preserve the CJD property of the overall model x -> preprocessing -> flow;

  • Logit is not constant-det (constant_det = False): composing it with a CJD flow yields a model whose density level sets are no longer pre-images of base level sets. Use it only if you know what you are doing.

Bits/dim convention (bits_per_dim()): 8-bit data x ∈ {0,…,255}^D is dequantized to x̃ = x + u ∈ [0, 256)^D with u ~ U[0,1)^D. The model sees y = g(x̃) and

bpd = (−log p_model(y) − log|det ∂y/∂x̃|) / (D ln 2),

which is the negative (variational lower bound of the) discrete log-likelihood in bits per dimension.

class cjd_flows.data.preprocess.Preprocessing[source]

Bases: object

Base class of a (fixed, non-learnable) preprocessing map y = g(x).

constant_det

whether log|det ∂g/∂x| is independent of x.

Type:

bool

log_abs_det(x)[source]

Per-sample log|det ∂g/∂x| evaluated at the input batch x (shape (B,)).

Return type:

Tensor

Parameters:

x (Tensor)

constant_log_abs_det(event_shape)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

Parameters:

event_shape (int | Sequence[int])

class cjd_flows.data.preprocess.UniformDequantize[source]

Bases: Preprocessing

Adds fresh uniform noise u ~ U[0,1) to integer data.

x ∈ {0, …, n_bins−1} becomes x̃ = x + u ∈ [0, n_bins). The map is stochastic but volume preserving (log-det 0); the inverse is floor.

__init__(n_bins=256)[source]
Parameters:

n_bins (int)

constant_log_abs_det(event_shape)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

class cjd_flows.data.preprocess.AffineScale[source]

Bases: Preprocessing

y = scale · x + shift with a scalar (or broadcastable) scale.

__init__(scale, shift=0.0)[source]
Parameters:
constant_log_abs_det(event_shape)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

class cjd_flows.data.preprocess.ToUnitInterval[source]

Bases: AffineScale

Maps [0, n_bins) to [0, 1): y = x / n_bins (log-det −D log n_bins).

__init__(n_bins=256)[source]
Parameters:

n_bins (int)

class cjd_flows.data.preprocess.ToSymmetric[source]

Bases: AffineScale

Maps [0, n_bins) to [−1, 1): y = 2x / n_bins − 1 (log-det D log(2/n_bins)).

__init__(n_bins=256)[source]
Parameters:

n_bins (int)

cjd_flows.data.preprocess.to_unit_interval(x, n_bins=256)[source]

x / n_bins; per-sample log-det −D log n_bins.

Return type:

Tensor

Parameters:
cjd_flows.data.preprocess.to_symmetric(x, n_bins=256)[source]

2x / n_bins − 1; per-sample log-det D (log 2 − log n_bins).

Return type:

Tensor

Parameters:
class cjd_flows.data.preprocess.Logit[source]

Bases: Preprocessing

RealNVP-style logit transform y = logit(α + (1−2α) u) for u ∈ [0, 1].

Warning

NOT constant-det (constant_det = False). Combined with a CJD flow the overall model loses the density level-set preservation property.

__init__(alpha=0.05)[source]
Parameters:

alpha (float)

log_abs_det(u)[source]

Per-sample log|det ∂g/∂x| evaluated at the input batch x (shape (B,)).

Return type:

Tensor

Parameters:

u (Tensor)

constant_log_abs_det(event_shape)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

class cjd_flows.data.preprocess.Standardize[source]

Bases: Preprocessing

Feature-wise standardization y = (x − mean) / std (constant log-det −Σ log std).

Parameters:
  • mean (Optional[Tensor]) – statistics over the event shape; use fit() to estimate them.

  • std (Optional[Tensor]) – statistics over the event shape; use fit() to estimate them.

  • eps (float) – lower bound for std.

__init__(mean=None, std=None, eps=1e-8)[source]
Parameters:
constant_log_abs_det(event_shape=None)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

class cjd_flows.data.preprocess.Compose[source]

Bases: Preprocessing

Sequential composition; log-dets add up.

__init__(*steps)[source]
Parameters:

steps (Preprocessing)

property constant_det: bool

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

log_abs_det(x)[source]

Per-sample log|det ∂g/∂x| evaluated at the input batch x (shape (B,)).

Return type:

Tensor

Parameters:

x (Tensor)

constant_log_abs_det(event_shape)[source]

Per-sample log-det for constant-det maps (raises otherwise).

Return type:

float

cjd_flows.data.preprocess.bits_per_dim(log_prob, dim, preprocessing_log_det=None, n_bins=256)[source]

Converts model log-likelihoods to bits/dim in the dequantized data space.

Parameters:
  • log_prob (Union[Tensor, float]) – log p_model(y) in model space (nats), per sample or averaged.

  • dim (int) – number of dimensions D.

  • preprocessing_log_det (Union[Tensor, float, None]) – log|det ∂y/∂x̃| of the preprocessing from the dequantized raw data x̃ ∈ [0, n_bins)^D to model space y (per sample). None means the model data is x̃ / n_bins ∈ [0,1)^D, i.e. −D log n_bins.

  • n_bins (int) – number of quantization levels (only used when preprocessing_log_det is None).

Return type:

Union[Tensor, float]

Returns:

(−log p(y) − log|det ∂y/∂x̃|) / (D ln 2). Equivalently, if L denotes the log-det relative to the [0, 1) scaling, (−log p(y) − L + D log n_bins) / (D ln 2).

Example

The uniform density on [0, 256)^D (identity preprocessing) has log p = −D log 256 and gives exactly 8 bits/dim.

Toy datasets

Toy datasets (2-D benchmarks and an n-D asymmetric Gaussian mixture).

All samplers return float32 tensors of shape (n, d) and accept a seed (or a torch.Generator) for reproducibility. The 2-D generators follow the widely used FFJORD / “inf_train_gen” definitions.

Exact log densities are available for eight_gaussians(), checkerboard() and GaussianMixture (e.g. asymmetric_gmm()) via toy_log_prob() / GaussianMixture.log_prob.

cjd_flows.data.toy.two_moons(n, noise=0.1, seed=None)[source]

Two interleaving half circles (sklearn make_moons), scaled by 2 and centred.

Return type:

Tensor

Parameters:
cjd_flows.data.toy.circles(n, factor=0.5, noise=0.08, seed=None)[source]

Two concentric circles (sklearn make_circles) scaled by 3.

Return type:

Tensor

Parameters:
cjd_flows.data.toy.rings(n, noise=0.08, seed=None)[source]

Four concentric rings with radii 3, 2.25, 1.5, 0.75.

Return type:

Tensor

Parameters:
cjd_flows.data.toy.eight_gaussians(n, seed=None)[source]

Mixture of 8 isotropic Gaussians on a circle (radius 4/1.414, std 0.5/1.414).

Return type:

Tensor

Parameters:
cjd_flows.data.toy.eight_gaussians_mixture()[source]

The exact density of eight_gaussians() as a GaussianMixture.

Return type:

GaussianMixture

cjd_flows.data.toy.checkerboard(n, seed=None)[source]

Uniform density on 8 squares of a 4x4 checkerboard on [-4, 4]^2 (density 1/32).

Return type:

Tensor

Parameters:
cjd_flows.data.toy.checkerboard_log_prob(x)[source]

Exact log density of checkerboard() (-log 32 on the support, -inf outside).

Return type:

Tensor

Parameters:

x (Tensor)

cjd_flows.data.toy.pinwheel(n, num_classes=5, radial_std=0.3, tangential_std=0.1, rate=0.25, seed=None)[source]

Pinwheel with num_classes spiralling arms.

Return type:

Tensor

Parameters:
cjd_flows.data.toy.swiss_roll(n, noise=1.0, seed=None)[source]

2-D swiss roll (sklearn make_swiss_roll projected to (x, z), scaled by 1/5).

Return type:

Tensor

Parameters:
cjd_flows.data.toy.spirals(n, noise=0.1, seed=None)[source]

Two interleaved spirals.

Return type:

Tensor

Parameters:
class cjd_flows.data.toy.GaussianMixture[source]

Bases: Module

Gaussian mixture with diagonal covariances and exact log_prob / sample.

Parameters:
  • means (Tensor) – (K, d) component means.

  • variances (Tensor) – (K, d) diagonal covariances.

  • weights (Optional[Tensor]) – (K,) mixture weights (uniform if None).

__init__(means, variances, weights=None)[source]

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Parameters:
log_prob(x)[source]

Exact log density of shape (B,) (computed in float64, returned in x.dtype).

Return type:

Tensor

Parameters:

x (Tensor)

forward(x)[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Return type:

Tensor

Parameters:

x (Tensor)

cjd_flows.data.toy.asymmetric_gmm(d, high=5.0, low=0.5)[source]

Asymmetric two-component GMM of the USF paper.

Means +1_d and −1_d, equal weights, Σ1 = I and Σ2 = diag(high, …, high, low, …, low) (first d // 2 entries high).

Return type:

GaussianMixture

Parameters:
cjd_flows.data.toy.asymmetric_gmm_data(n, d=2, seed=None)[source]

Samples from asymmetric_gmm().

Return type:

Tensor

Parameters:
cjd_flows.data.toy.make_toy(name, n, seed=None, **kwargs)[source]

Samples n points of the toy dataset name (see TOY_DATASETS).

Return type:

Tensor

Parameters:
cjd_flows.data.toy.toy_log_prob(name, x, **kwargs)[source]

Exact log density of a toy dataset (where available).

Supported: eight_gaussians, checkerboard, asymmetric_gmm (pass d implicitly via x.shape[1]).

Return type:

Tensor

Parameters:

Tabular benchmarks

MAF tabular density-estimation benchmarks (POWER, GAS, HEPMASS, MINIBOONE, BSDS300).

The raw data is the archive of Papamakarios et al. (2017), “Masked Autoregressive Flow for Density Estimation” (zenodo record 1161203, data.tar.gz). The preprocessing replicates datasets/*.py of github.com/gpapamak/maf exactly (same random seed, column removal, noise, normalization and splits), so numbers are comparable with the literature.

Processed splits are cached as .npy files under <root>/maf/processed (root defaults to $CJD_FLOWS_DATA or ~/.cache/cjd_flows).

Expected shapes (train, val, test):

name

D

train

val

test

power

6

1,659,917

184,435

204,928

gas

8

852,174

94,685

105,206

hepmass

21

315,123

35,013

174,987

miniboone

43

29,556

3,284

3,648

bsds300

63

1,000,000

50,000

250,000

Optional dependencies (pip install "cjd-flows[tabular]"): pandas (gas, hepmass) and h5py (bsds300), needed only for the first preprocessing; cached splits load without them.

cjd_flows.data.tabular.load_tabular(name, root=None, download=True, dtype=torch.float32)[source]

Loads a MAF tabular benchmark as (train, val, test) tensors.

Parameters:
  • name (str) – one of power, gas, hepmass, miniboone, bsds300.

  • root (Union[str, PathLike, None]) – cache directory (default $CJD_FLOWS_DATA or ~/.cache/cjd_flows).

  • download (bool) – download the ~860 MB archive if necessary.

  • dtype (dtype) – dtype of the returned tensors.

Return type:

Tuple[Tensor, Tensor, Tensor]

Returns:

Three tensors of shape (N_split, D).

Image datasets

Image datasets (MNIST, Fashion-MNIST, CIFAR-10) with on-the-fly dequantization.

The raw 8-bit images are kept as uint8 tensors; every access draws fresh uniform dequantization noise and applies a constant-det affine scaling:

  • scale="unit": y = (x + u) / 256          ∈ [0, 1)

  • scale="symmetric": y = 2 (x + u) / 256 − 1    ∈ [−1, 1)

dataset.preprocessing_log_det is the per-sample log|det ∂y/∂x̃| w.r.t. the dequantized raw data x̃ = x + u ∈ [0, 256)^D; use dataset.bits_per_dim(log_prob) to report bits/dim.

Data is loaded through torchvision if it is installed (backend="auto") and otherwise downloaded directly (MNIST/Fashion IDX files and the binary CIFAR-10 archive – no pickle involved).

cjd_flows.data.images.load_image_tensors(name, split='train', root=None, download=True, backend='auto')[source]

Raw uint8 images (N, C, H, W) and int64 labels (N,).

Return type:

Tuple[Tensor, Tensor]

Parameters:
class cjd_flows.data.images.DequantizedImageDataset[source]

Bases: Dataset

Dataset of 8-bit images returning (y, label) with fresh dequantization noise.

Parameters:
  • images (Tensor) – uint8 tensor (N, C, H, W).

  • labels (Tensor) – (N,) labels.

  • dequantize (bool) – add U[0,1) noise (otherwise x + 0.5 is used, the bin centre).

  • scale (str) – "unit" ([0,1)) or "symmetric" ([-1,1)).

  • flatten (bool) – return vectors (C·H·W,) instead of images.

event_shape, dim, preprocessing, preprocessing_log_det (per sample,
w.r.t. ``x̃ ∈ [0,256)^D``), n_bins.

Besides __getitem__ it provides a vectorized get_batch() (used by cjd_flows.train.fit()) and to() to keep the uint8 storage on the GPU.

__init__(images, labels, dequantize=True, scale='symmetric', flatten=False)[source]
Parameters:
to(device)[source]

Moves the uint8 storage to device (in place); returns self.

Return type:

DequantizedImageDataset

get_batch(idx)[source]

Vectorized access: (y, labels) for a batch of indices.

Return type:

Tuple[Tensor, Tensor]

Parameters:

idx (Tensor | Sequence[int])

bits_per_dim(log_prob)[source]

Bits/dim of model log-likelihoods (nats, model space) on this dataset.

Return type:

Union[Tensor, float]

Parameters:

log_prob (Tensor | float)

to_raw(y)[source]

Maps model-space data back to uint8 images (quantizing).

Return type:

Tensor

Parameters:

y (Tensor)

cjd_flows.data.images.load_images(name, root=None, classes=None, split='train', dequantize=True, scale='symmetric', flatten=False, download=True, backend='auto', exclude_classes=False)[source]

Loads MNIST / Fashion-MNIST / CIFAR-10 as a dequantized dataset.

Parameters:
  • name (str) – "mnist", "fashion_mnist" or "cifar10".

  • root (Union[str, PathLike, None]) – cache directory (default $CJD_FLOWS_DATA or ~/.cache/cjd_flows).

  • classes (Union[int, Sequence[int], None]) – keep only these labels (one-class / subset filter).

  • split (str) – "train" or "test".

  • dequantize (bool) – uniform dequantization (fresh noise on every access).

  • scale (str) – "symmetric" ([-1, 1)) or "unit" ([0, 1)).

  • flatten (bool) – return flat vectors.

  • download (bool) – download if missing.

  • backend (str) – "auto" (torchvision if installed), "torchvision" or "raw".

  • exclude_classes (bool) – if True keep all labels except classes (handy for the “rest” set in one-class protocols).

Return type:

DequantizedImageDataset

Returns:

A DequantizedImageDataset.