Skip to content

Flows API

pyrox_flows holds the NumPyro bridges for gauss_flows' normalizing flows. They moved here from gauss_flows (#591), which no longer depends on NumPyro. pyrox_flows imports gauss_flows, flowjax and NumPyro and never imports pyrox.

A flow as a NumPyro distribution

flow_to_numpyro replaces gauss_flows' FlowDist. It wraps flowjax's own bridge so that the site also draws under NumPyro's handlers.

flow_to_numpyro(flow: AbstractDistribution, condition: ArrayLike | None = None) -> ndist.Distribution

Wrap a flowjax distribution (a gauss_flows flow is one) as a NumPyro one.

It is a prior, a likelihood with obs= or a guide under numpyro.sample. The numerics are flowjax's distribution_to_numpyro; the wrapper adds one thing, that sample accepts the legacy uint32 keys NumPyro's handlers pass, so the site draws under Predictive, seed and MCMC. It replaces gauss_flows' FlowDist, whose batch shape (empty), event shape (flow.shape) and real-valued support it keeps.

Parameters:

Name Type Description Default
flow AbstractDistribution

A flowjax distribution.

required
condition ArrayLike | None

The conditioning variable of a conditional flow. Its leading dims become the batch shape. Defaults to None.

None

Returns:

Type Description
Distribution

A NumPyro distribution with event_shape == flow.shape.

Examples:

>>> import jax.random as jr
>>> from gauss_flows import gaussianization_flow
>>> from pyrox_flows import flow_to_numpyro
>>> flow = gaussianization_flow(jr.key(0), n_dims=2)
>>> flow_dist = flow_to_numpyro(flow)
>>> flow_dist.event_shape
(2,)
>>> x = flow_dist.sample(jr.key(1), (5,))
>>> x.shape
(5, 2)
>>> flow_dist.log_prob(x).shape
(5,)
Source code in packages/pyrox-flows/src/pyrox_flows/_flow_to_numpyro.py
def flow_to_numpyro(
    flow: AbstractDistribution, condition: ArrayLike | None = None
) -> ndist.Distribution:
    """Wrap a flowjax distribution (a gauss_flows flow is one) as a NumPyro one.

    It is a prior, a likelihood with ``obs=`` or a guide under ``numpyro.sample``.
    The numerics are flowjax's ``distribution_to_numpyro``; the wrapper adds one
    thing, that ``sample`` accepts the legacy ``uint32`` keys NumPyro's handlers
    pass, so the site draws under ``Predictive``, ``seed`` and ``MCMC``. It
    replaces gauss_flows' ``FlowDist``, whose batch shape (empty), event shape
    (``flow.shape``) and real-valued support it keeps.

    Args:
        flow: A flowjax distribution.
        condition: The conditioning variable of a conditional flow. Its leading
            dims become the batch shape. Defaults to ``None``.

    Returns:
        A NumPyro distribution with ``event_shape == flow.shape``.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows import gaussianization_flow
        >>> from pyrox_flows import flow_to_numpyro
        >>> flow = gaussianization_flow(jr.key(0), n_dims=2)
        >>> flow_dist = flow_to_numpyro(flow)
        >>> flow_dist.event_shape
        (2,)
        >>> x = flow_dist.sample(jr.key(1), (5,))
        >>> x.shape
        (5, 2)
        >>> flow_dist.log_prob(x).shape
        (5,)
    """
    return _FlowNumpyro(distribution_to_numpyro(flow, condition))

A NumPyro distribution as a flow base

NumpyroBase

Bases: AbstractDistribution

Wrap any numpyro.distributions.Distribution as a flowjax base.

Two construction modes:

  • Unconditional (dist=...): a fixed numpyro distribution. The event_shape is read from dist.event_shape and cond_shape is None. The numpyro distribution must have batch_shape == (); if you need to broadcast a scalar dist to a vector event, use .expand(shape).to_event(rank) so the broadcasted dims are reinterpreted as event dims (otherwise batch_shape will be non-trivial and this wrapper will reject it).
  • Conditional (dist_factory=...): a callable condition -> numpyro.distributions.Distribution invoked per call. The user must supply event_shape and cond_shape because the factory is not run at construction time. Each invocation is responsible for returning a distribution with matching event_shape and batch_shape == ().

Vector events: numpyro returns one log-prob per event-shape position by default. Wrap your distribution in .to_event(rank) so that log_prob returns a scalar; alternatively, use a multivariate distribution like numpyro.distributions.MultivariateNormal whose event_shape already encodes the rank.

Parameters:

Name Type Description Default
dist Distribution | None

A numpyro distribution. Mutually exclusive with dist_factory.

None
dist_factory Callable[[Array], Distribution] | None

A callable mapping a condition array to a numpyro distribution. Mutually exclusive with dist.

None
event_shape tuple[int, ...] | None

Required when using dist_factory. Ignored when using dist (read from dist.event_shape instead).

None
cond_shape tuple[int, ...] | None

Required when using dist_factory.

None
Shape
  • Condition: cond_shape (None if unconditional)
  • Sample / log_prob input: event_shape
  • log_prob output: scalar ()

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import numpyro.distributions as ndist
>>> from pyrox_flows import NumpyroBase
>>> # Unconditional 3D Gaussian
>>> base = NumpyroBase(dist=ndist.Normal(0.0, 1.0).expand((3,)).to_event(1))
>>> base.shape, base.cond_shape
((3,), None)
>>> base.log_prob(jnp.zeros(3)).shape
()
>>> # Conditional: loc depends on context
>>> def factory(c):
...     return ndist.Normal(c, 1.0).to_event(1)
>>> cbase = NumpyroBase(
...     dist_factory=factory, event_shape=(3,), cond_shape=(3,)
... )
>>> cbase.log_prob(jnp.zeros(3), condition=jnp.ones(3)).shape
()
Source code in packages/pyrox-flows/src/pyrox_flows/_numpyro_base.py
class NumpyroBase(AbstractDistribution):
    """Wrap any `numpyro.distributions.Distribution` as a flowjax base.

    Two construction modes:

    - **Unconditional** (``dist=...``): a fixed numpyro distribution. The
      ``event_shape`` is read from ``dist.event_shape`` and ``cond_shape`` is
      ``None``. The numpyro distribution must have ``batch_shape == ()``; if
      you need to broadcast a scalar dist to a vector event, use
      ``.expand(shape).to_event(rank)`` so the broadcasted dims are
      reinterpreted as event dims (otherwise ``batch_shape`` will be
      non-trivial and this wrapper will reject it).
    - **Conditional** (``dist_factory=...``): a callable
      ``condition -> numpyro.distributions.Distribution`` invoked per call.
      The user must supply ``event_shape`` and ``cond_shape`` because the
      factory is not run at construction time. Each invocation is
      responsible for returning a distribution with matching ``event_shape``
      and ``batch_shape == ()``.

    Vector events: numpyro returns one log-prob per *event-shape* position
    by default. Wrap your distribution in ``.to_event(rank)`` so that
    ``log_prob`` returns a scalar; alternatively, use a multivariate
    distribution like `numpyro.distributions.MultivariateNormal` whose
    ``event_shape`` already encodes the rank.

    Args:
        dist: A numpyro distribution. Mutually exclusive with ``dist_factory``.
        dist_factory: A callable mapping a condition array to a numpyro
            distribution. Mutually exclusive with ``dist``.
        event_shape: Required when using ``dist_factory``. Ignored when
            using ``dist`` (read from ``dist.event_shape`` instead).
        cond_shape: Required when using ``dist_factory``.

    Shape:
        - Condition: ``cond_shape`` (``None`` if unconditional)
        - Sample / log_prob input: ``event_shape``
        - log_prob output: scalar ``()``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> import numpyro.distributions as ndist
        >>> from pyrox_flows import NumpyroBase
        >>> # Unconditional 3D Gaussian
        >>> base = NumpyroBase(dist=ndist.Normal(0.0, 1.0).expand((3,)).to_event(1))
        >>> base.shape, base.cond_shape
        ((3,), None)
        >>> base.log_prob(jnp.zeros(3)).shape
        ()
        >>> # Conditional: loc depends on context
        >>> def factory(c):
        ...     return ndist.Normal(c, 1.0).to_event(1)
        >>> cbase = NumpyroBase(
        ...     dist_factory=factory, event_shape=(3,), cond_shape=(3,)
        ... )
        >>> cbase.log_prob(jnp.zeros(3), condition=jnp.ones(3)).shape
        ()
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] | None
    _dist: ndist.Distribution | None
    # ``_factory`` is a regular (non-static) field so that an ``eqx.Module``
    # factory carrying learnable parameters remains visible to
    # ``eqx.filter_grad`` and to optimizers. Plain Python callables (lambdas /
    # closures) are still accepted — equinox treats them as opaque PyTree
    # leaves that ``eqx.is_array`` filters skip.
    _factory: Callable[[Array], ndist.Distribution] | None

    def __init__(
        self,
        *,
        dist: ndist.Distribution | None = None,
        dist_factory: Callable[[Array], ndist.Distribution] | None = None,
        event_shape: tuple[int, ...] | None = None,
        cond_shape: tuple[int, ...] | None = None,
    ):
        if (dist is None) == (dist_factory is None):
            raise ValueError(
                "Pass exactly one of 'dist' (unconditional) or 'dist_factory' "
                "(conditional)."
            )

        if dist is not None:
            if dist.batch_shape != ():
                raise ValueError(
                    "NumpyroBase requires a single-event distribution with "
                    f"batch_shape == (); got {dist.batch_shape}. Wrap with "
                    ".expand(...) only if necessary, then .to_event(...) the "
                    "broadcasted dims."
                )
            inferred = tuple(dist.event_shape)
            if event_shape is not None and tuple(event_shape) != inferred:
                raise ValueError(
                    f"event_shape={event_shape} does not match the wrapped "
                    f"distribution's event_shape={inferred}."
                )
            if cond_shape is not None:
                raise ValueError(
                    "cond_shape must be None when wrapping a fixed 'dist' "
                    "(unconditional mode)."
                )
            self.shape = inferred
            self.cond_shape = None
            self._dist = dist
            self._factory = None
        else:
            if event_shape is None or cond_shape is None:
                raise ValueError(
                    "When using 'dist_factory', both 'event_shape' and "
                    "'cond_shape' are required."
                )
            self.shape = tuple(event_shape)
            self.cond_shape = tuple(cond_shape)
            self._dist = None
            self._factory = dist_factory

    def _resolve(self, condition: Array | None) -> ndist.Distribution:
        if self._factory is None:
            return self._dist  # type: ignore[return-value]
        return self._factory(condition)

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        return self._resolve(condition).sample(key)

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        return self._resolve(condition).log_prob(x)

A flow as an SVI guide

FlowGuide

Bases: AutoContinuous

NumPyro variational guide using a Gaussianization flow.

Subclasses numpyro.infer.autoguide.AutoContinuous, using a normalizing flow as the variational distribution for SVI. The flow models a joint distribution over the concatenated unconstrained latent space of the model, so it captures cross-variable correlations because all latent sites are handled jointly. The flow is built lazily once latent_dim is known (at prototype setup), and its parameters are registered with NumPyro so the SVI optimiser can update them.

Parameters:

Name Type Description Default
model Callable[..., Any]

A NumPyro model.

required
flow_factory Callable[..., Transformed]

Callable that constructs a flowjax Transformed distribution. Must accept key and n_dims positional / keyword arguments, plus any flow_kwargs. Defaults to gauss_flows.gaussianization_flow.

gaussianization_flow
flow_kwargs dict[str, Any] | None

Extra keyword arguments forwarded to flow_factory (e.g. n_layers, n_components). Defaults to {}.

None
init_key PRNGKeyArray | None

JAX random key used to initialise the flow parameters. Defaults to jr.PRNGKey(0) when not provided. The SVI optimiser will update these parameters, so the exact choice of seed only affects the starting point of optimisation.

None
prefix str

Prefix used for numpyro parameter names. Defaults to "auto".

'auto'
init_loc_fn Callable[..., Any]

Per-site initialization strategy. Defaults to numpyro.infer.initialization.init_to_uniform.

init_to_uniform

Examples:

import jax.numpy as jnp
import jax.random as jr
import numpyro
import numpyro.distributions as dist
from numpyro.infer import SVI, Trace_ELBO
from numpyro.optim import Adam
from pyrox_flows import FlowGuide

def model(obs=None):
    mu = numpyro.sample("mu", dist.Normal(0.0, 1.0))
    numpyro.sample("obs", dist.Normal(mu, 1.0), obs=obs)

guide = FlowGuide(model)
svi = SVI(model, guide, Adam(1e-3), loss=Trace_ELBO())
result = svi.run(jr.key(0), num_steps=100, obs=jnp.array([1.0]))
Source code in packages/pyrox-flows/src/pyrox_flows/_guide.py
class FlowGuide(AutoContinuous):
    """NumPyro variational guide using a Gaussianization flow.

    Subclasses `numpyro.infer.autoguide.AutoContinuous`, using a
    normalizing flow as the variational distribution for SVI. The flow
    models a joint distribution over the concatenated unconstrained latent
    space of the model, so it captures cross-variable correlations because
    all latent sites are handled jointly. The flow is built lazily once
    ``latent_dim`` is known (at prototype setup), and its parameters are
    registered with NumPyro so the SVI optimiser can update them.

    Args:
        model: A NumPyro model.
        flow_factory: Callable that constructs a flowjax ``Transformed``
            distribution. Must accept ``key`` and ``n_dims`` positional /
            keyword arguments, plus any ``flow_kwargs``. Defaults to
            `gauss_flows.gaussianization_flow`.
        flow_kwargs: Extra keyword arguments forwarded to ``flow_factory``
            (e.g. ``n_layers``, ``n_components``). Defaults to ``{}``.
        init_key: JAX random key used to initialise the flow parameters.
            Defaults to ``jr.PRNGKey(0)`` when not provided.  The SVI
            optimiser will update these parameters, so the exact choice of
            seed only affects the starting point of optimisation.
        prefix: Prefix used for numpyro parameter names. Defaults to
            ``"auto"``.
        init_loc_fn: Per-site initialization strategy. Defaults to
            `numpyro.infer.initialization.init_to_uniform`.

    Examples:
        ```python
        import jax.numpy as jnp
        import jax.random as jr
        import numpyro
        import numpyro.distributions as dist
        from numpyro.infer import SVI, Trace_ELBO
        from numpyro.optim import Adam
        from pyrox_flows import FlowGuide

        def model(obs=None):
            mu = numpyro.sample("mu", dist.Normal(0.0, 1.0))
            numpyro.sample("obs", dist.Normal(mu, 1.0), obs=obs)

        guide = FlowGuide(model)
        svi = SVI(model, guide, Adam(1e-3), loss=Trace_ELBO())
        result = svi.run(jr.key(0), num_steps=100, obs=jnp.array([1.0]))
        ```
    """

    def __init__(
        self,
        model: Callable[..., Any],
        *,
        flow_factory: Callable[..., Transformed] = gaussianization_flow,
        flow_kwargs: dict[str, Any] | None = None,
        init_key: PRNGKeyArray | None = None,
        prefix: str = "auto",
        init_loc_fn: Callable[..., Any] = init_to_uniform,
    ):
        self._flow_factory = flow_factory
        self._flow_kwargs = flow_kwargs if flow_kwargs is not None else {}
        self._init_key = jr.PRNGKey(0) if init_key is None else init_key
        self._flow_init = None
        super().__init__(model, prefix=prefix, init_loc_fn=init_loc_fn)

    def _setup_prototype(self, *args, **kwargs):
        super()._setup_prototype(*args, **kwargs)
        # Build the initial flow now that latent_dim is known.
        self._flow_init = self._flow_factory(
            self._init_key, n_dims=self.latent_dim, **self._flow_kwargs
        )

    def _get_posterior(self):
        flow = register_params(f"{self.prefix}_flow", self._flow_init)
        return flow_to_numpyro(flow)