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:
exact: whether the result denotes the conditional law itself.InferenceMethoddeclaresexact = 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, asempirical_reweightingdoes: the posterior of an empirical prior is its atoms reweighted by the likelihood. Theexact_onlycontrol excludes the approximate methods.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:
- Robustness: how often the method gives a usable answer without tuning for the model, once its
checkpasses. - 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.
- 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.
- Diagnostics: a method that reports its failures ranks above one that fails without a signal.
- Breadth: the range of models the method applies to, which breaks ties only, since
checkdecides 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 |
{}
|
Returns:
| Type | Description |
|---|---|
Distribution
|
A normalized law over |
Source code in probpipe/operations/_condition.py
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:
- Values of the model's fields.
condition_on(model, {"y": y})gives a target whosegivenis aRecordkeyed by the fields it fixes, and whose event is the model's other fields. - Data the model takes but does not declare as fields, such as the
data block of a program.
givenis that data, as the model takes it. - Nothing. A law that is itself unnormalized, such as one built from a
log-density alone, is the target of conditioning on nothing.
givenis an emptyRecord, andjointis 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; |
Source code in probpipe/operations/_inference_target.py
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 |
required |
method
|
str
|
The inference method's name, by which the |
required |
annotations
|
DataTree or None
|
The method's diagnostics, sample statistics, and warmup draws, as
ArviZ groups of a |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If chains is empty or the chains differ in length, a draw's width is
not the |
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
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
A new converter¶
A converter moves a law to another representation.
It subclasses Converter and defines five members:
name: the name by which a call selects the converter;exact: whether the converted law is the source law in another representation;supported_types: the pair of the source types and the target types;check: the promise of a conversion as aConversionInfo, computed without converting, which leavesmethod_nameandexactfor the registry to set from the registration;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.
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
execute(source, target_type, **options)
abstractmethod
¶
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:
structural_route: an implementation that reads the operands' declared structure;capability_route: a call of a capability that one operand claims, such as_mean;registry_route: a delegation to a dispatch registry, whose selected method realizes the call;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 |
required |
applicability_checks
|
iterable of callable
|
Checks that the operation applies to a call; see |
()
|
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 |
None
|
derived_route
|
OperationRoute
|
A derived operation's composite derived route; see |
None
|
label
|
callable
|
The label rule; see |
None
|
registry
|
OperationRegistry
|
The registry to register in; |
None
|
Returns:
| Type | Description |
|---|---|
callable
|
The decorator, which returns the registered |
Raises:
| Type | Description |
|---|---|
TypeError
|
As |
ValueError
|
If the registry already has an operation of that name. |
Source code in probpipe/operations/_operation.py
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 | |
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
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; |
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
list()
¶
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
|
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
__getitem__(name)
¶
The operation registered as name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the operation's declaration, such as |
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
entry_summaries()
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
OperationSummary
|
The operation's entry as |
Raises:
| Type | Description |
|---|---|
KeyError
|
If name is not a registered operation. |
Source code in probpipe/operations/_operation.py
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; |
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, |
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;priorityandexact: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; |
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 |
required |
factory
|
callable
|
|
required |
description
|
str
|
A one-line description of the bijector, which the registry catalog
shows under |
''
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If description is not a |
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
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
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
|
|
required |
numpy_dtype
|
callable
|
|
lambda obj: _safe_numpy_dtype(dtype)
|
is_numeric
|
callable
|
|
lambda obj: True
|
to_jax
|
callable
|
|
_default_to_jax
|
to_numpy
|
callable
|
|
_default_to_numpy
|
take
|
callable
|
|
lambda obj, index: obj[index]
|
metadata
|
callable
|
|
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
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 optionchunk_sizesets 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 optionsmax_workersandchunk_size;process, which runs chunks in worker processes started under the calling process's JAX settings, with the optionsmax_workers,chunk_size, andstart_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 |
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;
|
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.
|
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
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
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 |
exact |
bool
|
|
priority |
int or None
|
Its rank in automatic selection, higher first; |
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
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
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
|
point_noun
|
str
|
The word for one evaluation point in messages, such as |
'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
|
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; |
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
traceable
property
¶
Whether JAX can trace the callable for these evaluation points; False when unknown.
__len__()
¶
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
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
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
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
__len__()
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
EvaluationOutcomes
|
One outcome per evaluation point of the chunk, in order. |
Source code in probpipe/core/_evaluation_points.py
__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
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.
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; |
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 |
Source code in probpipe/core/_evaluation_points.py
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the runs overlap or leave a gap. |
Source code in probpipe/core/_evaluation_points.py
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_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; |
__reduce__()
¶
Pickle the failure, leaving out an exception that does not survive pickling and unpickling.
Source code in probpipe/core/_evaluation_points.py
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
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:
- Floor status: a method that declares
is_flooris a fallback, and it ranks after every method that does not, whatever their exactness and priority. - Exactness: exact methods rank before approximate ones.
- Priority: a higher priority ranks first among methods of the same floor status and exactness, and a method whose priority is
Noneruns only when a call names it. - Specificity: the method whose declared types are closest to the arguments' classes ranks first.
- 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:
- every method that is not a floor before every floor;
- exact methods before approximate ones;
- priority among methods that agree on the first two criteria, higher first;
- specificity: the smaller distance
_distancereports, which favors the method whose declared types are closest to the arguments' classes in method-resolution order; - 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
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 |
ValueError
|
If |
Source code in probpipe/core/_dispatch.py
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
|
**kwargs
|
int or None
|
New priorities by method name, as keywords. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a name appears both in |
KeyError
|
If a name is not registered. |
TypeError
|
If a value is not an |
Source code in probpipe/core/_dispatch.py
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 |
Source code in probpipe/core/_dispatch.py
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;
|
Source code in probpipe/core/_dispatch.py
entry_summaries()
¶
One EntrySummary per method, in list_methods order.
Returns:
| Type | Description |
|---|---|
list of EntrySummary
|
Each method's registered name, exactness, floor status,
|
Source code in probpipe/core/_dispatch.py
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 |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no method is registered under name. |
Source code in probpipe/core/_dispatch.py
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 |
False
|
**kwargs
|
Any
|
Keyword arguments of the call, passed to each method's |
{}
|
Returns:
| Type | Description |
|---|---|
MethodInfo
|
Under auto-selection, the report of the first candidate in
selection order whose |
Raises:
| Type | Description |
|---|---|
ResolutionError
|
If |
TypeError
|
If there are fewer positional arguments than the registry's arity requires, none included. |
Source code in probpipe/core/_dispatch.py
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 |
False
|
**kwargs
|
Any
|
Keyword arguments of the call, passed to the selected method's
|
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The result of the selected method's |
Raises:
| Type | Description |
|---|---|
ResolutionError
|
If no candidate is feasible; if the first candidate that is not
infeasible is unresolved; or if |
TypeError
|
If there are fewer positional arguments than the registry's arity requires, none included. |
Source code in probpipe/core/_dispatch.py
probpipe.inference.UnaryDispatchRegistry(*, name='', description='')
¶
Bases: BaseDispatchRegistry[M]
Dispatches on the type of the first positional argument.
Source code in probpipe/core/_dispatch.py
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
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
check(*args, **kwargs)
abstractmethod
¶
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
|
|
description |
str
|
Describes why method does not apply if |
pending |
tuple of str
|
One entry per missing declaration, each describing what is required
for the method to be feasible. Non-empty exactly when |
actionable |
bool
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
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 |
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 anEntrySummary.
The catalog holds six registries:
"bijectors": the bijector factories thatbijector_forselects 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
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
|
ValueError
|
If |
Source code in probpipe/core/_catalog.py
__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
__contains__(name)
¶
names()
¶
list()
¶
One RegistryInfo per registry, sorted by name.
Source code in probpipe/core/_catalog.py
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
__repr__()
¶
One row per registry: its name, its kind, its entry count, and its description.
Source code in probpipe/core/_catalog.py
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
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 |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the registry holds no entry named name. |
Source code in probpipe/core/_catalog.py
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 |
supported_types |
tuple
|
What the entry admits, in its registry's form: a tuple of classes for a
unary dispatch registry, a |
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 |
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.
|
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 |
entry_count |
int
|
The number of entries the registry holds. |