Skip to content

Conditioners

A conditioner is a layer \((\vect{h}, \vect{c}) \mapsto \vect{y}\) that transforms an inner activation \(\vect{h} \in \mathbb{R}^{C}\) with a context or latent code \(\vect{c} \in \mathbb{R}^{K}\), passed as the second positional argument, layer(h, c). It is the same mechanism in a conditional flow and in a conditioned neural field, so gauss_flows_maps.conditioning holds it once for both. Each acts on one example and composes with jax.vmap over a batch of pairs \((\vect{h}, \vect{c})\).

  • ConcatConditioner concatenates and projects, \(\vect{y} = \mat{W} [\vect{h}; \vect{c}] + \vect{b}\). It is the cheapest, but its parameter count grows with \(K\).
  • AffineModulation (FiLM) scales and shifts, \(\vect{y} = \gvect{\gamma}(\vect{c}) \odot \vect{h} + \gvect{\beta}(\vect{c})\), with \([\gvect{\beta}; \vect{r}_\gamma] = \mat{W}\varphi(\vect{c}) + \vect{b}\) and \(\gvect{\gamma} = \sigma(\vect{r}_\gamma)\) for its scale map \(\sigma\) (gamma_activation), where \(\varphi\) is an optional MLP trunk (trunk_width, trunk_depth, trunk_activation; the identity without one). modulation(c) returns \((\gvect{\gamma}, \log \gvect{\gamma}, \gvect{\beta})\), and log_det(c) returns \(\log \lvert \det \partial \vect{y} / \partial \vect{h} \rvert = \sum_{i=1}^{C} \log \gamma_i\) for every positive map, from the map's stable log_value.
  • HyperLinear generates the weights of a target linear layer from the code, \((\mathrm{vec}\mat{W}_t, \vect{b}_t) = g(\vect{c})\), and applies \(\vect{y} = \mat{W}_t \vect{x} + \vect{b}_t\).

ConcatConditioner and AffineModulation start as the identity in \(\vect{h}\) for every code, so a conditional layer starts as its unconditional layer and the step-0 likelihood is the base model's. ConcatConditioner starts at \(\mat{W} = [\mat{I} \mid \mat{0}]\) and \(\vect{b} = \vect{0}\) (pass init="default" for the eqx.nn.Linear draw). AffineModulation starts its generator's weight at readout_scale times its default draw (zero by default) and its bias at \((\vect{0}, r_0 \vect{1})\), where \(r_0 = \sigma^{-1}(1)\) is the raw scale at which the scale map gives \(\gamma = 1\); with a zero weight the generator ignores the code, so \(\gvect{\beta} = \vect{0}\) and \(\gvect{\gamma} = \vect{1}\) (the adaLN-Zero rule of Peebles and Xie, 2023). The weight still learns from the first step, and a small readout_scale such as \(10^{-2}\) also keeps a gradient to the code at step 0. zero_readout gives the same start to any eqx.nn.Linear or to the last layer of an eqx.nn.MLP.

The scale map is a Reparametrised or Composed map of gauss_flows_maps.reparam, or one of these shorthands:

gamma_activation Map \(\gamma = \sigma(r)\) \(r_0\)
"one_plus_tanh" (default) Reparametrised("sigmoid", lower=0, upper=2) \(2 / (1 + e^{-r})\) \(0\)
"exp" Reparametrised("exp") \(e^{r}\) \(0\)
"softplus" Reparametrised("softplus") \(\log(1 + e^{r})\) \(\log(e - 1) \approx 0.5413\)
"identity" none \(r\) \(1\)

Because \(1 + \tanh r = 2 / (1 + e^{-2r})\), "one_plus_tanh" is the sigmoid map on \((0, 2)\) of \(r\) itself: it agrees with \(1 + \tanh r\) at \(r = 0\) and differs elsewhere. "identity" has no positive scale, so its log_det raises. A log-scale bounded by \(B\) keeps \(\gamma\) inside \((e^{-B}, e^{B})\):

from gauss_flows_maps.reparam import Composed, Reparametrised

# γ = exp(−B + 2B σ(r)) = exp(B tanh(r/2)), with B = 3
bounded = Composed(
    outer=Reparametrised("exp"),
    inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
)
film = AffineModulation.init(16, 7, key=key, gamma_activation=bounded, trunk_width=64, trunk_depth=2)

HyperLinear generates \(\vect{\theta} = (\mathrm{vec}\mat{W}_t, \vect{b}_t) = \mat{G}\vect{c}\) with a generator \(\mat{G} \in \mathbb{R}^{(C_\text{out} C_\text{in} + C_\text{out}) \times K}\). If the entries of \(\mat{G}\) are independent with mean zero and variance \(v_G\), and the code's entries have second moment \(m_2 = \mathbb{E}[c_k^2]\), each generated weight has variance \(K v_G m_2\). To start the generated layer at the variance \(v^\star = \sigma_\star^2\) of the target layer's own initialisation, times \(s^2\), the generator's weights draw from \(\mathcal{N}(0, v_G)\) with

\[ v_G = \frac{s^2 v^\star}{K m_2}, \]

where \(s\) is init_scale (default 1), \(\sigma_\star\) is target_std (default \(1/\sqrt{3 C_\text{in}}\), the standard deviation of eqx.nn.Linear's own initial weights) and \(m_2\) is cond_second_moment (default 1, which holds for a standardised code or an embedding that ends in a layer norm). This is hyperfan initialisation (Chang, Flokas and Lipson, 2020): the generator's variance comes from the variance the generated weights need, not from the generator's own fan-in. The rows of \(\mat{G}\) that generate \(\vect{b}_t\), and the generator's bias, start at zero, so the generated bias is zero at init.

The trainable linear maps keep the field names proj (in ConcatConditioner) and generator (in AffineModulation and HyperLinear), because pyrox-nn's Bayesian conditioners swap their weight and bias by name.

Conditioning in gauss_flows

Every conditional layer of gauss_flows reads its condition \(\vect{c} \in \mathbb{R}^{K}\) through a conditioner of this module and starts as its unconditional self, so the step-0 likelihood of a conditional flow is that of the same flow without the condition. \(K\) is the layer's cond_dim (control_dim for ContinuousAffineCoupling), and \(\vect{x}_p\) below is the passive half of a coupling's input, the coordinates it leaves untouched.

Layer Conditioner Input Starts as
Conditioner AffineModulation \(\vect{c}\) its inner bijection \(f\)
ConditionalDiagGaussian AffineModulation \(\vect{c}\) \(\mathcal{N}(\vect{0}, \mat{I})\)
GINCoupling, ContinuousAffineCoupling AffineModulation \([\vect{x}_p; \vect{c}]\) the identity
the FlowJax-built couplings FlowJax's MLP, through zero_readout \([\vect{x}_p; \vect{c}]\) the transformer's initial value

The FlowJax-built couplings are AffineCoupling, RQSplineCoupling, CircularRQSplineCoupling, MixtureGaussianCDFCoupling and DeepSigmoidCoupling. The couplings read \(\vect{c}\) only when they are built with a cond_dim (or a control_dim); without one their input is \(\vect{x}_p\) alone. No layer of gauss_flows uses ConcatConditioner or HyperLinear; they are here for conditioned neural fields and for layers outside the package.

The modulation. The first four layers share one head. For an input \(\vect{u} \in \mathbb{R}^{M}\) (the condition, or the passive half joined to it) and \(C\) modulated features, an AffineModulation reads a raw shift and a raw scale from its trunk \(\varphi\) (\(\mathbb{R}^{M} \to \mathbb{R}^{H}\), nn_depth layers of width nn_width with activation, or the identity with \(H = M\) when nn_depth=0) and its readout \(\mat{W} \in \mathbb{R}^{2C \times H}\), \(\vect{b} \in \mathbb{R}^{2C}\):

\[ [\vect{r}_\beta; \vect{r}_\gamma] = \mat{W}\varphi(\vect{u}) + \vect{b}. \]

The shift is \(\gvect{\beta} = \vect{r}_\beta\) and the scale is \(\gvect{\gamma} = \sigma(\vect{r}_\gamma)\), where \(\sigma\) is the positive scale map, applied elementwise. They modulate the activation \(\vect{h} \in \mathbb{R}^{C}\) as

$$ \vect{y} = \gvect{\gamma} \odot \vect{h} + \gvect{\beta}. $$ The map is elementwise in \(\vect{h}\), so its log-Jacobian is the sum of the scale map's log-values,

\[ \log \lvert \det \partial \vect{y} / \partial \vect{h} \rvert = \sum_{i=1}^{C} \log \sigma(r_{\gamma,i}), \]

which each map computes in a stable closed form (its log_value) rather than as the logarithm of \(\gamma_i\). Each layer uses the head in its own way. Conditioner modulates \(\vect{h} = f(\vect{x})\) and adds the log-Jacobian of \(f\). ConditionalDiagGaussian draws \(\vect{x} = \gvect{\beta} + \gvect{\gamma} \odot \gvect{\epsilon}\), so its log-density is \(\log \mathcal{N}(\gvect{\epsilon}; \vect{0}, \mat{I}) - \sum_{i} \log \sigma(r_{\gamma,i})\) at \(\gvect{\epsilon} = (\vect{x} - \gvect{\beta}) / \gvect{\gamma}\). ContinuousAffineCoupling multiplies \(\log \gvect{\gamma}\) and \(\gvect{\beta}\) by its time gate \(g(t)\), so its log-Jacobian is \(g(t) \sum_{i} \log \sigma(r_{\gamma,i})\). GINCoupling subtracts the mean of \(\log \gvect{\gamma}\) before it scales, so it preserves volume and its log-Jacobian is zero.

Identity at init and readout_scale. The four layers take readout_scale (default \(0\)) and start the readout at \(\mat{W} = s \mat{W}_0\), where \(s\) is readout_scale and \(\mat{W}_0\) the readout's default draw, and \(\vect{b} = (\vect{0}, r_0 \vect{1})\) with \(r_0 = \sigma^{-1}(1)\). With the default \(s = 0\) the readout ignores its input, so \(\vect{r}_\beta = \vect{0}\) and \(\vect{r}_\gamma = r_0 \vect{1}\) for every \(\vect{u}\), which gives \(\gvect{\beta} = \vect{0}\), \(\gvect{\gamma} = \vect{1}\) and a zero log-Jacobian: Conditioner is exactly \(f\), ConditionalDiagGaussian is exactly \(\mathcal{N}(\vect{0}, \mat{I})\), and the two couplings are exactly the identity, for every condition. The readout's weight still learns from the first step. A small readout_scale such as \(10^{-2}\) starts the layer close to that point rather than at it, and it also gives the trunk and the condition a gradient at step 0. A pre-built modulation replaces the arguments from nn_width to scale_map and keeps its own initialisation. The couplings built on FlowJax's Coupling take no readout_scale: zero_readout always zeroes the last layer of their MLP, and FlowJax adds the MLP's output to the transformer's initial parameters, so each starts at its transformer's initial value for every input, which is the identity for all of them except DeepSigmoidCoupling (a fixed sum of sigmoids).

Scale maps. scale_map takes any positive map of gauss_flows_maps.reparam or one of the shorthands "exp", "softplus" and "one_plus_tanh" in the table above. "identity" raises a ValueError, because a flow layer needs its log-Jacobian. The flow layers default to "exp" (with \(r_0 = 0\)), whereas AffineModulation.init on its own defaults to "one_plus_tanh". The bounded log-scale above, \(\gamma_i = \exp(B \tanh(r_{\gamma,i} / 2))\), keeps \(\lvert \log \gamma_i \rvert < B\) for every input (the soft clamp that many affine coupling flows put on their log-scales) and also has \(r_0 = 0\):

import jax.random as jr
from gauss_flows_maps.bijections import GINCoupling
from gauss_flows_maps.reparam import Composed, Reparametrised

# log γ bounded by 3, on the passive half of x joined to a code c of size 3
bounded = Composed(
    outer=Reparametrised("exp"),
    inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
)
coupling = GINCoupling(jr.key(0), shape=(4,), cond_dim=3, readout_scale=1e-2, scale_map=bounded)

Notebook 08 conditions a two-moons flow three ways (the base, the couplings, or both) and shows what each can model.

Reference

AbstractConditioner

Bases: Module

Protocol for (h, c) → y conditioning layers.

Subclasses implement __call__(h, c, /) with h ∈ ℝ^C and c ∈ ℝ^K. The protocol is duck-typed, so there is no abstractmethod enforcement.

Parameters:

Name Type Description Default
num_features

Output channel count C, which matches h.shape[-1].

required
cond_dim

Context dimension K, which matches c.shape[-1].

required
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
class AbstractConditioner(eqx.Module):
    """Protocol for `(h, c) → y` conditioning layers.

    Subclasses implement `__call__(h, c, /)` with `h ∈ ℝ^C` and `c ∈ ℝ^K`. The
    protocol is duck-typed, so there is no `abstractmethod` enforcement.

    Args:
        num_features: Output channel count `C`, which matches `h.shape[-1]`.
        cond_dim: Context dimension `K`, which matches `c.shape[-1]`.
    """

    num_features: int = eqx.field(static=True)
    cond_dim: int = eqx.field(static=True)

    def __call__(self, h: Array, c: Array, /) -> Array:  # pragma: no cover
        raise NotImplementedError

ConcatConditioner

Bases: AbstractConditioner

Concatenate h and c, then apply one Linear.

The layer computes y = W [h ; c] + b, with W ∈ ℝ^(C×(C+K)). It is the cheapest conditioner, but its parameter count grows with cond_dim: it has (C + K)·C + C parameters in all. By default the projection starts as W = [I | 0] and b = 0, so y = h for every c until training moves it.

Parameters:

Name Type Description Default
proj

Linear projection ℝ^(C+K) → ℝ^C.

required
num_features

Output channels C.

required
cond_dim

Context dimension K.

required

Examples:

Typical case, with eight features and a four-dimensional context:

>>> import jax.random as jr, jax.numpy as jnp
>>> from gauss_flows_maps.conditioning import ConcatConditioner
>>> layer = ConcatConditioner.init(num_features=8, cond_dim=4, key=jr.key(0))
>>> y = layer(jnp.ones(8), jnp.ones(4))
>>> y.shape
(8,)

Edge case, a one-dimensional context; the layer starts as the identity:

>>> thin = ConcatConditioner.init(num_features=3, cond_dim=1, key=jr.key(0))
>>> thin(jnp.arange(3.0), jnp.ones(1))
Array([0., 1., 2.], dtype=float32)

Composition with vmap over a batch of pairs (h, c):

>>> import jax
>>> jax.vmap(layer)(jnp.ones((5, 8)), jnp.ones((5, 4))).shape
(5, 8)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
class ConcatConditioner(AbstractConditioner):
    """Concatenate `h` and `c`, then apply one `Linear`.

    The layer computes `y = W [h ; c] + b`, with `W ∈ ℝ^(C×(C+K))`. It is the
    cheapest conditioner, but its parameter count grows with `cond_dim`: it has
    `(C + K)·C + C` parameters in all. By default the projection starts as
    `W = [I | 0]` and `b = 0`, so `y = h` for every `c` until training moves it.

    Args:
        proj: Linear projection `ℝ^(C+K) → ℝ^C`.
        num_features: Output channels `C`.
        cond_dim: Context dimension `K`.

    Examples:
        Typical case, with eight features and a four-dimensional context:

        >>> import jax.random as jr, jax.numpy as jnp
        >>> from gauss_flows_maps.conditioning import ConcatConditioner
        >>> layer = ConcatConditioner.init(num_features=8, cond_dim=4, key=jr.key(0))
        >>> y = layer(jnp.ones(8), jnp.ones(4))
        >>> y.shape
        (8,)

        Edge case, a one-dimensional context; the layer starts as the identity:

        >>> thin = ConcatConditioner.init(num_features=3, cond_dim=1, key=jr.key(0))
        >>> thin(jnp.arange(3.0), jnp.ones(1))
        Array([0., 1., 2.], dtype=float32)

        Composition with `vmap` over a batch of pairs `(h, c)`:

        >>> import jax
        >>> jax.vmap(layer)(jnp.ones((5, 8)), jnp.ones((5, 4))).shape
        (5, 8)
    """

    proj: eqx.nn.Linear

    @classmethod
    def init(
        cls,
        num_features: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray,
        init: Literal["identity", "default"] = "identity",
    ) -> ConcatConditioner:
        """Build a `ConcatConditioner` that starts as the identity in `h`.

        With `init="identity"` the projection starts at `W = [I | 0]` and `b = 0`,
        so `y = h` for every `c`; with `init="default"` it keeps the
        `eqx.nn.Linear` default init, a random projection of `[h ; c]`.

        Args:
            num_features: Output channel count `C`.
            cond_dim: Context dimension `K`.
            key: PRNG key for the projection's init.
            init: `"identity"` (default) or `"default"`, see above.

        Returns:
            Initialised `ConcatConditioner`.

        Raises:
            ValueError: If `num_features` or `cond_dim` is non-positive, or if
                `init` is not `"identity"` or `"default"`.
        """
        if num_features <= 0 or cond_dim <= 0:
            raise ValueError(
                "num_features and cond_dim must be positive; got "
                f"num_features={num_features}, cond_dim={cond_dim}."
            )
        if init not in ("identity", "default"):
            raise ValueError(f"init must be 'identity' or 'default'; got {init!r}.")
        proj = eqx.nn.Linear(num_features + cond_dim, num_features, key=key)
        if init == "identity":
            # W = [I | 0]: (C, C + K), the identity on h and zero on c
            eye = jnp.eye(num_features, dtype=proj.weight.dtype)
            zeros = jnp.zeros((num_features, cond_dim), dtype=proj.weight.dtype)
            weight = einx.id("c d, c k -> c (d + k)", eye, zeros)
            # b = 0
            bias = jnp.zeros(num_features, dtype=proj.weight.dtype)
            proj = eqx.tree_at(lambda m: (m.weight, m.bias), proj, (weight, bias))
        return cls(
            num_features=num_features,
            cond_dim=cond_dim,
            proj=proj,
        )

    def __call__(
        self,
        h: Float[Array, " C"],
        c: Float[Array, " K"],
        /,
    ) -> Float[Array, " C"]:
        """Concatenate `h` and `c`, then project to `C` features.

        Args:
            h: Inner activation `h ∈ ℝ^C`.
            c: Context vector `c ∈ ℝ^K`.

        Returns:
            The conditioned activation `y ∈ ℝ^C`.

        Raises:
            ValueError: If `h` or `c` does not match `num_features` or `cond_dim`.
        """
        if h.shape[-1] != self.num_features:
            raise ValueError(
                f"h.shape[-1]={h.shape[-1]} does not match "
                f"num_features={self.num_features}."
            )
        if c.shape[-1] != self.cond_dim:
            raise ValueError(
                f"c.shape[-1]={c.shape[-1]} does not match cond_dim={self.cond_dim}."
            )
        # [h ; c]
        cat = einx.id("d, k -> (d + k)", h, c)
        # y = W [h ; c] + b
        return self.proj(cat)

init classmethod

init(num_features: int, cond_dim: int, *, key: PRNGKeyArray, init: Literal['identity', 'default'] = 'identity') -> ConcatConditioner

Build a ConcatConditioner that starts as the identity in h.

With init="identity" the projection starts at W = [I | 0] and b = 0, so y = h for every c; with init="default" it keeps the eqx.nn.Linear default init, a random projection of [h ; c].

Parameters:

Name Type Description Default
num_features int

Output channel count C.

required
cond_dim int

Context dimension K.

required
key PRNGKeyArray

PRNG key for the projection's init.

required
init Literal['identity', 'default']

"identity" (default) or "default", see above.

'identity'

Returns:

Type Description
ConcatConditioner

Initialised ConcatConditioner.

Raises:

Type Description
ValueError

If num_features or cond_dim is non-positive, or if init is not "identity" or "default".

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
@classmethod
def init(
    cls,
    num_features: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray,
    init: Literal["identity", "default"] = "identity",
) -> ConcatConditioner:
    """Build a `ConcatConditioner` that starts as the identity in `h`.

    With `init="identity"` the projection starts at `W = [I | 0]` and `b = 0`,
    so `y = h` for every `c`; with `init="default"` it keeps the
    `eqx.nn.Linear` default init, a random projection of `[h ; c]`.

    Args:
        num_features: Output channel count `C`.
        cond_dim: Context dimension `K`.
        key: PRNG key for the projection's init.
        init: `"identity"` (default) or `"default"`, see above.

    Returns:
        Initialised `ConcatConditioner`.

    Raises:
        ValueError: If `num_features` or `cond_dim` is non-positive, or if
            `init` is not `"identity"` or `"default"`.
    """
    if num_features <= 0 or cond_dim <= 0:
        raise ValueError(
            "num_features and cond_dim must be positive; got "
            f"num_features={num_features}, cond_dim={cond_dim}."
        )
    if init not in ("identity", "default"):
        raise ValueError(f"init must be 'identity' or 'default'; got {init!r}.")
    proj = eqx.nn.Linear(num_features + cond_dim, num_features, key=key)
    if init == "identity":
        # W = [I | 0]: (C, C + K), the identity on h and zero on c
        eye = jnp.eye(num_features, dtype=proj.weight.dtype)
        zeros = jnp.zeros((num_features, cond_dim), dtype=proj.weight.dtype)
        weight = einx.id("c d, c k -> c (d + k)", eye, zeros)
        # b = 0
        bias = jnp.zeros(num_features, dtype=proj.weight.dtype)
        proj = eqx.tree_at(lambda m: (m.weight, m.bias), proj, (weight, bias))
    return cls(
        num_features=num_features,
        cond_dim=cond_dim,
        proj=proj,
    )

AffineModulation

Bases: AbstractConditioner

Feature-wise linear modulation (FiLM): y = γ(c) ⊙ h + β(c).

An optional MLP trunk φ embeds the code, e = φ(c) (or e = c without a trunk), and a linear readout, the generator, maps it to 2C numbers that split into the shift β and a raw scale r_γ:

[β ; r_γ] = W e + b,   γ = σ(r_γ),   y = γ ⊙ h + β.

The scale map σ is an elementwise map of gauss_flows_maps.reparam (Reparametrised or Composed), or one of these shorthands:

shorthand          map                              γ = σ(r)       r₀
"one_plus_tanh"    Reparametrised("sigmoid", 0, 2)  2 sigmoid(r)   0
"exp"              Reparametrised("exp")            eʳ             0
"softplus"         Reparametrised("softplus")       log(1 + eʳ)    log(e − 1)
"identity"         none                             r              1

"one_plus_tanh" is the sigmoid map on (0, 2) of r itself; 1 + tanh r equals 2 sigmoid(2r), so the two agree at r = 0 and differ elsewhere. A bounded log-scale is Composed(outer=Reparametrised("exp"), inner=Reparametrised("sigmoid", lower=-B, upper=B)), γ = exp(B tanh(r/2)), which keeps γ inside (e^(−B), e^B). "identity" has no positivity guarantee and is rarely useful.

The map is elementwise in h, so its log-Jacobian is log |det ∂y/∂h| = Σᵢ log γᵢ, which log_det computes from the map's stable log_value (for exp, log γ = r).

The layer starts as the identity in h for every c: the generator's weight starts at readout_scale · W (zero by default) and its bias at (0, r₀), with r₀ = σ⁻¹(1) the raw scale at which γ = 1. With a zero weight, β = 0 and γ = 1 whatever the code, so y = h (the adaLN-Zero rule of Peebles and Xie, 2023).

Parameters:

Name Type Description Default
generator

Linear readout ℝ^E → ℝ^(2C) that emits (β, r_γ), with E = K without a trunk.

required
trunk

Optional MLP φ: ℝ^K → ℝ^E before the readout, or None.

required
num_features

Output channels C.

required
cond_dim

Context dimension K.

required
gamma_activation

The scale map σ, a map or "identity".

required
Shape

__call__: h (C,) and c (K,) to y (C,). modulation: c (K,) to γ, log γ and β, each (C,). log_det: c (K,) to a scalar.

References

Perez, E., et al. (2018). FiLM: Visual reasoning with a general conditioning layer. AAAI. Peebles, W. and Xie, S. (2023). Scalable diffusion models with transformers. ICCV.

Examples:

Typical case, with eight features and a four-dimensional context:

>>> import jax.random as jr, jax.numpy as jnp
>>> from gauss_flows_maps.conditioning import AffineModulation
>>> film = AffineModulation.init(num_features=8, cond_dim=4, key=jr.key(0))
>>> y = film(jnp.ones(8), jnp.ones(4))
>>> y.shape
(8,)

Edge case, the "softplus" scale, which starts at γ = 1 for any code:

>>> pos = AffineModulation.init(
...     num_features=3, cond_dim=2, key=jr.key(0), gamma_activation="softplus"
... )
>>> pos(jnp.arange(3.0), jnp.array([4.0, -2.0]))
Array([0., 1., 2.], dtype=float32)

A bounded log-scale behind a two-layer trunk, and its modulation:

>>> from gauss_flows_maps.reparam import Composed, Reparametrised
>>> bounded = Composed(
...     outer=Reparametrised("exp"),
...     inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
... )
>>> deep = AffineModulation.init(
...     16, 7, key=jr.key(0), gamma_activation=bounded,
...     trunk_width=64, trunk_depth=2,
... )
>>> gamma, log_gamma, beta = deep.modulation(jnp.zeros(7))
>>> gamma.shape, log_gamma.shape, beta.shape
((16,), (16,), (16,))

Composition with vmap over a batch of pairs (h, c):

>>> import jax
>>> jax.vmap(film)(jnp.ones((5, 8)), jnp.ones((5, 4))).shape
(5, 8)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
class AffineModulation(AbstractConditioner):
    """Feature-wise linear modulation (FiLM): `y = γ(c) ⊙ h + β(c)`.

    An optional MLP trunk `φ` embeds the code, `e = φ(c)` (or `e = c` without a
    trunk), and a linear readout, the `generator`, maps it to `2C` numbers that
    split into the shift `β` and a raw scale `r_γ`:

        [β ; r_γ] = W e + b,   γ = σ(r_γ),   y = γ ⊙ h + β.

    The scale map `σ` is an elementwise map of `gauss_flows_maps.reparam`
    (`Reparametrised` or `Composed`), or one of these shorthands:

        shorthand          map                              γ = σ(r)       r₀
        "one_plus_tanh"    Reparametrised("sigmoid", 0, 2)  2 sigmoid(r)   0
        "exp"              Reparametrised("exp")            eʳ             0
        "softplus"         Reparametrised("softplus")       log(1 + eʳ)    log(e − 1)
        "identity"         none                             r              1

    `"one_plus_tanh"` is the sigmoid map on (0, 2) of `r` itself; `1 + tanh r`
    equals `2 sigmoid(2r)`, so the two agree at `r = 0` and differ elsewhere. A
    bounded log-scale is `Composed(outer=Reparametrised("exp"),
    inner=Reparametrised("sigmoid", lower=-B, upper=B))`, `γ = exp(B tanh(r/2))`,
    which keeps `γ` inside `(e^(−B), e^B)`. `"identity"` has no positivity
    guarantee and is rarely useful.

    The map is elementwise in `h`, so its log-Jacobian is
    `log |det ∂y/∂h| = Σᵢ log γᵢ`, which `log_det` computes from the map's stable
    `log_value` (for `exp`, `log γ = r`).

    The layer starts as the identity in `h` for every `c`: the generator's weight
    starts at `readout_scale · W` (zero by default) and its bias at `(0, r₀)`,
    with `r₀ = σ⁻¹(1)` the raw scale at which `γ = 1`. With a zero weight,
    `β = 0` and `γ = 1` whatever the code, so `y = h` (the adaLN-Zero rule of
    Peebles and Xie, 2023).

    Args:
        generator: Linear readout `ℝ^E → ℝ^(2C)` that emits `(β, r_γ)`, with
            `E = K` without a trunk.
        trunk: Optional MLP `φ: ℝ^K → ℝ^E` before the readout, or `None`.
        num_features: Output channels `C`.
        cond_dim: Context dimension `K`.
        gamma_activation: The scale map `σ`, a map or `"identity"`.

    Shape:
        `__call__`: `h` `(C,)` and `c` `(K,)` to `y` `(C,)`.
        `modulation`: `c` `(K,)` to `γ`, `log γ` and `β`, each `(C,)`.
        `log_det`: `c` `(K,)` to a scalar.

    References:
        Perez, E., et al. (2018). FiLM: Visual reasoning with a general
        conditioning layer. AAAI.
        Peebles, W. and Xie, S. (2023). Scalable diffusion models with
        transformers. ICCV.

    Examples:
        Typical case, with eight features and a four-dimensional context:

        >>> import jax.random as jr, jax.numpy as jnp
        >>> from gauss_flows_maps.conditioning import AffineModulation
        >>> film = AffineModulation.init(num_features=8, cond_dim=4, key=jr.key(0))
        >>> y = film(jnp.ones(8), jnp.ones(4))
        >>> y.shape
        (8,)

        Edge case, the `"softplus"` scale, which starts at `γ = 1` for any code:

        >>> pos = AffineModulation.init(
        ...     num_features=3, cond_dim=2, key=jr.key(0), gamma_activation="softplus"
        ... )
        >>> pos(jnp.arange(3.0), jnp.array([4.0, -2.0]))
        Array([0., 1., 2.], dtype=float32)

        A bounded log-scale behind a two-layer trunk, and its modulation:

        >>> from gauss_flows_maps.reparam import Composed, Reparametrised
        >>> bounded = Composed(
        ...     outer=Reparametrised("exp"),
        ...     inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
        ... )
        >>> deep = AffineModulation.init(
        ...     16, 7, key=jr.key(0), gamma_activation=bounded,
        ...     trunk_width=64, trunk_depth=2,
        ... )
        >>> gamma, log_gamma, beta = deep.modulation(jnp.zeros(7))
        >>> gamma.shape, log_gamma.shape, beta.shape
        ((16,), (16,), (16,))

        Composition with `vmap` over a batch of pairs `(h, c)`:

        >>> import jax
        >>> jax.vmap(film)(jnp.ones((5, 8)), jnp.ones((5, 4))).shape
        (5, 8)
    """

    generator: eqx.nn.Linear
    trunk: eqx.nn.MLP | None = None
    gamma_activation: _ScaleMap | Literal["identity"] = eqx.field(
        static=True, default=_GAMMA_SHORTHANDS["one_plus_tanh"]
    )

    @classmethod
    def init(
        cls,
        num_features: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray,
        gamma_activation: _ScaleMap
        | Literal["one_plus_tanh", "exp", "softplus", "identity"] = "one_plus_tanh",
        trunk_width: int | None = None,
        trunk_depth: int = 0,
        trunk_activation: Callable[[Array], Array] = jax.nn.relu,
        readout_scale: float = 0.0,
    ) -> AffineModulation:
        """Build `AffineModulation` that starts as the identity in `h`.

        The trunk, when `trunk_depth > 0`, is `trunk_depth` linear layers of
        width `trunk_width`, each followed by `trunk_activation`. The generator's
        weight starts at `readout_scale` times the `eqx.nn.Linear` default and
        its bias at `(0, r₀)`, with `r₀ = σ⁻¹(1)` (see the class docstring), so
        `β = 0` and `γ = 1` for every code when `readout_scale = 0`.

        Args:
            num_features: Output channel count `C`.
            cond_dim: Context dimension `K`.
            key: PRNG key for the trunk's and the generator's init.
            gamma_activation: The scale map `σ`: a `Reparametrised` or `Composed`
                map of `gauss_flows_maps.reparam` whose range contains 1, or a
                shorthand from the class docstring.
            trunk_width: Width `E` of the trunk; needed when `trunk_depth > 0`.
            trunk_depth: Number of linear layers in the trunk; `0` (default)
                means no trunk.
            trunk_activation: Activation after each of the trunk's layers.
            readout_scale: Factor on the generator's default weight. The default
                `0` makes the layer exactly the identity for every code; a small
                value such as `1e-2` starts it near the identity with a non-zero
                gradient to the code and the trunk.

        Returns:
            Initialised `AffineModulation`.

        Raises:
            ValueError: If `num_features` or `cond_dim` is non-positive, if
                `gamma_activation` is neither a map nor a shorthand or cannot
                reach `γ = 1`, if `trunk_depth` is negative, or if `trunk_width`
                is missing or non-positive with a trunk, or given without one.
        """
        if num_features <= 0 or cond_dim <= 0:
            raise ValueError(
                "num_features and cond_dim must be positive; got "
                f"num_features={num_features}, cond_dim={cond_dim}."
            )
        gamma = _resolve_gamma(gamma_activation)
        if trunk_depth < 0:
            raise ValueError(f"trunk_depth must be >= 0; got {trunk_depth}.")
        if trunk_depth == 0:
            if trunk_width is not None:
                raise ValueError(
                    f"trunk_width={trunk_width} needs trunk_depth > 0; got "
                    "trunk_depth=0."
                )
            trunk = None
            embed_dim = cond_dim
            generator_key = key
        else:
            if trunk_width is None or trunk_width <= 0:
                raise ValueError(
                    "trunk_width must be positive when trunk_depth > 0; got "
                    f"trunk_width={trunk_width}."
                )
            trunk_key, generator_key = jr.split(key)
            # φ: K → E → … → E, trunk_depth layers, each followed by the activation
            trunk = eqx.nn.MLP(
                cond_dim,
                trunk_width,
                trunk_width,
                trunk_depth - 1,
                activation=trunk_activation,
                final_activation=trunk_activation,
                key=trunk_key,
            )
            embed_dim = trunk_width
        generator = eqx.nn.Linear(embed_dim, 2 * num_features, key=generator_key)
        # b = (0, r₀): β = 0 and γ = σ(r₀) = 1
        raw_identity = _identity_raw(gamma)
        bias = einx.id(
            "beta, gamma -> (beta + gamma)",
            jnp.zeros(num_features),
            jnp.full(num_features, raw_identity),
        )
        # W ← readout_scale · W, so with 0 the code does not reach (β, r_γ)
        generator = zero_readout(generator, bias=bias, scale=readout_scale)
        return cls(
            num_features=num_features,
            cond_dim=cond_dim,
            generator=generator,
            trunk=trunk,
            gamma_activation=gamma,
        )

    def modulation(
        self,
        c: Float[Array, " K"],
        /,
    ) -> tuple[Float[Array, " C"], Float[Array, " C"], Float[Array, " C"]]:
        """Return the scale `γ`, its log `log γ` and the shift `β` for one code.

        `log γ` is the scale map's own `log_value`, stable far into its tails.
        With `gamma_activation="identity"` it is `log r_γ`, NaN where `γ ≤ 0`.

        Args:
            c: Context vector `c ∈ ℝ^K`.

        Returns:
            The tuple `(γ, log γ, β)`, each in `ℝ^C`.

        Raises:
            ValueError: If `c` does not match `cond_dim`.

        Examples:
            >>> import jax.numpy as jnp, jax.random as jr
            >>> from gauss_flows_maps.conditioning import AffineModulation
            >>> film = AffineModulation.init(4, 2, key=jr.key(0))
            >>> gamma, log_gamma, beta = film.modulation(jnp.ones(2))
            >>> gamma
            Array([1., 1., 1., 1.], dtype=float32)
        """
        if c.shape[-1] != self.cond_dim:
            raise ValueError(
                f"c.shape[-1]={c.shape[-1]} does not match cond_dim={self.cond_dim}."
            )
        # e = φ(c), or e = c without a trunk
        embedding = c if self.trunk is None else self.trunk(c)
        # [β ; r_γ] = W e + b
        raw = self.generator(embedding)
        # einx.id keeps the two-way split explicit and avoids jnp.split
        split = einx.id("(two d) -> two d", raw, two=2)
        beta, raw_gamma = split[0], split[1]
        if self.gamma_activation == "identity":
            # γ = r_γ, log γ = log r_γ
            return raw_gamma, jnp.log(raw_gamma), beta
        # γ = σ(r_γ)
        gamma = self.gamma_activation.forward(raw_gamma)
        # log γ = log σ(r_γ), in the map's stable form
        log_gamma = self.gamma_activation.log_value(raw_gamma)
        return gamma, log_gamma, beta

    def __call__(
        self,
        h: Float[Array, " C"],
        c: Float[Array, " K"],
        /,
    ) -> Float[Array, " C"]:
        """Scale and shift `h` by the scale and shift generated from `c`.

        Args:
            h: Inner activation `h ∈ ℝ^C`.
            c: Context vector `c ∈ ℝ^K`.

        Returns:
            The modulated activation `y ∈ ℝ^C`.

        Raises:
            ValueError: If `h` or `c` does not match `num_features` or `cond_dim`.
        """
        if h.shape[-1] != self.num_features:
            raise ValueError(
                f"h.shape[-1]={h.shape[-1]} does not match "
                f"num_features={self.num_features}."
            )
        gamma, _log_gamma, beta = self.modulation(c)
        # y = γ ⊙ h + β
        return gamma * h + beta

    def log_det(self, c: Float[Array, " K"], /) -> Float[Array, ""]:
        """Return `log |det ∂y/∂h| = Σᵢ log γᵢ`, the log-Jacobian in `h`.

        It holds for every positive scale map, through the map's `log_value`;
        `gamma_activation="identity"` has no positive scale, so it raises.

        Args:
            c: Context vector `c ∈ ℝ^K`.

        Returns:
            Scalar log-determinant `Σ log γ` of the diagonal scaling.

        Raises:
            NotImplementedError: If `gamma_activation="identity"`.
            ValueError: If `c` does not match `cond_dim`.

        Examples:
            >>> import jax.numpy as jnp
            >>> import jax.random as jr
            >>> film = AffineModulation.init(
            ...     num_features=4, cond_dim=2, key=jr.key(0),
            ...     gamma_activation="softplus",
            ... )
            >>> film.log_det(jnp.ones(2))  # γ = 1 at init, so Σ log γ = 0
            Array(0., dtype=float32)
        """
        if self.gamma_activation == "identity":
            raise NotImplementedError(
                "log_det needs a positive scale map; gamma_activation='identity' "
                "has none. Use a map of gauss_flows_maps.reparam or one of "
                f"{tuple(_GAMMA_SHORTHANDS)}."
            )
        _gamma, log_gamma, _beta = self.modulation(c)
        # log |det ∂y/∂h| = Σᵢ log γᵢ
        return einx.sum("[d]", log_gamma)

init classmethod

init(num_features: int, cond_dim: int, *, key: PRNGKeyArray, gamma_activation: _ScaleMap | Literal['one_plus_tanh', 'exp', 'softplus', 'identity'] = 'one_plus_tanh', trunk_width: int | None = None, trunk_depth: int = 0, trunk_activation: Callable[[Array], Array] = relu, readout_scale: float = 0.0) -> AffineModulation

Build AffineModulation that starts as the identity in h.

The trunk, when trunk_depth > 0, is trunk_depth linear layers of width trunk_width, each followed by trunk_activation. The generator's weight starts at readout_scale times the eqx.nn.Linear default and its bias at (0, r₀), with r₀ = σ⁻¹(1) (see the class docstring), so β = 0 and γ = 1 for every code when readout_scale = 0.

Parameters:

Name Type Description Default
num_features int

Output channel count C.

required
cond_dim int

Context dimension K.

required
key PRNGKeyArray

PRNG key for the trunk's and the generator's init.

required
gamma_activation _ScaleMap | Literal['one_plus_tanh', 'exp', 'softplus', 'identity']

The scale map σ: a Reparametrised or Composed map of gauss_flows_maps.reparam whose range contains 1, or a shorthand from the class docstring.

'one_plus_tanh'
trunk_width int | None

Width E of the trunk; needed when trunk_depth > 0.

None
trunk_depth int

Number of linear layers in the trunk; 0 (default) means no trunk.

0
trunk_activation Callable[[Array], Array]

Activation after each of the trunk's layers.

relu
readout_scale float

Factor on the generator's default weight. The default 0 makes the layer exactly the identity for every code; a small value such as 1e-2 starts it near the identity with a non-zero gradient to the code and the trunk.

0.0

Returns:

Type Description
AffineModulation

Initialised AffineModulation.

Raises:

Type Description
ValueError

If num_features or cond_dim is non-positive, if gamma_activation is neither a map nor a shorthand or cannot reach γ = 1, if trunk_depth is negative, or if trunk_width is missing or non-positive with a trunk, or given without one.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
@classmethod
def init(
    cls,
    num_features: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray,
    gamma_activation: _ScaleMap
    | Literal["one_plus_tanh", "exp", "softplus", "identity"] = "one_plus_tanh",
    trunk_width: int | None = None,
    trunk_depth: int = 0,
    trunk_activation: Callable[[Array], Array] = jax.nn.relu,
    readout_scale: float = 0.0,
) -> AffineModulation:
    """Build `AffineModulation` that starts as the identity in `h`.

    The trunk, when `trunk_depth > 0`, is `trunk_depth` linear layers of
    width `trunk_width`, each followed by `trunk_activation`. The generator's
    weight starts at `readout_scale` times the `eqx.nn.Linear` default and
    its bias at `(0, r₀)`, with `r₀ = σ⁻¹(1)` (see the class docstring), so
    `β = 0` and `γ = 1` for every code when `readout_scale = 0`.

    Args:
        num_features: Output channel count `C`.
        cond_dim: Context dimension `K`.
        key: PRNG key for the trunk's and the generator's init.
        gamma_activation: The scale map `σ`: a `Reparametrised` or `Composed`
            map of `gauss_flows_maps.reparam` whose range contains 1, or a
            shorthand from the class docstring.
        trunk_width: Width `E` of the trunk; needed when `trunk_depth > 0`.
        trunk_depth: Number of linear layers in the trunk; `0` (default)
            means no trunk.
        trunk_activation: Activation after each of the trunk's layers.
        readout_scale: Factor on the generator's default weight. The default
            `0` makes the layer exactly the identity for every code; a small
            value such as `1e-2` starts it near the identity with a non-zero
            gradient to the code and the trunk.

    Returns:
        Initialised `AffineModulation`.

    Raises:
        ValueError: If `num_features` or `cond_dim` is non-positive, if
            `gamma_activation` is neither a map nor a shorthand or cannot
            reach `γ = 1`, if `trunk_depth` is negative, or if `trunk_width`
            is missing or non-positive with a trunk, or given without one.
    """
    if num_features <= 0 or cond_dim <= 0:
        raise ValueError(
            "num_features and cond_dim must be positive; got "
            f"num_features={num_features}, cond_dim={cond_dim}."
        )
    gamma = _resolve_gamma(gamma_activation)
    if trunk_depth < 0:
        raise ValueError(f"trunk_depth must be >= 0; got {trunk_depth}.")
    if trunk_depth == 0:
        if trunk_width is not None:
            raise ValueError(
                f"trunk_width={trunk_width} needs trunk_depth > 0; got "
                "trunk_depth=0."
            )
        trunk = None
        embed_dim = cond_dim
        generator_key = key
    else:
        if trunk_width is None or trunk_width <= 0:
            raise ValueError(
                "trunk_width must be positive when trunk_depth > 0; got "
                f"trunk_width={trunk_width}."
            )
        trunk_key, generator_key = jr.split(key)
        # φ: K → E → … → E, trunk_depth layers, each followed by the activation
        trunk = eqx.nn.MLP(
            cond_dim,
            trunk_width,
            trunk_width,
            trunk_depth - 1,
            activation=trunk_activation,
            final_activation=trunk_activation,
            key=trunk_key,
        )
        embed_dim = trunk_width
    generator = eqx.nn.Linear(embed_dim, 2 * num_features, key=generator_key)
    # b = (0, r₀): β = 0 and γ = σ(r₀) = 1
    raw_identity = _identity_raw(gamma)
    bias = einx.id(
        "beta, gamma -> (beta + gamma)",
        jnp.zeros(num_features),
        jnp.full(num_features, raw_identity),
    )
    # W ← readout_scale · W, so with 0 the code does not reach (β, r_γ)
    generator = zero_readout(generator, bias=bias, scale=readout_scale)
    return cls(
        num_features=num_features,
        cond_dim=cond_dim,
        generator=generator,
        trunk=trunk,
        gamma_activation=gamma,
    )

modulation

modulation(c: Float[Array, ' K']) -> tuple[Float[Array, ' C'], Float[Array, ' C'], Float[Array, ' C']]

Return the scale γ, its log log γ and the shift β for one code.

log γ is the scale map's own log_value, stable far into its tails. With gamma_activation="identity" it is log r_γ, NaN where γ ≤ 0.

Parameters:

Name Type Description Default
c Float[Array, ' K']

Context vector c ∈ ℝ^K.

required

Returns:

Type Description
tuple[Float[Array, ' C'], Float[Array, ' C'], Float[Array, ' C']]

The tuple (γ, log γ, β), each in ℝ^C.

Raises:

Type Description
ValueError

If c does not match cond_dim.

Examples:

>>> import jax.numpy as jnp, jax.random as jr
>>> from gauss_flows_maps.conditioning import AffineModulation
>>> film = AffineModulation.init(4, 2, key=jr.key(0))
>>> gamma, log_gamma, beta = film.modulation(jnp.ones(2))
>>> gamma
Array([1., 1., 1., 1.], dtype=float32)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
def modulation(
    self,
    c: Float[Array, " K"],
    /,
) -> tuple[Float[Array, " C"], Float[Array, " C"], Float[Array, " C"]]:
    """Return the scale `γ`, its log `log γ` and the shift `β` for one code.

    `log γ` is the scale map's own `log_value`, stable far into its tails.
    With `gamma_activation="identity"` it is `log r_γ`, NaN where `γ ≤ 0`.

    Args:
        c: Context vector `c ∈ ℝ^K`.

    Returns:
        The tuple `(γ, log γ, β)`, each in `ℝ^C`.

    Raises:
        ValueError: If `c` does not match `cond_dim`.

    Examples:
        >>> import jax.numpy as jnp, jax.random as jr
        >>> from gauss_flows_maps.conditioning import AffineModulation
        >>> film = AffineModulation.init(4, 2, key=jr.key(0))
        >>> gamma, log_gamma, beta = film.modulation(jnp.ones(2))
        >>> gamma
        Array([1., 1., 1., 1.], dtype=float32)
    """
    if c.shape[-1] != self.cond_dim:
        raise ValueError(
            f"c.shape[-1]={c.shape[-1]} does not match cond_dim={self.cond_dim}."
        )
    # e = φ(c), or e = c without a trunk
    embedding = c if self.trunk is None else self.trunk(c)
    # [β ; r_γ] = W e + b
    raw = self.generator(embedding)
    # einx.id keeps the two-way split explicit and avoids jnp.split
    split = einx.id("(two d) -> two d", raw, two=2)
    beta, raw_gamma = split[0], split[1]
    if self.gamma_activation == "identity":
        # γ = r_γ, log γ = log r_γ
        return raw_gamma, jnp.log(raw_gamma), beta
    # γ = σ(r_γ)
    gamma = self.gamma_activation.forward(raw_gamma)
    # log γ = log σ(r_γ), in the map's stable form
    log_gamma = self.gamma_activation.log_value(raw_gamma)
    return gamma, log_gamma, beta

log_det

log_det(c: Float[Array, ' K']) -> Float[Array, '']

Return log |det ∂y/∂h| = Σᵢ log γᵢ, the log-Jacobian in h.

It holds for every positive scale map, through the map's log_value; gamma_activation="identity" has no positive scale, so it raises.

Parameters:

Name Type Description Default
c Float[Array, ' K']

Context vector c ∈ ℝ^K.

required

Returns:

Type Description
Float[Array, '']

Scalar log-determinant Σ log γ of the diagonal scaling.

Raises:

Type Description
NotImplementedError

If gamma_activation="identity".

ValueError

If c does not match cond_dim.

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> film = AffineModulation.init(
...     num_features=4, cond_dim=2, key=jr.key(0),
...     gamma_activation="softplus",
... )
>>> film.log_det(jnp.ones(2))  # γ = 1 at init, so Σ log γ = 0
Array(0., dtype=float32)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
def log_det(self, c: Float[Array, " K"], /) -> Float[Array, ""]:
    """Return `log |det ∂y/∂h| = Σᵢ log γᵢ`, the log-Jacobian in `h`.

    It holds for every positive scale map, through the map's `log_value`;
    `gamma_activation="identity"` has no positive scale, so it raises.

    Args:
        c: Context vector `c ∈ ℝ^K`.

    Returns:
        Scalar log-determinant `Σ log γ` of the diagonal scaling.

    Raises:
        NotImplementedError: If `gamma_activation="identity"`.
        ValueError: If `c` does not match `cond_dim`.

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> film = AffineModulation.init(
        ...     num_features=4, cond_dim=2, key=jr.key(0),
        ...     gamma_activation="softplus",
        ... )
        >>> film.log_det(jnp.ones(2))  # γ = 1 at init, so Σ log γ = 0
        Array(0., dtype=float32)
    """
    if self.gamma_activation == "identity":
        raise NotImplementedError(
            "log_det needs a positive scale map; gamma_activation='identity' "
            "has none. Use a map of gauss_flows_maps.reparam or one of "
            f"{tuple(_GAMMA_SHORTHANDS)}."
        )
    _gamma, log_gamma, _beta = self.modulation(c)
    # log |det ∂y/∂h| = Σᵢ log γᵢ
    return einx.sum("[d]", log_gamma)

HyperLinear

Bases: AbstractConditioner

Generate a target Linear's (W, b) from c, then apply it.

A single eqx.nn.Linear of output size C_out·C_in + C_out produces the flat parameter vector of an ad-hoc linear layer. The forward pass consumes single examples x ∈ ℝ^(C_in) and c ∈ ℝ^K and returns ℝ^(C_out).

The generator G ∈ ℝ^((C_out·C_in + C_out)×K) starts so that the generated weights have the variance of the target layer's own initialisation, times init_scale² (hyperfan initialisation, Chang, Flokas and Lipson, 2020). If the entries of G are independent with mean zero and variance v_G, and the code's entries have second moment m₂ = 𝔼[c_k²], each generated weight has variance Var[W_ij] = K v_G m₂. To start at the target variance v* = σ*² the generator draws

G_ij ~ 𝒩(0, v_G),    v_G = s² v* / (K m₂),

with s the init_scale, σ* the target_std and m₂ the cond_second_moment of HyperLinear.init. The rows of G that generate b, and the generator's own bias, start at zero, so the generated b is zero for every code at init.

Algorithm
  1. Generate the flat parameters θ = g(c) from the generator g.
  2. Split θ into W ∈ ℝ^(C_out×C_in), filled row by row, and b ∈ ℝ^(C_out).
  3. Apply the generated map y = W x + b.

Parameters:

Name Type Description Default
generator

Linear ℝ^K → ℝ^(C_out·C_in + C_out).

required
target_in

Input dimension C_in of the generated Linear.

required
target_out

Output dimension C_out of the generated Linear, which is num_features.

required
cond_dim

Context dimension K.

required
num_features

Alias for target_out, which satisfies the protocol.

required
References

Pan, Brunton and Kutz (2023). Neural implicit flow. JMLR. Chang, O., Flokas, L. and Lipson, H. (2020). Principled weight initialization for hypernetworks. ICLR.

Examples:

Typical case, mapping four inputs to eight outputs:

>>> import jax.random as jr, jax.numpy as jnp
>>> from gauss_flows_maps.conditioning import HyperLinear
>>> hyper = HyperLinear.init(
...     target_in=4, target_out=8, cond_dim=3, key=jr.key(0)
... )
>>> y = hyper(jnp.ones(4), jnp.ones(3))
>>> y.shape
(8,)

Edge case, a one-dimensional target:

>>> scalar = HyperLinear.init(
...     target_in=1, target_out=1, cond_dim=1, key=jr.key(0)
... )
>>> scalar(jnp.ones(1), jnp.ones(1)).shape
(1,)

Composition with vmap over a batch of pairs (x, c):

>>> import jax
>>> jax.vmap(hyper)(jnp.ones((5, 4)), jnp.ones((5, 3))).shape
(5, 8)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
class HyperLinear(AbstractConditioner):
    """Generate a target `Linear`'s `(W, b)` from `c`, then apply it.

    A single `eqx.nn.Linear` of output size `C_out·C_in + C_out` produces the flat
    parameter vector of an ad-hoc linear layer. The forward pass consumes single
    examples `x ∈ ℝ^(C_in)` and `c ∈ ℝ^K` and returns `ℝ^(C_out)`.

    The generator `G ∈ ℝ^((C_out·C_in + C_out)×K)` starts so that the generated
    weights have the variance of the target layer's own initialisation, times
    `init_scale²` (hyperfan initialisation, Chang, Flokas and Lipson, 2020). If the
    entries of `G` are independent with mean zero and variance `v_G`, and the code's
    entries have second moment `m₂ = 𝔼[c_k²]`, each generated weight has variance
    `Var[W_ij] = K v_G m₂`. To start at the target variance `v* = σ*²` the
    generator draws

        G_ij ~ 𝒩(0, v_G),    v_G = s² v* / (K m₂),

    with `s` the `init_scale`, `σ*` the `target_std` and `m₂` the
    `cond_second_moment` of `HyperLinear.init`. The rows of `G` that generate `b`,
    and the generator's own bias, start at zero, so the generated `b` is zero for
    every code at init.

    Algorithm:
        1. Generate the flat parameters `θ = g(c)` from the generator `g`.
        2. Split `θ` into `W ∈ ℝ^(C_out×C_in)`, filled row by row, and `b ∈ ℝ^(C_out)`.
        3. Apply the generated map `y = W x + b`.

    Args:
        generator: Linear `ℝ^K → ℝ^(C_out·C_in + C_out)`.
        target_in: Input dimension `C_in` of the generated `Linear`.
        target_out: Output dimension `C_out` of the generated `Linear`, which is
            `num_features`.
        cond_dim: Context dimension `K`.
        num_features: Alias for `target_out`, which satisfies the protocol.

    References:
        Pan, Brunton and Kutz (2023). Neural implicit flow. JMLR.
        Chang, O., Flokas, L. and Lipson, H. (2020). Principled weight
        initialization for hypernetworks. ICLR.

    Examples:
        Typical case, mapping four inputs to eight outputs:

        >>> import jax.random as jr, jax.numpy as jnp
        >>> from gauss_flows_maps.conditioning import HyperLinear
        >>> hyper = HyperLinear.init(
        ...     target_in=4, target_out=8, cond_dim=3, key=jr.key(0)
        ... )
        >>> y = hyper(jnp.ones(4), jnp.ones(3))
        >>> y.shape
        (8,)

        Edge case, a one-dimensional target:

        >>> scalar = HyperLinear.init(
        ...     target_in=1, target_out=1, cond_dim=1, key=jr.key(0)
        ... )
        >>> scalar(jnp.ones(1), jnp.ones(1)).shape
        (1,)

        Composition with `vmap` over a batch of pairs `(x, c)`:

        >>> import jax
        >>> jax.vmap(hyper)(jnp.ones((5, 4)), jnp.ones((5, 3))).shape
        (5, 8)
    """

    generator: eqx.nn.Linear
    target_in: int = eqx.field(static=True)
    target_out: int = eqx.field(static=True)

    @classmethod
    def init(
        cls,
        target_in: int,
        target_out: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray,
        target_std: float | None = None,
        cond_second_moment: float = 1.0,
        init_scale: float = 1.0,
    ) -> HyperLinear:
        """Build a `HyperLinear` whose generated layer starts at a target variance.

        The generator's weights draw `G_ij ~ 𝒩(0, s² σ*² / (K m₂))` for the rows
        that generate `W`; the rows that generate `b` and the generator's bias
        start at zero. Averaged over codes with `𝔼[c_k²] = m₂`, the generated
        weights then have standard deviation `s σ*`.

        Args:
            target_in: Input dimension `C_in` of the generated `Linear`.
            target_out: Output dimension `C_out` of the generated `Linear`.
            cond_dim: Context dimension `K`.
            key: PRNG key for the generator's init.
            target_std: Standard deviation `σ*` of the target layer's own initial
                weights. The default `1/√(3 C_in)` is that of `eqx.nn.Linear`,
                whose weights draw `U(−1/√C_in, 1/√C_in)`.
            cond_second_moment: Second moment `m₂ = 𝔼[c_k²]` of the code's
                entries. The default `1` holds for a standardised code or an
                embedding that ends in a layer norm.
            init_scale: Factor `s` on the generated weights' standard deviation;
                with `1` the generated layer starts at the target's variance.

        Returns:
            Initialised `HyperLinear`.

        Raises:
            ValueError: If `target_in`, `target_out`, `cond_dim`, `target_std`,
                `cond_second_moment` or `init_scale` is non-positive.
        """
        if target_in <= 0 or target_out <= 0 or cond_dim <= 0:
            raise ValueError(
                "target_in, target_out, and cond_dim must all be positive; got "
                f"target_in={target_in}, target_out={target_out}, "
                f"cond_dim={cond_dim}."
            )
        if init_scale <= 0:
            raise ValueError(f"init_scale must be > 0; got {init_scale}.")
        if cond_second_moment <= 0:
            raise ValueError(
                f"cond_second_moment must be > 0; got {cond_second_moment}."
            )
        if target_std is None:
            # eqx.nn.Linear draws U(−1/√C_in, 1/√C_in), whose std is 1/√(3 C_in)
            target_std = 1.0 / math.sqrt(3.0 * target_in)
        if target_std <= 0:
            raise ValueError(f"target_std must be > 0; got {target_std}.")
        w_size = target_out * target_in
        flat_size = w_size + target_out
        gen = eqx.nn.Linear(cond_dim, flat_size, key=key)
        # σ_G = s σ* / √(K m₂), so that Var[W_ij] = K σ_G² m₂ = s² σ*²
        generator_std = (
            init_scale * target_std / math.sqrt(cond_dim * cond_second_moment)
        )
        # G_W: (C_out·C_in, K), entries ~ 𝒩(0, σ_G²)
        weight_rows = generator_std * jr.normal(
            key, (w_size, cond_dim), dtype=gen.weight.dtype
        )
        # G_b: (C_out, K) = 0, so the generated bias is zero for every code
        bias_rows = jnp.zeros((target_out, cond_dim), dtype=gen.weight.dtype)
        gen = eqx.tree_at(
            lambda m: m.weight,
            gen,
            jnp.concatenate([weight_rows, bias_rows], axis=0),
        )
        gen = eqx.tree_at(
            lambda m: m.bias,
            gen,
            jnp.zeros_like(gen.bias),
        )
        return cls(
            num_features=target_out,
            cond_dim=cond_dim,
            generator=gen,
            target_in=target_in,
            target_out=target_out,
        )

    def _split_params(self, flat: Array) -> tuple[Array, Array]:
        """Split the flat vector into `W ∈ ℝ^(C_out×C_in)` and `b ∈ ℝ^(C_out)`."""
        w_size = self.target_out * self.target_in
        flat_W, flat_b = flat[:w_size], flat[w_size:]
        # W = reshape(flat_W, (C_out, C_in))
        W = einx.id(
            "(c c_in) -> c c_in", flat_W, c=self.target_out, c_in=self.target_in
        )
        return W, flat_b

    def __call__(
        self,
        x: Float[Array, " C_in"],
        c: Float[Array, " K"],
        /,
    ) -> Float[Array, " C_out"]:
        """Generate `(W, b)` from `c` and apply them to `x`.

        Args:
            x: Input vector `x ∈ ℝ^(C_in)`.
            c: Context vector `c ∈ ℝ^K`.

        Returns:
            The output `y ∈ ℝ^(C_out)`.

        Raises:
            ValueError: If `x` or `c` does not match `target_in` or `cond_dim`.
        """
        if x.shape[-1] != self.target_in:
            raise ValueError(
                f"x.shape[-1]={x.shape[-1]} does not match target_in={self.target_in}."
            )
        if c.shape[-1] != self.cond_dim:
            raise ValueError(
                f"c.shape[-1]={c.shape[-1]} does not match cond_dim={self.cond_dim}."
            )
        # θ = g(c)
        flat = self.generator(c)
        W, b = self._split_params(flat)
        # y = W x + b
        return W @ x + b

init classmethod

init(target_in: int, target_out: int, cond_dim: int, *, key: PRNGKeyArray, target_std: float | None = None, cond_second_moment: float = 1.0, init_scale: float = 1.0) -> HyperLinear

Build a HyperLinear whose generated layer starts at a target variance.

The generator's weights draw G_ij ~ 𝒩(0, s² σ*² / (K m₂)) for the rows that generate W; the rows that generate b and the generator's bias start at zero. Averaged over codes with 𝔼[c_k²] = m₂, the generated weights then have standard deviation s σ*.

Parameters:

Name Type Description Default
target_in int

Input dimension C_in of the generated Linear.

required
target_out int

Output dimension C_out of the generated Linear.

required
cond_dim int

Context dimension K.

required
key PRNGKeyArray

PRNG key for the generator's init.

required
target_std float | None

Standard deviation σ* of the target layer's own initial weights. The default 1/√(3 C_in) is that of eqx.nn.Linear, whose weights draw U(−1/√C_in, 1/√C_in).

None
cond_second_moment float

Second moment m₂ = 𝔼[c_k²] of the code's entries. The default 1 holds for a standardised code or an embedding that ends in a layer norm.

1.0
init_scale float

Factor s on the generated weights' standard deviation; with 1 the generated layer starts at the target's variance.

1.0

Returns:

Type Description
HyperLinear

Initialised HyperLinear.

Raises:

Type Description
ValueError

If target_in, target_out, cond_dim, target_std, cond_second_moment or init_scale is non-positive.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
@classmethod
def init(
    cls,
    target_in: int,
    target_out: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray,
    target_std: float | None = None,
    cond_second_moment: float = 1.0,
    init_scale: float = 1.0,
) -> HyperLinear:
    """Build a `HyperLinear` whose generated layer starts at a target variance.

    The generator's weights draw `G_ij ~ 𝒩(0, s² σ*² / (K m₂))` for the rows
    that generate `W`; the rows that generate `b` and the generator's bias
    start at zero. Averaged over codes with `𝔼[c_k²] = m₂`, the generated
    weights then have standard deviation `s σ*`.

    Args:
        target_in: Input dimension `C_in` of the generated `Linear`.
        target_out: Output dimension `C_out` of the generated `Linear`.
        cond_dim: Context dimension `K`.
        key: PRNG key for the generator's init.
        target_std: Standard deviation `σ*` of the target layer's own initial
            weights. The default `1/√(3 C_in)` is that of `eqx.nn.Linear`,
            whose weights draw `U(−1/√C_in, 1/√C_in)`.
        cond_second_moment: Second moment `m₂ = 𝔼[c_k²]` of the code's
            entries. The default `1` holds for a standardised code or an
            embedding that ends in a layer norm.
        init_scale: Factor `s` on the generated weights' standard deviation;
            with `1` the generated layer starts at the target's variance.

    Returns:
        Initialised `HyperLinear`.

    Raises:
        ValueError: If `target_in`, `target_out`, `cond_dim`, `target_std`,
            `cond_second_moment` or `init_scale` is non-positive.
    """
    if target_in <= 0 or target_out <= 0 or cond_dim <= 0:
        raise ValueError(
            "target_in, target_out, and cond_dim must all be positive; got "
            f"target_in={target_in}, target_out={target_out}, "
            f"cond_dim={cond_dim}."
        )
    if init_scale <= 0:
        raise ValueError(f"init_scale must be > 0; got {init_scale}.")
    if cond_second_moment <= 0:
        raise ValueError(
            f"cond_second_moment must be > 0; got {cond_second_moment}."
        )
    if target_std is None:
        # eqx.nn.Linear draws U(−1/√C_in, 1/√C_in), whose std is 1/√(3 C_in)
        target_std = 1.0 / math.sqrt(3.0 * target_in)
    if target_std <= 0:
        raise ValueError(f"target_std must be > 0; got {target_std}.")
    w_size = target_out * target_in
    flat_size = w_size + target_out
    gen = eqx.nn.Linear(cond_dim, flat_size, key=key)
    # σ_G = s σ* / √(K m₂), so that Var[W_ij] = K σ_G² m₂ = s² σ*²
    generator_std = (
        init_scale * target_std / math.sqrt(cond_dim * cond_second_moment)
    )
    # G_W: (C_out·C_in, K), entries ~ 𝒩(0, σ_G²)
    weight_rows = generator_std * jr.normal(
        key, (w_size, cond_dim), dtype=gen.weight.dtype
    )
    # G_b: (C_out, K) = 0, so the generated bias is zero for every code
    bias_rows = jnp.zeros((target_out, cond_dim), dtype=gen.weight.dtype)
    gen = eqx.tree_at(
        lambda m: m.weight,
        gen,
        jnp.concatenate([weight_rows, bias_rows], axis=0),
    )
    gen = eqx.tree_at(
        lambda m: m.bias,
        gen,
        jnp.zeros_like(gen.bias),
    )
    return cls(
        num_features=target_out,
        cond_dim=cond_dim,
        generator=gen,
        target_in=target_in,
        target_out=target_out,
    )

zero_readout

zero_readout(net: Net, *, bias: ArrayLike = 0.0, scale: float = 0.0) -> Net

Scale a readout's weight by scale and set its bias to bias.

The readout is net itself when it is an eqx.nn.Linear, or the last layer of an eqx.nn.MLP. With scale = 0 the readout returns bias for every input,

g(e) = (scale · W) e + bias = bias,

so a layer that reads its parameters from g starts at the value bias gives it (the adaLN-Zero rule of Peebles and Xie, 2023). The weight still learns from the first step, since ∂L/∂W = (∂L/∂g) eᵀ is not zero; a small scale such as 1e-2 also keeps a gradient to the layers before the readout at step 0.

Parameters:

Name Type Description Default
net Net

An eqx.nn.Linear, or an eqx.nn.MLP whose last layer is the readout.

required
bias ArrayLike

The readout's new bias, broadcast to the bias's shape.

0.0
scale float

The factor on the readout's weight.

0.0

Returns:

Type Description
Net

A copy of net whose readout has weight scale · W and bias bias.

Raises:

Type Description
ValueError

If the readout has no bias (use_bias=False).

Shape

bias: a scalar, or the readout's output shape.

References

Peebles, W. and Xie, S. (2023). Scalable diffusion models with transformers. ICCV.

Examples:

A linear readout that returns its bias for every input:

>>> import jax.numpy as jnp, jax.random as jr, equinox as eqx
>>> from gauss_flows_maps.conditioning import zero_readout
>>> readout = zero_readout(eqx.nn.Linear(3, 2, key=jr.key(0)), bias=1.0)
>>> readout(jnp.arange(3.0))
Array([1., 1.], dtype=float32)

The last layer of an MLP, with a small weight kept:

>>> mlp = eqx.nn.MLP(3, 2, width_size=8, depth=2, key=jr.key(0))
>>> small = zero_readout(mlp, scale=1e-2)
>>> bool(jnp.allclose(small.layers[-1].weight, 1e-2 * mlp.layers[-1].weight))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/conditioners.py
def zero_readout[Net: (eqx.nn.Linear, eqx.nn.MLP)](
    net: Net,
    *,
    bias: ArrayLike = 0.0,
    scale: float = 0.0,
) -> Net:
    """Scale a readout's weight by `scale` and set its bias to `bias`.

    The readout is `net` itself when it is an `eqx.nn.Linear`, or the last layer of
    an `eqx.nn.MLP`. With `scale = 0` the readout returns `bias` for every input,

        g(e) = (scale · W) e + bias = bias,

    so a layer that reads its parameters from `g` starts at the value `bias` gives
    it (the adaLN-Zero rule of Peebles and Xie, 2023). The weight still learns from
    the first step, since ∂L/∂W = (∂L/∂g) eᵀ is not zero; a small `scale` such as
    1e-2 also keeps a gradient to the layers before the readout at step 0.

    Args:
        net: An `eqx.nn.Linear`, or an `eqx.nn.MLP` whose last layer is the readout.
        bias: The readout's new bias, broadcast to the bias's shape.
        scale: The factor on the readout's weight.

    Returns:
        A copy of `net` whose readout has weight `scale · W` and bias `bias`.

    Raises:
        ValueError: If the readout has no bias (`use_bias=False`).

    Shape:
        ``bias``: a scalar, or the readout's output shape.

    References:
        Peebles, W. and Xie, S. (2023). Scalable diffusion models with
        transformers. ICCV.

    Examples:
        A linear readout that returns its bias for every input:

        >>> import jax.numpy as jnp, jax.random as jr, equinox as eqx
        >>> from gauss_flows_maps.conditioning import zero_readout
        >>> readout = zero_readout(eqx.nn.Linear(3, 2, key=jr.key(0)), bias=1.0)
        >>> readout(jnp.arange(3.0))
        Array([1., 1.], dtype=float32)

        The last layer of an MLP, with a small weight kept:

        >>> mlp = eqx.nn.MLP(3, 2, width_size=8, depth=2, key=jr.key(0))
        >>> small = zero_readout(mlp, scale=1e-2)
        >>> bool(jnp.allclose(small.layers[-1].weight, 1e-2 * mlp.layers[-1].weight))
        True
    """
    if isinstance(net, eqx.nn.MLP):
        last = net.layers[-1]
        last = zero_readout(last, bias=bias, scale=scale)
        layers = (*net.layers[:-1], last)
        return eqx.tree_at(lambda m: m.layers, net, layers)
    if net.bias is None:
        raise ValueError("zero_readout needs a readout bias; got use_bias=False.")
    # W ← scale · W
    weight = scale * net.weight
    # b ← bias, broadcast to b's shape and dtype
    new_bias = jnp.broadcast_to(jnp.asarray(bias, net.bias.dtype), net.bias.shape)
    return eqx.tree_at(lambda m: (m.weight, m.bias), net, (weight, new_bias))