Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Inference methods

This page documents the inference methods a user calls directly, the functions of amortized and sequential inference, and the registry from which condition_on selects a method. condition_on itself is on Operations, and MinibatchedDistribution, from which the stochastic-gradient methods estimate gradients, is on Random functions. InferenceMethod, which a new method subclasses, is on Registries for extensions.

MCMC

condition_on_nutpie(model, data=None, *, num_results=1000, num_warmup=500, num_chains=4, **kwargs)

MCMC sampling via nutpie (Rust-based NUTS).

Accepts a StanModel or its posterior, bound to data when it is a kernel, or a PyMCModel at the observed values data. The run's seed is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the chains, and an unscoped call runs fresh ones.

Parameters:

Name Type Description Default
model StanModel or PyMCModel

The program to sample: a Stan program, its posterior at its data, or a PyMC model.

required
data Mapping or None

The data that bind a Stan program, or the observed values of a PyMC model.

None
num_results int

The number of draws per chain.

1000
num_warmup int

The number of tuning steps per chain.

500
num_chains int

The number of chains.

4
**kwargs Any

Further keyword arguments of nutpie.sample, such as progress_bar; its seed is the run's.

{}

Returns:

Type Description
EmpiricalDistribution

The chains of the program's parameters, with nutpie's trace as the annotations. Its inference-run provenance includes compile_seconds (preparing the compiled model, including cache lookup and data binding), sampling_seconds (the sampler call), and backend_seed. Compilations are kept in a bounded process-local cache. Stan programs without includes reuse compilation across datasets; PyMC builds reuse compilation only at unchanged bound and observed values. A surrounding condition_on call retains this run's provenance as a parent of its own provenance record.

Raises:

Type Description
ImportError

If nutpie is not installed.

TypeError

If model is neither a Stan program nor a PyMC model, or kwargs holds random_seed or seed.

Source code in probpipe/inference/_nutpie.py
@function
def condition_on_nutpie(
    model: Any,
    data: ArrayLike | None = None,
    *,
    num_results: int = 1000,
    num_warmup: int = 500,
    num_chains: int = 4,
    **kwargs: Any,
) -> EmpiricalDistribution:
    """MCMC sampling via nutpie (Rust-based NUTS).

    Accepts a :class:`~probpipe.families.StanModel` or its posterior, bound
    to *data* when it is a kernel, or a :class:`~probpipe.families.PyMCModel`
    at the observed values *data*. The run's seed is drawn from a
    workflow-owned random event, so ``workflow_run(seed=...)`` reproduces the
    chains, and an unscoped call runs fresh ones.

    Parameters
    ----------
    model : StanModel or PyMCModel
        The program to sample: a Stan program, its posterior at its data, or
        a PyMC model.
    data : Mapping or None
        The data that bind a Stan program, or the observed values of a PyMC
        model.
    num_results : int
        The number of draws per chain.
    num_warmup : int
        The number of tuning steps per chain.
    num_chains : int
        The number of chains.
    **kwargs : Any
        Further keyword arguments of ``nutpie.sample``, such as
        ``progress_bar``; its ``seed`` is the run's.

    Returns
    -------
    EmpiricalDistribution
        The chains of the program's parameters, with nutpie's trace as the
        annotations. Its inference-run provenance includes ``compile_seconds`` (preparing
        the compiled model, including cache lookup and data binding),
        ``sampling_seconds`` (the sampler call), and ``backend_seed``.
        Compilations are kept in a bounded process-local cache. Stan programs
        without includes reuse compilation across datasets; PyMC builds reuse
        compilation only at unchanged bound and observed values.
        A surrounding ``condition_on`` call retains this run's provenance as
        a parent of its own provenance record.

    Raises
    ------
    ImportError
        If nutpie is not installed.
    TypeError
        If *model* is neither a Stan program nor a PyMC model, or *kwargs*
        holds ``random_seed`` or ``seed``.
    """
    refuse_seed_keywords("condition_on_nutpie", kwargs)
    return _nutpie_posterior(
        model,
        data,
        observed_target(model, data),
        num_results=num_results,
        num_warmup=num_warmup,
        num_chains=num_chains,
        random_seed=integer_seed(_inference_run_key("nutpie_nuts")),
        **kwargs,
    )

rwmh(dist, data=None, *, log_prob_fn=None, num_results=1000, num_warmup=500, num_chains=4, step_size=0.1, adapt=True, n_windows=4, proposal_cov=None, init=None)

Gradient-free random-walk Metropolis-Hastings (BlackJAX-backed).

Two execution paths share the same BlackJAX kernel:

  • a fast path using jax.lax.scan + jax.vmap across chains, when the target log-density is JAX-traceable at the initial state;
  • an eager Python-loop fallback otherwise (BridgeStan / scipy / external-simulator likelihoods).

The run's key is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the chains, and an unscoped call runs fresh ones.

Parameters:

Name Type Description Default
dist SupportsUnnormalizedLogProb

Distribution providing _unnormalized_log_prob. RWMH uses only the unnormalized density because the missing log normalizer cancels out of every accept/reject step.

required
data array - like or None

Observed data forwarded to log_prob_fn when supplied.

None
log_prob_fn callable or None

log_prob_fn(params, data) -> float combined with dist._unnormalized_log_prob(params) to form the target.

None
num_results int

Number of draws each chain keeps.

1000
num_warmup int

Number of warmup steps each chain runs before the draws it keeps, on which adapt fits the proposal.

500
num_chains int

Number of chains, which all start at the initial state.

4
step_size float

Diagonal proposal scale used when proposal_cov=None and either adapt=False or num_warmup == 0.

0.1
adapt bool

When True (default), runs a window-style adaptive warmup: geometrically growing windows that each sample with the current proposal Cholesky and accumulate Welford statistics on positions, refitting the proposal at every window boundary (see Notes). Production samples with proposal = chol(Sigma) * 2.38 / sqrt(d), which applies the Roberts-Gelman-Gilks scaling to the last refit covariance Sigma. When False, skips adaptation and uses sigma = step_size * I throughout.

True
n_windows int

Maximum number of geometric warmup windows when adapt=True. Windows are added only while each holds at least 25 steps, so a warmup shorter than 74 steps runs as a single window: a fixed RGG-scaled identity proposal throughout, refit once at the end. Default 4; n_windows <= 1 always gives the single window. Ignored when adapt=False.

4
proposal_cov array - like or None

Explicit (d, d) proposal Cholesky factor, where d is the dimension of the chain's state, whose coordinates are unconstrained for a leaf on a constrained support. Overrides both the adaptive fit and step_size. Useful when the user has a precomputed covariance estimate from elsewhere. A wrong-shape matrix raises ValueError.

None
init array - like or None

Initial chain state. Resolved by get_init_state when None.

None

Returns:

Type Description
EmpiricalDistribution

Posterior samples with chain structure and an annotations ArviZ-shaped DataTree carrying per-step acceptance stats and warmup positions.

Raises:

Type Description
TypeError

If dist does not implement SupportsUnnormalizedLogProb.

ValueError

If proposal_cov is not a (d, d) matrix, or if init is None and no initial state can be derived from dist.

Warns:

Type Description
UserWarning

If adapt=True and num_warmup == 0 without proposal_cov. There are then no warmup positions to adapt on, so the proposal is sigma = step_size * I.

Notes

At each window boundary the adaptive warmup refits the proposal covariance as (n * Sigma_hat + 5 * Sigma_prev) / (n + 5), where Sigma_hat is the Welford covariance of the n warmup positions so far and Sigma_prev is the covariance the proposal in use assumes, which is the identity before the first refit. This is Stan's covariance regularization with Sigma_prev in place of 1e-3 * I. The refit stays positive definite when the positions have no spread, as when every proposal in a window is rejected, and when they span fewer than d directions. The proposal therefore never collapses to zero, and the correction vanishes as n grows. The growing windows downweight the early, badly mixed positions by giving later windows more steps.

Source code in probpipe/inference/_blackjax_rwmh.py
def rwmh(
    dist: SupportsUnnormalizedLogProb,
    data: ArrayLike | None = None,
    *,
    log_prob_fn: Any | None = None,
    num_results: int = 1000,
    num_warmup: int = 500,
    num_chains: int = 4,
    step_size: float = 0.1,
    adapt: bool = True,
    n_windows: int = 4,
    proposal_cov: ArrayLike | None = None,
    init: ArrayLike | None = None,
) -> EmpiricalDistribution:
    """Gradient-free random-walk Metropolis-Hastings (BlackJAX-backed).

    Two execution paths share the same BlackJAX kernel:

    * a fast path using ``jax.lax.scan`` + ``jax.vmap`` across chains,
      when the target log-density is JAX-traceable at the initial
      state;
    * an eager Python-loop fallback otherwise (BridgeStan / scipy /
      external-simulator likelihoods).

    The run's key is drawn from a workflow-owned random event, so
    ``workflow_run(seed=...)`` reproduces the chains, and an unscoped call runs
    fresh ones.

    Parameters
    ----------
    dist : SupportsUnnormalizedLogProb
        Distribution providing ``_unnormalized_log_prob``. RWMH uses
        only the unnormalized density because the missing log
        normalizer cancels out of every accept/reject step.
    data : array-like or None
        Observed data forwarded to ``log_prob_fn`` when supplied.
    log_prob_fn : callable or None
        ``log_prob_fn(params, data) -> float`` combined with
        ``dist._unnormalized_log_prob(params)`` to form the target.
    num_results : int
        Number of draws each chain keeps.
    num_warmup : int
        Number of warmup steps each chain runs before the draws it keeps,
        on which ``adapt`` fits the proposal.
    num_chains : int
        Number of chains, which all start at the initial state.
    step_size : float
        Diagonal proposal scale used when ``proposal_cov=None`` and
        either ``adapt=False`` or ``num_warmup == 0``.
    adapt : bool
        When ``True`` (default), runs a window-style adaptive warmup:
        geometrically growing windows that each sample with the current
        proposal Cholesky and accumulate Welford statistics on
        positions, refitting the proposal at every window boundary (see
        Notes). Production samples with
        ``proposal = chol(Sigma) * 2.38 / sqrt(d)``, which applies the
        Roberts-Gelman-Gilks scaling to the last refit covariance
        ``Sigma``. When ``False``, skips adaptation and uses
        ``sigma = step_size * I`` throughout.
    n_windows : int
        Maximum number of geometric warmup windows when ``adapt=True``.
        Windows are added only while each holds at least 25 steps, so a
        warmup shorter than 74 steps runs as a single window: a fixed
        RGG-scaled identity proposal throughout, refit once at the end.
        Default ``4``; ``n_windows <= 1`` always gives the single window.
        Ignored when ``adapt=False``.
    proposal_cov : array-like or None
        Explicit ``(d, d)`` proposal Cholesky factor, where ``d`` is the
        dimension of the chain's state, whose coordinates are unconstrained
        for a leaf on a constrained support. Overrides both the adaptive fit and
        ``step_size``. Useful when the user has a precomputed covariance
        estimate from elsewhere. A wrong-shape matrix raises
        ``ValueError``.
    init : array-like or None
        Initial chain state. Resolved by
        :func:`~probpipe.inference._inference_utils.get_init_state`
        when ``None``.

    Returns
    -------
    EmpiricalDistribution
        Posterior samples with chain structure and an annotations
        ArviZ-shaped ``DataTree`` carrying per-step acceptance stats
        and warmup positions.

    Raises
    ------
    TypeError
        If ``dist`` does not implement ``SupportsUnnormalizedLogProb``.
    ValueError
        If ``proposal_cov`` is not a ``(d, d)`` matrix, or if ``init`` is
        ``None`` and no initial state can be derived from ``dist``.

    Warns
    -----
    UserWarning
        If ``adapt=True`` and ``num_warmup == 0`` without ``proposal_cov``.
        There are then no warmup positions to adapt on, so the proposal is
        ``sigma = step_size * I``.

    Notes
    -----
    At each window boundary the adaptive warmup refits the proposal
    covariance as ``(n * Sigma_hat + 5 * Sigma_prev) / (n + 5)``, where
    ``Sigma_hat`` is the Welford covariance of the ``n`` warmup positions
    so far and ``Sigma_prev`` is the covariance the proposal in use
    assumes, which is the identity before the first refit. This is Stan's
    covariance regularization with ``Sigma_prev`` in place of
    ``1e-3 * I``. The refit stays positive definite when the positions
    have no spread, as when every proposal in a window is rejected, and
    when they span fewer than ``d`` directions. The proposal therefore
    never collapses to zero, and the correction vanishes as ``n`` grows.
    The growing windows downweight the early, badly mixed positions by
    giving later windows more steps.
    """
    if not isinstance(dist, SupportsUnnormalizedLogProb):
        raise TypeError(f"cannot run rwmh: {no_density_reason(dist)}")
    return _rwmh(
        _as_inference_target(dist),
        dist,
        data,
        log_prob_fn=log_prob_fn,
        num_results=num_results,
        num_warmup=num_warmup,
        num_chains=num_chains,
        step_size=step_size,
        adapt=adapt,
        n_windows=n_windows,
        proposal_cov=proposal_cov,
        init=init,
        random_seed=_inference_run_key("blackjax_rwmh"),
    )

elliptical_slice(model, data, *, num_results=1000, num_warmup=500, num_chains=4, init=None)

Elliptical slice sampling of a joint with a Gaussian prior, at observed fields.

The joint is a factored one, such as likelihood & prior. The factors that produce the observed fields are the likelihood, and the others are the prior, which must be Gaussian, as _gaussian_prior_params recognizes. The run's key is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the chains, and an unscoped call runs fresh ones.

Parameters:

Name Type Description Default
model Distribution

The factored joint, whose factors that produce no observed field form a MultivariateNormal, a Normal, or a factored joint over those.

required
data Record or Mapping[str, Any]

The observed values, keyed by the fields they bind.

required
num_results int

Number of draws each chain keeps.

1000
num_warmup int

Number of steps each chain runs before the draws it keeps.

500
num_chains int

Number of chains, which all start at the initial state.

4
init array - like or None

Initial chain state in the flat parameter vector. Defaults to a sample from the prior.

None

Returns:

Type Description
EmpiricalDistribution

Posterior samples with chain structure and an annotations ArviZ-shaped DataTree carrying per-step subiter counts (the inner shrinkage iterations BlackJAX performed before accepting the proposal).

Raises:

Type Description
TypeError

If the joint at data has no prior and likelihood factors, or the prior is not Gaussian.

Source code in probpipe/inference/_blackjax_ess.py
def elliptical_slice(
    model: Distribution,
    data: Record | Mapping[str, Any],
    *,
    num_results: int = 1000,
    num_warmup: int = 500,
    num_chains: int = 4,
    init: ArrayLike | None = None,
) -> EmpiricalDistribution:
    """Elliptical slice sampling of a joint with a Gaussian prior, at observed fields.

    The joint is a factored one, such as ``likelihood & prior``. The factors that
    produce the observed fields are the likelihood, and the others are the
    prior, which must be Gaussian, as :func:`_gaussian_prior_params` recognizes.
    The run's key is drawn from a workflow-owned random event, so
    ``workflow_run(seed=...)`` reproduces the chains, and an unscoped call runs
    fresh ones.

    Parameters
    ----------
    model : Distribution
        The factored joint, whose factors that produce no observed field form a
        ``MultivariateNormal``, a ``Normal``, or a factored joint over those.
    data : Record or Mapping[str, Any]
        The observed values, keyed by the fields they bind.
    num_results : int
        Number of draws each chain keeps.
    num_warmup : int
        Number of steps each chain runs before the draws it keeps.
    num_chains : int
        Number of chains, which all start at the initial state.
    init : array-like or None
        Initial chain state in the flat parameter vector. Defaults to
        a sample from the prior.

    Returns
    -------
    EmpiricalDistribution
        Posterior samples with chain structure and an annotations
        ArviZ-shaped ``DataTree`` carrying per-step ``subiter`` counts
        (the inner shrinkage iterations BlackJAX performed before
        accepting the proposal).

    Raises
    ------
    TypeError
        If the joint at *data* has no prior and likelihood factors, or the prior
        is not Gaussian.
    """
    return _elliptical_slice(
        observed_target(model, data),
        num_results=num_results,
        num_warmup=num_warmup,
        num_chains=num_chains,
        init=init,
        random_seed=_inference_run_key("blackjax_ess"),
    )

Amortized simulation-based inference

learn_amortized_posterior(prior, simulator, *, method='npe', num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, optimizer='adam', **fit_kwargs)

Learn an amortized conditional posterior q(theta | y) with BayesFlow.

Trains an amortized neural posterior estimator (NPE / FMPE / CMPE) from a prior and a simulator and returns the learned kernel from the observation to the parameters, whose input is observation. condition_on(result, {"observation": y}) evaluates it without retraining or MCMC and returns the law at y, each of whose draws is one forward pass of the network; the evaluation is approximate, so exact_only=True refuses it. Provenance names the prior and the simulator it was trained on.

The training's seed is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the trained network, and an unscoped call trains afresh. The seed fixes the offline simulation (jax.random) and keras's network initialization and training, which keras.utils.set_random_seed seeds. The caller's global NumPy and Python random states are restored after training, and keras's global seed generator keeps the state training leaves. Each draw of the learned posterior's law at an observation is a workflow-owned random event of its own.

Parameters:

Name Type Description Default
prior Distribution

Prior over the model parameters. Must be a numeric distribution -- typically a factored joint of named distributions, or a single named distribution for a one-parameter model. It is sampled via the sample op to draw training thetas; it is not otherwise translated. Constrained leaves (positive, an interval, a simplex, positive-definite matrices, ...) are trained in unconstrained space via the per-leaf bijector from bijector_for -- applied at the leaf's native event shape -- and mapped back to the support at sample time; real-valued leaves use the identity. Discrete priors are not supported.

required
simulator ConditionalDistribution

The kernel of one observation given the prior's fields, which claims SupportsConditionalSampling. Its given values are the prior's native per-draw sample -- a record whose fields are accessible by name (given["a"]), not a flattened vector. It must be JAX-vmappable unless sim_backend="sequential" (see below). Training uses one simulated observation per theta, fixing the conditioning shape: condition_on must be given observed data of that same flattened size (datasets of any size are the NLE/NRE learners' case).

required
method ('npe', 'fmpe', 'cmpe')

Amortized estimator: NPE (coupling flow), FMPE (flow matching), or CMPE (consistency model). NPE's coupling flow needs at least two unconstrained parameter dimensions (a one-parameter prior has one; so does a single 2-simplex), below which the NPE default falls back to a flow-matching network (still reported as method="npe"), which gives no density.

"npe"
num_simulations int

Number of (theta, y) pairs simulated offline for training.

10000
epochs int

Number of keras training passes over the simulations.

50
batch_size int

Number of simulations in each keras training batch.

128
sim_backend ('jax', 'sequential')

How the offline simulation is executed. "jax" (default) vmaps the simulator and requires it to be JAX-traceable; "sequential" runs an eager per-draw loop, supporting non-JAX simulators (numpy / external code) at the cost of speed. The names match the executors jax and sequential.

"jax"
inference_network InferenceNetwork or None

Overrides the method default (CouplingFlow / FlowMatching / ConsistencyModel). A CouplingFlow gives the posterior a density.

None
optimizer str or Optimizer

Passed to approximator.compile.

'adam'
**fit_kwargs Any

Forwarded to approximator.fit (e.g. callbacks, verbose).

{}

Returns:

Type Description
ConditionalDistribution

The amortized posterior q(theta | y), which claims SupportsApproximateConditioning and SupportsConditionalSampling, and SupportsConditionalLogProb when its network is a coupling flow. Its prior and simulator are the joint it was trained on.

Raises:

Type Description
ValueError

If method is not one of "npe" / "fmpe" / "cmpe", sim_backend is not "jax" / "sequential", any of num_simulations / batch_size / epochs is less than one, or a prior field's support is not declared or admits no smooth bijector to R^d (e.g. a discrete prior).

TypeError

If a count parameter is not an integer, simulator is not a kernel that samples, prior is not a numeric distribution, or fit_kwargs holds random_seed or seed.

ImportError

If the [bayesflow] extra is not installed.

Source code in probpipe/inference/_bayesflow_posteriors.py
@function
def learn_amortized_posterior(
    prior: Distribution,
    simulator: ConditionalDistribution,
    *,
    method: AmortizedMethod = "npe",
    num_simulations: int = 10_000,
    epochs: int = 50,
    batch_size: int = 128,
    sim_backend: SimBackend = "jax",
    inference_network: InferenceNetwork | None = None,
    optimizer: str | KerasOptimizer = "adam",
    **fit_kwargs: Any,
) -> ConditionalDistribution:
    """Learn an amortized conditional posterior ``q(theta | y)`` with BayesFlow.

    Trains an amortized neural posterior estimator (NPE / FMPE / CMPE) from a
    ``prior`` and a ``simulator`` and returns the learned kernel from the
    observation to the parameters, whose input is ``observation``.
    ``condition_on(result, {"observation": y})`` evaluates it without retraining
    or MCMC and returns the law at ``y``, each of whose draws is one forward pass
    of the network; the evaluation is approximate, so ``exact_only=True`` refuses
    it. Provenance names the prior
    and the simulator it was trained on.

    The training's seed is drawn from a workflow-owned random event, so
    ``workflow_run(seed=...)`` reproduces the trained network, and an unscoped
    call trains afresh. The seed fixes the offline simulation (``jax.random``)
    and keras's network initialization and training, which
    ``keras.utils.set_random_seed`` seeds. The caller's global NumPy and Python
    random states are restored after training, and keras's global seed
    generator keeps the state training leaves. Each draw of the learned
    posterior's law at an observation is a workflow-owned random event of its
    own.

    Parameters
    ----------
    prior : Distribution
        Prior over the model parameters.  Must be a numeric distribution --
        typically a factored joint of named distributions, or a single named
        distribution for a one-parameter model.  It is
        sampled via the :func:`~probpipe.sample` op to draw training thetas; it is
        *not* otherwise translated.  Constrained leaves (positive, an interval, a
        simplex, positive-definite matrices, ...) are trained in unconstrained space
        via the per-leaf bijector from :func:`~probpipe.bijector_for` -- applied at
        the leaf's native event shape -- and mapped back to the support at sample
        time; real-valued leaves use the identity.  Discrete priors are not supported.
    simulator : ConditionalDistribution
        The kernel of one observation given the prior's fields, which claims
        ``SupportsConditionalSampling``. Its given values are the prior's native
        per-draw sample -- a record whose fields are accessible by name
        (``given["a"]``), not a flattened vector.  It must be JAX-vmappable unless
        ``sim_backend="sequential"`` (see below). Training uses one simulated
        observation per ``theta``, fixing the conditioning shape: ``condition_on``
        must be given observed data of that same flattened size (datasets of any
        size are the NLE/NRE learners' case).
    method : {"npe", "fmpe", "cmpe"}
        Amortized estimator: NPE (coupling flow), FMPE (flow matching), or CMPE
        (consistency model). NPE's coupling flow needs at least two *unconstrained*
        parameter dimensions (a one-parameter prior has one; so does a single
        2-simplex), below which the NPE default falls back to a flow-matching
        network (still reported as ``method="npe"``), which gives no density.
    num_simulations : int
        Number of ``(theta, y)`` pairs simulated offline for training.
    epochs : int
        Number of keras training passes over the simulations.
    batch_size : int
        Number of simulations in each keras training batch.
    sim_backend : {"jax", "sequential"}
        How the offline simulation is executed. ``"jax"`` (default) vmaps the
        simulator and requires it to be JAX-traceable; ``"sequential"`` runs an
        eager per-draw loop, supporting non-JAX simulators (numpy / external
        code) at the cost of speed. The names match the executors ``jax`` and
        ``sequential``.
    inference_network : bayesflow.networks.InferenceNetwork or None
        Overrides the method default (``CouplingFlow`` / ``FlowMatching`` /
        ``ConsistencyModel``). A ``CouplingFlow`` gives the posterior a density.
    optimizer : str or keras.Optimizer
        Passed to ``approximator.compile``.
    **fit_kwargs
        Forwarded to ``approximator.fit`` (e.g. ``callbacks``, ``verbose``).

    Returns
    -------
    ConditionalDistribution
        The amortized posterior ``q(theta | y)``, which claims
        ``SupportsApproximateConditioning`` and ``SupportsConditionalSampling``,
        and ``SupportsConditionalLogProb`` when its network is a coupling flow.
        Its ``prior`` and ``simulator`` are the joint it was trained on.

    Raises
    ------
    ValueError
        If ``method`` is not one of ``"npe"`` / ``"fmpe"`` / ``"cmpe"``,
        ``sim_backend`` is not ``"jax"`` / ``"sequential"``, any of
        ``num_simulations`` / ``batch_size`` / ``epochs`` is less than one, or a prior field's support is not declared or admits no
        smooth bijector to ``R^d`` (e.g. a discrete prior).
    TypeError
        If a count parameter is not an integer, ``simulator`` is not a kernel
        that samples, ``prior`` is not a numeric distribution, or
        ``fit_kwargs`` holds ``random_seed`` or ``seed``.
    ImportError
        If the ``[bayesflow]`` extra is not installed.
    """
    if method not in _METHODS:
        raise ValueError(unknown_names("method", [method], _METHODS))
    record = _validate_learn_inputs(
        prior,
        simulator,
        caller="learn_amortized_posterior",
        sim_backend=sim_backend,
        counts=(
            ("num_simulations", num_simulations),
            ("batch_size", batch_size),
            ("epochs", epochs),
        ),
        fit_kwargs=fit_kwargs,
    )
    # Per numeric leaf (slash paths for a nested prior; == fields for a flat
    # one). supports / bijectors are leaf-keyed, so this serves both uniformly.
    leaf_shapes = record.leaf_shapes
    leaf_keys = tuple(leaf_shapes)
    # Built up front: also rejects discrete / unsupported-support priors before
    # any simulation runs.
    bijectors = _field_bijectors(prior, leaf_keys)
    # The network trains on *unconstrained* widths, which differ from the prior's
    # event sizes for dimension-shifting bijectors (a d-simplex contributes d-1).
    unconstrained_size = sum(
        int(np.prod(_unconstrained_shape(bijectors[k], leaf_shapes[k]), dtype=int))
        for k in leaf_keys
    )

    bf = _import_bayesflow()
    random_seed = integer_seed(_inference_run_key("learn_amortized_posterior"))
    with _isolated_keras_seeding(random_seed):
        key = jax.random.PRNGKey(random_seed)
        named, y = _simulate_offline(
            prior,
            simulator,
            num_simulations,
            key,
            sim_backend=sim_backend,
            bijectors=bijectors,
        )
        # Re-key theta leaves to positional internal names so user field names
        # never enter BayesFlow's key namespace (no collision with the
        # observation key or the adapter's inference_variables/conditions).
        internal_keys = _adapter_field_keys(leaf_keys)
        sims = {k: named[lk] for k, lk in zip(internal_keys, leaf_keys)}
        sims[_OBSERVATION_KEY] = y

        adapter = _build_adapter(bf, internal_keys)
        num_batches = max(1, -(-num_simulations // batch_size))  # ceil: count partial batch
        net = inference_network or _make_inference_network(
            bf, method, total_steps=epochs * num_batches, unconstrained_size=unconstrained_size
        )

        approximator = bf.ContinuousApproximator(inference_network=net, adapter=adapter)
        approximator.compile(optimizer=optimizer)
        dataset = bf.OfflineDataset(data=sims, batch_size=batch_size, adapter=adapter)
        approximator.fit(dataset=dataset, epochs=epochs, **fit_kwargs)

    return _AmortizedPosterior(
        approximator,
        prior,
        simulator,
        method=method,
        data_dim=int(y.shape[-1]),
        bijectors=bijectors,
        has_density=isinstance(net, bf.networks.CouplingFlow),
    )

learn_amortized_likelihood(prior, simulator, *, num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, dequantize=False, optimizer='adam', **fit_kwargs)

Learn an amortized likelihood p(y | theta) (NLE) with BayesFlow.

Trains a conditional coupling flow on offline (theta, y) simulations and returns a BayesFlowLikelihood, the kernel p̂(y | theta) from the prior's outputs to datasets of observation rows, with the network's jax-traceable density. condition_on(learned & prior, {"observation": y}) then runs a registered gradient-based MCMC method (BlackJAX/TFP NUTS) for datasets of any size, since per-row scores sum under conditional independence. The network conditions on the raw constrained theta.

The training's seed is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the trained network, and an unscoped call trains afresh. The seed fixes the offline simulation, the dequantization jitter, and keras's network initialization and training. The caller's global NumPy and Python random states are restored after training.

Parameters:

Name Type Description Default
prior Distribution

Prior over the model parameters; a numeric distribution whose outputs name them, which may be nested (a factored joint of named distributions). Sampled (only) to draw training thetas; constrained and discrete-valued parameter fields are both fine here, since theta is a network input (whether the downstream sampler can handle the prior is the sampler's concern).

required
simulator ConditionalDistribution

The kernel of one observation given the prior's fields, which samples; its given values are the prior's structured per-draw record (named-field access). Must be JAX-vmappable unless sim_backend="sequential".

required
num_simulations int

Number of (theta, y) pairs simulated offline for training.

10000
epochs int

Number of keras training passes over the simulations.

50
batch_size int

Number of simulations in each keras training batch.

128
sim_backend ('jax', 'sequential')

"jax" (default) vmaps the simulator; "sequential" runs an eager per-draw loop for non-JAX simulators.

"jax"
inference_network InferenceNetwork or None

Overrides the default CouplingFlow. The density must be reverse-mode differentiable for gradient-based MCMC -- adaptive-ODE networks (FlowMatching, DiffusionModel) are not (their log_prob integrates with a dynamic-bound while_loop).

None
dequantize bool

Set for integer-valued observations (counts and other ordered integer encodings; unordered categoricals would inherit a meaningless cell adjacency). Fitting a continuous flow to atoms is ill-posed -- the MLE collapses density onto the data points, which in practice shows up as overdispersed, seed-unstable posteriors as observations concentrate on few values. Uniform dequantization fixes this: training adds U[0,1)^d jitter to the simulated y (the simulator itself stays untouched and keeps emitting raw integers), making the target absolutely continuous, and the returned wrapper scores integer data at the unit-cell midpoint y + 1/2, approximating the implied pmf P(y | theta) = integral over [y, y+1)^d of p(u | theta) du. This is the fixed-q special case of variational dequantization: the cell-integral identity is exact, and the training objective is its Jensen lower bound (Theis et al., 2016, arXiv:1511.01844; Ho et al., 2019 "Flow++", arXiv:1902.00275, section 3.1). Pass raw integers as data; do not pre-jitter or pre-shift. Counts must stay below 2**23 (~8.4e6): the pipeline is float32, whose spacing reaches 1.0 there, silently rounding away the jitter and the midpoint shift (enforced on the simulated training observations). For mixed discrete/continuous rows or when a learned density is not needed, prefer learn_amortized_ratio, whose classifier consumes discrete observations natively (cf. MNLE, Boelts et al., 2022, for the mixed-data approach in the torch sbi ecosystem).

False
optimizer str or Optimizer

Passed to approximator.compile.

'adam'
**fit_kwargs Any

Forwarded to approximator.fit (e.g. callbacks, verbose).

{}

Returns:

Type Description
BayesFlowLikelihood

Raises:

Type Description
ValueError

If sim_backend is unknown, a count parameter is less than one, or the simulated observations are one-dimensional with the default network (the coupling flow needs d_y >= 2; use learn_amortized_ratio, whose classifier has no minimum, or pass a custom inference_network); with dequantize=True, also if the simulated observations reach 2**23.

TypeError

If a count parameter is not an integer, simulator is not a kernel that samples, prior is not a numeric distribution, or fit_kwargs holds random_seed or seed.

ImportError

If the [bayesflow] extra is not installed.

Source code in probpipe/inference/_bayesflow_likelihoods.py
def learn_amortized_likelihood(
    prior: Distribution,
    simulator: ConditionalDistribution,
    *,
    num_simulations: int = 10_000,
    epochs: int = 50,
    batch_size: int = 128,
    sim_backend: SimBackend = "jax",
    inference_network: InferenceNetwork | None = None,
    dequantize: bool = False,
    optimizer: str | KerasOptimizer = "adam",
    **fit_kwargs: Any,
) -> BayesFlowLikelihood:
    """Learn an amortized likelihood ``p(y | theta)`` (NLE) with BayesFlow.

    Trains a conditional coupling flow on offline ``(theta, y)`` simulations and
    returns a :class:`BayesFlowLikelihood`, the kernel ``p̂(y | theta)`` from the
    prior's outputs to datasets of observation rows, with the network's
    jax-traceable density. ``condition_on(learned & prior, {"observation": y})``
    then runs a registered gradient-based MCMC method (BlackJAX/TFP NUTS) for
    datasets of any size, since per-row scores sum under conditional
    independence. The network conditions on the raw constrained ``theta``.

    The training's seed is drawn from a workflow-owned random event, so
    ``workflow_run(seed=...)`` reproduces the trained network, and an unscoped
    call trains afresh. The seed fixes the offline simulation, the
    dequantization jitter, and keras's network initialization and training.
    The caller's global NumPy and Python random states are restored after
    training.

    Parameters
    ----------
    prior : Distribution
        Prior over the model parameters; a numeric distribution whose
        outputs name them, which may be nested (a factored joint of named
        distributions). Sampled (only) to draw training thetas;
        constrained and discrete-valued parameter fields are both fine here,
        since theta is a network *input* (whether the downstream sampler can
        handle the prior is the sampler's concern).
    simulator : ConditionalDistribution
        The kernel of one observation given the prior's fields, which samples;
        its given values are the prior's structured per-draw record (named-field
        access). Must be JAX-vmappable unless ``sim_backend="sequential"``.
    num_simulations : int
        Number of ``(theta, y)`` pairs simulated offline for training.
    epochs : int
        Number of keras training passes over the simulations.
    batch_size : int
        Number of simulations in each keras training batch.
    sim_backend : {"jax", "sequential"}
        ``"jax"`` (default) vmaps the simulator; ``"sequential"`` runs an eager
        per-draw loop for non-JAX simulators.
    inference_network : bayesflow.networks.InferenceNetwork or None
        Overrides the default ``CouplingFlow``. The density must be
        reverse-mode differentiable for gradient-based MCMC -- adaptive-ODE
        networks (``FlowMatching``, ``DiffusionModel``) are **not** (their
        ``log_prob`` integrates with a dynamic-bound ``while_loop``).
    dequantize : bool
        Set for **integer-valued observations** (counts and other *ordered*
        integer encodings; unordered categoricals would inherit a meaningless
        cell adjacency). Fitting a continuous flow to atoms is ill-posed -- the
        MLE collapses density onto the data points, which in practice shows up
        as overdispersed, seed-unstable posteriors as observations concentrate
        on few values. Uniform dequantization fixes this: training adds
        ``U[0,1)^d`` jitter to the simulated ``y`` (the simulator itself stays
        untouched and keeps emitting raw integers), making the target
        absolutely continuous, and the returned wrapper scores integer data at
        the unit-cell midpoint ``y + 1/2``, approximating the implied pmf
        ``P(y | theta) = integral over [y, y+1)^d of p(u | theta) du``. This is
        the fixed-``q`` special case of variational dequantization: the
        cell-integral identity is exact, and the training objective is its
        Jensen lower bound (Theis et al., 2016, arXiv:1511.01844; Ho et al.,
        2019 "Flow++", arXiv:1902.00275, section 3.1). Pass raw integers as
        data; do **not** pre-jitter or pre-shift. Counts must stay below
        ``2**23`` (~8.4e6): the pipeline is float32, whose spacing reaches 1.0
        there, silently rounding away the jitter and the midpoint shift
        (enforced on the simulated training observations). For
        mixed discrete/continuous rows or when a learned density is not
        needed, prefer :func:`learn_amortized_ratio`, whose classifier
        consumes discrete observations natively (cf. MNLE, Boelts et al.,
        2022, for the mixed-data approach in the torch ``sbi`` ecosystem).
    optimizer : str or keras.Optimizer
        Passed to ``approximator.compile``.
    **fit_kwargs
        Forwarded to ``approximator.fit`` (e.g. ``callbacks``, ``verbose``).

    Returns
    -------
    BayesFlowLikelihood

    Raises
    ------
    ValueError
        If ``sim_backend`` is unknown, a count parameter is less than one, or
        the simulated observations are one-dimensional with the default network
        (the coupling flow needs ``d_y >= 2``; use
        :func:`learn_amortized_ratio`, whose classifier has no minimum, or pass
        a custom ``inference_network``); with ``dequantize=True``, also if the
        simulated observations reach ``2**23``.
    TypeError
        If a count parameter is not an integer, ``simulator`` is not a kernel
        that samples, ``prior`` is not a numeric distribution, or
        ``fit_kwargs`` holds ``random_seed`` or ``seed``.
    ImportError
        If the ``[bayesflow]`` extra is not installed.
    """

    def _build(bf: Any, adapter: Any, data_dim: int) -> Any:
        if inference_network is None and data_dim < 2:
            raise ValueError(
                "the default network of learn_amortized_likelihood requires observations of "
                f"at least 2 values, but the simulator gives {data_dim}. Pass an "
                "inference_network, or use learn_amortized_ratio, which has no minimum."
            )
        net = inference_network or bf.networks.CouplingFlow()
        return bf.ContinuousApproximator(inference_network=net, adapter=adapter)

    approximator, data_dim = _train_offline(
        prior,
        simulator,
        caller="learn_amortized_likelihood",
        num_simulations=num_simulations,
        epochs=epochs,
        batch_size=batch_size,
        sim_backend=sim_backend,
        theta_role="inference_conditions",
        build_approximator=_build,
        optimizer=optimizer,
        fit_kwargs=fit_kwargs,
        dequantize=dequantize,
    )
    return BayesFlowLikelihood(
        approximator, prior, simulator, data_dim=data_dim, dequantized=dequantize
    )

BayesFlowLikelihood(approximator, prior, simulator, *, data_dim, label=None, dequantized=False)

Bases: _BayesFlowLikelihoodBase, SupportsConditionalLogProb

A learned amortized likelihood p̂(y | theta): a kernel with the network's density.

The density of a dataset at theta is sum_i log p_net(y_i | theta). The score path is pure keras-jax ops (standardize, conditional-flow log_prob, plus the standardization log-det-jacobian), so it is jax.grad-transparent and jit-stable, and gradient-based MCMC normalizes condition_on(learned & prior, {"observation": y}). Values are faithful to the public approximator.log_prob (same standardization and log-det-jacobian); the only difference is staying on-device.

With dequantized=True (set by learn_amortized_likelihood's dequantize flag), the flow was trained on uniformly jittered observations y + U[0,1)^d, and scoring shifts integer-valued data to the unit-cell midpoint -- values then equal the public log_prob evaluated at y + 1/2, a one-point approximation of the implied pmf P(y | theta) = integral over [y, y+1)^d of p(u | theta) du (Theis et al., 2016, arXiv:1511.01844). Pass raw integer-valued observations; the kernel owns the cell convention.

Parameters:

Name Type Description Default
approximator ContinuousApproximator

The trained BayesFlow approximator whose standardizer and inference network score the rows.

required
prior Distribution

The prior the estimator was trained against, whose outputs are the kernel's inputs.

required
simulator ConditionalDistribution

The training simulator.

required
data_dim int

The flattened width of one observation row the network was trained on.

required
label str

The kernel's label, BayesFlowLikelihood by default.

None
dequantized bool

Whether the flow was trained on jittered integer-valued observations, so that scoring shifts the data to the unit-cell midpoint; False by default.

False

Raises:

Type Description
TypeError

If label is neither None nor a non-empty string.

Source code in probpipe/inference/_bayesflow_likelihoods.py
def __init__(
    self,
    approximator: ContinuousApproximator,
    prior: Distribution,
    simulator: ConditionalDistribution,
    *,
    data_dim: int,
    label: str | None = None,
    dequantized: bool = False,
):
    super().__init__(
        approximator,
        prior,
        simulator,
        data_dim=data_dim,
        label=label,
    )
    object.__setattr__(self, "_dequantized", dequantized)

learn_amortized_ratio(prior, simulator, *, num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, optimizer='adam', **fit_kwargs)

Learn an amortized likelihood-to-evidence ratio (NRE) with BayesFlow.

Trains an NRE-C classifier (RatioApproximator; contrastive pairs are built internally by shuffling theta within each batch, so the training data are the same offline (theta, y) simulations as NLE) and returns a BayesFlowRatio, the kernel from the prior's outputs to datasets of observation rows whose summed per-row log-ratios are its unnormalized density: the log-likelihood up to a theta-independent constant -- valid for condition_on(learned & prior, {"observation": y}), invalid for absolute-likelihood uses (model comparison, LOO/WAIC); see the class docstring. The classifier handles discrete-valued observations and one-dimensional data natively.

The training's seed is drawn from a workflow-owned random event, so workflow_run(seed=...) reproduces the trained classifier, and an unscoped call trains afresh. The seed fixes the offline simulation and keras's network initialization and training. The caller's global NumPy and Python random states are restored after training.

Parameters:

Name Type Description Default
prior Distribution

Prior over the model parameters; a numeric distribution, possibly nested (as in learn_amortized_likelihood -- constrained and discrete-valued parameter fields are fine, theta is a network input).

required
simulator ConditionalDistribution

The kernel of one observation given the prior's fields, which samples; its given values are the prior's structured per-draw record.

required
num_simulations int

Number of (theta, y) pairs simulated offline for training.

10000
epochs int

Number of keras training passes over the simulations.

50
batch_size int

Number of simulations in each keras training batch.

128
sim_backend ('jax', 'sequential')

"jax" (default) vmaps the simulator; "sequential" runs an eager per-draw loop for non-JAX simulators.

"jax"
inference_network Layer or None

The classifier body (defaults to bayesflow.networks.MLP()); the RatioApproximator adds its own scalar projection head.

None
optimizer str or Optimizer

Passed to approximator.compile.

'adam'
**fit_kwargs Any

Forwarded to approximator.fit (e.g. callbacks, verbose).

{}

Returns:

Type Description
BayesFlowRatio

Raises:

Type Description
ValueError

If sim_backend is unknown or a count parameter is less than one (no minimum observation dimension, unlike NLE).

TypeError

If a count parameter is not an integer, simulator is not a kernel that samples, prior is not a numeric distribution, or fit_kwargs holds random_seed or seed.

ImportError

If the [bayesflow] extra is not installed.

Source code in probpipe/inference/_bayesflow_likelihoods.py
def learn_amortized_ratio(
    prior: Distribution,
    simulator: ConditionalDistribution,
    *,
    num_simulations: int = 10_000,
    epochs: int = 50,
    batch_size: int = 128,
    sim_backend: SimBackend = "jax",
    inference_network: KerasLayer | None = None,
    optimizer: str | KerasOptimizer = "adam",
    **fit_kwargs: Any,
) -> BayesFlowRatio:
    """Learn an amortized likelihood-to-evidence ratio (NRE) with BayesFlow.

    Trains an NRE-C classifier (``RatioApproximator``; contrastive pairs are
    built internally by shuffling theta within each batch, so the training data
    are the same offline ``(theta, y)`` simulations as NLE) and returns a
    :class:`BayesFlowRatio`, the kernel from the prior's outputs to datasets
    of observation rows whose summed per-row log-ratios are its unnormalized
    density: the log-likelihood **up to a theta-independent constant** -- valid
    for ``condition_on(learned & prior, {"observation": y})``, invalid for
    absolute-likelihood uses (model comparison, LOO/WAIC); see the class
    docstring. The classifier handles discrete-valued observations and
    one-dimensional data natively.

    The training's seed is drawn from a workflow-owned random event, so
    ``workflow_run(seed=...)`` reproduces the trained classifier, and an
    unscoped call trains afresh. The seed fixes the offline simulation and
    keras's network initialization and training. The caller's global NumPy and
    Python random states are restored after training.

    Parameters
    ----------
    prior : Distribution
        Prior over the model parameters; a numeric distribution, possibly
        nested (as in :func:`learn_amortized_likelihood` -- constrained and
        discrete-valued parameter fields are fine, theta is a network input).
    simulator : ConditionalDistribution
        The kernel of one observation given the prior's fields, which samples;
        its given values are the prior's structured per-draw record.
    num_simulations : int
        Number of ``(theta, y)`` pairs simulated offline for training.
    epochs : int
        Number of keras training passes over the simulations.
    batch_size : int
        Number of simulations in each keras training batch.
    sim_backend : {"jax", "sequential"}
        ``"jax"`` (default) vmaps the simulator; ``"sequential"`` runs an eager
        per-draw loop for non-JAX simulators.
    inference_network : keras.Layer or None
        The classifier body (defaults to ``bayesflow.networks.MLP()``); the
        ``RatioApproximator`` adds its own scalar projection head.
    optimizer : str or keras.Optimizer
        Passed to ``approximator.compile``.
    **fit_kwargs
        Forwarded to ``approximator.fit`` (e.g. ``callbacks``, ``verbose``).

    Returns
    -------
    BayesFlowRatio

    Raises
    ------
    ValueError
        If ``sim_backend`` is unknown or a count parameter is less than one
        (no minimum observation dimension, unlike NLE).
    TypeError
        If a count parameter is not an integer, ``simulator`` is not a kernel
        that samples, ``prior`` is not a numeric distribution, or
        ``fit_kwargs`` holds ``random_seed`` or ``seed``.
    ImportError
        If the ``[bayesflow]`` extra is not installed.
    """

    def _build(bf: Any, adapter: Any, data_dim: int) -> Any:
        net = inference_network if inference_network is not None else bf.networks.MLP()
        return bf.approximators.RatioApproximator(inference_network=net, adapter=adapter)

    approximator, data_dim = _train_offline(
        prior,
        simulator,
        caller="learn_amortized_ratio",
        num_simulations=num_simulations,
        epochs=epochs,
        batch_size=batch_size,
        sim_backend=sim_backend,
        theta_role="inference_variables",
        build_approximator=_build,
        optimizer=optimizer,
        fit_kwargs=fit_kwargs,
    )
    return BayesFlowRatio(approximator, prior, simulator, data_dim=data_dim)

BayesFlowRatio(approximator, prior, simulator, *, data_dim, label=None)

Bases: _BayesFlowLikelihoodBase, SupportsConditionalUnnormalizedLogProb

A learned likelihood-to-evidence ratio: a kernel with an unnormalized density.

The per-row scores are the NRE-C classifier logits, which converge to log[p(y_i | theta) / p(y_i)], so a dataset's score equals its joint log-likelihood up to a theta-independent constant (sum_i log p(y_i)). The kernel therefore claims SupportsConditionalUnnormalizedLogProb alone: conditioning learned & prior on an observation cancels the constant, but the values are not normalized log-likelihoods, so do not use them for model comparison, information criteria (LOO / WAIC), or any reading of absolute likelihood magnitudes.

Because the estimator is a classifier (an MLP over concat(theta, y)), it has no continuous-density machinery: it handles discrete-valued observations natively (no dequantize flag needed, and mixed discrete/continuous rows are fine) and has no minimum observation dimension -- the two cases where BayesFlowLikelihood's coupling flow needs, respectively, dequantization or a custom network.

Parameters:

Name Type Description Default
approximator RatioApproximator

The trained BayesFlow ratio approximator whose classifier scores the rows.

required
prior Distribution

The prior the estimator was trained against, whose outputs are the kernel's inputs.

required
simulator ConditionalDistribution

The training simulator.

required
data_dim int

The flattened width of one observation row the network was trained on.

required
label str

The kernel's label, BayesFlowRatio by default.

None

Raises:

Type Description
TypeError

If label is neither None nor a non-empty string.

Source code in probpipe/inference/_bayesflow_likelihoods.py
def __init__(
    self,
    approximator: RatioApproximator,
    prior: Distribution,
    simulator: ConditionalDistribution,
    *,
    data_dim: int,
    label: str | None = None,
):
    super().__init__(
        approximator,
        prior,
        simulator,
        data_dim=data_dim,
        label=label,
    )

Sequential updating

iterate(step_fn, initial, inputs, *, callback=None)

Fold a step function over inputs, returning the batch of the laws the fold visits.

Starting from initial, applies step_fn(dist, inp) for each element of inputs. The laws visited, initial first, are the elements of a DistributionBatch on one level named iterate, so they share one event spec. Each element is a view of the law the fold produced at that step, and its provenance records the batch and that law.

A step's law that has no provenance receives a record of the step, whose parent is the previous law and whose metadata holds the step's index; a law that already has provenance keeps it.

Parameters:

Name Type Description Default
step_fn callable

(Distribution, S) -> Distribution: a plain function, a Function, or a bound method.

required
initial Distribution

The starting distribution.

required
inputs Iterable[S]

Sequence of inputs to pass to the step function.

required
callback callable or None

Called as callback(i, dist) after each step, where i is the step index and dist is the newly produced distribution. If it returns exactly False, iteration stops early.

None

Returns:

Type Description
DistributionBatch

The laws [initial, dist_1, dist_2, ...] on the level iterate.

Raises:

Type Description
TypeError

If a step returns something other than a Distribution, or a law whose event spec does not match initial's.

Source code in probpipe/core/transition.py
@function
def iterate[S](
    step_fn: Callable[[Distribution, S], Distribution],
    initial: Distribution,
    inputs: Iterable[S],
    *,
    callback: Callable[[int, Distribution], Any] | None = None,
) -> DistributionBatch:
    """Fold a step function over inputs, returning the batch of the laws the fold visits.

    Starting from *initial*, applies ``step_fn(dist, inp)`` for each element
    of *inputs*. The laws visited, *initial* first, are the elements of a
    ``DistributionBatch`` on one level named ``iterate``, so they share one
    event spec. Each element is a view of the law the fold produced at
    that step, and its provenance records the batch and that law.

    A step's law that has no provenance receives a record of the step, whose
    parent is the previous law and whose metadata holds the step's index; a
    law that already has provenance keeps it.

    Parameters
    ----------
    step_fn : callable
        ``(Distribution, S) -> Distribution``: a plain function, a
        :class:`Function`, or a bound method.
    initial : Distribution
        The starting distribution.
    inputs : Iterable[S]
        Sequence of inputs to pass to the step function.
    callback : callable or None
        Called as ``callback(i, dist)`` after each step, where *i* is
        the step index and *dist* is the newly produced distribution.
        If it returns exactly ``False``, iteration stops early.

    Returns
    -------
    DistributionBatch
        The laws ``[initial, dist_1, dist_2, ...]`` on the level ``iterate``.

    Raises
    ------
    TypeError
        If a step returns something other than a ``Distribution``, or a law
        whose event spec does not match *initial*'s.
    """
    laws: list[Distribution] = [initial]
    current = initial

    for i, inp in enumerate(inputs):
        result = step_fn(current, inp)
        if not isinstance(result, Distribution):
            raise TypeError(
                f"step function must return a Distribution, got {type(result).__name__} "
                f"for the input at index {i}"
            )

        # Auto-attach provenance if not already set
        if result.provenance is None:
            # write-once guard: re-sourcing an already-sourced result raises
            with contextlib.suppress(RuntimeError):
                result.with_provenance(
                    Provenance.create(
                        "iterate",
                        parents=[current],
                        metadata={"step": i},
                    )
                )

        laws.append(result)
        current = result

        if callback is not None:
            cont = callback(i, result)
            if cont is False:
                break

    return DistributionBatch(
        laws,
        _ITERATE_LEVEL,
        label=_ITERATE_LEVEL,
    )

with_conversion(step_fn, target_type, **convert_kwargs)

Wrap a step function to convert its output after each step.

After calling step_fn, converts the resulting distribution to target_type through the converter registry, which returns a law that already satisfies the target as it is. The pre-conversion distribution is the converted distribution's provenance parent, which the registry records with the converter it selected.

This is useful when the step function produces samples (e.g., MCMC output) but the next iteration needs a parametric distribution as input.

The returned wrapper is a Function, so it appears as a node in the ProbPipe workflow DAG.

Parameters:

Name Type Description Default
step_fn callable

The underlying step function.

required
target_type type

Distribution type to convert to (e.g., MultivariateNormal). Can also be a protocol (e.g., SupportsLogProb).

required
**convert_kwargs Any

The registry's controls method and exact_only and the converter's options, passed to converter_registry.convert.

{}

Returns:

Type Description
Function

A new step function with the same call signature.

Source code in probpipe/core/transition.py
def with_conversion(
    step_fn: Callable,
    target_type: type,
    **convert_kwargs: Any,
) -> Function:
    """Wrap a step function to convert its output after each step.

    After calling *step_fn*, converts the resulting distribution to
    *target_type* through the converter registry, which returns a law that
    already satisfies the target as it is. The pre-conversion distribution
    is the converted distribution's provenance parent, which the registry
    records with the converter it selected.

    This is useful when the step function produces samples (e.g.,
    MCMC output) but the next iteration needs a parametric
    distribution as input.

    The returned wrapper is a :class:`Function`, so it appears
    as a node in the ProbPipe workflow DAG.

    Parameters
    ----------
    step_fn : callable
        The underlying step function.
    target_type : type
        Distribution type to convert to (e.g., ``MultivariateNormal``).
        Can also be a protocol (e.g., ``SupportsLogProb``).
    **convert_kwargs
        The registry's controls ``method`` and ``exact_only`` and the
        converter's options, passed to ``converter_registry.convert``.

    Returns
    -------
    Function
        A new step function with the same call signature.
    """
    inner_name = _step_fn_name(step_fn)

    def _with_conversion_impl(dist: Distribution, inp: Any) -> Distribution:
        result = step_fn(dist, inp)
        return converter_registry.convert(result, target_type, **convert_kwargs)

    return Function(
        _with_conversion_impl,
        label=f"with_conversion({inner_name}, {target_type.__name__})",
    )

with_resampling(step_fn, *, ess_threshold=0.5)

Wrap a step function to resample when particle weights degenerate.

After calling step_fn, if the result is an EmpiricalDistribution with ESS / N < ess_threshold, performs multinomial resampling to produce equally-weighted particles.

Each resampling is a workflow-owned random event, whose PRNG key derives from the seed of the enclosing workflow_run scope and from the call's position in the workflow. A run inside workflow_run(seed=...) therefore reproduces its resampled particles, and a run under another seed or outside any scope resamples afresh.

When resampling occurs, the raw result from wrapper.apply(...) carries "resample" provenance whose metadata stores the pre-resampling "ess" and "ess_ratio". A normal wrapper(...) call returns an independent Function result whose provenance describes the wrapper invocation; it does not retain that implementation-level resampling metadata.

The returned wrapper is a Function, so it appears as a node in the ProbPipe workflow DAG.

Parameters:

Name Type Description Default
step_fn callable

The underlying step function.

required
ess_threshold float

Resample when ESS / N drops below this value (default 0.5).

0.5

Returns:

Type Description
Function

A new step function with the same call signature.

Notes

This API is likely to evolve as typical use cases become clearer. A future direction is a SupportsResampling protocol that would decouple this combinator from the concrete EmpiricalDistribution type.

Source code in probpipe/core/transition.py
def with_resampling(
    step_fn: Callable,
    *,
    ess_threshold: float = 0.5,
) -> Function:
    """Wrap a step function to resample when particle weights degenerate.

    After calling *step_fn*, if the result is an
    :class:`~probpipe.EmpiricalDistribution` with
    ``ESS / N < ess_threshold``, performs multinomial resampling to
    produce equally-weighted particles.

    Each resampling is a workflow-owned random event, whose PRNG key derives
    from the seed of the enclosing ``workflow_run`` scope and from the call's
    position in the workflow. A run inside ``workflow_run(seed=...)``
    therefore reproduces its resampled particles, and a run under another
    seed or outside any scope resamples afresh.

    When resampling occurs, the raw result from
    ``wrapper.apply(...)`` carries ``"resample"`` provenance whose
    metadata stores the pre-resampling ``"ess"`` and ``"ess_ratio"``.
    A normal ``wrapper(...)`` call returns an independent Function result
    whose provenance describes the wrapper invocation; it does not retain
    that implementation-level resampling metadata.

    The returned wrapper is a :class:`Function`, so it appears
    as a node in the ProbPipe workflow DAG.

    Parameters
    ----------
    step_fn : callable
        The underlying step function.
    ess_threshold : float
        Resample when ``ESS / N`` drops below this value (default 0.5).

    Returns
    -------
    Function
        A new step function with the same call signature.

    Notes
    -----
    This API is likely to evolve as typical use cases become clearer.
    A future direction is a ``SupportsResampling`` protocol that would
    decouple this combinator from the concrete
    :class:`~probpipe.EmpiricalDistribution` type.
    """
    inner_name = _step_fn_name(step_fn)

    def _with_resampling_impl(dist: Distribution, inp: Any) -> Distribution:
        out_dist = step_fn(dist, inp)

        if isinstance(out_dist, EmpiricalDistribution):
            n = out_dist.num_atoms
            ess = float(Weights(n=n, weights=out_dist.weights).effective_sample_size)
            ess_ratio = ess / n

            if ess_ratio < ess_threshold:
                key = _evaluation_keys._resolve_automatic_key(
                    None,
                    _evaluation_keys._singleton_effect_plan(
                        operation_kind="resample",
                        execution_mode="sampled",
                        sample_shape=(n,),
                        sampling_abi=_RESAMPLE_SAMPLING_ABI,
                        provider_abi=_MULTINOMIAL_RESAMPLING_PROVIDER_ABI,
                    ),
                )
                indices = weighted_choice(key, n, weights=out_dist.weights, shape=(n,))
                # The drawn atoms, equally weighted, on the one level resampling mints.
                atoms = _batch_form(
                    out_dist.label,
                    out_dist._atoms_at(indices),
                    "resample",
                    out_dist.event_spec.term_spec,
                )
                resampled = EmpiricalDistribution(
                    atoms, label=out_dist.label, event_spec=out_dist.event_spec
                )
                resampled.with_provenance(
                    Provenance.create(
                        "resample",
                        parents=[out_dist],
                        metadata={"ess": ess, "ess_ratio": ess_ratio},
                    )
                )
                return resampled

        return out_dist

    return Function(
        _with_resampling_impl,
        label=f"with_resampling({inner_name})",
    )

The inference-method registry

inference_method_registry.list_methods() names the registered methods, and condition_on.using(method=name) runs the method of that name instead of the one the registry selects.

inference_method_registry = _InferenceMethodRegistry(name='inference', description='Inference methods for condition_on, each given an inference target.') module-attribute

The registry of the normalization stage of condition_on, whose methods each receive an inference target.

The methods of probpipe.inference register here.