cjd_flows.conditioners

Conditioner networks for coupling and autoregressive layers.

All conditioners are plain torch.nn.Module objects with the signature forward(x, context=None) and are pyro-free. Their last layer is zero-initialized, so every coupling / autoregressive layer built on top of them starts as the identity map.

Each conditioner exposes piecewise_affine: bool. It is True iff the network is a piecewise-affine function of its input (ReLU / LeakyReLU activations, no normalization, no gating, no attention), which is what exact SMT/MILP verification of the resulting flow requires. Dropout is ignored for this flag since it is the identity in evaluation mode.

Context handling:
  • MLP and MADE: the context vector is concatenated to the input (MADE: added through an unmasked linear map, so every output may depend on it).

  • ConvNet: the context is broadcast over space and appended as extra input channels.

  • JetConditioner: adaLN-zero modulation in every block.

If a conditioner was built with context_dim > 0 and context is None, a zero context is used. If it was built with context_dim == 0, a passed context is ignored (so contextual and non-contextual layers can be mixed in one flow).

class cjd_flows.conditioners.MLP[source]

Bases: Module

Residual MLP conditioner x[, context] -> out.

Architecture: Linear(in + ctx, h0) -> residual blocks h -> h + Linear(act(norm(h))) for every subsequent hidden width -> act -> zero-initialized Linear(h_last, out). With hidden=(256, 256) this is a standard 2-hidden-layer MLP (3 linear layers) with one skip connection.

Input/output may be shapes: if in_features is a tuple the input is flattened, if out_features is a tuple the output is reshaped, so an MLP can be used as conditioner for image-shaped couplings.

Parameters:
  • in_features (Union[int, Sequence[int]]) – input size (int) or event shape.

  • out_features (Union[int, Sequence[int]]) – output size (int) or event shape.

  • hidden (Sequence[int]) – hidden widths (non-empty).

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

  • context_dim (int) – size of the context vector (concatenated to the input).

  • residual (bool) – use skip connections (projection if widths differ).

  • norm (Optional[str]) – None or "layernorm" (pre-norm in each block).

  • dropout (float) – dropout probability inside blocks.

  • spectral_norm (bool) – wrap all linear layers in torch.nn.utils.parametrizations.spectral_norm(). The output layer is then followed by a scalar gain initialized to zero (a spectrally normalized zero matrix is undefined).

__init__(in_features, out_features, hidden=(256, 256), activation='relu', context_dim=0, residual=True, norm=None, dropout=0.0, spectral_norm=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:
class cjd_flows.conditioners.ConvNet[source]

Bases: Module

Residual N-D convolutional conditioner (B, C_in, *S) -> (B, C_out, *S).

Architecture: Conv_k(C_in + ctx, h0) -> residual (optionally gated) blocks for every subsequent hidden width -> act -> zero-initialized Conv_k(h_last, C_out). All convolutions are stride 1 with “same” padding dilation * (k - 1) // 2 (kernel_size must be odd), so the spatial shape is preserved. The context is broadcast over space and appended as extra input channels.

Parameters:
  • in_channels (int) – input channels.

  • out_channels (int) – output channels (exactly).

  • spatial_ndim (int) – number of spatial dims (1, 2 or 3).

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

  • kernel_size (int) – odd kernel size.

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

  • context_dim (int) – size of the context vector.

  • gated (bool) – use gated blocks (val * sigmoid(gate); not piecewise affine).

  • norm (Optional[str]) – None or "layernorm" (channel LayerNorm, pre-norm).

  • dropout (float) – dropout probability inside blocks.

  • spectral_norm (bool) – spectrally normalize all convolutions (torch normalizes the reshaped (C_out, C_in*K) kernel, which is not the operator norm; see lipschitz_upper_bound()). The output conv is then followed by a zero-initialized scalar gain.

  • dilation (int) – dilation of the k x k convolutions.

  • residual (bool) – use skip connections.

__init__(in_channels, out_channels, spatial_ndim=2, hidden=(64, 64), kernel_size=3, activation='relu', context_dim=0, gated=False, norm=None, dropout=0.0, spectral_norm=False, dilation=1, residual=True)[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.conditioners.MADE[source]

Bases: Module

Masked autoregressive MLP (Germain et al., 2015).

Output i (for each of the out_multiplier output blocks) depends only on the inputs that precede dimension i in order; the first dimension in the order receives a constant (bias, or context-dependent) output. The context (if any) enters every hidden unit of the first layer through an unmasked linear map. The output layer is zero-initialized.

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

  • hidden (Sequence[int]) – hidden widths (non-empty).

  • context_dim (int) – size of the context vector.

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

  • order (Union[None, str, Sequence[int], Tensor]) – None (identity order), "reverse", "random" or a permutation (order[k] is the dimension at position k).

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

  • out_multiplier (int) – number of outputs per input dimension. The output has shape (B, out_multiplier * D), block j occupying [:, j*D:(j+1)*D].

Buffers:

order: the permutation. degrees: degrees[d] = position of d + 1.

__init__(features, hidden=(256, 256), context_dim=0, activation='relu', order=None, seed=0, out_multiplier=1)[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:
connectivity()[source]

Boolean (D * out_multiplier, D) matrix: may output i depend on input j.

Return type:

Tensor

class cjd_flows.conditioners.JetConditioner[source]

Bases: Module

ViT conditioner (Jet, Kolesnikov et al. 2024) with adaLN-zero context.

Pipeline: patchify (strided conv / token chunking) -> fixed sin-cos positional embedding -> depth pre-LN blocks with QK-norm attention and adaLN-zero context modulation -> LayerNorm -> zero-initialized token-wise head -> unpatchify. Output is exactly zero at initialization.

Topologies:
  • vector, in_dims == [D]: chunked into tokens of token_size entries (zero-padded). Output (B, out_dim) (default D).

  • spatial, in_dims == [C, *spatial] (1-3 spatial dims): patches of side patch_size (must divide all spatial dims). Output (B, out_dim, *spatial) (default out_dim = C).

If context is None (or context_dim == 0) a learned null embedding is used. Not piecewise affine.

Parameters:
  • in_dims (Iterable[int]) – input event shape.

  • patch_size (int) – patch side length (spatial inputs).

  • embed_dim (int) – token width.

  • depth (int) – number of blocks.

  • num_heads (int) – attention heads.

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

  • context_dim (int) – context size (0: unconditional). Note: the legacy default was 1; context=None still works with any value.

  • token_size (int) – entries per token (vector inputs).

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

  • causal (bool) – causal attention over the token order.

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

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

  • out_dim (Optional[int]) – output features (vector) / channels (spatial). New in v1.

__init__(in_dims, patch_size=4, embed_dim=256, depth=6, num_heads=8, mlp_ratio=4.0, context_dim=0, token_size=8, qk_norm=True, causal=False, nonlinearity=None, grad_checkpointing=False, out_dim=None)[source]

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

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

Args: x: (B, *in_dims). context: optional (B, context_dim) (or broadcastable single context). padding_mask: optional bool (B, n_tokens); True = valid token.

Return type:

Tensor

Parameters:
class cjd_flows.conditioners.LayerNormChannels[source]

Bases: Module

LayerNorm over the channel dimension of (B, C, *spatial) tensors.

__init__(channels, spatial_ndim, eps=1e-5)[source]

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

Parameters:
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.conditioners.sincos_pos_embed(embed_dim, grid_shape)[source]

Fixed sine-cosine positional embedding for an N-D token grid.

The embedding dimension is split evenly across grid axes (sin/cos pairs); remainder dimensions are zero.

Return type:

Tensor

Returns:

Tensor of shape (prod(grid_shape), embed_dim) (float32).

Parameters:
cjd_flows.conditioners.lipschitz_upper_bound(module)[source]

Upper bound on the Lipschitz constant (w.r.t. the l2 norm) of a conditioner.

Supported: MLP and ConvNet without normalization layers and without gating. The bound is the product of per-layer bounds, where a residual block h -> P h + W act(h) contributes L_P + L_act * L_W (L_P = 1 for the identity skip, i.e. 1 + L per residual block). Linear layer norms are computed exactly (SVD of the effective, possibly spectrally-normalized weight); convolution norms use the bound described in _conv_bound(). The bound refers to evaluation mode (dropout = identity) and to the joint input (x, context), hence also bounds the Lipschitz constant in x alone.

For a ReLU network this is a true upper bound; for smooth activations the activation’s maximal slope is used (e.g. 1.13 for GELU).

Parameters:

module (Module) – an MLP or ConvNet.

Return type:

float

Returns:

The bound as a Python float (inf if the activation’s Lipschitz constant is unknown).

cjd_flows.conditioners.make_activation(activation)[source]

Builds an activation module.

Parameters:

activation (Union[str, Module]) – one of relu, leaky_relu, elu, tanh, gelu, silu or an nn.Module instance (treated as non-piecewise-affine with unknown Lipschitz constant inf, except nn.ReLU/nn.LeakyReLU).

Return type:

Tuple[Module, float, bool]

Returns:

(module, lipschitz_constant, piecewise_affine).