MCMC¶
Markov chain Monte Carlo (MCMC) draws a
correlated sequence whose stationary distribution is the posterior.
Hamiltonian Monte Carlo (HMC) proposes moves by
simulating momentum with gradients, and the No-U-Turn Sampler (NUTS) adapts the length of each
trajectory (Neal, 2011; Hoffman and Gelman, 2014). The module gives the
HMC and NUTS
kernels, the MCMC runner, and the
MCMCResult summary. Warmup tunes the step size and mass
matrix before draws are kept, and windowed warmup
follows Stan's schedule. The target acceptance rate comes from an asymptotic analysis of
high-dimensional product targets (Beskos et al., 2013). Several chains reveal regions one chain
missed, and the
effective sample size
measures the precision of posterior summaries (Vehtari et al., 2021).
The runner targets a MonadicProgram. Models that declare every latent
as a sample site need no conversion. For models with nn.Parameters
or intermediate latent sites, the
bayesian_lift_parameters
function returns a 3-tuple (MonadicProgram, torch.Tensor, dict[str, torch.Tensor]),
whose first element is the program to pass to the runner.
PotentialFn is the log density the kernels walk. It is
evaluated at one position or, through log_density_batch and value_and_grad_batch, at
many positions in one pass.
quivers.inference re-exports the kernels, the runner, and its result.
quivers.inference.mcmc also exports the warmup adaptation primitives
and the type aliases that parameterize the kernels and the runner.
mcmc
¶
MCMC kernels, adaptation primitives, and the chain driver.
Public surface (the kernels and driver are also re-exported from
quivers.inference):
MCMCKernel: ABC for Markov kernels on the flat unconstrained latent vector, withKernelStateas its per-chain state andPotentialFnas the potential it evaluates.HMCKernel: Hamiltonian Monte Carlo with leapfrog integration, dual-averaging step-size adaptation, and Welford mass-matrix adaptation, parameterized by aMassMatrixKind.NUTSKernel: No-U-Turn Sampler with multinomial sampling.DualAveraging,WelfordCovariance, andfind_reasonable_step_size: the warmup adaptation primitives the kernels share.AdaptationSchedule,AdaptationWindow, andAdaptationMode: the Stan-style windowed warmup schedule the kernels follow by default.MetropolisKernelwith aProposal(RandomWalkProposal,IndependenceProposal): Metropolis-Hastings moves on the flat vector.GibbsKernel: Gibbs blocks over named latent sites held outside the flat vector, discrete ones included, updated by enumeration or by aGibbsUpdate.CycleKernelandMixtureKernel: compositions of kernels.MCMC: chain orchestrator with warmup, parallel chains, anInitStrategy, and posterior diagnostics (split-:math:\hat R, effective sample size).MCMCResult: posterior samples, per-draw sampler statistics, and per-chain diagnostics.MCMCCheckpoint: atomic checkpoints from whichMCMC.resumecontinues a run exactly;MCMCalso takes wall-clock and evaluation budgets and anMCMCCallbackprogress hook.
AdaptationMode
module-attribute
¶
How an HMC or NUTS kernel adapts during warmup: "windowed" follows
an AdaptationSchedule (fast, doubling slow, fast windows, with the
metric re-estimated and the step size re-initialized after every slow
window), and "single" runs dual averaging and the covariance
estimate over the whole warmup under the initial metric and installs
the metric once, when warmup ends.
CHECKPOINT_FILENAME
module-attribute
¶
The name of the checkpoint file inside an MCMCCheckpoint directory.
CHECKPOINT_FORMAT_VERSION
module-attribute
¶
The version of the checkpoint layout this library writes and reads.
MCMC.resume refuses a checkpoint of another version.
InitStrategy
module-attribute
¶
How MCMC chooses each chain's initial point in the unconstrained
latent space: "jitter" draws a seeded perturbation 0.1 * N(0, I)
of the origin, "prior" draws every latent from its prior given the
data (the model run forward with its observed sites held at their
values) and maps the draw into the unconstrained space, "zero"
starts at the origin, "guide" maps one draw of a fitted guide
into the unconstrained space, and "uniform" draws every coordinate
uniformly from (-init_radius, init_radius), Stan's and brms's
init = "random" with init_r.
MCMCCallback
module-attribute
¶
MCMCCallback = Callable[[int, int, KernelState, MCMCPhase], None]
A progress hook callback(chain, iteration, state, phase), called
after every transition with the chain's index, the transition's index
within its phase (counted from zero), the state it produced, and the
phase. It runs in the sampling loop; it should not draw from the
chain's generator or modify the state. The state of a recorded draw
has its log-density evaluated; after a warmup or thinned-out transition
that ended in a Gibbs sweep it may not (KernelState.has_density).
MCMCPhase
module-attribute
¶
The phase of a chain's transition: adaptation or sampling.
StopReason
module-attribute
¶
Why a chain stopped: "draws" when it collected every draw,
"seconds" when MCMC's max_seconds ran out, and
"evaluations" when its max_evaluations did.
GibbsUpdate
module-attribute
¶
GibbsUpdate = Callable[[torch.Generator | None, dict[str, torch.Tensor], dict[str, torch.Tensor]], dict[str, torch.Tensor]]
A user-supplied Gibbs update update(generator, gibbs_values,
latent_values) -> new_gibbs_values.
gibbs_values holds the block's current values and latent_values
the constrained values of the registry's sites (the flat vector), both
as trace-side values: a non-plate site carries a leading run axis of
one, a plate site has its constrained shape, and host data have the
shape and dtype of their starting value. The update returns new
values for exactly the block's sites, in the same layout, drawn from
their full conditional (or by any move that leaves it invariant), with
every random draw taken from generator.
MassMatrixKind
module-attribute
¶
The mass-matrix structure an HMC or NUTS kernel adapts during warmup:
"identity" keeps the unit metric, "diagonal" adapts per-coordinate
variances, and "dense" adapts a full covariance.
StateValue
¶
StateValue = Tensor | float | int | bool | str | None | list[StateValue] | dict[str, StateValue]
A value in a kernel's or a chain state's state dictionary: a tensor, a
Python scalar or string, None, or a list or string-keyed dictionary
of such values. These are exactly the values a checkpoint stores and
torch.load reads back with weights_only=True, so loading a
checkpoint executes no code.
AdaptationSchedule
didactic-model
¶
Bases: Model
The Stan-style windowed warmup schedule.
A warmup of N iterations is split into an initial fast interval
of init_buffer iterations, a run of slow windows over the next
N - init_buffer - term_buffer iterations, and a terminal fast
interval of term_buffer iterations. The first slow window has
base_window iterations and each later one twice the length of
the one before; when the window after next would not fit before the
terminal interval, the current window is stretched to reach it, so
the slow windows tile their interval exactly. This is the schedule
of the Stan reference manual's automatic parameter tuning and its
implementation in stan::mcmc::windowed_adaptation.
Two rules cover warmups too short for the configured buffers, again following Stan:
- When
init_buffer + base_window + term_buffer > N, the buffers are rescaled to 15% / 75% / 10% ofN:init_buffer = floor(0.15 N),term_buffer = floor(0.1 N), and one slow window covers the rest. - When
N < 20, no metric is estimated: the whole warmup is one fast window.
| ATTRIBUTE | DESCRIPTION |
|---|---|
init_buffer |
Length of the initial fast interval. Default
TYPE:
|
term_buffer |
Length of the terminal fast interval. Default
TYPE:
|
base_window |
Length of the first slow window. Default
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValidationError
|
If a buffer is negative or |
windows
¶
windows(num_warmup: int) -> tuple[AdaptationWindow, ...]
Lay a warmup of num_warmup iterations out in windows.
| PARAMETER | DESCRIPTION |
|---|---|
num_warmup
|
Number of warmup iterations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[AdaptationWindow, ...]
|
The windows in order. They tile |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/adapt.py
AdaptationWindow
didactic-model
¶
Bases: Model
One window of a warmup schedule.
| ATTRIBUTE | DESCRIPTION |
|---|---|
start |
The first warmup iteration in the window, counted from zero.
TYPE:
|
stop |
One past the last warmup iteration in the window.
TYPE:
|
adapts_metric |
Whether the window is a slow window: the positions it visits are accumulated into a covariance estimate that becomes the metric (inverse mass matrix) at the window's end. A fast window adapts only the step size.
TYPE:
|
DualAveraging
¶
DualAveraging(initial_step_size: float, target_accept: float = 0.8, gamma: float = 0.05, t0: float = 10.0, kappa: float = 0.75)
Nesterov dual averaging for adaptive step-size selection.
Maintains a running smoothed estimate of the log-step-size that
drives the chain's average acceptance probability toward the
user-supplied target_accept.
Algorithm parameters follow Hoffman-Gelman 2014 (Algorithm 6):
:math:\gamma = 0.05, :math:t_0 = 10, :math:\kappa = 0.75.
These are the defaults used by Stan.
| PARAMETER | DESCRIPTION |
|---|---|
initial_step_size
|
Starting step size. The first proposal uses
TYPE:
|
target_accept
|
Target Metropolis acceptance probability. Default
TYPE:
|
gamma
|
Adaptation regularisation. Default
TYPE:
|
t0
|
Stabilisation offset. Default
TYPE:
|
kappa
|
Decay exponent for the smoothed step size. Default
TYPE:
|
Source code in src/quivers/inference/mcmc/adapt.py
step_size
¶
smoothed_step_size
¶
update
¶
Update the step size given the latest Metropolis acceptance probability.
Source code in src/quivers/inference/mcmc/adapt.py
state_dict
¶
The adapter's state, for a checkpoint.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float | int]
|
Every parameter and running quantity; |
Source code in src/quivers/inference/mcmc/adapt.py
from_state_dict
classmethod
¶
from_state_dict(state: Mapping[str, StateValue]) -> 'DualAveraging'
Rebuild an adapter from state_dict's output.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DualAveraging
|
The adapter, in exactly the recorded state. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an entry is missing or is not a number. |
Source code in src/quivers/inference/mcmc/adapt.py
WelfordCovariance
¶
Welford-style online covariance accumulator.
Tracks the running mean and (co)variance of a stream of
D-dimensional vectors. Supports both diagonal and dense
forms: diagonal is sufficient for ill-scaled axis-aligned
posteriors, dense needed when off-axis correlations matter.
The dense form follows the standard pairwise update:
.. math::
M_n = M_{n-1} + (x_n - \bar{x}_{n-1})(x_n - \bar{x}_n)^\top
with :math:\bar{x}_n = \bar{x}_{n-1} + (x_n - \bar{x}_{n-1}) / n.
| PARAMETER | DESCRIPTION |
|---|---|
dim
|
Vector dimension.
TYPE:
|
regularise
|
Apply Stan's regularisation
:math:
TYPE:
|
diagonal
|
Track only the diagonal of the covariance (vector, not
matrix). Default
TYPE:
|
Source code in src/quivers/inference/mcmc/adapt.py
update
¶
update(x: Tensor) -> None
Fold one vector into the running statistics.
Source code in src/quivers/inference/mcmc/adapt.py
covariance
¶
covariance() -> Tensor
Return the empirical covariance (regularised if configured).
Source code in src/quivers/inference/mcmc/adapt.py
state_dict
¶
state_dict() -> dict[str, Tensor | int | bool]
The accumulator's state, for a checkpoint.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor | int | bool]
|
The configuration, the count, the running mean, and the running sum of squared deviations. |
Source code in src/quivers/inference/mcmc/adapt.py
from_state_dict
classmethod
¶
from_state_dict(state: Mapping[str, StateValue]) -> 'WelfordCovariance'
Rebuild an accumulator from state_dict's output.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
WelfordCovariance
|
The accumulator, in exactly the recorded state. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an entry is missing or has the wrong type or shape. |
Source code in src/quivers/inference/mcmc/adapt.py
reset
¶
Discard accumulated statistics.
CycleKernel
¶
CycleKernel(kernels: Sequence[MCMCKernel] | Mapping[str, MCMCKernel])
Bases: _CompositeKernel
Apply every component once per transition, in order.
The cycle leaves the posterior invariant when each component does.
During warmup every component adapts over the same num_warmup
transitions.
The composite's own stats hold each component's statistics
under "<name>.<key>", and "accepted" records whether the
transition moved the chain (its position or a Gibbs value).
| PARAMETER | DESCRIPTION |
|---|---|
kernels
|
The components, named by the mapping's keys or by position.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If there are no components, a name is empty or holds a dot, or one kernel object appears twice. |
TypeError
|
If a component is not an |
Source code in src/quivers/inference/mcmc/compose.py
start_adaptation
¶
Start every component's warmup of num_warmup transitions.
| PARAMETER | DESCRIPTION |
|---|---|
num_warmup
|
Number of warmup transitions.
TYPE:
|
Source code in src/quivers/inference/mcmc/compose.py
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run every component once, in order.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state.
TYPE:
|
potential
|
The target conditioned on
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The state after the last component. |
Source code in src/quivers/inference/mcmc/compose.py
MixtureKernel
¶
MixtureKernel(kernels: Sequence[MCMCKernel] | Mapping[str, MCMCKernel], probs: Sequence[float] | None = None)
Bases: _CompositeKernel
Apply one component per transition, chosen at random.
Component :math:i is chosen with probability probs[i],
independently of the chain's state, from the chain-local generator,
so the mixture leaves the posterior invariant when each component
does. During warmup the choices for all num_warmup transitions
are drawn when warmup starts, and each component starts its own
adaptation for exactly the number of transitions that will select
it, so a windowed schedule runs to completion.
The composite's stats hold the selected component's statistics
under "<name>.<key>" (the other components' keys are absent),
and "accepted" records whether the chain moved.
| PARAMETER | DESCRIPTION |
|---|---|
kernels
|
The components, named by the mapping's keys or by position.
TYPE:
|
probs
|
Selection probabilities, positive and summing to one; uniform when omitted.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the components are invalid (see |
TypeError
|
If a component is not an |
Source code in src/quivers/inference/mcmc/compose.py
configuration
¶
configuration() -> dict[str, StateValue]
The components' configurations and the selection probabilities.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/compose.py
state_dict
¶
state_dict() -> dict[str, StateValue]
The components' states and the warmup's drawn choices.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The state. |
Source code in src/quivers/inference/mcmc/compose.py
load_state_dict
¶
load_state_dict(state: dict[str, StateValue]) -> None
Restore what state_dict returned.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the warmup choices are missing or malformed. |
Source code in src/quivers/inference/mcmc/compose.py
init
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Initialize every component and clear the warmup choices.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
model
|
The model.
TYPE:
|
x
|
The one-row input.
TYPE:
|
observations
|
The data.
TYPE:
|
initial_position
|
The starting position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The first component's starting state. |
Source code in src/quivers/inference/mcmc/compose.py
start_adaptation
¶
Draw the warmup's component choices and start each component's adaptation for the transitions that select it.
| PARAMETER | DESCRIPTION |
|---|---|
num_warmup
|
Number of warmup transitions.
TYPE:
|
Source code in src/quivers/inference/mcmc/compose.py
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run one randomly chosen component.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state.
TYPE:
|
potential
|
The target conditioned on
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The chosen component's output. |
Source code in src/quivers/inference/mcmc/compose.py
MCMCCheckpoint
didactic-model
¶
Bases: Model
Where and how often MCMC checkpoints its chains.
A checkpoint is written after every every transitions of a chain
(warmup and sampling alike), after every_seconds of wall-clock
time since the last write, whichever comes first, and always when a
chain finishes or a budget stops it. MCMC.resume continues a run
from the checkpoint, bit for bit as if it had not been interrupted.
| ATTRIBUTE | DESCRIPTION |
|---|---|
directory |
The directory the checkpoint file is written to; created if absent.
TYPE:
|
every |
Transitions between writes;
TYPE:
|
every_seconds |
Seconds between writes;
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValidationError
|
If |
MCMC
¶
MCMC(kernel: MCMCKernel, num_warmup: int, num_samples: int, num_chains: int = 4, init_strategy: InitStrategy = 'jitter', *, seed: int | None = None, generator: Generator | None = None, checkpoint: MCMCCheckpoint | None = None, max_seconds: float | None = None, max_evaluations: int | None = None, callback: MCMCCallback | None = None, initial_values: Mapping[str, Tensor | float] | Sequence[Mapping[str, Tensor | float]] | None = None, thin: int = 1, init_radius: float = 2.0)
MCMC chain runner.
| PARAMETER | DESCRIPTION |
|---|---|
kernel
|
Markov kernel (e.g.
TYPE:
|
num_warmup
|
Number of adaptation steps. The kernel's adaptation machinery (dual averaging, Welford covariance) runs over this prefix.
TYPE:
|
num_samples
|
Post-warmup samples per chain.
TYPE:
|
num_chains
|
Independent chains. Default
TYPE:
|
init_strategy
|
How to pick each chain's initial position (
TYPE:
|
seed
|
Base seed used to derive an independent local generator for
each chain. Repeated calls to
TYPE:
|
generator
|
Caller-owned CPU generator used to draw one base seed per
TYPE:
|
checkpoint
|
Where and how often to checkpoint the chains, so that
TYPE:
|
max_seconds
|
Wall-clock budget per chain and per call of
TYPE:
|
max_evaluations
|
Budget of potential evaluations (gradient ones included) per chain and per call.
TYPE:
|
callback
|
Progress hook called after every transition.
TYPE:
|
initial_values
|
Natural-scale starting values for named latent sites. Scalars
broadcast to the site's shape; arrays must match it exactly.
Values must be finite and strictly inside the prior support.
They replace the configured strategy's corresponding coordinates
in every chain and are included in checkpoint compatibility. A
sequence of
TYPE:
|
thin
|
Keep every
TYPE:
|
init_radius
|
Half-width of the
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a count or budget is out of range, |
TypeError
|
If |
Source code in src/quivers/inference/mcmc/driver.py
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 750 751 752 753 | |
chain_start_values
¶
chain_start_values(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], guide: Guide | None = None) -> tuple[dict[str, Tensor], ...]
Return the initial values run gives each chain, without sampling.
A chain's initial point is the first draw from the chain's stream,
which run derives from the run seed and the chain index. With an
explicit seed the values here are thus those of run on the same
model and data.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
The model.
TYPE:
|
x
|
The input.
TYPE:
|
observations
|
The data.
TYPE:
|
guide
|
The guide for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[dict[str, Tensor], ...]
|
One mapping per chain from latent site to its initial value on the constrained scale, at the site's constrained shape. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the driver has no explicit integer seed, so that a later call cannot reproduce the chain streams. |
Notes
Cost is one setup of the potential and, per chain, one forward pass of the program for each initial point drawn until one scores a finite log-density.
Source code in src/quivers/inference/mcmc/driver.py
run
¶
run(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], guide: Guide | None = None) -> MCMCResult
Run the configured kernel for num_chains chains of
num_warmup + num_samples steps each.
Each chain's initial position is scored by
PotentialFn.check_initial before sampling, so an error in
the program or its data (observed values outside a
likelihood's support or not finite, mismatched row counts, an
error in a custom score function) raises here, with a note
naming the chain, rather than producing a chain that rejects
every proposal. During sampling only positions outside the
model's support score -inf; other errors propagate.
With a checkpoint the chains are checkpointed as they run,
and resume continues them. With a budget, a chain stops at the
first transition boundary past it, and the result records why
in MCMCResult.stopped_by.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
The program to sample.
TYPE:
|
x
|
Program input, shape
TYPE:
|
observations
|
Observed-site values and host data.
TYPE:
|
guide
|
Fitted guide, required by
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
Posterior draws and diagnostics. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
FileExistsError
|
If |
Exception
|
Any error the program raises at an initial position, or raises during sampling for a reason other than a position outside its support. |
Source code in src/quivers/inference/mcmc/driver.py
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | |
resume
¶
resume(directory: str | Path, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], guide: Guide | None = None) -> MCMCResult
Continue a run from its checkpoint.
Finished chains are kept as they are; a chain a budget or an
interruption stopped continues from its last checkpoint; chains
not yet started start as run would start them. The draws are
bit for bit those of an uninterrupted run with the same seed.
Budgets apply afresh to this call. Further checkpoints follow
this instance's checkpoint, if any.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
The directory holding the checkpoint.
TYPE:
|
model
|
The program the checkpoint was written for.
TYPE:
|
x
|
The input it was written for.
TYPE:
|
observations
|
The data it was written for.
TYPE:
|
guide
|
Fitted guide, for chains not yet started under
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
Posterior draws and diagnostics of every chain. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If the checkpoint is of another format version, or was written for a different model or data, kernel configuration, run settings, or seed. |
Source code in src/quivers/inference/mcmc/driver.py
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 | |
MCMCResult
didactic-model
¶
MCMCResult(*, samples: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_densities: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), acceptance_rates: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), divergence_counts: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), num_warmup: int, num_samples: int, component_acceptance: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), sample_stats: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), stopped_by: tuple[StopReason, ...] = (), num_draws: Tensor = field(default_factory=lambda: empty(0, dtype=int64), opaque=True, extras=OPAQUE_BY_IDENTITY), num_evaluations: Tensor = field(default_factory=lambda: empty(0, dtype=int64), opaque=True, extras=OPAQUE_BY_IDENTITY), num_gradient_evaluations: Tensor = field(default_factory=lambda: empty(0, dtype=int64), opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
Posterior samples, per-chain sampler statistics, and diagnostics.
The convergence diagnostics are derived from samples on first
access by the public estimators of quivers.diagnostics, so they
agree exactly with quivers.diagnostics.rhat and
quivers.diagnostics.ess applied to the same draws. Tensors and
statistic mappings are held by identity; immutable record updates
retain these references and compute their own diagnostic caches.
| ATTRIBUTE | DESCRIPTION |
|---|---|
samples |
Per-site posterior draws on the constrained support, the sites a
TYPE:
|
log_densities |
Unconstrained-space log-density (Jacobian-corrected) at
every posterior draw. Shape
TYPE:
|
acceptance_rates |
Per-chain post-warmup acceptance rate. Shape
TYPE:
|
divergence_counts |
Per-chain post-warmup divergence count. Shape
TYPE:
|
num_warmup |
Warmup iterations per chain.
TYPE:
|
num_samples |
Retained draws per chain.
TYPE:
|
component_acceptance |
For a composite kernel, each component's post-warmup acceptance
rate per chain, shape
TYPE:
|
sample_stats |
Per-draw sampler statistics, each of shape
TYPE:
|
stopped_by |
Why each chain stopped:
TYPE:
|
num_draws |
Post-warmup draws each chain made, shape
TYPE:
|
num_evaluations |
Potential evaluations per chain, gradient ones included, over
every call of
TYPE:
|
num_gradient_evaluations |
Gradient evaluations per chain. Shape
TYPE:
|
r_hat
cached
property
¶
r_hat: dict[str, Tensor]
Per-site rank-normalized split :math:\hat R.
Each coordinate reports the maximum of the rank-normalized
and folded statistics (quivers.diagnostics.rhat). Each
site's float64 tensor has shape site_shape, so a scalar
site's tensor is zero-dimensional.
GibbsKernel
¶
GibbsKernel(sites: Sequence[str], update: GibbsUpdate | None = None, *, host: bool = False)
Bases: MCMCKernel
Gibbs block over named latent sites.
| PARAMETER | DESCRIPTION |
|---|---|
sites
|
The latent sites the block updates, in update order. They are held outside the flat vector for the whole run.
TYPE:
|
update
|
A full-conditional sampler for the whole block. When omitted, each site is updated by enumerating its finite support element by element, which requires a boolean or bounded integer support.
TYPE:
|
host
|
Whether the block's names are host data the program reads
rather than sample sites it declares. Such a block needs an
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/gibbs.py
host_sites
property
¶
The block's sites when it holds host data, else none.
configuration
¶
configuration() -> dict[str, StateValue]
The class, the sites, and the update function's qualified name.
A block over host data also records that it is one.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/gibbs.py
init
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Check the block against the model and build the first state.
Without an update, every site's support is read from a run
of the model (drawn from a forked global generator, which is left
untouched) and must be finite.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry of the flat vector, without the block's sites.
TYPE:
|
model
|
The model.
TYPE:
|
x
|
The one-row input.
TYPE:
|
observations
|
The data, with the chain's current values of any host data a Gibbs block updates.
TYPE:
|
initial_position
|
The flat vector's starting position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The starting state; |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a site is in the registry, is not a latent sample site of
the run, or (without an |
Source code in src/quivers/inference/mcmc/gibbs.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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 | |
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run one Gibbs sweep over the block.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state, with the block's values in
TYPE:
|
potential
|
The target conditioned on
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The state with the block's new values.
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the state lacks a site of the block, or an |
Source code in src/quivers/inference/mcmc/gibbs.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
HMCKernel
¶
HMCKernel(step_size: float = 0.1, num_steps: int = 10, mass_matrix: MassMatrixKind = 'identity', target_accept: float = 0.65, divergence_threshold: float = 1000.0, adapt_step_size: bool = True, adapt_mass_matrix: bool = True, adaptation: AdaptationMode = 'single', adaptation_schedule: AdaptationSchedule | None = None)
Bases: _HamiltonianKernel
Hamiltonian Monte Carlo kernel with fixed trajectory length.
| PARAMETER | DESCRIPTION |
|---|---|
step_size
|
Leapfrog step size. Adapted during warmup when
TYPE:
|
num_steps
|
Leapfrog steps per proposal.
TYPE:
|
mass_matrix
|
Mass-matrix shape. Diagonal / dense are adapted during warmup from the empirical covariance of warmup samples.
TYPE:
|
target_accept
|
Target Metropolis acceptance for dual averaging. Default
TYPE:
|
divergence_threshold
|
Energy-error threshold for marking a proposal as divergent. Divergent steps still respect Metropolis correctness but are reported separately so the user can spot pathological regions.
TYPE:
|
adapt_step_size
|
Whether warmup adapts the step size by dual averaging.
TYPE:
|
adapt_mass_matrix
|
Whether warmup adapts a diagonal or dense metric.
TYPE:
|
adaptation
|
The warmup mode (see
TYPE:
|
adaptation_schedule
|
The windowed schedule; the Stan defaults (75 / 25 / 50) when omitted.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/hmc.py
configuration
¶
configuration() -> dict[str, StateValue]
The kernel's hyperparameters, the trajectory length included.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/hmc.py
init
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Reset the adaptation state and build the chain's first state.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
model
|
The model (unused; the potential carries it).
TYPE:
|
x
|
The input (unused).
TYPE:
|
observations
|
The data (unused).
TYPE:
|
initial_position
|
The starting position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The starting state. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/hmc.py
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run one HMC transition.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state.
TYPE:
|
potential
|
The target.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The next state; |
Source code in src/quivers/inference/mcmc/hmc.py
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 | |
NUTSKernel
¶
NUTSKernel(step_size: float = 0.1, max_tree_depth: int = 10, mass_matrix: MassMatrixKind = 'diagonal', target_accept: float = 0.8, divergence_threshold: float = 1000.0, adapt_step_size: bool = True, adapt_mass_matrix: bool = True, adaptation: AdaptationMode = 'single', adaptation_schedule: AdaptationSchedule | None = None)
Bases: _HamiltonianKernel
No-U-Turn Sampler with multinomial sampling and the standard U-turn termination (Hoffman-Gelman 2014 algorithms 3 + 6, Betancourt 2017's generalized slice variant for multinomial sampling).
| PARAMETER | DESCRIPTION |
|---|---|
step_size
|
Initial leapfrog step size; adapted via dual averaging.
TYPE:
|
max_tree_depth
|
Maximum tree doubling depth. Default
TYPE:
|
mass_matrix
|
Mass-matrix shape. Default
TYPE:
|
target_accept
|
Target tree-averaged Metropolis acceptance for dual
averaging. Default
TYPE:
|
divergence_threshold
|
Energy-error threshold above which a leapfrog substep is marked divergent and terminates the tree on its branch.
TYPE:
|
adapt_step_size
|
Whether warmup adapts the step size by dual averaging.
TYPE:
|
adapt_mass_matrix
|
Whether warmup adapts a diagonal or dense metric.
TYPE:
|
adaptation
|
The warmup mode (see
TYPE:
|
adaptation_schedule
|
The windowed schedule; the Stan defaults (75 / 25 / 50) when omitted.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/hmc.py
configuration
¶
configuration() -> dict[str, StateValue]
The kernel's hyperparameters, the maximum tree depth included.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/hmc.py
init
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Reset the adaptation state and build the chain's first state.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
model
|
The model (unused; the potential carries it).
TYPE:
|
x
|
The input (unused).
TYPE:
|
observations
|
The data (unused).
TYPE:
|
initial_position
|
The starting position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The starting state. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/hmc.py
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run one NUTS transition.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state.
TYPE:
|
potential
|
The target.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The next state; |
Source code in src/quivers/inference/mcmc/hmc.py
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 | |
KernelState
didactic-model
¶
KernelState(*, position: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_density: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), grad_log_density: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), step_count: int = 0, accept_count: int = 0, diverged: bool = False, extras: dict[str, StateValue] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), stats: dict[str, float] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), gibbs_values: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
One chain's MCMC state with immutable field updates.
Tensors and mappings are held by identity. A transition returns a state with its own counters and density fields, retaining the runtime references that remain part of the chain.
The log-density and its gradient are evaluated when they are first
read. A transition that knows them at the state it returns (the
endpoint of a trajectory, an accepted candidate) stores them, and a
transition that changes values outside the flat vector, as a
GibbsKernel does, leaves them unevaluated, since the transition
that follows may change those values again without reading the
density. has_density says which, evaluated returns the state with
them evaluated, at the cost of one PotentialFn.value_and_grad when
they are not, and density reads them.
| ATTRIBUTE | DESCRIPTION |
|---|---|
position |
Current flat unconstrained latent vector. Shape
TYPE:
|
log_density |
Unconstrained-space log-density (Jacobian-corrected
log-joint) at
TYPE:
|
grad_log_density |
Gradient of
TYPE:
|
step_count |
Number of
TYPE:
|
accept_count |
Number of proposals accepted across the chain. Useful for reporting acceptance rate.
TYPE:
|
diverged |
Whether the most recent step's energy error exceeded the kernel's divergence threshold. Reset by each kernel as appropriate.
TYPE:
|
extras |
Per-kernel additional state (e.g. NUTS tree depth, HMC step-size adaptation cumulants).
TYPE:
|
stats |
Statistics of the most recent transition, replaced by every
TYPE:
|
gibbs_values |
Current values of the sites a
TYPE:
|
has_density
property
¶
Whether the log-density and gradient at this state are evaluated.
They are not before the chain's first transition, when the
fields hold whatever the kernel's MCMCKernel.init put there,
nor after a transition that left them None.
density
¶
The stored log-density and gradient.
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If they are |
Source code in src/quivers/inference/mcmc/kernel.py
evaluated
¶
evaluated(potential: PotentialFn) -> KernelState
The state with its log-density and gradient evaluated.
| PARAMETER | DESCRIPTION |
|---|---|
potential
|
The target conditioned on this state's
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
This state when |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If a transition left the density unevaluated and it is not finite: the values the transition wrote outside the flat vector have no density under the model. |
Source code in src/quivers/inference/mcmc/kernel.py
state_dict
¶
state_dict() -> dict[str, StateValue]
The state as a dictionary a checkpoint can store.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
Every field, with tensors detached and an unevaluated
density as |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
Source code in src/quivers/inference/mcmc/kernel.py
from_state_dict
classmethod
¶
from_state_dict(state: dict[str, StateValue]) -> 'KernelState'
Rebuild a state from state_dict's output.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The state. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a field is missing or has the wrong type. |
Source code in src/quivers/inference/mcmc/kernel.py
MCMCKernel
¶
Bases: ABC
Abstract Markov kernel on the flat unconstrained latent vector.
Concrete subclasses implement init and step.
Adaptation phases (warmup) typically mutate kernel-internal
state (step size, mass matrix) and freeze it for the sampling
phase; the kernel's is_adapting flag tracks that.
gibbs_sites
property
¶
The latent sites this kernel updates outside the flat vector.
MCMC.run leaves these sites out of the registry, holds their
values in KernelState.gibbs_values, and conditions the
potential on them. A kernel that moves only the flat vector has
none; a GibbsKernel has its blocks, and a composite kernel the
union of its components'.
host_sites
property
¶
The Gibbs sites that are host data, not sample sites of the program.
A subset of gibbs_sites. The program declares no distribution
for such a name: its steps read it as data, the kernel's update
moves it, and MCMC takes each chain's starting value of it
from the caller. A kernel that updates only sample sites of the
program has none, and a composite kernel has the union of its
components'.
tune
¶
tune(population: Tensor) -> None
Tune the kernel to a population of positions.
A population sampler (SMC) calls this after init, at every
temperature, with the current particles; the kernel may set the
parameters it would otherwise adapt (a metric, a proposal scale)
from the population's spread. The base implementation leaves the
kernel as it is.
| PARAMETER | DESCRIPTION |
|---|---|
population
|
The particles' flat positions, shape
TYPE:
|
Source code in src/quivers/inference/mcmc/kernel.py
configuration
¶
configuration() -> dict[str, StateValue]
The kernel's configuration, for telling kernels apart.
A checkpoint records it and MCMC.resume refuses a checkpoint
written by a kernel whose configuration differs. The base
implementation records the class; concrete kernels add their
hyperparameters, and composites their components'.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/kernel.py
state_dict
¶
state_dict() -> dict[str, StateValue]
The kernel's mutable state for one chain.
Everything a chain's continuation depends on beyond its
KernelState and its generator: whether the kernel is adapting,
and its adaptation state (step size, metric, schedule
position). MCMC writes it to a checkpoint and restores it with
load_state_dict after init, so a resumed chain continues bit
for bit.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The state. |
Source code in src/quivers/inference/mcmc/kernel.py
load_state_dict
¶
load_state_dict(state: dict[str, StateValue]) -> None
Restore what state_dict returned.
Called after init for the same chain, which has rebuilt the
kernel's structures for the registry.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the dictionary lacks an entry or holds one of the wrong type. |
Source code in src/quivers/inference/mcmc/kernel.py
init
abstractmethod
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Build the starting KernelState from the supplied
initial flat unconstrained vector. The first transition evaluates
the initial density and gradient before using them.
Source code in src/quivers/inference/mcmc/kernel.py
step
abstractmethod
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Advance the chain one Metropolis step. The potential
function is constructed once per MCMC.run and
re-used across every step / chain.
Source code in src/quivers/inference/mcmc/kernel.py
start_adaptation
¶
Enter the adaptation (warmup) phase.
| PARAMETER | DESCRIPTION |
|---|---|
num_warmup
|
Number of warmup transitions that follow before
TYPE:
|
Source code in src/quivers/inference/mcmc/kernel.py
PotentialFn
¶
PotentialFn(model: MonadicProgram, registry: LatentRegistry, x: Tensor, observations: dict[str, Tensor])
Callable that maps a flat unconstrained position to the unconstrained-space negative log-density and its gradient.
HMC and NUTS need both the potential
:math:U(z) = -\log \tilde{p}(z) (where
:math:\tilde{p}(z) = p(T(z), y) \cdot |\det J_T(z)| is the
Jacobian-corrected unconstrained-space joint) and its gradient
:math:\nabla U(z). The two are computed in a single
autograd pass and cached on the kernel state.
The position z is the registry's flat unconstrained vector.
Inside log_density each latent site is mapped to one
constrained draw of shape LatentSite.constrained_shape and
then handed to MonadicProgram.log_joint as a trace-side value:
non-plate sites at (1, *constrained_shape), with the leading
axis being the program's batch axis, and plate sites at
constrained_shape.
The joint is the one MonadicProgram.log_joint computes, but the
program is not run on the reference machine at every position. The
first evaluation at a layout of the values (the shape, dtype, and
device of each latent, datum, and conditioned value) prepares the
program's scoring run once: its bind chain is compiled to a
straight-line sequence of the program's host steps and its sites'
densities, which every later evaluation at that layout replays,
with the same tensor operations in the same order, so values and
gradients are the machine's bit for bit. The preparation is shared
with every potential condition derives, since conditioning
changes values and not their layout. A layout the preparation does
not describe is evaluated by log_joint itself, every call: a
program with a scan (whose recursion runs over its sequence), a
datum that is not a tensor, and any evaluation made while effect
handlers are on the stack, under another installed evaluator, or of
a program whose log_joint is overridden.
Observed data are checked once, at construction, against the
support of each observed site's distribution, so data that are
not finite or lie outside a likelihood's support raise here rather
than scoring every position -inf; only latent positions
outside the support score -inf. check_initial scores a
starting position strictly and must run once before sampling
(MCMC.run does), catching the remaining program and data errors.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Generative model.
TYPE:
|
registry
|
Latent-site registry for
TYPE:
|
x
|
Model input. Shape
TYPE:
|
observations
|
Observed-site values and host data.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/kernel.py
num_evaluations
property
¶
Forward passes of the log-density so far, gradient ones included.
Counted across this potential and every potential condition
derived from it; check_initial is not counted.
num_gradient_evaluations
property
¶
Calls of value_and_grad so far, across this potential and
every potential condition derived from it.
registry
property
¶
registry: LatentRegistry
The registry whose flat vector the potential is a function of.
conditioned_values
property
¶
conditioned_values: dict[str, Tensor]
The site values condition fixed, keyed by site name.
condition
¶
condition(values: Mapping[str, Tensor]) -> 'PotentialFn'
The potential with further sites held at given values.
The returned potential scores the flat vector exactly as this
one does, with values added to the observations
MonadicProgram.log_joint receives. It replaces, rather than
adds to, any values this potential was itself conditioned on,
so conditioning on a chain's current KernelState.gibbs_values
is always relative to the data the potential was built with.
Conditioning is what lets a GibbsKernel hold sites outside the
flat vector: the other kernels move the flat vector under the
potential conditioned on the Gibbs sites' current values.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
Trace-side values of sites outside the registry (a non-plate site with a leading run axis of one, a plate site at its constrained shape).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PotentialFn
|
A potential of the same class sharing the model, registry, input, and data. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a name in |
Source code in src/quivers/inference/mcmc/kernel.py
log_density
¶
Unconstrained-space log-density (Jacobian-corrected).
z is unflattened into per-site unconstrained tensors,
pushed through each site's bijector to one draw of shape
LatentSite.constrained_shape, and lifted to trace-side
values by LatentRegistry.trace_values with a batch of one.
MonadicProgram.log_joint thus receives every non-plate site
at (1, *constrained_shape) (the program's (batch, ...)
input convention, which broadcasts against the input x)
and every plate site at constrained_shape. A custom
density reached through log_joint should index that
leading axis accordingly; the shapes reported by
MCMCResult carry no such axis.
A position outside the model's support scores -inf, and
the kernel rejects it. Errors from log_joint that mark
this are a ValueError from Torch distribution validation
or the inline positive-parameter validator (a scale that
underflows to zero, a latent pushed onto its boundary), and
a torch.linalg.LinAlgError from factorizing a matrix the
position makes non-positive-definite. They are recognised by
where they are raised, not by their message. Every other
error (a shape or dtype mismatch, an error in a custom score
function, a missing name) propagates, and so do the
validation errors that hold at every position, which
check_initial raises before sampling starts.
| PARAMETER | DESCRIPTION |
|---|---|
z
|
Flat unconstrained position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar Jacobian-corrected log-density, or |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Exception
|
Any error |
Source code in src/quivers/inference/mcmc/kernel.py
log_density_batch
¶
The log-density of log_density at many positions in one pass.
The program is scored once, with the positions mapped along a
position axis of their own (torch.func.vmap): the bijectors and
their log-Jacobians, every step, and every site's density are
computed for all rows together, and a value that depends on no
latent (a datum, or a step that reads data alone) is computed
once and shared by the rows. Each row's value is the
log_density of that row up to rounding, and a row outside the
model's support scores -inf without affecting the others.
Every step has to declare that it can be evaluated this way. A
step whose value is a Python callable the program cannot inspect
declares it with batched=True
(Let,
Score): the callable
is then called with the position axis leading every value that
depends on the position, and returns its result the same way. The
steps the DSL compiles and the distributions of the library carry
their own declaration.
| PARAMETER | DESCRIPTION |
|---|---|
positions
|
Flat unconstrained positions, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The Jacobian-corrected log-density of each row, shape
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
UnbatchableProgramError
|
If a step of the program does not declare that it can be
evaluated at many positions, or the program is not scored by
its own steps (its |
PositionLayoutError
|
If a callable declared |
Exception
|
Any error |
Source code in src/quivers/inference/mcmc/kernel.py
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 | |
check_initial
¶
Score a chain's initial position, raising on any failure.
Run once before sampling. The program is scored with
torch.distributions validation enabled and no error
converted, so mismatched row counts, data a score function
reads that its distribution rejects, and errors in custom
score functions raise here with their own type. A
position that scores a non-finite log-density raises, naming
the sites whose log-density is not finite.
| PARAMETER | DESCRIPTION |
|---|---|
z
|
Flat unconstrained initial position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The finite scalar Jacobian-corrected log-density at |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the log-density at |
Exception
|
Any error |
Source code in src/quivers/inference/mcmc/kernel.py
value_and_grad
¶
Return (log_density, grad_log_density) for z.
One call runs one forward pass of log_density and one
backward pass, and the HMC and NUTS integrators make exactly
one call per leapfrog step. The gradient is taken against a
fresh leaf copy of z with autograd enabled, so the call
differentiates even inside a torch.no_grad() block and
gradient propagation does not leak into the kernel's state.
For divergent positions (where the log-density is
-inf), returns a zero gradient: the kernel rejects
the trajectory in the Metropolis step anyway, and a zero
gradient keeps the leapfrog integrator from producing NaN
downstream.
| PARAMETER | DESCRIPTION |
|---|---|
z
|
Flat unconstrained position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The detached scalar log-density and its detached
gradient with respect to |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Any error |
Source code in src/quivers/inference/mcmc/kernel.py
value_and_grad_batch
¶
The value and gradient of value_and_grad at many positions.
One call runs one log_density_batch and one backward pass. Each
row's gradient is that of its own log-density with respect to its
own position, and, as in value_and_grad, is zero at a row whose
log-density or gradient is not finite.
| PARAMETER | DESCRIPTION |
|---|---|
positions
|
Flat unconstrained positions, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The detached log-densities, shape |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
UnbatchableProgramError
|
As |
Exception
|
Any error |
Source code in src/quivers/inference/mcmc/kernel.py
IndependenceProposal
¶
IndependenceProposal(distribution: Distribution, defensive: Distribution | None = None, defensive_weight: float = 0.1)
Bases: Proposal
Independence proposal from a fixed distribution over the flat vector.
Candidates are drawn from :math:q, whatever the current position,
and the correction is :math:\log q(z) - \log q(z'). With a
defensive distribution :math:d the proposal is the mixture
:math:q = (1 - w)\, g + w\, d of distribution :math:g and
:math:d with weight :math:w, which keeps the importance ratio
:math:\tilde p / q bounded where :math:g has lighter tails than
the target, the usual way to correct a fitted variational
approximation exactly (Hesterberg 1995,
doi:10.1080/00401706.1995.10484303
<https://doi.org/10.1080/00401706.1995.10484303>_).
| PARAMETER | DESCRIPTION |
|---|---|
distribution
|
The proposal :math:
TYPE:
|
defensive
|
The defensive component :math:
TYPE:
|
defensive_weight
|
The weight :math:
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a distribution has a batch shape or an event shape other than
a vector, or |
Source code in src/quivers/inference/mcmc/metropolis.py
configuration
¶
configuration() -> dict[str, StateValue]
The distributions' classes, the weight, and the proposal's log-density at two fixed points, which tells distributions with different parameters apart.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/metropolis.py
bind
¶
bind(registry: LatentRegistry) -> None
Check the proposal's event shape against the flat vector.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the event shape is not |
Source code in src/quivers/inference/mcmc/metropolis.py
log_prob
¶
The proposal's log-density.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
A flat position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The scalar :math: |
Source code in src/quivers/inference/mcmc/metropolis.py
propose
¶
Draw from the proposal, independently of position.
| PARAMETER | DESCRIPTION |
|---|---|
position
|
The current position, shape
TYPE:
|
generator
|
The chain-local generator; the component choice and the draw both come from it.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The candidate and |
Source code in src/quivers/inference/mcmc/metropolis.py
MetropolisKernel
¶
MetropolisKernel(proposal: Proposal)
Bases: MCMCKernel
Metropolis-Hastings kernel on the flat unconstrained vector.
One transition draws a candidate from the Proposal, scores it by
PotentialFn.log_density alone, and accepts it with probability
:math:\min(1, \exp(\log \tilde p(z') - \log \tilde p(z) +
\log c)), with :math:\log c the proposal's Hastings correction.
The gradient is evaluated only when the candidate is accepted, so
the state a gradient kernel receives next carries the gradient at
its position. A candidate outside the model's support scores
:math:-\infty and is rejected.
The kernel has no adaptation of its own; start_adaptation and
stop_adaptation only toggle is_adapting.
| PARAMETER | DESCRIPTION |
|---|---|
proposal
|
The proposal.
TYPE:
|
Source code in src/quivers/inference/mcmc/metropolis.py
tune
¶
tune(population: Tensor) -> None
Forward a population to the proposal (Proposal.tune).
| PARAMETER | DESCRIPTION |
|---|---|
population
|
Flat positions, shape
TYPE:
|
Source code in src/quivers/inference/mcmc/metropolis.py
configuration
¶
configuration() -> dict[str, StateValue]
The class and the proposal's configuration.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/metropolis.py
state_dict
¶
state_dict() -> dict[str, StateValue]
Whether the kernel is adapting, and the proposal's state.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The state. |
Source code in src/quivers/inference/mcmc/metropolis.py
load_state_dict
¶
load_state_dict(state: dict[str, StateValue]) -> None
Restore what state_dict returned.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an entry is missing or has the wrong type. |
Source code in src/quivers/inference/mcmc/metropolis.py
init
¶
init(registry: LatentRegistry, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], initial_position: Tensor) -> KernelState
Bind the proposal and build the chain's first state.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
model
|
The model (unused; the potential carries it).
TYPE:
|
x
|
The input (unused).
TYPE:
|
observations
|
The data (unused).
TYPE:
|
initial_position
|
The starting position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The starting state; its log-density and gradient are evaluated by the first transition. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/metropolis.py
step
¶
step(state: KernelState, potential: PotentialFn) -> KernelState
Run one Metropolis-Hastings transition.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
The current state.
TYPE:
|
potential
|
The target, conditioned on the state's Gibbs values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
KernelState
|
The next state, with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the proposal returns a candidate of the wrong shape or a correction that is not a scalar. |
Source code in src/quivers/inference/mcmc/metropolis.py
Proposal
¶
Bases: ABC
A Metropolis-Hastings proposal on the flat unconstrained vector.
Subclasses implement propose, and override bind when the
proposal needs the registry's layout (a site's offset in the flat
vector, for instance, to permute exchangeable blocks).
bind
¶
bind(registry: LatentRegistry) -> None
Receive the registry of the chain the proposal will move.
MetropolisKernel.init calls this once per chain, before the
first propose. The base implementation records nothing.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
Source code in src/quivers/inference/mcmc/metropolis.py
tune
¶
tune(population: Tensor) -> None
Tune the proposal to a population of positions.
MetropolisKernel.tune forwards the population here; the base
implementation leaves the proposal as it is.
| PARAMETER | DESCRIPTION |
|---|---|
population
|
Flat positions, shape
TYPE:
|
Source code in src/quivers/inference/mcmc/metropolis.py
configuration
¶
configuration() -> dict[str, StateValue]
The proposal's configuration, for telling kernels apart.
The base implementation records the class; a proposal with
parameters adds them, so that MCMC.resume refuses a checkpoint
written with different ones.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/metropolis.py
state_dict
¶
state_dict() -> dict[str, StateValue]
The proposal's mutable state for one chain.
The base implementation, for a proposal without state, is empty;
a proposal that adapts or otherwise changes during a run returns
what load_state_dict needs to continue it exactly.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The state. |
Source code in src/quivers/inference/mcmc/metropolis.py
load_state_dict
¶
load_state_dict(state: dict[str, StateValue]) -> None
Restore what state_dict returned, after bind.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
Source code in src/quivers/inference/mcmc/metropolis.py
propose
abstractmethod
¶
Draw a candidate and its log Hastings correction.
| PARAMETER | DESCRIPTION |
|---|---|
position
|
The current flat unconstrained position, shape
TYPE:
|
generator
|
The chain-local generator every random draw must use.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The candidate, shape |
Source code in src/quivers/inference/mcmc/metropolis.py
RandomWalkProposal
¶
RandomWalkProposal(scale: float | Tensor)
Bases: Proposal
Gaussian random-walk proposal :math:z' = z + \sigma \odot \epsilon.
The proposal is symmetric, so its Hastings correction is zero.
| PARAMETER | DESCRIPTION |
|---|---|
scale
|
The step scale :math:
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a scale is not positive and finite. |
Source code in src/quivers/inference/mcmc/metropolis.py
tune
¶
tune(population: Tensor) -> None
Scale the walk to a population's spread.
The scale becomes :math:2.38 / \sqrt{D} times each
coordinate's population standard deviation, the asymptotically
optimal random-walk scaling for a Gaussian target (Roberts,
Gelman, and Gilks 1997, doi:10.1214/aoap/1034625254
<https://doi.org/10.1214/aoap/1034625254>_).
| PARAMETER | DESCRIPTION |
|---|---|
population
|
Flat positions, shape
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the population has fewer than two rows or a coordinate with no spread. |
Source code in src/quivers/inference/mcmc/metropolis.py
configuration
¶
configuration() -> dict[str, StateValue]
The class and the step scale.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The configuration. |
Source code in src/quivers/inference/mcmc/metropolis.py
state_dict
¶
state_dict() -> dict[str, StateValue]
The step scale, which tune may have changed.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, StateValue]
|
The scale. |
load_state_dict
¶
load_state_dict(state: dict[str, StateValue]) -> None
Restore the step scale.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
A dictionary
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the scale is missing. |
Source code in src/quivers/inference/mcmc/metropolis.py
bind
¶
bind(registry: LatentRegistry) -> None
Check a per-coordinate scale against the flat vector's length.
| PARAMETER | DESCRIPTION |
|---|---|
registry
|
The registry whose flat vector the chain walks.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/mcmc/metropolis.py
propose
¶
Draw position + scale * N(0, I).
| PARAMETER | DESCRIPTION |
|---|---|
position
|
The current position, shape
TYPE:
|
generator
|
The chain-local generator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The candidate and a zero correction. |
Source code in src/quivers/inference/mcmc/metropolis.py
ChainStates
didactic-model
¶
ChainStates(*, fingerprint: str, run_seed: int, states: Mapping[int, dict[str, StateValue]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
The records of the chains one worker ran.
| PARAMETER | DESCRIPTION |
|---|---|
fingerprint
|
Model fingerprint of the worker's rebuilt program and data, which must equal the parent's.
TYPE:
|
run_seed
|
The run seed the worker derived its chain streams from.
TYPE:
|
states
|
Each chain's record, as a checkpoint stores it, keyed by chain index.
TYPE:
|
ChainWorker
¶
Bases: Protocol
A picklable recipe that rebuilds a run and runs some of its chains.
A worker is called in a fresh process with the chain indices assigned to
it. It rebuilds the program, data, and driver exactly as the parent built
them and returns run_chains of the assigned chains.
__call__
¶
__call__(chains: tuple[int, ...]) -> ChainStates
Run the assigned chains.
| PARAMETER | DESCRIPTION |
|---|---|
chains
|
Chain indices.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ChainStates
|
Their records. |
find_reasonable_step_size
¶
find_reasonable_step_size(log_density: Callable[[Tensor], Tensor], grad_log_density: Callable[[Tensor], Tensor], z0: Tensor, initial_step: float = 1.0, target_log_accept: float = log(0.5)) -> float
Heuristic-by-doubling initial step size (Hoffman-Gelman 2014 Algorithm 4).
Starting from initial_step, doubles or halves the step size
until a single leapfrog step's Metropolis log-acceptance crosses
target_log_accept (default :math:\log 0.5). Returns the
step size at the crossing.
Source code in src/quivers/inference/mcmc/adapt.py
assemble_chains
¶
assemble_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], parts: Sequence[ChainStates]) -> MCMCResult
Assemble the result of a run from its chains' records.
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The parent's driver.
TYPE:
|
model
|
The parent's program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
parts
|
Every worker's records.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
The result |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a worker rebuilt a different program or data, used another run seed, or the parts do not cover every chain exactly once. |
Source code in src/quivers/inference/mcmc/parallel.py
parallel_chains
¶
parallel_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], worker: ChainWorker, cores: int) -> MCMCResult
Run a driver's chains in up to cores worker processes.
Chains are dealt to workers in turn (chain c to worker
c mod cores). Each worker is a fresh interpreter running
quivers.inference.mcmc._chain_entry, so none inherits the parent's
state or imports the calling script, and each uses the parent's thread
count. The result equals mcmc.run(model, x, observations).
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The parent's driver: it must have an explicit seed, which every worker shares, and no checkpoint or callback, which cannot be shared across processes.
TYPE:
|
model
|
The parent's program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
worker
|
Picklable recipe rebuilding the run in a worker.
TYPE:
|
cores
|
Maximum worker processes (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
The run's result. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
RuntimeError
|
If a worker process fails; the remaining workers are stopped. |
Source code in src/quivers/inference/mcmc/parallel.py
run_chains
¶
run_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], chains: Sequence[int], guide: Guide | None = None) -> ChainStates
Run some chains of a run as MCMC.run runs them.
Chain c starts from its own stream MCMC._chain_generator(seed, c)
with fresh kernel adaptation, so its record does not depend on which
other chains run in the same process.
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The driver, with a seed and no checkpoint or callback.
TYPE:
|
model
|
The program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
chains
|
Chain indices to run.
TYPE:
|
guide
|
Guide for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ChainStates
|
The chains' records and the model fingerprint. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a chain index is out of range. |
Source code in src/quivers/inference/mcmc/parallel.py
Parallel chains¶
A compiled program holds compilation-local family catalogs and prepared
evaluation plans, and a kernel holds the adaptation state of the chain it
runs, so neither is sent to another process. Instead,
parallel_chains starts
worker processes by the spawn method and gives each a picklable recipe, a
ChainWorker, which rebuilds
the program and data as the parent built them and runs its share of the
chains with run_chains. Chain
c draws from the stream the driver derives from the run seed and c, with
fresh kernel adaptation, so a chain's record does not depend on the process
it ran in. The parent checks each worker's model fingerprint and run seed and
assembles the records with the driver's own result assembly, so the result
equals the serial run with the same seed, draw for draw. A run with a
checkpoint, a callback, or no explicit seed is refused. Formula fits take
brms's cores, and MCMCMethod takes
cores for a model built from QVR source.
parallel
¶
Run the chains of one MCMC run in separate processes.
A compiled program holds compilation-local family catalogs and prepared
evaluation plans that do not cross a process boundary, and a kernel holds
the adaptation state of the chain it runs. Each worker process therefore
rebuilds the program from a picklable recipe (a ChainWorker), builds its
own driver and kernel, and runs only the chains assigned to it with the
streams MCMC derives from the run seed and the chain index. The parent
reads every chain's record back into the driver's result, so the draws,
statistics, and evaluation counts are those of the serial run with the same
seed.
ChainStates
didactic-model
¶
ChainStates(*, fingerprint: str, run_seed: int, states: Mapping[int, dict[str, StateValue]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
The records of the chains one worker ran.
| PARAMETER | DESCRIPTION |
|---|---|
fingerprint
|
Model fingerprint of the worker's rebuilt program and data, which must equal the parent's.
TYPE:
|
run_seed
|
The run seed the worker derived its chain streams from.
TYPE:
|
states
|
Each chain's record, as a checkpoint stores it, keyed by chain index.
TYPE:
|
ChainWorker
¶
Bases: Protocol
A picklable recipe that rebuilds a run and runs some of its chains.
A worker is called in a fresh process with the chain indices assigned to
it. It rebuilds the program, data, and driver exactly as the parent built
them and returns run_chains of the assigned chains.
__call__
¶
__call__(chains: tuple[int, ...]) -> ChainStates
Run the assigned chains.
| PARAMETER | DESCRIPTION |
|---|---|
chains
|
Chain indices.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ChainStates
|
Their records. |
run_chains
¶
run_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], chains: Sequence[int], guide: Guide | None = None) -> ChainStates
Run some chains of a run as MCMC.run runs them.
Chain c starts from its own stream MCMC._chain_generator(seed, c)
with fresh kernel adaptation, so its record does not depend on which
other chains run in the same process.
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The driver, with a seed and no checkpoint or callback.
TYPE:
|
model
|
The program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
chains
|
Chain indices to run.
TYPE:
|
guide
|
Guide for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ChainStates
|
The chains' records and the model fingerprint. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a chain index is out of range. |
Source code in src/quivers/inference/mcmc/parallel.py
assemble_chains
¶
assemble_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], parts: Sequence[ChainStates]) -> MCMCResult
Assemble the result of a run from its chains' records.
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The parent's driver.
TYPE:
|
model
|
The parent's program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
parts
|
Every worker's records.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
The result |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a worker rebuilt a different program or data, used another run seed, or the parts do not cover every chain exactly once. |
Source code in src/quivers/inference/mcmc/parallel.py
parallel_chains
¶
parallel_chains(mcmc: MCMC, model: MonadicProgram, x: Tensor, observations: dict[str, Tensor], worker: ChainWorker, cores: int) -> MCMCResult
Run a driver's chains in up to cores worker processes.
Chains are dealt to workers in turn (chain c to worker
c mod cores). Each worker is a fresh interpreter running
quivers.inference.mcmc._chain_entry, so none inherits the parent's
state or imports the calling script, and each uses the parent's thread
count. The result equals mcmc.run(model, x, observations).
| PARAMETER | DESCRIPTION |
|---|---|
mcmc
|
The parent's driver: it must have an explicit seed, which every worker shares, and no checkpoint or callback, which cannot be shared across processes.
TYPE:
|
model
|
The parent's program.
TYPE:
|
x
|
One-row input.
TYPE:
|
observations
|
Data.
TYPE:
|
worker
|
Picklable recipe rebuilding the run in a worker.
TYPE:
|
cores
|
Maximum worker processes (brms
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MCMCResult
|
The run's result. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
RuntimeError
|
If a worker process fails; the remaining workers are stopped. |
Source code in src/quivers/inference/mcmc/parallel.py
Sequential Monte Carlo¶
Tempered sequential Monte Carlo
moves a population from the prior to the posterior, rejuvenating it with
any of the kernels above, and estimates the evidence
(Del Moral et al., 2006). Typed score roles determine the temperature
path: prior potentials remain in the prior term, while observations and
likelihood scores are tempered. SMC.run initializes through the shared
ancestral prior projection and refuses unknown prior-potential normalizers.
Its log normalizing constant is ordinary model evidence only when the
sampling and prior factors have that interpretation. Both SMC.run and
TemperedPotential refuse opaque MonadicProgram.log_joint overrides,
which expose no prior/likelihood roles. Factor callbacks inside typed Score
steps retain those roles. This restriction does not change ordinary
PotentialFn scoring of overridden joints.
smc
¶
Adaptive likelihood-tempered sequential Monte Carlo.
SMC moves a population of particles from the prior to the posterior
through the tempered targets
.. math::
\pi_\beta(z) \propto p(z)\, L(z)^\beta, \qquad
0 = \beta_0 < \beta_1 < \dots < \beta_T = 1,
where :math:p(z) is the density of the model's latent draws and
explicit prior potentials, and :math:L(z) contains its observations and
score steps classified as likelihoods (Del Moral, Doucet, and Jasra 2006,
doi:10.1111/j.1467-9868.2006.00553.x
<https://doi.org/10.1111/j.1467-9868.2006.00553.x>_). Each step
- chooses the next temperature by bisection, as the largest
:math:
\beta' \le 1at which the conditional effective sample size of the incremental weights :math:L(z_i)^{\beta' - \beta}is at leasttarget_esstimes the number of particles (Jasra et al. 2011,doi:10.1111/j.1467-9469.2010.00723.x <https://doi.org/10.1111/j.1467-9469.2010.00723.x>; Zhou, Johansen, and Aston 2016,doi:10.1080/10618600.2015.1060885 <https://doi.org/10.1080/10618600.2015.1060885>); - reweights by those increments, adding the log of their weighted mean to the log-evidence estimate;
- resamples by the chosen
ResamplingScheme; - rejuvenates every particle by
num_mcmc_stepstransitions of the kernel at the new temperature, with the kernel's parameters fixed for the whole step: a pilot run on a particle, discarded, tunes them after the kernel has seen the population (MCMCKernel.tune), and every particle then moves under the frozen kernel, so each move leaves :math:\pi_{\beta'}invariant.
The product of the mean incremental weights estimates the normalizing
constant :math:Z = \int p(z) L(z)\, dz; its logarithm is
SMCResult.log_evidence. It is data evidence when the factors define a
normalized prior and sampling model. Arbitrary prior score potentials are
refused by SMC.run, because ancestral initialization does not normalize them.
Non-unit likelihood weights instead define a power-target normalizing constant.
ResamplingScheme
module-attribute
¶
How SMC resamples its particles; each draws every particle's
number of copies with expectation N times its normalized weight
(Douc and Cappé 2005, doi:10.1109/ISPA.2005.195385
<https://doi.org/10.1109/ISPA.2005.195385>_):
"multinomial":Nindependent draws from the weights;"stratified": one uniform draw in each ofNequal strata of the cumulative weights;"systematic": one uniform offset shared by theNstrata;"residual":floor(N w_i)copies of each particle, and the remaining copies by multinomial draws from the residual weights.
TemperedPotential
¶
TemperedPotential(model: MonadicProgram, registry: LatentRegistry, x: Tensor, observations: dict[str, Tensor], temperature: float = 1.0)
Bases: PotentialFn
The potential of a tempered posterior :math:p(z)\, L(z)^\beta.
:math:\log p(z) contains the model's latent draw densities,
explicit score potentials, and the bijectors' log-Jacobian.
:math:\log L(z) contains observations and scores whose typed role
is "likelihood". Registry and conditioned-site identities determine
which draws remain latent; a clamped observed draw belongs to the likelihood.
At temperature one the potential is the posterior's, at zero the
prior's.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
The model.
TYPE:
|
registry
|
The latent registry.
TYPE:
|
x
|
The one-row input.
TYPE:
|
observations
|
The data.
TYPE:
|
temperature
|
The inverse temperature :math:
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/smc.py
at_temperature
¶
The same potential at another temperature.
| PARAMETER | DESCRIPTION |
|---|---|
temperature
|
The inverse temperature, in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TemperedPotential
|
A copy sharing the model, data, conditioning, and evaluation counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/smc.py
log_prior_and_likelihood
¶
The two parts of the log joint at a position.
| PARAMETER | DESCRIPTION |
|---|---|
z
|
Flat unconstrained position, shape
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
Exception
|
Any error the program raises other than one marking the position as outside its support. |
Source code in src/quivers/inference/smc.py
SMCResult
didactic-model
¶
SMCResult(*, samples: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_evidence: float, temperatures: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), ess: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), acceptance: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_evidence_increments: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_likelihoods: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), num_evaluations: int)
Bases: ValueModel
The output of an SMC run.
| ATTRIBUTE | DESCRIPTION |
|---|---|
samples |
The final, equally weighted particles on the constrained support,
Gibbs sites included: each site at
TYPE:
|
log_evidence |
The log of the evidence estimate
:math:
TYPE:
|
temperatures |
The ladder :math:
TYPE:
|
ess |
The effective sample size, as a fraction of the population, of
the weights at each temperature before resampling, shape
TYPE:
|
acceptance |
The mean acceptance of the rejuvenation moves at each
temperature, shape
TYPE:
|
log_evidence_increments |
The log mean incremental weight at each temperature, shape
TYPE:
|
log_likelihoods |
:math:
TYPE:
|
num_evaluations |
Potential evaluations over the run.
TYPE:
|
SMC
¶
SMC(kernel: MCMCKernel, num_particles: int = 1024, num_mcmc_steps: int = 5, target_ess: float = 0.5, resampling: ResamplingScheme = 'systematic', num_pilot_steps: int = 50, *, seed: int | None = None, generator: Generator | None = None)
Adaptive likelihood-tempered sequential Monte Carlo sampler.
| PARAMETER | DESCRIPTION |
|---|---|
kernel
|
The rejuvenation kernel: any kernel, composites and Gibbs blocks included. Its configuration is shared by every particle; it is re-tuned at every temperature.
TYPE:
|
num_particles
|
Population size. Default
TYPE:
|
num_mcmc_steps
|
Rejuvenation transitions per particle per temperature. Default
TYPE:
|
target_ess
|
The conditional effective sample size, as a fraction of the
population, each temperature step is chosen to keep. Default
TYPE:
|
resampling
|
The resampling scheme. Default
TYPE:
|
num_pilot_steps
|
Adaptation transitions of the discarded pilot run that tunes the
kernel at each temperature;
TYPE:
|
seed
|
Seed of the run's generator. A run with the same seed is reproducible and leaves Torch's global RNG alone.
TYPE:
|
generator
|
Caller-owned CPU generator from which each run draws its seed;
mutually exclusive with
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a count is out of range, |
Source code in src/quivers/inference/smc.py
run
¶
run(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor]) -> SMCResult
Run the sampler from the prior to the posterior.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
The model.
TYPE:
|
x
|
A one-row input; as for
TYPE:
|
observations
|
Observed-site values and host data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SMCResult
|
The final particles, the evidence estimate, and the ladder. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
RuntimeError
|
If no temperature step keeps the target ESS. |
Source code in src/quivers/inference/smc.py
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 750 751 752 753 754 755 756 757 758 759 | |
resample
¶
resample(weights: Tensor, scheme: ResamplingScheme, generator: Generator | None = None) -> Tensor
Draw ancestor indices for a weighted population.
| PARAMETER | DESCRIPTION |
|---|---|
weights
|
Non-negative weights, shape
TYPE:
|
scheme
|
The resampling scheme.
TYPE:
|
generator
|
The generator every uniform draw comes from.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the weights are not a non-negative vector with a positive finite sum, or the scheme is unknown. |
Source code in src/quivers/inference/smc.py
Sequential particles for paths¶
sequence_particle_filter
extends a fixed population through a fixed number of path positions.
At a path prefix \(a_{1:t-1}\), the target supplies a positive potential
\(\psi_t(a_{1:t})\) and a successor state for each structurally
eligible action. The batched callbacks evaluate each path prefix
independently of the other particles and its position in the
population. The target and proposal have the same eligible
actions. Every eligible prefix extends to a complete path. Proposal
logits may depend on all observations. The positive lookahead
twists \(C_t\) have \(C_0=C_T=1\), with the terminal equality checked
before drawing that stage.
The algorithm proposes an action under \(q_t\) and forms the weight
The product of the stage mean weights \(\widehat Z_t\) estimates the unnormalized mass of prefixes weighted by \(C_t\). For a path test \(f\), let \(U_t(f)\) be \(\widehat Z_t\) times the weighted population average of \(f\). The conditional mean of each resampled offspring count is the population size times its parent's normalized weight. The next proposal expectation cancels \(q_t\) in \(w_t\). Thus the conditional expectation of \(U_t(f)\) after extending the population is \(U_{t-1}\) applied to the sum of \(f\) over each parent's extensions, weighted by \(\psi_t C_t/C_{t-1}\). Starting from the single empty prefix gives
in exact arithmetic. Taking \(f=1\) verifies the mass estimate. A ratio of estimated masses and \(\log\widehat Z_T\) can each be biased at finite population size. Lin and Eisner (2018), §4 and Douc, Cappé, and Moulines (2005), §2.1.
For a smooth target on fixed support, choose \(f(a)=\nabla_\theta\sum_t\log\psi_t(a_{1:t})\) to estimate the unnormalized mass derivative. A fixed path event can multiply this test function by its indicator. The score surrogate uses detached importance weights and the live target score along each selected history. Proposal and twist values determine draws and corrections and have no gradient through this estimator. The derivative concerns the unnormalized mass. Returned log normalizers and normalized importance weights are detached.
For \(T\) stages, \(N\) particles, \(K\) action positions and state width \(D\), the declared candidate count is \(TNK\). Each candidate-state batch has \(NKD\) scalars, and the two ordered genealogy tables use \(O(TN)\) integers. The algorithm draws one action per particle per stage and performs \(T-1\) multinomial resampling calls over \(N\) parents. The arithmetic of callback evaluation, its saved differentiation tensors, and the sampling backend's implementation contribute additional work. The binary64 implementation refuses loss of positive proposal or particle support through underflow and refuses unrepresentable stage scores. The path-dependent example uses ordinary checked QVR target and proposal computations.
SequenceParticleResult
dataclass
¶
SequenceParticleResult(paths: Tensor, target_log_scores: Tensor, log_probabilities: Tensor, log_normalizer: Tensor, candidate_count: int)
A weighted terminal population of ordered action histories.
| PARAMETER | DESCRIPTION |
|---|---|
paths
|
The chosen action indices in particle and step order. Duplicate histories retain their distinct population slots.
TYPE:
|
target_log_scores
|
The cumulative original log potentials along each returned history, with gradients through the chosen target states.
TYPE:
|
log_probabilities
|
Detached normalized terminal importance weights in log space.
TYPE:
|
log_normalizer
|
The detached log of the product of mean incremental weights.
TYPE:
|
candidate_count
|
The number of candidate slots evaluated across the stages.
TYPE:
|
score_surrogate
¶
Supply a target derivative estimate for unnormalized path mass.
The derivative uses the sampled target log-score gradients, weighted by detached unnormalized particle mass. With exact arithmetic and sampling, its expectation equals the derivative of the partition, restricted to the event when supplied.
| PARAMETER | DESCRIPTION |
|---|---|
event
|
One Boolean indicator per returned history. The event is a fixed function of the path. None includes every history.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
A scalar surrogate whose derivative is the estimate. Its value is a weighted sum of log scores. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
The supplied event has the wrong shape, dtype, or device. |
OverflowError
|
A positive coefficient or the scalar sum cannot be represented in the evaluation precision. |
Source code in src/quivers/inference/sequence_particles.py
sequence_particle_filter
¶
sequence_particle_filter(initial_state: Tensor, advance: Callable[[int, Tensor], tuple[Tensor, Tensor]], propose: Callable[[int, Tensor, Tensor], tuple[Tensor, Tensor]], *, steps: int, particles: int, actions: int, max_candidates: int, max_state_elements: int, generator: Generator | None = None) -> SequenceParticleResult
Estimate unnormalized path mass by sequential multinomial resampling.
At each step each particle proposes one action. Its incremental weight is the target potential times the current positive lookahead twist, divided by the proposal probability and the previous twist. The initial twist is one and every eligible terminal twist must be one. The mean incremental weight contributes to the normalizer before each reset, including the final weighted population.
The callbacks batch independent evaluations of each path prefix. A row depends only on that path, the step, and the data and parameters fixed for the run. Action positions identify the same actions across population slots. The target's original autodiff graph is live along the selected histories. The proposal and lookahead are evaluated on detached candidate values. Ordered categorical draws and multinomial ancestry carry no gradient.
| PARAMETER | DESCRIPTION |
|---|---|
initial_state
|
One dense, finite float64 state vector, copied across slots by broadcasting. The callbacks treat state arguments as read-only.
TYPE:
|
advance
|
Given the zero-based step and a particles-by-state tensor, return the successor states and their finite target log potentials, in particle and action order. Use constant -inf for a structurally forbidden action. Every eligible prefix must extend to a complete valid history.
TYPE:
|
propose
|
Given the step, detached successor states and detached target log potentials, return proposal logits and log twists with the same particle and action axes. The proposal must be positive exactly on the eligible actions. Eligible log twists must be finite and zero at the final step.
TYPE:
|
steps
|
Positive length shared by every admitted history.
TYPE:
|
particles
|
Positive fixed population size.
TYPE:
|
actions
|
Positive number of candidate action positions per step.
TYPE:
|
max_candidates
|
Limit on the total number of evaluated candidate slots, including structurally forbidden ones.
TYPE:
|
max_state_elements
|
Limit on the number of scalar entries in one candidate-state batch. Callback-internal work and buffers are caller-owned.
TYPE:
|
generator
|
The generator for proposal draws and multinomial ancestry.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SequenceParticleResult
|
Final weighted paths, live target scores, and sampled evidence. Normalized finite population expectations and the log of the normalizer estimate can be biased. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
A bound, state, callback output, support, or terminal twist violates the contract. |
OverflowError
|
A positive sampling weight or a finite stage score is outside the binary64 evaluation range. |
Source code in src/quivers/inference/sequence_particles.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
Variational warmup¶
WarmupThenHMC fits a guide with stochastic variational inference (SVI) and starts the chains from it.
warmup
¶
Run variational warmup before HMC or NUTS.
The orchestrator fits a guide with SVI, initializes the Markov chain from the guide, adapts the mass matrix from its covariance, and runs the configured MCMC driver.
WarmupThenHMC
¶
WarmupThenHMC(guide: Guide, kernel: MCMCKernel, svi_steps: int, mcmc_warmup: int, mcmc_samples: int, num_chains: int = 2, svi_lr: float = 0.01, objective: Objective | None = None)
Composite sampler: SVI warmup followed by HMC / NUTS chain.
| PARAMETER | DESCRIPTION |
|---|---|
guide
|
Variational guide trained in the SVI warmup phase. Any
TYPE:
|
kernel
|
Markov kernel for the sampling phase (typically
TYPE:
|
svi_steps
|
Number of SVI steps in the warmup phase.
TYPE:
|
svi_lr
|
Learning rate for the SVI optimizer. Default
TYPE:
|
mcmc_warmup
|
MCMC kernel's own warmup (on top of the SVI warmup; HMC still benefits from a few step-size-adaptation iterations because the SVI-mean's typical-set position differs from the maximum-density point).
TYPE:
|
mcmc_samples
|
Number of post-warmup MCMC samples per chain.
TYPE:
|
num_chains
|
Number of MCMC chains.
TYPE:
|
objective
|
SVI objective. Default
TYPE:
|
Source code in src/quivers/inference/warmup.py
fit_guide
¶
fit_guide(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor]) -> list[float]
Run the SVI warmup phase and return the per-step losses.
Source code in src/quivers/inference/warmup.py
run_mcmc
¶
run_mcmc(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor]) -> MCMCResult
Run the post-warmup MCMC phase. Chains are seeded from
the fitted guide via MCMC.run's init_strategy='guide'.
Source code in src/quivers/inference/warmup.py
run
¶
run(model: MonadicProgram, x: Tensor, observations: dict[str, Tensor]) -> tuple[list[float], MCMCResult]
Convenience: SVI warmup, then MCMC sampling.
Returns (svi_losses, mcmc_result).
Source code in src/quivers/inference/warmup.py
Cited sources¶
Radford M. Neal. MCMC Using Hamiltonian Dynamics. In Steve Brooks, Andrew Gelman, Galin L. Jones, and Xiao-Li Meng, editors, Handbook of Markov Chain Monte Carlo, chapter 5, pages 113–162. Chapman and Hall/CRC, 2011. URL: https://doi.org/10.1201/b10905-6, doi:10.1201/b10905-6.
Matthew D. Hoffman and Andrew Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47):1593–1623, 2014. URL: https://www.jmlr.org/papers/v15/hoffman14a.html.
Alexandros Beskos, Natesh Pillai, Gareth Roberts, Jesus-Maria Sanz-Serna, and Andrew Stuart. Optimal tuning of the hybrid Monte Carlo algorithm. Bernoulli, 19(5A):1501–1534, 2013. URL: https://doi.org/10.3150/12-BEJ414, doi:10.3150/12-BEJ414.
Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved R-hat for Assessing Convergence of MCMC (with Discussion). Bayesian Analysis, 16(2):667–718, 2021. URL: https://doi.org/10.1214/20-BA1221, doi:10.1214/20-BA1221.
Pierre Del Moral, Arnaud Doucet, and Ajay Jasra. Sequential Monte Carlo Samplers. Journal of the Royal Statistical Society Series B: Statistical Methodology, 68(3):411–436, 2006. doi:10.1111/j.1467-9868.2006.00553.x.