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
|
Returns:
| Type | Description |
|---|---|
Distribution
|
A NumPyro distribution with |
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
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. Theevent_shapeis read fromdist.event_shapeandcond_shapeisNone. The numpyro distribution must havebatch_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 (otherwisebatch_shapewill be non-trivial and this wrapper will reject it). - Conditional (
dist_factory=...): a callablecondition -> numpyro.distributions.Distributioninvoked per call. The user must supplyevent_shapeandcond_shapebecause the factory is not run at construction time. Each invocation is responsible for returning a distribution with matchingevent_shapeandbatch_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 |
None
|
dist_factory
|
Callable[[Array], Distribution] | None
|
A callable mapping a condition array to a numpyro
distribution. Mutually exclusive with |
None
|
event_shape
|
tuple[int, ...] | None
|
Required when using |
None
|
cond_shape
|
tuple[int, ...] | None
|
Required when using |
None
|
Shape
- Condition:
cond_shape(Noneif 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
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
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 |
gaussianization_flow
|
flow_kwargs
|
dict[str, Any] | None
|
Extra keyword arguments forwarded to |
None
|
init_key
|
PRNGKeyArray | None
|
JAX random key used to initialise the flow parameters.
Defaults to |
None
|
prefix
|
str
|
Prefix used for numpyro parameter names. Defaults to
|
'auto'
|
init_loc_fn
|
Callable[..., Any]
|
Per-site initialization strategy. Defaults to
|
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]))