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.

Registries for extensions

An extension implements a base class or a protocol of ProbPipe and registers an instance with a registry, and this page states, for each kind of extension, what to implement and where to register it. It also documents the dispatch registries, the operation registry, and the base classes these extensions implement, and its last section documents the registry catalog. The registries that users query are documented on the pages of their topics: inference_method_registry on Inference methods and converter_registry on Conversion.

A new family

A family subclasses Distribution, or ConditionalDistribution for a kernel, and passes its label and the event spec of one draw to the base constructor as label and event_spec. A draw that is one whole term is declared by an OutputSpec whose one keyword names its output, such as OutputSpec(y=NumericArraySpec((22,))). A family's constructor takes the output's name as its first argument and the label as the optional keyword label=, which defaults to the class name. So Normal("mu", 0.0, 1.0) is labeled Normal, and Normal("mu", 0.0, 1.0, label="prior") is labeled prior. A family over a TensorFlow Probability distribution subclasses TFPDistribution, which samples and scores through the backend distribution. A family claims a capability by defining its implementation method, such as _sample for SupportsSampling or _mean for SupportsMean, and claims a conditioning capability by inheriting SupportsExactConditioning or SupportsApproximateConditioning. A kernel's conditional methods, such as _conditional_sample, must be pure, since a joint compiles them when it maps the kernel over draws, as ConditionalDistribution states. Distributions and families documents the base classes and each capability.

A family registers with no registry, since an operation selects a capability route by the protocols the family claims. A family that stores its laws at batched parameters in one backend object implements SupportsArrayBackend.

SupportsArrayBackend

Bases: Protocol

A distribution class that stores its laws at batched parameters in one backend.

Implementations construct an internal _DistributionArrayBackend that owns the batched parameters and computes the laws' capabilities vectorized. A class that does not implement the protocol stores one Distribution per position instead.

The protocol attaches to the class, not to its instances: the runtime check is isinstance(MyDistribution, SupportsArrayBackend), which holds when the class implements _make_array_backend. An instance passes the check too, since it inherits the class's attributes, but the contract is the class's. The protocol is internal to the library, and user code never calls _make_array_backend.

Examples:

A distribution class declares the capability by implementing the classmethod::

class MyDistribution(Distribution):
    @classmethod
    def _make_array_backend(
        cls,
        *,
        output_name: str,
        batch_shape: tuple[int, ...],
        **batched_params,
    ) -> _DistributionArrayBackend:
        return _MyArrayBackend(
            cls=cls, output_name=output_name, batch_shape=batch_shape,
            **batched_params,
        )

A new inference method

An inference method normalizes the target that condition_on forms when no exact route conditions a law, and it returns a normalized law over the target's event. It subclasses InferenceMethod, declares name and supported_types, implements check and execute, and registers with inference_method_registry.register.

A method reads the model through its target, which is an InferenceTarget. It reads the model as target.joint and the observed values as target.given, and target.factors() gives a merged model's prior and likelihood. Every target is an InferenceTarget, so a method's supported_types admits Distribution, and a method that runs one kind of model, such as a Stan program, recognizes it in check through target.joint. A target is a law, so a method reads its density with unnormalized_log_prob(target, value), which applies when the model has a density; a method that requires one states SupportsUnnormalizedLogProb in its check, and a method that simulates reads target.factors() instead. A method that works on vectors uses the to_vector layout of the event's values: NumericRecord.from_vector(target.event_spec.term_spec, vec, label=...) reads a vector as a value of the parameters. execute also receives the run's random key as the keyword key, which condition_on derives from the enclosing workflow_run, so a seed reproduces the run; a method draws all of its randomness from that key. make_posterior turns chains of such vectors into the posterior the method returns.

This method draws vectors from a normal proposal and weights each by the target's density over the proposal's:

import jax
import jax.numpy as jnp
from jax.scipy.stats import norm

from probpipe import (
    Distribution,
    NumericRecord,
    NumericRecordSpec,
    SupportsUnnormalizedLogProb,
    inference_method_registry,
    unnormalized_log_prob,
)
from probpipe.inference import Feasibility, InferenceMethod, InferenceTarget, make_posterior


class ImportanceSampling(InferenceMethod):
    _method_options = ("num_draws", "proposal_scale")  # the method_options entries execute reads

    @property
    def name(self) -> str:
        return "my_importance_sampling"

    @property
    def description(self) -> str:  # one line, which the registry catalog shows
        return "Self-normalized importance sampling from a normal proposal."

    def supported_types(self) -> tuple[type, ...]:
        return (Distribution,)

    def check(self, target: InferenceTarget, /, **options) -> Feasibility:
        if not isinstance(target, SupportsUnnormalizedLogProb):
            return Feasibility(False, "the target has no unnormalized density")
        if not isinstance(target.event_spec.term_spec, NumericRecordSpec):
            return Feasibility(False, "the parameters must be a record of numeric arrays")
        return Feasibility(True)

    def execute(self, target: InferenceTarget, /, *, key, **options) -> Distribution:
        self._check_options(options)
        num_draws = options.get("num_draws", 2000)
        scale = options.get("proposal_scale", 2.0)
        spec = target.event_spec.term_spec
        vectors = scale * jax.random.normal(key, (num_draws, spec.vector_size))

        def log_density(vec):  # a JAX array, so jax.vmap and jax.grad apply
            value = NumericRecord.from_vector(spec, vec, label="theta")
            return jnp.asarray(unnormalized_log_prob(target, value))

        log_proposal = jnp.sum(norm.logpdf(vectors, 0.0, scale), axis=-1)
        log_weights = jax.vmap(log_density)(vectors) - log_proposal
        return make_posterior(
            target, [vectors], method=self.name, weights=jax.nn.softmax(log_weights)
        )


inference_method_registry.register(ImportanceSampling())

condition_on.using(method="my_importance_sampling") runs the method by name, and one seed gives the same draws:

from probpipe import Normal, NumericArraySpec, condition_on, conditional_distribution, mean, workflow_run

likelihood = conditional_distribution(
    lambda mu: Normal("y", mu * jnp.ones(3), 1.0), given_spec={"mu": NumericArraySpec(())}
)
model = (likelihood & Normal("mu", 0.0, 1.0))
observed = {"y": jnp.array([0.4, 0.9, -0.1])}

with workflow_run(seed=0):
    posterior = condition_on.using(method="my_importance_sampling")(model, observed)
with workflow_run(seed=0):
    again = condition_on.using(method="my_importance_sampling")(model, observed)

assert (posterior.atoms.raw["mu"] == again.atoms.raw["mu"]).all()
print(mean(posterior))  # mu is near 0.3, the exact posterior mean

The method takes part in automatic selection once it overrides priority.

Exactness and priority

A method declares its exactness and its priority, and the two are independent:

  1. exact: whether the result denotes the conditional law itself. InferenceMethod declares exact = False, the declaration of a finite MCMC, variational, or ABC output, which stands in for the conditional law. A method whose result is the conditional law overrides it, as empirical_reweighting does: the posterior of an empirical prior is its atoms reweighted by the likelihood. The exact_only control excludes the approximate methods.
  2. priority: the rank, which Dispatch registries defines with its default, None.

A new method takes its rank relative to the nearest of the ranks of the built-in methods:

Method Priority
empirical_reweighting (exact) 100
nutpie_nuts 88
blackjax_nuts 85
cmdstan_nuts, pymc_nuts 82
blackjax_elliptical_slice 75
blackjax_rwmh 55
blackjax_sgld 45
pyabc_smcabc 6

Five criteria, in decreasing weight, place a new approximate method among these ranks:

  1. Robustness: how often the method gives a usable answer without tuning for the model, once its check passes.
  2. Cost: the computation per effective draw or per converged result, whether a method saves it by exploiting the model's structure or by a faster backend.
  3. Approximation quality: an approximation with a controlled error ranks above an asymptotically exact MCMC method, which ranks above an approximation whose error does not vanish with more computation.
  4. Diagnostics: a method that reports its failures ranks above one that fails without a signal.
  5. Breadth: the range of models the method applies to, which breaks ties only, since check decides which methods apply.

probpipe.inference.InferenceMethod

Bases: UnaryDispatchMethod

Base class for registered inference methods; exact is False unless a method overrides it.

A method normalizes the target of condition_on's normalization stage: it takes the target, an InferenceTarget whose data are already bound, and returns a normalized law over the target's event. A subclass declares name, supported_types, check, and execute, and overrides priority to take part in automatic selection. Its check reads the interface it requires of the target, such as an unnormalized density, a backend program, or the prior and likelihood to simulate from.

A method validates the method_options entries it receives when it runs: a subclass names the entries its execute reads in _method_options and calls _check_options before it computes anything. No method reads a seed among them: execute receives the run's random key.

Notes

A method is exact when its result is the conditional law itself, as the reweighted atoms of an empirical prior are, and such a method overrides exact. A finite MCMC, SG-MCMC, slice, ABC, or variational output stands in for the conditional law, whatever its invariant target or asymptotic guarantee, so such a method keeps exact = False; those guarantees are the method's own documentation.

execute(target, /, *, key, **options) abstractmethod

Normalize target: return a normalized law over its event.

condition_on calls it once per run of the method, after check admitted the target, with a random key it derives for that run from the enclosing workflow_run, so workflow_run(seed=...) reproduces the run and two runs in one workflow draw differently. A method draws all of its randomness from key, splitting it as it needs, and none from a global random generator; a method that draws nothing ignores it. Code that calls a method directly passes a key of its own choice.

Parameters:

Name Type Description Default
target InferenceTarget

The law to normalize: a model's parameters at its observed values.

required
key PRNGKey

The run's random key.

required
**options Any

The call's method_options, which the method validates with _check_options.

{}

Returns:

Type Description
Distribution

A normalized law over target.event_spec, usually built with make_posterior.

Source code in probpipe/operations/_condition.py
@abstractmethod
def execute(self, target: InferenceTarget, /, *, key: PRNGKey, **options: Any) -> Distribution:
    """Normalize *target*: return a normalized law over its event.

    ``condition_on`` calls it once per run of the method, after ``check``
    admitted the target, with a random key it derives for that run from
    the enclosing ``workflow_run``, so ``workflow_run(seed=...)`` reproduces
    the run and two runs in one workflow draw differently. A method draws
    all of its randomness from *key*, splitting it as it needs, and none
    from a global random generator; a method that draws nothing ignores
    it. Code that calls a method directly passes a key of its own choice.

    Parameters
    ----------
    target : InferenceTarget
        The law to normalize: a model's parameters at its observed values.
    key : PRNGKey
        The run's random key.
    **options : Any
        The call's ``method_options``, which the method validates with
        :meth:`_check_options`.

    Returns
    -------
    Distribution
        A normalized law over ``target.event_spec``, usually built with
        :func:`~probpipe.inference.make_posterior`.
    """
    ...

probpipe.inference.InferenceTarget

Bases: Protocol

The law an inference method normalizes: a model's parameters at its observed values.

condition_on hands every inference method one target. The target is the law of the quantities left unobserved, called the parameters below, and its unnormalized log-density at a value of the parameters is the model's joint log-density at that value and the observed values. A method returns a normalized law over the target's event, usually through make_posterior.

The observed values take one of three forms, which given holds:

  1. Values of the model's fields. condition_on(model, {"y": y}) gives a target whose given is a Record keyed by the fields it fixes, and whose event is the model's other fields.
  2. Data the model takes but does not declare as fields, such as the data block of a program. given is that data, as the model takes it.
  3. Nothing. A law that is itself unnormalized, such as one built from a log-density alone, is the target of conditioning on nothing. given is an empty Record, and joint is that law.

A target is a law: it has the event spec, the label, and the capabilities of a Distribution. It has an unnormalized density, read through unnormalized_log_prob, exactly when the model has one, so a method states the capabilities it needs in its check: a method that evaluates a density requires SupportsUnnormalizedLogProb, and one that simulates reads factors.

A method that works on vectors uses the to_vector layout of the event's values: NumericRecord.from_vector(target.event_spec.term_spec, vec, label=...) reads a vector as a value of the parameters, and the chains make_posterior takes hold the to_vector coordinates of draws.

A target is immutable: a method reads it and never changes it.

Examples:

A method that weights draws of the prior by the likelihood reads the target's factors, and one that runs a chain evaluates its density at a vector::

factors = target.factors()          # None when the model has no prior and likelihood
spec = target.event_spec.term_spec  # a NumericRecordSpec, whose vector_size is d
value = NumericRecord.from_vector(spec, vec, label="theta")
unnormalized_log_prob(target, value)

label property

The target's label, which is the model's.

event_spec property

The output spec of one value of the parameters: the event of the law a method returns.

joint property

The model: the joint law of the parameters and the observed quantities.

given property

The observed values: a Record of fields, the data a model takes, or an empty Record.

factors()

The model's prior, likelihood, and observed value, or None when it has none.

A model has them when it is a merge of factors, such as likelihood & prior, conditioned on every field the likelihood factors produce and on no field of the prior factors.

Returns:

Type Description
ModelFactors or None

The prior, the likelihood, and the observed value of the likelihood's event; None for any other model.

Source code in probpipe/operations/_inference_target.py
def factors(self) -> ModelFactors | None:
    """The model's prior, likelihood, and observed value, or ``None`` when it has none.

    A model has them when it is a merge of factors, such as
    ``likelihood & prior``, conditioned on every field the likelihood
    factors produce and on no field of the prior factors.

    Returns
    -------
    ModelFactors or None
        The prior, the likelihood, and the observed value of the
        likelihood's event; ``None`` for any other model.
    """
    ...

probpipe.inference.ModelFactors

Bases: NamedTuple

The prior and the likelihood of a model, and the observed value of the likelihood's event.

InferenceTarget.factors returns it for a model merged from factors, such as likelihood & prior, conditioned on the fields its likelihood produces.

Attributes:

Name Type Description
prior Distribution

The law of the parameters: the merge of the factors that produce no observed field.

likelihood Distribution or ConditionalDistribution

The law of the observed fields given the parameters: the merge of the factors that produce them, a kernel whose inputs are fields of the prior, or a law when it reads none.

observed Any

The observed value of the likelihood's event.

probpipe.inference.make_posterior(target, chains, *, method, annotations=None, parameter_shapes=None, weights=None, label='posterior', **meta)

The posterior an inference method returns: the empirical law of its draws of the target's parameters.

The result is an EmpiricalDistribution labeled label, whose atoms are the draws on the levels chain and draw, labeled by the target's outputs, as beta or (K, r, phi). Its event spec is the target's, so a record of parameters keeps its fields' supports, shapes, and nested groups. Each chain holds the to_vector coordinates of draws of the target's event, which the result reads back as draws of the parameters. Its provenance names the method, with the target as its parent, or the law itself for the target of conditioning a law on nothing. Its annotations are a DataTree whose root attribute method is method, and which stores the method's diagnostics, sample statistics, and warmup draws as ArviZ-compatible groups under arviz/.

Parameters:

Name Type Description Default
target InferenceTarget

The target the method ran on.

required
chains list of Array

Per-chain draws, each of shape (num_draws, vector_size): row i is to_vector() of draw i of the target's event. The chains have equal lengths.

required
method str

The inference method's name, by which the method control selects it, such as "tfp_nuts" or "blackjax_rwmh".

required
annotations DataTree or None

The method's diagnostics, sample statistics, and warmup draws, as ArviZ groups of a DataTree, such as sample_stats. A posterior or warmup group whose one variable params holds vectors of shape (chains, draws, vector_size) is stored with one variable per leaf of the result, named by its path with . between the parts, since a DataTree variable has no / in its name.

None
parameter_shapes Mapping of str to tuple of int, or None

The shape of each parameter as the run fixed it, by output, for a target whose event leaves shapes for a program to fix when it runs, such as a Stan model whose array sizes come from its data. It names every output of the target and nothing else, and each parameter keeps the dtype and the support the target declares.

None
weights array-like, :class:`~probpipe.Weights`, or None

Per-draw importance weights across all chains in chain order, as SMC-ABC returns them.

None
label str

The result's label.

'posterior'
**meta Any

Further metadata recorded in the provenance.

{}

Returns:

Type Description
EmpiricalDistribution

The posterior, with its atoms on the levels chain and draw, labeled by its outputs.

Raises:

Type Description
ValueError

If chains is empty or the chains differ in length, a draw's width is not the vector_size of the target's event, or parameter_shapes misses an output of the target or names one it does not have.

TypeError

If the target's event has a leaf that is not a numeric array, or parameter_shapes is given for a target whose event is not a record.

Examples:

A method that draws vectors of the target's parameters returns them as a posterior::

chain = jnp.stack(vectors)                       # (num_draws, vector_size)
return make_posterior(target, [chain], method="my_method")
Source code in probpipe/inference/_approximate_distribution.py
def make_posterior(
    target: InferenceTarget,
    chains: list[Array],
    *,
    method: str,
    annotations: DataTree | None = None,
    parameter_shapes: Mapping[str, tuple[int, ...]] | None = None,
    weights: ArrayLike | Weights | None = None,
    label: str = "posterior",
    **meta: Any,
) -> EmpiricalDistribution:
    """The posterior an inference method returns: the empirical law of its draws of the target's parameters.

    The result is an :class:`~probpipe.EmpiricalDistribution` labeled *label*,
    whose atoms are the draws on the levels ``chain`` and ``draw``, labeled by
    the target's outputs, as ``beta`` or ``(K, r, phi)``. Its event spec is
    the target's, so a record of parameters keeps its fields' supports, shapes,
    and nested groups. Each chain holds the ``to_vector`` coordinates of draws
    of the target's event, which the result reads back as draws of the
    parameters. Its provenance names the method, with the target as its
    parent, or the law itself for the target of conditioning a law on nothing. Its annotations are a ``DataTree`` whose root
    attribute ``method`` is *method*, and which stores the method's
    diagnostics, sample statistics, and warmup draws as ArviZ-compatible
    groups under ``arviz/``.

    Parameters
    ----------
    target : InferenceTarget
        The target the method ran on.
    chains : list of Array
        Per-chain draws, each of shape ``(num_draws, vector_size)``: row ``i``
        is ``to_vector()`` of draw ``i`` of the target's event. The chains have
        equal lengths.
    method : str
        The inference method's name, by which the ``method`` control selects it,
        such as ``"tfp_nuts"`` or ``"blackjax_rwmh"``.
    annotations : DataTree or None
        The method's diagnostics, sample statistics, and warmup draws, as
        ArviZ groups of a ``DataTree``, such as ``sample_stats``. A
        ``posterior`` or ``warmup`` group whose one variable ``params`` holds
        vectors of shape ``(chains, draws, vector_size)`` is stored with one
        variable per leaf of the result, named by its path with ``.`` between
        the parts, since a ``DataTree`` variable has no ``/`` in its name.
    parameter_shapes : Mapping of str to tuple of int, or None
        The shape of each parameter as the run fixed it, by output, for a
        target whose event leaves shapes for a program to fix when it runs,
        such as a Stan model whose array sizes come from its data. It names
        every output of the target and nothing else, and each parameter keeps
        the dtype and the support the target declares.
    weights : array-like, :class:`~probpipe.Weights`, or None
        Per-draw importance weights across all chains in chain order, as SMC-ABC
        returns them.
    label : str
        The result's label.
    **meta
        Further metadata recorded in the provenance.

    Returns
    -------
    EmpiricalDistribution
        The posterior, with its atoms on the levels ``chain`` and ``draw``,
        labeled by its outputs.

    Raises
    ------
    ValueError
        If *chains* is empty or the chains differ in length, a draw's width is
        not the ``vector_size`` of the target's event, or *parameter_shapes* misses an output of
        the target or names one it does not have.
    TypeError
        If the target's event has a leaf that is not a numeric array, or
        *parameter_shapes* is given for a target whose event is not a record.

    Examples
    --------
    A method that draws vectors of the target's parameters returns them as a
    posterior::

        chain = jnp.stack(vectors)                       # (num_draws, vector_size)
        return make_posterior(target, [chain], method="my_method")
    """
    return _posterior_from_chains(
        chains,
        (target,),
        method,
        annotations=annotations,
        event_spec=_target_event_spec(target, parameter_shapes),
        weights=weights,
        label=label,
        **meta,
    )

A new converter

A converter moves a law to another representation. It subclasses Converter and defines five members:

  1. name: the name by which a call selects the converter;
  2. exact: whether the converted law is the source law in another representation;
  3. supported_types: the pair of the source types and the target types;
  4. check: the promise of a conversion as a ConversionInfo, computed without converting, which leaves method_name and exact for the registry to set from the registration;
  5. execute: the converted law, which carries the source's event spec.

check and execute receive a call's converter options as keywords, such as num_samples, and a converter's execute must raise TypeError for an option it does not read. converter_registry.register registers an instance, and convert and with_conversion then select among the registered converters. The shipped converters have priorities from 10 to 20, and a new converter sets its priority to take part in automatic selection.

Converter

Bases: BinaryDispatchMethod

A binary dispatch method that converts a law to a requested representation.

A subclass declares name, exact, and the (source, target) types it supports, and implements a non-executing check and an execute. A target type is a distribution class or a capability protocol, and both methods receive the target the caller requested, which may be a base of a declared target. The registry passes the caller's converter options to both as keywords; a converter reads the options it names, and its execute refuses any other.

supported_types() abstractmethod

The source types this converter reads and the target types it produces.

Source code in probpipe/distributions/_conversion.py
@abstractmethod
def supported_types(self) -> tuple[tuple[type, ...], tuple[type, ...]]:
    """The source types this converter reads and the target types it produces."""

check(source, target_type, **options) abstractmethod

Promise the conversion of source to target_type without executing it.

It never samples, fits, or evaluates a density, and it reports as pending whatever it cannot settle without the source's values. The report states the promise and claims_random_events and leaves method_name and exact unset, which the registry sets from the registration.

Source code in probpipe/distributions/_conversion.py
@abstractmethod
def check(self, source: Any, target_type: type, **options: Any) -> ConversionInfo:
    """Promise the conversion of *source* to *target_type* without executing it.

    It never samples, fits, or evaluates a density, and it reports as
    pending whatever it cannot settle without the source's values. The
    report states the promise and ``claims_random_events`` and leaves
    ``method_name`` and ``exact`` unset, which the registry sets from the
    registration.
    """

execute(source, target_type, **options) abstractmethod

Construct the converted law, carrying source's event spec.

Source code in probpipe/distributions/_conversion.py
@abstractmethod
def execute(self, source: Any, target_type: type, **options: Any) -> Distribution:
    """Construct the converted law, carrying *source*'s event spec."""

A new operation or route

@operation declares an operation from its signature and its result rule, and it registers the operation with operation_registry. An operation registers its routes after construction, with register_route for any object that has the members of OperationRoute, or with one of four helpers:

  1. structural_route: an implementation that reads the operands' declared structure;
  2. capability_route: a call of a capability that one operand claims, such as _mean;
  3. registry_route: a delegation to a dispatch registry, whose selected method realizes the call;
  4. fallback_route: a generic scheme for a stated domain, which ranks below every other route of its exactness.

operation_registry.describe("mean") prints the operands and the routes of mean in selection order.

probpipe.operations.operation(*, result, applicability_checks=(), roles=None, derived_route_check=None, derived_route=None, label=None, registry=None)

Declare an operation from its signature and register it.

The decorated function's signature contains the operands and the parameters the result rule reads; an empty body declares a primitive operation and a body that returns an expression states a derived operation's formula. The routes are registered on the returned operation.

Parameters:

Name Type Description Default
result callable

The result rule; see Operation.

required
applicability_checks iterable of callable

Checks that the operation applies to a call; see Operation.

()
roles mapping of str to iterable of TermSpec subclasses

Roles that override the kinds the annotations name.

None
derived_route_check callable

The derived route's feasibility check; see Operation.

None
derived_route OperationRoute

A derived operation's composite derived route; see Operation.

None
label callable

The label rule; see Operation.

None
registry OperationRegistry

The registry to register in; operation_registry by default.

None

Returns:

Type Description
callable

The decorator, which returns the registered Operation.

Raises:

Type Description
TypeError

As Operation and OperationRegistry.register raise.

ValueError

If the registry already has an operation of that name.

Source code in probpipe/operations/_operation.py
def operation(
    *,
    result: Callable[..., OutputSpec | None],
    applicability_checks: Iterable[Callable[..., Any]] = (),
    roles: Mapping[str, Iterable[type[TermSpec]]] | None = None,
    derived_route_check: Callable[..., Any] | None = None,
    derived_route: OperationRoute | None = None,
    label: Callable[..., str] | None = None,
    registry: OperationRegistry | None = None,
) -> Callable[[Callable[..., Any]], Operation]:
    """Declare an operation from its signature and register it.

    The decorated function's signature contains the operands and the parameters
    the result rule reads; an empty body declares a primitive operation and a
    body that returns an expression states a derived operation's formula. The
    routes are registered on the returned operation.

    Parameters
    ----------
    result : callable
        The result rule; see :class:`Operation`.
    applicability_checks : iterable of callable
        Checks that the operation applies to a call; see :class:`Operation`.
    roles : mapping of str to iterable of TermSpec subclasses, optional
        Roles that override the kinds the annotations name.
    derived_route_check : callable, optional
        The derived route's feasibility check; see :class:`Operation`.
    derived_route : OperationRoute, optional
        A derived operation's composite derived route; see :class:`Operation`.
    label : callable, optional
        The label rule; see :class:`Operation`.
    registry : OperationRegistry, optional
        The registry to register in; :data:`operation_registry` by default.

    Returns
    -------
    callable
        The decorator, which returns the registered :class:`Operation`.

    Raises
    ------
    TypeError
        As :class:`Operation` and :meth:`OperationRegistry.register` raise.
    ValueError
        If the registry already has an operation of that name.
    """

    def decorate(declaration: Callable[..., Any]) -> Operation:
        op = Operation(
            declaration,
            result=result,
            applicability_checks=applicability_checks,
            roles=roles,
            derived_route_check=derived_route_check,
            derived_route=derived_route,
            label=label,
        )
        (operation_registry if registry is None else registry).register(op)
        return op

    return decorate

operation_registry = OperationRegistry() module-attribute

The global registry of operations.

probpipe.operations.OperationRegistry()

Bases: SupportsRegistryCataloging

The registry of operations, which makes the vocabulary discoverable.

Each entry is an operation, listed with its operands, whether it is primitive or derived, and its routes in selection order. The registry implements SupportsRegistryCataloging through name, description, kind, entry_summaries, and describe_entry, and it is cataloged as "operations".

Source code in probpipe/operations/_operation.py
def __init__(self) -> None:
    self._operations: dict[str, Operation] = {}

name property

"operations", the registry's name in the registry catalog.

description property

A one-line description of the registry, which the registry catalog shows.

kind property

"operation", the registry's catalog kind.

register(op)

Register the operation op under its name.

Parameters:

Name Type Description Default
op Operation

The operation; operation calls this method for each operation it declares.

required

Raises:

Type Description
TypeError

If op is not an operation.

ValueError

If an operation of that name is registered.

Source code in probpipe/operations/_operation.py
def register(self, op: Function) -> None:
    """Register the operation *op* under its name.

    Parameters
    ----------
    op : Operation
        The operation; :func:`operation` calls this method for each operation
        it declares.

    Raises
    ------
    TypeError
        If *op* is not an operation.
    ValueError
        If an operation of that name is registered.
    """
    if not isinstance(op, Operation):
        raise TypeError(f"only an operation registers here; got {type(op).__name__}")
    if op.label in self._operations:
        raise ValueError(f"an operation named {op.label!r} is already registered")
    self._operations[op.label] = op

list()

One summary per operation, in registration order.

Source code in probpipe/operations/_operation.py
def list(self) -> list[OperationSummary]:
    """One summary per operation, in registration order."""
    return [op.summary() for op in self._operations.values()]

describe(name=None)

The summaries as text, for the operation name or for all of them.

Parameters:

Name Type Description Default
name str or None

An operation's name in the registry; None describes every operation, in registration order.

None

Returns:

Type Description
str

One block per operation, the blocks separated by a blank line. A block opens with the signature and whether the operation is primitive or derived, and then lists the description, the operands, and the routes in selection order.

Raises:

Type Description
KeyError

If name is not a registered operation.

Source code in probpipe/operations/_operation.py
def describe(self, name: str | None = None) -> str:
    """The summaries as text, for the operation *name* or for all of them.

    Parameters
    ----------
    name : str or None
        An operation's name in the registry; ``None`` describes every
        operation, in registration order.

    Returns
    -------
    str
        One block per operation, the blocks separated by a blank line. A block
        opens with the signature and whether the operation is primitive or
        derived, and then lists the description, the operands, and the routes
        in selection order.

    Raises
    ------
    KeyError
        If *name* is not a registered operation.
    """
    if name is not None:
        return _render(self._get(name).summary())
    return "\n\n".join(_render(summary) for summary in self.list())

__getitem__(name)

The operation registered as name.

Parameters:

Name Type Description Default
name str

The name of the operation's declaration, such as "mean".

required

Returns:

Type Description
Operation

The registered object itself.

Raises:

Type Description
KeyError

If no operation is registered as name.

Source code in probpipe/operations/_operation.py
def __getitem__(self, name: str) -> Function:
    """The operation registered as *name*.

    Parameters
    ----------
    name : str
        The name of the operation's declaration, such as ``"mean"``.

    Returns
    -------
    Operation
        The registered object itself.

    Raises
    ------
    KeyError
        If no operation is registered as *name*.
    """
    return self._get(name)

entry_summaries()

The summaries, as a cataloged registry reports its entries.

Source code in probpipe/operations/_operation.py
def entry_summaries(self) -> list[OperationSummary]:
    """The summaries, as a cataloged registry reports its entries."""
    return self.list()

describe_entry(name)

The summary of the operation name.

Parameters:

Name Type Description Default
name str

The name of the operation's declaration, such as "mean".

required

Returns:

Type Description
OperationSummary

The operation's entry as list reports it.

Raises:

Type Description
KeyError

If name is not a registered operation.

Source code in probpipe/operations/_operation.py
def describe_entry(self, name: str) -> OperationSummary:
    """The summary of the operation *name*.

    Parameters
    ----------
    name : str
        The name of the operation's declaration, such as ``"mean"``.

    Returns
    -------
    OperationSummary
        The operation's entry as :meth:`list` reports it.

    Raises
    ------
    KeyError
        If *name* is not a registered operation.
    """
    return self._get(name).summary()

probpipe.operations.OperationRoute

Bases: Protocol

One implementation behind an operation, bound to a call rather than to argument types.

A route has the interface of a dispatch method: a check that reads the call's declarations without evaluating the body, an execute that realizes the call over raw forms, and an exact flag. The construction helpers of Operation build the four kinds; any object with these members registers through Operation.register_route.

Attributes:

Name Type Description
name str

The route's name, unique within its operation.

source RouteSource

Where the implementation comes from.

exact bool or None

Whether the result denotes the requested mathematical object; None for a route whose exactness is that of the implementation it delegates to, until that implementation is selected. A delegating route, which can restrict itself to exact implementations, is ranked twice: among the exact routes and among the approximate ones. A derived operation's derived route is ranked once, as the module docstring states. exact_only excludes any other route whose exactness is None.

check(call, result)

Whether this route realizes call, whose result's output spec is result.

Source code in probpipe/operations/_operation.py
def check(self, call: BoundCall, result: OutputSpec | None) -> Feasibility:
    """Whether this route realizes *call*, whose result's output spec is *result*."""
    ...

execute(call, result)

Realize call and return its raw result.

A route may instead return the declared term with a provenance record of how the route produced it, which the call's own record keeps as a parent.

Source code in probpipe/operations/_operation.py
def execute(self, call: BoundCall, result: OutputSpec | None) -> Any:
    """Realize *call* and return its raw result.

    A route may instead return the declared term with a provenance record
    of how the route produced it, which the call's own record keeps as a
    parent.
    """
    ...

probpipe.operations.RouteSource

Bases: Enum

Where a route's implementation comes from.

probpipe.operations.BoundCall(operation, operands, controls) dataclass

One call of an operation, after binding and normalization.

Attributes:

Name Type Description
operation Function

The operation, as the view the call went through.

operands Mapping[str, Any]

Every bound argument by its parameter name, defaults included, in signature order: a term, a raw value, or a planned conversion; at a point of a lifted call, an element or a stand-in for a draw.

controls Mapping[str, Any]

The resolved controls, method, exact_only, raw, and method_options among them. A lookup of max_evaluations or num_samples here is a read of that count by the call, which the call notes so that it warns about a count it was given and never read; code that copies the controls to pass them on copies controls.peek(), which notes nothing.

Notes

The engine probes a point's candidates and runs the selected one on the same bound call, so a route that repeats work across the probes of its two candidates and its run keeps it in the call's private memo, under a key of its own. The memo lives only as long as the call, so nothing it holds, such as a guard's outcome, outlives the call.

specs property

Each supplying operand's spec: a term's own, or the kind its raw value wraps as.

A parameter whose role accepts no kind selects rather than supplies, as a field path does, and has no entry. An optional argument left at None has none either.

declarations property

What the result rule and the applicability checks read, by parameter.

A supplying operand contributes its spec, and a parameter that selects contributes its value.

probpipe.operations.OperationSummary(name, priority, supported_types=(), description='', module_path='', exact=None, is_floor=False, *, operands, is_derived, formula, routes) dataclass

Bases: EntrySummary

One operation, as the registry of operations lists it.

The attributes of EntrySummary come first, and for an operation they hold:

  • name: the operation's name;
  • priority and exact: None, since operations are not ranked against each other and each route declares its own exactness;
  • supported_types: the kinds the first operand accepts;
  • description: the first paragraph of the operation's docstring;
  • module_path: the module that declares the operation.

Attributes:

Name Type Description
operands tuple of OperandSummary

Every parameter, in signature order.

is_derived bool

Whether the operation is defined by a formula over other operations.

formula str or None

The formula, when derived.

routes tuple of RouteSummary

The routes, in selection order.

probpipe.operations.OperandSummary(name, accepts, planning) dataclass

One parameter of an operation: its role and whether the result rule reads it.

Attributes:

Name Type Description
name str

The parameter, as the signature spells it.

accepts tuple of type

The kinds it takes, each named by its spec class; empty when the parameter selects rather than supplies, as a field path does.

planning bool

Whether the result rule reads it.

probpipe.operations.RouteSummary(name, source, exact, requires, condition) dataclass

One route of an operation, as the registry of operations lists it.

Attributes:

Name Type Description
name str

The route's name.

source RouteSource

Where its implementation comes from.

exact bool or None

Its declared exactness; None for a route whose exactness is that of the implementation it selects.

requires tuple of type

The protocols a capability route needs; empty otherwise.

condition str

The feasibility condition in words.

A new evaluation rule

A call f(d) of a function at a distribution or a batch resolves among the evaluation rules, and a rule realizes the call for a pair of a map type and an operand type, as a closed form or a batched routine does. A rule is a BinaryDispatchMethod whose supported_types is a pair of the map types and the operand types. Its check and execute take the map and the operand positionally and the keywords parameter, fixed_args, and controls, and evaluation_rule_registry.register registers an instance. The registry ships three rules: the sampling lift and the elementwise sweep, which are floors and so rank below every other rule, and the exact enumeration of empirical laws.

evaluation_rule_registry = BinaryDispatchRegistry(name='evaluation_rules', description='Evaluation rules for a map applied to a law or a batch, keyed on both types.') module-attribute

The routes of a lifted application, keyed on the map's and the operand's types.

A bijector for a constraint

register_bijector registers the factory of the bijector that bijector_for returns for a constraint, keyed on a Constraint subclass or on one constraint.

register_bijector(key, factory, *, description='')

Register a bijector factory for a constraint type or one constraint.

Parameters:

Name Type Description Default
key type[Constraint] or Constraint

A Constraint subclass, which covers each of its instances, or one constraint, which covers the constraints equal to it. An instance key takes precedence over a type key.

required
factory callable

factory(constraint) returns a bijector Function claiming the inverse and the log-determinant of its Jacobian, or a backend bijector, which enters as such a Function. It receives the constraint, so it can read the constraint's parameters.

required
description str

A one-line description of the bijector, which the registry catalog shows under "bijectors"; empty by default.

''

Raises:

Type Description
TypeError

If description is not a str.

Notes

Registering a key again replaces its factory and its description. A registration for Constraint itself would cover every constraint without a registration of its own.

Source code in probpipe/functions/_reparameterization.py
def register_bijector(
    key: type[Constraint] | Constraint, factory: BijectorFactory, *, description: str = ""
) -> None:
    """Register a bijector factory for a constraint type or one constraint.

    Parameters
    ----------
    key : type[Constraint] or Constraint
        A ``Constraint`` subclass, which covers each of its instances, or one
        constraint, which covers the constraints equal to it. An instance key
        takes precedence over a type key.
    factory : callable
        ``factory(constraint)`` returns a bijector ``Function`` claiming the
        inverse and the log-determinant of its Jacobian, or a backend bijector,
        which enters as such a ``Function``. It receives the constraint, so it
        can read the constraint's parameters.
    description : str, optional
        A one-line description of the bijector, which the registry catalog
        shows under ``"bijectors"``; empty by default.

    Raises
    ------
    TypeError
        If *description* is not a ``str``.

    Notes
    -----
    Registering a key again replaces its factory and its description. A
    registration for ``Constraint`` itself would cover every constraint
    without a registration of its own.
    """
    if not isinstance(description, str):
        raise TypeError(f"register_bijector's description must be a str, got {description!r}")
    _CONSTRAINT_BIJECTOR_REGISTRY[key] = factory
    _BIJECTOR_DESCRIPTIONS[key] = description

A new array backend

register_array_backend makes the instances of an array-container type numeric leaves, and its ArrayBackend argument holds the functions that read their shapes and dtypes and convert them to arrays.

register_array_backend(leaf_type, backend)

Register backend as the array-backend hooks for leaf_type.

Registering a type makes its instances first-class numeric leaves everywhere at once: template inference and NumericArraySpec.is_valid recognise them, all-numeric records holding them auto-promote to NumericRecord, the compute boundary converts them through backend.to_jax, batch stacking coerces them per element, and fingerprint() hashes their content through backend.to_numpy.

Parameters:

Name Type Description Default
leaf_type type

The container type to register. Lookup walks the MRO of a value's type, so registering a base class also covers its subclasses.

required
backend ArrayBackend

The recognition/conversion hooks.

required
Notes

Re-registering an existing leaf_type overwrites the previous registration and issues a UserWarning, so an accidental double registration (e.g. two libraries claiming the same type) is visible.

Source code in probpipe/core/_array_backend.py
def register_array_backend(leaf_type: type, backend: ArrayBackend) -> None:
    """Register *backend* as the array-backend hooks for *leaf_type*.

    Registering a type makes its instances first-class numeric leaves
    everywhere at once: template inference and ``NumericArraySpec.is_valid``
    recognise them, all-numeric records holding them auto-promote to
    ``NumericRecord``, the compute boundary converts them through
    ``backend.to_jax``, batch stacking coerces them per element, and
    ``fingerprint()`` hashes their content through ``backend.to_numpy``.

    Parameters
    ----------
    leaf_type : type
        The container type to register. Lookup walks the MRO of a value's
        type, so registering a base class also covers its subclasses.
    backend : ArrayBackend
        The recognition/conversion hooks.

    Notes
    -----
    Re-registering an existing ``leaf_type`` overwrites the previous
    registration and issues a ``UserWarning``, so an accidental double
    registration (e.g. two libraries claiming the same type) is visible.
    """
    if leaf_type in _backend_registry:
        warnings.warn(
            f"register_array_backend() replaced the ArrayBackend already registered "
            f"for {leaf_type.__name__}",
            stacklevel=2,
        )
    _backend_registry[leaf_type] = backend

ArrayBackend(*, event_shape, numpy_dtype=lambda obj: _safe_numpy_dtype(obj.dtype), is_numeric=lambda obj: True, to_jax=_default_to_jax, to_numpy=_default_to_numpy, take=lambda obj, index: obj[index], metadata=lambda obj: None) dataclass

Recognition and conversion hooks for one native array-container type.

All fields are keyword-only. event_shape is required; the rest have working defaults for containers that speak the numpy protocol.

Parameters:

Name Type Description Default
event_shape callable

event_shape(obj) -> tuple[int, ...] — the leaf's event shape, read from container metadata without materialising values.

required
numpy_dtype callable

numpy_dtype(obj) -> np.dtype | None — the leaf's single numpy dtype, or None when the container has no single dtype (e.g. a heterogeneous frame). Defaults to reading obj.dtype.

lambda obj: _safe_numpy_dtype(dtype)
is_numeric callable

is_numeric(obj) -> bool — whether this instance holds numeric data. Defaults to True (the registered type is numeric by construction).

lambda obj: True
to_jax callable

to_jax(obj) -> jax.Array — the compute-boundary conversion. Materialises lazy/disk-backed values. Defaults to jnp.asarray(np.asarray(obj)).

_default_to_jax
to_numpy callable

to_numpy(obj) -> np.ndarray — the fingerprint materialisation. Defaults to np.asarray(obj).

_default_to_numpy
take callable

take(obj, index) -> Any — positional selection along the leading axes, where index is a tuple of ints and slices, one per leading axis. Defaults to obj[index], which is positional for a numpy-protocol container. A container whose [] means something else must override it: pandas reads labels there, so its backend selects through .iloc. This is what lets a batch address its elements by position without materialising the whole store.

lambda obj, index: obj[index]
metadata callable

metadata(obj) -> Any — the container's identity-bearing metadata beyond its values (an xarray array's dims / coords / attrs / name, a pandas object's index / columns), as a fingerprint-able structure (nested tuples / dicts / arrays / scalars). Values are not included (they are covered by to_numpy). This is what makes the metadata part of a record's identity: fingerprint folds it into the digest and Record.__eq__ compares it, so two containers with equal values but different coords are distinct. Defaults to None — a container with no identity-bearing metadata (a bare array, zarr, dask), whose identity is its values alone.

lambda obj: None

array_backend_for(obj)

Return the registered backend for obj's type, or None.

Walks the MRO of type(obj) so subclass instances pick up base-class registrations. Consumers resolve registry-first and fall back to numpy-protocol duck-typing when this returns None.

Notes

Exact-type lookup is checked before the MRO walk, so a registered type resolves in one dict probe and only a subclass of a registered type pays for the walk. Unregistered leaves (bare np.ndarray / jax.Array, the common case) miss the exact probe and walk their MRO, but that is short and off the hot path — _child_field_as_jax fast-returns a jax.Array leaf before this is ever called.

Source code in probpipe/core/_array_backend.py
def array_backend_for(obj: Any) -> ArrayBackend | None:
    """Return the registered backend for ``obj``'s type, or ``None``.

    Walks the MRO of ``type(obj)`` so subclass instances pick up
    base-class registrations. Consumers resolve registry-first and fall
    back to numpy-protocol duck-typing when this returns ``None``.

    Notes
    -----
    Exact-type lookup is checked before the MRO walk, so a registered type
    resolves in one dict probe and only a subclass of a registered type pays
    for the walk. Unregistered leaves (bare ``np.ndarray`` / ``jax.Array``,
    the common case) miss the exact probe and walk their MRO, but that is
    short and off the hot path — ``_child_field_as_jax`` fast-returns a
    ``jax.Array`` leaf before this is ever called.
    """
    if not _backend_registry:
        return None
    cls = type(obj)
    backend = _backend_registry.get(cls)
    if backend is not None:
        return backend
    for base in cls.__mro__[1:]:
        backend = _backend_registry.get(base)
        if backend is not None:
            return backend
    return None

A new executor

An executor decides how the evaluations a call asks for run: one after another, on threads, in worker processes, compiled by JAX, or on a cluster. It never decides what they compute, so changing the executor changes no result beyond the last bit of rounding. The evaluations of one callable that one request asks for, such as 200 runs of a simulator at 200 parameter values, form one EvaluationPoints, and an executor runs it by its chunks. A user names an executor on a Function, as simulate.using(executor="thread", executor_options={"max_workers": 8}), and a lifted call, a sweep, and a plain call of simulate then run their evaluations on it. A function JAX can trace is mapped by jax whatever executor is named.

ProbPipe ships four executors in executor_registry:

  • jax, which maps a callable JAX can trace over every evaluation point at once, and is selected automatically for one; when that map would hold more than 256 MiB, it compiles the map and runs it in chunks that fit, and its option chunk_size sets the chunks instead;
  • sequential, which runs the evaluation points one after another, and is selected automatically for every other callable;
  • thread, which runs chunks on a pool of threads, with the options max_workers and chunk_size;
  • process, which runs chunks in worker processes started under the calling process's JAX settings, with the options max_workers, chunk_size, and start_method.

thread and process run only when named, since user code may not be safe to run in several threads or to send to another process.

A new executor subclasses EvaluationExecutor, sets its name and description, and implements check and execute. Its options are the parameters of execute after the set of evaluation points, which check takes too. execute runs every chunk, passing each the set's shared payload, and returns one outcome per evaluation point in order; EvaluationOutcomes.merge restores that order from chunks that finished in any order. A chunk pickles, so an executor may run it in another process or on another machine, and shipping_check() reports whether the set can be sent. Pickling a chunk again, to retry it after its first run was lost, gives the retry the same random keys. An executor that runs chunks elsewhere returns EvaluationOutcomes.lost(chunk, reason) for a chunk that never finished. An executor with no priority runs only when named. check_executor, in probpipe.testing, checks an executor against the contract before it is registered:

import submitit

from probpipe import EvaluationExecutor, EvaluationOutcomes, executor_registry
from probpipe.testing import check_executor


def run_chunk(chunk, shared_payload):
    return chunk.run(shared_payload)


class SlurmExecutor(EvaluationExecutor):
    name = "slurm"
    description = "Run chunks of evaluation points as Slurm array jobs."

    def check(self, evaluation_points, /, *, n_jobs=1, partition="short", retries=0):
        return evaluation_points.shipping_check()

    def execute(self, evaluation_points, /, *, n_jobs=1, partition="short", retries=0):
        cluster = submitit.AutoExecutor(folder="slurm_logs")
        cluster.update_parameters(slurm_partition=partition)
        shared_payload = evaluation_points.shared_payload()
        pending_chunks = evaluation_points.chunks(num_chunks=n_jobs)
        chunk_outcomes, failed_jobs = [], []
        for _ in range(retries + 1):
            jobs = cluster.map_array(run_chunk, pending_chunks, [shared_payload] * len(pending_chunks))
            failed_jobs = []
            for chunk, job in zip(pending_chunks, jobs):
                try:
                    chunk_outcomes.append(job.result())   # errors of user code are in the outcomes
                except Exception as job_error:            # the job itself died
                    failed_jobs.append((chunk, job_error))
            pending_chunks = [chunk for chunk, _ in failed_jobs]
            if not pending_chunks:
                break
        chunk_outcomes += [EvaluationOutcomes.lost(chunk, str(job_error)) for chunk, job_error in failed_jobs]
        return EvaluationOutcomes.merge(chunk_outcomes)


check_executor(SlurmExecutor())
executor_registry.register(SlurmExecutor())

Code that runs inside a ProbPipe call, such as a route of an operation, asks for the evaluations of a callable at many arguments with evaluate_at_points, which builds one EvaluationPoints and runs it on the executor the call chooses.

evaluate_at_points(fn, /, *, varying, shared, origin, output_spec, stacked=False)

Evaluate fn at many arguments, on the executor the running call chooses.

Each evaluation point calls fn(**shared, **arguments), where arguments holds each varying argument's values at that evaluation point. With concrete arguments the evaluation points form one EvaluationPoints, which runs under the running call's settings, and a draw made inside one takes its random key from its place in the workflow, so changing the executor changes no result. A Function that claims traceable=True is mapped by jax whatever executor the call names. The call takes a place of its own in the workflow, as a nested call does, so it can be made from a route, an inference method, or a function's body. With traced arguments, as inside a function that JAX traces, fn is mapped inline with jax.vmap.

Parameters:

Name Type Description Default
fn callable

The callable. A Function's execution claims say how it may run.

required
varying Mapping of str to Any

Each argument that differs between evaluation points, its values stacked on a leading axis with one row per evaluation point.

required
shared Mapping of str to Any

Each argument that every evaluation point receives unchanged.

required
origin str

The name of the callable or of the site that asks for the evaluations, which messages use.

required
output_spec OutputSpec or None

The callable's output spec, which each output is checked against; None checks nothing.

required
stacked bool

Whether to return the outputs as one tree stacked on a leading axis of evaluation points, in place of one output per evaluation point. jax returns its mapped output whole. The outputs of any other executor are stacked leaf by leaf when every leaf of every output is numeric and the outputs share one tree structure, and are otherwise returned as a one-dimensional object array that holds each output, as are outputs that are tuples or lists. False by default.

False

Returns:

Type Description
tuple or Any

Each evaluation point's output, in point order, or under stacked the outputs stacked as one tree.

Raises:

Type Description
EvaluationError

If an evaluation point failed, naming every failed one.

ResolutionError

If the executor named for the callable cannot run its evaluation points, or no registered executor can.

ValueError

If the varying arguments do not have one row per evaluation point, or the chosen executor does not take one of its options.

Examples:

A route of a ProbPipe call evaluates a simulator at 200 parameter values, stacked in thetas, against the observed data y::

simulations = evaluate_at_points(
    simulate,
    varying={"theta": thetas},
    shared={"data": y},
    origin="simulate",
    output_spec=simulate.output_spec,
)
Source code in probpipe/core/_executors.py
def evaluate_at_points(
    fn: Callable[..., Any],
    /,
    *,
    varying: Mapping[str, Any],
    shared: Mapping[str, Any],
    origin: str,
    output_spec: OutputSpec | None,
    stacked: bool = False,
) -> Any:
    """Evaluate *fn* at many arguments, on the executor the running call chooses.

    Each evaluation point calls ``fn(**shared, **arguments)``, where
    ``arguments`` holds each varying argument's values at that evaluation
    point. With concrete arguments the evaluation points form one
    :class:`EvaluationPoints`, which runs under the running call's settings,
    and a draw made inside one takes its random key from its place in the
    workflow, so changing the executor changes no result. A ``Function`` that
    claims ``traceable=True`` is mapped by ``jax`` whatever executor the call
    names. The call takes a place of its own in the workflow, as a nested
    call does, so it can be made from a route, an inference method, or a
    function's body. With traced arguments, as inside a function that JAX
    traces, *fn* is mapped inline with ``jax.vmap``.

    Parameters
    ----------
    fn : callable
        The callable. A ``Function``'s execution claims say how it may run.
    varying : Mapping of str to Any
        Each argument that differs between evaluation points, its values
        stacked on a leading axis with one row per evaluation point.
    shared : Mapping of str to Any
        Each argument that every evaluation point receives unchanged.
    origin : str
        The name of the callable or of the site that asks for the
        evaluations, which messages use.
    output_spec : OutputSpec or None
        The callable's output spec, which each output is checked against;
        ``None`` checks nothing.
    stacked : bool, optional
        Whether to return the outputs as one tree stacked on a leading axis of
        evaluation points, in place of one output per evaluation point.
        ``jax`` returns its mapped output whole. The outputs of any other
        executor are stacked leaf by leaf when every leaf of every output is
        numeric and the outputs share one tree structure, and are otherwise
        returned as a one-dimensional object array that holds each output, as
        are outputs that are tuples or lists.
        ``False`` by default.

    Returns
    -------
    tuple or Any
        Each evaluation point's output, in point order, or under *stacked* the
        outputs stacked as one tree.

    Raises
    ------
    EvaluationError
        If an evaluation point failed, naming every failed one.
    ResolutionError
        If the executor named for the callable cannot run its evaluation
        points, or no registered executor can.
    ValueError
        If the varying arguments do not have one row per evaluation point, or
        the chosen executor does not take one of its options.
    Examples
    --------
    A route of a ProbPipe call evaluates a simulator at 200 parameter values,
    stacked in ``thetas``, against the observed data ``y``::

        simulations = evaluate_at_points(
            simulate,
            varying={"theta": thetas},
            shared={"data": y},
            origin="simulate",
            output_spec=simulate.output_spec,
        )
    """
    if _holds_tracer((varying, shared)):
        return _mapped_inline(fn, varying, shared, origin=origin, stacked=stacked)
    with _requester_scope():
        evaluation_points = EvaluationPoints(
            fn,
            varying=varying,
            shared=shared,
            origin=origin,
            output_spec=output_spec,
            claims=_execution_claims_of(fn),
        )
        return _evaluated_outputs(evaluation_points, stacked=stacked)

EvaluationExecutor

Bases: UnaryDispatchMethod

The base class of an executor: a named way to run a set of evaluation points.

A subclass sets name and description, sets priority when automatic selection may choose it, and implements check and execute. Its options are the keyword-only parameters of execute, which check takes too; ProbPipe refuses an option that execute does not take before it calls either. An executor passes probpipe.testing.check_executor when it runs every evaluation point through its chunks' run, returns the outcomes in order with what the evaluation points noted, and changes no argument.

Attributes:

Name Type Description
name str

The name the control executor selects it by.

exact bool

True: an executor returns the requested result itself.

priority int or None

Its rank in automatic selection, higher first; None, the default, makes it opt-in, run only when named.

description str

One line, which the registry catalog shows.

Examples:

An executor that runs the chunks of a set on a pool the user gives::

class PoolExecutor(EvaluationExecutor):
    name = "my_pool"
    description = "Run chunks of evaluation points on my pool."

    def check(self, evaluation_points, /, *, num_chunks=8):
        return evaluation_points.shipping_check()

    def execute(self, evaluation_points, /, *, num_chunks=8):
        shared_payload = evaluation_points.shared_payload()
        chunks = evaluation_points.chunks(num_chunks=num_chunks)
        return EvaluationOutcomes.merge(
            my_pool.map(lambda chunk: chunk.run(shared_payload), chunks)
        )

executor_registry.register(PoolExecutor())

check(evaluation_points, /, **executor_options) abstractmethod

Whether the executor can run evaluation_points, read from their claims and the environment.

It runs none of the evaluation points.

Parameters:

Name Type Description Default
evaluation_points EvaluationPoints

The set of evaluation points.

required
**executor_options Any

The executor's options.

{}

Returns:

Type Description
Feasibility

Feasible when the executor can run the set; otherwise infeasible, with the reason in its description.

Source code in probpipe/core/_executors.py
@abstractmethod
def check(self, evaluation_points: EvaluationPoints, /, **executor_options: Any) -> Feasibility:
    """Whether the executor can run *evaluation_points*, read from their claims and the environment.

    It runs none of the evaluation points.

    Parameters
    ----------
    evaluation_points : EvaluationPoints
        The set of evaluation points.
    **executor_options : Any
        The executor's options.

    Returns
    -------
    Feasibility
        Feasible when the executor can run the set; otherwise infeasible,
        with the reason in its description.
    """

execute(evaluation_points, /, **executor_options) abstractmethod

Run every evaluation point and return their outcomes, in the order of the evaluation points.

Parameters:

Name Type Description Default
evaluation_points EvaluationPoints

The set of evaluation points.

required
**executor_options Any

The executor's options.

{}

Returns:

Type Description
EvaluationOutcomes

One outcome per evaluation point, starting at point index 0.

Source code in probpipe/core/_executors.py
@abstractmethod
def execute(
    self, evaluation_points: EvaluationPoints, /, **executor_options: Any
) -> EvaluationOutcomes:
    """Run every evaluation point and return their outcomes, in the order of the evaluation points.

    Parameters
    ----------
    evaluation_points : EvaluationPoints
        The set of evaluation points.
    **executor_options : Any
        The executor's options.

    Returns
    -------
    EvaluationOutcomes
        One outcome per evaluation point, starting at point index 0.
    """

executor_registry = _ExecutorRegistry(name='executors', description='Executors that run sets of evaluation points: in order, on threads, in worker processes, or compiled by JAX') module-attribute

The registry of executors, from which a call chooses the one that runs its evaluations.

It holds jax, sequential, thread, and process; register an executor of your own with executor_registry.register.

EvaluationPoints(fn, /, *, varying, shared=None, origin, output_spec=None, claims=NO_CLAIMS, traceable=None, point_noun='evaluation point')

The evaluation points of one callable that one request asks for.

An evaluation point is one evaluation of the callable at one set of arguments. A set of evaluation points holds the callable, the arguments every evaluation point shares, and the arguments that vary, stacked on a leading axis, so it describes its evaluation points without building each one. An executor runs it by its chunks, and never reads or changes the arguments, so the executor decides only how the evaluation points run, never what they compute.

A set of evaluation points is built by the code that asks for the evaluations, such as a lifted call, under the call that runs it: each evaluation point then runs under that call's settings, and a ProbPipe draw made inside it takes its random key from its place in the workflow, whatever executor runs it.

Parameters:

Name Type Description Default
fn callable

The callable, which each evaluation point calls with its arguments by keyword.

required
varying Mapping of str to Any

Each argument that differs between evaluation points, its values stacked on a leading axis: every array leaf of one argument has one row per evaluation point.

required
shared Mapping of str to Any

Each argument that every evaluation point receives unchanged.

None
origin str

The name of the callable or of the site that asks for the evaluations, which messages and reports use.

required
output_spec OutputSpec or None

The callable's output spec, which each output is checked against.

None
claims ExecutionClaims

The callable's execution claims; none by default.

NO_CLAIMS
traceable bool or None

Whether JAX can trace the callable for these arguments, as its claim or its stored probe result says; None when that is unknown, and the set then runs as opaque code.

None
point_noun str

The word for one evaluation point in messages, such as "draw" or "grid point".

'evaluation point'

Attributes:

Name Type Description
origin str

The name of the callable or of the site.

claims ExecutionClaims

The callable's execution claims.

output_spec OutputSpec or None

The callable's output spec.

point_noun str

The word for one evaluation point in messages.

Raises:

Type Description
ValueError

If there are no varying arguments, or they do not all have the same number of rows, or the output spec declares float64 while jax_enable_x64 is disabled.

RuntimeError

If it is built where no ProbPipe call gives its evaluation points a place in the workflow, which gives them their random keys, such as directly in a function's body; evaluate_at_points takes a place of its own there. Embedded evaluations carry their call through a token instead and cannot draw workflow randomness.

Examples:

An executor receives a set of evaluation points and runs it by its chunks, here two evaluation points at a time::

def execute(self, evaluation_points, /):
    shared_payload = evaluation_points.shared_payload()
    return EvaluationOutcomes.merge(
        chunk.run(shared_payload) for chunk in evaluation_points.chunks(chunk_size=2)
    )
Source code in probpipe/core/_evaluation_points.py
def __init__(
    self,
    fn: Callable[..., Any],
    /,
    *,
    varying: Mapping[str, Any],
    shared: Mapping[str, Any] | None = None,
    origin: str,
    output_spec: OutputSpec | None = None,
    claims: ExecutionClaims = NO_CLAIMS,
    traceable: bool | None = None,
    point_noun: str = "evaluation point",
) -> None:
    self._set_up(
        fn,
        varying=varying,
        shared=shared,
        origin=origin,
        output_spec=output_spec,
        claims=claims,
        traceable=traceable,
        point_noun=point_noun,
    )

traceable property

Whether JAX can trace the callable for these evaluation points; False when unknown.

__len__()

The number of evaluation points.

Source code in probpipe/core/_evaluation_points.py
def __len__(self) -> int:
    """The number of evaluation points."""
    return self._num_evaluation_points

chunks(*, chunk_size=None, num_chunks=None)

Split the evaluation points into contiguous chunks, in order.

Parameters:

Name Type Description Default
chunk_size int

The number of evaluation points in each chunk; the last chunk may hold fewer.

None
num_chunks int

The number of chunks, as equal in size as possible; at most one per evaluation point.

None

Returns:

Type Description
list of EvaluationChunk

The chunks, which together hold every evaluation point once, in order. Without chunk_size and num_chunks, one chunk holds them all.

Raises:

Type Description
ValueError

If both chunk_size and num_chunks are given, or either is less than 1.

TypeError

If chunk_size or num_chunks is not an integer.

Source code in probpipe/core/_evaluation_points.py
def chunks(
    self, *, chunk_size: int | None = None, num_chunks: int | None = None
) -> list[EvaluationChunk]:
    """Split the evaluation points into contiguous chunks, in order.

    Parameters
    ----------
    chunk_size : int, optional
        The number of evaluation points in each chunk; the last chunk may
        hold fewer.
    num_chunks : int, optional
        The number of chunks, as equal in size as possible; at most one
        per evaluation point.

    Returns
    -------
    list of EvaluationChunk
        The chunks, which together hold every evaluation point once, in
        order. Without *chunk_size* and *num_chunks*, one chunk holds them
        all.

    Raises
    ------
    ValueError
        If both *chunk_size* and *num_chunks* are given, or either is less
        than 1.
    TypeError
        If *chunk_size* or *num_chunks* is not an integer.
    """
    if chunk_size is not None and num_chunks is not None:
        raise ValueError(
            "cannot split evaluation points by both chunk_size and num_chunks. Give one of them"
        )
    num_points = self._num_evaluation_points
    if num_points == 0:
        return []
    if chunk_size is not None:
        _checked_count(chunk_size, "chunk_size")
        starts = range(0, num_points, chunk_size)
        bounds = [(start, min(start + chunk_size, num_points)) for start in starts]
    else:
        if num_chunks is not None:
            _checked_count(num_chunks, "num_chunks")
        num_chunks_cut = min(num_chunks or 1, num_points)
        base_size, remainder = divmod(num_points, num_chunks_cut)
        bounds = []
        start = 0
        for chunk_index in range(num_chunks_cut):
            stop = start + base_size + (1 if chunk_index < remainder else 0)
            bounds.append((start, stop))
            start = stop
    return [EvaluationChunk(self, start, stop) for start, stop in bounds]

shared_payload()

The callable and the arguments every evaluation point shares.

An executor passes it to EvaluationChunk.run: one that runs chunks in the calling process passes it without copying, and one that sends chunks to other processes sends it with them.

Returns:

Type Description
SharedPayload

The same object on every call.

Source code in probpipe/core/_evaluation_points.py
def shared_payload(self) -> SharedPayload:
    """The callable and the arguments every evaluation point shares.

    An executor passes it to :meth:`EvaluationChunk.run`: one that runs
    chunks in the calling process passes it without copying, and one that
    sends chunks to other processes sends it with them.

    Returns
    -------
    SharedPayload
        The same object on every call.
    """
    return self._shared_payload

shipping_check()

Whether the chunks and the shared payload can be pickled, for another process.

The check pickles the callable, the shared arguments, the call's settings, and the first evaluation point's arguments, and runs nothing. Its outcome is computed once.

Returns:

Type Description
Feasibility

Feasible when everything pickles; otherwise infeasible, with the reason in its description.

Source code in probpipe/core/_evaluation_points.py
def shipping_check(self) -> Feasibility:
    """Whether the chunks and the shared payload can be pickled, for another process.

    The check pickles the callable, the shared arguments, the call's
    settings, and the first evaluation point's arguments, and runs
    nothing. Its outcome is computed once.

    Returns
    -------
    Feasibility
        Feasible when everything pickles; otherwise infeasible, with the
        reason in its description.
    """
    if self._shipping_feasibility is None:
        self._shipping_feasibility = self._compute_shipping_feasibility()
    return self._shipping_feasibility

EvaluationChunk(evaluation_points, start, stop)

A contiguous slice of a set of evaluation points, which an executor runs as one unit.

A chunk pickles, so an executor may run it in another process or on another machine; a pickled chunk carries only its own evaluation points' arguments and the settings of the call that asked for them. Running it does the same wherever it runs. Pickling a chunk reserves its evaluation points' random keys with the call that asked for them, and pickling it again, as an executor that retries a lost chunk does, replaces that reservation, so the retry draws with the same keys.

Parameters:

Name Type Description Default
evaluation_points EvaluationPoints

The set the chunk is a slice of.

required
start int

The point index of its first evaluation point.

required
stop int

One past the point index of its last evaluation point.

required

Attributes:

Name Type Description
start int

The point index of its first evaluation point.

stop int

One past the point index of its last evaluation point.

Source code in probpipe/core/_evaluation_points.py
def __init__(self, evaluation_points: EvaluationPoints, start: int, stop: int) -> None:
    self.start = start
    self.stop = stop
    self._origin = evaluation_points.origin
    self._set_ordinal = evaluation_points._set_ordinal
    self._point_noun = evaluation_points.point_noun
    self._output_spec = evaluation_points.output_spec
    self._vectorized = evaluation_points.claims.vectorized
    self._evaluation_context = evaluation_points._call_context.evaluation_context()
    self._point_scopes = evaluation_points._point_scopes
    self._arguments_source: EvaluationPoints | Mapping[str, Any] = evaluation_points

__len__()

The number of evaluation points in the chunk.

Source code in probpipe/core/_evaluation_points.py
def __len__(self) -> int:
    """The number of evaluation points in the chunk."""
    return self.stop - self.start

run(shared_payload)

Run every evaluation point of the chunk, in order, and return their outcomes.

Each evaluation point runs under the settings of the call that asked for it, and a ProbPipe draw made inside it takes its random key from the evaluation point's place in the workflow. An exception its code raises, an Exception and never a KeyboardInterrupt, is that evaluation point's failure, and the chunk goes on with the next one. Each output is checked against the callable's output spec. A callable that claims vectorized is called once for the whole chunk, and if that call raises, every evaluation point of the chunk fails with its error.

Parameters:

Name Type Description Default
shared_payload SharedPayload

The set's EvaluationPoints.shared_payload.

required

Returns:

Type Description
EvaluationOutcomes

One outcome per evaluation point of the chunk, in order.

Source code in probpipe/core/_evaluation_points.py
def run(self, shared_payload: SharedPayload) -> EvaluationOutcomes:
    """Run every evaluation point of the chunk, in order, and return their outcomes.

    Each evaluation point runs under the settings of the call that asked
    for it, and a ProbPipe draw made inside it takes its random key from
    the evaluation point's place in the workflow. An exception its code
    raises, an ``Exception`` and never a ``KeyboardInterrupt``, is that
    evaluation point's failure, and the chunk goes on with the next one.
    Each output is checked against the callable's output spec. A callable
    that claims ``vectorized`` is called once for the whole chunk, and if
    that call raises, every evaluation point of the chunk fails with its
    error.

    Parameters
    ----------
    shared_payload : SharedPayload
        The set's :meth:`EvaluationPoints.shared_payload`.

    Returns
    -------
    EvaluationOutcomes
        One outcome per evaluation point of the chunk, in order.
    """
    chunk_context = self._evaluation_context.with_fresh_call_accumulators(
        collects_calls=self._evaluation_context.collects_calls()
    )
    with _under_call_context(chunk_context):
        if self._vectorized:
            point_results = self._run_vectorized(shared_payload)
        else:
            point_results = [
                self._run_point(shared_payload, point_index)
                for point_index in range(self.start, self.stop)
            ]
    return _assembled_outcomes(
        self.start,
        point_results,
        noted_num_samples=cast(
            _NumSamplesUsed, chunk_context.num_samples_used
        ).num_samples_values,
        noted_count_reads=cast(_NumSamplesUsed, chunk_context.num_samples_used).count_reads,
        noted_set_records=cast(_EvaluationLog, chunk_context.evaluation_log).set_records,
        claim_reports=tuple(self._point_scopes.claim_reports()),
    )

__reduce__()

Pickle the chunk with its own evaluation points' arguments, to run in another process.

Pickling reserves the chunk's evaluation points with the call that asked for them, so the draws made inside them in the other process take the keys they take in this one, and the keys they claim come back with the outcomes.

Source code in probpipe/core/_evaluation_points.py
def __reduce__(self) -> tuple[Any, ...]:
    """Pickle the chunk with its own evaluation points' arguments, to run in another process.

    Pickling reserves the chunk's evaluation points with the call that
    asked for them, so the draws made inside them in the other process
    take the keys they take in this one, and the keys they claim come back
    with the outcomes.
    """
    chunk_state = {
        "start": self.start,
        "stop": self.stop,
        "origin": self._origin,
        "set_ordinal": self._set_ordinal,
        "point_noun": self._point_noun,
        "output_spec": self._output_spec,
        "vectorized": self._vectorized,
        "evaluation_context": self._evaluation_context,
        "point_scopes": self._point_scopes.shipped(range(self.start, self.stop)),
        "varying_arguments": self._arguments_in_chunk(),
    }
    return (_unpickled_chunk, (chunk_state,))

SharedPayload(fn, shared_arguments) dataclass

The callable of a set of evaluation points and the arguments every evaluation point shares.

An executor treats it as opaque: it sends it to its workers and passes it to EvaluationChunk.run.

Attributes:

Name Type Description
fn callable

The callable.

shared_arguments Mapping of str to Any

The arguments every evaluation point receives unchanged.

__reduce__()

Pickle with the shared arguments as a plain dict, read-only again when unpickled.

Source code in probpipe/core/_evaluation_points.py
def __reduce__(self) -> tuple[Any, ...]:
    """Pickle with the shared arguments as a plain dict, read-only again when unpickled."""
    return (_unpickled_shared_payload, (self.fn, dict(self.shared_arguments)))

EvaluationOutcomes(start, outputs, failures, _noted_num_samples=frozenset(), _noted_count_reads=frozenset(), _noted_set_records=(), _claim_reports=(), _lossy_casts=frozenset()) dataclass

The outcomes of a run of contiguous evaluation points: an output or a failure for each.

A chunk's run returns one, and an executor merges its chunks' outcomes into one for the whole set, with merge.

Attributes:

Name Type Description
start int

The point index of the first evaluation point covered.

outputs tuple

Each evaluation point's output, in order; None where one failed.

failures Mapping of int to EvaluationFailure

The failure of each evaluation point that has no output, by point index.

lost(chunk, reason) classmethod

The outcomes of a chunk whose every evaluation point the infrastructure lost.

Parameters:

Name Type Description Default
chunk EvaluationChunk

The chunk that did not finish, such as a cluster job that died.

required
reason str

Why, for the failures' messages.

required

Returns:

Type Description
EvaluationOutcomes

A "lost" failure for each evaluation point of chunk.

Source code in probpipe/core/_evaluation_points.py
@classmethod
def lost(cls, chunk: EvaluationChunk, reason: str) -> EvaluationOutcomes:
    """The outcomes of a chunk whose every evaluation point the infrastructure lost.

    Parameters
    ----------
    chunk : EvaluationChunk
        The chunk that did not finish, such as a cluster job that died.
    reason : str
        Why, for the failures' messages.

    Returns
    -------
    EvaluationOutcomes
        A ``"lost"`` failure for each evaluation point of *chunk*.
    """
    failures = {
        point_index: _point_failure(
            chunk._origin, chunk._set_ordinal, point_index, "lost", reason
        )
        for point_index in range(chunk.start, chunk.stop)
    }
    return cls(
        start=chunk.start,
        outputs=(None,) * len(chunk),
        failures=MappingProxyType(failures),
    )

merge(chunk_outcomes) classmethod

The outcomes of several runs as one, in the order of the evaluation points.

Parameters:

Name Type Description Default
chunk_outcomes iterable of EvaluationOutcomes

The outcomes of contiguous runs that together cover a range of evaluation points once, in any order.

required

Returns:

Type Description
EvaluationOutcomes

The outcomes sorted by start and joined.

Raises:

Type Description
ValueError

If the runs overlap or leave a gap.

Source code in probpipe/core/_evaluation_points.py
@classmethod
def merge(cls, chunk_outcomes: Iterable[EvaluationOutcomes]) -> EvaluationOutcomes:
    """The outcomes of several runs as one, in the order of the evaluation points.

    Parameters
    ----------
    chunk_outcomes : iterable of EvaluationOutcomes
        The outcomes of contiguous runs that together cover a range of
        evaluation points once, in any order.

    Returns
    -------
    EvaluationOutcomes
        The outcomes sorted by ``start`` and joined.

    Raises
    ------
    ValueError
        If the runs overlap or leave a gap.
    """
    ordered_outcomes = sorted(chunk_outcomes, key=lambda outcomes: outcomes.start)
    if not ordered_outcomes:
        return cls(start=0, outputs=(), failures=MappingProxyType({}))
    next_start = ordered_outcomes[0].start
    for outcomes in ordered_outcomes:
        if outcomes.start != next_start:
            raise ValueError(
                f"cannot merge outcomes that start at {outcomes.start} after outcomes that "
                f"end at {next_start}. Merge the outcomes of contiguous chunks that cover "
                "each evaluation point once"
            )
        next_start = outcomes.start + len(outcomes.outputs)
    return cls(
        start=ordered_outcomes[0].start,
        outputs=tuple(output for outcomes in ordered_outcomes for output in outcomes.outputs),
        failures=MappingProxyType(
            {
                point_index: failure
                for outcomes in ordered_outcomes
                for point_index, failure in outcomes.failures.items()
            }
        ),
        _noted_num_samples=frozenset().union(
            *(outcomes._noted_num_samples for outcomes in ordered_outcomes)
        ),
        _noted_count_reads=frozenset().union(
            *(outcomes._noted_count_reads for outcomes in ordered_outcomes)
        ),
        _noted_set_records=tuple(
            set_record
            for outcomes in ordered_outcomes
            for set_record in outcomes._noted_set_records
        ),
        _claim_reports=tuple(
            report for outcomes in ordered_outcomes for report in outcomes._claim_reports
        ),
        _lossy_casts=frozenset().union(
            *(outcomes._lossy_casts for outcomes in ordered_outcomes)
        ),
    )

EvaluationFailure(point_index, point_identity, kind, error_type, message, error) dataclass

Why one evaluation point has no output.

Attributes:

Name Type Description
point_index int

Its position within its set of evaluation points.

point_identity tuple of (str, int, int)

Its unique name within the call: the callable, which of the call's sets of evaluation points of that callable it belongs to, counting from 0, and its point index.

kind {'error', 'invalid', 'lost', 'timeout'}

"error" when its code raised; "invalid" when its output did not match the output spec; "lost" when the infrastructure lost it; "timeout" when it ran out of time.

error_type str

The class name of the exception, which survives sending it between processes.

message str

The exception's message.

error Exception or None

The exception itself; None when it could not be sent back from the process that ran the evaluation point.

__reduce__()

Pickle the failure, leaving out an exception that does not survive pickling and unpickling.

Source code in probpipe/core/_evaluation_points.py
def __reduce__(self) -> tuple[Any, ...]:
    """Pickle the failure, leaving out an exception that does not survive pickling and unpickling."""
    error = self.error
    if error is not None:
        try:
            cloudpickle.loads(cloudpickle.dumps(error))
        except Exception:
            error = None
    return (
        EvaluationFailure,
        (
            self.point_index,
            self.point_identity,
            self.kind,
            self.error_type,
            self.message,
            error,
        ),
    )

check_executor(executor)

Check that executor follows the executor contract, raising on the first rule it breaks.

The check runs fixed sets of evaluation points on executor and on the sequential executor, and compares their outcomes. The sets include a simulator that draws from the workflow inside each evaluation point, evaluation points that raise, an output that does not match its output spec, a callable that takes a whole chunk at once, a callable that reads the call's settings and notes a draw count, a callable that makes a ProbPipe call of its own, and a callable JAX can trace. They run with 64-bit floats on and jax_threefry_partitionable flipped, so an executor that runs work in another process must carry the parent's JAX settings; both settings are restored when the check ends. A set the executor's check reports it cannot run is skipped, and the executor must run at least one.

An executor passes when, for each set it runs, it returns one outcome per evaluation point in order, each output equal to the sequential one, bit for bit, or within a relative tolerance of 1e-6 for a set JAX compiles, each failure at the same evaluation point with the same kind, and the draw counts its evaluation points noted brought back to the call.

Parameters:

Name Type Description Default
executor EvaluationExecutor

The executor, registered or not; it runs with its default options.

required

Raises:

Type Description
AssertionError

If the executor breaks a rule of the contract, naming the set and the rule.

Examples:

>>> from probpipe import executor_registry
>>> from probpipe.testing import check_executor
>>> check_executor(executor_registry.get_method("thread"))
Source code in probpipe/testing/_executors.py
def check_executor(executor: EvaluationExecutor) -> None:
    """Check that *executor* follows the executor contract, raising on the first rule it breaks.

    The check runs fixed sets of evaluation points on *executor* and on the
    ``sequential`` executor, and compares their outcomes. The sets include a
    simulator that draws from the workflow inside each evaluation point,
    evaluation points that raise, an output that does not match its output
    spec, a callable that takes a whole chunk at once, a callable that reads
    the call's settings and notes a draw count, a callable that makes a
    ProbPipe call of its own, and a callable JAX can trace. They run with 64-bit
    floats on and ``jax_threefry_partitionable`` flipped, so an executor that
    runs work in another process must carry the parent's JAX settings; both
    settings are restored when the check ends. A set the executor's ``check``
    reports it cannot run is skipped, and the executor must run at least one.

    An executor passes when, for each set it runs, it returns one outcome per
    evaluation point in order, each output equal to the ``sequential`` one,
    bit for bit, or within a relative tolerance of ``1e-6`` for a set JAX
    compiles, each failure at the same evaluation point with the same kind,
    and the draw counts its evaluation points noted brought back to the call.

    Parameters
    ----------
    executor : EvaluationExecutor
        The executor, registered or not; it runs with its default options.

    Raises
    ------
    AssertionError
        If the executor breaks a rule of the contract, naming the set and the
        rule.

    Examples
    --------
    >>> from probpipe import executor_registry
    >>> from probpipe.testing import check_executor
    >>> check_executor(executor_registry.get_method("thread"))  # doctest: +SKIP
    """
    reference_executor = executor_registry.get_method("sequential")
    sets_run = []
    with _flipped_parent_jax_settings():
        for conformance_set in _CONFORMANCE_SETS:
            executor_run = conformance_set.run_on(executor)
            if executor_run is None:
                continue
            reference_run = conformance_set.run_on(reference_executor)
            if reference_run is None:
                raise RuntimeError(
                    f"the sequential executor refused check_executor's set "
                    f"{conformance_set.name!r}. This is a fault of check_executor, not of the "
                    "executor"
                )
            conformance_set.check_reference(reference_run.outcomes)
            conformance_set.check_agreement(executor.name, executor_run, reference_run)
            sets_run.append(conformance_set.name)
    _require(
        bool(sets_run),
        f"executor {executor.name!r} cannot run any of check_executor's sets of evaluation "
        "points. Its check must accept at least one of them",
    )

Dispatch registries

A dispatch registry holds named methods and selects one for a call by the types of its arguments. It ranks the methods that admit a call by five criteria, in decreasing precedence:

  1. Floor status: a method that declares is_floor is a fallback, and it ranks after every method that does not, whatever their exactness and priority.
  2. Exactness: exact methods rank before approximate ones.
  3. Priority: a higher priority ranks first among methods of the same floor status and exactness, and a method whose priority is None runs only when a call names it.
  4. Specificity: the method whose declared types are closest to the arguments' classes ranks first.
  5. Registration order: the method registered first ranks first.

The registry runs the first method in this order whose check reports the call feasible. set_priorities re-ranks the methods of a registry at runtime and keeps each method's exactness and floor status.

probpipe.inference.BaseDispatchRegistry(*, name='', description='')

Bases: ABC

Registry of dispatch methods for one operation.

register adds a method, check reports which method a call would run, execute runs it, set_priorities re-ranks at runtime, and list_methods lists the methods in selection order. The registry reads a method's name, exact, priority, is_floor, supported_types(), and description once, at registration, and validates them before it changes; ranking, filtering, and reporting then use that registration, so a method mutated afterwards changes nothing.

Automatic selection admits the methods whose supported_types() admit the call's arguments and whose priority is not None, keeps only the exact ones under exact_only=True, and runs the first whose check establishes feasibility, in this selection order:

  1. every method that is not a floor before every floor;
  2. exact methods before approximate ones;
  3. priority among methods that agree on the first two criteria, higher first;
  4. specificity: the smaller distance _distance reports, which favors the method whose declared types are closest to the arguments' classes in method-resolution order;
  5. registration order.

A floor is a method that declares is_floor: a fallback on its supported types, which a call tries only after every other candidate, whatever their exactness and priority. The other four criteria order the floors among themselves as they order the other methods. Since set_priorities changes neither exactness nor floor status, it moves a method only among the methods that agree with it on both.

The first three criteria are the method's rank, which _rank computes and list_methods follows; specificity depends on the call's arguments, so only a call applies it.

A registry implements SupportsRegistryCataloging through name, description, kind, entry_summaries, and describe_entry. Constructing a registry does not catalog it: registry_catalog.register(registry) does, and it requires a non-empty name.

Everything that does not depend on how many arguments select the method is implemented here, admission and ranking included; an arity subclass supplies the four hooks _cache_key, _validate_supported_types, _distance, and _format_key.

Parameters:

Name Type Description Default
name str

The registry's name in the registry catalog; empty for a registry that is not cataloged.

''
description str

A one-line description, which the registry catalog shows.

''
Notes

name and description are read-only after construction, so the name a registry is cataloged under stays its name.

Source code in probpipe/core/_dispatch.py
def __init__(self, *, name: str = "", description: str = "") -> None:
    self._name = name
    self._description = description
    self._registrations: list[_Registration[M]] = []
    self._by_name: dict[str, _Registration[M]] = {}
    self._priority_overrides: dict[str, int | None] = {}
    self._type_cache: dict[Any, list[_Registration[M]]] = {}
    self._cache_token = abc.get_cache_token()

name property

The registry's name in the registry catalog; empty for a registry that is not cataloged.

description property

A one-line description of the registry, which the registry catalog shows.

kind property

"dispatch", the catalog kind of every dispatch registry.

register(method)

Register a method.

The method's name, exact, priority, is_floor, supported_types(), and description are read here, once, and validated before the registry changes, so a rejected method leaves it as it was.

Parameters:

Name Type Description Default
method M

The method to register.

required

Raises:

Type Description
TypeError

If method.name is not a str; if method.exact or method.is_floor is not a bool; if method.priority is not an int or None, a bool included; if method.supported_types() does not have the registry's arity shape, or lists a class whose membership follows an instance's declaration rather than its class, such as NumericDistribution, which matching by class would miss; or if method.description is not a str.

ValueError

If method.name is empty or already registered.

Source code in probpipe/core/_dispatch.py
def register(self, method: M) -> None:
    """Register a method.

    The method's ``name``, ``exact``, ``priority``, ``is_floor``,
    ``supported_types()``, and ``description`` are read here, once, and
    validated before the registry changes, so a rejected method leaves it
    as it was.

    Parameters
    ----------
    method : M
        The method to register.

    Raises
    ------
    TypeError
        If ``method.name`` is not a ``str``; if ``method.exact`` or
        ``method.is_floor`` is not a ``bool``; if ``method.priority`` is
        not an ``int`` or ``None``, a ``bool`` included; if
        ``method.supported_types()`` does not
        have the registry's arity shape, or lists a class whose
        membership follows an instance's declaration rather than its class,
        such as ``NumericDistribution``, which matching by class would miss;
        or if ``method.description`` is not a ``str``.
    ValueError
        If ``method.name`` is empty or already registered.
    """
    name = method.name
    if not isinstance(name, str):
        raise TypeError(f"method name must be a string, got {name!r}")
    if not name:
        raise ValueError("method name must be a non-empty string, got ''")
    if name in self._by_name:
        raise ValueError(f"a method named {name!r} is already registered")
    exact = method.exact
    if type(exact) is not bool:
        raise TypeError(f"method {name!r} must declare exact as a bool, got {exact!r}")
    priority = _validated_priority(name, method.priority)
    is_floor = method.is_floor
    if type(is_floor) is not bool:
        raise TypeError(f"method {name!r} must declare is_floor as a bool, got {is_floor!r}")
    supported_types = method.supported_types()
    self._validate_supported_types(name, supported_types)
    _refuse_declaration_markers(name, supported_types)
    description = method.description
    if not isinstance(description, str):
        raise TypeError(
            f"method {name!r} must declare description as a str, got {description!r}"
        )
    registration = _Registration(
        method=method,
        name=name,
        exact=exact,
        priority=priority,
        supported_types=supported_types,
        index=len(self._registrations),
        is_floor=is_floor,
        description=description,
    )
    self._registrations.append(registration)
    self._by_name[name] = registration
    self._sort_registrations()

set_priorities(priorities=None, /, **kwargs)

Override the rank of one or more methods.

Overrides are recorded on the registry and never mutate a method. An override changes neither exactness nor floor status, so it never lifts an approximate method above an exact one or a floor above a method that is not one. A move between None and an integer emits a UserWarning, since it changes whether the method participates in automatic selection. When an error is raised, nothing is applied.

Parameters:

Name Type Description Default
priorities mapping of str to int or None

New priorities by method name; None makes a method opt-in-only. This form accepts names that are not Python identifiers.

None
**kwargs int or None

New priorities by method name, as keywords.

{}

Raises:

Type Description
ValueError

If a name appears both in priorities and as a keyword.

KeyError

If a name is not registered.

TypeError

If a value is not an int or None, a bool included.

Source code in probpipe/core/_dispatch.py
def set_priorities(
    self,
    priorities: Mapping[str, int | None] | None = None,
    /,
    **kwargs: int | None,
) -> None:
    """Override the rank of one or more methods.

    Overrides are recorded on the registry and never mutate a method. An
    override changes neither exactness nor floor status, so it never lifts
    an approximate method above an exact one or a floor above a method
    that is not one. A move between ``None`` and an integer
    emits a ``UserWarning``, since it changes whether the method
    participates in automatic selection. When an error is raised, nothing
    is applied.

    Parameters
    ----------
    priorities : mapping of str to int or None, optional
        New priorities by method name; ``None`` makes a method
        opt-in-only. This form accepts names that are not Python
        identifiers.
    **kwargs : int or None
        New priorities by method name, as keywords.

    Raises
    ------
    ValueError
        If a name appears both in ``priorities`` and as a keyword.
    KeyError
        If a name is not registered.
    TypeError
        If a value is not an ``int`` or ``None``, a ``bool`` included.
    """
    overrides: dict[str, int | None] = dict(priorities or {})
    for name, value in kwargs.items():
        if name in overrides:
            raise ValueError(f"method {name!r} is given both in the mapping and as a keyword")
        overrides[name] = value
    for name, value in overrides.items():
        if name not in self._by_name:
            raise KeyError(self._unknown(name))
        _validated_priority(name, value)
    for name, new_priority in overrides.items():
        old_priority = self._effective_priority(self._by_name[name])
        if (old_priority is None) != (new_priority is None):
            effect = (
                "automatic dispatch can now select it"
                if old_priority is None
                else f"it now runs only when requested with method={name!r}"
            )
            warnings.warn(
                f"method {name!r} changed from priority {old_priority} to {new_priority}, "
                f"so {effect}",
                UserWarning,
                stacklevel=2,
            )
    self._priority_overrides.update(overrides)
    self._sort_registrations()

get_method(name)

Look up a method by name.

Parameters:

Name Type Description Default
name str

A registered method name.

required

Returns:

Type Description
M

The registered method.

Raises:

Type Description
KeyError

If no method is registered under name.

Source code in probpipe/core/_dispatch.py
def get_method(self, name: str) -> M:
    """Look up a method by name.

    Parameters
    ----------
    name : str
        A registered method name.

    Returns
    -------
    M
        The registered method.

    Raises
    ------
    KeyError
        If no method is registered under ``name``.
    """
    try:
        return self._by_name[name].method
    except KeyError:
        raise KeyError(self._unknown(name)) from None

list_methods()

Every registered method name, ranked by floor status, exactness, priority, and registration order.

Returns:

Type Description
list of str

The names in the order automatic selection considers them before type specificity, which depends on the arguments; an opt-in-only method follows the ranked methods of its floor status and exactness. The listing does not say what a call would run; check does.

Source code in probpipe/core/_dispatch.py
def list_methods(self) -> list[str]:
    """Every registered method name, ranked by floor status, exactness, priority, and registration order.

    Returns
    -------
    list of str
        The names in the order automatic selection considers them before
        type specificity, which depends on the arguments; an opt-in-only
        method follows the ranked methods of its floor status and
        exactness. The listing does not say what a call would run;
        :meth:`check` does.
    """
    return [registration.name for registration in self._registrations]

entry_summaries()

One EntrySummary per method, in list_methods order.

Returns:

Type Description
list of EntrySummary

Each method's registered name, exactness, floor status, supported_types(), and description, its defining module, and its effective priority, a set_priorities override included.

Source code in probpipe/core/_dispatch.py
def entry_summaries(self) -> list[EntrySummary]:
    """One :class:`~probpipe.core._catalog.EntrySummary` per method, in :meth:`list_methods` order.

    Returns
    -------
    list of EntrySummary
        Each method's registered name, exactness, floor status,
        ``supported_types()``, and description, its defining module, and
        its effective priority, a :meth:`set_priorities` override
        included.
    """
    return [self._summary(registration) for registration in self._registrations]

describe_entry(name)

The EntrySummary of the method name.

Parameters:

Name Type Description Default
name str

A registered method name.

required

Returns:

Type Description
EntrySummary

The method's summary, as entry_summaries reports it.

Raises:

Type Description
KeyError

If no method is registered under name.

Source code in probpipe/core/_dispatch.py
def describe_entry(self, name: str) -> EntrySummary:
    """The :class:`~probpipe.core._catalog.EntrySummary` of the method *name*.

    Parameters
    ----------
    name : str
        A registered method name.

    Returns
    -------
    EntrySummary
        The method's summary, as :meth:`entry_summaries` reports it.

    Raises
    ------
    KeyError
        If no method is registered under *name*.
    """
    try:
        registration = self._by_name[name]
    except KeyError:
        raise KeyError(self._unknown(name)) from None
    return self._summary(registration)

check(*args, method=None, exact_only=False, **kwargs)

Report which method a call would run, without running anything.

A method= name bypasses the type pre-filter, not the arity: the positional arguments are validated before the named method's check runs.

Parameters:

Name Type Description Default
*args Any

Positional arguments of the call; the dispatch key is computed from them.

()
method str or None

A registered method name to probe instead of auto-selecting.

None
exact_only bool

If True, approximate methods are excluded.

False
**kwargs Any

Keyword arguments of the call, passed to each method's check.

{}

Returns:

Type Description
MethodInfo

Under auto-selection, the report of the first candidate in selection order whose check is feasible or unresolved, so an unresolved candidate ranked above a feasible one is the one reported. When no candidate is feasible, an infeasible report that names no method and whose description lists every method tried. With method, that method's report, or an infeasible report when exact_only excludes it.

Raises:

Type Description
ResolutionError

If method is not a registered name.

TypeError

If there are fewer positional arguments than the registry's arity requires, none included.

Source code in probpipe/core/_dispatch.py
def check(
    self,
    *args: Any,
    method: str | None = None,
    exact_only: bool = False,
    **kwargs: Any,
) -> MethodInfo:
    """Report which method a call would run, without running anything.

    A ``method=`` name bypasses the type pre-filter, not the arity: the
    positional arguments are validated before the named method's
    ``check`` runs.

    Parameters
    ----------
    *args : Any
        Positional arguments of the call; the dispatch key is computed
        from them.
    method : str or None
        A registered method name to probe instead of auto-selecting.
    exact_only : bool
        If ``True``, approximate methods are excluded.
    **kwargs : Any
        Keyword arguments of the call, passed to each method's ``check``.

    Returns
    -------
    MethodInfo
        Under auto-selection, the report of the first candidate in
        selection order whose ``check`` is feasible or unresolved, so an
        unresolved candidate ranked above a feasible one is the one
        reported. When no candidate is feasible, an infeasible report
        that names no method and whose ``description`` lists every method
        tried. With ``method``, that method's report, or an infeasible
        report when ``exact_only`` excludes it.

    Raises
    ------
    ResolutionError
        If ``method`` is not a registered name.
    TypeError
        If there are fewer positional arguments than the registry's arity
        requires, none included.
    """
    key = self._cache_key(args)
    if method is not None:
        named = self._named(method)
        if not self._passes_exact_only(named, exact_only):
            return MethodInfo(
                feasible=False,
                description=_approximate(method),
                method_name=method,
                exact=named.exact,
            )
        return self._report(named, named.method.check(*args, **kwargs))
    tried: list[str] = []
    lead = ""
    for candidate in self._candidates(key, exact_only):
        info = self._report(candidate, candidate.method.check(*args, **kwargs))
        if info.feasible is not False:
            return info
        tried.append(f"{candidate.name}: {info.description or 'infeasible'}")
        if info.actionable and not lead:
            lead = info.description
    return MethodInfo(
        feasible=False,
        description=self._no_method_message(key, tried, exact_only, listing=False, lead=lead),
    )

execute(*args, method=None, exact_only=False, **kwargs)

Run the selected method and return its result.

Under auto-selection the first feasible candidate in selection order runs. A method= name bypasses the type pre-filter, not the arity. An exception raised by a method's check or execute propagates unchanged, and no other method is tried after it.

Parameters:

Name Type Description Default
*args Any

Positional arguments of the call; the dispatch key is computed from them, and they are passed to the selected method.

()
method str or None

A registered method name to run instead of auto-selecting.

None
exact_only bool

If True, approximate methods are excluded.

False
**kwargs Any

Keyword arguments of the call, passed to the selected method's check and execute.

{}

Returns:

Type Description
Any

The result of the selected method's execute.

Raises:

Type Description
ResolutionError

If no candidate is feasible; if the first candidate that is not infeasible is unresolved; or if method names a method that is not registered, is infeasible, or is approximate while exact_only is True.

TypeError

If there are fewer positional arguments than the registry's arity requires, none included.

Source code in probpipe/core/_dispatch.py
def execute(
    self,
    *args: Any,
    method: str | None = None,
    exact_only: bool = False,
    **kwargs: Any,
) -> Any:
    """Run the selected method and return its result.

    Under auto-selection the first feasible candidate in selection order
    runs. A ``method=`` name bypasses the type pre-filter, not the arity.
    An exception raised by a method's ``check`` or ``execute`` propagates
    unchanged, and no other method is tried after it.

    Parameters
    ----------
    *args : Any
        Positional arguments of the call; the dispatch key is computed
        from them, and they are passed to the selected method.
    method : str or None
        A registered method name to run instead of auto-selecting.
    exact_only : bool
        If ``True``, approximate methods are excluded.
    **kwargs : Any
        Keyword arguments of the call, passed to the selected method's
        ``check`` and ``execute``.

    Returns
    -------
    Any
        The result of the selected method's ``execute``.

    Raises
    ------
    ResolutionError
        If no candidate is feasible; if the first candidate that is not
        infeasible is unresolved; or if ``method`` names a method that is
        not registered, is infeasible, or is approximate while
        ``exact_only`` is ``True``.
    TypeError
        If there are fewer positional arguments than the registry's arity
        requires, none included.
    """
    cache_key = self._cache_key(args)
    if method is not None:
        named = self._named(method)
        if not self._passes_exact_only(named, exact_only):
            raise ResolutionError(_approximate(method))
        info = named.method.check(*args, **kwargs)
        if info.feasible is None:
            raise ResolutionError(_unresolved(method, info.pending))
        if not info.feasible:
            raise ResolutionError(f"method {method!r} does not apply: {info.description}")
        return self._run_selected(named, args, kwargs)
    tried: list[str] = []
    lead = ""
    for candidate in self._candidates(cache_key, exact_only):
        info = candidate.method.check(*args, **kwargs)
        if info.feasible is None:
            raise ResolutionError(_unresolved(candidate.name, info.pending))
        if info.feasible is True:
            return self._run_selected(candidate, args, kwargs)
        tried.append(f"{candidate.name}: {info.description or 'infeasible'}")
        if info.actionable and not lead:
            lead = info.description
    raise ResolutionError(self._no_method_message(cache_key, tried, exact_only, lead=lead))

probpipe.inference.UnaryDispatchRegistry(*, name='', description='')

Bases: BaseDispatchRegistry[M]

Dispatches on the type of the first positional argument.

Source code in probpipe/core/_dispatch.py
def __init__(self, *, name: str = "", description: str = "") -> None:
    self._name = name
    self._description = description
    self._registrations: list[_Registration[M]] = []
    self._by_name: dict[str, _Registration[M]] = {}
    self._priority_overrides: dict[str, int | None] = {}
    self._type_cache: dict[Any, list[_Registration[M]]] = {}
    self._cache_token = abc.get_cache_token()

probpipe.inference.BinaryDispatchRegistry(*, name='', description='')

Bases: BaseDispatchRegistry[M]

Dispatches on the joint type of the first two positional arguments.

A method matches when the left type is a subclass of one of its left types and the right type of one of its right types.

Source code in probpipe/core/_dispatch.py
def __init__(self, *, name: str = "", description: str = "") -> None:
    self._name = name
    self._description = description
    self._registrations: list[_Registration[M]] = []
    self._by_name: dict[str, _Registration[M]] = {}
    self._priority_overrides: dict[str, int | None] = {}
    self._type_cache: dict[Any, list[_Registration[M]]] = {}
    self._cache_token = abc.get_cache_token()

probpipe.inference.BaseDispatchMethod

Bases: ABC

Abstract base for all pluggable dispatch methods.

A subclass declares a unique name, whether it is exact, the supported_types the registry's structural pre-filter admits, and check / execute; priority, is_floor, and description have defaults. The type parameter is the shape of supported_types. UnaryDispatchMethod and BinaryDispatchMethod fix it, so an implementation subclasses one of those and never spells the parameter.

A subclass overrides each declaration as a property, and a declaration may differ between instances, as when one class registers two methods under names, priorities, and descriptions its constructor receives. A registry reads every declaration once, when the method is registered.

name abstractmethod property

Unique identifier for this method, for example 'blackjax_nuts'.

exact abstractmethod property

Whether the result denotes the requested mathematical object.

True for an equivalent representation or an exact draw in law; False for a stand-in, such as a finite Monte Carlo output or a moment-matched family. Declared once and fixed for the method's life.

priority property

Rank among the methods of the same exactness and floor status, higher first.

None, the default, is opt-in-only: excluded from automatic selection and reachable only by name.

is_floor property

Whether the method is a floor, a fallback ranked after every method that is not one.

A floor ranks after every other method its registry admits for a call, whatever their exactness and priority; among the floors, exactness, priority, specificity, and registration order apply as they do among the other methods. False by default. Declared once and fixed for the method's life, as exact is.

description property

A one-line description, which the registry catalog shows; empty by default.

supported_types() abstractmethod

Types admitted by the registry's structural pre-filter.

Concrete classes, matched by issubclass; a protocol with non-method members does not work there and belongs in check. The shape is the type parameter: a tuple of classes for a unary method, a (left_types, right_types) pair of them for a binary one.

Source code in probpipe/core/_dispatch.py
@abstractmethod
def supported_types(self) -> SupportedTypesT:
    """Types admitted by the registry's structural pre-filter.

    Concrete classes, matched by ``issubclass``; a protocol with
    non-method members does not work there and belongs in ``check``.
    The shape is the type parameter: a tuple of classes for a unary
    method, a ``(left_types, right_types)`` pair of them for a binary
    one.
    """
    ...

check(*args, **kwargs) abstractmethod

Probe feasibility for a call without significant computation.

Source code in probpipe/core/_dispatch.py
@abstractmethod
def check(self, *args: Any, **kwargs: Any) -> Feasibility:
    """Probe feasibility for a call without significant computation."""
    ...

execute(*args, **kwargs) abstractmethod

Run the method and return the result.

Source code in probpipe/core/_dispatch.py
@abstractmethod
def execute(self, *args: Any, **kwargs: Any) -> Any:
    """Run the method and return the result."""
    ...

probpipe.inference.UnaryDispatchMethod

Bases: BaseDispatchMethod[UnarySupportedTypes]

Dispatch method whose first argument determines admission.

probpipe.inference.BinaryDispatchMethod

Bases: BaseDispatchMethod[BinarySupportedTypes]

Dispatch method whose first two arguments determine admission.

probpipe.inference.Feasibility(feasible, description='', pending=tuple(), actionable=False) dataclass

What a method's check reports about one call.

Attributes:

Name Type Description
feasible bool or None

True if the method applies, False if it does not, and None if the probe could not determine feasibility.

description str

Describes why method does not apply if feasible is False.

pending tuple of str

One entry per missing declaration, each describing what is required for the method to be feasible. Non-empty exactly when feasible is None.

actionable bool

True when the method accepts this kind of argument and fails on a detail of the call that the caller can fix, such as a field name the argument does not have. A message that lists several reports leads with an actionable one. Only an infeasible report is actionable.

Raises:

Type Description
TypeError

If feasible is anything but a bool or None. Registries compare it by identity, so a truthy or falsy stand-in such as 1 or "" would make check and execute disagree.

ValueError

If pending is empty while feasible is None, or non-empty while it is not, or if actionable is set on a report that is not infeasible.

unresolved property

True when feasible is None.

__repr__()

The feasibility, positionally, then each other attribute that differs from its default.

Source code in probpipe/core/_dispatch.py
def __repr__(self) -> str:
    """The feasibility, positionally, then each other attribute that differs from its default."""
    return call_repr(type(self).__name__, [repr(self.feasible)], self._repr_arguments())

probpipe.inference.MethodInfo(feasible, description='', pending=tuple(), actionable=False, method_name=None, exact=None) dataclass

Bases: Feasibility

Used by a registry to describe a method's feasibility plus its registration information.

The method_name and exact attributes are both None exactly when no method could be selected, which is the infeasible report that lists every method tried; a feasible or unresolved report names its method.

Attributes:

Name Type Description
method_name str or None

The selected method's name.

exact bool or None

The selected method's declared exactness.

Raises:

Type Description
ValueError

If exactly one of method_name and exact is None; if both are None while feasible is not False; or on a condition Feasibility rejects.

probpipe.inference.UnarySupportedTypes = tuple[type, ...]

The supported_types of a unary dispatch method: a tuple of classes.

probpipe.inference.BinarySupportedTypes = tuple[tuple[type, ...], tuple[type, ...]]

The supported_types of a binary dispatch method: a pair of tuples of classes.

The registry catalog

registry_catalog lists every cataloged registry and its entries, where an entry is one registered item of a registry, such as an inference method or a converter. It answers three queries:

  • print(registry_catalog): one row per registry, with its kind, its entry count, and its description;
  • registry_catalog.describe("inference"): one registry's entries in its own order, each with its priority where the registry ranks its entries and its exactness where the registry declares it, with a dispatch registry's floors and its opt-in-only methods each in a section of their own;
  • registry_catalog["inference"].describe_entry("blackjax_nuts"): one entry, as an EntrySummary.

The catalog holds six registries:

  • "bijectors": the bijector factories that bijector_for selects from;
  • "converters": converter_registry;
  • "evaluation_rules": evaluation_rule_registry;
  • "executors": executor_registry;
  • "inference": inference_method_registry;
  • "operations": operation_registry.

A registry joins the catalog by implementing SupportsRegistryCataloging and by an explicit registry_catalog.register(registry), which rejects an empty or duplicate name. Constructing a registry does not catalog it, so a registry that a test builds stays out of the catalog. The catalog has no removal, so reloading a module that registers a registry, as importlib.reload or IPython's %autoreload does, raises ValueError; restart the process instead. A dispatch registry implements the protocol already, and it takes its catalog name and description at construction:

from probpipe import registry_catalog
from probpipe.inference import BinaryDispatchRegistry

kl_registry = BinaryDispatchRegistry(name="kl", description="KL divergence between two laws.")
registry_catalog.register(kl_registry)

A dispatch method may declare a one-line description property, as it declares its name, which the registry reads at registration and the catalog shows. register_bijector takes a description keyword for the same purpose.

registry_catalog = RegistryCatalog() module-attribute

The global registry catalog.

probpipe.RegistryCatalog()

A catalog of registries, keyed by registry name.

The catalog records registries and describes them, and it holds no selection state.

Examples:

>>> import probpipe
>>> "inference" in probpipe.registry_catalog
True
>>> print(probpipe.registry_catalog.describe("inference"))
inference  (dispatch) — Inference methods for condition_on, each given an inference target.
...
Source code in probpipe/core/_catalog.py
def __init__(self) -> None:
    self._registries: dict[str, SupportsRegistryCataloging] = {}

register(registry)

Add registry to the catalog under its name.

The catalog has no removal, so a name stays registered for the life of the process. A module that registers a registry when it is imported therefore raises when it is reloaded, as importlib.reload or IPython's %autoreload does after an edit; restart the process instead.

Parameters:

Name Type Description Default
registry SupportsRegistryCataloging

The registry to add.

required

Raises:

Type Description
TypeError

If registry does not implement SupportsRegistryCataloging, or its name is not a str, as when a registry class is passed in place of an instance.

ValueError

If registry.name is empty or already registered.

Source code in probpipe/core/_catalog.py
def register(self, registry: SupportsRegistryCataloging) -> None:
    """Add *registry* to the catalog under its ``name``.

    The catalog has no removal, so a name stays registered for the life of
    the process. A module that registers a registry when it is imported
    therefore raises when it is reloaded, as ``importlib.reload`` or
    IPython's ``%autoreload`` does after an edit; restart the process
    instead.

    Parameters
    ----------
    registry : SupportsRegistryCataloging
        The registry to add.

    Raises
    ------
    TypeError
        If *registry* does not implement
        :class:`SupportsRegistryCataloging`, or its ``name`` is not a
        ``str``, as when a registry class is passed in place of an
        instance.
    ValueError
        If ``registry.name`` is empty or already registered.
    """
    if isinstance(registry, type) or not isinstance(registry, SupportsRegistryCataloging):
        raise TypeError(
            "registry_catalog.register takes a registry instance that implements "
            f"SupportsRegistryCataloging, got {registry!r}"
        )
    name = registry.name
    if not isinstance(name, str):
        raise TypeError(f"a cataloged registry's name must be a str, got {name!r}")
    if not name:
        fix = (
            '; pass name="..." when you construct the registry'
            if registry.kind == "dispatch"
            else ""
        )
        raise ValueError(f"cannot catalog a registry whose name is empty{fix}")
    if name in self._registries:
        raise ValueError(
            f"cannot catalog a second registry named {name!r}: "
            "the catalog already holds one under that name"
        )
    self._registries[name] = registry

__getitem__(name)

The registry named name.

Parameters:

Name Type Description Default
name str

A registered registry name.

required

Returns:

Type Description
SupportsRegistryCataloging

The registry itself, not a copy.

Raises:

Type Description
KeyError

If no registry is registered under name.

Source code in probpipe/core/_catalog.py
def __getitem__(self, name: str) -> SupportsRegistryCataloging:
    """The registry named *name*.

    Parameters
    ----------
    name : str
        A registered registry name.

    Returns
    -------
    SupportsRegistryCataloging
        The registry itself, not a copy.

    Raises
    ------
    KeyError
        If no registry is registered under *name*.
    """
    try:
        return self._registries[name]
    except KeyError:
        raise KeyError(
            unknown_names("registry", [name], self.names(), plural="registries")
        ) from None

__contains__(name)

True when name is a registered registry name.

Source code in probpipe/core/_catalog.py
def __contains__(self, name: object) -> bool:
    """``True`` when *name* is a registered registry name."""
    return isinstance(name, str) and name in self._registries

names()

Every registry name, sorted.

Source code in probpipe/core/_catalog.py
def names(self) -> list[str]:
    """Every registry name, sorted."""
    return sorted(self._registries)

list()

One RegistryInfo per registry, sorted by name.

Source code in probpipe/core/_catalog.py
def list(self) -> list[RegistryInfo]:
    """One :class:`RegistryInfo` per registry, sorted by name."""
    return [
        RegistryInfo(
            name=registry.name,
            description=registry.description,
            kind=registry.kind,
            entry_count=len(registry.entry_summaries()),
        )
        for registry in (self._registries[name] for name in self.names())
    ]

describe(name)

A readable summary of the registry named name.

The first line names the registry, its kind, and its description, and each entry follows on a line of its own: its priority, or - for None; its exactness, where the registry declares one; its name; its description; and its module. The priority column is left out when every entry's priority is None, as in a registry that does not rank its entries, and the exactness column when no entry declares one.

The entries follow the registry's entry_summaries order, which for a dispatch registry is its selection order before type specificity. A dispatch registry's entries are listed in up to three sections: the ranked entries that are not floors, the ranked floors, and the opt-in-only entries. Any other registry's entries are listed together.

Parameters:

Name Type Description Default
name str

A registered registry name.

required

Returns:

Type Description
str

The summary.

Raises:

Type Description
KeyError

If no registry is registered under name.

Source code in probpipe/core/_catalog.py
def describe(self, name: str) -> str:
    """A readable summary of the registry named *name*.

    The first line names the registry, its kind, and its description, and
    each entry follows on a line of its own: its priority, or ``-`` for
    ``None``; its exactness, where the registry declares one; its name; its
    description; and its module. The priority column is left out when
    every entry's priority is ``None``, as in a registry that does not
    rank its entries, and the exactness column when no entry declares
    one.

    The entries follow the registry's
    :meth:`~SupportsRegistryCataloging.entry_summaries` order, which for a
    dispatch registry is its selection order before type specificity. A
    dispatch registry's entries are listed in up to three sections: the
    ranked entries that are not floors, the ranked floors, and the
    opt-in-only entries. Any other registry's entries are listed together.

    Parameters
    ----------
    name : str
        A registered registry name.

    Returns
    -------
    str
        The summary.

    Raises
    ------
    KeyError
        If no registry is registered under *name*.
    """
    registry = self[name]
    summaries = registry.entry_summaries()
    show_exactness = any(summary.exact is not None for summary in summaries)
    if any(summary.priority is not None for summary in summaries):
        priority_width = max(len(_priority_text(summary)) for summary in summaries)
    else:
        priority_width = 0
    if registry.kind == "dispatch":
        ranked = [summary for summary in summaries if not summary.is_opt_in_only]
        sections = [
            (
                "Auto-dispatched, in selection order:",
                [summary for summary in ranked if not summary.is_floor],
            ),
            (
                "Floors, after every other entry:",
                [summary for summary in ranked if summary.is_floor],
            ),
            (
                "Opt-in only (run by method=...):",
                [summary for summary in summaries if summary.is_opt_in_only],
            ),
        ]
    else:
        sections = [("Entries:", summaries)]
    header = f"{registry.name}  ({registry.kind})"
    if registry.description:
        header += f" — {registry.description}"
    lines = [header, ""]
    for label, entries in sections:
        if not entries:
            continue
        lines.append(f"  {label}")
        lines.extend(
            _format_entry_line(entry, show_exactness, priority_width) for entry in entries
        )
        lines.append("")
    if not summaries:
        lines.append("  (no entries registered)")
    return "\n".join(lines).rstrip()

__repr__()

One row per registry: its name, its kind, its entry count, and its description.

Source code in probpipe/core/_catalog.py
def __repr__(self) -> str:
    """One row per registry: its name, its kind, its entry count, and its description."""
    if not self._registries:
        return "RegistryCatalog(empty)"
    infos = self.list()
    name_width = max(len(info.name) for info in infos)
    kind_width = max(len(info.kind) for info in infos)
    rows = [
        f"  {info.name:<{name_width}}  {info.kind:<{kind_width}}  "
        f"{info.entry_count:>3} {'entry' if info.entry_count == 1 else 'entries'}"
        + (f"  — {info.description}" if info.description else "")
        for info in infos
    ]
    return "RegistryCatalog (\n" + "\n".join(rows) + "\n)"

probpipe.SupportsRegistryCataloging

Bases: Protocol

The members a registry implements to be cataloged.

name, description, and kind are read-only, so a registry may implement each as a property or as a plain class attribute.

Notes

The protocol states a registry's identity and its entries and states nothing about selection, so a registry that selects by other means, such as the bijector factory's lookup by constraint instance and then by constraint class, is cataloged as it is. Satisfying the protocol does not place a registry in the catalog; RegistryCatalog.register does.

name property

The registry's name, unique within the catalog.

description property

A one-line description of the registry.

kind property

The registry's kind, such as "dispatch", "operation", or "factory".

The kind is a string, so a plugin can introduce one.

entry_summaries()

One summary per entry, in the registry's order.

Returns:

Type Description
list of EntrySummary

The entries in selection order before type specificity for a dispatch registry, registration order for the operation registry, and name order for the bijector factory.

Source code in probpipe/core/_catalog.py
def entry_summaries(self) -> list[EntrySummary]:
    """One summary per entry, in the registry's order.

    Returns
    -------
    list of EntrySummary
        The entries in selection order before type specificity for a
        dispatch registry, registration order for the operation registry,
        and name order for the bijector factory.
    """
    ...

describe_entry(name)

The summary of the entry named name.

Parameters:

Name Type Description Default
name str

An entry's name within the registry.

required

Returns:

Type Description
EntrySummary

The entry's summary, as entry_summaries reports it.

Raises:

Type Description
KeyError

If the registry holds no entry named name.

Source code in probpipe/core/_catalog.py
def describe_entry(self, name: str) -> EntrySummary:
    """The summary of the entry named *name*.

    Parameters
    ----------
    name : str
        An entry's name within the registry.

    Returns
    -------
    EntrySummary
        The entry's summary, as :meth:`entry_summaries` reports it.

    Raises
    ------
    KeyError
        If the registry holds no entry named *name*.
    """
    ...

probpipe.EntrySummary(name, priority, supported_types=(), description='', module_path='', exact=None, is_floor=False) dataclass

The catalog's record of one entry of a registry.

An entry is one registered item, such as an inference method, a converter, an operation, or a bijector factory. A registry returns these from SupportsRegistryCataloging.entry_summaries and SupportsRegistryCataloging.describe_entry.

Attributes:

Name Type Description
name str

The entry's name, unique within its registry.

priority int or None

The entry's effective rank among the entries of the same floor status and exactness, higher first. In a dispatch registry None is opt-in-only. A registry that does not rank its entries, such as the bijector factory or the operation registry, reports None for every entry.

supported_types tuple

What the entry admits, in its registry's form: a tuple of classes for a unary dispatch registry, a (left_types, right_types) pair for a binary one, the kinds of the first operand for an operation, and the constraint key in a 1-tuple for a bijector factory.

description str

A one-line description of the entry, empty when it declares none.

module_path str

The module that defines the entry.

exact bool or None

The entry's declared exactness, or None when its registry declares no exactness per entry.

is_floor bool

Whether the entry is a floor, a fallback that its registry ranks after every entry that is not one, whatever their exactness and priority. False for an entry of a registry that has no floors.

is_opt_in_only property

True when priority is None.

The flag applies to a registry that ranks its entries: a dispatch registry skips such an entry in automatic selection and runs it only when a call names it with method="...". A registry that does not rank its entries reports None for every entry and has no opt-in entries; RegistryCatalog.describe lists its entries together.

probpipe.RegistryInfo(name, description, kind, entry_count) dataclass

The catalog's record of one registry.

RegistryCatalog.list returns these; EntrySummary holds the detail of each entry.

Attributes:

Name Type Description
name str

The registry's name, unique within the catalog.

description str

A one-line description of the registry.

kind str

The registry's kind, such as "dispatch", "operation", or "factory".

entry_count int

The number of entries the registry holds.