jax_backend#

This module compiles pangolin models into plain-old JAX functions.

An Op and its already-computed parent values lower to either a JAX value or a LoweredDistribution. Graph-level operations combine that local interpretation with the generic traversal operations in pangolin.dag.

ir.Bijected is evaluated using its stored IR bijector. Choosing unconstrained coordinates is a separate graph transformation, not part of this backend’s lowering policy.

Graph operations#

pangolin.jax_backend.ancestor_sample(vars, key=None, size=None)[source]#

Draw ancestral samples while preserving the requested RV PyTree structure.

Parameters:
  • vars (PyTree[RV]) – PyTree of RVs to sample.

  • key (Array | None) – JAX random key, or None to generate a key automatically.

  • size (int | None) – Number of samples, or None to draw a single sample.

Returns:

out – PyTree matching vars, with JAX arrays in place of RVs. When size is provided, each array has an additional leading dimension of that size.

Return type:

PyTree[Array]

Examples

Sample a constant RV.

>>> x = RV(ir.Constant(1.5))
>>> ancestor_sample(x)
Array(1.5, dtype=float...)

Sample a PyTree with the RV inside it.

>>> ancestor_sample({'sup': [[x]]})
{'sup': [[Array(1.5, dtype=float...)]]}

Draw several samples.

>>> ancestor_sample(x, size=3)
Array([1.5, 1.5, 1.5], dtype=float...)

Draw several samples from a PyTree with an RV inside it.

>>> ancestor_sample({'sup': x}, size=3)
{'sup': Array([1.5, 1.5, 1.5], dtype=float...)}

Sample from several random variables at once.

>>> y = RV(ir.Add(), x, x)
>>> z = RV(ir.Mul(), x, y)
>>> print(ancestor_sample({'cat': x, 'dog': [y, z]}))
{'cat': Array(1.5, dtype=float...), 'dog': [Array(3., dtype=float...), Array(4.5, dtype=float...)]}
pangolin.jax_backend.ancestor_sampler(vars)[source]#

Create a keyed ancestral sampler for an RV PyTree.

Parameters:

vars (PyTree[RV]) – PyTree of RVs to sample.

Returns:

sampler – Function taking a JAX random key and returning a joint sample as a PyTree of JAX arrays matching the structure and shapes of vars.

Return type:

Callable[[Array], PyTree[Array]]

Examples

>>> x = RV(ir.Constant(1.5))
>>> y = RV(ir.Add(), x, x)
>>> fun = ancestor_sampler([{'cat': x}, y])

You now have a plain-old JAX function. You can evaluate it.

>>> key = jax.random.PRNGKey(0)
>>> fun(key)
[{'cat': Array(1.5, dtype=float...)}, Array(3., dtype=float...)]

You can do normal JAX stuff with it, e.g. vmap it.

>>> print(jax.vmap(fun)(jax.random.split(key, 3)))
[{'cat': Array([1.5, 1.5, 1.5], dtype=float...)}, Array([3., 3., 3.], dtype=float...)]
pangolin.jax_backend.ancestor_log_prob(*vars, **kwvars)[source]#

Create a joint log-probability function for a PyTree of random variables.

Parameters:
  • *vars (PyTree[RV]) – PyTrees of random RVs whose values will be supplied positionally.

  • **kwvars (PyTree[RV]) – PyTrees of random RVs whose values will be supplied by keyword. Together with vars, these must include every upstream random RV.

Returns:

log_prob – Function accepting values matching the positional and keyword RV PyTrees and returning their scalar joint log probability as a JAX array.

Return type:

Callable[…, ArrayLike]

Examples

>>> loc = ir.RV(ir.Constant(0.0))
>>> scale = ir.RV(ir.Constant(1.0))
>>> x = RV(ir.Normal(), loc, scale)
>>> fun = ancestor_log_prob(x)

You now have a plain JAX function. You can evaluate it.

>>> fun(0.0)
Array(-0.9189385..., dtype=float...)

Or you can vmap it.

>>> jax.vmap(fun)(jnp.array([0.0, 0.5]))
Array([-0.9189385..., -1.0439385...], dtype=float...)

Here’s a more complex example:

>>> op = ir.VMap(ir.Normal(), [None, None], 3)
>>> y = RV(op, loc, scale)
>>> fun = ancestor_log_prob({'x': x, 'y': y})
>>> fun({'x': 0.0, 'y': [0.0, 0.5, 0.1]})
Array(-3.805..., dtype=float...)

You can also create a function that uses positional and/or keyword arguments:

>>> fun = ancestor_log_prob(x, cat=y)
>>> fun(0.0, cat=[0.0, 0.5, 0.1])
Array(-3.805..., dtype=float...)
pangolin.jax_backend.fill_in(random_vars, random_values, desired_vars, key=None)[source]#

Compute desired values from supplied random values, optionally sampling missing ones.

Parameters:
  • random_vars (Sequence[RV])

  • random_values (Sequence[TypeAliasForwardRef('ArrayLike')])

  • desired_vars (Sequence[RV])

  • key (Array | None)

Return type:

list[Array]

Op lowering#

pangolin.jax_backend.lower(op, parent_values)[source]#

Bind an Op to its parent values as a JAX value or distribution.

Parameters:
  • op (Op)

  • parent_values (Sequence[TypeAliasForwardRef('ArrayLike')])

Return type:

LoweringResult

class pangolin.jax_backend.LoweredDistribution(sample, log_prob)[source]#

A bound JAX distribution represented by sampling and log-density functions.

Parameters:
  • sample (Callable[[Array], Array])

  • log_prob (Callable[[Array], Array])

sample(key)[source]#

Draw one sample using a JAX PRNG key.

Parameters:

key (Array)

Return type:

Array

log_prob(value)[source]#

Evaluate the log density or mass at a value.

Parameters:

value (ArrayLike)

Return type:

Array

pangolin.jax_backend.lower_transformed(op, parent_values)[source]#

Lower a transformed distribution using its base distribution and IR bijector.

Sampling applies the forward map. Log density applies the inverse and the change-of-variables formula. Bijections operate between open domains: evaluation at endpoints or outside the inverse’s domain is not guaranteed. Neither operation uses sign.

Parameters:
  • op (Bijected)

  • parent_values (tuple[Array, ...])

Return type:

LoweredDistribution

pangolin.jax_backend.lower_quantile(op, parent_values)[source]#

Evaluate a scalar quantile with all distribution parameters fixed.

Primitive distributions use NumPyro’s inverse CDF: Normal, NormalPrec, Cauchy, Exponential, Lognormal, and Uniform are supported. Beta, Gamma, and StudentT quantiles are unsupported. Discrete distributions are currently unsupported by this backend, although the IR permits their quantiles; they raise NotImplementedError.

Composite evaluates its deterministic intermediates. Scalar Bijected uses its bijector’s sign and forward operation, reversing the probability for decreasing bijections. Truncated rescales the probability to the retained base-CDF interval. These rules compose recursively. Quantiles of array-valued distributions are rejected by the IR; use VMap around Quantile for independent evaluations. Other base Ops raise NotImplementedError.

Probabilities outside [0, 1] return NaN, including under JIT. At zero and one, primitive quantiles use support endpoints. Bijections need not handle endpoint limits: transformed quantiles are guaranteed only for probabilities strictly between zero and one.

Parameters:
  • op (Quantile)

  • parent_values (tuple[Array, ...])

Return type:

Array

pangolin.jax_backend.lower_truncated(op, parent_values)[source]#

Lower a continuous scalar distribution restricted by optional interior bounds.

Each supplied bound must be finite and strictly inside the base distribution’s interval. Log density subtracts the log retained probability; sampling evaluates the base Quantile at a uniform probability between the bound CDFs. Composite, Bijected, and nested Truncated bases use these same rules recursively. Each nested truncation validates its own bounds.

Sampling requires Quantile support; log density requires only the base CDF and density. With neither bound supplied, delegate to the base without requiring either CDF or Quantile. Unsupported operations raise NotImplementedError.

Invalid bounds produce NaN samples and log densities, including under JIT. Density is zero outside the retained interval. Direct CDF subtraction can lose precision in extreme tails or narrow intervals; rounded endpoint probabilities are rejected as non-interior. No specialized tail-stable normalization or sampler is provided.

Parameters:
  • op (Truncated)

  • parent_values (tuple[Array, ...])

Return type:

LoweredDistribution