Surjections & Stochastic transforms¶
The SurVAE framework generalises a normalizing flow
beyond exact bijections. A surjection is deterministic in one direction and
stochastic (or many-to-one) in the other; a stochastic transform is random in both. Both
relax the change-of-variables equality into a bound, contributing a likelihood
contribution term in place of an exact log_det:
which is exact when the inverse direction is deterministic. This lets a flow change
dimensionality (augment/slice, max-pool), encode invariances (abs, sort), or insert
VAE-style stochastic layers — while still composing inside a SurVAEFlow.
Surjection and stochastic methods take an explicit key (the direction may sample) and follow
the single-event convention; the SurVAEFlow container vmaps log_prob / sample over
any leading sample_shape.
Base classes¶
AbstractSurjection
¶
Bases: Module
Base class for SurVAE surjective transforms.
Subclasses set the three class-level flags so SurVAEFlow (and
other containers) can decide whether log_prob is exact or only an
evidence lower bound:
Attributes:
| Name | Type | Description |
|---|---|---|
stochastic_forward |
bool
|
|
stochastic_inverse |
bool
|
|
lower_bound |
bool
|
|
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/base.py
forward_and_log_det
abstractmethod
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Compute z = f(x) and log |det J_f(x)| (or its bound).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/base.py
inverse_and_log_det
abstractmethod
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Compute x = f^{-1}(z) and log |det J_{f^{-1}}(z)| (or its bound).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/base.py
AbstractStochastic
¶
Bases: AbstractSurjection
Base class for transforms that are stochastic in both directions.
Canonical example: a VAE layer where forward samples from
q(z | x) and inverse samples from p(x | z). log_prob
returns an ELBO contribution.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/base.py
Surjections¶
SimpleAbsSurjection
¶
Bases: AbstractSurjection
Elementwise absolute-value surjection with a random-sign inverse.
Inference-style surjection (Nielsen et al. 2020 §3.1). The forward map is deterministic; the inverse draws a uniform sign per dimension:
forward: z = |x| (deterministic)
inverse: s ~ Bernoulli(½)^D, x = (2s − 1) · z
The log-det contribution is the entropy of the uniform sign prior:
log_det = log p(s) = −D · log 2, D = prod(shape)
This is exact, not a bound: every collapsed pair {+x, −x} has equal
prior mass, so the inverse uniform sampler matches the true posterior over
pre-images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape of a single input (no leading batch — see the project-wide single-event convention). |
required |
Shape
- Input
x:shape - Output
z:shape(non-negative) log_det: scalar (shape())
Examples:
Single-event call:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.surjections import SimpleAbsSurjection
>>>
>>> surj = SimpleAbsSurjection((3,))
>>> z, log_det = surj.forward_and_log_det(
... jnp.array([1.0, -2.0, 3.0]), jr.key(0)
... )
>>> # z == [1., 2., 3.]; log_det == -3 * log(2)
Inside a flow, see gauss_flows_models.flows.SurVAEFlow, whose tests
compose this layer with a base distribution.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/abs.py
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Compute z = |x| and the constant log-det -D · log 2.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/abs.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample x = ±z element-wise with uniform signs.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/abs.py
SimpleSortSurjection
¶
Bases: AbstractSurjection
Sort along one axis; invert via independent per-slice permutations.
Inference-style surjection. The forward map sorts each 1D slice along
axis independently — jnp.sort(x, axis=axis) is per-slice — so the
inverse draws an independent uniform permutation σ_i ∈ S_{shape[axis]} for
each of the n_slices = prod(shape) // shape[axis] slices and applies it
along axis:
forward: z = sort(x, axis) (deterministic, per-slice)
inverse: σ_i ~ Uniform(S_n) for i ∈ {0, …, n_slices − 1}
x_i = z_i ∘ σ_i
The log-det contribution is the joint entropy of the n_slices independent uniform permutation priors:
log_det = −n_slices · log(shape[axis]!)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape of a single input (no leading batch). |
required |
axis
|
int
|
Axis to sort along (default |
0
|
Shape
- Input
x:shape - Output
z:shape(sorted alongaxis) log_det: scalar (shape())
Examples:
1D event:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.surjections import SimpleSortSurjection
>>>
>>> surj = SimpleSortSurjection((4,))
>>> z, _ = surj.forward_and_log_det(
... jnp.array([3.0, 1.0, 4.0, 1.5]), jr.key(0)
... )
>>> # z == [1., 1.5, 3., 4.]; log_det == -log(4!)
2D event sorted along axis=0 (each column is its own slice):
>>> surj2 = SimpleSortSurjection((4, 3), axis=0)
>>> # n_slices = 3 (the W axis); log_det == -3 * log(4!)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/sort.py
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 | |
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sort each slice along axis; return (z, -n_slices · log(D!)).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/sort.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Apply an independent uniform permutation to each slice along axis.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/sort.py
SimpleMaxPoolSurjection2d
¶
Bases: AbstractSurjection
2D max-pooling surjection with a learned residual decoder.
Inference-style surjection on a single image event x ∈ ℝ^{H × W × C}.
Each pool window of shape (pool_size, pool_size) collapses to its max,
and the pool_area − 1 non-max values are scored by a conditional
decoder. With pool_area = pool_size² and
N = (H/pool_size) · (W/pool_size) · C pooled positions:
forward: z[h, w, c] = max(x[h·ps:(h+1)·ps, w·ps:(w+1)·ps, c])
residuals = z − {non-max values per pool} (≥ 0)
log_det = log q(residuals | z) − N · log(pool_area)
inverse: k ~ Uniform({0..pool_area−1})^N (argmax slot)
resid ~ q(· | z) (decoder)
x = unpool(z, resid, k)
The −N · log(pool_area) term is the entropy of the uniform prior on the
argmax location k; it is marginalised out of the log-det. The decoder
contribution is exact under the residual parameterisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Image event shape |
required |
decoder
|
ConditionalDistribution
|
Object satisfying |
required |
pool_size
|
int
|
Spatial pool size (default |
2
|
Shape
- Input
x:(H, W, C) - Output
z:(H/pool_size, W/pool_size, C) log_det: scalar (shape())
Examples:
my_decoder must implement the ConditionalDistribution
protocol (see _src/_protocols.py); it maps a pooled image
z of shape (4, 4, 3) to residuals of shape (4, 4, 3, 3):
import jax.numpy as jnp
import jax.random as jr
from gauss_flows_maps.surjections import SimpleMaxPoolSurjection2d
surj = SimpleMaxPoolSurjection2d((8, 8, 3), my_decoder, pool_size=2)
z, log_det = surj.forward_and_log_det(jnp.zeros((8, 8, 3)), jr.key(0))
# z.shape == (4, 4, 3); residuals.shape == (4, 4, 3, 3) (pool_area-1).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/pool.py
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 | |
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Pool x to z; return (z, log q(residuals|z) - N·log(pool_area)).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/pool.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample residuals + uniform argmax slot; reconstruct x.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/pool.py
Augment
¶
Bases: AbstractSurjection
Generative surjection that appends conditionally sampled dimensions.
Forward draws augment_size extra dims from encoder conditioned on
the input and concatenates them; inverse drops the augmented tail:
forward: z_aug ~ q(· | x) (encoder sample)
z = concat([x, z_aug])
log_det = − log q(z_aug | x)
inverse: x = z[:x_size] (deterministic drop)
Because the forward direction is stochastic, the contribution to
log_prob is an ELBO over the encoder's samples, not an exact density.
Use Augment to give a flow extra latent dimensions to model multi-modal
structure that would not fit in the data dim alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
ConditionalDistribution
|
Object satisfying |
required |
x_size
|
int
|
Size of the data input event. Determines |
required |
augment_size
|
int
|
Number of latent dims to append. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...]
|
|
Shape
- Input
x:(x_size,) - Output
z:(x_size + augment_size,) log_det: scalar (shape())
Examples:
Augment a 2-D data event with a 2-D learned latent:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.distributions import Normal
>>> from gauss_flows_maps.surjections import Augment
>>>
>>> enc = Normal(jnp.zeros(2))
>>> surj = Augment(encoder=enc, x_size=2, augment_size=2)
>>> x = jnp.array([0.5, -0.3])
>>> z, log_det = surj.forward_and_log_det(x, jr.key(0))
>>> # z.shape == (4,); log_det == -Normal(0,1).log_prob(z[2:]).sum()
Inside a flow, see gauss_flows_models.flows.SurVAEFlow, whose tests
compose this layer with a base distribution.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/augment.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 | |
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample z_aug from encoder; z = concat([x, z_aug]).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/augment.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Drop the augmented tail; deterministic, log_det = 0.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/augment.py
Slice
¶
Bases: AbstractSurjection
Inference surjection that drops the trailing dimensions of a 1D event.
Forward keeps the first keep_dims entries of x and scores the dropped
tail under decoder conditioned on the kept prefix:
forward: z = x[:keep_dims] (deterministic)
log_det = log q(x[keep_dims:] | z)
inverse: dropped ~ q(· | z) (decoder sample)
x = concat([z, dropped])
The forward log-det contribution is exact when the decoder q matches the
true conditional density of the dropped dims given the kept dims; otherwise
it is a (typically loose) lower bound on log p(x).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keep_dims
|
int
|
Number of leading entries to keep. Must be positive. |
required |
decoder
|
ConditionalDistribution
|
Object satisfying |
required |
Shape
- Input
x:(D,)(withD > keep_dims) - Output
z:(keep_dims,) log_det: scalar (shape())
Note
Unlike most transforms, Slice does not expose a shape
attribute. Its forward-input dim D is determined by whatever the
upstream transform produces — it is a chain-context property, not a
constructor parameter, so there is no fixed shape to declare. The
full data shape lives on SurVAEFlow.data_shape instead.
Examples:
Score the dropped tail under a unit Gaussian decoder:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.distributions import Normal
>>> from gauss_flows_maps.surjections import Slice
>>>
>>> dec = Normal(jnp.zeros(2)) # decoder for the dropped 2 dims
>>> surj = Slice(keep_dims=3, decoder=dec)
>>> x = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0])
>>> z, log_det = surj.forward_and_log_det(x, jr.key(0))
>>> # z == [1., 2., 3.]; log_det == sum of Normal(0,1).log_prob([4., 5.])
Inside a flow, see gauss_flows_models.flows.SurVAEFlow, whose tests
compose this layer with a base distribution.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/slice.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 | |
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Drop trailing dims; return (kept, log q(dropped | kept)).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/slice.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample the missing tail from the decoder; concat back.
Returns log q(dropped_sampled | z) to mirror
forward_and_log_det and match SimpleMaxPoolSurjection2d's
inverse convention. SurVAEFlow.log_prob doesn't consume this value
(it only uses forward_and_log_det); the consistent return shape is
for callers using the inverse standalone (e.g. ELBO computations).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/surjections/dimension/slice.py
Stochastic transforms¶
VAE
¶
Bases: AbstractStochastic
Variational autoencoder as a SurVAE stochastic transform.
Wraps an encoder q(z | x) and decoder p(x | z) so that a VAE
becomes a single link in a SurVAEFlow chain. Stacking N of
these yields an N-level HVAE with no bespoke container code — the
chain machinery already handles key splitting and ELBO accumulation.
Forward (data → latent, used inside log_prob):
The forward log_det is exactly the per-event ELBO contribution of a
single stochastic lift (Nielsen et al. 2020, eq. 7): together with the
base-distribution term log p(z) it yields the standard ELBO
E_q[log p(x|z) + log p(z) − log q(z|x)].
Inverse (latent → data, used for generation):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder
|
ConditionalDistribution
|
Conditional distribution |
required |
decoder
|
ConditionalDistribution
|
Conditional distribution |
required |
Shape
- Input
x:encodercondition shape - Output
z:encodersample shape log_det: scalar (shape())
Note
Unconditional distributions such as flowjax.distributions.Normal
do not satisfy the ConditionalDistribution protocol
(they have no condition= kwarg). A small wrapper that amortises
the parameters on the conditioning variable is required — see the
DiagGaussianConditional helper used in
tests/test_transforms_stochastic.py for a minimal reference.
Examples:
Build the layer from a reparameterised encoder and a decoder; to form a
one-level VAE flow, give it to gauss_flows_models.flows.SurVAEFlow
with a standard Normal prior:
from gauss_flows_maps.surjections import VAE
encoder = MyConditionalGaussian(...) # q(z|x), reparameterized
decoder = MyConditionalGaussian(...) # p(x|z)
vae = VAE(encoder, decoder)
References
Nielsen, Jaini, Hoogeboom, Winther, Welling. SurVAE Flows: Surjections to Bridge the Gap between VAEs and Flows, NeurIPS 2020.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/stochastic/vae.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 | |
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample z ~ q(z | x) and return log p(x | z) − log q(z | x).
Uses a single reparameterized sample for both the returned z and
the ELBO estimate — the caller's vmap over a batch axis amortizes
the Monte Carlo variance.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/stochastic/vae.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample x ~ p(x | z); inverse log-det is zero by convention.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/stochastic/vae.py
StochasticPermutation
¶
Bases: AbstractStochastic
Uniform random permutation along one axis (zero log-det).
Both directions draw a fresh permutation σ of {0, …, n−1} (with
n = shape[axis]) and apply it along axis. The forward and inverse
sampling distributions are identical:
q_forward(z | x) = q_inverse(x | z) = 1 / n! for each σ ∈ S_n
so the entropy contribution to log_prob cancels and log_det = 0 in
both directions. The transform is volume-preserving in the discrete sense:
every output is a permutation of the input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
Event shape of a single input (no leading batch dim — callers
vmap externally; see the project-wide single-event convention in
|
required |
axis
|
int
|
Axis along which to permute (default |
0
|
Shape
- Input
x:shape - Output
z:shape(a permutation ofxalongaxis) log_det: scalar (shape())
Examples:
Permute a 1D event:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_maps.surjections import StochasticPermutation
>>>
>>> surj = StochasticPermutation((4,))
>>> z, log_det = surj.forward_and_log_det(jnp.arange(4.0), jr.key(0))
>>> # z is a permutation of [0., 1., 2., 3.]; log_det == 0.
Permute the columns of a 2D event:
>>> surj2 = StochasticPermutation((3, 4), axis=1)
>>> z, _ = surj2.forward_and_log_det(jnp.zeros((3, 4)), jr.key(0))
>>> # z.shape == (3, 4); same permutation applied to every row.
Inside a flow, see gauss_flows_models.flows.SurVAEFlow, whose tests
compose this layer with a base distribution.
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/stochastic/permutation.py
forward_and_log_det
¶
forward_and_log_det(x: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample z = σ_forward(x) with σ_forward ~ Uniform(S_n).
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/stochastic/permutation.py
inverse_and_log_det
¶
inverse_and_log_det(z: ArrayLike, key: PRNGKeyArray, cond: Array | None = None) -> tuple[Array, Array]
Sample x = σ_inverse(z) with σ_inverse ~ Uniform(S_n).