Skip to content

Conditioning

A conditioner is a layer (h, c) → y that transforms an inner activation h based on a context vector c. The three concrete conditioners (ConcatConditioner, AffineModulation, HyperLinear) live in gauss_flows_maps.conditioning and are re-exported here; pyrox_nn adds their Bayesian variants, which wrap those cores, and the ConditionedINR composite of geonnax wraps any inner network with per-layer conditioning.

Decision rubric

Pattern Use when Cost Where it shows up
ConcatConditioner You want a cheap baseline; cond_dim is small. (C + K) · C + C per layer DiffeqMLP-style CNF vector fields
AffineModulation (FiLM) Feature-wise modulation is enough; you want low generator cost regardless of cond_dim. 2C · K + 2C per layer π-GAN, Modulated SIREN, conditional INRs
HyperLinear You need the full target weight matrix to depend on z; want NIF/MetaSDF. K · (C·C_in + C) per layer NIF (Pan et al. 2023), MetaSDF, Ha et al. hypernets

The Bayesian variants put Normal(0, prior_std) priors on the readout weights only: the generator of AffineModulation and HyperLinear, the projection of ConcatConditioner. An AffineModulation core with an MLP trunk keeps the trunk deterministic, and its gen_W takes the trunk's width as input size. Posterior cost scales with the readout size, not the target network — that's the whole point of Bayesian amortised inference.

End-to-end use

import jax.random as jr
import jax.numpy as jnp
from pyrox_nn import SIREN, AffineModulation, ConditionedINR, HyperSIREN

key = jr.key(0)

# 1) FiLM-modulate every hidden layer of a SIREN
inner = SIREN.init(2, 32, 1, depth=4, key=key)
wrapped = ConditionedINR.init(
    inner, conditioner_cls=AffineModulation, cond_dim=4, key=key
)
y = wrapped(jnp.ones((10, 2)), jnp.ones((10, 4)))   # (10, 1)

# 2) Full NIF stack — ParameterNet → per-layer HyperLinear → ShapeNet (SIREN)
import equinox as eqx
class IdentityNet(eqx.Module):
    def __call__(self, mu): return mu

nif = HyperSIREN(
    in_features=2, hidden_features=32, out_features=1,
    depth=5, cond_dim=3, parameter_net=IdentityNet(), key=key,
)
y = nif(jnp.ones((10, 2)), jnp.ones((3,)))           # (10, 1)

For a hands-on walkthrough see the Conditional Neural Fields notebook.

Protocol

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 .venv/lib/python3.12/site-packages/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

Concrete conditioners

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 .venv/lib/python3.12/site-packages/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(num_features: int, cond_dim: int, *, key: PRNGKeyArray, init: Literal['identity', 'default'] = 'identity') -> ConcatConditioner classmethod

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 .venv/lib/python3.12/site-packages/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 .venv/lib/python3.12/site-packages/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(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 classmethod

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 .venv/lib/python3.12/site-packages/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(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 .venv/lib/python3.12/site-packages/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(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 .venv/lib/python3.12/site-packages/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 .venv/lib/python3.12/site-packages/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(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 classmethod

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 .venv/lib/python3.12/site-packages/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,
    )

Bayesian variants

BayesianConcatConditioner

Bases: PyroxModule

ConcatConditioner of gauss-flows-maps with Normal priors on the projection.

Registers two NumPyro sample sites — {scope}.proj_W and {scope}.proj_b — under Normal(0, prior_std). Total of two sites per forward call; nothing is sampled from the inner h or the context c.

Holds a frozen gauss_flows_maps.conditioning.ConcatConditioner core whose proj weights are swapped with the sampled arrays each call. The core's own init (the identity in h) is therefore not the start of the prior: the sampled proj replaces it.

Attributes:

Name Type Description
core ConcatConditioner

Frozen gauss_flows_maps.conditioning.ConcatConditioner carrying the single-example forward.

num_features int

Output channels.

cond_dim int

Context dimension.

prior_std float

Scale of the Normal priors.

pyrox_name str | None

Optional explicit scope name for NumPyro.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
class BayesianConcatConditioner(PyroxModule):
    """`ConcatConditioner` of gauss-flows-maps with Normal priors on the projection.

    Registers two NumPyro sample sites — ``{scope}.proj_W`` and
    ``{scope}.proj_b`` — under ``Normal(0, prior_std)``. Total of two
    sites per forward call; nothing is sampled from the inner ``h`` or
    the context ``c``.

    Holds a frozen `gauss_flows_maps.conditioning.ConcatConditioner` core whose
    ``proj`` weights are swapped with the sampled arrays each call. The core's
    own init (the identity in ``h``) is therefore not the start of the prior:
    the sampled ``proj`` replaces it.

    Attributes:
        core: Frozen `gauss_flows_maps.conditioning.ConcatConditioner` carrying the
            single-example forward.
        num_features: Output channels.
        cond_dim: Context dimension.
        prior_std: Scale of the Normal priors.
        pyrox_name: Optional explicit scope name for NumPyro.
    """

    core: _GxConcatConditioner
    num_features: int = eqx.field(static=True)
    cond_dim: int = eqx.field(static=True)
    prior_std: float = eqx.field(static=True, default=1.0)
    pyrox_name: str | None = eqx.field(static=True, default=None)

    @classmethod
    def init(
        cls,
        num_features: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray | None = None,
        prior_std: float = 1.0,
        pyrox_name: str | None = None,
    ) -> BayesianConcatConditioner:
        """Build a `BayesianConcatConditioner`.

        Args:
            num_features: Output channels.
            cond_dim: Context dimension.
            key: PRNG key for the core's init, whose ``proj`` the sampled
                arrays replace on every call. Defaults to ``jax.random.key(0)``.
            prior_std: Scale of the Normal priors.
            pyrox_name: Optional explicit scope name.

        Raises:
            ValueError: If ``num_features`` or ``cond_dim`` is non-positive (the
                core's init checks) or ``prior_std`` is not positive.
        """
        core = _GxConcatConditioner.init(
            num_features=num_features,
            cond_dim=cond_dim,
            key=jax.random.key(0) if key is None else key,
        )
        if prior_std <= 0:
            raise ValueError(f"prior_std must be > 0; got {prior_std}.")
        return cls(
            core=core,
            num_features=num_features,
            cond_dim=cond_dim,
            prior_std=prior_std,
            pyrox_name=pyrox_name,
        )

    @pyrox_method
    def __call__(
        self,
        h: Float[Array, "*batch C"],
        c: Float[Array, "*batch K"] | Float[Array, " K"],
    ) -> Float[Array, "*batch C"]:
        # eqx.nn.Linear stores weight as (out, in); match the core's shape.
        out_dim, in_dim = self.core.proj.weight.shape
        W = self.pyrox_sample(
            "proj_W",
            dist.Normal(0.0, self.prior_std).expand([out_dim, in_dim]).to_event(2),
        )
        b = self.pyrox_sample(
            "proj_b",
            dist.Normal(0.0, self.prior_std).expand([out_dim]).to_event(1),
        )
        new_proj = eqx.tree_at(lambda m: (m.weight, m.bias), self.core.proj, (W, b))
        new_core = eqx.tree_at(lambda m: m.proj, self.core, new_proj)

        # Broadcast and batch via vmap; the core expects a single example and
        # checks the shapes of h and c.
        squeeze_h = h.ndim == 1
        if squeeze_h:
            h = h[None, :]
        if c.ndim == 1:
            c = jnp.broadcast_to(c, (h.shape[0], c.shape[-1]))
        out = jax.vmap(new_core, in_axes=(0, 0))(h, c)
        return out[0] if squeeze_h else out

init(num_features: int, cond_dim: int, *, key: PRNGKeyArray | None = None, prior_std: float = 1.0, pyrox_name: str | None = None) -> BayesianConcatConditioner classmethod

Build a BayesianConcatConditioner.

Parameters:

Name Type Description Default
num_features int

Output channels.

required
cond_dim int

Context dimension.

required
key PRNGKeyArray | None

PRNG key for the core's init, whose proj the sampled arrays replace on every call. Defaults to jax.random.key(0).

None
prior_std float

Scale of the Normal priors.

1.0
pyrox_name str | None

Optional explicit scope name.

None

Raises:

Type Description
ValueError

If num_features or cond_dim is non-positive (the core's init checks) or prior_std is not positive.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
@classmethod
def init(
    cls,
    num_features: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray | None = None,
    prior_std: float = 1.0,
    pyrox_name: str | None = None,
) -> BayesianConcatConditioner:
    """Build a `BayesianConcatConditioner`.

    Args:
        num_features: Output channels.
        cond_dim: Context dimension.
        key: PRNG key for the core's init, whose ``proj`` the sampled
            arrays replace on every call. Defaults to ``jax.random.key(0)``.
        prior_std: Scale of the Normal priors.
        pyrox_name: Optional explicit scope name.

    Raises:
        ValueError: If ``num_features`` or ``cond_dim`` is non-positive (the
            core's init checks) or ``prior_std`` is not positive.
    """
    core = _GxConcatConditioner.init(
        num_features=num_features,
        cond_dim=cond_dim,
        key=jax.random.key(0) if key is None else key,
    )
    if prior_std <= 0:
        raise ValueError(f"prior_std must be > 0; got {prior_std}.")
    return cls(
        core=core,
        num_features=num_features,
        cond_dim=cond_dim,
        prior_std=prior_std,
        pyrox_name=pyrox_name,
    )

BayesianAffineModulation

Bases: PyroxModule

AffineModulation of gauss-flows-maps with Normal priors on the FiLM generator.

Registers two sites — {scope}.gen_W and {scope}.gen_b — under Normal(0, prior_std). The γ activation is fixed by construction (default "one_plus_tanh") so the prior over the raw generator output induces a well-defined prior over γ, β.

Holds a frozen gauss_flows_maps.conditioning.AffineModulation core whose generator weights are swapped with the sampled arrays each call. The generator's input size is the core's: cond_dim, or trunk_width when the core has an MLP trunk, and gen_W is sampled with that shape. The trunk gets no prior: priors live on the readout only, so the trunk's weights stay deterministic parameters of the core.

Attributes:

Name Type Description
core AffineModulation

Frozen gauss_flows_maps.conditioning.AffineModulation carrying the single-example forward.

num_features int

Output channels.

cond_dim int

Context dimension.

gamma_activation Reparametrised | Composed | str

Parameterisation of γ: a map of gauss_flows_maps.reparam or one of the core's shorthand strings.

prior_std float

Scale of the Normal priors.

pyrox_name str | None

Optional explicit scope name.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
class BayesianAffineModulation(PyroxModule):
    """`AffineModulation` of gauss-flows-maps with Normal priors on the FiLM generator.

    Registers two sites — ``{scope}.gen_W`` and ``{scope}.gen_b`` —
    under ``Normal(0, prior_std)``. The ``γ`` activation is fixed by
    construction (default ``"one_plus_tanh"``) so the prior over the raw
    generator output induces a well-defined prior over ``γ``, ``β``.

    Holds a frozen `gauss_flows_maps.conditioning.AffineModulation` core whose
    ``generator`` weights are swapped with the sampled arrays each call. The
    generator's input size is the core's: ``cond_dim``, or ``trunk_width`` when the
    core has an MLP trunk, and ``gen_W`` is sampled with that shape. The trunk
    gets no prior: priors live on the readout only, so the trunk's weights
    stay deterministic parameters of the core.

    Attributes:
        core: Frozen `gauss_flows_maps.conditioning.AffineModulation` carrying the
            single-example forward.
        num_features: Output channels.
        cond_dim: Context dimension.
        gamma_activation: Parameterisation of ``γ``: a map of
            `gauss_flows_maps.reparam` or one of the core's shorthand strings.
        prior_std: Scale of the Normal priors.
        pyrox_name: Optional explicit scope name.
    """

    core: _GxAffineModulation
    num_features: int = eqx.field(static=True)
    cond_dim: int = eqx.field(static=True)
    gamma_activation: Reparametrised | Composed | str = eqx.field(
        static=True, default="one_plus_tanh"
    )
    prior_std: float = eqx.field(static=True, default=1.0)
    pyrox_name: str | None = eqx.field(static=True, default=None)

    @classmethod
    def init(
        cls,
        num_features: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray | None = None,
        gamma_activation: Reparametrised
        | Composed
        | 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,
        prior_std: float = 1.0,
        pyrox_name: str | None = None,
    ) -> BayesianAffineModulation:
        """Build a `BayesianAffineModulation`.

        Args:
            num_features: Output channels.
            cond_dim: Context dimension.
            key: PRNG key for the core's init: the trunk's weights, which stay
                deterministic, and the generator, which the sampled arrays replace.
                Defaults to ``jax.random.key(0)``.
            gamma_activation: What `gauss_flows_maps.conditioning.AffineModulation.init`
                takes: a `Reparametrised` or `Composed` map of
                `gauss_flows_maps.reparam`, or one of its shorthand strings.
            trunk_width: Width of the core's MLP trunk; needed when
                ``trunk_depth > 0``.
            trunk_depth: Number of linear layers in the trunk; ``0`` means no trunk.
            trunk_activation: Activation after each trunk layer.
            prior_std: Scale of the Normal priors on the generator.
            pyrox_name: Optional explicit scope name.

        Raises:
            ValueError: If the core's init rejects ``num_features``, ``cond_dim``,
                ``gamma_activation`` or the trunk arguments, or if ``prior_std``
                is not positive.
        """
        core = _GxAffineModulation.init(
            num_features=num_features,
            cond_dim=cond_dim,
            key=jax.random.key(0) if key is None else key,
            gamma_activation=gamma_activation,
            trunk_width=trunk_width,
            trunk_depth=trunk_depth,
            trunk_activation=trunk_activation,
        )
        if prior_std <= 0:
            raise ValueError(f"prior_std must be > 0; got {prior_std}.")
        return cls(
            core=core,
            num_features=num_features,
            cond_dim=cond_dim,
            gamma_activation=gamma_activation,
            prior_std=prior_std,
            pyrox_name=pyrox_name,
        )

    @pyrox_method
    def __call__(
        self,
        h: Float[Array, "*batch C"],
        c: Float[Array, "*batch K"] | Float[Array, " K"],
    ) -> Float[Array, "*batch C"]:
        # eqx.nn.Linear stores weight as (out, in); the core's generator reads the
        # trunk's width, or cond_dim without a trunk.
        out_dim, in_dim = self.core.generator.weight.shape
        W = self.pyrox_sample(
            "gen_W",
            dist.Normal(0.0, self.prior_std).expand([out_dim, in_dim]).to_event(2),
        )
        b = self.pyrox_sample(
            "gen_b",
            dist.Normal(0.0, self.prior_std).expand([out_dim]).to_event(1),
        )
        new_gen = eqx.tree_at(lambda m: (m.weight, m.bias), self.core.generator, (W, b))
        new_core = eqx.tree_at(lambda m: m.generator, self.core, new_gen)

        squeeze_h = h.ndim == 1
        if squeeze_h:
            h = h[None, :]
        if c.ndim == 1:
            c = jnp.broadcast_to(c, (h.shape[0], c.shape[-1]))
        out = jax.vmap(new_core, in_axes=(0, 0))(h, c)
        return out[0] if squeeze_h else out

init(num_features: int, cond_dim: int, *, key: PRNGKeyArray | None = None, gamma_activation: Reparametrised | Composed | 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, prior_std: float = 1.0, pyrox_name: str | None = None) -> BayesianAffineModulation classmethod

Build a BayesianAffineModulation.

Parameters:

Name Type Description Default
num_features int

Output channels.

required
cond_dim int

Context dimension.

required
key PRNGKeyArray | None

PRNG key for the core's init: the trunk's weights, which stay deterministic, and the generator, which the sampled arrays replace. Defaults to jax.random.key(0).

None
gamma_activation Reparametrised | Composed | Literal['one_plus_tanh', 'exp', 'softplus', 'identity']

What gauss_flows_maps.conditioning.AffineModulation.init takes: a Reparametrised or Composed map of gauss_flows_maps.reparam, or one of its shorthand strings.

'one_plus_tanh'
trunk_width int | None

Width of the core's MLP trunk; needed when trunk_depth > 0.

None
trunk_depth int

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

0
trunk_activation Callable[[Array], Array]

Activation after each trunk layer.

relu
prior_std float

Scale of the Normal priors on the generator.

1.0
pyrox_name str | None

Optional explicit scope name.

None

Raises:

Type Description
ValueError

If the core's init rejects num_features, cond_dim, gamma_activation or the trunk arguments, or if prior_std is not positive.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
@classmethod
def init(
    cls,
    num_features: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray | None = None,
    gamma_activation: Reparametrised
    | Composed
    | 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,
    prior_std: float = 1.0,
    pyrox_name: str | None = None,
) -> BayesianAffineModulation:
    """Build a `BayesianAffineModulation`.

    Args:
        num_features: Output channels.
        cond_dim: Context dimension.
        key: PRNG key for the core's init: the trunk's weights, which stay
            deterministic, and the generator, which the sampled arrays replace.
            Defaults to ``jax.random.key(0)``.
        gamma_activation: What `gauss_flows_maps.conditioning.AffineModulation.init`
            takes: a `Reparametrised` or `Composed` map of
            `gauss_flows_maps.reparam`, or one of its shorthand strings.
        trunk_width: Width of the core's MLP trunk; needed when
            ``trunk_depth > 0``.
        trunk_depth: Number of linear layers in the trunk; ``0`` means no trunk.
        trunk_activation: Activation after each trunk layer.
        prior_std: Scale of the Normal priors on the generator.
        pyrox_name: Optional explicit scope name.

    Raises:
        ValueError: If the core's init rejects ``num_features``, ``cond_dim``,
            ``gamma_activation`` or the trunk arguments, or if ``prior_std``
            is not positive.
    """
    core = _GxAffineModulation.init(
        num_features=num_features,
        cond_dim=cond_dim,
        key=jax.random.key(0) if key is None else key,
        gamma_activation=gamma_activation,
        trunk_width=trunk_width,
        trunk_depth=trunk_depth,
        trunk_activation=trunk_activation,
    )
    if prior_std <= 0:
        raise ValueError(f"prior_std must be > 0; got {prior_std}.")
    return cls(
        core=core,
        num_features=num_features,
        cond_dim=cond_dim,
        gamma_activation=gamma_activation,
        prior_std=prior_std,
        pyrox_name=pyrox_name,
    )

BayesianHyperLinear

Bases: PyroxModule

HyperLinear of gauss-flows-maps with Normal priors on the generator only.

Two sites: {scope}.gen_W and {scope}.gen_b. The target weights (W_target, b_target) are generated — not sampled — so Bayesian inference cost scales with the generator size cond_dim * (target_out * target_in + target_out), not with the target-network size. This is the architectural advantage of doing Bayesian amortised inference via hypernetworks.

Attributes:

Name Type Description
core HyperLinear

Frozen gauss_flows_maps.conditioning.HyperLinear carrying the single-example forward.

target_in int

Inner Linear's input dim C_in.

target_out int

Inner Linear's output dim C_out.

cond_dim int

Context dimension K.

num_features int

Alias for target_out.

prior_std float

Scale of the Normal priors on the generator.

pyrox_name str | None

Optional explicit scope name.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
class BayesianHyperLinear(PyroxModule):
    """`HyperLinear` of gauss-flows-maps with Normal priors on the generator only.

    Two sites: ``{scope}.gen_W`` and ``{scope}.gen_b``. The target
    weights ``(W_target, b_target)`` are *generated* — not sampled — so
    Bayesian inference cost scales with the generator size
    ``cond_dim * (target_out * target_in + target_out)``, not with the
    target-network size. This is the architectural advantage of doing
    Bayesian amortised inference via hypernetworks.

    Attributes:
        core: Frozen `gauss_flows_maps.conditioning.HyperLinear` carrying the
            single-example forward.
        target_in: Inner ``Linear``'s input dim ``C_in``.
        target_out: Inner ``Linear``'s output dim ``C_out``.
        cond_dim: Context dimension ``K``.
        num_features: Alias for ``target_out``.
        prior_std: Scale of the Normal priors on the generator.
        pyrox_name: Optional explicit scope name.
    """

    core: _GxHyperLinear
    num_features: int = eqx.field(static=True)
    cond_dim: int = eqx.field(static=True)
    target_in: int = eqx.field(static=True)
    target_out: int = eqx.field(static=True)
    prior_std: float = eqx.field(static=True, default=1.0)
    pyrox_name: str | None = eqx.field(static=True, default=None)

    @classmethod
    def init(
        cls,
        target_in: int,
        target_out: int,
        cond_dim: int,
        *,
        key: PRNGKeyArray | None = None,
        prior_std: float = 1.0,
        pyrox_name: str | None = None,
    ) -> BayesianHyperLinear:
        """Build a `BayesianHyperLinear`.

        Args:
            target_in: Inner ``Linear``'s input dim.
            target_out: Inner ``Linear``'s output dim.
            cond_dim: Context dimension.
            key: PRNG key for the core's init, whose generator the sampled
                arrays replace on every call. Defaults to ``jax.random.key(0)``.
            prior_std: Scale of the Normal priors on the generator.
            pyrox_name: Optional explicit scope name.

        Raises:
            ValueError: If a dimension is non-positive (the core's init checks) or
                ``prior_std`` is not positive.
        """
        core = _GxHyperLinear.init(
            target_in=target_in,
            target_out=target_out,
            cond_dim=cond_dim,
            key=jax.random.key(0) if key is None else key,
        )
        if prior_std <= 0:
            raise ValueError(f"prior_std must be > 0; got {prior_std}.")
        return cls(
            core=core,
            num_features=target_out,
            cond_dim=cond_dim,
            target_in=target_in,
            target_out=target_out,
            prior_std=prior_std,
            pyrox_name=pyrox_name,
        )

    @pyrox_method
    def __call__(
        self,
        x: Float[Array, "*batch C_in"],
        c: Float[Array, "*batch K"] | Float[Array, " K"],
    ) -> Float[Array, "*batch C_out"]:
        # eqx.nn.Linear stores weight as (out, in); match the core's shape.
        flat_size, in_dim = self.core.generator.weight.shape
        W = self.pyrox_sample(
            "gen_W",
            dist.Normal(0.0, self.prior_std).expand([flat_size, in_dim]).to_event(2),
        )
        b = self.pyrox_sample(
            "gen_b",
            dist.Normal(0.0, self.prior_std).expand([flat_size]).to_event(1),
        )
        new_gen = eqx.tree_at(lambda m: (m.weight, m.bias), self.core.generator, (W, b))
        new_core = eqx.tree_at(lambda m: m.generator, self.core, new_gen)

        squeeze_x = x.ndim == 1
        if squeeze_x:
            x = x[None, :]
        if c.ndim == 1:
            c = jnp.broadcast_to(c, (x.shape[0], c.shape[-1]))
        out = jax.vmap(new_core, in_axes=(0, 0))(x, c)
        return out[0] if squeeze_x else out

init(target_in: int, target_out: int, cond_dim: int, *, key: PRNGKeyArray | None = None, prior_std: float = 1.0, pyrox_name: str | None = None) -> BayesianHyperLinear classmethod

Build a BayesianHyperLinear.

Parameters:

Name Type Description Default
target_in int

Inner Linear's input dim.

required
target_out int

Inner Linear's output dim.

required
cond_dim int

Context dimension.

required
key PRNGKeyArray | None

PRNG key for the core's init, whose generator the sampled arrays replace on every call. Defaults to jax.random.key(0).

None
prior_std float

Scale of the Normal priors on the generator.

1.0
pyrox_name str | None

Optional explicit scope name.

None

Raises:

Type Description
ValueError

If a dimension is non-positive (the core's init checks) or prior_std is not positive.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
@classmethod
def init(
    cls,
    target_in: int,
    target_out: int,
    cond_dim: int,
    *,
    key: PRNGKeyArray | None = None,
    prior_std: float = 1.0,
    pyrox_name: str | None = None,
) -> BayesianHyperLinear:
    """Build a `BayesianHyperLinear`.

    Args:
        target_in: Inner ``Linear``'s input dim.
        target_out: Inner ``Linear``'s output dim.
        cond_dim: Context dimension.
        key: PRNG key for the core's init, whose generator the sampled
            arrays replace on every call. Defaults to ``jax.random.key(0)``.
        prior_std: Scale of the Normal priors on the generator.
        pyrox_name: Optional explicit scope name.

    Raises:
        ValueError: If a dimension is non-positive (the core's init checks) or
            ``prior_std`` is not positive.
    """
    core = _GxHyperLinear.init(
        target_in=target_in,
        target_out=target_out,
        cond_dim=cond_dim,
        key=jax.random.key(0) if key is None else key,
    )
    if prior_std <= 0:
        raise ValueError(f"prior_std must be > 0; got {prior_std}.")
    return cls(
        core=core,
        num_features=target_out,
        cond_dim=cond_dim,
        target_in=target_in,
        target_out=target_out,
        prior_std=prior_std,
        pyrox_name=pyrox_name,
    )

Spectral hyper-conditioning

HyperFourierFeatures is the conditional analogue of RBFFourierFeatures: instead of sampling the random Fourier features' (W, b, lengthscale) from a fixed prior, a user-supplied parameter network produces them from the context vector. ConditionedRFFNet adds a learnable linear readout — the conditional analogue of RandomKitchenSinks.

HyperFourierFeatures

Bases: PyroxModule

Random Fourier features with (W, b, log_lengthscale) from a parameter net.

The deterministic counterpart pyrox_nn.RBFFourierFeatures samples its frequencies and lengthscale from priors. This layer instead amortises them over a context vector z via a user-supplied parameter_net:

\[ \begin{aligned} (W(z), b(z), \log\ell(z)) &= \text{unflatten}(\text{parameter\_net}(z)) \\ \phi(x; z) &= \sqrt{1/n_{\text{features}}}\; \bigl[\cos(W(z)^\top x / \ell(z) + b(z)),\; \sin(W(z)^\top x / \ell(z) + b(z))\bigr] \end{aligned} \]

Two execution modes are supported:

  • Shared mode (z.ndim == 1): the parameter net runs once and the generated features are reused across all rows of x — same efficiency trick as HyperLinear's shared path.
  • Per-sample mode (z.ndim == 2): a distinct (W, b, log_lengthscale) is generated per row of z via jax.vmap and applied with einx.dot. This is substantially more expensive in compute and memory because the Fourier parameters are no longer shared across rows of x, but it is required when each x row needs its own context.

The flat output of parameter_net(z) must have size in_features * n_features + n_features + 1 (frequencies, phases, log-lengthscale). init does not invoke parameter_net — a misshapen output surfaces only on the first call.

Attributes:

Name Type Description
parameter_net PyroxModule | Module

Callable (K,) -> (P,) producing the flat feature parameters from the context. Typically a small MLP or any PyroxModule.

in_features int

Coordinate dimension (D_in).

n_features int

Number of frequency pairs; output dim is 2 * n_features.

cond_dim int

Context dimension expected by parameter_net.

pyrox_name str | None

Optional explicit scope name.

Examples:

>>> import jax.random as jr, jax.numpy as jnp
>>> import equinox as eqx
>>> key = jr.key(0)
>>> # Parameter net: (cond_dim=2,) -> (1*16 + 16 + 1 = 33,)
>>> pnet = eqx.nn.MLP(in_size=2, out_size=33, width_size=32, depth=2, key=key)
>>> hff = HyperFourierFeatures.init(
...     parameter_net=pnet, in_features=1, n_features=16, cond_dim=2,
... )
>>> y = hff(jnp.ones((5, 1)), jnp.ones((2,)))
>>> y.shape
(5, 32)
Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
class HyperFourierFeatures(PyroxModule):
    r"""Random Fourier features with ``(W, b, log_lengthscale)`` from a parameter net.

    The deterministic counterpart `pyrox_nn.RBFFourierFeatures`
    *samples* its frequencies and lengthscale from priors. This layer
    instead amortises them over a context vector ``z`` via a user-supplied
    ``parameter_net``:

    $$
    \begin{aligned}
    (W(z), b(z), \log\ell(z)) &= \text{unflatten}(\text{parameter\_net}(z)) \\
    \phi(x; z) &= \sqrt{1/n_{\text{features}}}\;
        \bigl[\cos(W(z)^\top x / \ell(z) + b(z)),\;
              \sin(W(z)^\top x / \ell(z) + b(z))\bigr]
    \end{aligned}
    $$

    Two execution modes are supported:

    * **Shared mode** (``z.ndim == 1``): the parameter net runs once
      and the generated features are reused across all rows of ``x``
      — same efficiency trick as `HyperLinear`'s shared path.
    * **Per-sample mode** (``z.ndim == 2``): a distinct
      ``(W, b, log_lengthscale)`` is generated per row of ``z`` via
      ``jax.vmap`` and applied with ``einx.dot``. This is
      substantially more expensive in compute and memory because the
      Fourier parameters are no longer shared across rows of ``x``,
      but it is required when each ``x`` row needs its own context.

    The flat output of ``parameter_net(z)`` must have size
    ``in_features * n_features + n_features + 1`` (frequencies, phases,
    log-lengthscale). ``init`` does **not** invoke ``parameter_net`` —
    a misshapen output surfaces only on the first call.

    Attributes:
        parameter_net: Callable ``(K,) -> (P,)`` producing the flat
            feature parameters from the context. Typically a small MLP
            or any `PyroxModule`.
        in_features: Coordinate dimension (``D_in``).
        n_features: Number of frequency pairs; output dim is
            ``2 * n_features``.
        cond_dim: Context dimension expected by ``parameter_net``.
        pyrox_name: Optional explicit scope name.

    Examples:
        >>> import jax.random as jr, jax.numpy as jnp
        >>> import equinox as eqx
        >>> key = jr.key(0)
        >>> # Parameter net: (cond_dim=2,) -> (1*16 + 16 + 1 = 33,)
        >>> pnet = eqx.nn.MLP(in_size=2, out_size=33, width_size=32, depth=2, key=key)
        >>> hff = HyperFourierFeatures.init(
        ...     parameter_net=pnet, in_features=1, n_features=16, cond_dim=2,
        ... )
        >>> y = hff(jnp.ones((5, 1)), jnp.ones((2,)))
        >>> y.shape
        (5, 32)
    """

    parameter_net: PyroxModule | eqx.Module
    in_features: int = eqx.field(static=True)
    n_features: int = eqx.field(static=True)
    cond_dim: int = eqx.field(static=True)
    pyrox_name: str | None = eqx.field(static=True, default=None)

    @classmethod
    def init(
        cls,
        *,
        parameter_net: PyroxModule | eqx.Module,
        in_features: int,
        n_features: int,
        cond_dim: int,
        pyrox_name: str | None = None,
    ) -> HyperFourierFeatures:
        """Build `HyperFourierFeatures`.

        ``parameter_net`` is **not** invoked at construction time, so
        Bayesian / numpyro-aware parameter nets that rely on
        ``pyrox_sample`` work without needing a seed handler at init.
        The expected output size is ``in_features * n_features +
        n_features + 1``; a mismatch surfaces as a shape error on the
        first ``__call__``.
        """
        if in_features <= 0 or n_features <= 0 or cond_dim <= 0:
            raise ValueError(
                "in_features, n_features, and cond_dim must all be positive; got "
                f"in_features={in_features}, n_features={n_features}, "
                f"cond_dim={cond_dim}."
            )
        return cls(
            parameter_net=parameter_net,
            in_features=in_features,
            n_features=n_features,
            cond_dim=cond_dim,
            pyrox_name=pyrox_name,
        )

    def _unpack(self, z: Array) -> tuple[Array, Array, Array]:
        """Split ``parameter_net(z)`` into ``(W, b, log_l)``.

        ``W`` is returned with shape ``(in_features, n_features)`` to
        match the layout expected by `functax.basis.features.rff_forward`.
        """
        flat = self.parameter_net(z)  # ty: ignore[call-non-callable]
        w_size = self.in_features * self.n_features
        flat_W = flat[:w_size]
        b = flat[w_size : w_size + self.n_features]
        log_l = flat[-1]
        W = einx.id("(i j) -> i j", flat_W, i=self.in_features)
        return W, b, log_l

    def _single_example(
        self,
        x: Float[Array, " D_in"],
        W: Float[Array, "D_in n"],
        b: Float[Array, " n"],
        log_l: Float[Array, ""],
    ) -> Float[Array, " D_rff"]:
        """Per-example RFF with phase ``b``.

        Like `functax.basis.features.rff_forward`, with the phase added.
        """
        proj = einx.dot("d, d n -> n", x, W) * jnp.exp(-log_l) + b  # (n,)
        scale = jnp.sqrt(1.0 / self.n_features)
        return scale * jnp.concatenate([jnp.cos(proj), jnp.sin(proj)], axis=-1)

    @pyrox_method
    def __call__(
        self,
        x: Float[Array, "*batch D_in"],
        z: Float[Array, "*batch K"] | Float[Array, " K"],
    ) -> Float[Array, "*batch D_rff"]:
        if x.shape[-1] != self.in_features:
            raise ValueError(
                f"x.shape[-1]={x.shape[-1]} does not match "
                f"in_features={self.in_features}."
            )
        if z.shape[-1] != self.cond_dim:
            raise ValueError(
                f"z.shape[-1]={z.shape[-1]} does not match cond_dim={self.cond_dim}."
            )
        # Single-example forward over arbitrary leading batch dims of x
        # (and z, when conditioning is per-sample).
        if z.ndim == 1:
            W, b, log_l = self._unpack(z)
            return vmap_over_flat_batch(
                lambda xi: self._single_example(xi, W, b, log_l), x
            )

        batch_shape = x.shape[:-1]
        x_flat = einx.id("b... d -> (b...) d", x)
        z_flat = einx.id("b... k -> (b...) k", z)
        W_all, b_all, log_l_all = jax.vmap(self._unpack)(z_flat)
        out_flat = jax.vmap(self._single_example)(x_flat, W_all, b_all, log_l_all)
        return einx.id("(b...) k -> b... k", out_flat, b=batch_shape)

init(*, parameter_net: PyroxModule | eqx.Module, in_features: int, n_features: int, cond_dim: int, pyrox_name: str | None = None) -> HyperFourierFeatures classmethod

Build HyperFourierFeatures.

parameter_net is not invoked at construction time, so Bayesian / numpyro-aware parameter nets that rely on pyrox_sample work without needing a seed handler at init. The expected output size is in_features * n_features + n_features + 1; a mismatch surfaces as a shape error on the first __call__.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
@classmethod
def init(
    cls,
    *,
    parameter_net: PyroxModule | eqx.Module,
    in_features: int,
    n_features: int,
    cond_dim: int,
    pyrox_name: str | None = None,
) -> HyperFourierFeatures:
    """Build `HyperFourierFeatures`.

    ``parameter_net`` is **not** invoked at construction time, so
    Bayesian / numpyro-aware parameter nets that rely on
    ``pyrox_sample`` work without needing a seed handler at init.
    The expected output size is ``in_features * n_features +
    n_features + 1``; a mismatch surfaces as a shape error on the
    first ``__call__``.
    """
    if in_features <= 0 or n_features <= 0 or cond_dim <= 0:
        raise ValueError(
            "in_features, n_features, and cond_dim must all be positive; got "
            f"in_features={in_features}, n_features={n_features}, "
            f"cond_dim={cond_dim}."
        )
    return cls(
        parameter_net=parameter_net,
        in_features=in_features,
        n_features=n_features,
        cond_dim=cond_dim,
        pyrox_name=pyrox_name,
    )

ConditionedRFFNet

Bases: PyroxModule

Conditional analogue of pyrox_nn.RandomKitchenSinks.

Composes a HyperFourierFeatures feature map with a learnable linear readout. The full forward is

\[ y(x; z) = \phi(x; z)\, \beta + b_{\text{out}} \]

where \(\phi(x; z)\) is the HyperFourierFeatures output and (beta, b_out) are the readout's deterministic weights. For the Bayesian variant, wrap readout in a DenseReparameterization and move the priors there — this composite stays minimal.

Attributes:

Name Type Description
feat HyperFourierFeatures

A HyperFourierFeatures instance.

readout Linear

eqx.nn.Linear mapping 2 * n_features -> out_features.

pyrox_name str | None

Optional explicit scope name.

Examples:

>>> import jax.random as jr, jax.numpy as jnp
>>> import equinox as eqx
>>> key = jr.key(0)
>>> pnet = eqx.nn.MLP(
...     in_size=4, out_size=1 * 32 + 32 + 1, width_size=32, depth=2, key=key,
... )
>>> feat = HyperFourierFeatures.init(
...     parameter_net=pnet, in_features=1, n_features=32, cond_dim=4,
... )
>>> net = ConditionedRFFNet.init(feat=feat, out_features=1, key=key)
>>> y = net(jnp.zeros((10, 1)), jnp.zeros((10, 4)))
>>> y.shape
(10, 1)
Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
class ConditionedRFFNet(PyroxModule):
    """Conditional analogue of `pyrox_nn.RandomKitchenSinks`.

    Composes a `HyperFourierFeatures` feature map with a learnable
    linear readout. The full forward is

    $$
    y(x; z) = \\phi(x; z)\\, \\beta + b_{\\text{out}}
    $$

    where $\\phi(x; z)$ is the ``HyperFourierFeatures`` output and
    ``(beta, b_out)`` are the readout's deterministic weights. For the
    Bayesian variant, wrap ``readout`` in a ``DenseReparameterization`` and
    move the priors there — this composite stays minimal.

    Attributes:
        feat: A `HyperFourierFeatures` instance.
        readout: ``eqx.nn.Linear`` mapping ``2 * n_features -> out_features``.
        pyrox_name: Optional explicit scope name.

    Examples:
        >>> import jax.random as jr, jax.numpy as jnp
        >>> import equinox as eqx
        >>> key = jr.key(0)
        >>> pnet = eqx.nn.MLP(
        ...     in_size=4, out_size=1 * 32 + 32 + 1, width_size=32, depth=2, key=key,
        ... )
        >>> feat = HyperFourierFeatures.init(
        ...     parameter_net=pnet, in_features=1, n_features=32, cond_dim=4,
        ... )
        >>> net = ConditionedRFFNet.init(feat=feat, out_features=1, key=key)
        >>> y = net(jnp.zeros((10, 1)), jnp.zeros((10, 4)))
        >>> y.shape
        (10, 1)
    """

    feat: HyperFourierFeatures
    readout: eqx.nn.Linear
    pyrox_name: str | None = eqx.field(static=True, default=None)

    @classmethod
    def init(
        cls,
        *,
        feat: HyperFourierFeatures,
        out_features: int,
        key: Array,
        pyrox_name: str | None = None,
    ) -> ConditionedRFFNet:
        """Build `ConditionedRFFNet` with a default linear readout."""
        if out_features <= 0:
            raise ValueError(f"out_features must be > 0; got {out_features}.")
        readout = eqx.nn.Linear(2 * feat.n_features, out_features, key=key)
        return cls(feat=feat, readout=readout, pyrox_name=pyrox_name)

    @pyrox_method
    def __call__(
        self,
        x: Float[Array, "*batch D_in"],
        z: Float[Array, "*batch K"] | Float[Array, " K"],
    ) -> Float[Array, "*batch D_out"]:
        phi = self.feat(x, z)
        # Single-example linear readout over arbitrary leading batch dims.
        return vmap_over_flat_batch(self.readout, phi)

init(*, feat: HyperFourierFeatures, out_features: int, key: Array, pyrox_name: str | None = None) -> ConditionedRFFNet classmethod

Build ConditionedRFFNet with a default linear readout.

Source code in packages/pyrox-nn/src/pyrox_nn/_conditioning.py
@classmethod
def init(
    cls,
    *,
    feat: HyperFourierFeatures,
    out_features: int,
    key: Array,
    pyrox_name: str | None = None,
) -> ConditionedRFFNet:
    """Build `ConditionedRFFNet` with a default linear readout."""
    if out_features <= 0:
        raise ValueError(f"out_features must be > 0; got {out_features}.")
    readout = eqx.nn.Linear(2 * feat.n_features, out_features, key=key)
    return cls(feat=feat, readout=readout, pyrox_name=pyrox_name)

Composites

ConditionedINR

Bases: Module

Wrap an inner network's per-layer activations with conditioners.

Given an inner network that exposes a layers sequence, as SIREN does, the module runs the inner forward pass and inserts a conditioner after each layer except the readout. The conditioners are those of gauss_flows_maps.conditioning.

Algorithm

For mode="feature" (the default):

  1. Set h ← x.
  2. For each non-readout layer ℓ, set h ← layer_ℓ(h), then h ← g_ℓ(h, c).
  3. Return the readout y = layer_L(h), which is not conditioned.

For mode="input", which suits inner networks with no layers sequence:

  1. Set x ← g(x, c) with a single head conditioner.
  2. Return y = inner(x).
Initialisation

AffineModulation and ConcatConditioner start as the identity in h for every context c (the default init="identity" of ConcatConditioner), so the wrapped field starts as the plain inner network, y = inner(x), and training moves it away from it. Pass init="default" to ConcatConditioner or a non-zero readout_scale to AffineModulation, through conditioner_kwargs, to start from a context-dependent field. HyperLinear is not an identity: it generates the weights.

Parameters:

Name Type Description Default
inner

Inner network with a layers attribute for mode="feature", or any callable for mode="input".

required
conditioners

Per-layer conditioners, one for each non-readout layer in "feature" mode, or a single head conditioner in "input" mode.

required
cond_dim

Context dimension K, shared by all conditioners.

required
mode

"feature" for per-layer modulation, or "input" for input-side conditioning.

required

Examples:

Typical case, a four-layer SIREN with AffineModulation after each hidden layer:

>>> import jax.random as jr, jax.numpy as jnp
>>> from geonnax import SIREN
>>> from gauss_flows_maps.conditioning import AffineModulation
>>> from geonnax.conditioning import ConditionedINR
>>> key = jr.key(0)
>>> inner = SIREN.init(2, 32, 1, depth=4, key=key)
>>> wrapped = ConditionedINR.init(
...     inner, conditioner_cls=AffineModulation, cond_dim=4, key=key
... )
>>> y = wrapped(jnp.zeros(2), jnp.zeros(4))
>>> y.shape
(1,)

The conditioners start as the identity, so at init the field is the plain SIREN for every context:

>>> x, c = jnp.array([0.3, -0.2]), jnp.arange(4.0)
>>> bool(jnp.allclose(wrapped(x, c), inner(x)))
True

Input-side conditioning, with one head conditioner on x:

>>> head = ConditionedINR.init(
...     inner, conditioner_cls=AffineModulation, cond_dim=4, key=key,
...     mode="input",
... )
>>> head(jnp.zeros(2), jnp.zeros(4)).shape
(1,)

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

>>> import jax
>>> jax.vmap(wrapped)(jnp.zeros((5, 2)), jnp.zeros((5, 4))).shape
(5, 1)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/conditioning/_inr.py
class ConditionedINR(eqx.Module):
    """Wrap an inner network's per-layer activations with conditioners.

    Given an `inner` network that exposes a `layers` sequence, as `SIREN` does, the
    module runs the inner forward pass and inserts a conditioner after each layer
    except the readout. The conditioners are those of `gauss_flows_maps.conditioning`.

    Algorithm:
        For `mode="feature"` (the default):

        1. Set `h ← x`.
        2. For each non-readout layer `ℓ`, set `h ← layer_ℓ(h)`, then `h ← g_ℓ(h, c)`.
        3. Return the readout `y = layer_L(h)`, which is not conditioned.

        For `mode="input"`, which suits inner networks with no `layers` sequence:

        1. Set `x ← g(x, c)` with a single head conditioner.
        2. Return `y = inner(x)`.

    Initialisation:
        `AffineModulation` and `ConcatConditioner` start as the identity in `h` for
        every context `c` (the default `init="identity"` of `ConcatConditioner`), so
        the wrapped field starts as the plain inner network, `y = inner(x)`, and
        training moves it away from it. Pass `init="default"` to `ConcatConditioner`
        or a non-zero `readout_scale` to `AffineModulation`, through
        `conditioner_kwargs`, to start from a context-dependent field. `HyperLinear`
        is not an identity: it generates the weights.

    Args:
        inner: Inner network with a `layers` attribute for `mode="feature"`, or any
            callable for `mode="input"`.
        conditioners: Per-layer conditioners, one for each non-readout layer in
            `"feature"` mode, or a single head conditioner in `"input"` mode.
        cond_dim: Context dimension `K`, shared by all conditioners.
        mode: `"feature"` for per-layer modulation, or `"input"` for input-side
            conditioning.

    Examples:
        Typical case, a four-layer `SIREN` with `AffineModulation` after each
        hidden layer:

        >>> import jax.random as jr, jax.numpy as jnp
        >>> from geonnax import SIREN
        >>> from gauss_flows_maps.conditioning import AffineModulation
        >>> from geonnax.conditioning import ConditionedINR
        >>> key = jr.key(0)
        >>> inner = SIREN.init(2, 32, 1, depth=4, key=key)
        >>> wrapped = ConditionedINR.init(
        ...     inner, conditioner_cls=AffineModulation, cond_dim=4, key=key
        ... )
        >>> y = wrapped(jnp.zeros(2), jnp.zeros(4))
        >>> y.shape
        (1,)

        The conditioners start as the identity, so at init the field is the plain
        `SIREN` for every context:

        >>> x, c = jnp.array([0.3, -0.2]), jnp.arange(4.0)
        >>> bool(jnp.allclose(wrapped(x, c), inner(x)))
        True

        Input-side conditioning, with one head conditioner on `x`:

        >>> head = ConditionedINR.init(
        ...     inner, conditioner_cls=AffineModulation, cond_dim=4, key=key,
        ...     mode="input",
        ... )
        >>> head(jnp.zeros(2), jnp.zeros(4)).shape
        (1,)

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

        >>> import jax
        >>> jax.vmap(wrapped)(jnp.zeros((5, 2)), jnp.zeros((5, 4))).shape
        (5, 1)
    """

    inner: eqx.Module
    conditioners: list[AbstractConditioner]
    cond_dim: int = eqx.field(static=True)
    mode: ConditionedMode = eqx.field(static=True)

    @classmethod
    def init(
        cls,
        inner: eqx.Module,
        *,
        conditioner_cls: type[AbstractConditioner],
        cond_dim: int,
        key: PRNGKeyArray,
        mode: ConditionedMode = "feature",
        **conditioner_kwargs: object,
    ) -> ConditionedINR:
        """Build a `ConditionedINR` around `inner`.

        Args:
            inner: Inner network. It must have a `layers` sequence for
                `mode="feature"`, and can be any callable for `mode="input"`.
            conditioner_cls: One of the classes of `gauss_flows_maps.conditioning`:
                `ConcatConditioner`, `AffineModulation` or `HyperLinear`.
            cond_dim: Context dimension `K`, passed to each conditioner.
            key: PRNG key, split once for each conditioner.
            mode: `"feature"` for per-layer modulation (the default), or `"input"`
                for a single input-side conditioner.
            **conditioner_kwargs: Extra keyword arguments forwarded to each
                `conditioner_cls.init`.

        Returns:
            Initialised `ConditionedINR`.

        Raises:
            ValueError: If `mode` is unknown, if `mode="feature"` and `inner` has no
                `layers` attribute or fewer than two layers, or if a layer or the
                inner network lacks an integer width attribute that sizes the
                conditioners.
        """
        if mode not in ("feature", "input"):
            raise ValueError(f"mode must be 'feature' or 'input'; got {mode!r}.")

        if mode == "input":
            keys = jr.split(key, 1)
            head = _build_conditioner(
                conditioner_cls,
                num_features=_inner_in_features(inner),
                cond_dim=cond_dim,
                key=keys[0],
                **conditioner_kwargs,
            )
            return cls(
                inner=inner,
                conditioners=[head],
                cond_dim=cond_dim,
                mode="input",
            )

        layers = getattr(inner, "layers", None)
        if layers is None:
            raise ValueError(
                "mode='feature' requires `inner` to expose a `layers` sequence "
                "(e.g. geonnax.SIREN). For inners without `layers`, use mode='input'."
            )
        if len(layers) < 2:
            raise ValueError(
                "mode='feature' needs at least two inner layers; got "
                f"{len(layers)}. Use mode='input' for shallow inners."
            )

        # the readout layer is not conditioned, so there is one fewer conditioner
        n_cond = len(layers) - 1
        keys = jr.split(key, n_cond)
        conditioners: list[AbstractConditioner] = []
        for i, k in enumerate(keys):
            num_features = _layer_out_features(layers[i], i)
            conditioners.append(
                _build_conditioner(
                    conditioner_cls,
                    num_features=num_features,
                    cond_dim=cond_dim,
                    key=k,
                    **conditioner_kwargs,
                )
            )
        return cls(
            inner=inner,
            conditioners=conditioners,
            cond_dim=cond_dim,
            mode="feature",
        )

    def __call__(
        self,
        x: Float[Array, " D_in"],
        c: Float[Array, " K"],
        /,
    ) -> Float[Array, " D_out"]:
        """Run the inner network with the conditioners applied to the context `c`.

        Both arguments are positional-only.

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

        Returns:
            Output vector `y ∈ ℝ^(D_out)`.

        Raises:
            ValueError: If `c` does not match `cond_dim`.
        """
        if c.shape[-1] != self.cond_dim:
            raise ValueError(
                f"c.shape[-1]={c.shape[-1]} does not match cond_dim={self.cond_dim}."
            )
        if self.mode == "input":
            head = self.conditioners[0]
            # x ← g(x, c)
            x = head(x, c)
            # y = inner(x)
            return self.inner(x)  # ty: ignore[call-non-callable]

        # --- feature mode: run each non-readout layer, then condition it ---
        layers = self.inner.layers  # ty: ignore[unresolved-attribute]
        h = x
        for i, layer in enumerate(layers[:-1]):
            # h ← layer_i(h)
            h = layer(h)
            # h ← g_i(h, c)
            h = self.conditioners[i](h, c)
        # y = layer_L(h), the readout
        return layers[-1](h)

init(inner: eqx.Module, *, conditioner_cls: type[AbstractConditioner], cond_dim: int, key: PRNGKeyArray, mode: ConditionedMode = 'feature', **conditioner_kwargs: object) -> ConditionedINR classmethod

Build a ConditionedINR around inner.

Parameters:

Name Type Description Default
inner Module

Inner network. It must have a layers sequence for mode="feature", and can be any callable for mode="input".

required
conditioner_cls type[AbstractConditioner]

One of the classes of gauss_flows_maps.conditioning: ConcatConditioner, AffineModulation or HyperLinear.

required
cond_dim int

Context dimension K, passed to each conditioner.

required
key PRNGKeyArray

PRNG key, split once for each conditioner.

required
mode ConditionedMode

"feature" for per-layer modulation (the default), or "input" for a single input-side conditioner.

'feature'
**conditioner_kwargs object

Extra keyword arguments forwarded to each conditioner_cls.init.

{}

Returns:

Type Description
ConditionedINR

Initialised ConditionedINR.

Raises:

Type Description
ValueError

If mode is unknown, if mode="feature" and inner has no layers attribute or fewer than two layers, or if a layer or the inner network lacks an integer width attribute that sizes the conditioners.

Source code in .venv/lib/python3.12/site-packages/geonnax/_src/conditioning/_inr.py
@classmethod
def init(
    cls,
    inner: eqx.Module,
    *,
    conditioner_cls: type[AbstractConditioner],
    cond_dim: int,
    key: PRNGKeyArray,
    mode: ConditionedMode = "feature",
    **conditioner_kwargs: object,
) -> ConditionedINR:
    """Build a `ConditionedINR` around `inner`.

    Args:
        inner: Inner network. It must have a `layers` sequence for
            `mode="feature"`, and can be any callable for `mode="input"`.
        conditioner_cls: One of the classes of `gauss_flows_maps.conditioning`:
            `ConcatConditioner`, `AffineModulation` or `HyperLinear`.
        cond_dim: Context dimension `K`, passed to each conditioner.
        key: PRNG key, split once for each conditioner.
        mode: `"feature"` for per-layer modulation (the default), or `"input"`
            for a single input-side conditioner.
        **conditioner_kwargs: Extra keyword arguments forwarded to each
            `conditioner_cls.init`.

    Returns:
        Initialised `ConditionedINR`.

    Raises:
        ValueError: If `mode` is unknown, if `mode="feature"` and `inner` has no
            `layers` attribute or fewer than two layers, or if a layer or the
            inner network lacks an integer width attribute that sizes the
            conditioners.
    """
    if mode not in ("feature", "input"):
        raise ValueError(f"mode must be 'feature' or 'input'; got {mode!r}.")

    if mode == "input":
        keys = jr.split(key, 1)
        head = _build_conditioner(
            conditioner_cls,
            num_features=_inner_in_features(inner),
            cond_dim=cond_dim,
            key=keys[0],
            **conditioner_kwargs,
        )
        return cls(
            inner=inner,
            conditioners=[head],
            cond_dim=cond_dim,
            mode="input",
        )

    layers = getattr(inner, "layers", None)
    if layers is None:
        raise ValueError(
            "mode='feature' requires `inner` to expose a `layers` sequence "
            "(e.g. geonnax.SIREN). For inners without `layers`, use mode='input'."
        )
    if len(layers) < 2:
        raise ValueError(
            "mode='feature' needs at least two inner layers; got "
            f"{len(layers)}. Use mode='input' for shallow inners."
        )

    # the readout layer is not conditioned, so there is one fewer conditioner
    n_cond = len(layers) - 1
    keys = jr.split(key, n_cond)
    conditioners: list[AbstractConditioner] = []
    for i, k in enumerate(keys):
        num_features = _layer_out_features(layers[i], i)
        conditioners.append(
            _build_conditioner(
                conditioner_cls,
                num_features=num_features,
                cond_dim=cond_dim,
                key=k,
                **conditioner_kwargs,
            )
        )
    return cls(
        inner=inner,
        conditioners=conditioners,
        cond_dim=cond_dim,
        mode="feature",
    )

HyperSIREN(in_features: int, hidden_features: int, out_features: int, *, depth: int, cond_dim: int, parameter_net: eqx.Module, key: PRNGKeyArray, first_omega: float = 30.0, hidden_omega: float = 30.0, c: float = 6.0, init_scale: float = 1.0) -> GeneratedSiren

Build the NIF-style ShapeNet and ParameterNet composite.

The composite generates the weights of a SIREN from a latent code, z = P(μ), with each hidden layer h_ℓ = sin(ω_ℓ (W_ℓ(z) h_{ℓ-1} + b_ℓ(z))). It builds a SIREN of the requested topology, then one HyperLinear generator per layer (from gauss_flows_maps.conditioning). Each generator starts at its SIREN layer's initial variance (hyperfan initialisation): Sitzmann's layer draws W ~ U(−a, a) with a = siren_W_limit(...), whose standard deviation is σ* = a/√3, and the generator is passed target_std = σ*, so that, averaged over codes with 𝔼[z_k²] = 1, the generated W has standard deviation s σ* for every K. Without this calibration the ShapeNet's pre-activation variance is wrong and training is unstable.

Algorithm
  1. Compute the latent code z = P(μ) once per call.
  2. For each layer ℓ, with h₀ = x, form pre_ℓ = W_ℓ(z) h_{ℓ-1} + b_ℓ(z).
  3. Set h_ℓ = sin(ω_ℓ pre_ℓ) for hidden layers, and h_L = pre_L for the readout.

Parameters:

Name Type Description Default
in_features int

Coordinate dimension D_in of the SIREN.

required
hidden_features int

Hidden width.

required
out_features int

Output dimension D_out.

required
depth int

SIREN depth L, which must be at least two.

required
cond_dim int

Latent dimension K that parameter_net produces.

required
parameter_net Module

Callable ℝ^P → ℝ^K, supplied by the user.

required
key PRNGKeyArray

PRNG key, split internally for the SIREN and the hyper generators.

required
first_omega float

First-layer frequency ω_1.

30.0
hidden_omega float

Hidden-layer frequency ω_ℓ.

30.0
c float

SIREN Theorem-1 constant.

6.0
init_scale float

Factor s on the generated weights' standard deviation. The default 1 starts every generated layer at its SIREN layer's initial variance.

1.0

Returns:

Type Description
GeneratedSiren

A composite that takes (x, μ) and runs the NIF forward pass.

Raises:

Type Description
ValueError

If depth < 2 or any positive-only argument is non-positive.

References

Pan, Brunton and Kutz (2023). Neural implicit flow. JMLR. Sitzmann, V., et al. (2020). Implicit neural representations with periodic activation functions. NeurIPS. Chang, O., Flokas, L. and Lipson, H. (2020). Principled weight initialization for hypernetworks. ICLR.

Examples:

Typical case, a two-layer network from three inputs to two outputs:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import equinox as eqx
>>> pnet_key, build_key = jr.split(jr.PRNGKey(0))
>>> pnet = eqx.nn.MLP(
...     in_size=2, out_size=4, width_size=8, depth=2, key=pnet_key
... )
>>> net = HyperSIREN(
...     in_features=3, hidden_features=8, out_features=2, depth=2,
...     cond_dim=4, parameter_net=pnet, key=build_key,
... )
>>> net(jnp.zeros(3), jnp.zeros(2)).shape
(2,)

Edge case, a depth below two is rejected:

>>> HyperSIREN(
...     in_features=3, hidden_features=8, out_features=2, depth=1,
...     cond_dim=4, parameter_net=pnet, key=build_key,
... )
Traceback (most recent call last):
ValueError: depth must be >= 2 (first + last); got depth=1.

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

>>> import jax
>>> jax.vmap(net)(jnp.zeros((5, 3)), jnp.zeros((5, 2))).shape
(5, 2)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/conditioning/_inr.py
def HyperSIREN(
    in_features: int,
    hidden_features: int,
    out_features: int,
    *,
    depth: int,
    cond_dim: int,
    parameter_net: eqx.Module,
    key: PRNGKeyArray,
    first_omega: float = 30.0,
    hidden_omega: float = 30.0,
    c: float = 6.0,
    init_scale: float = 1.0,
) -> GeneratedSiren:
    """Build the NIF-style ShapeNet and ParameterNet composite.

    The composite generates the weights of a SIREN from a latent code,
    `z = P(μ)`, with each hidden layer `h_ℓ = sin(ω_ℓ (W_ℓ(z) h_{ℓ-1} + b_ℓ(z)))`.
    It builds a SIREN of the requested topology, then one `HyperLinear` generator per
    layer (from `gauss_flows_maps.conditioning`). Each generator starts at its SIREN
    layer's initial variance (hyperfan initialisation): Sitzmann's layer draws
    `W ~ U(−a, a)` with `a = siren_W_limit(...)`, whose standard deviation is
    `σ* = a/√3`, and the generator is passed `target_std = σ*`, so that, averaged
    over codes with `𝔼[z_k²] = 1`, the generated `W` has standard deviation
    `s σ*` for every `K`. Without this calibration the ShapeNet's pre-activation
    variance is wrong and training is unstable.

    Algorithm:
        1. Compute the latent code `z = P(μ)` once per call.
        2. For each layer `ℓ`, with `h₀ = x`, form `pre_ℓ = W_ℓ(z) h_{ℓ-1} + b_ℓ(z)`.
        3. Set `h_ℓ = sin(ω_ℓ pre_ℓ)` for hidden layers, and `h_L = pre_L` for the
           readout.

    Args:
        in_features: Coordinate dimension `D_in` of the SIREN.
        hidden_features: Hidden width.
        out_features: Output dimension `D_out`.
        depth: SIREN depth `L`, which must be at least two.
        cond_dim: Latent dimension `K` that `parameter_net` produces.
        parameter_net: Callable `ℝ^P → ℝ^K`, supplied by the user.
        key: PRNG key, split internally for the SIREN and the hyper generators.
        first_omega: First-layer frequency `ω_1`.
        hidden_omega: Hidden-layer frequency `ω_ℓ`.
        c: SIREN Theorem-1 constant.
        init_scale: Factor `s` on the generated weights' standard deviation. The
            default `1` starts every generated layer at its SIREN layer's
            initial variance.

    Returns:
        A composite that takes `(x, μ)` and runs the NIF forward pass.

    Raises:
        ValueError: If `depth < 2` or any positive-only argument is non-positive.

    References:
        Pan, Brunton and Kutz (2023). Neural implicit flow. JMLR.
        Sitzmann, V., et al. (2020). Implicit neural representations with periodic
        activation functions. NeurIPS.
        Chang, O., Flokas, L. and Lipson, H. (2020). Principled weight
        initialization for hypernetworks. ICLR.

    Examples:
        Typical case, a two-layer network from three inputs to two outputs:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> import equinox as eqx
        >>> pnet_key, build_key = jr.split(jr.PRNGKey(0))
        >>> pnet = eqx.nn.MLP(
        ...     in_size=2, out_size=4, width_size=8, depth=2, key=pnet_key
        ... )
        >>> net = HyperSIREN(
        ...     in_features=3, hidden_features=8, out_features=2, depth=2,
        ...     cond_dim=4, parameter_net=pnet, key=build_key,
        ... )
        >>> net(jnp.zeros(3), jnp.zeros(2)).shape
        (2,)

        Edge case, a depth below two is rejected:

        >>> HyperSIREN(  # doctest: +IGNORE_EXCEPTION_DETAIL
        ...     in_features=3, hidden_features=8, out_features=2, depth=1,
        ...     cond_dim=4, parameter_net=pnet, key=build_key,
        ... )
        Traceback (most recent call last):
        ValueError: depth must be >= 2 (first + last); got depth=1.

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

        >>> import jax
        >>> jax.vmap(net)(jnp.zeros((5, 3)), jnp.zeros((5, 2))).shape
        (5, 2)
    """
    if depth < 2:
        raise ValueError(f"depth must be >= 2 (first + last); got depth={depth}.")
    for name, v in {
        "in_features": in_features,
        "hidden_features": hidden_features,
        "out_features": out_features,
        "cond_dim": cond_dim,
        "first_omega": first_omega,
        "hidden_omega": hidden_omega,
        "c": c,
        "init_scale": init_scale,
    }.items():
        if v <= 0:
            raise ValueError(f"{name} must be > 0; got {v}.")

    # one key for the SIREN, one for each hyper generator
    siren_key, *hyper_keys = jr.split(key, 1 + depth)
    siren = SIREN.init(
        in_features,
        hidden_features,
        out_features,
        depth=depth,
        key=siren_key,
        first_omega=first_omega,
        hidden_omega=hidden_omega,
        c=c,
    )
    hyper_layers: list[HyperLinear] = []
    for i, layer in enumerate(siren.layers):
        layer_in = layer.in_features
        layer_out = layer.out_features
        # a = Sitzmann's per-regime half-width of W
        regime_limit = siren_W_limit(layer.layer_type, layer_in, layer.omega, c)
        # σ* = a/√3, the standard deviation of U(−a, a)
        target_std = regime_limit / math.sqrt(3.0)
        hyper_layers.append(
            HyperLinear.init(
                target_in=layer_in,
                target_out=layer_out,
                cond_dim=cond_dim,
                key=hyper_keys[i],
                target_std=target_std,
                init_scale=init_scale,
            )
        )
    return GeneratedSiren(
        parameter_net=parameter_net,
        siren=siren,
        hyper_layers=hyper_layers,
        in_features=in_features,
        out_features=out_features,
        depth=depth,
    )