Bijections¶
A bijection is an exactly invertible map \(f:\mathbb{R}^D\!\to\mathbb{R}^D\) paired with the log-absolute-determinant of its Jacobian. Under the change-of-variables formula a base density \(p_Z\) pushes forward to
so each layer exposes its map and the log-determinant of its Jacobian in both directions —
transform_and_log_det and inverse_and_log_det, each returning (y, log_det). Per the
FlowJax convention a
Transformed distribution applies transform when
sampling (base → data) and inverse when evaluating density (data → base — the \(f\) in
the formula above), so a layer's data/latent orientation is set by how it is composed, not by
the method name. Generative-only layers such as PlanarFlow / SylvesterFlow implement only
transform_and_log_det. All layers below subclass
flowjax.bijections.AbstractBijection and follow
the single-event convention (x.shape == self.shape, scalar log_det); batch with
jax.vmap.
Coupling layers¶
Coupling layers split the input into two halves, leave one half untouched, and transform the
other half with an elementwise bijection whose parameters are predicted by a neural network
from the untouched half. The Jacobian is triangular, so log_det is a cheap sum and the
inverse is closed-form — the workhorse of expressive flows.
Every coupling starts as its unconditional self. GINCoupling and ContinuousAffineCoupling read their shift \(\gvect{\beta}\) and scale \(\gvect{\gamma}\) from the shared AffineModulation of the untouched half (and the condition), whose readout starts at zero weight and bias \((\vect{0}, r_0)\), so \(\gvect{\gamma} = \vect{1}\) and \(\gvect{\beta} = \vect{0}\) for every input; they take nn_width, nn_depth, activation, readout_scale and scale_map, or a pre-built modulation. The couplings built on FlowJax's Coupling (AffineCoupling, RQSplineCoupling, CircularRQSplineCoupling, DeepSigmoidCoupling, MixtureGaussianCDFCoupling) zero their network's readout with zero_readout, and FlowJax adds the network's output to the transformer's initial parameters, so the transformer starts at its initial value for every input: the identity for all of them except DeepSigmoidCoupling, whose initial transformer is a fixed sum of sigmoids rather than the identity.
AffineCoupling
¶
Bases: AbstractBijection
Affine coupling layer.
Splits the input into two halves along its single (1D) axis. The first
n_dims // 2 dims pass through unchanged and feed an inner conditioner
MLP that emits per-dim affine parameters (shift, log_scale) for the
remaining dims, which are transformed as y = x · exp(log_scale) + shift.
With cond_dim set, the same MLP additionally consumes an external
context vector concatenated onto the first-half input.
Wraps flowjax.bijections.Coupling with an
flowjax.bijections.affine.Affine transformer; this class adds the
convention that an unconditional layer (cond_dim=None) drops any
incoming condition so a base-only condition cannot leak into the inner
MLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for conditioner MLP initialisation. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
cond_dim
|
int | None
|
If not |
None
|
nn_width
|
int
|
Hidden layer width of the conditioner MLP. Defaults to 64. |
64
|
nn_depth
|
int
|
Depth of the conditioner MLP. Defaults to 2. |
2
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det
(with
cond_dimset, also takes aconditionof shape(cond_dim,))
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import AffineCoupling
>>> t = AffineCoupling(jr.key(0), shape=(4,))
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/affine.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
transform_and_log_det
¶
Forward map x → y and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/affine.py
inverse_and_log_det
¶
Inverse map y → x and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/affine.py
GINCoupling
¶
Bases: AbstractBijection
Volume-preserving affine coupling from Sorrenson et al. (2020).
This matches AffineCoupling except the active-half log-scales are
centred before exponentiation:
y_active = x_active · exp(log γ − mean(log γ)) + β
where (γ, log γ, β) come from the shared
gauss_flows_maps.conditioning.AffineModulation applied to the passive half
(and the condition, when set). Its readout starts at zero weight and bias
(0, r₀), so log γ = 0 and β = 0 for every input and the layer
starts as the identity.
so the transformed block has unit determinant and the layer returns
log_det = 0 exactly. We hardcode jnp.zeros(()) rather than
returning jnp.sum(log_scale_centered) because the centering still
leaves ~1e-7 float32 drift per layer; compounded across a stack of
Chain-ed GIN blocks that drift breaks the volume-preservation that
is the whole point of this bijection.
The active half must have at least two dimensions for centering to
actually constrain a scale — a 1-element log_scale is centred to
zero and degenerates to a pure shift. We therefore require
shape[0] >= 3 (smallest dim with transformed_dim = 2).
Reference
Sorrenson, Rother, Köthe (2020), Disentanglement by Nonlinear ICA with General Incompressible-flow Networks (GIN).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for the modulation's init. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
cond_dim
|
int | None
|
If not |
None
|
nn_width
|
int
|
Width of the modulation's trunk. Defaults to 64. |
64
|
nn_depth
|
int
|
Number of trunk layers. Defaults to 2. |
2
|
activation
|
Callable[[Array], Array]
|
Activation after each trunk layer. Defaults to ReLU. |
relu
|
readout_scale
|
float
|
Factor on the readout's default weight; the default |
0.0
|
scale_map
|
_FlowScaleMap
|
The positive scale map |
'exp'
|
modulation
|
AffineModulation | None
|
A pre-built |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det (≡ 0)
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det (≡ 0)
(with
cond_dimset, also takes aconditionof shape(cond_dim,))
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import GINCoupling
>>> coupling = GINCoupling(jr.key(0), shape=(4,), nn_width=16, nn_depth=1)
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = coupling.transform_and_log_det(x)
>>> x_rec, log_det_inv = coupling.inverse_and_log_det(y)
>>> assert jnp.allclose(x, x_rec)
>>> assert jnp.array_equal(log_det, jnp.array(0.0, dtype=log_det.dtype))
>>> assert jnp.array_equal(log_det_inv, jnp.array(0.0, dtype=log_det_inv.dtype))
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/gin_coupling.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
transform_and_log_det
¶
Forward map x → y with volume-preserving log_det ≡ 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/gin_coupling.py
inverse_and_log_det
¶
Inverse map y → x with volume-preserving log_det ≡ 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/gin_coupling.py
RQSplineCoupling
¶
Bases: AbstractBijection
Rational quadratic spline coupling layer.
Splits the input into two halves along its single (1D) axis. The first
n_dims // 2 dims pass through unchanged and feed an inner conditioner
MLP that emits the knot/derivative parameters of a monotone rational
quadratic spline applied per-dim to the remaining half. Like
AffineCoupling but with a far more expressive per-dim
transformer; with cond_dim set, the inner MLP additionally consumes
an external context vector concatenated onto the first-half input.
Wraps flowjax.bijections.Coupling with a
flowjax.bijections.RationalQuadraticSpline transformer; this
class adds the convention that an unconditional layer drops any incoming
condition so a base-only condition cannot leak into the inner MLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for conditioner MLP initialisation. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
n_bins
|
int
|
Number of spline bins (knots). Defaults to 8. |
8
|
interval
|
float
|
Half-width of the spline interval |
5.0
|
cond_dim
|
int | None
|
If not |
None
|
nn_width
|
int
|
Hidden layer width of the conditioner MLP. Defaults to 64. |
64
|
nn_depth
|
int
|
Depth of the conditioner MLP. Defaults to 2. |
2
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det
(with
cond_dimset, also takes aconditionof shape(cond_dim,))
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import RQSplineCoupling
>>> t = RQSplineCoupling(jr.key(0), shape=(4,))
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/spline.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
transform_and_log_det
¶
Forward map x → y and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/spline.py
inverse_and_log_det
¶
Inverse map y → x and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/spline.py
CircularRQSplineCoupling
¶
Bases: AbstractBijection
Coupling layer whose transformer is a circular rational quadratic spline.
Implements the construction of Rezende et al. 2020 for densities on the
n-torus. All input dims are assumed periodic with period 2·bound.
For mixed periodic/linear inputs, compose this with a regular
RQSplineCoupling via flowjax.bijections.Chain.
Two ingredients combine to make the resulting log-density continuous across the wrap join:
- The per-dim transformer is
CircularRationalQuadraticSpline(tied endpoint derivatives → C¹ across the join). - The conditioner sees
[sin(x_cond), cos(x_cond)]features rather than raw angles, so it cannot distinguish-π+εfrom+π-ε.
The transformed slice is input[untransformed_dim:]; the leading
untransformed_dim dims pass through unchanged and supply the
Fourier-feature conditioning. This is unconditional — there is no external
condition argument (cond_shape is None).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for the conditioner MLP. |
required |
shape
|
tuple[int, ...]
|
Input shape |
required |
n_bins
|
int
|
Number of spline bins. Defaults to 8. |
8
|
bound
|
float
|
Half-width of the circular interval; period is |
float(pi)
|
untransformed_dim
|
int | None
|
Number of leading dims left unchanged (used as
conditioner inputs). Must lie in |
None
|
nn_width
|
int
|
Hidden layer width for the conditioner MLP. Defaults to 64. |
64
|
nn_depth
|
int
|
Depth of the conditioner MLP. Defaults to 2. |
2
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import CircularRQSplineCoupling
>>> coupling = CircularRQSplineCoupling(jr.key(0), shape=(4,), n_bins=8)
>>> x = jr.uniform(jr.key(1), (4,), minval=-jnp.pi, maxval=jnp.pi)
>>> y, log_det = coupling.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = coupling.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-4))
True
Reference
Rezende et al. 2020, Normalizing Flows on Tori and Spheres.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/circular_spline.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
transform_and_log_det
¶
Forward map x → y on the torus and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
Single event of shape |
required |
condition
|
Array | None
|
Unused (this layer is unconditional). |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/circular_spline.py
inverse_and_log_det
¶
Inverse map y → x on the torus and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Array
|
Single event of shape |
required |
condition
|
Array | None
|
Unused (this layer is unconditional). |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/circular_spline.py
DeepSigmoidCoupling
¶
Bases: AbstractBijection
Coupling layer with a monotone single-layer sigmoidal transformer.
Replaces AffineCoupling's affine transformer with the
_DeepSigmoidTransformer — a per-dim monotone function
parametrised by n_components sigmoid units (single-layer DSF, Huang
et al. 2018 NAF §3.2). The transformer is strictly more expressive
than affine in the function-class sense: it has nonzero second derivative
where Affine has zero, and can in principle approximate any smooth
monotone CDF.
In practice, single-layer DSF inherits the optimisation difficulties
Huang et al. flagged: the loss surface around the conditioner's default
initialisation is dominated by an affine-equivalent basin, and SGD often
fails to escape it on multi-modal / heavy-tailed targets within a few
hundred steps. For challenging targets, prefer RQSplineCoupling (see
flowjax) or stacked DSF chains.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for conditioner MLP initialisation. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
n_components
|
int
|
Number of sigmoid units in the per-dim transformer. More components → more capacity, more parameters per dim. Defaults to 8. |
8
|
cond_dim
|
int | None
|
If not |
None
|
nn_width
|
int
|
Hidden layer width of the conditioner MLP. Defaults to 64. |
64
|
nn_depth
|
int
|
Depth of the conditioner MLP. Defaults to 2. |
2
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det
(with
cond_dimset, also takes aconditionof shape(cond_dim,); the coupling splits inton_dims // 2kept + transformed halves, andlog_detsumslog(dy/dx)over the transformed dims)
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import DeepSigmoidCoupling
>>> coupling = DeepSigmoidCoupling(
... key=jr.key(0), shape=(4,), n_components=8, nn_width=32, nn_depth=2,
... )
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = coupling.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = coupling.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-4))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/deepsigmoid.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
transform_and_log_det
¶
Forward map x → y and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/deepsigmoid.py
inverse_and_log_det
¶
Inverse map y → x and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/deepsigmoid.py
MixtureGaussianCDFCoupling
¶
Bases: AbstractBijection
Coupling layer whose transformed half goes through a mixture-CDF.
Splits input into two halves along the leading (1D) axis. The first
n_dims // 2 dims are passed through and feed a conditioner MLP that
emits per-dim mixture parameters for the remaining dims, which are
then Gaussianized via z = Φ⁻¹(F(x; π, μ, σ)).
The per-dim log-scales are passed through a tanh clamp
bound · tanh(raw) for training stability and for RBIG warm-start
inversion — see gauss_flows_models.inference.fit_rbig_coupling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for the conditioner MLP. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
n_components
|
int
|
Mixture components |
8
|
cond_dim
|
int | None
|
If not |
None
|
nn_width
|
int
|
Hidden layer width of the conditioner MLP. Defaults to 64. |
64
|
nn_depth
|
int
|
Depth of the conditioner MLP. Defaults to 2. |
2
|
log_scale_bound
|
float
|
Tanh bound applied to per-dim log-scales. Defaults to 5.0 (σ ∈ [exp(-5), exp(5)] ≈ [6.7e-3, 148]). |
5.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det: (n_dims,) → (n_dims,), scalar log_det
- inverse_and_log_det: (n_dims,) → (n_dims,), scalar log_det
(with
cond_dimset, also takes aconditionof shape(cond_dim,))
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import MixtureGaussianCDFCoupling
>>> coupling = MixtureGaussianCDFCoupling(jr.key(0), shape=(4,), n_components=4)
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = coupling.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = coupling.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-4))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/mixture_cdf.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
transform_and_log_det
¶
Forward map x → z and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/mixture_cdf.py
inverse_and_log_det
¶
Inverse map z → x and its scalar log-determinant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ArrayLike
|
Single event of shape |
required |
condition
|
ArrayLike | None
|
Context of shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Tuple |
Array
|
scalar |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/mixture_cdf.py
Marginal (elementwise) transforms¶
Marginal transforms act independently on each coordinate — the Gaussianization "G" step that reshapes per-dimension marginals toward a target (usually a standard normal or a uniform). Because they are diagonal, the Jacobian determinant is the product of per-coordinate derivatives.
MixtureGaussianCDF
¶
Bases: AbstractBijection
Marginal Gaussianization via a mixture-of-Gaussians CDF.
Maps each dimension independently through its Gaussian-mixture CDF
(→ uniform on [0, 1]) then through the inverse normal CDF (probit),
giving Gaussianised marginals. Each dim has its own n_components means,
scales, and log-weights; the scales use a soft floor σ = 5e−3 + softplus(u)
for training stability, stored as the paramax.Parameterize leaf scales
of gauss_flows_maps.reparam.Reparametrised (paramax.unwrap gives σ),
and the weights are a softmax over log_weights. The inverse runs a
per-dim bisection solver to invert the (monotone) mixture CDF.
Use as the marginal block of a Gaussianization / RBIG flow. Construct
parameters at zero (uniform components) with MixtureGaussianCDF(...), or
data-adapt the means/scales to per-dim quantiles via from_data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int
|
Number of mixture components |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import MixtureGaussianCDF
>>> t = MixtureGaussianCDF(n_components=4, shape=(3,))
>>> x = jnp.zeros(3)
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/mixture_cdf.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
from_data
classmethod
¶
from_data(x: ArrayLike, n_components: int = 8) -> MixtureGaussianCDF
Build a marginal layer with means at per-dim quantiles of x.
The per-dim component means are placed at evenly spaced quantiles
of x[:, i], and the scales are set to the inter-quantile spacing ×
per-dim std (at least 1e-2) — each dim gets its own target scale
based on its own standard deviation.
Weights remain uniform. This gives a meaningful first forward pass
without running the full RBIG fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Training data of shape |
required |
n_components
|
int
|
Mixture components |
8
|
Returns:
| Type | Description |
|---|---|
MixtureGaussianCDF
|
A |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/mixture_cdf.py
MixtureLogisticCDF
¶
Bases: AbstractBijection
Marginal Gaussianization via a mixture-of-logistics CDF.
Identical in structure to MixtureGaussianCDF but each per-dim
mixture component is logistic rather than Gaussian: the component CDF is the
sigmoid σ((x − μ) / s). Maps each dimension through its logistic-mixture
CDF (→ uniform on [0, 1]) then through the inverse normal CDF (probit).
Scales use the same soft floor s = 5e−3 + softplus(u), stored as the
leaf scales, and weights are a softmax over log_weights; the inverse
uses a per-dim bisection solver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int
|
Number of mixture components |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import MixtureLogisticCDF
>>> t = MixtureLogisticCDF(n_components=4, shape=(3,))
>>> y, log_det = t.transform_and_log_det(jnp.zeros(3))
>>> y.shape
(3,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/mixture_cdf.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
RQSplineMarginal
¶
Bases: AbstractBijection
Marginal Gaussianization via rational-quadratic splines.
Applies a monotonic rational-quadratic spline (Durkan et al. 2019,
Neural Spline Flows) independently to each dimension — the elementwise
counterpart of RQSplineCoupling. Each dim gets its own n_bins
knots over the symmetric interval [−interval, interval]; outside that
interval the map is the identity (linear tails). Inputs should lie within
the interval for the spline to act non-trivially.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_bins
|
int
|
Number of spline knots (bins) per dimension. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
interval
|
float
|
Half-width of the symmetric spline interval
|
5.0
|
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import RQSplineMarginal
>>> t = RQSplineMarginal(n_bins=8, shape=(3,), interval=5.0)
>>> x = jnp.array([0.1, -0.5, 1.0]) # inside [−5, 5]
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/spline.py
CircularRationalQuadraticSpline
¶
Bases: AbstractBijection
Scalar rational quadratic spline with tied endpoint derivatives.
The spline maps [-bound, bound] → [-bound, bound] and is C¹-continuous
when the interval is identified with the circle (derivative(+bound) ==
derivative(-bound)). This makes the resulting density continuous across the
angular wrap boundary, matching the construction of Rezende et al. 2020,
Normalizing Flows on Tori and Spheres.
Implementation: wraps flowjax.bijections.RationalQuadraticSpline and
replaces the derivatives Parameterize with a tied variant — one fewer
free parameter than the unconstrained spline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
knots
|
int
|
Number of bins. |
required |
bound
|
float
|
Half-width of the periodic interval. Defaults to |
float(pi)
|
min_derivative
|
float
|
Minimum derivative at any knot. Defaults to |
0.001
|
min_width
|
float
|
Minimum bin width. Defaults to |
0.001
|
Shape
Scalar bijection: shape == (). Use inside a Coupling or Vmap
to apply it to a vector of periodic coordinates.
- transform_and_log_det:
()→(), scalar log_det - inverse_and_log_det:
()→(), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import CircularRationalQuadraticSpline
>>> t = CircularRationalQuadraticSpline(knots=8) # bound = π
>>> x = jnp.array(0.3) # scalar angle inside [−π, π]
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
()
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/circular_spline.py
HistogramCDF
¶
Bases: AbstractBijection
Marginal Gaussianization via a per-dimension empirical histogram CDF.
Maps each dimension through its empirical CDF estimated from training
data. Forward yields uniform marginals on [0, 1]; out-of-training-
range inputs are clamped to {0, 1} with log_det = −∞ (signals
"outside the support of the fitted CDF").
The CDF is built from an equal-width histogram and routed through a
functax 1-D interpolant per dimension (functax.interp). Two
interpolation strategies are supported:
method="linear"(default): piecewise-linear CDF (functaxLinear). Density is the piecewise-constant bin PDF; log-det is piecewise-constant inx.method="monotonic": Fritsch-Carlson monotone cubic Hermite (PCHIP, functaxPchip) interpolant through the same CDF breakpoints. Gives a smooth CDF and a smooth (continuous, piecewise-cubic) density via the analytic derivative. The inverse is a second monotonic-cubic interpolator on swapped axes, so roundtrip is approximate (~1e-5) rather than exact — use"linear"if exact roundtrip matters.
Construction is two-phase: build an unfitted instance with
HistogramCDF(n_bins, shape), then call .fit(data) to get a
fitted instance with concrete bin edges, densities, CDF breakpoints,
and the forward/inverse interpolators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_bins
|
int
|
Number of equal-width histogram bins per dimension. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
method
|
str
|
|
'linear'
|
bin_edges
|
Array | None
|
Optional pre-fit bin edges of shape |
None
|
bin_pdf
|
Array | None
|
Optional pre-fit per-bin density of shape |
None
|
cdf_edges
|
Array | None
|
Optional pre-fit CDF values at bin edges of shape
|
None
|
fwd_interp
|
Interpolant | SeriesInterpolant | None
|
Optional pre-built forward-CDF interpolator.
Use |
None
|
inv_interp
|
Interpolant | SeriesInterpolant | None
|
Optional pre-built inverse-CDF interpolator. |
None
|
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,)in[0, 1], scalar log_det (sum of per-dimlog(density)) - inverse_and_log_det:
(n_dims,)in[0, 1]→(n_dims,), scalar log_det
Examples:
Fit and transform on Gaussian data:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import HistogramCDF
>>> data = jr.normal(jr.key(0), (5000, 3))
>>> hist = HistogramCDF(n_bins=64, shape=(3,)).fit(data)
>>> y, log_det = hist.transform_and_log_det(jnp.zeros(3))
>>> y.shape
(3,)
>>> # y is roughly [0.5, 0.5, 0.5] (CDF at 0 of N(0,1) ≈ 0.5).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/histogram.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
fit
¶
fit(data: ArrayLike) -> HistogramCDF
Fit the empirical CDF to data and return a new fitted instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ArrayLike
|
Array of shape |
required |
Returns:
| Type | Description |
|---|---|
HistogramCDF
|
A new |
HistogramCDF
|
|
HistogramCDF
|
interpolators populated. Idempotent: refitting with the same |
HistogramCDF
|
data yields the same fitted parameters. |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/histogram.py
transform_and_log_det
¶
Map x → uniform via the fitted CDF; log_det = sum(log density).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/histogram.py
inverse_and_log_det
¶
Map uniform y → x via the inverse CDF; log_det = -sum(log density).
Log-det uses the forward density at the recovered x (i.e.
-log(fwd'(x_rec))) rather than the inverse-interpolator's own
derivative. For method="linear" the two are exact reciprocals
(roundtrip is exact). For method="monotonic" the two
interpolators are independent monotone-cubic fits on swapped axes,
so the sum log_det_f + log_det_i is approximately zero rather
than exactly zero (typically < 1e-3 for well-fit histograms).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/histogram.py
InverseGaussCDF
¶
Bases: AbstractBijection
Apply the inverse Gaussian CDF (probit) element-wise.
Maps uniform marginals on [0, 1] to standard-Gaussian marginals via the
probit function Φ⁻¹. This is the standard final step of a marginal
Gaussianization layer: a CDF transform (histogram, mixture, …) sends data to
uniform, then this layer sends uniform to N(0, 1). The forward map is
y = Φ⁻¹(x); inputs are clipped to [1e−6, 1 − 1e−6] to keep the probit
finite at the boundaries. The inverse is the Gaussian CDF x = Φ(y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import InverseGaussCDF
>>> t = InverseGaussCDF(shape=(3,))
>>> x = jnp.array([0.2, 0.5, 0.8])
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
>>> bool(jnp.allclose(y[1], 0.0)) # Φ⁻¹(0.5) == 0
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/inverse_gauss.py
Elementwise
¶
Bases: AbstractBijection
The bijection x ↦ y = g(x), elementwise, for a reparametrisation map g.
y = g(x), x = g⁻¹(y), log |det ∂y/∂x| = Σᵢ log g′(xᵢ)
g is an elementwise map of gauss_flows_maps.reparam (Reparametrised
or Composed), which supplies the forward map, its inverse and the
stable log-derivative: log g′(x) is x for exp, −softplus(−x) for softplus
and log(b − a) − softplus(x) − softplus(−x) for the sigmoid map on
(a, b). These stay finite for |x| ≤ 100 in float32. The image of g is its
set, so inverse_and_log_det returns NaN for a y outside it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
map
|
The elementwise reparametrisation g. |
required | |
shape
|
Event shape; g is applied to every entry. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Shape
- transform_and_log_det:
shape→shape, scalar log_det - inverse_and_log_det:
shape→shape, scalar log_det
Examples:
The positive part y = softplus(x) of a 4-vector, and its log-Jacobian:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import Elementwise
>>> from gauss_flows_maps.reparam import Reparametrised
>>> positive_part = Elementwise(Reparametrised("softplus"), shape=(4,))
>>> y, log_det = positive_part.transform_and_log_det(jnp.zeros(4))
>>> bool(jnp.allclose(y, jnp.log(2.0)))
True
>>> bool(jnp.allclose(log_det, 4 * jnp.log(0.5)))
True
A bijection onto (0, 1), inside a flow:
>>> from gauss_flows_maps.reparam import Composed
>>> unit = Elementwise(Reparametrised("sigmoid", lower=0.0, upper=1.0), (3,))
>>> x, _ = unit.inverse_and_log_det(jnp.full(3, 0.5))
>>> bool(jnp.allclose(x, 0.0))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/reparametrised.py
Elementwise turns an elementwise map of gauss_flows_maps.reparam (exp, softplus or sigmoid with bounds) into a bijection, with its log-Jacobian taken from the map's log_derivative.
The positive parameters of the layers on this page are stored as leaves of the same maps, Reparametrised("softplus", lower=floor).parameter(value): ActNorm and ActNorm1D keep scale (floor 1e-5), the two GDN layers keep beta (floor beta_floor) and gamma (no floor), MixtureGaussianCDF and MixtureLogisticCDF keep scales (floor 5e-3), and CircularRationalQuadraticSpline keeps its free derivatives (floor min_derivative). DeepSigmoidCoupling's transformer keeps base_scale, amplitudes and slopes (floor 1e-4). PlanarFlow computes its constraint −1 + softplus(w·u) with the map's forward.
Linear & rotation layers¶
Linear layers mix information across coordinates — the rotation "R" step of RBIG. A rotation \(W\) contributes \(\log|\det W|\) (zero for an orthogonal \(W\)) and, by decorrelating dimensions, lets the next marginal step make progress.
HouseholderRotation
¶
Bases: AbstractBijection
Orthogonal rotation via a sequence of Householder reflections.
Composes n_reflections Householder reflections — each of the form
x ↦ x − 2·(x·v̂)·v̂ with unit vector v̂ — to build a general
orthogonal map. With n_reflections == n_dims this can represent any
orthogonal matrix. Each reflection is its own inverse, so the inverse
simply applies the reflections in reverse order. Being orthogonal, the map
is volume-preserving and log_det = 0 exactly.
Operates on a single (n_dims,) event; callers vmap over any batch axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_reflections
|
int
|
Number of Householder reflections to compose. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0 - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import HouseholderRotation
>>> t = HouseholderRotation(n_reflections=2, shape=(3,))
>>> x = jnp.array([1.0, 2.0, 3.0])
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
>>> bool(jnp.allclose(log_det, 0.0))
True
>>> x_rec, _ = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/rotation.py
OrthogonalRotation
¶
Bases: AbstractBijection
Learnable orthogonal rotation via the Cayley map.
Parameterises an orthogonal matrix Q = (I − A)(I + A)⁻¹ from a
skew-symmetric A (built from the n_dims·(n_dims−1)/2 strictly
lower-triangular free parameters, then antisymmetrised). The Cayley
transform maps any skew-symmetric A to a special orthogonal Q,
so the map y = Q·x is volume-preserving with log_det = 0 exactly.
Initialised at A = 0 (Q = I), i.e. the identity at step 0.
Operates on a single (n_dims,) event; callers vmap over any batch axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0 - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import OrthogonalRotation
>>> t = OrthogonalRotation(shape=(3,)) # Q = I at init
>>> x = jnp.array([1.0, 2.0, 3.0])
>>> y, log_det = t.transform_and_log_det(x)
>>> bool(jnp.allclose(y, x)) # identity at zero init
True
>>> bool(jnp.allclose(log_det, 0.0))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/rotation.py
FixedRotation
¶
Bases: AbstractBijection
Fixed (non-trainable) orthogonal rotation matrix.
Applies a pre-computed orthogonal matrix y = matrix·x (e.g. a PCA
rotation from from_data) that is held constant during training.
Orthogonality makes the map volume-preserving, so log_det = 0 exactly
and the inverse is the transpose.
The matrix is stored wrapped in paramax.NonTrainable so
fit_gaussianization_flow and other paramax-aware loops skip it during
gradient descent — without the wrapper Adam drifts the rows off the
orthogonal manifold and sampling
silently collapses while log_prob keeps reporting plausible numbers.
The public matrix property transparently returns the unwrapped
jax.Array so downstream code can still do rot.matrix @ x.
Operates on a single (n_dims,) event; callers vmap over any batch axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ArrayLike
|
Orthogonal rotation matrix of shape |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0 - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det = 0
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import FixedRotation
>>> Q, _ = jnp.linalg.qr(jr.normal(jr.key(0), (3, 3)))
>>> t = FixedRotation(Q)
>>> x = jnp.array([1.0, 2.0, 3.0])
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
>>> x_rec, _ = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/rotation.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
from_data
classmethod
¶
from_data(x: ArrayLike) -> FixedRotation
Build a PCA rotation from the eigenvectors of cov(x).
The rotation is the matrix whose rows are the principal axes of
x, in descending-eigenvalue order, so that y = rotation(x)
is the decorrelating PCA projection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Training data of shape |
required |
Returns:
| Type | Description |
|---|---|
FixedRotation
|
A |
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/rotation.py
LULinearPermute
¶
Bases: AbstractBijection
Invertible linear layer via LU decomposition composed with a fixed permutation.
Applies y = P @ L @ U @ x, where P is a fixed permutation matrix,
L is unit lower-triangular, and U is upper-triangular with a strictly
positive diagonal (parameterised as exp(log_diag)). The log-absolute
determinant reduces to sum(log_diag), avoiding an explicit Jacobian.
Cheaper than OrthogonalRotation in the relevant regime (no Cayley
solve at forward / inverse time) and widely used as the mixing layer in
Neural Spline Flows (Durkan et al. 2019, Neural Spline Flows).
Operates on a single (n_dims,) event; callers vmap over any batch axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
permutation
|
ArrayLike | None
|
Optional permutation of length |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import LULinearPermute
>>> t = LULinearPermute(shape=(3,)) # reverse permutation
>>> x = jnp.array([1.0, 2.0, 3.0])
>>> y, log_det = t.transform_and_log_det(x)
>>> y.shape
(3,)
>>> x_rec, log_det_inv = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/lu.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
Invertible1x1Conv
¶
Bases: AbstractBijection
Invertible 1×1 convolution with LU-parameterised weight (Glow).
Mixes channels/features with an invertible linear map y = W·x,
where W = L·U is stored in LU form: L is lower-triangular with
unit diagonal and U is upper-triangular with strictly positive
diagonal (parameterised as exp(log_diag_u)). This guarantees
invertibility and reduces the log-determinant to the cheap
∑ log_diag_u, avoiding an explicit Jacobian. Introduced as the 1×1
convolution of Glow (Kingma & Dhariwal 2018,
https://arxiv.org/abs/1807.03039).
Operates on a single (n_channels,) event (the channel/feature
vector). Callers vmap over any spatial or batch axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for near-identity initialisation (small off-diagonals). |
required |
n_channels
|
int
|
Number of channels / feature dimensions. |
required |
Shape
- transform_and_log_det:
(n_channels,)→(n_channels,), scalar log_det - inverse_and_log_det:
(n_channels,)→(n_channels,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import Invertible1x1Conv
>>> conv = Invertible1x1Conv(jr.key(0), n_channels=4)
>>> x = jr.normal(jr.key(1), (4,))
>>> y, log_det = conv.transform_and_log_det(x)
>>> y.shape
(4,)
>>> x_rec, log_det_inv = conv.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/conv1x1.py
Orthogonal1x1Conv
¶
Bases: AbstractBijection
Orthogonal 1x1 convolution (Cayley-parameterised orthogonal mixing).
For a (n_channels,) single event, applies an orthogonal matrix Q as
y = Q·x; the inverse is x = Q.T·y; log|det Q| = 0 (volume-
preserving). Callers that operate on (H, W, C) image events should
vmap externally — this matches the single-event convention shared with
Invertible1x1Conv and the rest of the package (see
CLAUDE.md).
Learnable path (default): delegates to OrthogonalRotation's
Cayley parameterisation Q = (I − A)(I + A)^{-1} with skew-symmetric
A. Unlike OrthogonalRotation's zero init (which starts at
Q = I), this class re-initialises the skew parameters with small
Gaussian noise so the initial mixing is near-identity but not exactly
identity — breaking the symmetry that would otherwise pin gradients to
zero for a Householder-like conditioner.
Fixed path (fixed_matrix supplied): holds Q constant at the
supplied matrix. fixed_matrix is wrapped in
paramax.NonTrainable so paramax-aware training loops
(fit_gaussianization_flow among them) and any
eqx.filter(model, eqx.is_inexact_array)-based optimizer-filter
combined with paramax.unwrap treat the matrix as frozen; the
wrapper also applies jax.lax.stop_gradient to the inner array
every time _get_rotation_matrix unwraps the module.
Warning
Decoupled weight decay bypasses NonTrainable. Optimizers that
update parameters from the parameter value (e.g. optax.adamw
with a non-zero weight_decay) will still drift fixed_matrix
away from orthogonality because weight decay does not go through
the gradient path. To keep fixed_matrix bit-identical under
adamw-style training, partition it out of the optimizer state
before updating:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key used for learnable Cayley initialisation. Ignored
when |
required |
n_channels
|
int
|
Number of channels / feature dimensions. |
required |
fixed_matrix
|
ArrayLike | None
|
Optional pre-computed |
None
|
orthogonality_atol
|
float
|
Absolute tolerance for the orthogonality
check on |
1e-05
|
Shape
- Input
x:(n_channels,) - Output
y:(n_channels,) log_det: scalar (always0)
Note
The public surface is a superset of
OrthogonalRotation: the learnable path produces the same
family of orthogonal matrices (same skew_params shape, same
Cayley map), with a more flow-literature-friendly name and a
genuinely-fixed alternative branch. Prefer
OrthogonalRotation if you want the exact zero-init
(Q = I at step 0) used by classic RBIG flows; prefer this
class when small-random init or a pre-computed fixed rotation is
wanted.
Examples:
Learnable (Cayley-parameterised, near-identity init):
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import Orthogonal1x1Conv
>>> conv = Orthogonal1x1Conv(jr.key(0), n_channels=4)
>>> y, log_det = conv.transform_and_log_det(jr.normal(jr.key(1), (4,)))
>>> assert y.shape == (4,)
>>> assert jnp.allclose(log_det, 0.0)
Fixed (pre-computed orthogonal matrix, non-trainable):
>>> Q, _ = jnp.linalg.qr(jr.normal(jr.key(2), (4, 4)))
>>> conv_fixed = Orthogonal1x1Conv(jr.key(0), n_channels=4, fixed_matrix=Q)
>>> y_fixed, _ = conv_fixed.transform_and_log_det(jr.normal(jr.key(3), (4,)))
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/orthogonal_conv1x1.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
OrthogonalConvExponential
¶
Bases: AbstractBijection
Orthogonal convolution via the exponential of a skew-symmetric operator.
Motivation Glow-style image flows need an invertible linear mixer across pixels and channels whose log-determinant is cheap to evaluate. A convolution with a spatially-extended kernel has the desired receptive field, but is not invertible in general. The convolution exponential (Hoogeboom et al., 2020) lifts a possibly non-invertible conv operator \(M\) to
which is always invertible (its inverse is \(\exp(-M)\)). Taking \(M\) skew-symmetric (\(M^\top = -M\)) further makes \(\exp(M)\) an orthogonal matrix, so the bijection is norm-preserving and has Jacobian determinant exactly \(+1\).
Construction 1. Skew-symmetric conv operator. For a \((k_h, k_w, C, C)\) kernel \(K\) indexed relative to its center, the induced circular-convolution Toeplitz operator \(M_K\) acting on flattened images has the transpose
Skew-symmetry \(M_K = -M_K^\top\) therefore holds iff
We enforce this exactly by setting \(K = W - \widetilde{W}\) where
\(\widetilde{W}[i,j,a,b] = W[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a]\)
(flip spatial axes + swap input/output channels). See _skew.
2. Truncated Taylor series. The forward map applies \(\exp(M_K)\) via the \(N\)-term truncation
which we compute with a jax.lax.scan using a separate
Taylor-term accumulator \(t_k\): starting from
\(t_0 = r_0 = x\), we update
so that \(r_N = p_N(M_K)\,x\) (see
_convolution_exponential). The truncation error is
so with n_terms = 8 and ||M|| <= 1 the residual is below
\(1/9! \approx 2.8\times 10^{-6}\).
3. Spectral normalization. To keep \(\|M_K\| \leq 1\), we estimate
the operator norm via image-space power iteration and divide by
\(\max(\sigma, 1)\). Gradients are blocked through the
\(\sigma\)-estimate (jax.lax.stop_gradient), so training does
not differentiate through the power iteration itself — only through the
explicit kernel / sigma rescale. See _spectral_normalize.
4. Log-determinant. Because \(M_K\) is skew-symmetric its trace vanishes, and
exactly. We return jnp.zeros(()) — the truncated operator's log-det
differs from this by \(\mathcal{O}(\|M\|^{N+1}/(N{+}1)!)\), the same
negligible quantity as the round-trip residual.
5. Inverse. Since \(\exp(M)^{-1} = \exp(-M)\) for any \(M\), the inverse applies the same truncated series with negated kernel. Composing \(p_N(-M_K)\circ p_N(M_K)\) leaves an \(\mathcal{O}(\|M\|^{N+1}/(N{+}1)!)\) residual, acceptable for any reasonable \(N\).
Shapes
x, y : (H, W, C)
weight / skew kernel K : (k_h, k_w, C, C) in flowjax/JAX HWIO
log_det : () (scalar, always 0)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
JAX random key for kernel initialization. |
required |
shape
|
tuple[int, int, int]
|
Image shape |
required |
kernel_size
|
int
|
Spatial kernel size (must be a positive odd integer so the kernel has a unique center pixel). |
3
|
n_terms
|
int
|
Number of Taylor-series terms |
8
|
n_power_iterations
|
int
|
Power-iteration steps for the spectral-norm
estimate ( |
2
|
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> key = jr.key(0)
>>> transform = OrthogonalConvExponential(key, shape=(8, 8, 3))
>>> x = jr.normal(key, (8, 8, 3))
>>> y, log_det = transform.transform_and_log_det(x)
>>> x_rec, log_det_inv = transform.inverse_and_log_det(y)
>>> assert jnp.allclose(x, x_rec, atol=1e-4)
>>> assert jnp.isclose(log_det, 0.0)
References
Hoogeboom, E., van den Berg, R., & Welling, M. The Convolution Exponential and Generalized Sylvester Flows, NeurIPS 2020. https://arxiv.org/abs/2006.01910
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/conv_exp.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
transform_and_log_det
¶
Forward map \(y = \exp(M_K)\,x\) and scalar log-det (=0).
Shape
x : (H, W, C)
returns : ((H, W, C), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/conv_exp.py
inverse_and_log_det
¶
Inverse map \(x = \exp(-M_K)\,y\) and scalar log-det (=0).
Uses the identity \(\exp(M)^{-1} = \exp(-M)\) — truncated at
the same n_terms as forward, so the round-trip residual is
O(||M||^{n_terms+1} / (n_terms+1)!).
Shape
y : (H, W, C)
returns : ((H, W, C), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/conv_exp.py
MatrixExponential
¶
Bases: AbstractBijection
Closed-form linear neural flow parameterised by exp(W · t).
Computes
y = exp(W · t) · x + h(t) · b
with exact log-determinant
log |det ∂y/∂x| = t · tr(W).
The map is exactly the identity at t = 0 because exp(0) = I and the
default time gate satisfies h(0) = 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for parameter initialisation. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
w_init_scale
|
float
|
Standard deviation used to initialise |
0.01
|
use_bias
|
bool
|
If |
True
|
time_bias_net
|
_TimeGate | None
|
Optional scalar time gate |
None
|
Shape
- Input
x:(dim,) - Condition: packed time
(1,)fromgauss_flows.pack_time_control - Output
y:(dim,) log_det: scalar()
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import MatrixExponential
>>> from gauss_flows_maps.conditioning import pack_time_control
>>> bij = MatrixExponential(jr.key(0), shape=(3,))
>>> x = jnp.array([1.0, -1.0, 0.5])
>>> y, log_det = bij.transform_and_log_det(x, pack_time_control(0.25))
>>> x_rec, log_det_inv = bij.inverse_and_log_det(y, pack_time_control(0.25))
>>> assert jnp.allclose(x, x_rec)
>>> assert jnp.allclose(log_det + log_det_inv, 0.0)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/matrix_exponential.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
HaarWavelet
¶
Bases: AbstractBijection
Haar wavelet transform bijection (1-D, last axis).
Applies the single-level 1-D Haar wavelet transform along the last axis:
splits each consecutive even/odd pair into its average and half-difference
avg = (even + odd)/2, diff = (even − odd)/2, then concatenates all
averages followed by all differences. This factorises an event into a
coarse (low-pass) and a detail (high-pass) half, as used in multi-scale
flow architectures. Both halves scale by 1/2, so the forward
log-determinant is the constant −n·log 2 where n is the size of
the last axis.
Operates on a single event whose last axis is divisible by 2; the transform acts independently along any leading axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape. The last dimension must be divisible by 2. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last dimension of |
Shape
- transform_and_log_det:
(…, n)→(…, n), scalar log_det = −n·log 2 - inverse_and_log_det:
(…, n)→(…, n), scalar log_det = +n·log 2
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import HaarWavelet
>>> t = HaarWavelet(shape=(4,))
>>> x = jnp.array([1.0, 3.0, 5.0, 9.0])
>>> y, log_det = t.transform_and_log_det(x)
>>> y # [avg0, avg1, diff0, diff1]
Array([ 2., 7., -1., -2.], dtype=float32)
>>> x_rec, _ = t.inverse_and_log_det(y)
>>> bool(jnp.allclose(x, x_rec))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/haar.py
Normalisation layers¶
Normalisation layers rescale and recentre activations between flow blocks, stabilising both training and the conditioning of downstream rotations.
ActNorm
¶
Bases: AbstractBijection
Activation normalization (ActNorm) for image-shaped events.
Per-channel affine normalization with learnable location loc and
positive scale 1e-5 + softplus(u). The scale is stored as the
paramax.Parameterize leaf scale of
gauss_flows_maps.reparam.Reparametrised and starts at 1e-5 + log 2;
paramax.unwrap turns the leaf into the scale itself. The scale and
location are indexed by the trailing (channel) axis and broadcast across
any leading spatial axes, so the log-det of a single event is the
per-channel log-scale sum multiplied by the number of spatial positions.
Introduced as a replacement for batch normalization in Glow (Kingma &
Dhariwal 2018).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
Shape
- transform_and_log_det:
(..., C)→(..., C), scalar log_det - inverse_and_log_det:
(..., C)→(..., C), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import ActNorm
>>> layer = ActNorm(shape=(4, 4, 3))
>>> y, log_det = layer.transform_and_log_det(jnp.ones((4, 4, 3)))
>>> y.shape, log_det.shape
((4, 4, 3), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/actnorm.py
ActNorm1D
¶
Bases: AbstractBijection
Activation normalization (ActNorm) for 1-D events.
The 1-D specialisation of ActNorm used inside the coupling-flow
stack where there are no spatial axes. Applies a per-dimension affine map
y = (x − loc) / scale with positive scale = 1e-5 + softplus(u),
stored as in ActNorm (the leaf scale). Unlike batch normalization,
the parameters are learned and not data-dependent at inference time
(Kingma & Dhariwal 2018).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import ActNorm1D
>>> layer = ActNorm1D(shape=(3,))
>>> y, log_det = layer.transform_and_log_det(jnp.ones((3,)))
>>> y.shape, log_det.shape
((3,), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/actnorm.py
BatchNorm
¶
Bases: AbstractBijection
Invertible batch normalization layer for 1D inputs.
Like every other bijection in this package, transform_and_log_det and
inverse_and_log_det operate on a single event (x.shape == self.shape)
and return a scalar log_det. Callers vectorise over a batch with
jax.vmap / eqx.filter_vmap. Because a single event has no batch
statistics of its own, the layer requires an explicit statistics source
before the forward pass:
- Training: compute batch statistics once outside
vmapvia.with_batch_stats_from_data(batch). The returned layer uses those stats for every per-event call in that forward pass. Inverse roundtrip holds only while the samebatch_statsare in effect. - Evaluation: warm the running EMA via
.update_running_stats_from_batch(...)(outsidejit), then flip to eval mode with.with_running_average(True). Forward/inverse are exact roundtrips regardless of the current batch.
Calling either method without having set one of those two sources raises
RuntimeError — there is no silent fall-back to computing stats from
the single-event input.
Design note: running stats and batch stats live as regular (immutable)
Array fields updated via eqx.tree_at rather than equinox.nn.State.
This keeps the module a plain PyTree that plays nicely with Chain,
flowjax.bijections.Scan, and fit_gaussianization_flow; the
trade-off is that users must thread updated copies back through their loop
explicitly instead of mutating in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
momentum
|
float
|
Exponential moving-average factor for running statistics,
updated as |
0.1
|
eps
|
float
|
Numerical stability term added to the variance. Defaults to
|
1e-05
|
use_running_average
|
bool
|
Whether to use running statistics (evaluation)
rather than batch statistics. Defaults to |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import BatchNorm
>>> batch = jr.normal(jr.key(0), (8, 2))
>>> bn = BatchNorm(shape=(2,)).with_batch_stats_from_data(batch)
>>> y, log_det = bn.transform_and_log_det(batch[0])
>>> y.shape, log_det.shape
((2,), ())
Training step pattern (per batch):
@eqx.filter_value_and_grad
def loss_fn(layer, x):
_, log_dets = jax.vmap(layer.transform_and_log_det)(x)
return -jnp.mean(log_dets)
bn = bn.with_batch_stats_from_data(batch) # set source
loss, grads = loss_fn(bn, batch)
bn = eqx.apply_updates(bn, jax.tree.map(lambda g: -1e-3 * g, grads))
bn = bn.update_running_stats_from_batch(batch) # update EMA
Evaluation:
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
update_running_stats
¶
update_running_stats(batch_mean: ArrayLike, batch_var: ArrayLike) -> BatchNorm
Return a copy with running stats updated (call outside jit).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
update_running_stats_from_batch
¶
update_running_stats_from_batch(batch: ArrayLike) -> BatchNorm
Compute batch statistics from batch (shape (N, *self.shape))
and update running buffers via the EMA.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
with_batch_stats_from_data
¶
with_batch_stats_from_data(batch: ArrayLike) -> BatchNorm
Return a copy using batch statistics computed from batch
(shape (N, *self.shape)). Enables the use_batch_stats code path
and atomically clears use_running_average so the two stats sources
are mutually exclusive.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
with_running_average
¶
with_running_average(use_running_average: bool = True) -> BatchNorm
Return a copy toggling the use of running statistics.
When enabling running-average mode, use_batch_stats is atomically
cleared so the two stats sources are mutually exclusive.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
GeneralizedDivisiveNormalization
¶
Bases: AbstractBijection
Generalized divisive normalization for image-shaped events (..., C).
Couples across the trailing channel axis (a 1x1 GDN) and broadcasts over any
leading spatial axes, so the dense log-det is O(C^3) per spatial position
rather than O((HWC)^3). Parameters use the project's positive
reparameterization, stored as paramax.Parameterize leaves of
gauss_flows_maps.reparam.Reparametrised: beta = beta_floor +
softplus(u) (> 0) and gamma = softplus(v) (>= 0, off-diagonal
only — the diagonal is held at zero so each coordinate is not
self-bounded), optionally symmetrized.
The inverse runs a damped fixed point with an implicit-function-theorem
custom_vjp, so backprop through inverse / sample is exact.
Like any divisive-normalization flow, GDN is a diffeomorphism only onto its
image, not all of R^D: with positive coupling the joint range is bounded, so
keep the coupling moderate (or regularize its spectral norm). A target outside
the image has no preimage; inverse_and_log_det verifies forward(x*) ≈ y
and returns NaN for such targets rather than a silently-wrong finite value, so
out-of-support points surface as NaN log_prob / samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
symmetric_gamma
|
bool
|
If True, symmetrize |
False
|
beta_floor
|
float
|
Floor added after |
1e-05
|
inverse_max_iters
|
int
|
Fixed-point iteration cap. Defaults to 100. |
100
|
inverse_tol
|
float
|
Fixed-point convergence tolerance. Defaults to 1e-6. |
1e-06
|
inverse_damping
|
float
|
Damping |
0.5
|
Shape
- transform_and_log_det:
(..., C)->(..., C), scalar log_det - inverse_and_log_det:
(..., C)->(..., C), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import GeneralizedDivisiveNormalization
>>> layer = GeneralizedDivisiveNormalization(shape=(4, 4, 3))
>>> y, log_det = layer.transform_and_log_det(jnp.ones((4, 4, 3)))
>>> y.shape, log_det.shape
((4, 4, 3), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/gdn.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | |
GeneralizedDivisiveNormalization1D
¶
Bases: AbstractBijection
1-D Generalized divisive normalization with full D x D coupling.
The 1-D specialization of GeneralizedDivisiveNormalization for use inside
gaussianization_flow / iterative_rbig stacks, where there are no
spatial axes. Couples the whole (D,) event, so the exact log-det is
O(D^3) — practical for moderate D. Raises on non-1-D shape (matches
the ActNorm1D convention).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
symmetric_gamma
|
bool
|
If True, symmetrize |
False
|
beta_floor
|
float
|
Floor added after |
1e-05
|
inverse_max_iters
|
int
|
Fixed-point iteration cap. Defaults to 100. |
100
|
inverse_tol
|
float
|
Fixed-point convergence tolerance. Defaults to 1e-6. |
1e-06
|
inverse_damping
|
float
|
Damping |
0.5
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(D,)->(D,), scalar log_det - inverse_and_log_det:
(D,)->(D,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import GeneralizedDivisiveNormalization1D
>>> layer = GeneralizedDivisiveNormalization1D(shape=(3,))
>>> y, log_det = layer.transform_and_log_det(jnp.ones((3,)))
>>> y.shape, log_det.shape
((3,), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/gdn.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
Periodic layers¶
Periodic layers operate on angular (circular) coordinates living on \([-\pi, \pi)\), for flows on the torus or sphere.
PeriodicShift
¶
Bases: AbstractBijection
Learnable circular shift on selected periodic dimensions.
Adds a learnable per-index offset to the chosen dimensions and re-wraps the
result back into [−bound, bound]. The map is a translation on the
circle, so its Jacobian determinant is 1 and log_det = 0. Non-periodic
dimensions pass through unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind
|
Iterable[int]
|
Indices of periodic dimensions to shift. Must be unique and lie in
|
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
bound
|
float
|
Half-width of the periodic interval. Defaults to |
pi
|
shift_init
|
Array | float
|
Initial shift. Either a scalar (broadcast to every index) or
a 1-D array of length |
0.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import PeriodicShift
>>> shift = PeriodicShift(ind=(0,), shape=(2,), shift_init=0.25)
>>> y, log_det = shift.transform_and_log_det(jnp.array([1.0, 0.5]))
>>> y.shape, float(log_det)
((2,), 0.0)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/periodic/shift.py
PeriodicWrap
¶
Bases: AbstractBijection
Canonical projection of selected dimensions onto [−bound, bound].
Wraps the chosen periodic dimensions into the canonical interval
[−bound, bound] and leaves all other dimensions untouched.
Warning
This subclasses flowjax.bijections.AbstractBijection for API
compatibility but is not a true bijection on ℝ — it is a
many-to-one canonical projection. x and x + 2·bound·k collapse
to the same canonical value, and inverse_and_log_det returns that
same wrapped value (not the original x) with log_det = 0.
Composing this inside a flowjax.distributions.Transformed or
SurVAEFlow will give incorrect log-densities if the upstream
samples are not already in [−bound, bound], because the
change-of-variables formula assumes invertibility. Use this layer only
as a leading-edge canonicaliser for raw angles, never as an inner layer
in a density model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind
|
Iterable[int]
|
Indices of periodic dimensions to wrap. Must lie in
|
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
bound
|
float
|
Half-width of the periodic interval. Defaults to |
pi
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det:
(n_dims,)→(n_dims,), scalar log_det (returns the wrapped value, not the originalx; see warning)
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import PeriodicWrap
>>> wrap = PeriodicWrap(ind=(0,), shape=(2,))
>>> y, log_det = wrap.transform_and_log_det(jnp.array([3.5, 0.2]))
>>> bool(y[0] >= -jnp.pi and y[0] < jnp.pi) # dim 0 wrapped; dim 1 kept
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/periodic/wrap.py
Reshape layers¶
Squeeze
¶
Bases: AbstractBijection
Volume-preserving squeeze that trades spatial extent for channels.
Reshapes a single event so that resolution along the leading axis is halved
and the trailing (channel) axis is correspondingly enlarged, exposing more
structure to subsequent channel-wise layers. The map is a pure reshape, so
it is exactly invertible and volume-preserving (log_det = 0). Commonly
used to build multi-scale normalizing-flow architectures (Dinh et al. 2017).
Three regimes by rank of shape:
- 1-D
(n,)withneven →(n // 2, 2): split into adjacent pairs. - 2-D
(H, C)withHeven →(H // 2, 2·C): fold pairs of rows into the channel axis. - Higher rank: pass through unchanged (identity reshape).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the leading axis of a 1-D or 2-D |
Shape
- transform_and_log_det:
shape→out_shape, scalar log_det (0) - inverse_and_log_det:
out_shape→shape, scalar log_det (0)
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.bijections import Squeeze
>>> layer = Squeeze(shape=(4, 3))
>>> y, log_det = layer.transform_and_log_det(jnp.ones((4, 3)))
>>> y.shape, float(log_det)
((2, 6), 0.0)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/reshape/squeeze.py
Classic residual flows¶
Residual flows apply a low-rank perturbation \(x + u\,h(w^\top x + b)\). The determinant follows
from the matrix-determinant lemma, so log_det stays cheap despite the full-rank coupling
across coordinates.
PlanarFlow
¶
Bases: AbstractBijection
Planar normalizing-flow bijection (Rezende & Mohamed 2015).
Applies the rank-1 perturbation y = x + û · tanh(w · x + b), where û
is the reparameterisation of the raw vector u that guarantees
w · û ≥ −1 — the invertibility condition from the original paper. The
log-abs-det collapses to log|1 + (û · w)·(1 − tanh²(w·x + b))|.
The forward map has no closed-form inverse, so this layer is generative-only:
use it in the sampling / variational-inference direction via
flowjax.distributions.Transformed.sample_and_log_prob.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key used to initialise |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
scale_init
|
float
|
Std of the Gaussian used to initialise |
0.01
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NotImplementedError
|
From |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det: not implemented (raises)
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import PlanarFlow
>>> flow = PlanarFlow(jr.key(0), shape=(3,))
>>> y, log_det = flow.transform_and_log_det(jnp.ones((3,)))
>>> y.shape, log_det.shape
((3,), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/classic/planar.py
SylvesterFlow
¶
Bases: AbstractBijection
Sylvester normalizing flow (van den Berg et al. 2018).
Generalises PlanarFlow from a rank-1 to a rank-M (M ≤ D)
perturbation:
``y = x + Q · R̃ · tanh(R · Qᵀ · x + b)``
where Q ∈ ℝ^{D×M} has orthonormal columns (parameterised via M
Householder reflections applied to I_D), and R, R̃ are M×M
upper-triangular matrices whose diagonals are constrained with tanh to
keep |diag(R) · diag(R̃)| < 1 — sufficient for invertibility. Via
Sylvester's determinant identity the log-abs-det reduces to a sum over the
M diagonal entries, costing O(M) rather than O(D).
The forward map has no closed-form inverse, so this layer is generative-only:
use it in the sampling / variational-inference direction via
flowjax.distributions.Transformed.sample_and_log_prob.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key used to initialise all parameters. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
rank
|
int | None
|
Rank |
None
|
scale_init
|
float
|
Std of the Gaussian used to initialise the Householder
vectors (offset from the identity), the strict upper-triangular
entries of |
0.01
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
NotImplementedError
|
From |
Shape
- transform_and_log_det:
(n_dims,)→(n_dims,), scalar log_det - inverse_and_log_det: not implemented (raises)
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import SylvesterFlow
>>> flow = SylvesterFlow(jr.key(0), shape=(4,), rank=2)
>>> y, log_det = flow.transform_and_log_det(jnp.ones((4,)))
>>> y.shape, log_det.shape
((4,), ())
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/classic/sylvester.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
Continuous (FFJORD) flows¶
A continuous normalizing flow replaces the discrete layer stack with an ODE \(\dot{x} = v_\theta(t, x)\) integrated over \(t\in[0,1]\). The log-density change accumulates the instantaneous trace of the Jacobian,
estimated exactly (small \(D\)) or with the Hutchinson trace estimator. The Diffeq* networks
parameterise \(v_\theta\), the Time* nets embed \(t\), and pack_time_control bundles the time
and optional control signal into the condition FlowJax threads through the solver.
FFJORD
¶
Bases: AbstractBijection
Continuous normalizing flow via a learned ODE.
FFJORD integrates the augmented dynamics
dx/dt = f(t, x, condition)
dlog|det J|/dt = tr(∂f/∂x)
over a time span [t0, t1] using diffrax. The trace term is
gaussx.trace of the Jacobian operator ∂f/∂x, applied by forward-mode
JVPs: either exact, by materialising the Jacobian (cost O(dim) JVPs per
ODE step — use for small dim or validation), or stochastic, with
Hutchinson's estimator tr(A) ≈ (1/N) ∑ᵢ zᵢᵀ A zᵢ (cost
O(n_hutchinson_samples) JVPs per step).
Hutchinson probes are fixed per FFJORD instance: the trace_key is
stored once at construction and reused across every call to
transform_and_log_det / inverse_and_log_det and across every
internal ODE step. This is the "fixed noise" FFJORD variant (Grathwohl
et al. 2019, Appendix C) — it makes log_det a deterministic function
of parameters and stabilises gradient optimisation. To draw new probes,
construct a new FFJORD with a freshly split key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for the default vector field and Hutchinson probes. |
required |
shape
|
tuple[int, ...]
|
Event shape |
required |
vector_field
|
_VectorField | None
|
Module with signature
|
None
|
control_dim
|
int
|
Size of the packed control vector |
0
|
t_span
|
tuple[float, float]
|
Integration interval |
(0.0, 1.0)
|
solver
|
_SolverName
|
ODE solver name. |
'tsit5'
|
adjoint
|
_AdjointName
|
Diffrax adjoint name. |
'recursive_checkpoint'
|
rtol
|
float
|
Relative tolerance for adaptive solvers. |
1e-05
|
atol
|
float
|
Absolute tolerance for adaptive solvers. |
1e-05
|
divergence_mode
|
_DivergenceMode
|
|
'hutchinson'
|
n_hutchinson_samples
|
int
|
Number of Hutchinson probes. |
1
|
probe_distribution
|
_ProbeDistribution
|
Probe distribution for Hutchinson estimation. |
'rademacher'
|
Shape
- Input
x/y:(dim,) - Condition:
control_dim == 0:cond_shape = None— no condition accepted (unconditional FFJORD; diffrax supplies the ODE time).control_dim > 0:(1 + control_dim,)packed as[t_query, c]viagauss_flows.pack_time_control.
- Output
log_det: scalar()
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.flows import DiffeqMLP, FFJORD
>>> from gauss_flows_maps.conditioning import pack_time_control
>>> # Conditional FFJORD — packed (t_query, c) condition.
>>> vf = DiffeqMLP(jr.key(1), in_dim=2, control_dim=1, hidden=(8, 8))
>>> bij = FFJORD(jr.key(0), shape=(2,), vector_field=vf, control_dim=1)
>>> x = jnp.array([0.1, -0.2])
>>> cond = pack_time_control(0.5, jnp.array([1.0]))
>>> y, log_det = bij.transform_and_log_det(x, cond)
>>> x_rec, log_det_inv = bij.inverse_and_log_det(y, cond)
>>> assert jnp.allclose(x, x_rec, atol=1e-4)
>>> assert jnp.allclose(log_det + log_det_inv, 0.0, atol=1e-4)
>>> # Unconditional FFJORD — no condition required.
>>> bij0 = FFJORD(jr.key(2), shape=(2,), control_dim=0)
>>> assert bij0.cond_shape is None
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/continuous/ffjord.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
DiffeqMLP
¶
Bases: Module
MLP vector field f(ode_time, x, condition) via concatenation.
For conditional models this concatenates the ODE time, the packed conditioning time, the state, and the control vector. For unconditional models it concatenates only the ODE time and state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for network initialisation. |
required |
in_dim
|
int
|
Event dimension |
required |
control_dim
|
int
|
Size of the optional control vector |
0
|
hidden
|
int | Sequence[int]
|
Hidden-layer widths. |
(64, 64)
|
activation
|
Callable[[Array], Array]
|
Non-linearity applied after each hidden layer. |
tanh
|
Shape
- Input
ode_time:()or(1,) - Input
x:(dim,) - Input
condition:(1 + control_dim,)orNonewhencontrol_dim == 0 - Output:
(dim,)
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.flows import DiffeqMLP
>>> from gauss_flows_maps.conditioning import pack_time_control
>>> net = DiffeqMLP(jr.key(0), in_dim=3, control_dim=2, hidden=(16, 16))
>>> x = jnp.ones((3,))
>>> cond = pack_time_control(0.5, jnp.array([1.0, -1.0]))
>>> net(0.25, x, cond).shape
(3,)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/nn/diffeq_nets.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
DiffeqConcat
¶
Bases: Module
MLP vector field with a learnable scalar time embedding.
This variant replaces the raw ODE time with time_net(ode_time) before
concatenation, while preserving the same packed-condition API as
DiffeqMLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for the MLP and default time net. |
required |
in_dim
|
int
|
Event dimension |
required |
control_dim
|
int
|
Size of the optional control vector |
0
|
hidden
|
int | Sequence[int]
|
Hidden-layer widths. |
(64, 64)
|
time_net
|
_TimeNet | None
|
Optional scalar time embedding. When omitted, a
|
None
|
activation
|
Callable[[Array], Array]
|
Non-linearity applied after each hidden layer. |
tanh
|
Shape
- Input
ode_time:()or(1,) - Input
x:(dim,) - Input
condition:(1 + control_dim,)orNonewhencontrol_dim == 0 - Output:
(dim,)
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.flows import DiffeqConcat
>>> from gauss_flows_maps.conditioning import pack_time_control
>>> net = DiffeqConcat(jr.key(0), in_dim=3, control_dim=2, hidden=(16, 16))
>>> x = jnp.ones((3,))
>>> cond = pack_time_control(0.5, jnp.array([1.0, -1.0]))
>>> net(0.25, x, cond).shape
(3,)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/nn/diffeq_nets.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
TimeIdentity
¶
Bases: Module
Identity time gate g(t) = t.
Shape
- Input
t:()or(1,) - Output: scalar
()
Examples:
>>> from gauss_flows_maps.bijections import TimeIdentity
>>> gate = TimeIdentity()
>>> float(gate(0.25))
0.25
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/nn/time_net.py
TimeTanh
¶
Bases: Module
Tanh time gate with g(0) = 0 by construction.
The gate is
g(t) = Σᵢ wᵢ tanh(aᵢ t)
so every feature vanishes exactly at t = 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for parameter initialisation. |
required |
embedding_dim
|
int
|
Number of tanh features. |
16
|
Shape
- Input
t:()or(1,) - Output: scalar
()
Examples:
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import TimeTanh
>>> gate = TimeTanh(jr.key(0), embedding_dim=8)
>>> float(gate(0.0))
0.0
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/nn/time_net.py
TimeFourier
¶
Bases: Module
Fourier-feature time gate with g(0) = 0 by construction.
The gate is
g(t) = Σᵢ wᵢ sin(ωᵢ t)
so every feature vanishes exactly at t = 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for parameter initialisation. |
required |
embedding_dim
|
int
|
Number of sinusoidal features. |
16
|
Shape
- Input
t:()or(1,) - Output: scalar
()
Examples:
>>> import jax.random as jr
>>> from gauss_flows_maps.bijections import TimeFourier
>>> gate = TimeFourier(jr.key(0), embedding_dim=8)
>>> float(gate(0.0))
0.0
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/nn/time_net.py
pack_time_control
¶
Pack time and optional control vector into one condition array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ArrayLike
|
Scalar time value or an array with shape |
required |
control
|
ArrayLike | None
|
Optional control vector with shape |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Packed condition with shape |
Array
|
|
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.conditioning import pack_time_control
>>> pack_time_control(0.5).shape
(1,)
>>> pack_time_control(0.5, jnp.array([1.0, 2.0])).shape
(3,)
>>> pack_time_control(jnp.array([0.0, 1.0]), jnp.ones((2, 2))).shape
(2, 3)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioning.py
unpack_time_control
¶
Unpack a packed (time, control) condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition
|
Array
|
Packed condition with shape |
required |
control_dim
|
int
|
Size of the control vector. Use |
0
|
Returns:
| Type | Description |
|---|---|
Array
|
A tuple |
Array | None
|
|
Examples:
>>> import jax.numpy as jnp
>>> from gauss_flows_maps.conditioning import unpack_time_control
>>> t, control = unpack_time_control(jnp.array([0.5, 1.0, 2.0]), control_dim=2)
>>> t.shape, control.shape
((1,), (2,))
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioning.py
time_control_cond_shape
¶
Return the FlowJax cond_shape for packed (time, control) inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
control_dim
|
int
|
Size of the control vector. Use |
0
|
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
A one-tuple |
Examples:
>>> from gauss_flows_maps.conditioning import time_control_cond_shape
>>> time_control_cond_shape()
(1,)
>>> time_control_cond_shape(3)
(4,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioning.py
Conditional wrappers¶
Conditioner modulates an unconditional bijection \(f\) by a context \(\vect{c}\) through the shared AffineModulation, \(\vect{y} = \gvect{\gamma}(\vect{c}) \odot f(\vect{x}) + \gvect{\beta}(\vect{c})\) with log-Jacobian \(\log |\det \partial f / \partial \vect{x}| + \sum_i \log \gamma_i(\vect{c})\). The modulation's readout starts at zero, so the layer equals \(f\) for every context at initialisation and the step-0 likelihood is the unconditional flow's.
Conditioner
¶
Bases: AbstractBijection
Wrap an unconditional bijection with a context-amortised affine modulation.
For an unconditional bijection f and a context c, the layer computes
y = γ(c) ⊙ f(x) + β(c), log |det ∂y/∂x| = log |det ∂f/∂x| + Σᵢ log γᵢ(c),
where (γ, log γ, β) = modulation.modulation(c) come from the shared
AffineModulation of gauss_flows_maps.conditioning. Its readout starts at
zero weight and bias (0, r₀), so γ = 1 and β = 0 for every c and the
layer starts as f itself.
Use this for transforms that cannot take a condition (rotations,
normalisations, fixed orthogonal layers). Coupling layers and other transforms
that take a condition natively get cond_dim directly instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key for the modulation's init; unused with a pre-built
|
required |
inner
|
AbstractBijection
|
Any bijection whose |
required |
cond_dim
|
int
|
Context size |
required |
nn_width
|
int
|
Width of the modulation's trunk. |
64
|
nn_depth
|
int
|
Number of trunk layers; |
2
|
activation
|
Callable[[Array], Array]
|
Activation after each trunk layer. |
tanh
|
readout_scale
|
float
|
Factor on the readout's default weight; the default |
0.0
|
scale_map
|
_FlowScaleMap
|
The positive scale map |
'exp'
|
modulation
|
AffineModulation | None
|
A pre-built |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Shape
transform_and_log_det: x (D,) and condition (K,) to y (D,)
and a scalar log-determinant; inverse_and_log_det the same in reverse.
Examples:
At init the layer equals its inner bijection for every context:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.conditioning import Conditioner
>>> from gauss_flows_maps.bijections import OrthogonalRotation
>>> rot = OrthogonalRotation(shape=(4,))
>>> bij = Conditioner(jr.key(1), inner=rot, cond_dim=2)
>>> x = jr.normal(jr.key(2), (4,))
>>> y, log_det = bij.transform_and_log_det(x, jnp.array([0.5, -0.5]))
>>> bool(jnp.allclose(y, rot.transform(x)))
True
Round trip with a small non-zero readout and a bounded scale:
>>> bij = Conditioner(
... jr.key(1), inner=rot, cond_dim=2, readout_scale=1e-2,
... scale_map="one_plus_tanh",
... )
>>> y, log_det = bij.transform_and_log_det(x, jnp.array([0.5, -0.5]))
>>> x_rec, log_det_inv = bij.inverse_and_log_det(y, jnp.array([0.5, -0.5]))
>>> bool(jnp.allclose(x, x_rec, atol=1e-5))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/conditioner.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | |