cjd_flows.bijections

Bijections with constant Jacobian determinant.

All classes below are also importable from cjd_flows.bijections.

Linear and elementwise layers

Channel-wise linear bijections (“one-star convolutions”).

Every layer in this module acts on the channel dimension (dim 1) and is shared across all spatial positions, i.e. for x of shape (B, C, *spatial)

y[:, :, s] = W @ x[:, :, s] + b for every spatial position s,

and for vector data (B, D) it is an ordinary dense affine layer (D is the channel dimension). This is a 1x1 convolution for images, but works for any number of spatial dimensions. The Jacobian determinant is constant:

log|det J| = n_spatial * log|det W|, n_spatial = prod(event_shape[1:]),

which is why all constructors take event_shape.

Implementation notes:
  • The forward (normalizing / training) direction never inverts a matrix: it is a single batched matmul baddbmm on a (B, C, N) view, which benchmarked fastest on GPU (forward + backward) compared to 1x1 convolution, F.linear on channels-last views and einsum.

  • Inverses use the cheap inverse of each parametrization (triangular solves, transposes, reversed reflections, …).

  • ChannelLinear.to_matrix() / ChannelLinear.as_dense() expose the affine map explicitly (e.g. for verifier export), and merge_linear() collapses consecutive channel-linear layers into one frozen AffineFromMatrix.

class cjd_flows.bijections.linear.ChannelLinear[source]

Bases: Bijection

Abstract channel-wise affine bijection y = W x + b (applied on dim 1).

Subclasses implement weight() and may override bias(), inverse_weight(), log_abs_det_weight(), forward() and inverse() with cheaper parametrization-specific versions.

Parameters:

event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

event_shape

the event shape.

channels

C (the matrix size).

n_spatial

prod(event_shape[1:]) (1 for vectors).

__init__(event_shape)[source]

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

Parameters:

event_shape (int | Sequence[int] | Size)

weight()[source]

The (C, C) matrix W.

Return type:

Tensor

bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

log_abs_det()[source]

Constant log|det J_f| of the forward (normalizing) map as a 0-dim tensor.

Return type:

Tensor

forward(x, context=None)[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:
to_matrix()[source]

Returns (W, b) of the channel map (b is zeros if there is no bias).

Return type:

Tuple[Tensor, Tensor]

as_dense()[source]

Returns (A, c) of the full affine map on flattened events.

A has shape (D, D) with D = prod(event_shape) such that forward(x).flatten(1) == x.flatten(1) @ A.T + c. Since events are flattened channel-major, A = kron(W, I_{n_spatial}).

Return type:

Tuple[Tensor, Tensor]

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.LULinear[source]

Bases: ChannelLinear

Channel-wise LU-parametrized linear layer W = P L U with bias.

P is a fixed permutation (buffer), L is unit lower triangular and U is upper triangular with diagonal sign * exp(log_s) (sign is a fixed ±1 buffer), so log|det W| = sum(log_s) and the layer is always invertible. The forward direction is one matmul with W; the inverse uses two triangular solves (applied either directly to the data when there are fewer vectors than channels, or to I to form W^{-1} followed by one matmul otherwise – whichever is faster). torch.inverse is never used.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • unit_det (bool) – if True the log-diagonal is projected to zero sum (log_s - mean(log_s)), i.e. W ∈ SL(C) up to sign: |det W| = 1 while anisotropic scaling remains possible (GIN trick).

  • identity_init (bool) – if True initialize L = U = I (so W = P). Otherwise W is initialized as a random orthogonal matrix (Glow-style).

  • permute (bool) – use a random fixed channel permutation P; otherwise P = I (with identity_init=False the orthogonal init is then P^T Q).

  • prior_scale (Optional[float]) – scale σ of the bilateral log-normal prior used by log_prior() (None disables the prior).

  • max_log_scale (Optional[float]) – bound on each |log_s| (None disables clamping).

  • soft_clamp (bool) – use a smooth tanh clamp instead of a hard clamp.

  • bias (bool) – whether to learn a bias.

__init__(event_shape, unit_det=False, identity_init=True, permute=True, prior_scale=None, max_log_scale=8.0, soft_clamp=True, bias=True)[source]

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

Parameters:
log_diag()[source]

Effective log|u_ii| after clamping and (optional) zero-sum projection.

Return type:

Tensor

weight()[source]

The (C, C) matrix W.

Return type:

Tensor

bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

prior_std()[source]

Per-entry std σ0 = prior_scale / (n_spatial * sqrt(C)) of log|u_ii|.

Return type:

Optional[float]

log_prior(include_constants=False)[source]

Log-density of the bilateral log-normal prior on diag(U).

Each |u_ii| is LogNormal(0, σ0²) (with a symmetric random sign, hence “bilateral”), i.e. log|u_ii| ~ N(0, σ0²) i.i.d. with

σ0 = prior_scale / (n_spatial * sqrt(C)).

Then log|det J| = n_spatial * Σ_i log|u_ii| ~ N(0, prior_scale²), so prior_scale directly controls the prior spread of the layer’s total log-volume change regardless of channel count and resolution.

Returns the (Gaussian) log-density of the log-diagonal Σ_i log N(log|u_ii|; 0, σ0²) – i.e. the density w.r.t. the log_s parametrization, without the -Σ log|u_ii| change-of- variables term that would give the density of |u_ii| itself. Returns 0 if prior_scale is None.

Parameters:

include_constants (bool) – include the Gaussian normalization constants.

Return type:

Tensor

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.HouseholderLinear[source]

Bases: ChannelLinear

Product of k Householder reflections W = H_k ⋯ H_1 (plus optional bias).

H_i = I - 2 v_i v_iᵀ / ‖v_i‖². Forward and inverse apply the reflections as rank-1 updates in O(k·C) per vector; no C×C matrix is formed. det W = (-1)^k so the layer is volume preserving.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • n_reflections (Optional[int]) – number k of reflections (defaults to C).

  • bias (bool) – whether to learn a bias.

__init__(event_shape, n_reflections=None, bias=False)[source]

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

Parameters:
bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

forward(x, context=None)[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:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.OrthogonalLinear[source]

Bases: ChannelLinear

Learnable special-orthogonal channel mixing (det W = 1) with optional bias.

W is the Cayley transform (I - A)(I + A)^{-1} or the matrix exponential exp(A) of a skew-symmetric A (initialized at 0, so W = I). The inverse is Wᵀ. Note that the Cayley map cannot represent rotations with eigenvalue -1; both maps cover only SO(C).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • method (str) – "cayley" or "exp".

  • bias (bool) – whether to learn a bias.

  • init_std (float) – std of a random perturbation of A at init (0 = identity).

__init__(event_shape, method='cayley', bias=True, init_std=0.0)[source]

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

Parameters:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.ActNorm[source]

Bases: ChannelLinear

Per-channel affine y = exp(s) * x + b with data-dependent initialization.

On the first forward call in training mode, s and b are set so that the output has zero mean and unit variance per channel on that batch; the persistent buffer initialized records this (so a loaded state dict is not re-initialized).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • zero_sum (bool) – if True the effective log-scale is s - mean(s) so that |det| = 1. The data init then equalizes the per-channel std (to the geometric mean of the input stds) instead of making it one.

  • eps (float) – numerical floor for the std in the data init.

__init__(event_shape, zero_sum=False, eps=1e-6)[source]

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

Parameters:
data_init(x)[source]

Initializes s and b from a batch x.

Return type:

None

Parameters:

x (Tensor)

forward(x, context=None)[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:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.GlobalScale[source]

Bases: ChannelLinear

Uniform scaling y = exp(log_scale) * x with a single scalar parameter.

log|det J| = D * log_scale with D = prod(event_shape).

Parameters:
__init__(event_shape, init=1.0)[source]

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

Parameters:
forward(x, context=None)[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:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

log_abs_det()[source]

Constant log|det J_f| of the forward (normalizing) map as a 0-dim tensor.

Return type:

Tensor

set_from_latents(z, method='mle')[source]

Sets the scale in closed form for a standard-normal base.

z are samples of the input of this layer (the latents produced by all preceding layers, before scaling).

Parameters:
  • z (Tensor) – tensor (N, *event_shape).

  • method (str) – "mle": exact maximum-likelihood scale for fixed preceding layers, c = sqrt(D / E‖z‖²) (maximizes E[log N(c z)] + D log c). "det": Draxler et al.’s optimal uniform scale c = |Σ_z|^{-1/(2D)}, optimal when the preceding volume- preserving part can whiten the latents (requires N > D).

Return type:

float

Returns:

The new scale factor c.

class cjd_flows.bijections.linear.Shift[source]

Bases: Bijection

Learnable translation y = x + b (volume preserving, log|det J| = 0).

Constant-Jacobian flows built only from additive couplings have no explicit bias; the couplings have to centre the latents themselves. A Shift before the global scale gives the flow a direct, volume-preserving bias. With data_init=True it is set to minus the mean of the first training batch (like ActNorm; the persistent buffer initialized prevents re-initialization after loading a state dict), so training starts with centred latents. It does not prevent the couplings from moving the latents off-centre again during training.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • per (str) – "coordinate" (one offset per entry of the event, the default) or "channel" (one offset per channel, shared across positions).

  • data_init (bool) – initialize from the first forward call in training mode.

__init__(event_shape, per='coordinate', data_init=True)[source]

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

Parameters:
data_init(x)[source]

Sets the offset to minus the mean of x ((B, *event_shape)).

Return type:

None

Parameters:

x (Tensor)

forward(x, context=None)[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:
log_abs_det()[source]

Constant log|det J_f| of the forward (normalizing) map as a 0-dim tensor.

Return type:

Tensor

extra_repr()[source]

Return the extra representation of the module.

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

Return type:

str

class cjd_flows.bijections.linear.Permutation[source]

Bases: ChannelLinear

Fixed channel permutation y[:, i] = x[:, perm[i]] (buffer).

Parameters:
__init__(event_shape, perm=None)[source]

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

Parameters:
forward(x, context=None)[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:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

class cjd_flows.bijections.linear.Reverse[source]

Bases: Permutation

Reverses the channel order.

__init__(event_shape)[source]

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

Parameters:

event_shape (int | Sequence[int] | Size)

class cjd_flows.bijections.linear.FixedOrthogonal[source]

Bases: ChannelLinear

Fixed random Haar-distributed orthogonal channel mixing (buffer).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) or (D,).

  • seed (Optional[int]) – optional seed for reproducibility.

  • dtype (Optional[dtype]) – dtype of the stored matrix (default: torch.get_default_dtype()). The matrix is orthogonal to the precision of this dtype; a layer built in float32 and converted with .double() is orthogonal only up to ~1e-7, so log_abs_det() == 0 is then exact only to that precision. Pass dtype=torch.float64 for float64 work.

__init__(event_shape, seed=None, dtype=None)[source]

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

Parameters:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

class cjd_flows.bijections.linear.AffineFromMatrix[source]

Bases: ChannelLinear

Frozen general channel-wise affine map y = W x + b.

W^{-1} and log|det W| are precomputed (in float64) and stored as buffers. Used by merge_linear() / simplify().

Parameters:
__init__(W, b=None, event_shape=None)[source]

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

Parameters:
weight()[source]

The (C, C) matrix W.

Return type:

Tensor

inverse_weight()[source]

W^{-1} (generic fallback via torch.linalg.inv; not used for training).

Return type:

Tensor

bias()[source]

The (C,) bias b or None.

Return type:

Optional[Tensor]

log_abs_det_weight()[source]

log|det W| of the channel matrix (0-dim).

Return type:

Tensor

cjd_flows.bijections.linear.merge_linear(chain, min_group=2)[source]

Collapses runs of consecutive channel-linear layers into AffineFromMatrix.

Nested Chain objects are flattened; inverses of channel-linear layers are merged too. Layers in a run must share the same event_shape. The composition f2 ∘ f1 has W = W2 W1 and b = W2 b1 + b2 (computed in float64, then cast to the dtype of the first layer).

Parameters:
  • chain (Bijection) – a Chain (or single bijection).

  • min_group (int) – minimum run length to merge; shorter runs are kept as is.

Return type:

Chain

Returns:

A new Chain (sharing the non-merged modules with chain).

cjd_flows.bijections.linear.apply_channel_matrix(x, W, b=None)[source]

Computes W @ x[:, :, s] + b for every spatial position s.

Parameters:
  • x (Tensor) – input of shape (B, C, *spatial) or (B, C).

  • W (Tensor) – matrix of shape (C_out, C).

  • b (Optional[Tensor]) – optional bias of shape (C_out,).

Return type:

Tensor

Returns:

Tensor of shape (B, C_out, *spatial).

Couplings

Volume-preserving coupling layers.

  • MaskedAdditiveCoupling – y = x + (1 - m) * t(m * x) with a binary mask buffer (checkerboard / channel / random / custom).

  • SplitAdditiveCoupling – Jet-style pairing: the input is split by index buffers into a conditioning half x_a and a transformed half x_b; y_b = x_b + t(x_a). No compute is wasted on masked zeros.

  • GINCoupling – same split, but affine with zero-sum log-scale (Sorrenson et al., 2020): y_b = x_b * exp(s - mean(s)) + t. Still volume preserving, but not piecewise affine.

All layers have log|det J| = 0. Conditioners are called as conditioner(x_a, context) (context is only passed when not None) and should be zero-initialized (all conditioners in cjd_flows.conditioners are), so that every layer starts as the identity.

Mask convention: 1 = conditioning (passed through), 0 = transformed.

cjd_flows.bijections.coupling.checkerboard_mask(event_shape, parity=0)[source]

Checkerboard mask over the spatial dims (identical for every channel).

For vectors (D,) the mask alternates over the dimensions ([1, 0, 1, 0, ...] for parity=0), as in the legacy code.

Return type:

Tensor

Returns:

Float tensor of event_shape with ones on the conditioning positions.

Parameters:
cjd_flows.bijections.coupling.channel_mask(event_shape, parity=0)[source]

Mask selecting the first C // 2 channels (parity=0) or the rest (parity=1).

For vectors, the channel dimension is D.

Raises:

ValueError – if the event has a single channel.

Return type:

Tensor

Parameters:
cjd_flows.bijections.coupling.random_mask(event_shape, seed=0)[source]

Random mask with floor(n / 2) ones (reproducible via seed).

Return type:

Tensor

Parameters:
cjd_flows.bijections.coupling.split_indices(event_shape, split='channel', parity=0, seed=0)[source]

Computes flat index sets for a two-way split of an event.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (D,) or (C, *spatial).

  • split (Union[str, Tensor]) –

    one of

    • "channel" – first C // 2 channels vs. the rest (for vectors: first D // 2 dims vs. the rest; alias "half"),

    • "interleaved" (vectors) / "checkerboard" – even vs. odd dims (vectors) or checkerboard over the spatial dims; the last spatial dim must be even and the halves have shape (C, *spatial[:-1], spatial[-1] // 2),

    • "spatial-row" – even/odd indices along the first spatial axis,

    • "spatial-col" – even/odd indices along the last spatial axis,

    • "random" – a random half (seeded); halves are flat vectors,

    • a boolean tensor of event_shape (True = conditioning half); halves are flat vectors.

  • parity (int) – 1 swaps the roles of the two halves.

  • seed (int) – seed for split="random".

Return type:

Tuple[Tensor, Tensor, Tuple[int, ...], Tuple[int, ...]]

Returns:

(idx_a, idx_b, shape_a, shape_b) – flat indices into the flattened event for the conditioning half a and the transformed half b and the event shapes of the halves.

class cjd_flows.bijections.coupling.MaskedAdditiveCoupling[source]

Bases: VolumePreserving

Additive masked coupling y = x + (1 - m) * t(m * x, context).

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – event shape of the input.

  • conditioner (Module) – module mapping (B, *event_shape) -> (B, *event_shape).

  • mask (Union[str, Tensor]) – binary tensor of event_shape (1 = conditioning) or one of "checkerboard", "channel", "random".

  • parity (int) – parity for string masks ("checkerboard", "channel").

  • seed (int) – seed for mask="random".

piecewise_affine follows the conditioner.

__init__(event_shape, conditioner, mask='checkerboard', parity=0, seed=0)[source]

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

Parameters:
forward(x, context=None)[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:
class cjd_flows.bijections.coupling.SplitAdditiveCoupling[source]

Bases: _SplitCoupling

Additive split coupling y_a = x_a, y_b = x_b + t(x_a, context).

Parameters:
  • event_shape – input event shape.

  • conditioner – a module mapping (B, *shape_a) -> (B, *shape_b), or a factory f(shape_a, shape_b) -> module (shapes are event shapes, channel first), e.g. lambda i, o: ConvNet(i[0], o[0], spatial_ndim=len(i) - 1) or lambda i, o: MLP(i, o).

  • split – see split_indices().

  • parity – 1 swaps the halves.

  • seed – seed for split="random".

shape_a, shape_b

event shapes of the conditioning / transformed half.

__init__(event_shape, conditioner, split='channel', parity=0, seed=0)[source]

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

class cjd_flows.bijections.coupling.GINCoupling[source]

Bases: _SplitCoupling

Volume-preserving affine split coupling (GIN, Sorrenson et al. 2020).

y_b = x_b * exp(s - mean(s)) + t with [s, t] = conditioner(x_a) split along dim 1 and s bounded by clamp * tanh(s / clamp). The mean is taken over all transformed dimensions of each sample, so the log-scales sum to zero and log|det J| = 0.

Parameters:
  • event_shape – input event shape.

  • conditioner – module mapping (B, *shape_a) -> (B, 2 * C_b, *spatial_b) (vectors: (B, 2 * D_b)), or a factory f(shape_a, out_shape) where out_shape already has the doubled channel count.

  • split – see split_indices().

  • parity – see split_indices().

  • seed – see split_indices().

  • clamp (Optional[float]) – soft bound of the raw log-scale (None disables it).

__init__(event_shape, conditioner, split='channel', parity=0, seed=0, clamp=2.0)[source]

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

Parameters:

clamp (float | None)

Autoregressive layers

Shift-only (volume-preserving) autoregressive layers.

The normalizing direction (forward) is a single parallel pass; the generative direction (inverse) is sequential. The Jacobian is unit lower triangular (in the autoregressive order), hence log|det J| = 0.

class cjd_flows.bijections.autoregressive.ShiftAutoregressive[source]

Bases: VolumePreserving

Additive autoregressive layer z_i = x_i + mu_i(x_{<i}, context).

forward (data -> latent) costs one MADE pass. inverse solves the triangular system by the fixed-point iteration x <- z - mu(x), which is exact after D passes (after pass k the first k dimensions of the autoregressive order are exact).

Parameters:
  • features (int) – number of dimensions D.

  • made (Optional[MADE]) – a MADE with features == D and out_multiplier == 1. Defaults to MADE(features).

piecewise_affine follows the MADE.

__init__(features, made=None)[source]

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

Parameters:
  • features (int)

  • made (MADE | None)

forward(x, context=None)[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:
class cjd_flows.bijections.autoregressive.MaskedConvAutoregressive[source]

Bases: VolumePreserving

Experimental. Spatial autoregressive shift layer with causal convolutions.

z[:, :, p] = x[:, :, p] + mu(x[:, :, <p])[:, :, p] where <p are the positions preceding p in raster order (all channels). The shift network is a PixelCNN-style stack: a type-A masked convolution (excludes the centre), type-B masked hidden convolutions with residual connections, and a zero-initialized type-B output convolution. Channels at the same position do not condition on each other.

forward is one parallel pass; inverse needs prod(spatial) sequential passes (raster scan) and is therefore slow for large inputs.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) with 1-3 spatial dims.

  • hidden (Sequence[int]) – hidden channel widths.

  • kernel_size (int) – odd kernel size.

  • activation (Union[str, Module]) – activation name or module.

  • context_dim (int) – context size (added to the first hidden layer through an unmasked linear map, broadcast over space).

__init__(event_shape, hidden=(64, 64), kernel_size=3, activation='relu', context_dim=0)[source]

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

Parameters:
shift(x, context=None)[source]

The autoregressive shift mu(x).

Return type:

Tensor

Parameters:
forward(x, context=None)[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:
class cjd_flows.bijections.autoregressive.TransformerAutoregressive[source]

Bases: VolumePreserving

Token-autoregressive layer with a causal transformer.

For a sequence of N tokens with D features each (event shape (N, D), e.g. the output of Patchify):

z_t = x_t + mu_t(x_<t, context)                         (scale=False)
z_t = x_t * exp(s_t(x_<t, context)) + mu_t(x_<t, context)  (scale=True)

where s_t is bounded by clamp * tanh(. / clamp) and centred over the D features of each token, so sum_d s_{t,d} = 0. The Jacobian is block lower triangular with diagonal blocks I (or diag(exp(s_t))), hence log|det J| = 0 in both cases. With scale=True this is the GIN-style (volume-preserving) counterpart of TarFlow (Zhai et al. 2024), whose per-token scales change the volume.

The shift network is a pre-LN transformer with causal attention, QK-norm and adaLN-zero context modulation (the blocks of JetConditioner). Its inputs are a learned start token followed by x_0, ..., x_{N-2}, so output t only sees x_<t. The output head is zero-initialized (identity at init).

forward (data -> latent) is one parallel pass. inverse decodes the tokens one by one and reuses the attention keys/values of earlier tokens, so it costs about one parallel pass of compute spread over N sequential steps. Without autograd (torch.no_grad, inference_mode, ONNX export) the keys/values go into preallocated buffers and every step has fixed shapes; with autograd (e.g. rsample) the cache grows by concatenation so that gradients flow through the inverse.

Alternate reverse between stacked layers so that every token is conditioned on every other one in some layer.

Numerics: with scale=False the inverse is exact up to rounding. With scale=True rounding errors of earlier tokens are multiplied by up to exp(|s|) in later ones, so large log-scales make the sequential inverse (sampling) ill-conditioned over long sequences. forward and log_prob are not affected. Check inverse(forward(x)) on trained models, or lower clamp.

Under fp16/bf16 autocast the cached inverse rounds the shifts differently from the parallel forward, so inverse(forward(x)) is only exact to about half precision (also with scale=False). Train with autocast if you like, but sample and invert without it.

Parameters:
  • event_shape (Union[int, Sequence[int], Size]) – (N, D): number of tokens and features per token.

  • embed_dim (int) – transformer width.

  • depth (int) – number of transformer blocks.

  • num_heads (Optional[int]) – attention heads (default max(1, embed_dim // 64)).

  • mlp_ratio (float) – token MLP hidden width / embed_dim.

  • context_dim (int) – context size (0: unconditional).

  • reverse (bool) – process the tokens in reverse order.

  • scale (bool) – add zero-sum log-scales per token (see above).

  • clamp (Optional[float]) – soft bound of the raw log-scale (None disables it).

  • qk_norm (bool) – RMSNorm on per-head queries/keys.

  • nonlinearity (Optional[Module]) – token MLP activation (default GELU).

  • grad_checkpointing (bool) – recompute block activations in backward.

__init__(event_shape, embed_dim=256, depth=4, num_heads=None, mlp_ratio=4.0, context_dim=0, reverse=False, scale=False, clamp=2.0, qk_norm=True, nonlinearity=None, grad_checkpointing=False)[source]

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

Parameters:
forward(x, context=None)[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:
cjd_flows.bijections.autoregressive.causal_kernel_mask(kernel_size, ndim, include_center)[source]

Raster-order causal mask for an ndim-D kernel (PixelCNN type A/B).

Kernel offsets that precede the centre in row-major (raster) order are 1; the centre itself is 1 iff include_center (type B).

Return type:

Tensor

Parameters:
  • kernel_size (int)

  • ndim (int)

  • include_center (bool)

Reshapes

Shape-changing volume-preserving bijections (pure permutations / orthonormal maps).

All layers here change the event shape. They expose event_shape (input) and out_shape (output) attributes; inverse() maps back from out_shape. Their Jacobian is a permutation or an orthonormal matrix, so log|det J| = 0.

Note that cjd_flows.testing.check_bijection() asserts shape preservation, so these layers are tested with dedicated checks.

class cjd_flows.bijections.reshape.Squeeze[source]

Bases: _ShapeChanging

Space-to-depth: (C, S1, ..., Sk) -> (C·f^k, S1/f, ..., Sk/f) for k = 1..3.

Output channel c·f^k + o holds input channel c at block offset o (offsets enumerated row-major), as in Glow/RealNVP.

Parameters:
__init__(event_shape, factor=2)[source]

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

Parameters:
forward(x, context=None)[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:
class cjd_flows.bijections.reshape.HaarWavelet[source]

Bases: _ShapeChanging

One level of the orthonormal Haar wavelet transform as space-to-depth.

(C, S1, ..., Sk) -> (2^k·C, S1/2, ..., Sk/2). Each 2×…×2 block is multiplied by H_k = H ⊗ … ⊗ H with H = [[1, 1], [1, -1]] / √2. The output is subband-major: channels [0, C) are the low-pass (approximation, scaled average 2^{k/2}·mean) coefficients, followed by the 2^k - 1 detail subbands of C channels each. |det| = 1.

Parameters:

event_shape (Union[int, Sequence[int], Size]) – (C, *spatial) with even spatial sizes.

__init__(event_shape)[source]

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

Parameters:

event_shape (int | Sequence[int] | Size)

forward(x, context=None)[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:
class cjd_flows.bijections.reshape.Patchify[source]

Bases: _ShapeChanging

Token layout (C, S1, ..., Sk) -> (N_tokens, p^k·C) for transformer conditioners.

N_tokens = prod(S_i / p) (row-major over patch positions) and each token’s features are ordered (p, …, p, C) (channels last), i.e. b c (h p1) (w p2) -> b (h w) (p1 p2 c). A pure permutation.

Note that after this layer dim 1 indexes tokens, so channel-wise layers applied afterwards would mix tokens.

Parameters:
__init__(event_shape, patch_size)[source]

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

Parameters:
forward(x, context=None)[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:
class cjd_flows.bijections.reshape.Flatten[source]

Bases: Reshape

Flattens events (C, *spatial) -> (prod,).

__init__(event_shape)[source]

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

Parameters:

event_shape (int | Sequence[int] | Size)

class cjd_flows.bijections.reshape.Reshape[source]

Bases: _ShapeChanging

Reshapes events from in_shape to out_shape (row-major).

__init__(in_shape, out_shape)[source]

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

Parameters:
forward(x, context=None)[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: