AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Inference methods¶
This page documents the inference methods a user calls directly, the functions of amortized and sequential inference, and the registry from which condition_on selects a method.
condition_on itself is on Operations, and MinibatchedDistribution, from which the stochastic-gradient methods estimate gradients, is on Random functions.
InferenceMethod, which a new method subclasses, is on Registries for extensions.
MCMC¶
condition_on_nutpie(model, data=None, *, num_results=1000, num_warmup=500, num_chains=4, **kwargs)
¶
MCMC sampling via nutpie (Rust-based NUTS).
Accepts a StanModel or its posterior, bound
to data when it is a kernel, or a PyMCModel
at the observed values data. The run's seed is drawn from a
workflow-owned random event, so workflow_run(seed=...) reproduces the
chains, and an unscoped call runs fresh ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
StanModel or PyMCModel
|
The program to sample: a Stan program, its posterior at its data, or a PyMC model. |
required |
data
|
Mapping or None
|
The data that bind a Stan program, or the observed values of a PyMC model. |
None
|
num_results
|
int
|
The number of draws per chain. |
1000
|
num_warmup
|
int
|
The number of tuning steps per chain. |
500
|
num_chains
|
int
|
The number of chains. |
4
|
**kwargs
|
Any
|
Further keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
EmpiricalDistribution
|
The chains of the program's parameters, with nutpie's trace as the
annotations. Its inference-run provenance includes |
Raises:
| Type | Description |
|---|---|
ImportError
|
If nutpie is not installed. |
TypeError
|
If model is neither a Stan program nor a PyMC model, or kwargs
holds |
Source code in probpipe/inference/_nutpie.py
rwmh(dist, data=None, *, log_prob_fn=None, num_results=1000, num_warmup=500, num_chains=4, step_size=0.1, adapt=True, n_windows=4, proposal_cov=None, init=None)
¶
Gradient-free random-walk Metropolis-Hastings (BlackJAX-backed).
Two execution paths share the same BlackJAX kernel:
- a fast path using
jax.lax.scan+jax.vmapacross chains, when the target log-density is JAX-traceable at the initial state; - an eager Python-loop fallback otherwise (BridgeStan / scipy / external-simulator likelihoods).
The run's key is drawn from a workflow-owned random event, so
workflow_run(seed=...) reproduces the chains, and an unscoped call runs
fresh ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
SupportsUnnormalizedLogProb
|
Distribution providing |
required |
data
|
array - like or None
|
Observed data forwarded to |
None
|
log_prob_fn
|
callable or None
|
|
None
|
num_results
|
int
|
Number of draws each chain keeps. |
1000
|
num_warmup
|
int
|
Number of warmup steps each chain runs before the draws it keeps,
on which |
500
|
num_chains
|
int
|
Number of chains, which all start at the initial state. |
4
|
step_size
|
float
|
Diagonal proposal scale used when |
0.1
|
adapt
|
bool
|
When |
True
|
n_windows
|
int
|
Maximum number of geometric warmup windows when |
4
|
proposal_cov
|
array - like or None
|
Explicit |
None
|
init
|
array - like or None
|
Initial chain state. Resolved by
|
None
|
Returns:
| Type | Description |
|---|---|
EmpiricalDistribution
|
Posterior samples with chain structure and an annotations
ArviZ-shaped |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If |
Notes
At each window boundary the adaptive warmup refits the proposal
covariance as (n * Sigma_hat + 5 * Sigma_prev) / (n + 5), where
Sigma_hat is the Welford covariance of the n warmup positions
so far and Sigma_prev is the covariance the proposal in use
assumes, which is the identity before the first refit. This is Stan's
covariance regularization with Sigma_prev in place of
1e-3 * I. The refit stays positive definite when the positions
have no spread, as when every proposal in a window is rejected, and
when they span fewer than d directions. The proposal therefore
never collapses to zero, and the correction vanishes as n grows.
The growing windows downweight the early, badly mixed positions by
giving later windows more steps.
Source code in probpipe/inference/_blackjax_rwmh.py
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 | |
elliptical_slice(model, data, *, num_results=1000, num_warmup=500, num_chains=4, init=None)
¶
Elliptical slice sampling of a joint with a Gaussian prior, at observed fields.
The joint is a factored one, such as likelihood & prior. The factors that
produce the observed fields are the likelihood, and the others are the
prior, which must be Gaussian, as _gaussian_prior_params recognizes.
The run's key is drawn from a workflow-owned random event, so
workflow_run(seed=...) reproduces the chains, and an unscoped call runs
fresh ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Distribution
|
The factored joint, whose factors that produce no observed field form a
|
required |
data
|
Record or Mapping[str, Any]
|
The observed values, keyed by the fields they bind. |
required |
num_results
|
int
|
Number of draws each chain keeps. |
1000
|
num_warmup
|
int
|
Number of steps each chain runs before the draws it keeps. |
500
|
num_chains
|
int
|
Number of chains, which all start at the initial state. |
4
|
init
|
array - like or None
|
Initial chain state in the flat parameter vector. Defaults to a sample from the prior. |
None
|
Returns:
| Type | Description |
|---|---|
EmpiricalDistribution
|
Posterior samples with chain structure and an annotations
ArviZ-shaped |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the joint at data has no prior and likelihood factors, or the prior is not Gaussian. |
Source code in probpipe/inference/_blackjax_ess.py
Amortized simulation-based inference¶
learn_amortized_posterior(prior, simulator, *, method='npe', num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, optimizer='adam', **fit_kwargs)
¶
Learn an amortized conditional posterior q(theta | y) with BayesFlow.
Trains an amortized neural posterior estimator (NPE / FMPE / CMPE) from a
prior and a simulator and returns the learned kernel from the
observation to the parameters, whose input is observation.
condition_on(result, {"observation": y}) evaluates it without retraining
or MCMC and returns the law at y, each of whose draws is one forward pass
of the network; the evaluation is approximate, so exact_only=True refuses
it. Provenance names the prior
and the simulator it was trained on.
The training's seed is drawn from a workflow-owned random event, so
workflow_run(seed=...) reproduces the trained network, and an unscoped
call trains afresh. The seed fixes the offline simulation (jax.random)
and keras's network initialization and training, which
keras.utils.set_random_seed seeds. The caller's global NumPy and Python
random states are restored after training, and keras's global seed
generator keeps the state training leaves. Each draw of the learned
posterior's law at an observation is a workflow-owned random event of its
own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Distribution
|
Prior over the model parameters. Must be a numeric distribution --
typically a factored joint of named distributions, or a single named
distribution for a one-parameter model. It is
sampled via the |
required |
simulator
|
ConditionalDistribution
|
The kernel of one observation given the prior's fields, which claims
|
required |
method
|
('npe', 'fmpe', 'cmpe')
|
Amortized estimator: NPE (coupling flow), FMPE (flow matching), or CMPE
(consistency model). NPE's coupling flow needs at least two unconstrained
parameter dimensions (a one-parameter prior has one; so does a single
2-simplex), below which the NPE default falls back to a flow-matching
network (still reported as |
"npe"
|
num_simulations
|
int
|
Number of |
10000
|
epochs
|
int
|
Number of keras training passes over the simulations. |
50
|
batch_size
|
int
|
Number of simulations in each keras training batch. |
128
|
sim_backend
|
('jax', 'sequential')
|
How the offline simulation is executed. |
"jax"
|
inference_network
|
InferenceNetwork or None
|
Overrides the method default ( |
None
|
optimizer
|
str or Optimizer
|
Passed to |
'adam'
|
**fit_kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
ConditionalDistribution
|
The amortized posterior |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If a count parameter is not an integer, |
ImportError
|
If the |
Source code in probpipe/inference/_bayesflow_posteriors.py
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
learn_amortized_likelihood(prior, simulator, *, num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, dequantize=False, optimizer='adam', **fit_kwargs)
¶
Learn an amortized likelihood p(y | theta) (NLE) with BayesFlow.
Trains a conditional coupling flow on offline (theta, y) simulations and
returns a BayesFlowLikelihood, the kernel p̂(y | theta) from the
prior's outputs to datasets of observation rows, with the network's
jax-traceable density. condition_on(learned & prior, {"observation": y})
then runs a registered gradient-based MCMC method (BlackJAX/TFP NUTS) for
datasets of any size, since per-row scores sum under conditional
independence. The network conditions on the raw constrained theta.
The training's seed is drawn from a workflow-owned random event, so
workflow_run(seed=...) reproduces the trained network, and an unscoped
call trains afresh. The seed fixes the offline simulation, the
dequantization jitter, and keras's network initialization and training.
The caller's global NumPy and Python random states are restored after
training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Distribution
|
Prior over the model parameters; a numeric distribution whose outputs name them, which may be nested (a factored joint of named distributions). Sampled (only) to draw training thetas; constrained and discrete-valued parameter fields are both fine here, since theta is a network input (whether the downstream sampler can handle the prior is the sampler's concern). |
required |
simulator
|
ConditionalDistribution
|
The kernel of one observation given the prior's fields, which samples;
its given values are the prior's structured per-draw record (named-field
access). Must be JAX-vmappable unless |
required |
num_simulations
|
int
|
Number of |
10000
|
epochs
|
int
|
Number of keras training passes over the simulations. |
50
|
batch_size
|
int
|
Number of simulations in each keras training batch. |
128
|
sim_backend
|
('jax', 'sequential')
|
|
"jax"
|
inference_network
|
InferenceNetwork or None
|
Overrides the default |
None
|
dequantize
|
bool
|
Set for integer-valued observations (counts and other ordered
integer encodings; unordered categoricals would inherit a meaningless
cell adjacency). Fitting a continuous flow to atoms is ill-posed -- the
MLE collapses density onto the data points, which in practice shows up
as overdispersed, seed-unstable posteriors as observations concentrate
on few values. Uniform dequantization fixes this: training adds
|
False
|
optimizer
|
str or Optimizer
|
Passed to |
'adam'
|
**fit_kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
BayesFlowLikelihood
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If a count parameter is not an integer, |
ImportError
|
If the |
Source code in probpipe/inference/_bayesflow_likelihoods.py
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | |
BayesFlowLikelihood(approximator, prior, simulator, *, data_dim, label=None, dequantized=False)
¶
Bases: _BayesFlowLikelihoodBase, SupportsConditionalLogProb
A learned amortized likelihood p̂(y | theta): a kernel with the network's density.
The density of a dataset at theta is sum_i log p_net(y_i | theta).
The score path is pure keras-jax ops (standardize, conditional-flow
log_prob, plus the standardization log-det-jacobian), so it is
jax.grad-transparent and jit-stable, and gradient-based MCMC normalizes
condition_on(learned & prior, {"observation": y}). Values are faithful
to the public approximator.log_prob (same standardization and
log-det-jacobian); the only difference is staying on-device.
With dequantized=True (set by learn_amortized_likelihood's
dequantize flag), the flow was trained on uniformly jittered
observations y + U[0,1)^d, and scoring shifts integer-valued data to
the unit-cell midpoint -- values then equal the public log_prob
evaluated at y + 1/2, a one-point approximation of the implied pmf
P(y | theta) = integral over [y, y+1)^d of p(u | theta) du
(Theis et al., 2016, arXiv:1511.01844). Pass raw integer-valued
observations; the kernel owns the cell convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
approximator
|
ContinuousApproximator
|
The trained BayesFlow approximator whose standardizer and inference network score the rows. |
required |
prior
|
Distribution
|
The prior the estimator was trained against, whose outputs are the kernel's inputs. |
required |
simulator
|
ConditionalDistribution
|
The training simulator. |
required |
data_dim
|
int
|
The flattened width of one observation row the network was trained on. |
required |
label
|
str
|
The kernel's label, |
None
|
dequantized
|
bool
|
Whether the flow was trained on jittered integer-valued observations,
so that scoring shifts the data to the unit-cell midpoint; |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is neither |
Source code in probpipe/inference/_bayesflow_likelihoods.py
learn_amortized_ratio(prior, simulator, *, num_simulations=10000, epochs=50, batch_size=128, sim_backend='jax', inference_network=None, optimizer='adam', **fit_kwargs)
¶
Learn an amortized likelihood-to-evidence ratio (NRE) with BayesFlow.
Trains an NRE-C classifier (RatioApproximator; contrastive pairs are
built internally by shuffling theta within each batch, so the training data
are the same offline (theta, y) simulations as NLE) and returns a
BayesFlowRatio, the kernel from the prior's outputs to datasets
of observation rows whose summed per-row log-ratios are its unnormalized
density: the log-likelihood up to a theta-independent constant -- valid
for condition_on(learned & prior, {"observation": y}), invalid for
absolute-likelihood uses (model comparison, LOO/WAIC); see the class
docstring. The classifier handles discrete-valued observations and
one-dimensional data natively.
The training's seed is drawn from a workflow-owned random event, so
workflow_run(seed=...) reproduces the trained classifier, and an
unscoped call trains afresh. The seed fixes the offline simulation and
keras's network initialization and training. The caller's global NumPy and
Python random states are restored after training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Distribution
|
Prior over the model parameters; a numeric distribution, possibly
nested (as in |
required |
simulator
|
ConditionalDistribution
|
The kernel of one observation given the prior's fields, which samples; its given values are the prior's structured per-draw record. |
required |
num_simulations
|
int
|
Number of |
10000
|
epochs
|
int
|
Number of keras training passes over the simulations. |
50
|
batch_size
|
int
|
Number of simulations in each keras training batch. |
128
|
sim_backend
|
('jax', 'sequential')
|
|
"jax"
|
inference_network
|
Layer or None
|
The classifier body (defaults to |
None
|
optimizer
|
str or Optimizer
|
Passed to |
'adam'
|
**fit_kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
BayesFlowRatio
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If a count parameter is not an integer, |
ImportError
|
If the |
Source code in probpipe/inference/_bayesflow_likelihoods.py
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 | |
BayesFlowRatio(approximator, prior, simulator, *, data_dim, label=None)
¶
Bases: _BayesFlowLikelihoodBase, SupportsConditionalUnnormalizedLogProb
A learned likelihood-to-evidence ratio: a kernel with an unnormalized density.
The per-row scores are the NRE-C classifier logits, which converge to
log[p(y_i | theta) / p(y_i)], so a dataset's score equals its joint
log-likelihood up to a theta-independent constant (sum_i log p(y_i)).
The kernel therefore claims SupportsConditionalUnnormalizedLogProb
alone: conditioning learned & prior on an observation cancels the
constant, but the values are not normalized log-likelihoods, so do not use
them for model comparison, information criteria (LOO / WAIC), or any
reading of absolute likelihood magnitudes.
Because the estimator is a classifier (an MLP over concat(theta, y)), it
has no continuous-density machinery: it handles discrete-valued
observations natively (no dequantize flag needed, and mixed
discrete/continuous rows are fine) and has no minimum observation
dimension -- the two cases where BayesFlowLikelihood's coupling
flow needs, respectively, dequantization or a custom network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
approximator
|
RatioApproximator
|
The trained BayesFlow ratio approximator whose classifier scores the rows. |
required |
prior
|
Distribution
|
The prior the estimator was trained against, whose outputs are the kernel's inputs. |
required |
simulator
|
ConditionalDistribution
|
The training simulator. |
required |
data_dim
|
int
|
The flattened width of one observation row the network was trained on. |
required |
label
|
str
|
The kernel's label, |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If label is neither |
Source code in probpipe/inference/_bayesflow_likelihoods.py
Sequential updating¶
iterate(step_fn, initial, inputs, *, callback=None)
¶
Fold a step function over inputs, returning the batch of the laws the fold visits.
Starting from initial, applies step_fn(dist, inp) for each element
of inputs. The laws visited, initial first, are the elements of a
DistributionBatch on one level named iterate, so they share one
event spec. Each element is a view of the law the fold produced at
that step, and its provenance records the batch and that law.
A step's law that has no provenance receives a record of the step, whose parent is the previous law and whose metadata holds the step's index; a law that already has provenance keeps it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step_fn
|
callable
|
|
required |
initial
|
Distribution
|
The starting distribution. |
required |
inputs
|
Iterable[S]
|
Sequence of inputs to pass to the step function. |
required |
callback
|
callable or None
|
Called as |
None
|
Returns:
| Type | Description |
|---|---|
DistributionBatch
|
The laws |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a step returns something other than a |
Source code in probpipe/core/transition.py
with_conversion(step_fn, target_type, **convert_kwargs)
¶
Wrap a step function to convert its output after each step.
After calling step_fn, converts the resulting distribution to target_type through the converter registry, which returns a law that already satisfies the target as it is. The pre-conversion distribution is the converted distribution's provenance parent, which the registry records with the converter it selected.
This is useful when the step function produces samples (e.g., MCMC output) but the next iteration needs a parametric distribution as input.
The returned wrapper is a Function, so it appears
as a node in the ProbPipe workflow DAG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step_fn
|
callable
|
The underlying step function. |
required |
target_type
|
type
|
Distribution type to convert to (e.g., |
required |
**convert_kwargs
|
Any
|
The registry's controls |
{}
|
Returns:
| Type | Description |
|---|---|
Function
|
A new step function with the same call signature. |
Source code in probpipe/core/transition.py
with_resampling(step_fn, *, ess_threshold=0.5)
¶
Wrap a step function to resample when particle weights degenerate.
After calling step_fn, if the result is an
EmpiricalDistribution with
ESS / N < ess_threshold, performs multinomial resampling to
produce equally-weighted particles.
Each resampling is a workflow-owned random event, whose PRNG key derives
from the seed of the enclosing workflow_run scope and from the call's
position in the workflow. A run inside workflow_run(seed=...)
therefore reproduces its resampled particles, and a run under another
seed or outside any scope resamples afresh.
When resampling occurs, the raw result from
wrapper.apply(...) carries "resample" provenance whose
metadata stores the pre-resampling "ess" and "ess_ratio".
A normal wrapper(...) call returns an independent Function result
whose provenance describes the wrapper invocation; it does not retain
that implementation-level resampling metadata.
The returned wrapper is a Function, so it appears
as a node in the ProbPipe workflow DAG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
step_fn
|
callable
|
The underlying step function. |
required |
ess_threshold
|
float
|
Resample when |
0.5
|
Returns:
| Type | Description |
|---|---|
Function
|
A new step function with the same call signature. |
Notes
This API is likely to evolve as typical use cases become clearer.
A future direction is a SupportsResampling protocol that would
decouple this combinator from the concrete
EmpiricalDistribution type.
Source code in probpipe/core/transition.py
199 200 201 202 203 204 205 206 207 208 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 | |
The inference-method registry¶
inference_method_registry.list_methods() names the registered methods, and condition_on.using(method=name) runs the method of that name instead of the one the registry selects.
inference_method_registry = _InferenceMethodRegistry(name='inference', description='Inference methods for condition_on, each given an inference target.')
module-attribute
¶
The registry of the normalization stage of condition_on, whose methods each receive an inference target.
The methods of probpipe.inference register here.