Skip to content

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

\[ \log p_X(x) \;=\; \log p_Z\!\big(f(x)\big) \;+\; \log\left|\det \frac{\partial f}{\partial x}\right|, \]

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 (n_dims,). Only 1D inputs are supported.

required
cond_dim int | None

If not None, the layer expects a 1-D condition of shape (cond_dim,) at call time and concatenates it onto the inner MLP's input. Defaults to None (unconditional).

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 is not 1D, or cond_dim is a non-positive int.

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_dim set, also takes a condition of 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
class AffineCoupling(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.

    Args:
        key: JAX random key for conditioner MLP initialisation.
        shape: Event shape ``(n_dims,)``. Only 1D inputs are supported.
        cond_dim: If not ``None``, the layer expects a 1-D ``condition`` of
            shape ``(cond_dim,)`` at call time and concatenates it onto the
            inner MLP's input. Defaults to ``None`` (unconditional).
        nn_width: Hidden layer width of the conditioner MLP. Defaults to 64.
        nn_depth: Depth of the conditioner MLP. Defaults to 2.

    Raises:
        ValueError: If ``shape`` is not 1D, or ``cond_dim`` is a non-positive int.

    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_dim`` set, also takes a ``condition`` of 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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    _coupling: AbstractBijection

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        *,
        cond_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
    ):
        if len(shape) != 1:
            raise ValueError("AffineCoupling only supports 1D inputs.")
        if cond_dim is not None and cond_dim < 1:
            raise ValueError(
                f"cond_dim must be a positive int or None; got {cond_dim}."
            )
        n_dims = shape[0]
        self.shape = shape
        self.cond_shape = None if cond_dim is None else (cond_dim,)

        affine = Affine()
        coupling = Coupling(
            key=key,
            transformer=affine,
            untransformed_dim=n_dims // 2,
            dim=n_dims,
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
        )
        # A zero readout gives every input the transformer's initial parameters
        self._coupling = eqx.tree_at(
            lambda c: c.conditioner, coupling, zero_readout(coupling.conditioner)
        )

    def transform_and_log_det(
        self, x: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Forward map ``x → y`` and its scalar log-determinant.

        Args:
            x: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        # Drop the condition when the layer is unconditional. flowjax's inner
        # Coupling unconditionally concatenates any non-None condition with
        # the untransformed half, which would crash the inner MLP if we let
        # a SurVAEFlow base-only condition leak into an unconditional layer.
        if self.cond_shape is None:
            condition = None
        return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

    def inverse_and_log_det(
        self, y: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Inverse map ``y → x`` and its scalar log-determinant.

        Args:
            y: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Forward map x → y and its scalar log-determinant.

Parameters:

Name Type Description Default
x ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (y, log_det) with y of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/affine.py
def transform_and_log_det(
    self, x: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Forward map ``x → y`` and its scalar log-determinant.

    Args:
        x: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    # Drop the condition when the layer is unconditional. flowjax's inner
    # Coupling unconditionally concatenates any non-None condition with
    # the untransformed half, which would crash the inner MLP if we let
    # a SurVAEFlow base-only condition leak into an unconditional layer.
    if self.cond_shape is None:
        condition = None
    return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Inverse map y → x and its scalar log-determinant.

Parameters:

Name Type Description Default
y ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/affine.py
def inverse_and_log_det(
    self, y: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Inverse map ``y → x`` and its scalar log-determinant.

    Args:
        y: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

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 (n_dims,).

required
cond_dim int | None

If not None, the layer expects a 1-D condition of shape (cond_dim,) at call time, concatenated onto the modulation's input alongside the passive half of x. Defaults to None.

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 makes the layer exactly the identity at init.

0.0
scale_map _FlowScaleMap

The positive scale map σ of AffineModulation, a map of gauss_flows_maps.reparam or one of "exp" (default), "softplus" and "one_plus_tanh".

'exp'
modulation AffineModulation | None

A pre-built AffineModulation from n_dims // 2 + (cond_dim or 0) inputs to n_dims - n_dims // 2 features; it replaces the arguments from nn_width to scale_map.

None

Raises:

Type Description
ValueError

If shape is not 1D or shape[0] < 3, if cond_dim is a non-positive int, if scale_map is "identity", or if modulation has the wrong sizes.

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_dim set, also takes a condition of 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
class GINCoupling(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)*.

    Args:
        key: JAX random key for the modulation's init.
        shape: Event shape ``(n_dims,)``.
        cond_dim: If not ``None``, the layer expects a 1-D ``condition`` of
            shape ``(cond_dim,)`` at call time, concatenated onto the
            modulation's input alongside the passive half of ``x``. Defaults to
            ``None``.
        nn_width: Width of the modulation's trunk. Defaults to 64.
        nn_depth: Number of trunk layers. Defaults to 2.
        activation: Activation after each trunk layer. Defaults to ReLU.
        readout_scale: Factor on the readout's default weight; the default ``0``
            makes the layer exactly the identity at init.
        scale_map: The positive scale map ``σ`` of `AffineModulation`, a map of
            `gauss_flows_maps.reparam` or one of ``"exp"`` (default),
            ``"softplus"`` and ``"one_plus_tanh"``.
        modulation: A pre-built `AffineModulation` from
            ``n_dims // 2 + (cond_dim or 0)`` inputs to ``n_dims - n_dims // 2``
            features; it replaces the arguments from ``nn_width`` to
            ``scale_map``.

    Raises:
        ValueError: If ``shape`` is not 1D or ``shape[0] < 3``, if ``cond_dim``
            is a non-positive int, if ``scale_map`` is ``"identity"``, or if
            ``modulation`` has the wrong sizes.

    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_dim`` set, also takes a ``condition`` of 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))
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    untransformed_dim: int = eqx.field(static=True)
    modulation: AffineModulation

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        *,
        cond_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
        activation: Callable[[Array], Array] = jnn.relu,
        readout_scale: float = 0.0,
        scale_map: _FlowScaleMap = "exp",
        modulation: AffineModulation | None = None,
    ):
        if len(shape) != 1:
            raise ValueError("GINCoupling only supports 1D inputs.")
        if shape[0] < 3:
            raise ValueError(
                "GINCoupling requires shape[0] >= 3 so the active half has "
                "at least two dimensions; otherwise centering collapses the "
                f"log_scale to zero and the layer is a pure shift. Got "
                f"shape={shape}."
            )
        if cond_dim is not None and cond_dim < 1:
            raise ValueError(
                f"cond_dim must be a positive int or None; got {cond_dim}."
            )

        dim = shape[0]
        transformed_dim = dim - dim // 2
        self.shape = shape
        self.cond_shape = None if cond_dim is None else (cond_dim,)
        self.untransformed_dim = dim // 2
        # The modulation reads [passive_half, condition] when cond_dim is set,
        # mirroring how flowjax's Coupling threads condition into its
        # conditioner for the other coupling layers in this package.
        self.modulation = _flow_modulation(
            key,
            num_features=transformed_dim,
            cond_dim=self.untransformed_dim + (cond_dim or 0),
            nn_width=nn_width,
            nn_depth=nn_depth,
            activation=activation,
            readout_scale=readout_scale,
            scale_map=scale_map,
            modulation=modulation,
        )

    def _active_params(
        self, passive: Array, condition: Array | None
    ) -> tuple[Array, Array]:
        if self.cond_shape is None:
            mlp_in = passive
        else:
            mlp_in = jnp.concatenate(
                [passive, jnp.asarray(condition, dtype=passive.dtype)]
            )
        _gamma, log_gamma, beta = self.modulation.modulation(mlp_in)
        return beta, _center_log_scale(log_gamma)

    def transform_and_log_det(
        self,
        x: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        """Forward map ``x → y`` with volume-preserving ``log_det ≡ 0``.

        Args:
            x: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when conditional;
                ``None`` otherwise.

        Returns:
            Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
            scalar ``log_det`` that is exactly zero.
        """
        x = jnp.asarray(x)
        passive = x[: self.untransformed_dim]
        active = x[self.untransformed_dim :]
        shift, log_scale = self._active_params(passive, condition)
        active_y = active * jnp.exp(log_scale) + shift
        y = jnp.concatenate((passive, active_y))
        # Use y.dtype rather than x.dtype: if x is integer, jnp.exp promotes
        # active_y to float and y.dtype is the right thing to match.
        log_det = jnp.zeros((), dtype=y.dtype)
        return y, log_det

    def inverse_and_log_det(
        self,
        y: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        """Inverse map ``y → x`` with volume-preserving ``log_det ≡ 0``.

        Args:
            y: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when conditional;
                ``None`` otherwise.

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det`` that is exactly zero.
        """
        y = jnp.asarray(y)
        passive = y[: self.untransformed_dim]
        active_y = y[self.untransformed_dim :]
        shift, log_scale = self._active_params(passive, condition)
        active_x = (active_y - shift) * jnp.exp(-log_scale)
        x = jnp.concatenate((passive, active_x))
        # Mirror the forward-direction fix: base log_det.dtype on the output x,
        # which is promoted to float by jnp.exp even when the input y is int.
        log_det = jnp.zeros((), dtype=x.dtype)
        return x, log_det

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Forward map x → y with volume-preserving log_det ≡ 0.

Parameters:

Name Type Description Default
x ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when conditional; None otherwise.

None

Returns:

Type Description
Array

Tuple (y, log_det) with y of shape (n_dims,) and a

Array

scalar log_det that is exactly zero.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/gin_coupling.py
def transform_and_log_det(
    self,
    x: ArrayLike,
    condition: ArrayLike | None = None,
) -> tuple[Array, Array]:
    """Forward map ``x → y`` with volume-preserving ``log_det ≡ 0``.

    Args:
        x: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when conditional;
            ``None`` otherwise.

    Returns:
        Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
        scalar ``log_det`` that is exactly zero.
    """
    x = jnp.asarray(x)
    passive = x[: self.untransformed_dim]
    active = x[self.untransformed_dim :]
    shift, log_scale = self._active_params(passive, condition)
    active_y = active * jnp.exp(log_scale) + shift
    y = jnp.concatenate((passive, active_y))
    # Use y.dtype rather than x.dtype: if x is integer, jnp.exp promotes
    # active_y to float and y.dtype is the right thing to match.
    log_det = jnp.zeros((), dtype=y.dtype)
    return y, log_det

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Inverse map y → x with volume-preserving log_det ≡ 0.

Parameters:

Name Type Description Default
y ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when conditional; None otherwise.

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det that is exactly zero.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/gin_coupling.py
def inverse_and_log_det(
    self,
    y: ArrayLike,
    condition: ArrayLike | None = None,
) -> tuple[Array, Array]:
    """Inverse map ``y → x`` with volume-preserving ``log_det ≡ 0``.

    Args:
        y: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when conditional;
            ``None`` otherwise.

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det`` that is exactly zero.
    """
    y = jnp.asarray(y)
    passive = y[: self.untransformed_dim]
    active_y = y[self.untransformed_dim :]
    shift, log_scale = self._active_params(passive, condition)
    active_x = (active_y - shift) * jnp.exp(-log_scale)
    x = jnp.concatenate((passive, active_x))
    # Mirror the forward-direction fix: base log_det.dtype on the output x,
    # which is promoted to float by jnp.exp even when the input y is int.
    log_det = jnp.zeros((), dtype=x.dtype)
    return x, log_det

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 (n_dims,). Only 1D inputs are supported.

required
n_bins int

Number of spline bins (knots). Defaults to 8.

8
interval float

Half-width of the spline interval [−interval, interval]; the transformer is affine (identity-tail) outside it. Defaults to 5.0.

5.0
cond_dim int | None

If not None, the layer expects a 1-D condition of shape (cond_dim,) at call time. Defaults to None.

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 is not 1D, or cond_dim is a non-positive int.

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_dim set, also takes a condition of 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
class RQSplineCoupling(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.

    Args:
        key: JAX random key for conditioner MLP initialisation.
        shape: Event shape ``(n_dims,)``. Only 1D inputs are supported.
        n_bins: Number of spline bins (knots). Defaults to 8.
        interval: Half-width of the spline interval ``[−interval, interval]``;
            the transformer is affine (identity-tail) outside it. Defaults to 5.0.
        cond_dim: If not ``None``, the layer expects a 1-D ``condition`` of
            shape ``(cond_dim,)`` at call time. Defaults to ``None``.
        nn_width: Hidden layer width of the conditioner MLP. Defaults to 64.
        nn_depth: Depth of the conditioner MLP. Defaults to 2.

    Raises:
        ValueError: If ``shape`` is not 1D, or ``cond_dim`` is a non-positive int.

    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_dim`` set, also takes a ``condition`` of 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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    _coupling: AbstractBijection

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        n_bins: int = 8,
        interval: float = 5.0,
        *,
        cond_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
    ):
        if len(shape) != 1:
            raise ValueError("RQSplineCoupling only supports 1D inputs.")
        if cond_dim is not None and cond_dim < 1:
            raise ValueError(
                f"cond_dim must be a positive int or None; got {cond_dim}."
            )
        n_dims = shape[0]
        self.shape = shape
        self.cond_shape = None if cond_dim is None else (cond_dim,)

        spline = RationalQuadraticSpline(knots=n_bins, interval=interval)
        coupling = Coupling(
            key=key,
            transformer=spline,
            untransformed_dim=n_dims // 2,
            dim=n_dims,
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
        )
        # A zero readout gives every input the transformer's initial parameters
        self._coupling = eqx.tree_at(
            lambda c: c.conditioner, coupling, zero_readout(coupling.conditioner)
        )

    def transform_and_log_det(
        self, x: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Forward map ``x → y`` and its scalar log-determinant.

        Args:
            x: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

    def inverse_and_log_det(
        self, y: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Inverse map ``y → x`` and its scalar log-determinant.

        Args:
            y: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Forward map x → y and its scalar log-determinant.

Parameters:

Name Type Description Default
x ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (y, log_det) with y of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/spline.py
def transform_and_log_det(
    self, x: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Forward map ``x → y`` and its scalar log-determinant.

    Args:
        x: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Inverse map y → x and its scalar log-determinant.

Parameters:

Name Type Description Default
y ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/spline.py
def inverse_and_log_det(
    self, y: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Inverse map ``y → x`` and its scalar log-determinant.

    Args:
        y: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

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:

  1. The per-dim transformer is CircularRationalQuadraticSpline (tied endpoint derivatives → C¹ across the join).
  2. 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 (n_dims,). Every dim is treated as periodic. Requires n_dims >= 2.

required
n_bins int

Number of spline bins. Defaults to 8.

8
bound float

Half-width of the circular interval; period is 2·bound. Defaults to π.

float(pi)
untransformed_dim int | None

Number of leading dims left unchanged (used as conditioner inputs). Must lie in (0, n_dims). Defaults to n_dims // 2.

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 is not 1D, n_dims < 2, or untransformed_dim is not in (0, n_dims).

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
class CircularRQSplineCoupling(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:

    1. The per-dim transformer is `CircularRationalQuadraticSpline`
       (tied endpoint derivatives → C¹ across the join).
    2. 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``).

    Args:
        key: JAX random key for the conditioner MLP.
        shape: Input shape ``(n_dims,)``. Every dim is treated as periodic.
            Requires ``n_dims >= 2``.
        n_bins: Number of spline bins. Defaults to 8.
        bound: Half-width of the circular interval; period is ``2·bound``.
            Defaults to ``π``.
        untransformed_dim: Number of leading dims left unchanged (used as
            conditioner inputs). Must lie in ``(0, n_dims)``. Defaults to
            ``n_dims // 2``.
        nn_width: Hidden layer width for the conditioner MLP. Defaults to 64.
        nn_depth: Depth of the conditioner MLP. Defaults to 2.

    Raises:
        ValueError: If ``shape`` is not 1D, ``n_dims < 2``, or
            ``untransformed_dim`` is not in ``(0, n_dims)``.

    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*.
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    bound: float
    untransformed_dim: int
    _inner: AbstractBijection

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        n_bins: int = 8,
        bound: float = float(jnp.pi),
        untransformed_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
    ):
        if len(shape) != 1:
            raise ValueError("CircularRQSplineCoupling only supports 1D inputs.")
        n_dims = shape[0]
        if n_dims < 2:
            raise ValueError("CircularRQSplineCoupling requires n_dims >= 2.")

        if untransformed_dim is None:
            untransformed_dim = n_dims // 2
        if not 0 < untransformed_dim < n_dims:
            raise ValueError(
                f"untransformed_dim must be in (0, n_dims); got {untransformed_dim}."
            )

        self.shape = shape
        self.bound = float(bound)
        self.untransformed_dim = int(untransformed_dim)

        spline = CircularRationalQuadraticSpline(knots=n_bins, bound=bound)
        # Use cond_dim = 2 * untransformed_dim to feed Fourier features
        # ([sin(x_cond), cos(x_cond)]) into the conditioner MLP. Setting the
        # inner Coupling's untransformed_dim=0 means we manage the split
        # ourselves and pass the periodic conditioning via `condition`.
        n_trans = n_dims - untransformed_dim
        coupling = Coupling(
            key=key,
            transformer=spline,
            untransformed_dim=0,
            dim=n_trans,
            cond_dim=2 * untransformed_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
            nn_activation=jnn.relu,
        )
        # A zero readout gives every input the transformer's initial parameters
        self._inner = eqx.tree_at(
            lambda c: c.conditioner, coupling, zero_readout(coupling.conditioner)
        )

    def _fourier_features(self, x_cond: Array) -> Array:
        # x_cond: (untransformed_dim,) -> features: (2 * untransformed_dim,)
        return jnp.concatenate([jnp.sin(x_cond), jnp.cos(x_cond)])

    def transform_and_log_det(
        self, x: Array, condition: Array | None = None
    ) -> tuple[Array, Array]:
        """Forward map ``x → y`` on the torus and its scalar log-determinant.

        Args:
            x: Single event of shape ``(n_dims,)``; wrapped into
                ``[−bound, bound]`` before transforming.
            condition: Unused (this layer is unconditional).

        Returns:
            Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        x_arr = jnp.asarray(x)
        x_wrapped = _wrap_all(x_arr, self.bound)
        x_cond = x_wrapped[: self.untransformed_dim]
        x_trans = x_wrapped[self.untransformed_dim :]
        y_trans, log_det = self._inner.transform_and_log_det(
            x_trans, self._fourier_features(x_cond)
        )
        y = jnp.concatenate([x_cond, y_trans])
        return y, log_det

    def inverse_and_log_det(
        self, y: Array, condition: Array | None = None
    ) -> tuple[Array, Array]:
        """Inverse map ``y → x`` on the torus and its scalar log-determinant.

        Args:
            y: Single event of shape ``(n_dims,)``; wrapped into
                ``[−bound, bound]`` before transforming.
            condition: Unused (this layer is unconditional).

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        y_arr = jnp.asarray(y)
        y_wrapped = _wrap_all(y_arr, self.bound)
        y_cond = y_wrapped[: self.untransformed_dim]
        y_trans = y_wrapped[self.untransformed_dim :]
        x_trans, log_det = self._inner.inverse_and_log_det(
            y_trans, self._fourier_features(y_cond)
        )
        x = jnp.concatenate([y_cond, x_trans])
        return x, log_det

transform_and_log_det

transform_and_log_det(x: Array, condition: Array | None = None) -> tuple[Array, Array]

Forward map x → y on the torus and its scalar log-determinant.

Parameters:

Name Type Description Default
x Array

Single event of shape (n_dims,); wrapped into [−bound, bound] before transforming.

required
condition Array | None

Unused (this layer is unconditional).

None

Returns:

Type Description
Array

Tuple (y, log_det) with y of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/circular_spline.py
def transform_and_log_det(
    self, x: Array, condition: Array | None = None
) -> tuple[Array, Array]:
    """Forward map ``x → y`` on the torus and its scalar log-determinant.

    Args:
        x: Single event of shape ``(n_dims,)``; wrapped into
            ``[−bound, bound]`` before transforming.
        condition: Unused (this layer is unconditional).

    Returns:
        Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    x_arr = jnp.asarray(x)
    x_wrapped = _wrap_all(x_arr, self.bound)
    x_cond = x_wrapped[: self.untransformed_dim]
    x_trans = x_wrapped[self.untransformed_dim :]
    y_trans, log_det = self._inner.transform_and_log_det(
        x_trans, self._fourier_features(x_cond)
    )
    y = jnp.concatenate([x_cond, y_trans])
    return y, log_det

inverse_and_log_det

inverse_and_log_det(y: Array, condition: Array | None = None) -> tuple[Array, Array]

Inverse map y → x on the torus and its scalar log-determinant.

Parameters:

Name Type Description Default
y Array

Single event of shape (n_dims,); wrapped into [−bound, bound] before transforming.

required
condition Array | None

Unused (this layer is unconditional).

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/circular_spline.py
def inverse_and_log_det(
    self, y: Array, condition: Array | None = None
) -> tuple[Array, Array]:
    """Inverse map ``y → x`` on the torus and its scalar log-determinant.

    Args:
        y: Single event of shape ``(n_dims,)``; wrapped into
            ``[−bound, bound]`` before transforming.
        condition: Unused (this layer is unconditional).

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    y_arr = jnp.asarray(y)
    y_wrapped = _wrap_all(y_arr, self.bound)
    y_cond = y_wrapped[: self.untransformed_dim]
    y_trans = y_wrapped[self.untransformed_dim :]
    x_trans, log_det = self._inner.inverse_and_log_det(
        y_trans, self._fourier_features(y_cond)
    )
    x = jnp.concatenate([y_cond, x_trans])
    return x, log_det

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 (n_dims,).

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, the layer expects a 1-D condition of shape (cond_dim,) at call time, concatenated onto the inner MLP's input. Defaults to None.

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 is not 1D, or cond_dim is a non-positive int.

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_dim set, also takes a condition of shape (cond_dim,); the coupling splits into n_dims // 2 kept + transformed halves, and log_det sums log(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
class DeepSigmoidCoupling(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.

    Args:
        key: JAX random key for conditioner MLP initialisation.
        shape: Event shape ``(n_dims,)``.
        n_components: Number of sigmoid units in the per-dim transformer.
            More components → more capacity, more parameters per dim.
            Defaults to 8.
        cond_dim: If not ``None``, the layer expects a 1-D ``condition`` of
            shape ``(cond_dim,)`` at call time, concatenated onto the inner
            MLP's input. Defaults to ``None``.
        nn_width: Hidden layer width of the conditioner MLP. Defaults to 64.
        nn_depth: Depth of the conditioner MLP. Defaults to 2.

    Raises:
        ValueError: If ``shape`` is not 1D, or ``cond_dim`` is a non-positive int.

    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_dim`` set, also takes a ``condition`` of shape ``(cond_dim,)``;
        the coupling splits into ``n_dims // 2`` kept + transformed halves, and
        ``log_det`` sums ``log(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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    _coupling: AbstractBijection

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        n_components: int = 8,
        *,
        cond_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
    ):
        if len(shape) != 1:
            raise ValueError("DeepSigmoidCoupling only supports 1D inputs.")
        if cond_dim is not None and cond_dim < 1:
            raise ValueError(
                f"cond_dim must be a positive int or None; got {cond_dim}."
            )
        n_dims = shape[0]
        self.shape = shape
        self.cond_shape = None if cond_dim is None else (cond_dim,)

        transformer = _DeepSigmoidTransformer(n_components=n_components)
        coupling = Coupling(
            key=key,
            transformer=transformer,
            untransformed_dim=n_dims // 2,
            dim=n_dims,
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
        )
        # A zero readout gives every input the transformer's initial parameters
        self._coupling = eqx.tree_at(
            lambda c: c.conditioner, coupling, zero_readout(coupling.conditioner)
        )

    def transform_and_log_det(
        self, x: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Forward map ``x → y`` and its scalar log-determinant.

        Args:
            x: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

    def inverse_and_log_det(
        self, y: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Inverse map ``y → x`` and its scalar log-determinant.

        Args:
            y: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Forward map x → y and its scalar log-determinant.

Parameters:

Name Type Description Default
x ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (y, log_det) with y of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/deepsigmoid.py
def transform_and_log_det(
    self, x: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Forward map ``x → y`` and its scalar log-determinant.

    Args:
        x: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(y, log_det)`` with ``y`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Inverse map y → x and its scalar log-determinant.

Parameters:

Name Type Description Default
y ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/deepsigmoid.py
def inverse_and_log_det(
    self, y: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Inverse map ``y → x`` and its scalar log-determinant.

    Args:
        y: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

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 (n_dims,).

required
n_components int

Mixture components K per transformed dim. Defaults to 8.

8
cond_dim int | None

If not None, the layer expects a 1-D condition of shape (cond_dim,) at call time, concatenated onto the inner MLP's input. Defaults to None.

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 is not 1D, cond_dim is a non-positive int, or n_dims < 2 (no non-trivial split).

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_dim set, also takes a condition of 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
class MixtureGaussianCDFCoupling(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``.

    Args:
        key: JAX random key for the conditioner MLP.
        shape: Event shape ``(n_dims,)``.
        n_components: Mixture components ``K`` per transformed dim.
            Defaults to 8.
        cond_dim: If not ``None``, the layer expects a 1-D ``condition`` of
            shape ``(cond_dim,)`` at call time, concatenated onto the inner
            MLP's input. Defaults to ``None``.
        nn_width: Hidden layer width of the conditioner MLP. Defaults to 64.
        nn_depth: Depth of the conditioner MLP. Defaults to 2.
        log_scale_bound: Tanh bound applied to per-dim log-scales. Defaults
            to 5.0 (σ ∈ [exp(-5), exp(5)] ≈ [6.7e-3, 148]).

    Raises:
        ValueError: If ``shape`` is not 1D, ``cond_dim`` is a non-positive int,
            or ``n_dims < 2`` (no non-trivial split).

    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_dim`` set, also takes a ``condition`` of 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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    n_components: int = eqx.field(static=True)
    log_scale_bound: float = eqx.field(static=True)
    _coupling: AbstractBijection

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        n_components: int = 8,
        *,
        cond_dim: int | None = None,
        nn_width: int = 64,
        nn_depth: int = 2,
        log_scale_bound: float = 5.0,
    ):
        if len(shape) != 1:
            raise ValueError("MixtureGaussianCDFCoupling only supports 1D inputs.")
        if cond_dim is not None and cond_dim < 1:
            raise ValueError(
                f"cond_dim must be a positive int or None; got {cond_dim}."
            )
        n_dims = shape[0]
        if n_dims < 2:
            raise ValueError(
                "MixtureGaussianCDFCoupling needs n_dims >= 2 for a non-trivial split."
            )
        self.shape = shape
        self.cond_shape = None if cond_dim is None else (cond_dim,)
        self.n_components = int(n_components)
        self.log_scale_bound = float(log_scale_bound)

        transformer = _MixtureGaussianCDFTransformer(
            n_components=n_components, log_scale_bound=log_scale_bound
        )
        coupling = Coupling(
            key=key,
            transformer=transformer,
            untransformed_dim=n_dims // 2,
            dim=n_dims,
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
        )
        # A zero readout gives every input the transformer's initial parameters
        self._coupling = eqx.tree_at(
            lambda c: c.conditioner, coupling, zero_readout(coupling.conditioner)
        )

    def transform_and_log_det(
        self, x: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Forward map ``x → z`` and its scalar log-determinant.

        Args:
            x: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(z, log_det)`` with ``z`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

    def inverse_and_log_det(
        self, y: ArrayLike, condition: ArrayLike | None = None
    ) -> tuple[Array, Array]:
        """Inverse map ``z → x`` and its scalar log-determinant.

        Args:
            y: Single event of shape ``(n_dims,)``.
            condition: Context of shape ``(cond_dim,)`` when the layer is
                conditional; ignored (dropped) when ``cond_dim=None``.

        Returns:
            Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
            scalar ``log_det``.
        """
        if self.cond_shape is None:
            condition = None
        return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Forward map x → z and its scalar log-determinant.

Parameters:

Name Type Description Default
x ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (z, log_det) with z of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/mixture_cdf.py
def transform_and_log_det(
    self, x: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Forward map ``x → z`` and its scalar log-determinant.

    Args:
        x: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(z, log_det)`` with ``z`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.transform_and_log_det(jnp.asarray(x), condition)

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition: ArrayLike | None = None) -> tuple[Array, Array]

Inverse map z → x and its scalar log-determinant.

Parameters:

Name Type Description Default
y ArrayLike

Single event of shape (n_dims,).

required
condition ArrayLike | None

Context of shape (cond_dim,) when the layer is conditional; ignored (dropped) when cond_dim=None.

None

Returns:

Type Description
Array

Tuple (x, log_det) with x of shape (n_dims,) and a

Array

scalar log_det.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/coupling/mixture_cdf.py
def inverse_and_log_det(
    self, y: ArrayLike, condition: ArrayLike | None = None
) -> tuple[Array, Array]:
    """Inverse map ``z → x`` and its scalar log-determinant.

    Args:
        y: Single event of shape ``(n_dims,)``.
        condition: Context of shape ``(cond_dim,)`` when the layer is
            conditional; ignored (dropped) when ``cond_dim=None``.

    Returns:
        Tuple ``(x, log_det)`` with ``x`` of shape ``(n_dims,)`` and a
        scalar ``log_det``.
    """
    if self.cond_shape is None:
        condition = None
    return self._coupling.inverse_and_log_det(jnp.asarray(y), condition)

ContinuousAffineCoupling module-attribute

ContinuousAffineCoupling = ContinuousAffineCoupling

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 K per dimension.

required
shape tuple[int, ...]

Event shape (n_dims,). Only 1-D events are supported.

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
class MixtureGaussianCDF(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`.

    Args:
        n_components: Number of mixture components ``K`` per dimension.
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.

    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,)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    means: Array
    # a paramax.Parameterize leaf (see Reparametrised.parameter) that unwraps to
    # the positive scales; annotated Array as flowjax does for its own leaves
    scales: Array
    log_weights: Array

    def __init__(self, n_components: int, shape: tuple[int, ...]):
        if len(shape) != 1:
            raise ValueError("MixtureGaussianCDF only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        self.means = jnp.zeros((n_dims, n_components))
        self.scales = _SCALE.parameter(jnp.full((n_dims, n_components), _INITIAL_SCALE))
        self.log_weights = jnp.zeros((n_dims, n_components))

    @classmethod
    def from_data(
        cls,
        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.

        Args:
            x: Training data of shape ``(n, d)``.
            n_components: Mixture components ``K``. Defaults to 8.

        Returns:
            A `MixtureGaussianCDF` with data-adapted means and scales.
        """
        import numpy as np

        x = np.asarray(x)
        if x.ndim != 2:
            raise ValueError(f"x must be 2-D (n, d); got shape {x.shape}")
        n_dims = x.shape[-1]
        qs = np.linspace(0.5 / n_components, 1.0 - 0.5 / n_components, n_components)
        means = np.stack(
            [np.quantile(x[:, i], qs) for i in range(n_dims)], axis=0
        ).astype("float32")
        data_std_per_dim = np.asarray(x.std(axis=0), dtype=np.float32)  # (d,)
        if n_components > 1:
            target_scale = np.maximum(
                float(np.mean(np.diff(qs))) * data_std_per_dim, 0.1
            )
        else:
            target_scale = np.maximum(data_std_per_dim, 0.1)
        # scale = 5e-3 + softplus(u) is at least 1e-2 at the target, which keeps
        # the leaf's value strictly above its floor
        scale_per_dim = jnp.asarray(np.maximum(target_scale, 2 * _SCALE_FLOOR))  # (d,)
        scales = jnp.broadcast_to(scale_per_dim[:, None], (n_dims, n_components))

        obj = cls(n_components=n_components, shape=(n_dims,))
        obj = eqx.tree_at(lambda m: m.means, obj, jnp.asarray(means))
        obj = eqx.tree_at(lambda m: m.scales, obj, _SCALE.parameter(scales))
        return obj

    def _gmm_logcdf(
        self, x: Array, means: Array, scales: Array, weights: Array
    ) -> Array:
        """Log CDF of a 1D Gaussian mixture evaluated at x."""
        log_cdfs = jstats.norm.logcdf(x[:, None], loc=means, scale=scales)
        return jsp_special.logsumexp(jnp.log(weights) + log_cdfs, axis=-1)

    def _gmm_logsf(
        self, x: Array, means: Array, scales: Array, weights: Array
    ) -> Array:
        """Log survival function of a 1D Gaussian mixture evaluated at x."""
        log_sfs = jstats.norm.logsf(x[:, None], loc=means, scale=scales)
        return jsp_special.logsumexp(jnp.log(weights) + log_sfs, axis=-1)

    def _gmm_logpdf(
        self, x: Array, means: Array, scales: Array, weights: Array
    ) -> Array:
        """Log PDF of a 1D Gaussian mixture evaluated at x."""
        # logsumexp (not log(sum(exp(...)) + eps)) so the log-density stays exact
        # in the tails: exponentiating first underflows to 0 once the component
        # logpdfs drop below ~-87 (float32), flooring log_pdf_x and corrupting
        # the log-det for the very tail samples this bijector is meant to keep.
        log_pdfs = jstats.norm.logpdf(x[:, None], loc=means, scale=scales)
        return jsp_special.logsumexp(jnp.log(weights) + log_pdfs, axis=-1)

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        scales = self.scales
        weights = softmax(self.log_weights, axis=-1)

        # GMM CDF -> uniform -> probit, done entirely in log-space. Take the
        # probit of whichever tail is smaller (log-CDF in the lower tail,
        # log-SF in the upper) and feed the *log*-probability straight into the
        # probit via `_ndtri_exp`. Exponentiating first underflows in the tails
        # (float32 caps the probit near ±12.9), collapsing distinct tail samples
        # onto the same y and destroying invertibility.
        log_cdf = self._gmm_logcdf(x, self.means, scales, weights)
        log_sf = self._gmm_logsf(x, self.means, scales, weights)
        lower = log_cdf <= log_sf
        mag = _ndtri_exp(jnp.where(lower, log_cdf, log_sf))
        y = jnp.where(lower, mag, -mag)

        # Log det: log |dy/dx| = log |phi^{-1}'(u) * gmm_pdf(x)|
        # = log_gmm_pdf(x) - log_norm_pdf(y)
        log_pdf_x = self._gmm_logpdf(x, self.means, scales, weights)
        log_pdf_y = jstats.norm.logpdf(y)
        log_det = jnp.sum(log_pdf_x - log_pdf_y)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        from gauss_flows_maps._src.utils import bisection_inverse

        y = jnp.asarray(y)
        scales = self.scales
        weights = softmax(self.log_weights, axis=-1)

        # Invert in log-space to mirror the forward pass: solve
        # log-CDF(x) = log Φ(y) in the lower tail and log-SF(x) = log Φ(-y) in
        # the upper tail. Bracketing on the linear CDF/SF target would underflow
        # for |y| ≳ 5.5 in float32 and collapse the bisection onto the bounds.
        def _invert_lower(ops):
            y_i, means_i, scales_i, weights_i = ops
            target = jax.scipy.special.log_ndtr(y_i)

            def _fn(xi):
                return self._gmm_logcdf(
                    xi[None], means_i[None], scales_i[None], weights_i[None]
                )[0]

            return bisection_inverse(_fn, target)

        def _invert_upper(ops):
            y_i, means_i, scales_i, weights_i = ops
            target = jax.scipy.special.log_ndtr(-y_i)

            def _fn(xi):
                return -self._gmm_logsf(
                    xi[None], means_i[None], scales_i[None], weights_i[None]
                )[0]

            return bisection_inverse(_fn, -target)

        def _invert_i(y_i, means_i, scales_i, weights_i):
            return jax.lax.cond(
                y_i < 0.0,
                _invert_lower,
                _invert_upper,
                (y_i, means_i, scales_i, weights_i),
            )

        x = jax.vmap(_invert_i)(y, self.means, scales, weights)

        # Log det of inverse = -log_det of forward
        log_pdf_x = self._gmm_logpdf(x, self.means, scales, weights)
        log_pdf_y = jstats.norm.logpdf(y)
        log_det = -jnp.sum(log_pdf_x - log_pdf_y)
        return x, log_det

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 (n, d).

required
n_components int

Mixture components K. Defaults to 8.

8

Returns:

Type Description
MixtureGaussianCDF

A MixtureGaussianCDF with data-adapted means and scales.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/elementwise/mixture_cdf.py
@classmethod
def from_data(
    cls,
    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.

    Args:
        x: Training data of shape ``(n, d)``.
        n_components: Mixture components ``K``. Defaults to 8.

    Returns:
        A `MixtureGaussianCDF` with data-adapted means and scales.
    """
    import numpy as np

    x = np.asarray(x)
    if x.ndim != 2:
        raise ValueError(f"x must be 2-D (n, d); got shape {x.shape}")
    n_dims = x.shape[-1]
    qs = np.linspace(0.5 / n_components, 1.0 - 0.5 / n_components, n_components)
    means = np.stack(
        [np.quantile(x[:, i], qs) for i in range(n_dims)], axis=0
    ).astype("float32")
    data_std_per_dim = np.asarray(x.std(axis=0), dtype=np.float32)  # (d,)
    if n_components > 1:
        target_scale = np.maximum(
            float(np.mean(np.diff(qs))) * data_std_per_dim, 0.1
        )
    else:
        target_scale = np.maximum(data_std_per_dim, 0.1)
    # scale = 5e-3 + softplus(u) is at least 1e-2 at the target, which keeps
    # the leaf's value strictly above its floor
    scale_per_dim = jnp.asarray(np.maximum(target_scale, 2 * _SCALE_FLOOR))  # (d,)
    scales = jnp.broadcast_to(scale_per_dim[:, None], (n_dims, n_components))

    obj = cls(n_components=n_components, shape=(n_dims,))
    obj = eqx.tree_at(lambda m: m.means, obj, jnp.asarray(means))
    obj = eqx.tree_at(lambda m: m.scales, obj, _SCALE.parameter(scales))
    return obj

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 K per dimension.

required
shape tuple[int, ...]

Event shape (n_dims,). Only 1-D events are supported.

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
class MixtureLogisticCDF(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.

    Args:
        n_components: Number of mixture components ``K`` per dimension.
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.

    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,)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    means: Array
    # a paramax.Parameterize leaf (see Reparametrised.parameter) that unwraps to
    # the positive scales; annotated Array as flowjax does for its own leaves
    scales: Array
    log_weights: Array

    def __init__(self, n_components: int, shape: tuple[int, ...]):
        if len(shape) != 1:
            raise ValueError("MixtureLogisticCDF only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        self.means = jnp.zeros((n_dims, n_components))
        self.scales = _SCALE.parameter(jnp.full((n_dims, n_components), _INITIAL_SCALE))
        self.log_weights = jnp.zeros((n_dims, n_components))

    def _mixture_cdf(
        self, x: Array, means: Array, scales: Array, weights: Array
    ) -> Array:
        """CDF of a 1D logistic mixture evaluated at x."""
        cdfs = jax.scipy.special.expit((x[:, None] - means) / scales)
        return jnp.sum(weights * cdfs, axis=-1)

    def _mixture_logpdf(
        self, x: Array, means: Array, scales: Array, weights: Array
    ) -> Array:
        """Log PDF of a 1D logistic mixture evaluated at x."""
        z = (x[:, None] - means) / scales
        log_pdfs = -jnp.log(scales) + jax.nn.log_sigmoid(z) + jax.nn.log_sigmoid(-z)
        return jnp.log(jnp.sum(weights * jnp.exp(log_pdfs), axis=-1) + 1e-38)

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        scales = self.scales
        weights = softmax(self.log_weights, axis=-1)

        u = self._mixture_cdf(x, self.means, scales, weights)
        u = jnp.clip(u, 1e-6, 1 - 1e-6)
        y = jax.scipy.special.ndtri(u)

        log_pdf_x = self._mixture_logpdf(x, self.means, scales, weights)
        log_pdf_y = jstats.norm.logpdf(y)
        log_det = jnp.sum(log_pdf_x - log_pdf_y)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        from gauss_flows_maps._src.utils import bisection_inverse

        y = jnp.asarray(y)
        scales = self.scales
        weights = softmax(self.log_weights, axis=-1)

        u = jnp.clip(jax.scipy.special.ndtr(y), 1e-6, 1.0 - 1e-6)

        def _cdf_i(u_i, means_i, scales_i, weights_i):
            def _fn(xi):
                return self._mixture_cdf(
                    xi[None], means_i[None], scales_i[None], weights_i[None]
                )[0]

            return bisection_inverse(_fn, u_i)

        x = jax.vmap(_cdf_i)(u, self.means, scales, weights)

        log_pdf_x = self._mixture_logpdf(x, self.means, scales, weights)
        log_pdf_y = jstats.norm.logpdf(y)
        log_det = -jnp.sum(log_pdf_x - log_pdf_y)
        return x, log_det

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 (n_dims,). Only 1-D events are supported.

required
interval float

Half-width of the symmetric spline interval [−interval, interval]. Defaults to 5.0.

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
class RQSplineMarginal(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.

    Args:
        n_bins: Number of spline knots (bins) per dimension.
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.
        interval: Half-width of the symmetric spline interval
            ``[−interval, interval]``. Defaults to ``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,)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    spline: AbstractBijection

    def __init__(self, n_bins: int, shape: tuple[int, ...], interval: float = 5.0):
        if len(shape) != 1:
            raise ValueError("RQSplineMarginal only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        spline = eqx.filter_vmap(
            lambda: RationalQuadraticSpline(knots=n_bins, interval=interval),
            axis_size=n_dims,
        )()
        self.spline = Vmap(spline, in_axes=eqx.if_array(0))

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        return self.spline.transform_and_log_det(x, condition)

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        return self.spline.inverse_and_log_det(y, condition)

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 1e-3.

0.001
min_width float

Minimum bin width. Defaults to 1e-3.

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
class CircularRationalQuadraticSpline(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.

    Args:
        knots: Number of bins.
        bound: Half-width of the periodic interval. Defaults to ``π``.
        min_derivative: Minimum derivative at any knot. Defaults to ``1e-3``.
        min_width: Minimum bin width. Defaults to ``1e-3``.

    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
        ()
    """

    shape: ClassVar[tuple[int, ...]] = ()
    cond_shape: ClassVar[None] = None
    bound: float
    _spline: RationalQuadraticSpline

    def __init__(
        self,
        knots: int,
        bound: float = float(jnp.pi),
        min_derivative: float = 1e-3,
        min_width: float = 1e-3,
    ):
        self.bound = float(bound)
        spline = RationalQuadraticSpline(
            knots=knots,
            interval=bound,
            min_derivative=min_derivative,
            min_width=min_width,
        )
        # K free derivatives (one per knot position on the circle, with d[0] tied
        # to d[K]), each min_derivative + softplus(u) and started at 1. Resolved
        # shape (K+2,) matches flowjax's allocation; the final slot is unused by
        # flowjax's indexing but kept for shape compatibility.
        free = Reparametrised("softplus", lower=min_derivative).parameter(
            jnp.ones(knots)
        )
        self._spline = eqx.tree_at(
            lambda s: s.derivatives,
            spline,
            replace=px.Parameterize(_tie_endpoints, free),
        )

    def transform_and_log_det(self, x: Array, condition=None) -> tuple[Array, Array]:
        return self._spline.transform_and_log_det(x, condition)

    def inverse_and_log_det(self, y: Array, condition=None) -> tuple[Array, Array]:
        return self._spline.inverse_and_log_det(y, condition)

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 (functax Linear). Density is the piecewise-constant bin PDF; log-det is piecewise-constant in x.
  • method="monotonic": Fritsch-Carlson monotone cubic Hermite (PCHIP, functax Pchip) 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 (n_dims,). Only 1-D events are supported (each dim is independently histogrammed).

required
method str

"linear" or "monotonic" (PCHIP). Defaults to "linear".

'linear'
bin_edges Array | None

Optional pre-fit bin edges of shape (n_dims, n_bins+1). Use .fit(data) instead of passing this directly.

None
bin_pdf Array | None

Optional pre-fit per-bin density of shape (n_dims, n_bins).

None
cdf_edges Array | None

Optional pre-fit CDF values at bin edges of shape (n_dims, n_bins+1).

None
fwd_interp Interpolant | SeriesInterpolant | None

Optional pre-built forward-CDF interpolator. Use .fit(data) instead of passing this directly.

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-dim log(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
class HistogramCDF(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 (functax
      `Linear`). Density is the piecewise-constant bin PDF; log-det is
      piecewise-constant in ``x``.
    - ``method="monotonic"``: Fritsch-Carlson monotone cubic Hermite (PCHIP,
      functax `Pchip`) 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.

    Args:
        n_bins: Number of equal-width histogram bins per dimension.
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported
            (each dim is independently histogrammed).
        method: ``"linear"`` or ``"monotonic"`` (PCHIP). Defaults to
            ``"linear"``.
        bin_edges: Optional pre-fit bin edges of shape ``(n_dims, n_bins+1)``.
            Use ``.fit(data)`` instead of passing this directly.
        bin_pdf: Optional pre-fit per-bin density of shape ``(n_dims, n_bins)``.
        cdf_edges: Optional pre-fit CDF values at bin edges of shape
            ``(n_dims, n_bins+1)``.
        fwd_interp: Optional pre-built forward-CDF interpolator.
            Use ``.fit(data)`` instead of passing this directly.
        inv_interp: Optional pre-built inverse-CDF interpolator.

    Shape:
        - transform_and_log_det: ``(n_dims,)`` → ``(n_dims,)`` in ``[0, 1]``,
          scalar log_det (sum of per-dim ``log(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).
    """

    n_bins: int = eqx.field(static=True)
    shape: tuple[int, ...]
    method: str = eqx.field(static=True)
    cond_shape: ClassVar[None] = None
    bin_edges: Array | None
    bin_pdf: Array | None
    cdf_edges: Array | None
    fwd_interp: Interpolant | SeriesInterpolant | None
    inv_interp: Interpolant | SeriesInterpolant | None

    def __init__(
        self,
        n_bins: int,
        shape: tuple[int, ...],
        method: str = "linear",
        bin_edges: Array | None = None,
        bin_pdf: Array | None = None,
        cdf_edges: Array | None = None,
        fwd_interp: Interpolant | SeriesInterpolant | None = None,
        inv_interp: Interpolant | SeriesInterpolant | None = None,
    ):
        if len(shape) != 1:
            raise ValueError("HistogramCDF only supports 1D inputs.")
        if method not in ("linear", "monotonic"):
            raise ValueError(f"method must be 'linear' or 'monotonic', got {method!r}.")
        self.n_bins = n_bins
        self.shape = shape
        self.method = method
        self.bin_edges = bin_edges
        self.bin_pdf = bin_pdf
        self.cdf_edges = cdf_edges
        self.fwd_interp = fwd_interp
        self.inv_interp = inv_interp

    def fit(self, data: ArrayLike) -> HistogramCDF:
        """Fit the empirical CDF to ``data`` and return a new fitted instance.

        Args:
            data: Array of shape ``(n_samples, n_dims)`` from which to
                estimate the marginal CDFs.

        Returns:
            A new `HistogramCDF` with concrete ``bin_edges``,
            ``bin_pdf``, ``cdf_edges``, and per-dim forward/inverse
            interpolators populated. Idempotent: refitting with the same
            data yields the same fitted parameters.
        """
        # values: (n_samples, n_dims)
        values = jnp.asarray(data)
        if values.ndim != 2 or values.shape[1] != self.shape[0]:
            raise ValueError(
                f"Expected data shape (n_samples, {self.shape[0]}), got {values.shape}."
            )
        # mins, maxs: (n_dims,)
        mins = jnp.min(values, axis=0)
        maxs = jnp.max(values, axis=0)

        def _edges(lo, hi):
            # 1% padding so the extremes don't sit on a boundary.
            span = jnp.where(hi > lo, hi - lo, 1.0)
            start = lo - 0.01 * span
            end = hi + 0.01 * span
            return jnp.linspace(start, end, self.n_bins + 1)

        # bin_edges: (n_dims, n_bins+1)
        bin_edges = jax.vmap(_edges)(mins, maxs)

        def _hist(column, edges):
            # column: (n_samples,); edges: (n_bins+1,) -> counts: (n_bins,)
            counts, _ = jnp.histogram(column, bins=edges)
            return counts

        # counts: (n_dims, n_bins). Smooth by 1e-6 to avoid log(0) and to
        # keep cdf_edges monotone; the float32 tail can still repeat values,
        # which `_strictly_increasing` separates for the inverse's knots.
        counts = jax.vmap(_hist)(values.T, bin_edges) + 1e-6
        totals = jnp.sum(counts, axis=1, keepdims=True)  # (n_dims, 1)
        widths = jnp.diff(bin_edges, axis=1)  # (n_dims, n_bins)
        pdf = counts / (totals * widths)  # (n_dims, n_bins)
        # cdf_edges: (n_dims, n_bins+1) — CDF value at each bin edge.
        cdf_edges = jnp.concatenate(
            [jnp.zeros((self.shape[0], 1)), jnp.cumsum(pdf * widths, axis=1)],
            axis=1,
        )
        cdf_edges = jnp.minimum(cdf_edges, 1.0)

        # Per-dim interpolants batched via eqx.filter_vmap → one PyTree with
        # leading axis ``n_dims`` per leaf.
        fwd_interp, inv_interp = _interpolants(self.method, bin_edges, cdf_edges)

        return HistogramCDF(
            self.n_bins,
            self.shape,
            self.method,
            bin_edges,
            pdf,
            cdf_edges,
            fwd_interp,
            inv_interp,
        )

    def _check_fitted(self):
        if (
            self.bin_edges is None
            or self.bin_pdf is None
            or self.cdf_edges is None
            or self.fwd_interp is None
            or self.inv_interp is None
        ):
            raise ValueError("HistogramCDF requires fitting data first.")

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        """Map x → uniform via the fitted CDF; log_det = sum(log density)."""
        self._check_fitted()
        x_arr = jnp.asarray(x)
        edges = self.bin_edges  # type: ignore[assignment]

        def _one(fwd, x_i, edges_i):
            # fwd: per-dim interpolant; x_i, edges_i: scalar / (n_bins+1,)
            y_i = _read(fwd, x_i)
            # Analytic derivative: for "linear" this is the piecewise-constant
            # bin PDF; for "monotonic" it is the smooth Hermite derivative.
            density = _slope(fwd, x_i)
            inside = (x_i >= edges_i[0]) & (x_i <= edges_i[-1])
            # Outside the fitted range F is 0 below and 1 above.
            y_i = jnp.where(x_i < edges_i[0], 0.0, y_i)
            y_i = jnp.where(x_i > edges_i[-1], 1.0, y_i)
            # Redundant inside the range, but guards against monotonic-cubic
            # overshoot (PCHIP does not overshoot; cheap).
            y_i = jnp.clip(y_i, 0.0, 1.0)
            log_det_i = jnp.where(
                inside, jnp.log(jnp.clip(density, min=1e-38)), -jnp.inf
            )
            return y_i, log_det_i

        y, log_det = eqx.filter_vmap(_one)(self.fwd_interp, x_arr, edges)
        return y, jnp.sum(log_det)

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        """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).
        """
        self._check_fitted()
        y_arr = jnp.asarray(y)
        edges = self.bin_edges  # type: ignore[assignment]

        def _one(inv, fwd, y_i, edges_i):
            # Exact boundaries y == 0 / y == 1 are treated as inside (they
            # map to edges[0] / edges[-1] and carry a finite log_det),
            # consistent with forward's treatment of x == edges[0/-1].
            y_clipped = jnp.clip(y_i, 0.0, 1.0)
            x_i = _read(inv, y_clipped)
            # Above the last CDF knot (float32 can leave it just below 1), F⁻¹
            # is the right edge.
            x_i = jnp.where(y_clipped > inv.source.values[-1], edges_i[-1], x_i)
            density = _slope(fwd, x_i)
            outside = (y_i < 0.0) | (y_i > 1.0)
            x_i = jnp.where(y_i < 0.0, edges_i[0], x_i)
            x_i = jnp.where(y_i > 1.0, edges_i[-1], x_i)
            log_det_i = jnp.where(
                outside, -jnp.inf, -jnp.log(jnp.clip(density, min=1e-38))
            )
            return x_i, log_det_i

        x, log_det = eqx.filter_vmap(_one)(
            self.inv_interp, self.fwd_interp, y_arr, edges
        )
        return x, jnp.sum(log_det)

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 (n_samples, n_dims) from which to estimate the marginal CDFs.

required

Returns:

Type Description
HistogramCDF

A new HistogramCDF with concrete bin_edges,

HistogramCDF

bin_pdf, cdf_edges, and per-dim forward/inverse

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
def fit(self, data: ArrayLike) -> HistogramCDF:
    """Fit the empirical CDF to ``data`` and return a new fitted instance.

    Args:
        data: Array of shape ``(n_samples, n_dims)`` from which to
            estimate the marginal CDFs.

    Returns:
        A new `HistogramCDF` with concrete ``bin_edges``,
        ``bin_pdf``, ``cdf_edges``, and per-dim forward/inverse
        interpolators populated. Idempotent: refitting with the same
        data yields the same fitted parameters.
    """
    # values: (n_samples, n_dims)
    values = jnp.asarray(data)
    if values.ndim != 2 or values.shape[1] != self.shape[0]:
        raise ValueError(
            f"Expected data shape (n_samples, {self.shape[0]}), got {values.shape}."
        )
    # mins, maxs: (n_dims,)
    mins = jnp.min(values, axis=0)
    maxs = jnp.max(values, axis=0)

    def _edges(lo, hi):
        # 1% padding so the extremes don't sit on a boundary.
        span = jnp.where(hi > lo, hi - lo, 1.0)
        start = lo - 0.01 * span
        end = hi + 0.01 * span
        return jnp.linspace(start, end, self.n_bins + 1)

    # bin_edges: (n_dims, n_bins+1)
    bin_edges = jax.vmap(_edges)(mins, maxs)

    def _hist(column, edges):
        # column: (n_samples,); edges: (n_bins+1,) -> counts: (n_bins,)
        counts, _ = jnp.histogram(column, bins=edges)
        return counts

    # counts: (n_dims, n_bins). Smooth by 1e-6 to avoid log(0) and to
    # keep cdf_edges monotone; the float32 tail can still repeat values,
    # which `_strictly_increasing` separates for the inverse's knots.
    counts = jax.vmap(_hist)(values.T, bin_edges) + 1e-6
    totals = jnp.sum(counts, axis=1, keepdims=True)  # (n_dims, 1)
    widths = jnp.diff(bin_edges, axis=1)  # (n_dims, n_bins)
    pdf = counts / (totals * widths)  # (n_dims, n_bins)
    # cdf_edges: (n_dims, n_bins+1) — CDF value at each bin edge.
    cdf_edges = jnp.concatenate(
        [jnp.zeros((self.shape[0], 1)), jnp.cumsum(pdf * widths, axis=1)],
        axis=1,
    )
    cdf_edges = jnp.minimum(cdf_edges, 1.0)

    # Per-dim interpolants batched via eqx.filter_vmap → one PyTree with
    # leading axis ``n_dims`` per leaf.
    fwd_interp, inv_interp = _interpolants(self.method, bin_edges, cdf_edges)

    return HistogramCDF(
        self.n_bins,
        self.shape,
        self.method,
        bin_edges,
        pdf,
        cdf_edges,
        fwd_interp,
        inv_interp,
    )

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition=None)

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
def transform_and_log_det(self, x: ArrayLike, condition=None):
    """Map x → uniform via the fitted CDF; log_det = sum(log density)."""
    self._check_fitted()
    x_arr = jnp.asarray(x)
    edges = self.bin_edges  # type: ignore[assignment]

    def _one(fwd, x_i, edges_i):
        # fwd: per-dim interpolant; x_i, edges_i: scalar / (n_bins+1,)
        y_i = _read(fwd, x_i)
        # Analytic derivative: for "linear" this is the piecewise-constant
        # bin PDF; for "monotonic" it is the smooth Hermite derivative.
        density = _slope(fwd, x_i)
        inside = (x_i >= edges_i[0]) & (x_i <= edges_i[-1])
        # Outside the fitted range F is 0 below and 1 above.
        y_i = jnp.where(x_i < edges_i[0], 0.0, y_i)
        y_i = jnp.where(x_i > edges_i[-1], 1.0, y_i)
        # Redundant inside the range, but guards against monotonic-cubic
        # overshoot (PCHIP does not overshoot; cheap).
        y_i = jnp.clip(y_i, 0.0, 1.0)
        log_det_i = jnp.where(
            inside, jnp.log(jnp.clip(density, min=1e-38)), -jnp.inf
        )
        return y_i, log_det_i

    y, log_det = eqx.filter_vmap(_one)(self.fwd_interp, x_arr, edges)
    return y, jnp.sum(log_det)

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition=None)

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
def inverse_and_log_det(self, y: ArrayLike, condition=None):
    """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).
    """
    self._check_fitted()
    y_arr = jnp.asarray(y)
    edges = self.bin_edges  # type: ignore[assignment]

    def _one(inv, fwd, y_i, edges_i):
        # Exact boundaries y == 0 / y == 1 are treated as inside (they
        # map to edges[0] / edges[-1] and carry a finite log_det),
        # consistent with forward's treatment of x == edges[0/-1].
        y_clipped = jnp.clip(y_i, 0.0, 1.0)
        x_i = _read(inv, y_clipped)
        # Above the last CDF knot (float32 can leave it just below 1), F⁻¹
        # is the right edge.
        x_i = jnp.where(y_clipped > inv.source.values[-1], edges_i[-1], x_i)
        density = _slope(fwd, x_i)
        outside = (y_i < 0.0) | (y_i > 1.0)
        x_i = jnp.where(y_i < 0.0, edges_i[0], x_i)
        x_i = jnp.where(y_i > 1.0, edges_i[-1], x_i)
        log_det_i = jnp.where(
            outside, -jnp.inf, -jnp.log(jnp.clip(density, min=1e-38))
        )
        return x_i, log_det_i

    x, log_det = eqx.filter_vmap(_one)(
        self.inv_interp, self.fwd_interp, y_arr, edges
    )
    return x, jnp.sum(log_det)

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 (n_dims,). The transform is applied independently to each entry.

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
class InverseGaussCDF(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)``.

    Args:
        shape: Event shape ``(n_dims,)``. The transform is applied
            independently to each entry.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None

    def __init__(self, shape: tuple[int, ...]):
        self.shape = shape

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        x_clipped = jnp.clip(x, 1e-6, 1 - 1e-6)
        y = jax.scipy.special.ndtri(x_clipped)
        log_det = jnp.sum(-jstats.norm.logpdf(y))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        y = jnp.asarray(y)
        x = jax.scipy.special.ndtr(y)
        log_det = jnp.sum(jstats.norm.logpdf(y))
        return x, log_det

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 map is not an elementwise reparametrisation (a CholeskyFactor or a Simplex mixes entries).

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
class Elementwise(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.

    Args:
        map: The elementwise reparametrisation g.
        shape: Event shape; g is applied to every entry.

    Raises:
        ValueError: When ``map`` is not an elementwise reparametrisation (a
            `CholeskyFactor` or a `Simplex` mixes entries).

    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
    """

    map: AbstractReparametrisation
    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None

    def __check_init__(self) -> None:
        if not isinstance(self.map, Reparametrised | Composed):
            msg = (
                "'map' must be an elementwise reparametrisation (Reparametrised "
                f"or Composed), got {type(self.map).__name__}"
            )
            raise ValueError(msg)

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        # y = g(x)
        y = self.map.forward(x)
        # log |det ∂y/∂x| = Σᵢ log g′(xᵢ)
        log_det = jnp.sum(self.map.log_derivative(x))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        y = jnp.asarray(y)
        # x = g⁻¹(y)
        x = self.map.inverse(y)
        # log |det ∂x/∂y| = −Σᵢ log g′(xᵢ)
        log_det = -jnp.sum(self.map.log_derivative(x))
        return x, log_det

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 (n_dims,). Only 1-D events are supported.

required

Raises:

Type Description
ValueError

If shape is not 1-D.

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
class HouseholderRotation(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.

    Args:
        n_reflections: Number of Householder reflections to compose.
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.

    Raises:
        ValueError: If ``shape`` is not 1-D.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    params: Array

    def __init__(self, n_reflections: int, shape: tuple[int, ...]):
        if len(shape) != 1:
            raise ValueError("HouseholderRotation only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        # Initialize with random-looking but deterministic params
        self.params = jnp.ones((n_reflections, n_dims)) / jnp.sqrt(
            jnp.arange(1, n_dims + 1, dtype=float)
        )

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        for v in self.params:
            x = _householder(x, v)
        return x, jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        y = jnp.asarray(y)
        # Inverse is applying reflections in reverse order (each H is self-inverse)
        for v in reversed(list(self.params)):
            y = _householder(y, v)
        return y, jnp.zeros(())

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 (n_dims,). Only 1-D events are supported.

required

Raises:

Type Description
ValueError

If shape is not 1-D.

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
class OrthogonalRotation(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.

    Args:
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.

    Raises:
        ValueError: If ``shape`` is not 1-D.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    skew_params: Array

    def __init__(self, shape: tuple[int, ...]):
        if len(shape) != 1:
            raise ValueError("OrthogonalRotation only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        n_params = n_dims * (n_dims - 1) // 2
        self.skew_params = jnp.zeros(n_params)

    def _get_rotation_matrix(self) -> Array:
        n_dims = self.shape[0]
        A = jnp.zeros((n_dims, n_dims))
        idx = jnp.tril_indices(n_dims, k=-1)
        A = A.at[idx].set(self.skew_params)
        A = A - A.T  # make skew-symmetric
        eye = jnp.eye(n_dims)
        # Cayley map: Q = (I - A)(I + A)^{-1}
        # Equivalent to: Q = solve(I + A, I - A)^T with A^T = -A gives (I-A)(I+A)^{-1}
        Q = jnp.linalg.solve(eye - A, eye + A).T
        return Q

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        Q = self._get_rotation_matrix()
        y = Q @ jnp.asarray(x)
        return y, jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        Q = self._get_rotation_matrix()
        x = Q.T @ jnp.asarray(y)
        return x, jnp.zeros(())

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 (n_dims, n_dims).

required

Raises:

Type Description
ValueError

If matrix is not a square 2-D array.

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
class FixedRotation(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.

    Args:
        matrix: Orthogonal rotation matrix of shape ``(n_dims, n_dims)``.

    Raises:
        ValueError: If ``matrix`` is not a square 2-D array.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    _matrix: paramax.NonTrainable

    def __init__(self, matrix: ArrayLike):
        matrix = jnp.asarray(matrix, dtype=float)
        if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
            raise ValueError("matrix must be a square 2D array.")
        self.shape = (matrix.shape[0],)
        self._matrix = paramax.non_trainable(matrix)

    @property
    def matrix(self) -> Array:
        """The orthogonal rotation matrix (unwrapped from NonTrainable)."""
        return paramax.unwrap(self._matrix)

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        y = self.matrix @ jnp.asarray(x)
        return y, jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        x = self.matrix.T @ jnp.asarray(y)
        return x, jnp.zeros(())

    @classmethod
    def from_data(cls, 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.

        Args:
            x: Training data of shape ``(n, d)``.

        Returns:
            A `FixedRotation` whose matrix is the PCA rotation of ``x``.
        """
        x = jnp.asarray(x, dtype=float)
        if x.ndim != 2:
            raise ValueError(f"x must be 2-D (n, d); got shape {x.shape}")
        xc = x - jnp.mean(x, axis=0, keepdims=True)
        cov = (xc.T @ xc) / jnp.maximum(x.shape[0] - 1, 1)
        eigvals, eigvecs = jnp.linalg.eigh(cov)
        # eigh returns ascending eigvals; reverse for PCA convention, then
        # transpose so rows are principal axes (y = matrix @ x).
        del eigvals
        matrix = eigvecs[:, ::-1].T
        return cls(matrix)

matrix property

matrix: Array

The orthogonal rotation matrix (unwrapped from NonTrainable).

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 (n, d).

required

Returns:

Type Description
FixedRotation

A FixedRotation whose matrix is the PCA rotation of x.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/linear/rotation.py
@classmethod
def from_data(cls, 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.

    Args:
        x: Training data of shape ``(n, d)``.

    Returns:
        A `FixedRotation` whose matrix is the PCA rotation of ``x``.
    """
    x = jnp.asarray(x, dtype=float)
    if x.ndim != 2:
        raise ValueError(f"x must be 2-D (n, d); got shape {x.shape}")
    xc = x - jnp.mean(x, axis=0, keepdims=True)
    cov = (xc.T @ xc) / jnp.maximum(x.shape[0] - 1, 1)
    eigvals, eigvecs = jnp.linalg.eigh(cov)
    # eigh returns ascending eigvals; reverse for PCA convention, then
    # transpose so rows are principal axes (y = matrix @ x).
    del eigvals
    matrix = eigvecs[:, ::-1].T
    return cls(matrix)

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 (n_dims,). Only 1-D events are supported.

required
permutation ArrayLike | None

Optional permutation of length n_dims. Defaults to the reverse permutation [n_dims−1, …, 1, 0].

None

Raises:

Type Description
ValueError

If shape is not 1-D, or permutation is not a valid permutation of 0..n_dims−1 with the right shape.

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
class LULinearPermute(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.

    Args:
        shape: Event shape ``(n_dims,)``. Only 1-D events are supported.
        permutation: Optional permutation of length ``n_dims``. Defaults to the
            reverse permutation ``[n_dims−1, …, 1, 0]``.

    Raises:
        ValueError: If ``shape`` is not 1-D, or ``permutation`` is not a valid
            permutation of ``0..n_dims−1`` with the right shape.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    lower_params: Array
    upper_params: Array
    log_diag: Array
    permutation: Array
    inv_permutation: Array

    def __init__(
        self,
        shape: tuple[int, ...],
        permutation: ArrayLike | None = None,
    ):
        if len(shape) != 1:
            raise ValueError("LULinearPermute only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        n_strict = n_dims * (n_dims - 1) // 2
        self.lower_params = jnp.zeros(n_strict)
        self.upper_params = jnp.zeros(n_strict)
        self.log_diag = jnp.zeros(n_dims)
        if permutation is None:
            self.permutation = jnp.arange(n_dims - 1, -1, -1)
        else:
            perm = jnp.asarray(permutation, dtype=jnp.int32)
            if perm.shape != (n_dims,):
                raise ValueError(
                    f"permutation must have shape ({n_dims},), got {perm.shape}."
                )
            if sorted(perm.tolist()) != list(range(n_dims)):
                raise ValueError(
                    f"permutation must be a permutation of 0..{n_dims - 1}, "
                    f"got {perm.tolist()}."
                )
            self.permutation = perm
        # Cache the inverse permutation so inverse_and_log_det avoids an argsort
        # on every call.
        self.inv_permutation = jnp.argsort(self.permutation)

    def _build_lu(self) -> tuple[Array, Array]:
        n = self.shape[0]
        lower_idx = jnp.tril_indices(n, k=-1)
        upper_idx = jnp.triu_indices(n, k=1)
        L = jnp.eye(n).at[lower_idx].set(self.lower_params)
        U = jnp.diag(jnp.exp(self.log_diag)).at[upper_idx].set(self.upper_params)
        return L, U

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        L, U = self._build_lu()
        x = jnp.asarray(x)
        y = L @ (U @ x)
        y = y[self.permutation]
        log_det = jnp.sum(self.log_diag)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        L, U = self._build_lu()
        y = jnp.asarray(y)
        y = y[self.inv_permutation]
        w = jax.scipy.linalg.solve_triangular(L, y, lower=True, unit_diagonal=True)
        x = jax.scipy.linalg.solve_triangular(U, w, lower=False)
        log_det = -jnp.sum(self.log_diag)
        return x, log_det

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
class Invertible1x1Conv(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.

    Args:
        key: PRNG key for near-identity initialisation (small off-diagonals).
        n_channels: Number of channels / feature dimensions.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    lower_off: Array  # lower-triangular off-diagonal entries of L
    upper_off: Array  # upper-triangular off-diagonal entries of U
    log_diag_u: Array  # log of diagonal of U (ensures non-zero det)

    def __init__(self, key: PRNGKeyArray, n_channels: int):
        self.shape = (n_channels,)
        n = n_channels
        # Initialize near identity: small random off-diagonals, unit diagonal
        k1, k2 = jr.split(key)
        n_off = n * (n - 1) // 2
        self.lower_off = jr.normal(k1, (n_off,)) * 0.01
        self.upper_off = jr.normal(k2, (n_off,)) * 0.01
        self.log_diag_u = jnp.zeros(n)

    def _get_weight(self) -> Array:
        n = self.shape[0]
        idx_lower = jnp.tril_indices(n, k=-1)
        idx_upper = jnp.triu_indices(n, k=1)
        L = jnp.eye(n).at[idx_lower].set(self.lower_off)
        # Build U: zero off-diagonal, then set upper triangle and diagonal explicitly
        U = jnp.zeros((n, n)).at[idx_upper].set(self.upper_off)
        U = U.at[jnp.diag_indices(n)].set(jnp.exp(self.log_diag_u))
        return L @ U

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        W = self._get_weight()
        y = W @ jnp.asarray(x)
        log_det = jnp.sum(self.log_diag_u)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        W = self._get_weight()
        x = jnp.linalg.solve(W, jnp.asarray(y))
        log_det = -jnp.sum(self.log_diag_u)
        return x, log_det

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:

trainable, frozen = eqx.partition(
    model,
    lambda leaf: eqx.is_inexact_array(leaf)
    and not isinstance(leaf, paramax.NonTrainable),
    is_leaf=lambda leaf: isinstance(leaf, paramax.NonTrainable),
)
# optimize `trainable`, recombine with `frozen` at step end.

Parameters:

Name Type Description Default
key PRNGKeyArray

PRNG key used for learnable Cayley initialisation. Ignored when fixed_matrix is supplied (but still required for API symmetry with the other learnable bijections in this subpackage).

required
n_channels int

Number of channels / feature dimensions.

required
fixed_matrix ArrayLike | None

Optional pre-computed (n_channels, n_channels) orthogonal matrix (e.g. from PCA or a random QR). Validated at construction — must satisfy Q.T @ Q ≈ I within orthogonality_atol. When None (default), the layer is Cayley-parameterised and trainable.

None
orthogonality_atol float

Absolute tolerance for the orthogonality check on fixed_matrix. Defaults to 1e-5 — loose enough for fp32 QR / SVD residuals, tight enough to catch casual errors (e.g. passing a non-orthogonal PCA loading matrix).

1e-05
Shape
  • Input x: (n_channels,)
  • Output y: (n_channels,)
  • log_det: scalar (always 0)
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
class Orthogonal1x1Conv(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:
        ```python
        trainable, frozen = eqx.partition(
            model,
            lambda leaf: eqx.is_inexact_array(leaf)
            and not isinstance(leaf, paramax.NonTrainable),
            is_leaf=lambda leaf: isinstance(leaf, paramax.NonTrainable),
        )
        # optimize `trainable`, recombine with `frozen` at step end.
        ```

    Args:
        key: PRNG key used for learnable Cayley initialisation. Ignored
            when ``fixed_matrix`` is supplied (but still required for API
            symmetry with the other learnable bijections in this
            subpackage).
        n_channels: Number of channels / feature dimensions.
        fixed_matrix: Optional pre-computed ``(n_channels, n_channels)``
            orthogonal matrix (e.g. from PCA or a random QR). Validated
            at construction — must satisfy ``Q.T @ Q ≈ I`` within
            ``orthogonality_atol``. When ``None`` (default), the layer is
            Cayley-parameterised and trainable.
        orthogonality_atol: Absolute tolerance for the orthogonality
            check on ``fixed_matrix``. Defaults to ``1e-5`` — loose enough
            for fp32 QR / SVD residuals, tight enough to catch casual
            errors (e.g. passing a non-orthogonal PCA loading matrix).

    Shape:
        - Input  ``x``:  ``(n_channels,)``
        - Output ``y``:  ``(n_channels,)``
        - ``log_det``:   scalar (always ``0``)

    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,)))
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    _rotation: OrthogonalRotation | None
    # ``fixed_matrix`` is stored as ``paramax.NonTrainable[Array]`` at
    # runtime when supplied, None otherwise. Annotated as ``Array | None``
    # to match flowjax/paramax ergonomics (same pragmatic convention used
    # by ``_DeepSigmoidTransformer``'s ``base_scale`` / ``amplitudes``).
    fixed_matrix: Array | None

    def __init__(
        self,
        key: PRNGKeyArray,
        n_channels: int,
        *,
        fixed_matrix: ArrayLike | None = None,
        orthogonality_atol: float = 1e-5,
    ):
        self.shape = (n_channels,)
        if fixed_matrix is None:
            # Learnable path — delegate to OrthogonalRotation's Cayley
            # construction, replacing its zero init with small-random skew
            # params so the initial Q is near-identity (breaks symmetry).
            base = OrthogonalRotation(shape=self.shape)
            n_params = n_channels * (n_channels - 1) // 2
            self._rotation = eqx.tree_at(
                lambda m: m.skew_params,
                base,
                jr.normal(key, (n_params,)) * 0.01,
            )
            self.fixed_matrix = None
        else:
            m = jnp.asarray(fixed_matrix, dtype=float)
            if m.shape != (n_channels, n_channels):
                raise ValueError(
                    "fixed_matrix must have shape "
                    f"({n_channels}, {n_channels}); got {m.shape}."
                )
            # Validate Q.T @ Q ≈ I. Evaluated eagerly at construction —
            # outside jit, so the ``.item()`` call is safe.
            eye = jnp.eye(n_channels, dtype=m.dtype)
            residual = jnp.max(jnp.abs(m.T @ m - eye))
            if not bool(jnp.allclose(m.T @ m, eye, atol=orthogonality_atol).item()):
                raise ValueError(
                    "fixed_matrix must be orthogonal (Q.T @ Q ≈ I) within "
                    f"atol={orthogonality_atol}; got max|Q.T @ Q - I| = "
                    f"{float(residual.item()):.3e}."
                )
            self._rotation = None
            # NonTrainable signals to paramax-aware training loops that
            # this leaf should not be updated. Its ``unwrap`` applies
            # ``stop_gradient`` so the gradient path is also blocked.
            self.fixed_matrix = paramax.NonTrainable(m)

    def _get_rotation_matrix(self) -> Array:
        """Return the orthogonal matrix Q for the current forward/inverse call.

        Shape: ``(n_channels, n_channels)``. Unwraps the module so
        ``NonTrainable``-wrapped ``fixed_matrix`` is materialised with
        ``stop_gradient`` applied automatically.
        """
        unwrapped = paramax.unwrap(self)
        if unwrapped.fixed_matrix is not None:
            return unwrapped.fixed_matrix
        # Learnable path: reuse OrthogonalRotation's Cayley construction.
        return unwrapped._rotation._get_rotation_matrix()  # type: ignore[union-attr]

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        Q = self._get_rotation_matrix()
        y = Q @ jnp.asarray(x)
        # Orthogonal => |det Q| = 1 => log|det| = 0 exactly.
        return y, jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        Q = self._get_rotation_matrix()
        # Orthogonal matrix inverse is its transpose.
        x = Q.T @ jnp.asarray(y)
        return x, jnp.zeros(())

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

\[ \exp(M) \;=\; \sum_{k=0}^{\infty} \frac{M^k}{k!}, \]

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

\[ (M_K^\top)_{p,q} \;=\; K[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a]\quad \text{when}\quad (M_K)_{p,q} \;=\; K[i,\,j,\,a,\,b]. \]

Skew-symmetry \(M_K = -M_K^\top\) therefore holds iff

\[ K[i, j, a, b] \;=\; -\,K[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a]. \]

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

\[ p_N(M_K)\,x \;=\; \sum_{k=0}^{N} \frac{M_K^k\, x}{k!} \;=\; \bigl(I + M_K + \tfrac{1}{2!}M_K^2 + \dots\bigr)\,x, \]

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

\[ t_{k+1} \;=\; \frac{1}{k+1}\, M_K\, t_k, \qquad r_{k+1} \;=\; r_k + t_{k+1}, \]

so that \(r_N = p_N(M_K)\,x\) (see _convolution_exponential). The truncation error is

\[ \lVert p_N(M) - \exp(M) \rVert \;=\; \mathcal{O}\!\bigl(\|M\|^{N+1}/(N{+}1)!\bigr), \]

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

\[ \log\!\bigl|\det \exp(M_K)\bigr| \;=\; \operatorname{tr}(M_K) \;=\; 0 \]

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 (H, W, C) — single event (no batch axis).

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 N (>= 1). Truncation error scales as \(\mathcal{O}(1 / (N{+}1)!)\).

8
n_power_iterations int

Power-iteration steps for the spectral-norm estimate (>= 1). Two iterations is usually enough because \(\sigma\) only needs an upper bound, not high accuracy.

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
class OrthogonalConvExponential(AbstractBijection):
    r"""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

    $$
    \exp(M) \;=\; \sum_{k=0}^{\infty} \frac{M^k}{k!},
    $$

    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

    $$
    (M_K^\top)_{p,q} \;=\; K[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a]\quad
        \text{when}\quad
    (M_K)_{p,q} \;=\; K[i,\,j,\,a,\,b].
    $$

    Skew-symmetry $M_K = -M_K^\top$ therefore holds iff

    $$
    K[i, j, a, b] \;=\; -\,K[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a].
    $$

    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

    $$
    p_N(M_K)\,x
        \;=\; \sum_{k=0}^{N} \frac{M_K^k\, x}{k!}
        \;=\; \bigl(I + M_K + \tfrac{1}{2!}M_K^2 + \dots\bigr)\,x,
    $$

    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

    $$
    t_{k+1} \;=\; \frac{1}{k+1}\, M_K\, t_k, \qquad
    r_{k+1} \;=\; r_k + t_{k+1},
    $$

    so that $r_N = p_N(M_K)\,x$ (see
    `_convolution_exponential`). The truncation error is

    $$
    \lVert p_N(M) - \exp(M) \rVert
        \;=\; \mathcal{O}\!\bigl(\|M\|^{N+1}/(N{+}1)!\bigr),
    $$

    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

    $$
    \log\!\bigl|\det \exp(M_K)\bigr|
        \;=\; \operatorname{tr}(M_K) \;=\; 0
    $$

    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**
    ```python
    x, y                     : (H, W, C)
    weight / skew kernel K   : (k_h, k_w, C, C) in flowjax/JAX HWIO
    log_det                  : ()                 (scalar, always 0)
    ```

    Args:
        key: JAX random key for kernel initialization.
        shape: Image shape ``(H, W, C)`` — single event (no batch axis).
        kernel_size: Spatial kernel size (must be a positive **odd** integer
            so the kernel has a unique center pixel).
        n_terms: Number of Taylor-series terms ``N`` (``>= 1``). Truncation
            error scales as $\mathcal{O}(1 / (N{+}1)!)$.
        n_power_iterations: Power-iteration steps for the spectral-norm
            estimate (``>= 1``). Two iterations is usually enough because
            $\sigma$ only needs an upper bound, not high accuracy.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    weight: Array  # (k_h, k_w, C, C) free parameter; skew kernel derived per-call
    spectral_seed: Array  # (H, W, C) persistent unit-norm seed for power iteration
    n_terms: int
    n_power_iterations: int

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, int, int],
        *,
        kernel_size: int = 3,
        n_terms: int = 8,
        n_power_iterations: int = 2,
    ):
        if len(shape) != 3:
            raise ValueError(
                f"OrthogonalConvExponential expects shape (H, W, C); got {shape!r}."
            )
        if kernel_size < 1 or kernel_size % 2 == 0:
            raise ValueError(
                f"kernel_size must be a positive odd integer; got {kernel_size}."
            )
        if n_terms < 1:
            raise ValueError(f"n_terms must be >= 1; got {n_terms}.")
        if n_power_iterations < 1:
            raise ValueError(
                f"n_power_iterations must be >= 1; got {n_power_iterations}."
            )

        self.shape = tuple(shape)
        c = int(shape[-1])
        self.n_terms = int(n_terms)
        self.n_power_iterations = int(n_power_iterations)
        # Split the user's key: weight init and the persistent spectral seed
        # must be independent so a pathologically-aligned weight/seed pair is
        # measure-zero rather than correlated by construction.
        w_key, s_key = jr.split(key)
        # Small weight init: the skew kernel K = W - flip(W)^T doubles scale,
        # and spectral norm caps ||K|| <= 1, so near-identity behavior at
        # step 0. weight: (k_h, k_w, C, C).
        self.weight = jr.normal(w_key, (kernel_size, kernel_size, c, c)) * 0.05
        # Persistent random (H, W, C) seed for power iteration. A random
        # vector has non-zero projection on every fixed singular direction
        # with probability 1; a deterministic seed (constant, sin(arange),
        # ...) can collide with ker(M_K) for specific kernel configurations
        # (e.g. shape=(1,1,3) + kernel_size=1 yields a 3x3 skew matrix
        # whose 1-D nullspace could align with a fixed pattern). Grads are
        # blocked in _spectral_normalize so this field stays constant.
        raw_seed = jr.normal(s_key, self.shape)
        self.spectral_seed = raw_seed / (jnp.linalg.norm(raw_seed) + 1e-8)

    @staticmethod
    def _skew(weight: Array) -> Array:
        r"""Project a free weight tensor to a skew-symmetric conv kernel.

        Given free parameter ``W`` of shape ``(k_h, k_w, C, C)``, returns

        $$
        K \;=\; W \,-\, \widetilde{W},\qquad
        \widetilde{W}[i, j, a, b] \;=\; W[k_h{-}1{-}i,\,k_w{-}1{-}j,\,b,\,a].
        $$

        Under circular padding, the induced Toeplitz operator ``M_K`` satisfies
        $M_K = -M_K^\top$, so $\exp(M_K)$ is orthogonal.

        Shape:
            ``weight``: ``(k_h, k_w, C, C)``
            returns:    ``(k_h, k_w, C, C)`` (same shape, skew-symmetric)
        """
        # flip spatial dims -> reverse (i, j) indices relative to center;
        # swapaxes(2, 3) -> swap input/output channel axes (the "transpose" ^T).
        flipped = jnp.swapaxes(jnp.flip(weight, axis=(0, 1)), 2, 3)
        return weight - flipped  # (k_h, k_w, C, C)

    def _circular_conv(self, x: Array, kernel: Array) -> Array:
        """Single-event circular 2D convolution.

        Pads ``x`` with wrap-mode boundary so that VALID-padded convolution
        produces the circular (periodic) result, then delegates to
        `jax.lax.conv_general_dilated` with NHWC/HWIO layout.

        Shape:
            ``x``      : ``(H, W, C_in)``
            ``kernel`` : ``(k_h, k_w, C_in, C_out)`` (HWIO)
            returns    : ``(H, W, C_out)``
        """
        k_h, k_w = kernel.shape[0], kernel.shape[1]
        pad_h, pad_w = k_h // 2, k_w // 2
        # x:        (H, W, C)          -> x_padded: (H + 2*pad_h, W + 2*pad_w, C)
        x_padded = jnp.pad(x, ((pad_h, pad_h), (pad_w, pad_w), (0, 0)), mode="wrap")
        # x_padded[None]: (1, Hp, Wp, C) -> y: (1, H, W, C_out) under VALID padding.
        y = lax.conv_general_dilated(
            x_padded[None, ...],
            kernel,
            window_strides=(1, 1),
            padding="VALID",
            dimension_numbers=("NHWC", "HWIO", "NHWC"),
        )
        return y[0]  # (H, W, C_out)

    def _circular_conv_transpose(self, x: Array, kernel: Array) -> Array:
        r"""Mathematical transpose (adjoint) of circular conv.

        For a circular conv with kernel $K$ the operator adjoint is the
        circular conv with the *index-flipped, channel-transposed* kernel
        $K^\top[i, j, o, c] = K[k_h{-}1{-}i, k_w{-}1{-}j, c, o]$.

        Shape:
            ``x``      : ``(H, W, C_out)``
            ``kernel`` : ``(k_h, k_w, C_in, C_out)``
            returns    : ``(H, W, C_in)``
        """
        # Flip spatial -> reverse (i, j); swapaxes(2, 3) -> swap I<->O.
        kernel_t = jnp.swapaxes(jnp.flip(kernel, axis=(0, 1)), 2, 3)
        return self._circular_conv(x, kernel_t)

    def _spectral_normalize(self, kernel: Array) -> Array:
        r"""Clip kernel spectral norm to at most 1 via power iteration.

        Estimates $\sigma \approx \|M_K\|_{op}$ using the standard SVD
        power iteration in image space: alternately apply $M_K$ and
        $M_K^\top$, renormalizing after each step. The estimate is
        wrapped in `jax.lax.stop_gradient` so backprop does *not*
        differentiate through the iteration itself — gradients flow only
        through the explicit ``kernel / sigma`` rescale.

        After $n$ iterations, $\sigma$ converges to
        $\sigma_1 = \|M_K\|$ with ratio $(\sigma_2/\sigma_1)^n$.
        Two iterations suffice because we only need an *upper bound* (we
        take $\max(\sigma, 1)$), not high accuracy.

        **Seed choice.** The seed must have non-zero projection on the
        leading singular vector of $M_K$. Any *deterministic* seed
        (constant, $\sin(\text{arange})$, ...) can collide with
        $\ker(M_K)$ for specific kernel configurations — e.g. a
        constant vector is in $\ker(M_K)$ for skew-symmetric kernels
        with $C = 1$, and any fixed pattern in $\mathbb{R}^3$
        can land in the 1-D nullspace of a ``shape=(1,1,3)`` +
        ``kernel_size=1`` skew kernel. We therefore use a **persistent
        random** seed stored at construction time
        (`spectral_seed`). A random Gaussian has non-zero projection
        on every fixed direction with probability 1, so alignment with
        $\ker(M_K)$ over the kernel trajectory during training is
        measure-zero.

        Shape:
            ``kernel`` : ``(k_h, k_w, C, C)``
            ``u``, ``v`` (power-iteration vectors): ``(H, W, C)``
            returns    : ``(k_h, k_w, C, C)``  (rescaled, grad-flowing)
        """
        # Persistent random seed: measure-zero probability of alignment
        # with ker(M_K). stop_gradient blocks gradient flow into the seed
        # field (it stays constant across training steps).
        u0 = lax.stop_gradient(self.spectral_seed)

        # Block gradients through the power iteration: we only want grads
        # through the *rescale* `kernel / sigma`, not through the estimate.
        kernel_sg = lax.stop_gradient(kernel)

        def body(_, u_vec):
            # v = M^T u, normalized  -> singular direction on input side.
            v_vec = self._circular_conv_transpose(u_vec, kernel_sg)  # (H, W, C)
            v_vec = v_vec / (jnp.linalg.norm(v_vec) + 1e-8)
            # u = M v, normalized    -> singular direction on output side.
            u_new = self._circular_conv(v_vec, kernel_sg)  # (H, W, C)
            return u_new / (jnp.linalg.norm(u_new) + 1e-8)

        # After n_power_iterations steps, u ~ leading left-singular vector.
        u = lax.fori_loop(0, self.n_power_iterations, body, u0)  # (H, W, C)
        # Final pairing to estimate sigma = ||M v|| where v = M^T u normalized.
        v = self._circular_conv_transpose(u, kernel_sg)  # (H, W, C)
        v = v / (jnp.linalg.norm(v) + 1e-8)
        sigma = jnp.linalg.norm(self._circular_conv(v, kernel_sg))  # scalar

        # max(sigma, 1): only rescale if the norm *exceeds* 1; otherwise
        # leave the kernel alone so near-identity init isn't perturbed.
        scale = jnp.maximum(lax.stop_gradient(sigma), 1.0)
        return kernel / (scale + 1e-8)  # (k_h, k_w, C, C)

    def _convolution_exponential(self, x: Array, kernel: Array) -> Array:
        r"""Apply the truncated matrix exponential $p_N(M_K)\,x$.

        Computes the partial Taylor sum

        $$
        r_N \;=\; \sum_{k=0}^{N} \frac{M_K^k\, x}{k!},
        $$

        via the recurrence $t_0 = x$, $t_{k+1} = \tfrac{1}{k+1} M_K\, t_k$,
        $r_{k+1} = r_k + t_{k+1}$. Each iteration costs one circular conv
        (``O(H W k_h k_w C^2)``); total cost scales linearly in ``n_terms``.

        Shape:
            ``x``, ``kernel``, returns as in `_circular_conv`.
        """

        def body(carry, i):
            prod, acc = carry  # both (H, W, C)
            # t_{k+1} = (1/(k+1)) * M_K * t_k
            prod = self._circular_conv(prod, kernel) / (i + 1)
            return (prod, acc + prod), None

        # carry0 = (t_0, r_0) = (x, x)  — the k=0 term is I*x = x.
        (_, result), _ = lax.scan(body, (x, x), jnp.arange(self.n_terms))
        return result  # (H, W, C)

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        """Forward map $y = \\exp(M_K)\\,x$ and scalar log-det (=0).

        Shape:
            ``x``    : ``(H, W, C)``
            returns  : ``((H, W, C), ())``
        """
        x_arr = jnp.asarray(x)  # (H, W, C)
        # 1) W -> K (skew)  2) K -> K / max(sigma, 1)  3) apply p_N(M_K)
        kernel = self._spectral_normalize(self._skew(self.weight))
        y = self._convolution_exponential(x_arr, kernel)  # (H, W, C)
        # Skew-symmetric M  =>  tr(M) = 0  =>  log|det exp(M)| = 0 exactly.
        return y, jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        """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), ())``
        """
        y_arr = jnp.asarray(y)  # (H, W, C)
        kernel = self._spectral_normalize(self._skew(self.weight))
        # exp(-M_K) via the same truncation with negated kernel.
        x = self._convolution_exponential(y_arr, -kernel)  # (H, W, C)
        return x, jnp.zeros(())

transform_and_log_det

transform_and_log_det(x: ArrayLike, condition=None)

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
def transform_and_log_det(self, x: ArrayLike, condition=None):
    """Forward map $y = \\exp(M_K)\\,x$ and scalar log-det (=0).

    Shape:
        ``x``    : ``(H, W, C)``
        returns  : ``((H, W, C), ())``
    """
    x_arr = jnp.asarray(x)  # (H, W, C)
    # 1) W -> K (skew)  2) K -> K / max(sigma, 1)  3) apply p_N(M_K)
    kernel = self._spectral_normalize(self._skew(self.weight))
    y = self._convolution_exponential(x_arr, kernel)  # (H, W, C)
    # Skew-symmetric M  =>  tr(M) = 0  =>  log|det exp(M)| = 0 exactly.
    return y, jnp.zeros(())

inverse_and_log_det

inverse_and_log_det(y: ArrayLike, condition=None)

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
def inverse_and_log_det(self, y: ArrayLike, condition=None):
    """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), ())``
    """
    y_arr = jnp.asarray(y)  # (H, W, C)
    kernel = self._spectral_normalize(self._skew(self.weight))
    # exp(-M_K) via the same truncation with negated kernel.
    x = self._convolution_exponential(y_arr, -kernel)  # (H, W, C)
    return x, jnp.zeros(())

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 (dim,).

required
w_init_scale float

Standard deviation used to initialise W and b.

0.01
use_bias bool

If False, drop the h(t) · b term.

True
time_bias_net _TimeGate | None

Optional scalar time gate h with h(0) = 0. Defaults to gauss_flows.TimeIdentity when use_bias=True.

None
Shape
  • Input x: (dim,)
  • Condition: packed time (1,) from gauss_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
class MatrixExponential(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``.

    Args:
        key: PRNG key for parameter initialisation.
        shape: Event shape ``(dim,)``.
        w_init_scale: Standard deviation used to initialise ``W`` and ``b``.
        use_bias: If ``False``, drop the ``h(t) · b`` term.
        time_bias_net: Optional scalar time gate ``h`` with ``h(0) = 0``.
            Defaults to `gauss_flows.TimeIdentity` when ``use_bias=True``.

    Shape:
        - Input ``x``: ``(dim,)``
        - Condition: packed time ``(1,)`` from `gauss_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)
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...]
    W: Array
    b: Array | None
    time_bias_net: _TimeGate | None

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        *,
        w_init_scale: float = 1e-2,
        use_bias: bool = True,
        time_bias_net: _TimeGate | None = None,
    ):
        if len(shape) != 1:
            raise ValueError("MatrixExponential only supports 1D inputs.")
        if not use_bias and time_bias_net is not None:
            raise ValueError(
                "time_bias_net was provided but use_bias=False; the gate would "
                "be ignored. Pass use_bias=True or leave time_bias_net=None."
            )

        n_dims = shape[0]
        key_w, key_b = jr.split(key) if use_bias else (key, None)
        self.shape = shape
        self.cond_shape = time_control_cond_shape(0)
        self.W = jr.normal(key_w, (n_dims, n_dims)) * w_init_scale
        self.b = jr.normal(key_b, (n_dims,)) * w_init_scale if use_bias else None
        self.time_bias_net = (
            TimeIdentity() if use_bias and time_bias_net is None else time_bias_net
        )

    @staticmethod
    def _unpack_scalar_time(condition: ArrayLike, *, dtype) -> Array:
        t, _ = unpack_time_control(jnp.asarray(condition, dtype=dtype), control_dim=0)
        if t.shape != (1,):
            raise ValueError(
                "MatrixExponential expects a single-example packed condition "
                "with shape (1,); got t.shape="
                f"{t.shape}. For batched conditions wrap the call in jax.vmap."
            )
        return t[0]

    def transform_and_log_det(
        self,
        x: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        if condition is None:
            raise ValueError(
                "MatrixExponential requires a packed time condition. "
                "Use pack_time_control(t)."
            )

        x = jnp.asarray(x)
        t_scalar = self._unpack_scalar_time(condition, dtype=x.dtype)
        M = jsp_linalg.expm(self.W * t_scalar)
        y = M @ x
        if self.b is not None and self.time_bias_net is not None:
            y = y + jnp.asarray(self.time_bias_net(t_scalar), dtype=x.dtype) * self.b
        log_det = t_scalar * jnp.trace(self.W)
        return y, log_det

    def inverse_and_log_det(
        self,
        y: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        if condition is None:
            raise ValueError(
                "MatrixExponential requires a packed time condition. "
                "Use pack_time_control(t)."
            )

        y = jnp.asarray(y)
        t_scalar = self._unpack_scalar_time(condition, dtype=y.dtype)
        y_shifted = y
        if self.b is not None and self.time_bias_net is not None:
            gate = jnp.asarray(self.time_bias_net(t_scalar), dtype=y.dtype)
            y_shifted = y_shifted - gate * self.b
        M_inv = jsp_linalg.expm(-self.W * t_scalar)
        x = M_inv @ y_shifted
        log_det = -t_scalar * jnp.trace(self.W)
        return x, log_det

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 is not divisible by 2.

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
class HaarWavelet(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.

    Args:
        shape: Event shape. The last dimension must be divisible by 2.

    Raises:
        ValueError: If the last dimension of ``shape`` is not divisible by 2.

    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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None

    def __init__(self, shape: tuple[int, ...]):
        if shape[-1] % 2 != 0:
            raise ValueError("Last dimension must be divisible by 2 for HaarWavelet.")
        self.shape = shape

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        # Haar wavelet: split into even/odd, compute averages and differences
        even = x[..., ::2]
        odd = x[..., 1::2]
        avg = (even + odd) / 2.0
        diff = (even - odd) / 2.0
        y = jnp.concatenate([avg, diff], axis=-1)
        # Log det: both avg and diff scale by 1/2, giving -n*log(2) total.
        log_det = -x.shape[-1] * jnp.log(2.0)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        y = jnp.asarray(y)
        n = y.shape[-1] // 2
        avg = y[..., :n]
        diff = y[..., n:]
        even = avg + diff
        odd = avg - diff
        # Interleave even and odd
        x = jnp.stack([even, odd], axis=-1).reshape((*y.shape[:-1], y.shape[-1]))
        log_det = x.shape[-1] * jnp.log(2.0)
        return x, log_det

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 (..., C); the last axis is the channel axis. For example (H, W, C) for an image or (C,) for a plain channel vector.

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
class ActNorm(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).

    Args:
        shape: Event shape ``(..., C)``; the last axis is the channel axis.
            For example ``(H, W, C)`` for an image or ``(C,)`` for a plain
            channel vector.

    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), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    loc: Array
    # a paramax.Parameterize leaf (see Reparametrised.parameter) that unwraps to
    # the positive scale; annotated Array as flowjax does for its own leaves
    scale: Array

    def __init__(self, shape: tuple[int, ...]):
        self.shape = shape
        n_dims = shape[-1]
        self.loc = jnp.zeros(n_dims)
        self.scale = _SCALE.parameter(jnp.full(n_dims, _INITIAL_SCALE))

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        scale = self.scale
        y = (jnp.asarray(x) - self.loc) / scale
        # Multiply by number of non-channel positions (spatial dims) so that
        # the log-det accounts for each broadcasted application of the scale.
        n_spatial = (
            int(jnp.prod(jnp.array(self.shape[:-1]))) if len(self.shape) > 1 else 1
        )
        log_det = -n_spatial * jnp.sum(jnp.log(scale))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        scale = self.scale
        x = jnp.asarray(y) * scale + self.loc
        n_spatial = (
            int(jnp.prod(jnp.array(self.shape[:-1]))) if len(self.shape) > 1 else 1
        )
        log_det = n_spatial * jnp.sum(jnp.log(scale))
        return x, log_det

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 (n_dims,). Must be 1-D.

required

Raises:

Type Description
ValueError

If shape is not 1-D.

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
class ActNorm1D(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).

    Args:
        shape: Event shape ``(n_dims,)``. Must be 1-D.

    Raises:
        ValueError: If ``shape`` is not 1-D.

    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,), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    loc: Array
    # a paramax.Parameterize leaf (see Reparametrised.parameter) that unwraps to
    # the positive scale; annotated Array as flowjax does for its own leaves
    scale: Array

    def __init__(self, shape: tuple[int, ...]):
        if len(shape) != 1:
            raise ValueError("ActNorm1D only supports 1D inputs.")
        n_dims = shape[0]
        self.shape = shape
        self.loc = jnp.zeros(n_dims)
        self.scale = _SCALE.parameter(jnp.full(n_dims, _INITIAL_SCALE))

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        scale = self.scale
        y = (jnp.asarray(x) - self.loc) / scale
        log_det = -jnp.sum(jnp.log(scale))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        scale = self.scale
        x = jnp.asarray(y) * scale + self.loc
        log_det = jnp.sum(jnp.log(scale))
        return x, log_det

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 vmap via .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 same batch_stats are in effect.
  • Evaluation: warm the running EMA via .update_running_stats_from_batch(...) (outside jit), 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 (n_dims,). Must be 1-D.

required
momentum float

Exponential moving-average factor for running statistics, updated as running = (1 - momentum) * running + momentum * batch. Must lie in (0, 1). Defaults to 0.1.

0.1
eps float

Numerical stability term added to the variance. Defaults to 1e-5.

1e-05
use_running_average bool

Whether to use running statistics (evaluation) rather than batch statistics. Defaults to False.

False

Raises:

Type Description
ValueError

If shape is not 1-D or momentum is outside (0, 1).

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:

bn_eval = bn.with_running_average(True)
y, _ = jax.vmap(bn_eval.transform_and_log_det)(batch)

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/bijections/normalization/batchnorm.py
class BatchNorm(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 ``vmap`` via
      ``.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 same ``batch_stats`` are in effect.
    - **Evaluation**: warm the running EMA via
      ``.update_running_stats_from_batch(...)`` (outside ``jit``), 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.

    Args:
        shape: Event shape ``(n_dims,)``. Must be 1-D.
        momentum: Exponential moving-average factor for running statistics,
            updated as ``running = (1 - momentum) * running + momentum * batch``.
            Must lie in ``(0, 1)``. Defaults to ``0.1``.
        eps: Numerical stability term added to the variance. Defaults to
            ``1e-5``.
        use_running_average: Whether to use running statistics (evaluation)
            rather than batch statistics. Defaults to ``False``.

    Raises:
        ValueError: If ``shape`` is not 1-D or ``momentum`` is outside
            ``(0, 1)``.

    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):
        ```python
        @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:
        ```python
        bn_eval = bn.with_running_average(True)
        y, _ = jax.vmap(bn_eval.transform_and_log_det)(batch)
        ```
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    momentum: float = eqx.field(static=True)
    eps: float = eqx.field(static=True)
    # use_running_average / use_batch_stats are Python bools kept in the pytree
    # (no static=True) so eqx.tree_at can target them. Python bools are already
    # static-in-practice for jit purposes since they are not JAX arrays.
    use_running_average: bool
    use_batch_stats: bool
    log_gamma: Array
    beta: Array
    running_mean: Array
    running_var: Array
    batch_stats: tuple[Array, Array]

    def __init__(
        self,
        shape: tuple[int, ...],
        momentum: float = 0.1,
        eps: float = 1e-5,
        *,
        use_running_average: bool = False,
    ):
        if len(shape) != 1:
            raise ValueError("BatchNorm only supports 1D inputs.")
        if not 0.0 < momentum < 1.0:
            raise ValueError(f"momentum must be in (0, 1), got {momentum}.")
        self.shape = shape
        self.momentum = momentum
        self.eps = eps
        self.use_running_average = use_running_average
        self.use_batch_stats = False
        n_dims = shape[0]
        self.log_gamma = jnp.zeros(n_dims)
        self.beta = jnp.zeros(n_dims)
        self.running_mean = jnp.zeros(n_dims)
        self.running_var = jnp.ones(n_dims)
        # Kept as a real tuple (never ``None``) so the pytree structure stays
        # constant across ``.with_batch_stats_from_data`` calls — jit does not
        # retrace and vmap does not see a structure mismatch.
        self.batch_stats = (jnp.zeros(n_dims), jnp.ones(n_dims))

    def _select_stats(self) -> tuple[Array, Array]:
        if self.use_running_average:
            return self.running_mean, self.running_var
        if self.use_batch_stats:
            return self.batch_stats
        raise RuntimeError(
            "BatchNorm needs a statistics source. Call "
            ".with_batch_stats_from_data(batch) before the forward pass for "
            "training, or .with_running_average(True) for evaluation."
        )

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x_arr = jnp.asarray(x)
        mean, var = self._select_stats()
        scale = jnp.exp(self.log_gamma) / jnp.sqrt(var + self.eps)
        y = (x_arr - mean) * scale + self.beta
        log_det = jnp.sum(self.log_gamma - 0.5 * jnp.log(var + self.eps))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        y_arr = jnp.asarray(y)
        mean, var = self._select_stats()
        scale = jnp.exp(-self.log_gamma) * jnp.sqrt(var + self.eps)
        x = (y_arr - self.beta) * scale + mean
        log_det = jnp.sum(-self.log_gamma + 0.5 * jnp.log(var + self.eps))
        return x, log_det

    def update_running_stats(
        self, batch_mean: ArrayLike, batch_var: ArrayLike
    ) -> BatchNorm:
        """Return a copy with running stats updated (call outside ``jit``)."""

        new_mean = (
            1 - self.momentum
        ) * self.running_mean + self.momentum * jnp.asarray(batch_mean)
        new_var = (1 - self.momentum) * self.running_var + self.momentum * jnp.asarray(
            batch_var
        )
        return eqx.tree_at(
            lambda m: (m.running_mean, m.running_var), self, (new_mean, new_var)
        )

    def update_running_stats_from_batch(self, batch: ArrayLike) -> BatchNorm:
        """Compute batch statistics from ``batch`` (shape ``(N, *self.shape)``)
        and update running buffers via the EMA."""

        batch_arr = jnp.asarray(batch)
        batch_mean = jnp.mean(batch_arr, axis=0)
        batch_var = jnp.var(batch_arr, axis=0)
        return self.update_running_stats(batch_mean, batch_var)

    def with_batch_stats_from_data(self, 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."""

        batch_arr = jnp.asarray(batch)
        batch_mean = jnp.mean(batch_arr, axis=0)
        batch_var = jnp.var(batch_arr, axis=0)
        return eqx.tree_at(
            lambda m: (m.batch_stats, m.use_batch_stats, m.use_running_average),
            self,
            ((batch_mean, batch_var), True, False),
        )

    def with_running_average(self, 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."""

        if use_running_average:
            return eqx.tree_at(
                lambda m: (m.use_running_average, m.use_batch_stats),
                self,
                (True, False),
            )
        return eqx.tree_at(lambda m: m.use_running_average, self, False)

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
def update_running_stats(
    self, batch_mean: ArrayLike, batch_var: ArrayLike
) -> BatchNorm:
    """Return a copy with running stats updated (call outside ``jit``)."""

    new_mean = (
        1 - self.momentum
    ) * self.running_mean + self.momentum * jnp.asarray(batch_mean)
    new_var = (1 - self.momentum) * self.running_var + self.momentum * jnp.asarray(
        batch_var
    )
    return eqx.tree_at(
        lambda m: (m.running_mean, m.running_var), self, (new_mean, new_var)
    )

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
def update_running_stats_from_batch(self, batch: ArrayLike) -> BatchNorm:
    """Compute batch statistics from ``batch`` (shape ``(N, *self.shape)``)
    and update running buffers via the EMA."""

    batch_arr = jnp.asarray(batch)
    batch_mean = jnp.mean(batch_arr, axis=0)
    batch_var = jnp.var(batch_arr, axis=0)
    return self.update_running_stats(batch_mean, batch_var)

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
def with_batch_stats_from_data(self, 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."""

    batch_arr = jnp.asarray(batch)
    batch_mean = jnp.mean(batch_arr, axis=0)
    batch_var = jnp.var(batch_arr, axis=0)
    return eqx.tree_at(
        lambda m: (m.batch_stats, m.use_batch_stats, m.use_running_average),
        self,
        ((batch_mean, batch_var), True, False),
    )

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
def with_running_average(self, 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."""

    if use_running_average:
        return eqx.tree_at(
            lambda m: (m.use_running_average, m.use_batch_stats),
            self,
            (True, False),
        )
    return eqx.tree_at(lambda m: m.use_running_average, self, False)

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 (..., C); the last axis is the channel axis.

required
symmetric_gamma bool

If True, symmetrize gamma (Ballé's convention).

False
beta_floor float

Floor added after softplus on beta. Defaults to 1e-5 (matches ActNorm).

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 lambda in (0, 1] for the inverse fixed point; smaller is more robust but slower. Defaults to 0.5.

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
class GeneralizedDivisiveNormalization(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((H*W*C)^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.

    Args:
        shape: Event shape ``(..., C)``; the last axis is the channel axis.
        symmetric_gamma: If True, symmetrize ``gamma`` (Ballé's convention).
        beta_floor: Floor added after ``softplus`` on ``beta``. Defaults to 1e-5
            (matches `ActNorm`).
        inverse_max_iters: Fixed-point iteration cap. Defaults to 100.
        inverse_tol: Fixed-point convergence tolerance. Defaults to 1e-6.
        inverse_damping: Damping ``lambda`` in ``(0, 1]`` for the inverse
            fixed point; smaller is more robust but slower. Defaults to 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), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    # paramax.Parameterize leaves (see Reparametrised.parameter) that unwrap to
    # the positive beta and gamma; annotated Array as flowjax does
    beta: Array
    gamma: Array
    symmetric_gamma: bool = eqx.field(static=True)
    beta_floor: float = eqx.field(static=True)
    inverse_max_iters: int = eqx.field(static=True)
    inverse_tol: float = eqx.field(static=True)
    inverse_damping: float = eqx.field(static=True)

    def __init__(
        self,
        shape: tuple[int, ...],
        *,
        symmetric_gamma: bool = False,
        beta_floor: float = 1e-5,
        inverse_max_iters: int = 100,
        inverse_tol: float = 1e-6,
        inverse_damping: float = 0.5,
    ):
        _validate_controls(beta_floor, inverse_max_iters, inverse_tol, inverse_damping)
        self.shape = shape
        self.symmetric_gamma = symmetric_gamma
        self.beta_floor = beta_floor
        self.inverse_max_iters = inverse_max_iters
        self.inverse_tol = inverse_tol
        self.inverse_damping = inverse_damping
        self.beta, self.gamma = _init_params(shape[-1], beta_floor)

    def _params(self) -> tuple[Array, Array]:
        # unwrap is a no-op on arrays, so this holds whether or not the caller
        # (flowjax's method wrapper) has already unwrapped the leaves
        beta = paramax.unwrap(self.beta)
        gamma = paramax.unwrap(self.gamma)
        if self.symmetric_gamma:
            gamma = 0.5 * (gamma + gamma.T)
        # Hold the diagonal at zero: a positive gamma_ii would let a coordinate
        # divide by its own energy, capping |y_i| < 1 / sqrt(gamma_ii). The
        # forward map would then land in a bounded box rather than all of R^D,
        # so it would not be a bijection and out-of-box targets would have no
        # preimage for the inverse fixed point. Cross-coordinate (off-diagonal)
        # gain control is what GDN is for; the self-term is dropped.
        gamma = gamma * (1.0 - jnp.eye(gamma.shape[-1], dtype=gamma.dtype))
        return beta, gamma

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        beta, gamma = self._params()
        y, log_det, _ = _forward(jnp.asarray(x), beta, gamma)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        beta, gamma = self._params()
        x, log_det, _ = _inverse(
            jnp.asarray(y),
            beta,
            gamma,
            self.inverse_max_iters,
            self.inverse_tol,
            self.inverse_damping,
        )
        return x, log_det

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 (D,). Must be 1-D.

required
symmetric_gamma bool

If True, symmetrize gamma (Ballé's convention).

False
beta_floor float

Floor added after softplus on beta. Defaults to 1e-5.

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 lambda in (0, 1] for the inverse fixed point. Defaults to 0.5.

0.5

Raises:

Type Description
ValueError

If shape is not 1-D.

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
class GeneralizedDivisiveNormalization1D(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).

    Args:
        shape: Event shape ``(D,)``. Must be 1-D.
        symmetric_gamma: If True, symmetrize ``gamma`` (Ballé's convention).
        beta_floor: Floor added after ``softplus`` on ``beta``. Defaults to 1e-5.
        inverse_max_iters: Fixed-point iteration cap. Defaults to 100.
        inverse_tol: Fixed-point convergence tolerance. Defaults to 1e-6.
        inverse_damping: Damping ``lambda`` in ``(0, 1]`` for the inverse
            fixed point. Defaults to 0.5.

    Raises:
        ValueError: If ``shape`` is not 1-D.

    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,), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    # paramax.Parameterize leaves (see Reparametrised.parameter) that unwrap to
    # the positive beta and gamma; annotated Array as flowjax does
    beta: Array
    gamma: Array
    symmetric_gamma: bool = eqx.field(static=True)
    beta_floor: float = eqx.field(static=True)
    inverse_max_iters: int = eqx.field(static=True)
    inverse_tol: float = eqx.field(static=True)
    inverse_damping: float = eqx.field(static=True)

    def __init__(
        self,
        shape: tuple[int, ...],
        *,
        symmetric_gamma: bool = False,
        beta_floor: float = 1e-5,
        inverse_max_iters: int = 100,
        inverse_tol: float = 1e-6,
        inverse_damping: float = 0.5,
    ):
        if len(shape) != 1:
            raise ValueError(
                "GeneralizedDivisiveNormalization1D only supports 1D inputs."
            )
        _validate_controls(beta_floor, inverse_max_iters, inverse_tol, inverse_damping)
        self.shape = shape
        self.symmetric_gamma = symmetric_gamma
        self.beta_floor = beta_floor
        self.inverse_max_iters = inverse_max_iters
        self.inverse_tol = inverse_tol
        self.inverse_damping = inverse_damping
        self.beta, self.gamma = _init_params(shape[0], beta_floor)

    def _params(self) -> tuple[Array, Array]:
        # unwrap is a no-op on arrays, so this holds whether or not the caller
        # (flowjax's method wrapper) has already unwrapped the leaves
        beta = paramax.unwrap(self.beta)
        gamma = paramax.unwrap(self.gamma)
        if self.symmetric_gamma:
            gamma = 0.5 * (gamma + gamma.T)
        # Hold the diagonal at zero: a positive gamma_ii would let a coordinate
        # divide by its own energy, capping |y_i| < 1 / sqrt(gamma_ii). The
        # forward map would then land in a bounded box rather than all of R^D,
        # so it would not be a bijection and out-of-box targets would have no
        # preimage for the inverse fixed point. Cross-coordinate (off-diagonal)
        # gain control is what GDN is for; the self-term is dropped.
        gamma = gamma * (1.0 - jnp.eye(gamma.shape[-1], dtype=gamma.dtype))
        return beta, gamma

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        beta, gamma = self._params()
        y, log_det, _ = _forward(jnp.asarray(x), beta, gamma)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        beta, gamma = self._params()
        x, log_det, _ = _inverse(
            jnp.asarray(y),
            beta,
            gamma,
            self.inverse_max_iters,
            self.inverse_tol,
            self.inverse_damping,
        )
        return x, log_det

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 [0, n_dims).

required
shape tuple[int, ...]

Event shape (n_dims,). Must be 1-D.

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 len(ind). Defaults to 0.0.

0.0

Raises:

Type Description
ValueError

If shape is not 1-D, if any index is out of range or duplicated, or if shift_init has an incompatible shape.

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
class PeriodicShift(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.

    Args:
        ind: Indices of periodic dimensions to shift. Must be unique and lie in
            ``[0, n_dims)``.
        shape: Event shape ``(n_dims,)``. Must be 1-D.
        bound: Half-width of the periodic interval. Defaults to ``π``.
        shift_init: Initial shift. Either a scalar (broadcast to every index) or
            a 1-D array of length ``len(ind)``. Defaults to ``0.0``.

    Raises:
        ValueError: If ``shape`` is not 1-D, if any index is out of range or
            duplicated, or if ``shift_init`` has an incompatible shape.

    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)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    bound: float
    mask: Array  # boolean mask over the full event, used for re-wrapping only
    indices: Array  # integer indices in `ind` order, used for shift scatter
    shift: Array

    def __init__(
        self,
        ind: Iterable[int],
        shape: tuple[int, ...],
        bound: float = jnp.pi,
        shift_init: Array | float = 0.0,
    ):
        if len(shape) != 1:
            raise ValueError("PeriodicShift only supports 1D inputs.")
        n_dims = shape[0]
        ind = tuple(ind)
        if any(i < 0 or i >= n_dims for i in ind):
            raise ValueError("All indices in ind must be within [0, n_dims).")
        if len(set(ind)) != len(ind):
            raise ValueError("ind must not contain duplicate indices.")
        self.shape = shape
        self.bound = float(bound)
        self.mask = _build_periodic_mask(ind, n_dims)
        self.indices = jnp.asarray(ind, dtype=jnp.int32)
        shift_values = jnp.asarray(shift_init, dtype=jnp.float32)
        if shift_values.ndim == 0:
            shift_values = jnp.broadcast_to(shift_values, (len(ind),))
        elif shift_values.shape != (len(ind),):
            raise ValueError(
                "shift_init must be scalar or match the number of indices."
            )
        self.shift = shift_values

    def _apply(self, x: Array, sign: float) -> Array:
        # Scatter via integer indices so the shift values stay aligned with
        # `ind` order (boolean-mask scatter would silently sort by index).
        shift_vec = jnp.zeros_like(x).at[self.indices].set(sign * self.shift)
        return _wrap_angles(x + shift_vec, self.mask, self.bound)

    def transform_and_log_det(self, x: Array, condition=None) -> tuple[Array, Array]:
        return self._apply(jnp.asarray(x), 1.0), jnp.zeros(())

    def inverse_and_log_det(self, y: Array, condition=None) -> tuple[Array, Array]:
        return self._apply(jnp.asarray(y), -1.0), jnp.zeros(())

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 [0, n_dims).

required
shape tuple[int, ...]

Event shape (n_dims,). Must be 1-D.

required
bound float

Half-width of the periodic interval. Defaults to π.

pi

Raises:

Type Description
ValueError

If shape is not 1-D or any index is out of range.

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 original x; 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
class PeriodicWrap(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.

    Args:
        ind: Indices of periodic dimensions to wrap. Must lie in
            ``[0, n_dims)``.
        shape: Event shape ``(n_dims,)``. Must be 1-D.
        bound: Half-width of the periodic interval. Defaults to ``π``.

    Raises:
        ValueError: If ``shape`` is not 1-D or any index is out of range.

    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 original ``x``; 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
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    bound: float
    mask: Array

    def __init__(
        self,
        ind: Iterable[int],
        shape: tuple[int, ...],
        bound: float = jnp.pi,
    ):
        if len(shape) != 1:
            raise ValueError("PeriodicWrap only supports 1D inputs.")
        n_dims = shape[0]
        ind = tuple(ind)
        if any(i < 0 or i >= n_dims for i in ind):
            raise ValueError("All indices in ind must be within [0, n_dims).")
        self.shape = shape
        self.bound = float(bound)
        self.mask = _build_periodic_mask(ind, n_dims)

    def transform_and_log_det(self, x: Array, condition=None) -> tuple[Array, Array]:
        x_arr = jnp.asarray(x)
        y = _wrap_angles(x_arr, self.mask, self.bound)
        return y, jnp.zeros(())

    def inverse_and_log_det(self, y: Array, condition=None) -> tuple[Array, Array]:
        y_arr = jnp.asarray(y)
        x = _wrap_angles(y_arr, self.mask, self.bound)
        return x, jnp.zeros(())

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,) with n even → (n // 2, 2): split into adjacent pairs.
  • 2-D (H, C) with H even → (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 (n,) or (H, C); the leading axis must be even in those two cases. Higher-rank shapes are accepted but unchanged.

required

Raises:

Type Description
ValueError

If the leading axis of a 1-D or 2-D shape is not even.

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
class Squeeze(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,)`` with ``n`` even → ``(n // 2, 2)``: split into adjacent pairs.
    - 2-D ``(H, C)`` with ``H`` even → ``(H // 2, 2·C)``: fold pairs of rows
      into the channel axis.
    - Higher rank: pass through unchanged (identity reshape).

    Args:
        shape: Event shape ``(n,)`` or ``(H, C)``; the leading axis must be even
            in those two cases. Higher-rank shapes are accepted but unchanged.

    Raises:
        ValueError: If the leading axis of a 1-D or 2-D ``shape`` is not even.

    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)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    out_shape: tuple[int, ...]

    def __init__(self, shape: tuple[int, ...]):
        self.shape = shape
        if len(shape) == 1:
            # 1D case: split into two halves → (n//2, 2)
            n = shape[0]
            if n % 2 != 0:
                raise ValueError("1D squeeze requires even dimension size.")
            self.out_shape = (n // 2, 2)
        elif len(shape) == 2:
            h, c = shape
            if h % 2 != 0:
                raise ValueError("Height must be divisible by 2 for Squeeze.")
            self.out_shape = (h // 2, c * 2)
        else:
            self.out_shape = shape

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        # Volume-preserving: log det = 0
        return jnp.asarray(x).reshape(self.out_shape), jnp.zeros(())

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        return jnp.asarray(y).reshape(self.shape), jnp.zeros(())

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 u and w.

required
shape tuple[int, ...]

Event shape (n_dims,). Must be 1-D.

required
scale_init float

Std of the Gaussian used to initialise u and w. Defaults to 0.01.

0.01

Raises:

Type Description
ValueError

If shape is not 1-D.

NotImplementedError

From inverse_and_log_det — there is no algebraic inverse.

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
class PlanarFlow(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`.

    Args:
        key: PRNG key used to initialise ``u`` and ``w``.
        shape: Event shape ``(n_dims,)``. Must be 1-D.
        scale_init: Std of the Gaussian used to initialise ``u`` and ``w``.
            Defaults to ``0.01``.

    Raises:
        ValueError: If ``shape`` is not 1-D.
        NotImplementedError: From ``inverse_and_log_det`` — there is no
            algebraic inverse.

    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,), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    u: Array
    w: Array
    b: Array

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        scale_init: float = 0.01,
    ):
        if len(shape) != 1:
            raise ValueError("PlanarFlow only supports 1D inputs.")
        d = shape[0]
        k_u, k_w = jr.split(key)
        self.shape = shape
        self.u = jr.normal(k_u, (d,)) * scale_init
        self.w = jr.normal(k_w, (d,)) * scale_init
        self.b = jnp.zeros(())

    def _u_hat(self) -> Array:
        wu = jnp.dot(self.w, self.u)
        m = _CONSTRAINT.forward(wu)
        w_norm_sq = jnp.sum(self.w**2) + 1e-12
        return self.u + (m - wu) * self.w / w_norm_sq

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        u_hat = self._u_hat()
        a = jnp.dot(self.w, x) + self.b
        y = x + u_hat * jnp.tanh(a)
        psi_dot_w = (1.0 - jnp.tanh(a) ** 2) * jnp.dot(u_hat, self.w)
        log_det = jnp.log(jnp.abs(1.0 + psi_dot_w) + 1e-12)
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        raise NotImplementedError(
            "PlanarFlow has no algebraic inverse; use sample_and_log_prob in the "
            "generative direction (VI). log_prob of arbitrary points is not supported."
        )

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 (n_dims,). Must be 1-D.

required
rank int | None

Rank M of the flow. Defaults to the full input dim D.

None
scale_init float

Std of the Gaussian used to initialise the Householder vectors (offset from the identity), the strict upper-triangular entries of R and R̃, and their raw diagonal parameter vectors. Defaults to 0.01.

0.01

Raises:

Type Description
ValueError

If shape is not 1-D or rank is outside [1, D].

NotImplementedError

From inverse_and_log_det — there is no algebraic inverse.

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
class SylvesterFlow(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`.

    Args:
        key: PRNG key used to initialise all parameters.
        shape: Event shape ``(n_dims,)``. Must be 1-D.
        rank: Rank ``M`` of the flow. Defaults to the full input dim ``D``.
        scale_init: Std of the Gaussian used to initialise the Householder
            vectors (offset from the identity), the strict upper-triangular
            entries of ``R`` and ``R̃``, and their raw diagonal parameter
            vectors. Defaults to ``0.01``.

    Raises:
        ValueError: If ``shape`` is not 1-D or ``rank`` is outside ``[1, D]``.
        NotImplementedError: From ``inverse_and_log_det`` — there is no
            algebraic inverse.

    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,), ())
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    householder_vectors: Array
    R_raw_diag: Array
    R_upper: Array
    R_tilde_raw_diag: Array
    R_tilde_upper: Array
    b: Array

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        rank: int | None = None,
        scale_init: float = 0.01,
    ):
        if len(shape) != 1:
            raise ValueError("SylvesterFlow only supports 1D inputs.")
        d = shape[0]
        if rank is None:
            rank = d
        if not 1 <= rank <= d:
            raise ValueError(f"rank must be in [1, {d}], got {rank}.")
        m = rank
        self.shape = shape
        n_strict = m * (m - 1) // 2
        k_hh, k_rd, k_ru, k_td, k_tu = jr.split(key, 5)
        # Initialise Householder vectors away from zero to avoid degenerate norms
        self.householder_vectors = (
            jr.normal(k_hh, (m, d)) * scale_init + jnp.eye(m, d) * 1.0
        )
        self.R_raw_diag = jr.normal(k_rd, (m,)) * scale_init
        self.R_upper = jr.normal(k_ru, (n_strict,)) * scale_init
        self.R_tilde_raw_diag = jr.normal(k_td, (m,)) * scale_init
        self.R_tilde_upper = jr.normal(k_tu, (n_strict,)) * scale_init
        self.b = jnp.zeros((m,))

    def _q_transpose_apply(self, x: Array) -> Array:
        """Compute ``Q.T @ x`` without materialising Q.

        ``Q = (H_1 H_2 ... H_M) @ E`` where ``E = I_D[:, :M]`` selects the
        first M columns. So ``Q.T @ x = E.T @ (H_M ... H_1) @ x``: apply
        Householders ``H_1, ..., H_M`` in order, then take the leading M
        components.
        """

        def body(carry, vec):
            v_norm = vec / (jnp.linalg.norm(vec) + 1e-12)
            return carry - 2.0 * v_norm * jnp.dot(v_norm, carry), None

        result, _ = jax.lax.scan(body, x, self.householder_vectors)
        m = self.householder_vectors.shape[0]
        return result[:m]

    def _q_apply(self, v: Array) -> Array:
        """Compute ``Q @ v`` without materialising Q.

        Pad ``v`` (shape ``(M,)``) to ``D`` with zeros, then apply the
        Householder reflections in reverse order.
        """
        d = self.shape[0]
        w = jnp.zeros(d).at[: v.shape[0]].set(v)

        def body(carry, vec):
            v_norm = vec / (jnp.linalg.norm(vec) + 1e-12)
            return carry - 2.0 * v_norm * jnp.dot(v_norm, carry), None

        result, _ = jax.lax.scan(body, w, self.householder_vectors[::-1])
        return result

    def _build_Q(self) -> Array:
        """Materialise ``Q`` as a ``(D, M)`` matrix.

        Used by tests to verify orthonormality. The hot path
        (``transform_and_log_det``) uses `_q_apply` /
        `_q_transpose_apply` and never builds this matrix.
        """
        m = self.householder_vectors.shape[0]
        return jax.vmap(self._q_apply, in_axes=1, out_axes=1)(jnp.eye(m))

    def _build_upper_triangular(self, diag: Array, strict_upper: Array) -> Array:
        m = diag.shape[0]
        R = jnp.diag(diag)
        if m > 1:
            upper_idx = jnp.triu_indices(m, k=1)
            R = R.at[upper_idx].set(strict_upper)
        return R

    def _build_RR_tilde(self) -> tuple[Array, Array, Array, Array]:
        # Constrain |diag(R) * diag(R_tilde)| < 1 for invertibility.
        r_diag = jnp.tanh(self.R_raw_diag)
        r_tilde_diag = jnp.tanh(self.R_tilde_raw_diag)
        R = self._build_upper_triangular(r_diag, self.R_upper)
        R_tilde = self._build_upper_triangular(r_tilde_diag, self.R_tilde_upper)
        return R, R_tilde, r_diag, r_tilde_diag

    def transform_and_log_det(self, x: ArrayLike, condition=None):
        x = jnp.asarray(x)
        R, R_tilde, r_diag, r_tilde_diag = self._build_RR_tilde()
        z = R @ self._q_transpose_apply(x) + self.b
        y = x + self._q_apply(R_tilde @ jnp.tanh(z))
        # Sylvester's identity: det(I_D + Q R_tilde diag(h') R Q^T)
        # = det(I_M + R_tilde diag(h') R). Both R, R_tilde upper-triangular, so
        # the result is upper-triangular with diagonal
        # 1 + diag(R_tilde) * h'(z) * diag(R).
        h_prime = 1.0 - jnp.tanh(z) ** 2
        diag_term = 1.0 + r_tilde_diag * h_prime * r_diag
        log_det = jnp.sum(jnp.log(jnp.abs(diag_term) + 1e-12))
        return y, log_det

    def inverse_and_log_det(self, y: ArrayLike, condition=None):
        raise NotImplementedError(
            "SylvesterFlow has no algebraic inverse; use sample_and_log_prob in "
            "the generative direction (VI). log_prob of arbitrary points is not "
            "supported."
        )

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,

\[ \log p_X(x(0)) \;=\; \log p_Z(x(1)) + \int_0^1 \nabla\!\cdot\, v_\theta\big(t, x(t)\big)\,\mathrm{d}t, \]

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 (dim,).

required
vector_field _VectorField | None

Module with signature f(ode_time, x, condition) -> dx_dt. When omitted, a default gauss_flows.DiffeqMLP is created.

None
control_dim int

Size of the packed control vector c.

0
t_span tuple[float, float]

Integration interval (t0, t1).

(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" or "exact".

'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] via gauss_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
class FFJORD(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.

    Args:
        key: PRNG key for the default vector field and Hutchinson probes.
        shape: Event shape ``(dim,)``.
        vector_field: Module with signature
            ``f(ode_time, x, condition) -> dx_dt``. When omitted, a default
            `gauss_flows.DiffeqMLP` is created.
        control_dim: Size of the packed control vector ``c``.
        t_span: Integration interval ``(t0, t1)``.
        solver: ODE solver name.
        adjoint: Diffrax adjoint name.
        rtol: Relative tolerance for adaptive solvers.
        atol: Absolute tolerance for adaptive solvers.
        divergence_mode: ``"hutchinson"`` or ``"exact"``.
        n_hutchinson_samples: Number of Hutchinson probes.
        probe_distribution: Probe distribution for Hutchinson estimation.

    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]`` via `gauss_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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    control_dim: int = eqx.field(static=True)
    vector_field: _VectorField
    trace_key: PRNGKeyArray
    t_span: tuple[float, float] = eqx.field(static=True)
    solver: _SolverName = eqx.field(static=True)
    adjoint: _AdjointName = eqx.field(static=True)
    rtol: float = eqx.field(static=True)
    atol: float = eqx.field(static=True)
    divergence_mode: _DivergenceMode = eqx.field(static=True)
    n_hutchinson_samples: int = eqx.field(static=True)
    probe_distribution: _ProbeDistribution = eqx.field(static=True)

    def __init__(
        self,
        key: PRNGKeyArray,
        shape: tuple[int, ...],
        *,
        vector_field: _VectorField | None = None,
        control_dim: int = 0,
        t_span: tuple[float, float] = (0.0, 1.0),
        solver: _SolverName = "tsit5",
        adjoint: _AdjointName = "recursive_checkpoint",
        rtol: float = 1e-5,
        atol: float = 1e-5,
        divergence_mode: _DivergenceMode = "hutchinson",
        n_hutchinson_samples: int = 1,
        probe_distribution: _ProbeDistribution = "rademacher",
    ):
        if len(shape) != 1:
            raise ValueError("FFJORD only supports 1D event shapes.")
        if shape[0] < 1:
            raise ValueError(f"shape must have a positive dimension; got {shape}.")
        if control_dim < 0:
            raise ValueError(
                "control_dim must be non-negative "
                f"(got {control_dim}); use 0 for unconditional models."
            )
        if n_hutchinson_samples < 1:
            raise ValueError(
                f"n_hutchinson_samples must be positive; got {n_hutchinson_samples}."
            )
        if t_span[0] == t_span[1]:
            raise ValueError("t_span endpoints must differ.")
        if divergence_mode not in ("hutchinson", "exact"):
            raise ValueError(
                "divergence_mode must be 'hutchinson' or 'exact'; "
                f"got {divergence_mode!r}."
            )
        if probe_distribution not in ("rademacher", "normal"):
            raise ValueError(
                "probe_distribution must be 'rademacher' or 'normal'; "
                f"got {probe_distribution!r}."
            )
        if solver not in _SOLVER_NAMES:
            raise ValueError(f"solver must be one of {_SOLVER_NAMES}; got {solver!r}.")
        if adjoint not in _ADJOINT_NAMES:
            raise ValueError(
                f"adjoint must be one of {_ADJOINT_NAMES}; got {adjoint!r}."
            )

        key_vf, key_trace = jr.split(key)
        self.shape = shape
        # control_dim == 0 is a genuinely unconditional FFJORD: the vector
        # field gets the ODE's own time from diffrax, so there's no "outer"
        # time to pack. Setting cond_shape=None makes condition=None valid
        # at the flowjax layer (matching other unconditional bijections).
        self.cond_shape = (
            None if control_dim == 0 else time_control_cond_shape(control_dim)
        )
        self.control_dim = control_dim
        self.vector_field = (
            DiffeqMLP(key_vf, in_dim=shape[0], control_dim=control_dim)
            if vector_field is None
            else vector_field
        )
        self.trace_key = key_trace
        self.t_span = t_span
        self.solver = solver
        self.adjoint = adjoint
        self.rtol = rtol
        self.atol = atol
        self.divergence_mode = divergence_mode
        self.n_hutchinson_samples = n_hutchinson_samples
        self.probe_distribution = probe_distribution

    def transform_and_log_det(
        self,
        x: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        return self._solve(
            jnp.asarray(x), condition, t0=self.t_span[0], t1=self.t_span[1]
        )

    def inverse_and_log_det(
        self,
        y: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> tuple[Array, Array]:
        return self._solve(
            jnp.asarray(y), condition, t0=self.t_span[1], t1=self.t_span[0]
        )

    def _solve(
        self,
        x0: Array,
        condition: ArrayLike | None,
        *,
        t0: float,
        t1: float,
    ) -> tuple[Array, Array]:
        if condition is None:
            if self.control_dim != 0:
                raise ValueError(
                    "FFJORD requires a packed condition when control_dim > 0. "
                    "Use pack_time_control(t, control)."
                )
            condition_array: Array | None = None
        else:
            if self.control_dim == 0:
                raise ValueError(
                    "FFJORD with control_dim=0 is unconditional (cond_shape is "
                    "None); pass condition=None rather than a packed value. "
                    "A non-None condition here would be silently dropped by "
                    "the default DiffeqMLP (or silently consumed by a custom "
                    "vector field), violating the advertised contract."
                )
            condition_array = jnp.asarray(condition, dtype=x0.dtype)

        def augmented_vector_field(
            ode_time: Array,
            state: tuple[Array, Array],
            packed_condition: Array | None,
        ) -> tuple[Array, Array]:
            x_state, _ = state
            dx_dt = self.vector_field(ode_time, x_state, packed_condition)
            div = self._divergence(ode_time, x_state, packed_condition)
            return dx_dt, div

        return solve_augmented_dynamics(
            augmented_vector_field,
            x0=x0,
            condition=condition_array,
            t0=t0,
            t1=t1,
            solver=self.solver,
            adjoint=self.adjoint,
            rtol=self.rtol,
            atol=self.atol,
        )

    def _divergence(
        self,
        ode_time: Array,
        x: Array,
        condition: Array | None,
    ) -> Array:
        # J = ∂f/∂x at (t, x), as a matrix-free operator applied by JVPs. gaussx owns
        # both modes: functax.diffops.divergence gives the same exact value and
        # gradients but has no stochastic estimator.
        jacobian = lx.JacobianLinearOperator(
            lambda x_, _: self.vector_field(ode_time, x_, condition), x, jac="fwd"
        )
        if self.divergence_mode == "exact":
            # tr(J), from the materialised (dim, dim) Jacobian
            return gaussx.trace(jacobian)
        # tr(J) ≈ (1/N) ∑ᵢ zᵢᵀ J zᵢ, with the fixed probes of trace_key
        return gaussx.trace(
            jacobian,
            stochastic=True,
            num_probes=self.n_hutchinson_samples,
            key=self.trace_key,
            sampler=_GAUSSX_SAMPLERS[self.probe_distribution],
            algorithm="hutchinson",
        )

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 dim.

required
control_dim int

Size of the optional control vector c.

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,) or None when control_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
class DiffeqMLP(eqx.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.

    Args:
        key: PRNG key for network initialisation.
        in_dim: Event dimension ``dim``.
        control_dim: Size of the optional control vector ``c``.
        hidden: Hidden-layer widths.
        activation: Non-linearity applied after each hidden layer.

    Shape:
        - Input ``ode_time``: ``()`` or ``(1,)``
        - Input ``x``: ``(dim,)``
        - Input ``condition``: ``(1 + control_dim,)`` or ``None`` when
          ``control_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,)
    """

    in_dim: int = eqx.field(static=True)
    control_dim: int = eqx.field(static=True)
    mlp: _MLPHead

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        in_dim: int,
        control_dim: int = 0,
        hidden: int | Sequence[int] = (64, 64),
        activation: Callable[[Array], Array] = jnn.tanh,
    ):
        if in_dim < 1:
            raise ValueError(f"in_dim must be positive; got {in_dim}.")
        if control_dim < 0:
            raise ValueError(f"control_dim must be non-negative; got {control_dim}.")

        hidden_sizes = _hidden_sizes(hidden)
        # unconditional: [ode_time, x] -> (1 + dim)
        # conditional: [ode_time, x, t_query, c] -> (2 + dim + control_dim)
        input_dim = 1 + in_dim if control_dim == 0 else 2 + in_dim + control_dim
        self.in_dim = in_dim
        self.control_dim = control_dim
        self.mlp = _MLPHead(
            key,
            input_dim=input_dim,
            output_dim=in_dim,
            hidden=hidden_sizes,
            activation=activation,
        )

    def __call__(
        self,
        ode_time: ArrayLike,
        x: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> Array:
        x_array = jnp.asarray(x)
        ode_time_scalar = jnp.reshape(_as_scalar_time(ode_time), (1,))
        condition_features = _maybe_condition_features(
            condition,
            self.control_dim,
            dtype=x_array.dtype,
        )
        # [ode_time, x, t_query, c?]: (1 + dim + maybe(1 + control_dim),)
        features = jnp.concatenate((ode_time_scalar, x_array, condition_features))
        return self.mlp(features)

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 dim.

required
control_dim int

Size of the optional control vector c.

0
hidden int | Sequence[int]

Hidden-layer widths.

(64, 64)
time_net _TimeNet | None

Optional scalar time embedding. When omitted, a gauss_flows.TimeFourier module is created.

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,) or None when control_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
class DiffeqConcat(eqx.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`.

    Args:
        key: PRNG key for the MLP and default time net.
        in_dim: Event dimension ``dim``.
        control_dim: Size of the optional control vector ``c``.
        hidden: Hidden-layer widths.
        time_net: Optional scalar time embedding. When omitted, a
            `gauss_flows.TimeFourier` module is created.
        activation: Non-linearity applied after each hidden layer.

    Shape:
        - Input ``ode_time``: ``()`` or ``(1,)``
        - Input ``x``: ``(dim,)``
        - Input ``condition``: ``(1 + control_dim,)`` or ``None`` when
          ``control_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,)
    """

    in_dim: int = eqx.field(static=True)
    control_dim: int = eqx.field(static=True)
    time_net: _TimeNet
    mlp: _MLPHead

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        in_dim: int,
        control_dim: int = 0,
        hidden: int | Sequence[int] = (64, 64),
        time_net: _TimeNet | None = None,
        activation: Callable[[Array], Array] = jnn.tanh,
    ):
        if in_dim < 1:
            raise ValueError(f"in_dim must be positive; got {in_dim}.")
        if control_dim < 0:
            raise ValueError(f"control_dim must be non-negative; got {control_dim}.")

        key_mlp, key_time = jr.split(key)
        hidden_sizes = _hidden_sizes(hidden)
        # unconditional: [time_net(ode_time), x] -> (1 + dim)
        # conditional: [time_net(ode_time), x, t_query, c] -> (2 + dim + control_dim)
        input_dim = 1 + in_dim if control_dim == 0 else 2 + in_dim + control_dim
        self.in_dim = in_dim
        self.control_dim = control_dim
        self.time_net = TimeFourier(key_time) if time_net is None else time_net
        self.mlp = _MLPHead(
            key_mlp,
            input_dim=input_dim,
            output_dim=in_dim,
            hidden=hidden_sizes,
            activation=activation,
        )

    def __call__(
        self,
        ode_time: ArrayLike,
        x: ArrayLike,
        condition: ArrayLike | None = None,
    ) -> Array:
        x_array = jnp.asarray(x)
        embedded_time = jnp.reshape(
            jnp.asarray(self.time_net(_as_scalar_time(ode_time)), dtype=x_array.dtype),
            (1,),
        )
        condition_features = _maybe_condition_features(
            condition,
            self.control_dim,
            dtype=x_array.dtype,
        )
        # [time_net(ode_time), x, t_query, c?]: (1 + dim + maybe(1 + control_dim),)
        features = jnp.concatenate((embedded_time, x_array, condition_features))
        return self.mlp(features)

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
class TimeIdentity(eqx.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
    """

    def __call__(self, t: ArrayLike) -> Array:
        return _scalar_time(t)

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
class TimeTanh(eqx.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``.

    Args:
        key: PRNG key for parameter initialisation.
        embedding_dim: Number of tanh features.

    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
    """

    slopes: Array
    weights: Array

    def __init__(self, key: PRNGKeyArray, embedding_dim: int = 16):
        if embedding_dim < 1:
            raise ValueError(f"embedding_dim must be positive; got {embedding_dim}.")
        key_slope, key_weight = jr.split(key)
        self.slopes = jr.normal(key_slope, (embedding_dim,))
        self.weights = jr.normal(key_weight, (embedding_dim,)) * 0.1

    def __call__(self, t: ArrayLike) -> Array:
        t_scalar = _scalar_time(t)
        return jnp.dot(self.weights, jnp.tanh(self.slopes * t_scalar))

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
class TimeFourier(eqx.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``.

    Args:
        key: PRNG key for parameter initialisation.
        embedding_dim: Number of sinusoidal features.

    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
    """

    frequencies: Array
    weights: Array

    def __init__(self, key: PRNGKeyArray, embedding_dim: int = 16):
        if embedding_dim < 1:
            raise ValueError(f"embedding_dim must be positive; got {embedding_dim}.")
        key_freq, key_weight = jr.split(key)
        self.frequencies = jr.normal(key_freq, (embedding_dim,))
        self.weights = jr.normal(key_weight, (embedding_dim,)) * 0.1

    def __call__(self, t: ArrayLike) -> Array:
        t_scalar = _scalar_time(t)
        return jnp.dot(self.weights, jnp.sin(self.frequencies * t_scalar))

pack_time_control

pack_time_control(t: ArrayLike, control: ArrayLike | None = None) -> Array

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 (...,) or (..., 1).

required
control ArrayLike | None

Optional control vector with shape (..., C).

None

Returns:

Type Description
Array

Packed condition with shape (..., 1 + C) — or (..., 1) when

Array

control is None.

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
def pack_time_control(
    t: ArrayLike,
    control: ArrayLike | None = None,
) -> Array:
    """Pack time and optional control vector into one condition array.

    Args:
        t: Scalar time value or an array with shape ``(...,)`` or ``(..., 1)``.
        control: Optional control vector with shape ``(..., C)``.

    Returns:
        Packed condition with shape ``(..., 1 + C)`` — or ``(..., 1)`` when
        ``control`` is ``None``.

    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)
    """
    t_array = _as_time_column(t)
    if control is None:
        return t_array

    control_array = jnp.atleast_1d(jnp.asarray(control))
    if t_array.shape[:-1] != control_array.shape[:-1]:
        raise ValueError(
            "t and control must share the same leading batch shape; "
            f"got {t_array.shape[:-1]} and {control_array.shape[:-1]}."
        )
    return jnp.concatenate((t_array, control_array), axis=-1)

unpack_time_control

unpack_time_control(condition: Array, control_dim: int = 0) -> tuple[Array, Array | None]

Unpack a packed (time, control) condition.

Parameters:

Name Type Description Default
condition Array

Packed condition with shape (..., 1 + control_dim).

required
control_dim int

Size of the control vector. Use 0 for time-only conditioning.

0

Returns:

Type Description
Array

A tuple (t, control) where t has shape (..., 1) and

Array | None

control has shape (..., control_dim) or is 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
def unpack_time_control(
    condition: Array,
    control_dim: int = 0,
) -> tuple[Array, Array | None]:
    """Unpack a packed ``(time, control)`` condition.

    Args:
        condition: Packed condition with shape ``(..., 1 + control_dim)``.
        control_dim: Size of the control vector. Use ``0`` for time-only
            conditioning.

    Returns:
        A tuple ``(t, control)`` where ``t`` has shape ``(..., 1)`` and
        ``control`` has shape ``(..., control_dim)`` or is ``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,))
    """
    _validate_control_dim(control_dim)
    condition = jnp.asarray(condition)
    if condition.ndim == 0:
        raise ValueError("condition must have at least one dimension.")

    expected = 1 + control_dim
    if condition.shape[-1] != expected:
        raise ValueError(
            "condition has incompatible trailing dimension; "
            f"expected {expected}, got {condition.shape[-1]}."
        )

    t = condition[..., :1]
    if control_dim == 0:
        return t, None
    return t, condition[..., 1:]

time_control_cond_shape

time_control_cond_shape(control_dim: int = 0) -> tuple[int, ...]

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 for time-only conditioning.

0

Returns:

Type Description
tuple[int, ...]

A one-tuple (1 + control_dim,) suitable for AbstractBijection.

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
def time_control_cond_shape(control_dim: int = 0) -> tuple[int, ...]:
    """Return the FlowJax ``cond_shape`` for packed ``(time, control)`` inputs.

    Args:
        control_dim: Size of the control vector. Use ``0`` for time-only
            conditioning.

    Returns:
        A one-tuple ``(1 + control_dim,)`` suitable for ``AbstractBijection``.

    Examples:
        >>> from gauss_flows_maps.conditioning import time_control_cond_shape
        >>> time_control_cond_shape()
        (1,)
        >>> time_control_cond_shape(3)
        (4,)
    """
    _validate_control_dim(control_dim)
    return (1 + control_dim,)

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 modulation.

required
inner AbstractBijection

Any bijection whose cond_shape is None, with a 1-D shape.

required
cond_dim int

Context size K.

required
nn_width int

Width of the modulation's trunk.

64
nn_depth int

Number of trunk layers; 0 reads γ and β linearly from c.

2
activation Callable[[Array], Array]

Activation after each trunk layer.

tanh
readout_scale float

Factor on the readout's default weight; the default 0 makes the layer exactly f at init for every c.

0.0
scale_map _FlowScaleMap

The positive scale map σ of AffineModulation, a map of gauss_flows_maps.reparam or one of "exp" (default, γ = eʳ), "softplus" and "one_plus_tanh".

'exp'
modulation AffineModulation | None

A pre-built AffineModulation from K inputs to inner.shape[0] features; it replaces the arguments from nn_width to scale_map.

None

Raises:

Type Description
ValueError

If inner is conditional or not 1-D, if cond_dim is not positive, if scale_map is "identity", or if modulation has the wrong sizes.

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
class Conditioner(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.

    Args:
        key: PRNG key for the modulation's init; unused with a pre-built
            `modulation`.
        inner: Any bijection whose `cond_shape` is `None`, with a 1-D shape.
        cond_dim: Context size `K`.
        nn_width: Width of the modulation's trunk.
        nn_depth: Number of trunk layers; `0` reads `γ` and `β` linearly from `c`.
        activation: Activation after each trunk layer.
        readout_scale: Factor on the readout's default weight; the default `0`
            makes the layer exactly `f` at init for every `c`.
        scale_map: The positive scale map `σ` of `AffineModulation`, a map of
            `gauss_flows_maps.reparam` or one of `"exp"` (default, `γ = eʳ`),
            `"softplus"` and `"one_plus_tanh"`.
        modulation: A pre-built `AffineModulation` from `K` inputs to
            `inner.shape[0]` features; it replaces the arguments from `nn_width`
            to `scale_map`.

    Raises:
        ValueError: If `inner` is conditional or not 1-D, if `cond_dim` is not
            positive, if `scale_map` is `"identity"`, or if `modulation` has the
            wrong sizes.

    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
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...]
    inner: AbstractBijection
    modulation: AffineModulation

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        inner: AbstractBijection,
        cond_dim: int,
        nn_width: int = 64,
        nn_depth: int = 2,
        activation: Callable[[Array], Array] = jnn.tanh,
        readout_scale: float = 0.0,
        scale_map: _FlowScaleMap = "exp",
        modulation: AffineModulation | None = None,
    ):
        if inner.cond_shape is not None:
            raise ValueError(
                "Conditioner wraps strictly unconditional bijections "
                f"(inner.cond_shape must be None); got "
                f"inner.cond_shape={inner.cond_shape}. For transforms that "
                "natively accept a condition, pass cond_dim directly rather "
                "than wrapping in Conditioner."
            )
        if len(inner.shape) != 1:
            raise ValueError(
                "Conditioner only supports 1D inner event shapes; got "
                f"inner.shape={inner.shape}."
            )
        if cond_dim < 1:
            raise ValueError(f"cond_dim must be a positive int; got {cond_dim}.")

        self.shape = inner.shape
        self.cond_shape = (cond_dim,)
        self.inner = inner
        self.modulation = _flow_modulation(
            key,
            num_features=inner.shape[0],
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
            activation=activation,
            readout_scale=readout_scale,
            scale_map=scale_map,
            modulation=modulation,
        )

    def transform_and_log_det(
        self,
        x: ArrayLike,
        condition: ArrayLike,
    ) -> tuple[Array, Array]:
        x = jnp.asarray(x)
        y_inner, log_det_inner = self.inner.transform_and_log_det(x)
        context = jnp.asarray(condition, dtype=x.dtype)
        gamma, log_gamma, beta = self.modulation.modulation(context)
        # y = gamma ⊙ f(x) + β
        y = gamma * y_inner + beta
        # log |det ∂y/∂x| = log |det ∂f/∂x| + Σ log gamma
        return y, log_det_inner + jnp.sum(log_gamma)

    def inverse_and_log_det(
        self,
        y: ArrayLike,
        condition: ArrayLike,
    ) -> tuple[Array, Array]:
        y = jnp.asarray(y)
        context = jnp.asarray(condition, dtype=y.dtype)
        gamma, log_gamma, beta = self.modulation.modulation(context)
        # f(x) = (y - β) / gamma
        y_inner = (y - beta) / gamma
        x, log_det_inner_inv = self.inner.inverse_and_log_det(y_inner)
        return x, log_det_inner_inv - jnp.sum(log_gamma)