AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
How a result was computed¶
An operation such as mean or condition_on computes its result by one of several routes, exactly when a formula or an exact algorithm applies and approximately otherwise.
This chapter shows how to see and choose the route an operation takes, how to make random results reproducible, and how to read the record that each result keeps of its computation.
We need it when a result must be exact, when we compare two ways of computing it, or when we report how it was obtained.
# On Google Colab, install ProbPipe; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet "probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
import jax
import jax.numpy as jnp
from probpipe import (
Normal,
ResolutionError,
condition_on,
conditional_distribution,
function,
mean,
operation_registry,
prob,
provenance_ancestors,
replay_run,
config,
sample,
workflow_run,
)
Routes¶
We use one small model throughout. The prior of a mean $\mu$ is a standard normal distribution, and given $\mu$, five measurements $y$ are independent normal draws with mean $\mu$ and standard deviation 1.
prior = Normal("mu", 0.0, 1.0, label="prior")
def y_given_mu(mu: jax.Array) -> Normal:
return Normal("y", mu * jnp.ones(5), 1.0)
likelihood = conditional_distribution(
y_given_mu, label="likelihood", given_spec=prior.event_spec
)
model = (likelihood & prior).with_label("model")
y = jnp.array([1.2, 0.4, 2.1, 1.5, 0.9])
print("outputs of the model:", list(model.event_spec.outputs))
outputs of the model: ['y', 'mu']
Each operation has a list of routes, which are its implementations, and a call selects the first route that applies.
An operation's check takes the arguments of a call and reports the route the call would take, without computing anything.
A normal distribution has a formula for its mean, so mean takes the exact route closed_form:
report = mean.check(prior)
print("route for the mean of the prior:", report.route)
print("exact:", report.exact)
route for the mean of the prior: closed_form exact: True
The model is a joint distribution built from a conditional distribution, and it has no formula for its mean.
Displayed in a notebook, the report shows every route that mean considered and the reason each one declined:
mean.check(model)
| route | method | exact | feasible | reason | |
|---|---|---|---|---|---|
| closed_form | exact | infeasible | FactoredDistribution 'model' does not implement SupportsMean | ||
| by_output | exact | exact | infeasible | the outputs ('y',) have no exact mean, but ('mu',) do | |
| selected | by_output | approximate | approximate | feasible |
- result:
OutputSpec( NumericRecordSpec( y=NumericArraySpec(shape=(5,), dtype=float32, support=real), mu=NumericArraySpec(shape=(), dtype=float32, support=real), ), )
The route by_output computes the mean of each output through its view.
The mean of mu takes the exact route closed_form, and the mean of y takes the route monte_carlo, which averages draws from the model, so the result is approximate.
The registry of operations, operation_registry, lists each operation with its operands and its routes in the order a call tries them:
print(operation_registry.describe("mean"))
mean(d, given) — primitive
The mean ``𝔼[X]`` for ``X ~ d``, a value shaped like one draw.
operands:
d: DistributionSpec, ConditionalDistributionSpec; read by the result rule
given: RecordSpec
routes, in selection order:
closed_form (capability, exact; requires SupportsMean): membership in SupportsMean suffices
by_output (structural, exactness delegated): the event is a record of several outputs, at least one of which has an exact route of its own, and the rest of which have a route together
monte_carlo (fallback, approximate): The law samples numeric draws, which average coordinatewise, or laws, which average to a mixture.
operation_registry.list() returns one summary per operation, and its name attribute gives the names of all the operations:
print("operations:", ", ".join(summary.name for summary in operation_registry.list()))
operations: convert, sample, condition_on, log_prob, unnormalized_log_prob, prob, unnormalized_prob, random_log_prob, random_unnormalized_log_prob, inverse, log_det_jacobian, joint, marginal, factor, pushforward, mixture, mean, variance, standard_deviation, cov, quantile, expectation
Choosing a route with options¶
An operation's using returns a copy of the operation with revised controls, and calling the copy applies them.
The control method names the route to take.
The mean of the prior is 0, and the route monte_carlo estimates it from draws:
with workflow_run(seed=0):
estimate = mean.using(method="monte_carlo")(prior)
finer_estimate = mean.using(method="monte_carlo", num_samples=100_000)(prior)
print("mean of mu from 1,024 draws:", round(float(estimate.raw), 4))
print("mean of mu from 100,000 draws:", round(float(finer_estimate.raw), 4))
mean of mu from 1,024 draws: -0.0036 mean of mu from 100,000 draws: 0.0028
The control num_samples sets the number of draws, which is 1,024 by default, so the second estimate is closer to 0.
For condition_on, method also names an inference method, such as blackjax_nuts, as Conditioning and inference methods shows.
The control exact_only=True refuses every approximate route.
The mean of y has no exact route, so check reports that the call is infeasible, and the call raises a ResolutionError that names the exact call on the view of mu:
exact_mean = mean.using(exact_only=True)
print("feasible with exact_only:", exact_mean.check(model).feasible)
try:
exact_mean(model)
except ResolutionError as error:
print("error:", error)
feasible with exact_only: False
error: mean: the outputs ('y',) have no exact mean, but ('mu',) do; call mean on the view of each output that does, as mean(d['mu']). Routes tried with exact_only: closed_form: FactoredDistribution 'model' does not implement SupportsMean; by_output (exact): the outputs ('y',) have no exact mean, but ('mu',) do; call mean on the view of each output that does, as mean(d['mu'])
A copy keeps the controls set on it, and options reads them.
The original operation is unchanged, and giving a control as None resets it to its default:
by_draws = mean.using(method="monte_carlo")
print("method of mean:", mean.options["method"])
print("method of the copy:", by_draws.options["method"])
print("method after the reset:", by_draws.using(method=None).options["method"])
method of mean: None method of the copy: monte_carlo method after the reset: None
A control set on an operation also governs the operations that its computation calls.
prob computes the density from log_prob, so prob.using(exact_only=True) restricts that log_prob to exact routes, and the density of the prior is exact:
density = prob.using(exact_only=True)(prior, 0.0)
print("density of the prior at 0:", density.raw)
print("exact:", density.provenance.metadata["exact"])
density of the prior at 0: 0.3989423 exact: True
A function made with @function takes the same controls.
Called on a distribution, it is evaluated at most max_evaluations times, at draws of its argument, as Functions on values and distributions explains.
For one new measurement $y_{\text{new}} \sim \text{Normal}(\mu, 1)$, the probability that it is positive is $\Phi(\mu)$:
@function
def prob_next_positive(mu: jax.Array) -> jax.Array:
return jax.scipy.stats.norm.cdf(mu)
with workflow_run(seed=0):
default_draws = prob_next_positive(prior)
more_draws = prob_next_positive.using(max_evaluations=2000)(prior)
print("draws at the default count:", default_draws.num_atoms)
print("draws with max_evaluations=2000:", more_draws.num_atoms)
draws at the default count: 256 draws with max_evaluations=2000: 2000
Reproducible draws¶
Operations take no random key.
Instead, workflow_run(seed=...) seeds every random draw inside its block, so two blocks with the same seed and the same calls give the same draws:
with workflow_run(seed=0):
first = sample(prior, sample_shape=3)
second = sample(prior, sample_shape=3)
with workflow_run(seed=0):
first_again = sample(prior, sample_shape=3)
print("first draws:", first.raw)
print("second draws in the same block:", second.raw)
print("first draws of the rerun:", first_again.raw)
first draws: [-0.9115058 -0.31258115 -0.25014585] second draws in the same block: [-1.0254986 -0.3857639 -0.13261794] first draws of the rerun: [-0.9115058 -0.31258115 -0.25014585]
The draws of a call follow from the seed and the call's position in the block.
Two calls in one block therefore get different draws, and a rerun of the block repeats both.
A call outside every workflow_run block draws from a fresh seed each time.
A random draw inside a jax.jit or jax.vmap that our own code opens raises RuntimeError, so we call the random operations outside such a transformation.
replay_run reproduces one recorded call from its result's provenance, which the next section describes.
We run the same call inside it, and it repeats the recorded draws:
with replay_run(second.provenance):
replayed = sample(prior, sample_shape=3)
print("replayed draws:", replayed.raw)
replayed draws: [-1.0254986 -0.3857639 -0.13261794]
The provenance stores the seed and the position of the call, so the replay needs no workflow_run block.
The replay checks that the call matches the recorded one, and a ReplayCompatibilityError reports a call that does not.
Provenance¶
Every result records how it was computed in its provenance. We condition the model on the measurements, which takes an approximate route because no exact method computes this posterior:
with workflow_run(seed=0):
posterior = condition_on(model, {"y": y})
record = posterior.provenance
print("label of the posterior:", posterior.label)
print("notation of the posterior:", posterior)
print("route:", record.metadata["route"])
print("method:", record.metadata["method"])
print("exact:", record.metadata["exact"])
label of the posterior: model notation of the posterior: model(mu; y) route: inference_methods method: blackjax_nuts exact: False
The provenance's metadata holds the route, the inference method that route selected, and whether the result is exact.
The posterior keeps the model's label, and its notation model(mu; y) lists its output mu and, after ;, the path y at which condition_on fixed the model.
The provenance's parents are the terms the operation consumed:
for parent in record.parents:
print(f"parent: {parent.label} ({parent.type_name})")
parent: condition_on (Operation) parent: model (FactoredDistribution) parent: model (EmpiricalDistribution)
The parents are the operation condition_on, the model, and the draws that the method blackjax_nuts returned, from which condition_on built the posterior.
A result computed from the posterior records its own step.
The mean of the posterior holds one field per output, under the output's own name, so posterior_mean["mu"] selects the mean of mu:
posterior_mean = mean(posterior)
print("posterior mean:", repr(posterior_mean))
print("posterior mean of mu:", round(float(posterior_mean["mu"].raw), 3))
print("route of the mean:", posterior_mean.provenance.metadata["route"])
print("exact:", posterior_mean.provenance.metadata["exact"])
posterior mean: NumericRecord('𝔼[mu ~ model; y]')
mu 1.0261663
posterior mean of mu: 1.026
route of the mean: closed_form
exact: True
The mean is labeled 𝔼[mu ~ model; y], which is the expectation of a draw of mu from the posterior.
It is exact for the 4,000 draws of the posterior, since the mean of a distribution on finitely many points is a weighted sum.
The approximation entered one step earlier, when the sampler drew them.
For this normal model the posterior mean is $\sum_i y_i / 6 \approx 1.017$, so the sampler's draws account for the difference of about 0.01.
provenance_ancestors follows the parents back through every step and returns a descriptor of each ancestor, whose provenance is the record of the step that produced it.
Here the forecast evaluates prob_next_positive at draws from the posterior, and its mean summarizes the result:
with workflow_run(seed=1):
forecast = prob_next_positive(posterior["mu"])
forecast_mean = mean(forecast)
print("forecast:", forecast)
print("label of its mean:", forecast_mean.label)
print("P(next measurement > 0), posterior mean:", round(float(forecast_mean.raw), 3))
steps = [forecast_mean.provenance] + [
ancestor.provenance for ancestor in provenance_ancestors(forecast_mean) if ancestor.provenance
]
for step in steps:
if "exact" in step.metadata:
metadata = step.metadata
print(f"{metadata['func']}: route {metadata['route']}, exact {metadata['exact']}")
forecast: prob_next_positive(mu ~ model; y) label of its mean: 𝔼[prob_next_positive(mu ~ model; y)] P(next measurement > 0), posterior mean: 0.829 mean: route closed_form, exact True prob_next_positive: route sampling_lift, exact False condition_on: route inference_methods, exact False
The steps print from the last back to the first.
mean is exact for the forecast's draws.
The two steps before it are approximate: the route sampling_lift evaluated prob_next_positive at 256 draws of the posterior, and blackjax_nuts drew the posterior.
The error of the forecast is therefore the error of those two steps.
The forecast displays as prob_next_positive(mu ~ model; y), which is the function applied to a draw of mu from the posterior, and its mean is labeled as the expectation of that forecast.
provenance_dag builds the same chain as a graph, which the graphviz package draws.
The default counts¶
Each function and operation that sets no max_evaluations of its own uses the default count, 256, and each that sets no num_samples uses 1,024.
config.sampling holds the two defaults, and setting one changes it for every such function, including those defined before the setting:
config.sampling.max_evaluations = 1000
with workflow_run(seed=2):
forecast_1000 = prob_next_positive(posterior["mu"])
forecast_2000 = prob_next_positive.using(max_evaluations=2000)(posterior["mu"])
print("draws at the new default:", forecast_1000.num_atoms)
print("draws of a function that sets 2000:", forecast_2000.num_atoms)
config.sampling.reset()
print("default restored:", prob_next_positive.options["max_evaluations"])
draws at the new default: 1000 draws of a function that sets 2000: 2000 default restored: 256
A count set by using takes precedence over the default.
A script can set the defaults once at its start: max_evaluations then governs every lifted function, and num_samples every monte_carlo route.
See also¶
- Operations:
mean,sample,condition_on, and the errorsResolutionErrorandMathematicalDomainError. - Registries for extensions:
operation_registryand the routes of an operation. - Workflows and reproducibility:
workflow_run,replay_run, andconfig.sampling. - Labels and provenance: the provenance record,
provenance_ancestors,provenance_dag, and the settings of how much history a provenance keeps. - Functions on values and distributions: lifting a function to a distribution.
- Conditioning and inference methods: the routes and methods of
condition_on. - Tutorial 2 and tutorial 4: the provenance of a fitted posterior and of a forecast.
- Tutorial 7: choosing an inference method with
using, andexact_only.