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:
MLPandMADE: 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:
ModuleResidual MLP conditioner
x[, context] -> out.Architecture:
Linear(in + ctx, h0)-> residual blocksh -> h + Linear(act(norm(h)))for every subsequent hidden width ->act-> zero-initializedLinear(h_last, out). Withhidden=(256, 256)this is a standard 2-hidden-layer MLP (3 linear layers) with one skip connection.Input/output may be shapes: if
in_featuresis a tuple the input is flattened, ifout_featuresis 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.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]) –Noneor"layernorm"(pre-norm in each block).dropout (
float) – dropout probability inside blocks.spectral_norm (
bool) – wrap all linear layers intorch.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.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class cjd_flows.conditioners.ConvNet[source]¶
Bases:
ModuleResidual 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-initializedConv_k(h_last, C_out). All convolutions are stride 1 with “same” paddingdilation * (k - 1) // 2(kernel_sizemust 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).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]) –Noneor"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; seelipschitz_upper_bound()). The output conv is then followed by a zero-initialized scalar gain.dilation (
int) – dilation of thek x kconvolutions.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.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class cjd_flows.conditioners.MADE[source]¶
Bases:
ModuleMasked autoregressive MLP (Germain et al., 2015).
Output
i(for each of theout_multiplieroutput blocks) depends only on the inputs that precede dimensioniinorder; 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 dimensionsD.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 positionk).seed (
int) – seed fororder="random".out_multiplier (
int) – number of outputs per input dimension. The output has shape(B, out_multiplier * D), blockjoccupying[:, 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.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class cjd_flows.conditioners.JetConditioner[source]¶
Bases:
ModuleViT conditioner (Jet, Kolesnikov et al. 2024) with adaLN-zero context.
Pipeline: patchify (strided conv / token chunking) -> fixed sin-cos positional embedding ->
depthpre-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 oftoken_sizeentries (zero-padded). Output(B, out_dim)(defaultD).spatial,
in_dims == [C, *spatial](1-3 spatial dims): patches of sidepatch_size(must divide all spatial dims). Output(B, out_dim, *spatial)(defaultout_dim = C).
If
contextisNone(orcontext_dim == 0) a learned null embedding is used. Not piecewise affine.- Parameters:
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 was1;context=Nonestill 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.
- class cjd_flows.conditioners.LayerNormChannels[source]¶
Bases:
ModuleLayerNorm 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.
- 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
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- 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.
- cjd_flows.conditioners.lipschitz_upper_bound(module)[source]¶
Upper bound on the Lipschitz constant (w.r.t. the l2 norm) of a conditioner.
Supported:
MLPandConvNetwithout normalization layers and without gating. The bound is the product of per-layer bounds, where a residual blockh -> P h + W act(h)contributesL_P + L_act * L_W(L_P = 1for the identity skip, i.e.1 + Lper 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 inxalone.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).
- cjd_flows.conditioners.make_activation(activation)[source]¶
Builds an activation module.