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
baddbmmon a(B, C, N)view, which benchmarked fastest on GPU (forward + backward) compared to 1x1 convolution,F.linearon channels-last views andeinsum.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), andmerge_linear()collapses consecutive channel-linear layers into one frozenAffineFromMatrix.
- class cjd_flows.bijections.linear.ChannelLinear[source]¶
Bases:
BijectionAbstract channel-wise affine bijection
y = W x + b(applied on dim 1).Subclasses implement
weight()and may overridebias(),inverse_weight(),log_abs_det_weight(),forward()andinverse()with cheaper parametrization-specific versions.- 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.
- inverse_weight()[source]¶
W^{-1}(generic fallback viatorch.linalg.inv; not used for training).- Return type:
- log_abs_det()[source]¶
Constant
log|det J_f|of the forward (normalizing) map as a 0-dim tensor.- Return type:
- 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.bijections.linear.LULinear[source]¶
Bases:
ChannelLinearChannel-wise LU-parametrized linear layer
W = P L Uwith bias.Pis a fixed permutation (buffer),Lis unit lower triangular andUis upper triangular with diagonalsign * exp(log_s)(signis a fixed±1buffer), solog|det W| = sum(log_s)and the layer is always invertible. The forward direction is one matmul withW; the inverse uses two triangular solves (applied either directly to the data when there are fewer vectors than channels, or toIto formW^{-1}followed by one matmul otherwise – whichever is faster).torch.inverseis never used.- Parameters:
event_shape (
Union[int,Sequence[int],Size]) –(C, *spatial)or(D,).unit_det (
bool) – ifTruethe log-diagonal is projected to zero sum (log_s - mean(log_s)), i.e.W ∈ SL(C)up to sign:|det W| = 1while anisotropic scaling remains possible (GIN trick).identity_init (
bool) – ifTrueinitializeL = U = I(soW = P). OtherwiseWis initialized as a random orthogonal matrix (Glow-style).permute (
bool) – use a random fixed channel permutationP; otherwiseP = I(withidentity_init=Falsethe orthogonal init is thenP^T Q).prior_scale (
Optional[float]) – scaleσof the bilateral log-normal prior used bylog_prior()(Nonedisables the prior).max_log_scale (
Optional[float]) – bound on each|log_s|(Nonedisables clamping).soft_clamp (
bool) – use a smoothtanhclamp 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.
- log_diag()[source]¶
Effective
log|u_ii|after clamping and (optional) zero-sum projection.- Return type:
- inverse_weight()[source]¶
W^{-1}(generic fallback viatorch.linalg.inv; not used for training).- Return type:
- 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²), soprior_scaledirectly 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. thelog_sparametrization, without the-Σ log|u_ii|change-of- variables term that would give the density of|u_ii|itself. Returns0ifprior_scaleisNone.
- class cjd_flows.bijections.linear.HouseholderLinear[source]¶
Bases:
ChannelLinearProduct of
kHouseholder reflectionsW = 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 inO(k·C)per vector; noC×Cmatrix is formed.det W = (-1)^kso the layer is volume preserving.- Parameters:
- __init__(event_shape, n_reflections=None, bias=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.bijections.linear.OrthogonalLinear[source]¶
Bases:
ChannelLinearLearnable special-orthogonal channel mixing (
det W = 1) with optional bias.Wis the Cayley transform(I - A)(I + A)^{-1}or the matrix exponentialexp(A)of a skew-symmetricA(initialized at0, soW = I). The inverse isWᵀ. Note that the Cayley map cannot represent rotations with eigenvalue-1; both maps cover onlySO(C).- Parameters:
- __init__(event_shape, method='cayley', bias=True, init_std=0.0)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- class cjd_flows.bijections.linear.ActNorm[source]¶
Bases:
ChannelLinearPer-channel affine
y = exp(s) * x + bwith data-dependent initialization.On the first forward call in training mode,
sandbare set so that the output has zero mean and unit variance per channel on that batch; the persistent bufferinitializedrecords 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) – ifTruethe effective log-scale iss - 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.
- 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.bijections.linear.GlobalScale[source]¶
Bases:
ChannelLinearUniform scaling
y = exp(log_scale) * xwith a single scalar parameter.log|det J| = D * log_scalewithD = prod(event_shape).- Parameters:
- __init__(event_shape, init=1.0)[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.
- inverse_weight()[source]¶
W^{-1}(generic fallback viatorch.linalg.inv; not used for training).- Return type:
- log_abs_det()[source]¶
Constant
log|det J_f|of the forward (normalizing) map as a 0-dim tensor.- Return type:
- set_from_latents(z, method='mle')[source]¶
Sets the scale in closed form for a standard-normal base.
zare 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‖²)(maximizesE[log N(c z)] + D log c)."det": Draxler et al.’s optimal uniform scalec = |Σ_z|^{-1/(2D)}, optimal when the preceding volume- preserving part can whiten the latents (requiresN > D).
- Return type:
- Returns:
The new scale factor
c.
- class cjd_flows.bijections.linear.Shift[source]¶
Bases:
BijectionLearnable 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
Shiftbefore the global scale gives the flow a direct, volume-preserving bias. Withdata_init=Trueit is set to minus the mean of the first training batch (likeActNorm; the persistent bufferinitializedprevents 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:
- __init__(event_shape, per='coordinate', data_init=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.bijections.linear.Permutation[source]¶
Bases:
ChannelLinearFixed 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.
- 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.bijections.linear.Reverse[source]¶
Bases:
PermutationReverses the channel order.
- class cjd_flows.bijections.linear.FixedOrthogonal[source]¶
Bases:
ChannelLinearFixed random Haar-distributed orthogonal channel mixing (buffer).
- Parameters:
event_shape (
Union[int,Sequence[int],Size]) –(C, *spatial)or(D,).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, solog_abs_det() == 0is then exact only to that precision. Passdtype=torch.float64for float64 work.
- __init__(event_shape, seed=None, dtype=None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- class cjd_flows.bijections.linear.AffineFromMatrix[source]¶
Bases:
ChannelLinearFrozen general channel-wise affine map
y = W x + b.W^{-1}andlog|det W|are precomputed (in float64) and stored as buffers. Used bymerge_linear()/simplify().- Parameters:
- __init__(W, b=None, event_shape=None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- cjd_flows.bijections.linear.merge_linear(chain, min_group=2)[source]¶
Collapses runs of consecutive channel-linear layers into
AffineFromMatrix.Nested
Chainobjects are flattened; inverses of channel-linear layers are merged too. Layers in a run must share the sameevent_shape. The compositionf2 ∘ f1hasW = W2 W1andb = W2 b1 + b2(computed in float64, then cast to the dtype of the first layer).
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 halfx_aand a transformed halfx_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, ...]forparity=0), as in the legacy code.
- cjd_flows.bijections.coupling.channel_mask(event_shape, parity=0)[source]¶
Mask selecting the first
C // 2channels (parity=0) or the rest (parity=1).For vectors, the channel dimension is
D.
- cjd_flows.bijections.coupling.random_mask(event_shape, seed=0)[source]¶
Random mask with
floor(n / 2)ones (reproducible viaseed).
- 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).one of
"channel"– firstC // 2channels vs. the rest (for vectors: firstD // 2dims 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) –1swaps the roles of the two halves.seed (
int) – seed forsplit="random".
- Return type:
- Returns:
(idx_a, idx_b, shape_a, shape_b)– flat indices into the flattened event for the conditioning halfaand the transformed halfband the event shapes of the halves.
- class cjd_flows.bijections.coupling.MaskedAdditiveCoupling[source]¶
Bases:
VolumePreservingAdditive 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 ofevent_shape(1 = conditioning) or one of"checkerboard","channel","random".parity (
int) – parity for string masks ("checkerboard","channel").seed (
int) – seed formask="random".
piecewise_affinefollows the conditioner.- __init__(event_shape, conditioner, mask='checkerboard', parity=0, seed=0)[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.bijections.coupling.SplitAdditiveCoupling[source]¶
Bases:
_SplitCouplingAdditive 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 factoryf(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)orlambda i, o: MLP(i, o).split – see
split_indices().parity –
1swaps the halves.seed – seed for
split="random".
- shape_a, shape_b
event shapes of the conditioning / transformed half.
- class cjd_flows.bijections.coupling.GINCoupling[source]¶
Bases:
_SplitCouplingVolume-preserving affine split coupling (GIN, Sorrenson et al. 2020).
y_b = x_b * exp(s - mean(s)) + twith[s, t] = conditioner(x_a)split along dim 1 andsbounded byclamp * tanh(s / clamp). The mean is taken over all transformed dimensions of each sample, so the log-scales sum to zero andlog|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 factoryf(shape_a, out_shape)whereout_shapealready 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 (Nonedisables it).
Autoregressive layers¶
Shift-only (volume-preserving) autoregressive layers.
ShiftAutoregressive–z_i = x_i + mu_i(x_<i)with aMADE(vectors).MaskedConvAutoregressive– experimental spatial version with PixelCNN-style causal convolutions (images / sequences / volumes).TransformerAutoregressive– token-autoregressive layer with a causal transformer (volume-preserving variant of TarFlow), inverse with a key/value cache.
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:
VolumePreservingAdditive autoregressive layer
z_i = x_i + mu_i(x_{<i}, context).forward(data -> latent) costs one MADE pass.inversesolves the triangular system by the fixed-point iterationx <- z - mu(x), which is exact afterDpasses (after passkthe firstkdimensions of the autoregressive order are exact).- Parameters:
piecewise_affinefollows the MADE.- __init__(features, made=None)[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.bijections.autoregressive.MaskedConvAutoregressive[source]¶
Bases:
VolumePreservingExperimental. Spatial autoregressive shift layer with causal convolutions.
z[:, :, p] = x[:, :, p] + mu(x[:, :, <p])[:, :, p]where<pare the positions precedingpin 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.forwardis one parallel pass;inverseneedsprod(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.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.
- 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.bijections.autoregressive.TransformerAutoregressive[source]¶
Bases:
VolumePreservingToken-autoregressive layer with a causal transformer.
For a sequence of
Ntokens withDfeatures each (event shape(N, D), e.g. the output ofPatchify):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_tis bounded byclamp * tanh(. / clamp)and centred over theDfeatures of each token, sosum_d s_{t,d} = 0. The Jacobian is block lower triangular with diagonal blocksI(ordiag(exp(s_t))), hencelog|det J| = 0in both cases. Withscale=Truethis 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 byx_0, ..., x_{N-2}, so outputtonly seesx_<t. The output head is zero-initialized (identity at init).forward(data -> latent) is one parallel pass.inversedecodes the tokens one by one and reuses the attention keys/values of earlier tokens, so it costs about one parallel pass of compute spread overNsequential 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
reversebetween stacked layers so that every token is conditioned on every other one in some layer.Numerics: with
scale=Falsethe inverse is exact up to rounding. Withscale=Truerounding errors of earlier tokens are multiplied by up toexp(|s|)in later ones, so large log-scales make the sequential inverse (sampling) ill-conditioned over long sequences.forwardandlog_probare not affected. Checkinverse(forward(x))on trained models, or lowerclamp.Under fp16/bf16 autocast the cached inverse rounds the shifts differently from the parallel
forward, soinverse(forward(x))is only exact to about half precision (also withscale=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 (defaultmax(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 (Nonedisables 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.
- 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.
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:
_ShapeChangingSpace-to-depth:
(C, S1, ..., Sk) -> (C·f^k, S1/f, ..., Sk/f)fork = 1..3.Output channel
c·f^k + oholds input channelcat block offseto(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.
- 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.bijections.reshape.HaarWavelet[source]¶
Bases:
_ShapeChangingOne level of the orthonormal Haar wavelet transform as space-to-depth.
(C, S1, ..., Sk) -> (2^k·C, S1/2, ..., Sk/2). Each2×…×2block is multiplied byH_k = H ⊗ … ⊗ HwithH = [[1, 1], [1, -1]] / √2. The output is subband-major: channels[0, C)are the low-pass (approximation, scaled average2^{k/2}·mean) coefficients, followed by the2^k - 1detail subbands ofCchannels each.|det| = 1.- __init__(event_shape)[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.bijections.reshape.Patchify[source]¶
Bases:
_ShapeChangingToken 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.
- 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.bijections.reshape.Flatten[source]¶
Bases:
ReshapeFlattens events
(C, *spatial) -> (prod,).
- class cjd_flows.bijections.reshape.Reshape[source]¶
Bases:
_ShapeChangingReshapes events from
in_shapetoout_shape(row-major).- __init__(in_shape, out_shape)[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.