Skip to content

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, with KernelState as its per-chain state and PotentialFn as the potential it evaluates.
  • HMCKernel: Hamiltonian Monte Carlo with leapfrog integration, dual-averaging step-size adaptation, and Welford mass-matrix adaptation, parameterized by a MassMatrixKind.
  • NUTSKernel: No-U-Turn Sampler with multinomial sampling.
  • DualAveraging, WelfordCovariance, and find_reasonable_step_size: the warmup adaptation primitives the kernels share.
  • AdaptationSchedule, AdaptationWindow, and AdaptationMode: the Stan-style windowed warmup schedule the kernels follow by default.
  • MetropolisKernel with a Proposal (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 a GibbsUpdate.
  • CycleKernel and MixtureKernel: compositions of kernels.
  • MCMC: chain orchestrator with warmup, parallel chains, an InitStrategy, 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 which MCMC.resume continues a run exactly; MCMC also takes wall-clock and evaluation budgets and an MCMCCallback progress hook.

AdaptationMode module-attribute

AdaptationMode = Literal['windowed', 'single']

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

CHECKPOINT_FILENAME = 'mcmc_checkpoint.pt'

The name of the checkpoint file inside an MCMCCheckpoint directory.

CHECKPOINT_FORMAT_VERSION module-attribute

CHECKPOINT_FORMAT_VERSION = 1

The version of the checkpoint layout this library writes and reads. MCMC.resume refuses a checkpoint of another version.

InitStrategy module-attribute

InitStrategy = Literal['jitter', 'prior', 'zero', 'guide', 'uniform']

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

MCMCPhase = Literal['warmup', 'sampling']

The phase of a chain's transition: adaptation or sampling.

StopReason module-attribute

StopReason = Literal['draws', 'seconds', 'evaluations']

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

MassMatrixKind = Literal['identity', 'diagonal', 'dense']

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

AdaptationSchedule(*, init_buffer: int = 75, term_buffer: int = 50, base_window: int = 25)

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% of N: 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 75.

TYPE: int

term_buffer

Length of the terminal fast interval. Default 50.

TYPE: int

base_window

Length of the first slow window. Default 25.

TYPE: int

RAISES DESCRIPTION
ValidationError

If a buffer is negative or base_window is less than one.

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: int

RETURNS DESCRIPTION
tuple[AdaptationWindow, ...]

The windows in order. They tile [0, num_warmup) without gaps or overlaps; empty buffers are omitted, and a warmup of zero iterations has no windows.

RAISES DESCRIPTION
ValueError

If num_warmup is negative.

Source code in src/quivers/inference/mcmc/adapt.py
def windows(self, num_warmup: int) -> tuple[AdaptationWindow, ...]:
    """Lay a warmup of ``num_warmup`` iterations out in windows.

    Parameters
    ----------
    num_warmup : int
        Number of warmup iterations.

    Returns
    -------
    tuple[AdaptationWindow, ...]
        The windows in order. They tile ``[0, num_warmup)`` without
        gaps or overlaps; empty buffers are omitted, and a warmup of
        zero iterations has no windows.

    Raises
    ------
    ValueError
        If ``num_warmup`` is negative.
    """
    if num_warmup < 0:
        raise ValueError(
            f"AdaptationSchedule.windows: num_warmup must be >= 0, got {num_warmup}"
        )
    if num_warmup == 0:
        return ()
    if num_warmup < 20:
        return (AdaptationWindow(start=0, stop=num_warmup, adapts_metric=False),)
    init, term, base = self.init_buffer, self.term_buffer, self.base_window
    if init + base + term > num_warmup:
        init = int(0.15 * num_warmup)
        term = int(0.1 * num_warmup)
        base = num_warmup - init - term
    out: list[AdaptationWindow] = []
    if init > 0:
        out.append(AdaptationWindow(start=0, stop=init, adapts_metric=False))
    end = num_warmup - term
    start, size = init, base
    stop = init + base
    while True:
        out.append(AdaptationWindow(start=start, stop=stop, adapts_metric=True))
        if stop >= end:
            break
        start, size = stop, 2 * size
        stop = start + size
        # Stretch this window to the terminal interval when the
        # doubled window after it would not fit.
        if stop != end and (stop - 1) + 2 * size >= end:
            stop = end
    if term > 0:
        out.append(
            AdaptationWindow(start=end, stop=num_warmup, adapts_metric=False)
        )
    return tuple(out)

AdaptationWindow didactic-model

AdaptationWindow(*, start: int, stop: int, adapts_metric: bool)

Bases: Model

One window of a warmup schedule.

ATTRIBUTE DESCRIPTION
start

The first warmup iteration in the window, counted from zero.

TYPE: int

stop

One past the last warmup iteration in the window.

TYPE: int

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: bool

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 log(10 * ε₀) as the shrinkage anchor :math:\mu per Algorithm 6.

TYPE: float

target_accept

Target Metropolis acceptance probability. Default 0.8 (NUTS's standard), somewhat below the optimal 0.65 for HMC because NUTS averages acceptance over the tree.

TYPE: float DEFAULT: 0.8

gamma

Adaptation regularisation. Default 0.05.

TYPE: float DEFAULT: 0.05

t0

Stabilisation offset. Default 10.0.

TYPE: float DEFAULT: 10.0

kappa

Decay exponent for the smoothed step size. Default 0.75.

TYPE: float DEFAULT: 0.75

Source code in src/quivers/inference/mcmc/adapt.py
def __init__(
    self,
    initial_step_size: float,
    target_accept: float = 0.8,
    gamma: float = 0.05,
    t0: float = 10.0,
    kappa: float = 0.75,
) -> None:
    if initial_step_size <= 0:
        raise ValueError(
            f"DualAveraging: initial_step_size must be > 0, got {initial_step_size}"
        )
    if not 0.0 < target_accept < 1.0:
        raise ValueError(
            f"DualAveraging: target_accept must be in (0, 1), got {target_accept}"
        )
    self._mu = math.log(10.0 * initial_step_size)
    self._target_accept = target_accept
    self._gamma = gamma
    self._t0 = t0
    self._kappa = kappa
    self._log_step = math.log(initial_step_size)
    self._log_step_smoothed = 0.0
    self._h_bar = 0.0
    self._step_count = 0

step_count property

step_count: int

Number of update calls so far.

step_size

step_size() -> float

Current step size used by the next leapfrog proposal.

Source code in src/quivers/inference/mcmc/adapt.py
def step_size(self) -> float:
    """Current step size used by the *next* leapfrog proposal."""
    return math.exp(self._log_step)

smoothed_step_size

smoothed_step_size() -> float

Smoothed step size frozen after warmup ends.

Source code in src/quivers/inference/mcmc/adapt.py
def smoothed_step_size(self) -> float:
    """Smoothed step size frozen after warmup ends."""
    return math.exp(self._log_step_smoothed)

update

update(acceptance_prob: float) -> None

Update the step size given the latest Metropolis acceptance probability.

Source code in src/quivers/inference/mcmc/adapt.py
def update(self, acceptance_prob: float) -> None:
    """Update the step size given the latest Metropolis
    acceptance probability."""
    if not math.isfinite(acceptance_prob):
        acceptance_prob = 0.0
    acceptance_prob = max(0.0, min(1.0, acceptance_prob))
    self._step_count += 1
    m = float(self._step_count)
    eta_h = 1.0 / (m + self._t0)
    self._h_bar = (1.0 - eta_h) * self._h_bar + eta_h * (
        self._target_accept - acceptance_prob
    )
    self._log_step = self._mu - math.sqrt(m) / self._gamma * self._h_bar
    eta_step = m ** (-self._kappa)
    self._log_step_smoothed = (
        eta_step * self._log_step + (1.0 - eta_step) * self._log_step_smoothed
    )

state_dict

state_dict() -> dict[str, float | int]

The adapter's state, for a checkpoint.

RETURNS DESCRIPTION
dict[str, float | int]

Every parameter and running quantity; from_state_dict rebuilds the adapter exactly.

Source code in src/quivers/inference/mcmc/adapt.py
def state_dict(self) -> dict[str, float | int]:
    """The adapter's state, for a checkpoint.

    Returns
    -------
    dict[str, float | int]
        Every parameter and running quantity; `from_state_dict`
        rebuilds the adapter exactly.
    """
    return {
        "mu": self._mu,
        "target_accept": self._target_accept,
        "gamma": self._gamma,
        "t0": self._t0,
        "kappa": self._kappa,
        "log_step": self._log_step,
        "log_step_smoothed": self._log_step_smoothed,
        "h_bar": self._h_bar,
        "step_count": self._step_count,
    }

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 state_dict produced.

TYPE: Mapping[str, StateValue]

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
@classmethod
def from_state_dict(cls, state: Mapping[str, StateValue]) -> "DualAveraging":
    """Rebuild an adapter from `state_dict`'s output.

    Parameters
    ----------
    state : Mapping[str, StateValue]
        A dictionary `state_dict` produced.

    Returns
    -------
    DualAveraging
        The adapter, in exactly the recorded state.

    Raises
    ------
    ValueError
        If an entry is missing or is not a number.
    """
    floats = {
        key: _number(state, key, "DualAveraging")
        for key in (
            "mu",
            "target_accept",
            "gamma",
            "t0",
            "kappa",
            "log_step",
            "log_step_smoothed",
            "h_bar",
        )
    }
    count = state.get("step_count")
    if not isinstance(count, int) or isinstance(count, bool):
        raise ValueError("DualAveraging.from_state_dict: step_count must be an int")
    adapter = cls(
        math.exp(floats["log_step"]),
        target_accept=floats["target_accept"],
        gamma=floats["gamma"],
        t0=floats["t0"],
        kappa=floats["kappa"],
    )
    adapter._mu = floats["mu"]
    adapter._log_step = floats["log_step"]
    adapter._log_step_smoothed = floats["log_step_smoothed"]
    adapter._h_bar = floats["h_bar"]
    adapter._step_count = count
    return adapter

WelfordCovariance

WelfordCovariance(dim: int, regularise: bool = True, diagonal: bool = False)

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: int

regularise

Apply Stan's regularisation :math:(n / (n + 5)) \cdot \Sigma + 0.001 \cdot (5 / (n + 5)) \cdot I to the final covariance. Default True; mirrors Stan's warmup-end mass-matrix construction.

TYPE: bool DEFAULT: True

diagonal

Track only the diagonal of the covariance (vector, not matrix). Default False.

TYPE: bool DEFAULT: False

Source code in src/quivers/inference/mcmc/adapt.py
def __init__(
    self,
    dim: int,
    regularise: bool = True,
    diagonal: bool = False,
) -> None:
    if dim < 1:
        raise ValueError(f"WelfordCovariance: dim must be >= 1, got {dim}")
    self._dim = dim
    self._regularise = regularise
    self._diagonal = diagonal
    self._n = 0
    self._mean = torch.zeros(dim)
    self._m2: torch.Tensor
    if diagonal:
        self._m2 = torch.zeros(dim)
    else:
        self._m2 = torch.zeros(dim, dim)

update

update(x: Tensor) -> None

Fold one vector into the running statistics.

Source code in src/quivers/inference/mcmc/adapt.py
def update(self, x: torch.Tensor) -> None:
    """Fold one vector into the running statistics."""
    if x.shape != (self._dim,):
        raise ValueError(
            f"WelfordCovariance.update: expected shape "
            f"({self._dim},); got {tuple(x.shape)}"
        )
    self._n += 1
    delta = x - self._mean
    self._mean = self._mean + delta / float(self._n)
    delta_post = x - self._mean
    if self._diagonal:
        self._m2 = self._m2 + delta * delta_post
    else:
        self._m2 = self._m2 + delta.unsqueeze(-1) @ delta_post.unsqueeze(0)

covariance

covariance() -> Tensor

Return the empirical covariance (regularised if configured).

Source code in src/quivers/inference/mcmc/adapt.py
def covariance(self) -> torch.Tensor:
    """Return the empirical covariance (regularised if
    configured)."""
    if self._n < 2:
        # Insufficient samples; return identity so the kernel
        # behaves as before adaptation kicked in.
        if self._diagonal:
            return torch.ones(self._dim)
        return torch.eye(self._dim)
    cov = self._m2 / float(self._n - 1)
    if self._regularise:
        n = float(self._n)
        shrink = n / (n + 5.0)
        jitter = 1e-3 * (5.0 / (n + 5.0))
        if self._diagonal:
            cov = shrink * cov + jitter * torch.ones(self._dim)
        else:
            cov = shrink * cov + jitter * torch.eye(self._dim)
    return cov

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
def state_dict(self) -> dict[str, torch.Tensor | int | bool]:
    """The accumulator's state, for a checkpoint.

    Returns
    -------
    dict[str, torch.Tensor | int | bool]
        The configuration, the count, the running mean, and the
        running sum of squared deviations.
    """
    return {
        "dim": self._dim,
        "regularise": self._regularise,
        "diagonal": self._diagonal,
        "n": self._n,
        "mean": self._mean.clone(),
        "m2": self._m2.clone(),
    }

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 state_dict produced.

TYPE: Mapping[str, StateValue]

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
@classmethod
def from_state_dict(cls, state: Mapping[str, StateValue]) -> "WelfordCovariance":
    """Rebuild an accumulator from `state_dict`'s output.

    Parameters
    ----------
    state : Mapping[str, StateValue]
        A dictionary `state_dict` produced.

    Returns
    -------
    WelfordCovariance
        The accumulator, in exactly the recorded state.

    Raises
    ------
    ValueError
        If an entry is missing or has the wrong type or shape.
    """
    dim, n = state.get("dim"), state.get("n")
    regularise, diagonal = state.get("regularise"), state.get("diagonal")
    mean, m2 = state.get("mean"), state.get("m2")
    if not (
        isinstance(dim, int)
        and isinstance(n, int)
        and isinstance(regularise, bool)
        and isinstance(diagonal, bool)
        and isinstance(mean, torch.Tensor)
        and isinstance(m2, torch.Tensor)
    ):
        raise ValueError(
            "WelfordCovariance.from_state_dict: an entry is missing or has the "
            "wrong type"
        )
    accumulator = cls(dim, regularise=regularise, diagonal=diagonal)
    if mean.shape != accumulator._mean.shape or m2.shape != accumulator._m2.shape:
        raise ValueError(
            "WelfordCovariance.from_state_dict: the mean or the sum of squares "
            "has the wrong shape"
        )
    accumulator._n = n
    accumulator._mean = mean.clone()
    accumulator._m2 = m2.clone()
    return accumulator

reset

reset() -> None

Discard accumulated statistics.

Source code in src/quivers/inference/mcmc/adapt.py
def reset(self) -> None:
    """Discard accumulated statistics."""
    self._n = 0
    self._mean = torch.zeros(self._dim)
    if self._diagonal:
        self._m2 = torch.zeros(self._dim)
    else:
        self._m2 = torch.zeros(self._dim, self._dim)

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: Sequence[MCMCKernel] | Mapping[str, MCMCKernel]

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 MCMCKernel.

Source code in src/quivers/inference/mcmc/compose.py
def __init__(
    self, kernels: Sequence[MCMCKernel] | Mapping[str, MCMCKernel]
) -> None:
    self._components = _named_components(kernels, type(self).__name__)
    host = self.host_sites
    mixed = sorted(
        site
        for _, kernel in self._components
        for site in (kernel.gibbs_sites - kernel.host_sites) & host
    )
    if mixed:
        raise ValueError(
            f"{type(self).__name__}: {mixed} are host data for one component "
            "and sample sites of the program for another; every block that "
            "updates a name must declare it the same way"
        )

start_adaptation

start_adaptation(num_warmup: int) -> None

Start every component's warmup of num_warmup transitions.

PARAMETER DESCRIPTION
num_warmup

Number of warmup transitions.

TYPE: int

Source code in src/quivers/inference/mcmc/compose.py
def start_adaptation(self, num_warmup: int) -> None:
    """Start every component's warmup of ``num_warmup`` transitions.

    Parameters
    ----------
    num_warmup : int
        Number of warmup transitions.
    """
    super().start_adaptation(num_warmup)
    for _, kernel in self._components:
        kernel.start_adaptation(num_warmup)

step

step(state: KernelState, potential: PotentialFn) -> KernelState

Run every component once, in order.

PARAMETER DESCRIPTION
state

The current state.

TYPE: KernelState

potential

The target conditioned on state.gibbs_values.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The state after the last component.

Source code in src/quivers/inference/mcmc/compose.py
def step(self, state: KernelState, potential: PotentialFn) -> KernelState:
    """Run every component once, in order.

    Parameters
    ----------
    state : KernelState
        The current state.
    potential : PotentialFn
        The target conditioned on ``state.gibbs_values``.

    Returns
    -------
    KernelState
        The state after the last component.
    """
    stats: dict[str, float] = {}
    diverged = False
    current = state
    for name, kernel in self._components:
        current = self._run_component(name, kernel, current, potential, stats)
        diverged = diverged or current.diverged
    return self._finish(state, current, stats, diverged)

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: Sequence[MCMCKernel] | Mapping[str, MCMCKernel]

probs

Selection probabilities, positive and summing to one; uniform when omitted.

TYPE: Sequence[float] DEFAULT: None

RAISES DESCRIPTION
ValueError

If the components are invalid (see CycleKernel), or probs has the wrong length, a non-positive entry, or does not sum to one.

TypeError

If a component is not an MCMCKernel.

Source code in src/quivers/inference/mcmc/compose.py
def __init__(
    self,
    kernels: Sequence[MCMCKernel] | Mapping[str, MCMCKernel],
    probs: Sequence[float] | None = None,
) -> None:
    super().__init__(kernels)
    count = len(self._components)
    weights = [1.0 / count] * count if probs is None else [float(p) for p in probs]
    if len(weights) != count:
        raise ValueError(
            f"MixtureKernel: probs has {len(weights)} entries for {count} kernels"
        )
    if any(not p > 0.0 for p in weights) or abs(sum(weights) - 1.0) > 1e-6:
        raise ValueError(
            f"MixtureKernel: probs must be positive and sum to one, got {weights}"
        )
    self._probs = torch.tensor(weights, dtype=torch.float64)
    self._warmup_choices: list[int] = []
    self._warmup_index = 0

probs property

probs: Tensor

The selection probabilities, shape (num_components,).

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
def configuration(self) -> dict[str, StateValue]:
    """The components' configurations and the selection probabilities.

    Returns
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {**super().configuration(), "probs": self._probs.tolist()}

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
def state_dict(self) -> dict[str, StateValue]:
    """The components' states and the warmup's drawn choices.

    Returns
    -------
    dict[str, StateValue]
        The state.
    """
    return {
        **super().state_dict(),
        "warmup_choices": list(self._warmup_choices),
        "warmup_index": self._warmup_index,
    }

load_state_dict

load_state_dict(state: dict[str, StateValue]) -> None

Restore what state_dict returned.

PARAMETER DESCRIPTION
state

A dictionary state_dict produced.

TYPE: dict[str, StateValue]

RAISES DESCRIPTION
ValueError

If the warmup choices are missing or malformed.

Source code in src/quivers/inference/mcmc/compose.py
def load_state_dict(self, state: dict[str, StateValue]) -> None:
    """Restore what `state_dict` returned.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.

    Raises
    ------
    ValueError
        If the warmup choices are missing or malformed.
    """
    super().load_state_dict(state)
    choices, index = state.get("warmup_choices"), state.get("warmup_index")
    if (
        not isinstance(choices, list)
        or not all(isinstance(c, int) for c in choices)
        or not isinstance(index, int)
    ):
        raise ValueError("MixtureKernel.load_state_dict: bad warmup choices")
    self._warmup_choices = [c for c in choices if isinstance(c, int)]
    self._warmup_index = index

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: LatentRegistry

model

The model.

TYPE: MonadicProgram

x

The one-row input.

TYPE: Tensor

observations

The data.

TYPE: dict[str, Tensor]

initial_position

The starting position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
KernelState

The first component's starting state.

Source code in src/quivers/inference/mcmc/compose.py
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.Tensor,
) -> KernelState:
    """Initialize every component and clear the warmup choices.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.
    model : MonadicProgram
        The model.
    x : torch.Tensor
        The one-row input.
    observations : dict[str, torch.Tensor]
        The data.
    initial_position : torch.Tensor
        The starting position, shape ``(D,)``.

    Returns
    -------
    KernelState
        The first component's starting state.
    """
    self._warmup_choices = []
    self._warmup_index = 0
    return super().init(registry, model, x, observations, initial_position)

start_adaptation

start_adaptation(num_warmup: int) -> None

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: int

Source code in src/quivers/inference/mcmc/compose.py
def start_adaptation(self, num_warmup: int) -> None:
    """Draw the warmup's component choices and start each component's
    adaptation for the transitions that select it.

    Parameters
    ----------
    num_warmup : int
        Number of warmup transitions.
    """
    super().start_adaptation(num_warmup)
    self._warmup_choices = (
        torch.multinomial(
            self._probs, num_warmup, replacement=True, generator=self._generator
        ).tolist()
        if num_warmup > 0
        else []
    )
    self._warmup_index = 0
    for index, (_, kernel) in enumerate(self._components):
        kernel.start_adaptation(self._warmup_choices.count(index))

step

step(state: KernelState, potential: PotentialFn) -> KernelState

Run one randomly chosen component.

PARAMETER DESCRIPTION
state

The current state.

TYPE: KernelState

potential

The target conditioned on state.gibbs_values.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The chosen component's output.

Source code in src/quivers/inference/mcmc/compose.py
def step(self, state: KernelState, potential: PotentialFn) -> KernelState:
    """Run one randomly chosen component.

    Parameters
    ----------
    state : KernelState
        The current state.
    potential : PotentialFn
        The target conditioned on ``state.gibbs_values``.

    Returns
    -------
    KernelState
        The chosen component's output.
    """
    name, kernel = self._components[self._choose()]
    stats: dict[str, float] = {}
    current = self._run_component(name, kernel, state, potential, stats)
    return self._finish(state, current, stats, current.diverged)

MCMCCheckpoint didactic-model

MCMCCheckpoint(*, directory: str, every: int | None = 100, every_seconds: float | None = None)

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: str

every

Transitions between writes; None writes only on the time criterion and at chain ends. Default 100.

TYPE: int | None

every_seconds

Seconds between writes; None disables the time criterion.

TYPE: float | None

RAISES DESCRIPTION
ValidationError

If directory is empty, every is less than one, or every_seconds is not positive.

path property

path: Path

The checkpoint file.

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. HMCKernel, NUTSKernel, or a composite).

TYPE: MCMCKernel

num_warmup

Number of adaptation steps. The kernel's adaptation machinery (dual averaging, Welford covariance) runs over this prefix.

TYPE: int

num_samples

Post-warmup samples per chain.

TYPE: int

num_chains

Independent chains. Default 4 (Stan / NumPyro default).

TYPE: int DEFAULT: 4

init_strategy

How to pick each chain's initial position (InitStrategy).

TYPE: ('jitter', 'prior', 'zero', 'guide') DEFAULT: "jitter"

seed

Base seed used to derive an independent local generator for each chain. Repeated calls to run with the same seed are reproducible and do not consume Torch's global RNG.

TYPE: int DEFAULT: None

generator

Caller-owned CPU generator used to draw one base seed per run. The generator advances, while Torch's global RNG does not. Mutually exclusive with seed.

TYPE: Generator DEFAULT: None

checkpoint

Where and how often to checkpoint the chains, so that resume can continue an interrupted run exactly.

TYPE: MCMCCheckpoint DEFAULT: None

max_seconds

Wall-clock budget per chain and per call of run or resume.

TYPE: float DEFAULT: None

max_evaluations

Budget of potential evaluations (gradient ones included) per chain and per call.

TYPE: int DEFAULT: None

callback

Progress hook called after every transition.

TYPE: MCMCCallback DEFAULT: None

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 num_chains mappings gives each chain its own values, as brms's init list does. A name may also be a site a GibbsKernel updates: the chain then starts at that value instead of a draw from the program, and the value, at the shape of one draw in MCMCResult.samples, must be finite and inside the site's support, its boundary included. Host data a GibbsKernel updates (host=True) must be named, in every chain: the value is taken as given, with its shape and dtype, which every chain shares.

TYPE: Mapping[str, Tensor or float] or Sequence DEFAULT: None

thin

Keep every thin-th post-warmup transition; each chain runs num_samples * thin sampling transitions and keeps num_samples draws (Stan's and brms's thin).

TYPE: int DEFAULT: 1

init_radius

Half-width of the "uniform" initialization (brms init_r).

TYPE: float DEFAULT: 2.0

RAISES DESCRIPTION
ValueError

If a count or budget is out of range, seed and generator are both given, or generator is not on the CPU.

TypeError

If seed is not an int or generator not a generator.

Source code in src/quivers/inference/mcmc/driver.py
def __init__(
    self,
    kernel: MCMCKernel,
    num_warmup: int,
    num_samples: int,
    num_chains: int = 4,
    init_strategy: InitStrategy = "jitter",
    *,
    seed: int | None = None,
    generator: torch.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, torch.Tensor | float]
    | Sequence[Mapping[str, torch.Tensor | float]]
    | None = None,
    thin: int = 1,
    init_radius: float = 2.0,
) -> None:
    if num_warmup < 0:
        raise ValueError(f"MCMC: num_warmup must be >= 0, got {num_warmup}")
    if num_samples < 1:
        raise ValueError(f"MCMC: num_samples must be >= 1, got {num_samples}")
    if num_chains < 1:
        raise ValueError(f"MCMC: num_chains must be >= 1, got {num_chains}")
    if seed is not None and generator is not None:
        raise ValueError("MCMC: seed and generator are mutually exclusive")
    if seed is not None and (not isinstance(seed, int) or isinstance(seed, bool)):
        raise TypeError(f"MCMC: seed must be an int, got {type(seed).__name__}")
    if generator is not None:
        if not isinstance(generator, torch.Generator):
            raise TypeError(
                "MCMC: generator must be a torch.Generator, "
                f"got {type(generator).__name__}"
            )
        if generator.device.type != "cpu":
            raise ValueError(
                "MCMC: generator must be a CPU generator because MCMC "
                "currently runs chain state on CPU"
            )
    if max_seconds is not None and not max_seconds > 0:
        raise ValueError(f"MCMC: max_seconds must be > 0, got {max_seconds}")
    if max_evaluations is not None and max_evaluations < 1:
        raise ValueError(
            f"MCMC: max_evaluations must be >= 1, got {max_evaluations}"
        )
    self.kernel = kernel
    self.num_warmup = num_warmup
    self.num_samples = num_samples
    self.num_chains = num_chains
    self.init_strategy = init_strategy
    self.seed = seed
    self.generator = generator
    self.checkpoint = checkpoint
    self.max_seconds = max_seconds
    self.max_evaluations = max_evaluations
    self.callback = callback
    # brms thin, init_r, and per-chain init lists.
    if isinstance(thin, bool) or not isinstance(thin, int) or thin < 1:
        raise ValueError(f"MCMC: thin must be an integer >= 1, got {thin!r}")
    if not (isinstance(init_radius, (int, float)) and init_radius > 0):
        raise ValueError(f"MCMC: init_radius must be > 0, got {init_radius!r}")
    self.thin = thin
    self.init_radius = float(init_radius)
    per_chain = (
        ()
        if initial_values is None or isinstance(initial_values, Mapping)
        else tuple(initial_values)
    )
    if per_chain and len(per_chain) != num_chains:
        raise ValueError(
            f"MCMC: {len(per_chain)} per-chain initial values for "
            f"{num_chains} chains"
        )
    self.chain_initial_values: tuple[dict[str, torch.Tensor], ...] = tuple(
        {
            name: torch.as_tensor(value).detach().clone()
            for name, value in values.items()
        }
        for values in per_chain
    )
    self.initial_values = {
        name: torch.as_tensor(value).detach().clone()
        for name, value in (
            initial_values if isinstance(initial_values, Mapping) else {}
        ).items()
    }

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: MonadicProgram

x

The input.

TYPE: Tensor

observations

The data.

TYPE: dict[str, Tensor]

guide

The guide for init_strategy="guide".

TYPE: Guide or None DEFAULT: None

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
def chain_start_values(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    guide: Guide | None = None,
) -> tuple[dict[str, torch.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.

    Parameters
    ----------
    model : MonadicProgram
        The model.
    x : torch.Tensor
        The input.
    observations : dict[str, torch.Tensor]
        The data.
    guide : Guide or None
        The guide for ``init_strategy="guide"``.

    Returns
    -------
    tuple[dict[str, torch.Tensor], ...]
        One mapping per chain from latent site to its initial value on
        the constrained scale, at the site's constrained shape.

    Raises
    ------
    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.
    """
    if self.seed is None or self.generator is not None:
        raise ValueError(
            "MCMC.chain_start_values: chain streams are reproducible only "
            "from an explicit integer seed"
        )
    run_seed = self._run_seed()
    setup = self._setup(model, x, observations, "MCMC.chain_start_values", run_seed)
    return tuple(
        self._to_constrained(
            setup.registry,
            self._accepted_start(
                setup, guide, self._chain_generator(run_seed, chain), chain
            )[0],
        )
        for chain in range(self.num_chains)
    )

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: MonadicProgram

x

Program input, shape (batch, ...).

TYPE: Tensor

observations

Observed-site values and host data.

TYPE: dict[str, Tensor]

guide

Fitted guide, required by init_strategy="guide".

TYPE: Guide DEFAULT: None

RETURNS DESCRIPTION
MCMCResult

Posterior draws and diagnostics.

RAISES DESCRIPTION
ValueError

If x has more than one row (MCMC targets the posterior of one run), an observed value is not finite or lies outside its site's support, a chain's initial position is not finite, or the log-density at an initial position is not finite.

FileExistsError

If checkpoint names a directory that already holds a checkpoint; resume continues it.

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
def run(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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`.

    Parameters
    ----------
    model : MonadicProgram
        The program to sample.
    x : torch.Tensor
        Program input, shape ``(batch, ...)``.
    observations : dict[str, torch.Tensor]
        Observed-site values and host data.
    guide : Guide, optional
        Fitted guide, required by ``init_strategy="guide"``.

    Returns
    -------
    MCMCResult
        Posterior draws and diagnostics.

    Raises
    ------
    ValueError
        If ``x`` has more than one row (MCMC targets the posterior
        of one run), an observed value is not finite or lies
        outside its site's support, a chain's initial position is
        not finite, or the log-density at an initial position is
        not finite.
    FileExistsError
        If ``checkpoint`` names a directory that already holds a
        checkpoint; `resume` continues it.
    Exception
        Any error the program raises at an initial position, or
        raises during sampling for a reason other than a position
        outside its support.
    """
    if self.checkpoint is not None and self.checkpoint.path.exists():
        raise FileExistsError(
            f"MCMC.run: {self.checkpoint.path} already holds a checkpoint; "
            "continue it with MCMC.resume, or remove it to start afresh"
        )
    run_seed = self._run_seed()
    setup = self._setup(model, x, observations, "MCMC.run", run_seed)
    header = self._header(setup, run_seed)
    records: list[_ChainRecord | None] = [None] * self.num_chains
    return self._execute(setup, header, records, guide)

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: str | Path

model

The program the checkpoint was written for.

TYPE: MonadicProgram

x

The input it was written for.

TYPE: Tensor

observations

The data it was written for.

TYPE: dict[str, Tensor]

guide

Fitted guide, for chains not yet started under init_strategy="guide".

TYPE: Guide DEFAULT: None

RETURNS DESCRIPTION
MCMCResult

Posterior draws and diagnostics of every chain.

RAISES DESCRIPTION
FileNotFoundError

If directory holds no checkpoint.

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
def resume(
    self,
    directory: str | Path,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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.

    Parameters
    ----------
    directory : str | Path
        The directory holding the checkpoint.
    model : MonadicProgram
        The program the checkpoint was written for.
    x : torch.Tensor
        The input it was written for.
    observations : dict[str, torch.Tensor]
        The data it was written for.
    guide : Guide, optional
        Fitted guide, for chains not yet started under
        ``init_strategy="guide"``.

    Returns
    -------
    MCMCResult
        Posterior draws and diagnostics of every chain.

    Raises
    ------
    FileNotFoundError
        If ``directory`` holds no checkpoint.
    ValueError
        If the checkpoint is of another format version, or was
        written for a different model or data, kernel
        configuration, run settings, or seed.
    """
    stored_header, stored_chains = read_checkpoint(
        Path(directory) / CHECKPOINT_FILENAME
    )
    setup = self._setup(
        model, x, observations, "MCMC.resume", stored_header.run_seed
    )
    header = self._header(setup, stored_header.run_seed)
    # The run settings come first: initial values of Gibbs sites also
    # enter the model fingerprint's probes, and a change to them is a
    # change of settings.
    for field_name, what in (
        (
            "run_fingerprint",
            "different run settings (warmup, samples, chains, or initialization)",
        ),
        ("model_fingerprint", "a different model or data"),
        ("kernel_fingerprint", "a different kernel configuration"),
    ):
        if getattr(header, field_name) != getattr(stored_header, field_name):
            raise ValueError(
                f"MCMC.resume: the checkpoint in {directory} was written for "
                f"{what}; resume it with the model, data, kernel, and settings "
                "it was written with"
            )
    if self.seed is not None and self.seed != stored_header.run_seed:
        raise ValueError(
            f"MCMC.resume: the checkpoint was written with seed "
            f"{stored_header.run_seed}, not {self.seed}"
        )
    if len(stored_chains) != self.num_chains:
        raise ValueError(
            f"MCMC.resume: the checkpoint holds {len(stored_chains)} chains, "
            f"not {self.num_chains}"
        )
    records: list[_ChainRecord | None] = [
        None
        if stored is None
        else _ChainRecord.from_state_dict(stored, setup.site_names)
        for stored in stored_chains
    ]
    return self._execute(setup, header, records, guide)

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 GibbsKernel updates included. Shape (num_chains, num_samples, *site_shape), where site_shape is the site's LatentSite.constrained_shape: () for a scalar site, (d,) for a vector site, and (|A|, ...) for a plate site over A. The draws carry no batch axis; LatentRegistry.trace_values lifts one draw to the (batch, ...) values a program's log_joint and trace consume.

TYPE: dict[str, Tensor]

log_densities

Unconstrained-space log-density (Jacobian-corrected) at every posterior draw. Shape (num_chains, num_samples).

TYPE: Tensor

acceptance_rates

Per-chain post-warmup acceptance rate. Shape (num_chains,). For a composite kernel a transition counts as accepted when it moved the chain (its position or a Gibbs value).

TYPE: Tensor

divergence_counts

Per-chain post-warmup divergence count. Shape (num_chains,).

TYPE: Tensor

num_warmup

Warmup iterations per chain.

TYPE: int

num_samples

Retained draws per chain.

TYPE: int

component_acceptance

For a composite kernel, each component's post-warmup acceptance rate per chain, shape (num_chains,), keyed by component name ("outer.inner" for a component of a nested composite): the mean of the component's "accepted" statistic over the transitions that ran it, nan for a chain in which it never ran. Empty for a kernel that is not composite.

TYPE: dict[str, Tensor]

sample_stats

Per-draw sampler statistics, each of shape (num_chains, num_samples) and dtype float64, keyed as the kernel's KernelState.stats: for NUTSKernel "accept_prob", "accepted", "diverged" (0.0 or 1.0), "step_size", "tree_depth", "num_steps" (leapfrog steps), and "energy" (the Hamiltonian at the draw); HMCKernel the same without "tree_depth". A composite's entries carry each component's name as a prefix ("nuts.energy"), and an entry a transition did not report (an unselected mixture component's) is nan.

TYPE: dict[str, Tensor]

stopped_by

Why each chain stopped: "draws" when it finished, "seconds" or "evaluations" when a budget stopped it.

TYPE: tuple[StopReason, ...]

num_draws

Post-warmup draws each chain made, shape (num_chains,). When a budget stops a chain early, every per-draw quantity keeps the first min(num_draws) draws of each chain, and num_samples is that number.

TYPE: Tensor

num_evaluations

Potential evaluations per chain, gradient ones included, over every call of MCMC.run and MCMC.resume. Shape (num_chains,).

TYPE: Tensor

num_gradient_evaluations

Gradient evaluations per chain. Shape (num_chains,).

TYPE: Tensor

truncated property

truncated: bool

Whether a budget stopped any chain before its last draw.

num_chains property

num_chains: int

Number of chains.

mean_acceptance property

mean_acceptance: float

Post-warmup acceptance rate averaged over chains.

total_divergences property

total_divergences: int

Post-warmup divergences summed over chains.

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.

ess cached property

ess: dict[str, Tensor]

Per-site bulk effective sample size pooled across chains.

Computed by quivers.diagnostics.ess(draws, method="bulk"); same shape convention as r_hat.

ess_tail cached property

ess_tail: dict[str, Tensor]

Per-site tail effective sample size pooled across chains.

The smaller of the 5% and 95% quantile effective sample sizes, computed by quivers.diagnostics.ess(draws, method="tail"); same shape convention as r_hat.

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: Sequence[str]

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: GibbsUpdate DEFAULT: None

host

Whether the block's names are host data the program reads rather than sample sites it declares. Such a block needs an update, and MCMC needs a starting value for each name in its initial_values.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

If sites is empty or names a site twice, or host is set without an update: enumeration scores the support of a sample site, and host data have none.

Source code in src/quivers/inference/mcmc/gibbs.py
def __init__(
    self,
    sites: Sequence[str],
    update: GibbsUpdate | None = None,
    *,
    host: bool = False,
) -> None:
    names = tuple(sites)
    if not names:
        raise ValueError("GibbsKernel: sites must name at least one site")
    if len(set(names)) != len(names):
        raise ValueError(f"GibbsKernel: sites {names} name a site twice")
    if host and update is None:
        raise ValueError(
            f"GibbsKernel: {list(names)} are declared host data, which have no "
            "support to enumerate; pass update= with a sampler for the block, "
            "or declare them as sample sites of the program"
        )
    self._sites = names
    self._update = update
    self._host = host
    self._supports: dict[str, torch.Tensor] = {}
    self._registry: LatentRegistry | None = None

gibbs_sites property

gibbs_sites: frozenset[str]

The block's sites.

host_sites property

host_sites: frozenset[str]

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
def configuration(self) -> 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
    -------
    dict[str, StateValue]
        The configuration.
    """
    update = (
        None
        if self._update is None
        else f"{getattr(self._update, '__module__', '')}."
        f"{getattr(self._update, '__qualname__', type(self._update).__qualname__)}"
    )
    configuration: dict[str, StateValue] = {
        **super().configuration(),
        "sites": list(self._sites),
        "update": update,
    }
    if self._host:
        configuration["host"] = True
    return configuration

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: LatentRegistry

model

The model.

TYPE: MonadicProgram

x

The one-row input.

TYPE: Tensor

observations

The data, with the chain's current values of any host data a Gibbs block updates.

TYPE: dict[str, Tensor]

initial_position

The flat vector's starting position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
KernelState

The starting state; MCMC.run fills in its Gibbs values.

RAISES DESCRIPTION
ValueError

If a site is in the registry, is not a latent sample site of the run, or (without an update) has a support that is not a finite set of scalars.

Source code in src/quivers/inference/mcmc/gibbs.py
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.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.

    Parameters
    ----------
    registry : LatentRegistry
        The registry of the flat vector, without the block's sites.
    model : MonadicProgram
        The model.
    x : torch.Tensor
        The one-row input.
    observations : dict[str, torch.Tensor]
        The data, with the chain's current values of any host data
        a Gibbs block updates.
    initial_position : torch.Tensor
        The flat vector's starting position, shape ``(D,)``.

    Returns
    -------
    KernelState
        The starting state; `MCMC.run` fills in its Gibbs values.

    Raises
    ------
    ValueError
        If a site is in the registry, is not a latent sample site of
        the run, or (without an ``update``) has a support that is not
        a finite set of scalars.
    """
    inside = sorted(name for name in self._sites if name in registry)
    if inside:
        raise ValueError(
            f"GibbsKernel: {inside} are in the registry; a Gibbs site must be "
            "left out of the flat vector (MCMC.run does this for every site a "
            "GibbsKernel names)"
        )
    self._registry = registry
    self.is_adapting = False
    if self._update is None:
        # The run that names the sites draws from a copy of the
        # chain's stream, so a seeded chain reads the same run
        # whatever the global RNG holds, without advancing its stream.
        with torch.random.fork_rng(devices=[]):
            if self._generator is not None:
                torch.random.set_rng_state(self._generator.get_state())
            recorded = trace(model, x, observations=observations)
        for name in self._sites:
            record = recorded.sites.get(name)
            if record is None or record.is_observed or record.morphism is None:
                raise ValueError(
                    f"GibbsKernel: {name!r} is not a latent sample site of the run"
                )
            morphism = record.morphism
            support = (
                morphism.family.support
                if isinstance(morphism, PlateDraw)
                else morphism.support
            )
            values = _enumerable_support(support)
            if values is None:
                raise ValueError(
                    f"GibbsKernel: site {name!r} has support {support}, which is "
                    "not a finite set of scalars, so its full conditional cannot "
                    "be enumerated; pass update= with a sampler for it"
                )
            self._supports[name] = values
    return KernelState(
        position=initial_position.clone(),
        log_density=torch.tensor(0.0),
        grad_log_density=torch.zeros(registry.total_unconstrained_dim),
    )

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 gibbs_values.

TYPE: KernelState

potential

The target conditioned on state.gibbs_values.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The state with the block's new values. stats["accepted"] is 1.0 when the sweep changed a value; stats["accept_prob"] is 1.0. A sweep that changed a value leaves the log-density and gradient unevaluated, for the transition that next reads them to evaluate under the potential conditioned on the new values (KernelState.evaluated); a sweep that changed nothing passes on the density it was given.

RAISES DESCRIPTION
ValueError

If the state lacks a site of the block, or an update returns other sites, shapes, or dtypes than it was given.

Source code in src/quivers/inference/mcmc/gibbs.py
def step(self, state: KernelState, potential: PotentialFn) -> KernelState:
    """Run one Gibbs sweep over the block.

    Parameters
    ----------
    state : KernelState
        The current state, with the block's values in
        ``gibbs_values``.
    potential : PotentialFn
        The target conditioned on ``state.gibbs_values``.

    Returns
    -------
    KernelState
        The state with the block's new values.
        ``stats["accepted"]`` is ``1.0`` when the sweep changed a
        value; ``stats["accept_prob"]`` is ``1.0``. A sweep that
        changed a value leaves the log-density and gradient
        unevaluated, for the transition that next reads them to
        evaluate under the potential conditioned on the new values
        (`KernelState.evaluated`); a sweep that changed nothing
        passes on the density it was given.

    Raises
    ------
    ValueError
        If the state lacks a site of the block, or an ``update``
        returns other sites, shapes, or dtypes than it was given.
    """
    missing = sorted(name for name in self._sites if name not in state.gibbs_values)
    if missing:
        raise ValueError(
            f"GibbsKernel: the chain state holds no values for {missing}"
        )
    current = {name: state.gibbs_values[name] for name in self._sites}
    if self._update is None:
        new = self._enumerate(state.gibbs_values, state.position, potential)
        proposed = {name: new[name] for name in self._sites}
    else:
        assert self._registry is not None, "GibbsKernel.init was not called"
        constrained, _ = self._registry.to_constrained(
            self._registry.unflatten_unconstrained(state.position)
        )
        latent = self._registry.trace_values(constrained, batch_size=1)
        proposed = self._update(
            self._generator,
            {name: value.clone() for name, value in current.items()},
            latent,
        )
        if set(proposed) != set(self._sites):
            raise ValueError(
                f"GibbsKernel: the update returned sites {sorted(proposed)}; "
                f"the block is {sorted(self._sites)}"
            )
        for name in self._sites:
            old, value = current[name], proposed[name]
            if value.shape != old.shape or value.dtype != old.dtype:
                raise ValueError(
                    f"GibbsKernel: the update returned {name!r} with shape "
                    f"{tuple(value.shape)} and dtype {value.dtype}; the site "
                    f"holds shape {tuple(old.shape)} and dtype {old.dtype}"
                )
    changed = any(
        not torch.equal(proposed[name], current[name]) for name in self._sites
    )
    gibbs_values = {**state.gibbs_values, **proposed}
    keeps_density = state.has_density and not changed
    return KernelState(
        position=state.position,
        log_density=state.log_density if keeps_density else None,
        grad_log_density=state.grad_log_density if keeps_density else None,
        step_count=state.step_count + 1,
        accept_count=state.accept_count + int(changed),
        diverged=False,
        extras=state.extras,
        stats={"accepted": float(changed), "accept_prob": 1.0},
        gibbs_values=gibbs_values,
    )

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 adapt_step_size is true.

TYPE: float DEFAULT: 0.1

num_steps

Leapfrog steps per proposal.

TYPE: int DEFAULT: 10

mass_matrix

Mass-matrix shape. Diagonal / dense are adapted during warmup from the empirical covariance of warmup samples.

TYPE: ('identity', 'diagonal', 'dense') DEFAULT: "identity"

target_accept

Target Metropolis acceptance for dual averaging. Default 0.65, near the asymptotic optimum derived for specified high-dimensional product targets Beskos et al. (2013). This is a tuning default, not a universal optimum.

TYPE: float DEFAULT: 0.65

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: float DEFAULT: 1000.0

adapt_step_size

Whether warmup adapts the step size by dual averaging.

TYPE: bool DEFAULT: True

adapt_mass_matrix

Whether warmup adapts a diagonal or dense metric.

TYPE: bool DEFAULT: True

adaptation

The warmup mode (see AdaptationMode). Default "single". "windowed" keeps the initial transient out of the metric and tunes the step size under the metric it samples with; it suits warmups long enough for the schedule's buffers (150 iterations under the defaults), since a shorter warmup leaves a terminal step-size window of a few iterations.

TYPE: ('windowed', 'single') DEFAULT: "windowed"

adaptation_schedule

The windowed schedule; the Stan defaults (75 / 25 / 50) when omitted.

TYPE: AdaptationSchedule DEFAULT: None

RAISES DESCRIPTION
ValueError

If step_size is not positive, num_steps is less than one, target_accept is outside (0, 1), or adaptation is not a known mode.

Source code in src/quivers/inference/mcmc/hmc.py
def __init__(
    self,
    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,
) -> None:
    if num_steps < 1:
        raise ValueError(f"HMCKernel: num_steps must be >= 1, got {num_steps}")
    super().__init__(
        "HMCKernel",
        step_size,
        mass_matrix,
        target_accept,
        divergence_threshold,
        adapt_step_size,
        adapt_mass_matrix,
        adaptation,
        adaptation_schedule,
    )
    self._num_steps = num_steps

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
def configuration(self) -> dict[str, StateValue]:
    """The kernel's hyperparameters, the trajectory length included.

    Returns
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {**super().configuration(), "num_steps": self._num_steps}

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: LatentRegistry

model

The model (unused; the potential carries it).

TYPE: MonadicProgram

x

The input (unused).

TYPE: Tensor

observations

The data (unused).

TYPE: dict[str, Tensor]

initial_position

The starting position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
KernelState

The starting state.

RAISES DESCRIPTION
ValueError

If initial_position has the wrong shape or a non-finite value.

Source code in src/quivers/inference/mcmc/hmc.py
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.Tensor,
) -> KernelState:
    """Reset the adaptation state and build the chain's first state.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.
    model : MonadicProgram
        The model (unused; the potential carries it).
    x : torch.Tensor
        The input (unused).
    observations : dict[str, torch.Tensor]
        The data (unused).
    initial_position : torch.Tensor
        The starting position, shape ``(D,)``.

    Returns
    -------
    KernelState
        The starting state.

    Raises
    ------
    ValueError
        If ``initial_position`` has the wrong shape or a
        non-finite value.
    """
    del model, x, observations
    return self._initial_state(registry, initial_position)

step

step(state: KernelState, potential: PotentialFn) -> KernelState

Run one HMC transition.

PARAMETER DESCRIPTION
state

The current state.

TYPE: KernelState

potential

The target.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The next state; extras["accept_prob"] holds the Metropolis acceptance probability.

Source code in src/quivers/inference/mcmc/hmc.py
def step(
    self,
    state: KernelState,
    potential: PotentialFn,
) -> KernelState:
    """Run one HMC transition.

    Parameters
    ----------
    state : KernelState
        The current state.
    potential : PotentialFn
        The target.

    Returns
    -------
    KernelState
        The next state; ``extras["accept_prob"]`` holds the
        Metropolis acceptance probability.
    """
    assert self._mass is not None, "HMCKernel.init was not called"
    state = self._prepare_transition(state, potential)
    z0 = state.position
    ld0, g0 = state.density()
    p0 = self._mass.sample_momentum(generator=self._generator)
    h0 = -ld0 + self._mass.kinetic(p0)
    eps = self.step_size
    z1, p1, ld1, g1 = _leapfrog(
        z0, p0, g0, eps, self._num_steps, potential, self._mass
    )
    h1 = -ld1 + self._mass.kinetic(p1)
    delta_h = h1 - h0
    log_accept = -delta_h
    if not torch.isfinite(log_accept):
        log_accept = torch.tensor(-float("inf"))
    accept_prob = float(torch.exp(torch.clamp_max(log_accept, 0.0)))
    accept_prob = max(0.0, min(1.0, accept_prob))
    diverged = bool(
        not torch.isfinite(delta_h)
        or torch.abs(delta_h).item() > self._divergence_threshold
    )
    if (
        accept_prob >= 1.0
        or torch.rand((), generator=self._generator).item() < accept_prob
    ):
        new_position = z1.detach()
        new_log_density = ld1.detach()
        new_grad = g1.detach()
        accept_count_delta = 1
    else:
        new_position = z0
        new_log_density = ld0
        new_grad = g0
        accept_count_delta = 0
    new_state = KernelState(
        position=new_position,
        log_density=new_log_density,
        grad_log_density=new_grad,
        step_count=state.step_count + 1,
        accept_count=state.accept_count + accept_count_delta,
        diverged=diverged,
        extras={**state.extras, "accept_prob": accept_prob},
        stats={
            "accepted": float(accept_count_delta),
            "accept_prob": accept_prob,
            "diverged": float(diverged),
            "step_size": eps,
            "num_steps": float(self._num_steps),
            "energy": float(h1 if accept_count_delta else h0),
        },
        gibbs_values=state.gibbs_values,
    )
    self._adapt(new_state, potential, accept_prob)
    return new_state

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: float DEFAULT: 0.1

max_tree_depth

Maximum tree doubling depth. Default 10 (Stan default).

TYPE: int DEFAULT: 10

mass_matrix

Mass-matrix shape. Default "diagonal".

TYPE: ('identity', 'diagonal', 'dense') DEFAULT: "identity"

target_accept

Target tree-averaged Metropolis acceptance for dual averaging. Default 0.8.

TYPE: float DEFAULT: 0.8

divergence_threshold

Energy-error threshold above which a leapfrog substep is marked divergent and terminates the tree on its branch.

TYPE: float DEFAULT: 1000.0

adapt_step_size

Whether warmup adapts the step size by dual averaging.

TYPE: bool DEFAULT: True

adapt_mass_matrix

Whether warmup adapts a diagonal or dense metric.

TYPE: bool DEFAULT: True

adaptation

The warmup mode (see AdaptationMode). Default "single". "windowed" keeps the initial transient out of the metric and tunes the step size under the metric it samples with; it suits warmups long enough for the schedule's buffers (150 iterations under the defaults), since a shorter warmup leaves a terminal step-size window of a few iterations.

TYPE: ('windowed', 'single') DEFAULT: "windowed"

adaptation_schedule

The windowed schedule; the Stan defaults (75 / 25 / 50) when omitted.

TYPE: AdaptationSchedule DEFAULT: None

RAISES DESCRIPTION
ValueError

If step_size is not positive, max_tree_depth is less than one, target_accept is outside (0, 1), or adaptation is not a known mode.

Source code in src/quivers/inference/mcmc/hmc.py
def __init__(
    self,
    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,
) -> None:
    if max_tree_depth < 1:
        raise ValueError(
            f"NUTSKernel: max_tree_depth must be >= 1, got {max_tree_depth}"
        )
    super().__init__(
        "NUTSKernel",
        step_size,
        mass_matrix,
        target_accept,
        divergence_threshold,
        adapt_step_size,
        adapt_mass_matrix,
        adaptation,
        adaptation_schedule,
    )
    self._max_depth = max_tree_depth

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
def configuration(self) -> dict[str, StateValue]:
    """The kernel's hyperparameters, the maximum tree depth included.

    Returns
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {**super().configuration(), "max_tree_depth": self._max_depth}

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: LatentRegistry

model

The model (unused; the potential carries it).

TYPE: MonadicProgram

x

The input (unused).

TYPE: Tensor

observations

The data (unused).

TYPE: dict[str, Tensor]

initial_position

The starting position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
KernelState

The starting state.

RAISES DESCRIPTION
ValueError

If initial_position has the wrong shape or a non-finite value.

Source code in src/quivers/inference/mcmc/hmc.py
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.Tensor,
) -> KernelState:
    """Reset the adaptation state and build the chain's first state.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.
    model : MonadicProgram
        The model (unused; the potential carries it).
    x : torch.Tensor
        The input (unused).
    observations : dict[str, torch.Tensor]
        The data (unused).
    initial_position : torch.Tensor
        The starting position, shape ``(D,)``.

    Returns
    -------
    KernelState
        The starting state.

    Raises
    ------
    ValueError
        If ``initial_position`` has the wrong shape or a
        non-finite value.
    """
    del model, x, observations
    return self._initial_state(registry, initial_position)

step

step(state: KernelState, potential: PotentialFn) -> KernelState

Run one NUTS transition.

PARAMETER DESCRIPTION
state

The current state.

TYPE: KernelState

potential

The target.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The next state; extras holds the tree-averaged acceptance statistic under "accept_prob" and the tree depth under "tree_depth".

Source code in src/quivers/inference/mcmc/hmc.py
def step(
    self,
    state: KernelState,
    potential: PotentialFn,
) -> KernelState:
    """Run one NUTS transition.

    Parameters
    ----------
    state : KernelState
        The current state.
    potential : PotentialFn
        The target.

    Returns
    -------
    KernelState
        The next state; ``extras`` holds the tree-averaged
        acceptance statistic under ``"accept_prob"`` and the tree
        depth under ``"tree_depth"``.
    """
    assert self._mass is not None, "NUTSKernel.init was not called"
    state = self._prepare_transition(state, potential)
    z = state.position
    ld, g = state.density()
    p = self._mass.sample_momentum(generator=self._generator)
    h0 = float(-ld + self._mass.kinetic(p))
    eps = self.step_size
    z_minus = z
    p_minus = p
    grad_minus = g
    z_plus = z
    p_plus = p
    grad_plus = g
    z_proposal = z
    p_proposal = p
    log_density_proposal = ld
    grad_proposal = g
    log_weight = -h0
    depth = 0
    terminated = False
    sum_accept_prob = 0.0
    n_accept_steps = 0
    diverged = False
    while not terminated and depth < self._max_depth:
        direction = (
            1 if torch.rand((), generator=self._generator).item() > 0.5 else -1
        )
        if direction == -1:
            subtree = self._build_tree(
                z_minus,
                p_minus,
                grad_minus,
                direction,
                depth,
                h0,
                potential,
                eps,
            )
            z_minus = subtree.z_minus
            p_minus = subtree.p_minus
            grad_minus = subtree.grad_minus
        else:
            subtree = self._build_tree(
                z_plus,
                p_plus,
                grad_plus,
                direction,
                depth,
                h0,
                potential,
                eps,
            )
            z_plus = subtree.z_plus
            p_plus = subtree.p_plus
            grad_plus = subtree.grad_plus
        sum_accept_prob += subtree.sum_accept_prob
        n_accept_steps += subtree.n_accept_steps
        if not subtree.turning and not subtree.diverged:
            # Multinomial choice between current proposal and
            # the new subtree. ``log_total = log(e^a + e^b)``
            # via the numerically-stable logaddexp form:
            # ``max(a, b) + log1p(exp(min - max))``. This avoids
            # log(0) when both terms underflow to zero, which
            # happens routinely on ill-conditioned posteriors.
            if math.isfinite(log_weight) and math.isfinite(subtree.log_weight):
                a = max(log_weight, subtree.log_weight)
                b = min(log_weight, subtree.log_weight)
                log_total = a + math.log1p(math.exp(b - a))
            else:
                log_total = max(log_weight, subtree.log_weight)
            if math.isfinite(log_total):
                prob_new = math.exp(subtree.log_weight - log_total)
            else:
                prob_new = 0.0
            if torch.rand((), generator=self._generator).item() < prob_new:
                z_proposal = subtree.z_proposal
                p_proposal = subtree.p_proposal
                log_density_proposal = subtree.log_density_proposal
                grad_proposal = subtree.grad_proposal
            log_weight = log_total
        diverged = diverged or subtree.diverged
        terminated = (
            subtree.turning
            or subtree.diverged
            or _uturn(z_minus, z_plus, p_minus, p_plus, self._mass)
        )
        depth += 1
    accept_prob = (
        sum_accept_prob / float(n_accept_steps) if n_accept_steps > 0 else 0.0
    )
    accepted = not torch.equal(z_proposal, state.position)
    new_state = KernelState(
        position=z_proposal.detach(),
        log_density=log_density_proposal.detach(),
        grad_log_density=grad_proposal.detach(),
        step_count=state.step_count + 1,
        accept_count=state.accept_count + (1 if accepted else 0),
        diverged=diverged,
        extras={**state.extras, "accept_prob": accept_prob, "tree_depth": depth},
        stats={
            "accepted": float(accepted),
            "accept_prob": accept_prob,
            "diverged": float(diverged),
            "step_size": eps,
            "tree_depth": float(depth),
            "num_steps": float(n_accept_steps),
            "energy": float(-log_density_proposal + self._mass.kinetic(p_proposal)),
        },
        gibbs_values=state.gibbs_values,
    )
    self._adapt(new_state, potential, accept_prob)
    return new_state

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 (D,) for one chain, (num_chains, D) for parallel chains.

TYPE: Tensor

log_density

Unconstrained-space log-density (Jacobian-corrected log-joint) at position. Shape () or (num_chains,). None when not evaluated.

TYPE: Tensor | None

grad_log_density

Gradient of log_density with respect to position, same shape as position. Cached so leapfrog re-uses the last-evaluated gradient at the proposal endpoint. None exactly when log_density is.

TYPE: Tensor | None

step_count

Number of step calls so far (counts both warmup and post-warmup steps).

TYPE: int

accept_count

Number of proposals accepted across the chain. Useful for reporting acceptance rate.

TYPE: int

diverged

Whether the most recent step's energy error exceeded the kernel's divergence threshold. Reset by each kernel as appropriate.

TYPE: bool

extras

Per-kernel additional state (e.g. NUTS tree depth, HMC step-size adaptation cumulants).

TYPE: dict

stats

Statistics of the most recent transition, replaced by every MCMCKernel.step: "accepted" (1.0 or 0.0) and "accept_prob" for every kernel, with kernel-specific entries such as "tree_depth". A composite kernel prefixes each component's entries with the component's name and a dot ("nuts.accepted").

TYPE: dict[str, float]

gibbs_values

Current values of the sites a GibbsKernel updates, which sit outside the flat vector. Each is held as a trace-side value, the layout MonadicProgram.log_joint consumes: a non-plate site carries a leading run axis of one, a plate site has its constrained shape. log_density and grad_log_density are those of the potential conditioned on these values.

TYPE: dict[str, Tensor]

has_density property

has_density: bool

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

density() -> tuple[Tensor, Tensor]

The stored log-density and gradient.

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

log_density and grad_log_density.

RAISES DESCRIPTION
RuntimeError

If they are None; evaluated gives a state that has them.

Source code in src/quivers/inference/mcmc/kernel.py
def density(self) -> tuple[torch.Tensor, torch.Tensor]:
    """The stored log-density and gradient.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        ``log_density`` and ``grad_log_density``.

    Raises
    ------
    RuntimeError
        If they are ``None``; `evaluated` gives a state that has them.
    """
    if self.log_density is None or self.grad_log_density is None:
        raise RuntimeError(
            "KernelState.density: the state's log-density is not evaluated; "
            "read it from KernelState.evaluated(potential)"
        )
    return self.log_density, self.grad_log_density

evaluated

evaluated(potential: PotentialFn) -> KernelState

The state with its log-density and gradient evaluated.

PARAMETER DESCRIPTION
potential

The target conditioned on this state's gibbs_values.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

This state when has_density; otherwise a state with the same fields and the potential's value and gradient at position, from one PotentialFn.value_and_grad.

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
def evaluated(self, potential: PotentialFn) -> KernelState:
    """The state with its log-density and gradient evaluated.

    Parameters
    ----------
    potential : PotentialFn
        The target conditioned on this state's ``gibbs_values``.

    Returns
    -------
    KernelState
        This state when `has_density`; otherwise a state with the
        same fields and the potential's value and gradient at
        ``position``, from one `PotentialFn.value_and_grad`.

    Raises
    ------
    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.
    """
    if self.has_density:
        return self
    log_density, grad = potential.value_and_grad(self.position)
    if self.step_count > 0 and not math.isfinite(float(log_density)):
        raise RuntimeError(
            "KernelState.evaluated: the chain's log-density is not finite at "
            f"the values a transition left for {sorted(self.gibbs_values)}"
        )
    return self.with_(log_density=log_density, grad_log_density=grad)

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 None; from_state_dict rebuilds the state exactly.

RAISES DESCRIPTION
TypeError

If extras holds a value other than a tensor, a Python scalar, or a string.

Source code in src/quivers/inference/mcmc/kernel.py
def state_dict(self) -> dict[str, StateValue]:
    """The state as a dictionary a checkpoint can store.

    Returns
    -------
    dict[str, StateValue]
        Every field, with tensors detached and an unevaluated
        density as ``None``; `from_state_dict` rebuilds the state
        exactly.

    Raises
    ------
    TypeError
        If ``extras`` holds a value other than a tensor, a Python
        scalar, or a string.
    """
    extras: dict[str, StateValue] = {}
    for key, value in self.extras.items():
        if not isinstance(value, torch.Tensor | float | int | bool | str):
            raise TypeError(
                f"KernelState.state_dict: extras[{key!r}] is a "
                f"{type(value).__name__}, which a checkpoint cannot store"
            )
        extras[str(key)] = (
            value.detach() if isinstance(value, torch.Tensor) else value
        )
    return {
        "position": self.position.detach(),
        "log_density": (
            None if self.log_density is None else self.log_density.detach()
        ),
        "grad_log_density": (
            None
            if self.grad_log_density is None
            else self.grad_log_density.detach()
        ),
        "step_count": self.step_count,
        "accept_count": self.accept_count,
        "diverged": self.diverged,
        "extras": extras,
        "stats": {key: float(value) for key, value in self.stats.items()},
        "gibbs_values": {k: v.detach() for k, v in self.gibbs_values.items()},
    }

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 state_dict produced.

TYPE: dict[str, StateValue]

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
@classmethod
def from_state_dict(cls, state: dict[str, StateValue]) -> "KernelState":
    """Rebuild a state from `state_dict`'s output.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.

    Returns
    -------
    KernelState
        The state.

    Raises
    ------
    ValueError
        If a field is missing or has the wrong type.
    """
    try:
        position = state["position"]
        log_density = state["log_density"]
        grad = state["grad_log_density"]
        step_count = state["step_count"]
        accept_count = state["accept_count"]
        diverged = state["diverged"]
        extras = state["extras"]
        stats = state["stats"]
        gibbs_values = state["gibbs_values"]
    except KeyError as error:
        raise ValueError(f"KernelState.from_state_dict: missing {error}") from None
    if not (
        isinstance(position, torch.Tensor)
        and (log_density is None or isinstance(log_density, torch.Tensor))
        and (grad is None or isinstance(grad, torch.Tensor))
        and isinstance(step_count, int)
        and isinstance(accept_count, int)
        and isinstance(diverged, bool)
        and isinstance(extras, dict)
        and isinstance(stats, dict)
        and isinstance(gibbs_values, dict)
    ):
        raise ValueError("KernelState.from_state_dict: a field has the wrong type")
    values: dict[str, torch.Tensor] = {}
    for name, value in gibbs_values.items():
        if not isinstance(value, torch.Tensor):
            raise ValueError(
                f"KernelState.from_state_dict: Gibbs value {name!r} is not a tensor"
            )
        values[name] = value
    floats: dict[str, float] = {}
    for key, value in stats.items():
        if not isinstance(value, float):
            raise ValueError(
                f"KernelState.from_state_dict: statistic {key!r} is not a float"
            )
        floats[key] = value
    try:
        return cls(
            position=position,
            log_density=log_density,
            grad_log_density=grad,
            step_count=step_count,
            accept_count=accept_count,
            diverged=diverged,
            extras=dict(extras),
            stats=floats,
            gibbs_values=values,
        )
    except dx.ValidationError as error:
        raise ValueError(f"KernelState.from_state_dict: {error}") from error

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

gibbs_sites: frozenset[str]

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

host_sites: frozenset[str]

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 (N, D).

TYPE: Tensor

Source code in src/quivers/inference/mcmc/kernel.py
def tune(self, population: torch.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.

    Parameters
    ----------
    population : torch.Tensor
        The particles' flat positions, shape ``(N, D)``.
    """
    del population

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
def configuration(self) -> 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
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {"kernel": f"{type(self).__module__}.{type(self).__qualname__}"}

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
def state_dict(self) -> 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
    -------
    dict[str, StateValue]
        The state.
    """
    return {"is_adapting": self.is_adapting}

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 state_dict produced.

TYPE: dict[str, StateValue]

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
def load_state_dict(self, 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.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.

    Raises
    ------
    ValueError
        If the dictionary lacks an entry or holds one of the wrong
        type.
    """
    flag = state.get("is_adapting")
    if not isinstance(flag, bool):
        raise ValueError(
            f"{type(self).__name__}.load_state_dict: is_adapting must be a bool"
        )
    self.is_adapting = flag

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
@abstractmethod
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.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."""

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
@abstractmethod
def step(
    self,
    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."""

start_adaptation

start_adaptation(num_warmup: int) -> None

Enter the adaptation (warmup) phase.

PARAMETER DESCRIPTION
num_warmup

Number of warmup transitions that follow before stop_adaptation, so that a kernel can lay out a warmup schedule.

TYPE: int

Source code in src/quivers/inference/mcmc/kernel.py
def start_adaptation(self, num_warmup: int) -> None:
    """Enter the adaptation (warmup) phase.

    Parameters
    ----------
    num_warmup : int
        Number of warmup transitions that follow before
        `stop_adaptation`, so that a kernel can lay out a warmup
        schedule.
    """
    del num_warmup
    self.is_adapting = True

stop_adaptation

stop_adaptation() -> None

Freeze the kernel's adapted parameters.

Source code in src/quivers/inference/mcmc/kernel.py
def stop_adaptation(self) -> None:
    """Freeze the kernel's adapted parameters."""
    self.is_adapting = False

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: MonadicProgram

registry

Latent-site registry for model.

TYPE: LatentRegistry

x

Model input. Shape (batch, ...).

TYPE: Tensor

observations

Observed-site values and host data.

TYPE: dict[str, Tensor]

RAISES DESCRIPTION
ValueError

If x has more than one row, or an observed value is not finite or lies outside its site's support.

Source code in src/quivers/inference/mcmc/kernel.py
def __init__(
    self,
    model: MonadicProgram,
    registry: LatentRegistry,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> None:
    _require_one_run(x, "PotentialFn")
    _check_observed_support(model, observations, "PotentialFn")
    self._model = model
    self._registry = registry
    self._x = x
    self._base_observations = observations
    self._conditioned: dict[str, torch.Tensor] = {}
    self._observations = observations
    # [forward passes, gradient evaluations], shared with every
    # conditioned copy so that a chain's evaluations are counted in
    # one place.
    self._counts = [0, 0]
    # The program's log joint prepared per layout of the values,
    # shared with every conditioned copy: conditioning changes the
    # values, not their layout.
    self._plans = JointPlans(model, x)
    # The sets of given names under which every step has been found
    # to declare that it can be evaluated at many positions.
    self._batchable: set[frozenset[str]] = set()

num_evaluations property

num_evaluations: int

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

num_gradient_evaluations: int

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: Mapping[str, Tensor]

RETURNS DESCRIPTION
PotentialFn

A potential of the same class sharing the model, registry, input, and data.

RAISES DESCRIPTION
ValueError

If a name in values is a site of the registry or one of the observations.

Source code in src/quivers/inference/mcmc/kernel.py
def condition(self, values: Mapping[str, torch.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.

    Parameters
    ----------
    values : Mapping[str, torch.Tensor]
        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).

    Returns
    -------
    PotentialFn
        A potential of the same class sharing the model, registry,
        input, and data.

    Raises
    ------
    ValueError
        If a name in ``values`` is a site of the registry or one of
        the observations.
    """
    clash = sorted(
        name
        for name in values
        if name in self._registry or name in self._base_observations
    )
    if clash:
        raise ValueError(
            f"PotentialFn.condition: {clash} are latent sites of the registry "
            "or observations, so they cannot also be conditioned on"
        )
    conditioned = copy.copy(self)
    conditioned._conditioned = dict(values)
    conditioned._observations = {**self._base_observations, **values}
    return conditioned

log_density

log_density(z: Tensor) -> Tensor

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 (D,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Scalar Jacobian-corrected log-density, or -inf where the position is outside the model's support.

RAISES DESCRIPTION
ValueError

If z does not have the registry's flat length, or a plate is subsampled, since the potential is the exact log density.

Exception

Any error log_joint raises that does not mark the position as outside the support.

Source code in src/quivers/inference/mcmc/kernel.py
def log_density(self, z: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    z : torch.Tensor
        Flat unconstrained position, shape ``(D,)``.

    Returns
    -------
    torch.Tensor
        Scalar Jacobian-corrected log-density, or ``-inf`` where
        the position is outside the model's support.

    Raises
    ------
    ValueError
        If ``z`` does not have the registry's flat length, or a plate
        is subsampled, since the potential is the exact log density.
    Exception
        Any error ``log_joint`` raises that does not mark the
        position as outside the support.
    """
    refuse_subsampling(type(self).__name__)
    self._counts[0] += 1
    try:
        result = self._joint_density(z)
    except (ValueError, RuntimeError) as error:
        if not rejects_position(error):
            raise
        return torch.tensor(float("-inf"), device=z.device, dtype=z.dtype)
    if not torch.isfinite(result):
        return torch.tensor(float("-inf"), device=z.device, dtype=z.dtype)
    return result

log_density_batch

log_density_batch(positions: Tensor) -> Tensor

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 (B, D).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The Jacobian-corrected log-density of each row, shape (B,), and -inf at rows outside the model's support.

RAISES DESCRIPTION
ValueError

If positions does not have shape (B, D), or a plate is subsampled.

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 log_joint is overridden, handlers are on the stack, or another evaluator is installed). The error names each step and the reason.

PositionLayoutError

If a callable declared batched returns a value that does not lead with the position axis.

Exception

Any error log_density raises at a row, other than one marking the row as outside the support.

Source code in src/quivers/inference/mcmc/kernel.py
def log_density_batch(self, positions: torch.Tensor) -> torch.Tensor:
    """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`][quivers.continuous.program_steps.Let],
    [`Score`][quivers.continuous.program_steps.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.

    Parameters
    ----------
    positions : torch.Tensor
        Flat unconstrained positions, shape ``(B, D)``.

    Returns
    -------
    torch.Tensor
        The Jacobian-corrected log-density of each row, shape
        ``(B,)``, and ``-inf`` at rows outside the model's support.

    Raises
    ------
    ValueError
        If ``positions`` does not have shape ``(B, D)``, or a plate is
        subsampled.
    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 ``log_joint`` is overridden, handlers are
        on the stack, or another evaluator is installed). The error
        names each step and the reason.
    PositionLayoutError
        If a callable declared ``batched`` returns a value that does
        not lead with the position axis.
    Exception
        Any error `log_density` raises at a row, other than one
        marking the row as outside the support.
    """
    dimension = self._registry.total_unconstrained_dim
    if positions.dim() != 2 or int(positions.shape[1]) != dimension:
        raise ValueError(
            f"{type(self).__name__}.log_density_batch: expected positions of "
            f"shape (B, {dimension}), got {tuple(positions.shape)}"
        )
    refuse_subsampling(type(self).__name__)
    given = frozenset((*self._observations, *(fixed_site_values() or {})))
    if given in self._batchable:
        require_own_joint(self._model)
    else:
        require_batchable(self._model, self._registry.names, given)
        self._batchable.add(given)
    self._counts[0] += 1
    outside = positions.new_full((int(positions.shape[0]),), float("-inf"))
    if positions.shape[0] == 0:
        return outside
    try:
        mapped = map_positions(self._joint_density, positions)
    except (ValueError, RuntimeError) as error:
        if not rejects_position(error):
            raise
        return outside
    inside = mapped.accepted & torch.isfinite(mapped.values)
    return torch.where(inside, mapped.values, outside)

check_initial

check_initial(z: Tensor) -> Tensor

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 (D,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The finite scalar Jacobian-corrected log-density at z.

RAISES DESCRIPTION
ValueError

If the log-density at z is not finite.

Exception

Any error log_joint raises at z.

Source code in src/quivers/inference/mcmc/kernel.py
def check_initial(self, z: torch.Tensor) -> torch.Tensor:
    """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.

    Parameters
    ----------
    z : torch.Tensor
        Flat unconstrained initial position, shape ``(D,)``.

    Returns
    -------
    torch.Tensor
        The finite scalar Jacobian-corrected log-density at ``z``.

    Raises
    ------
    ValueError
        If the log-density at ``z`` is not finite.
    Exception
        Any error ``log_joint`` raises at ``z``.
    """
    with torch.no_grad(), _distribution_validation():
        trace_side, log_det_total = self._trace_side(z)
        values = {**trace_side, **self._observations}
        result = self._model.log_joint(self._x, values).sum() + log_det_total
        if torch.isfinite(result):
            return result
        recorded = trace(self._model, self._x, observations=values)
    offending = sorted(
        name
        for name, site in recorded.sites.items()
        if not torch.isfinite(site.log_prob).all()
    )
    if not torch.isfinite(log_det_total):
        offending.append("the bijector log-Jacobian")
    raise _NonFiniteInitialDensity(
        f"PotentialFn: the log-density at the initial position is "
        f"{float(result)}; non-finite terms: {', '.join(offending) or 'none recorded'}"
    )

value_and_grad

value_and_grad(z: Tensor) -> tuple[Tensor, Tensor]

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 (D,).

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The detached scalar log-density and its detached gradient with respect to z (shape (D,)).

RAISES DESCRIPTION
Exception

Any error log_density propagates: an error from the program or its data rather than a position outside the support.

Source code in src/quivers/inference/mcmc/kernel.py
def value_and_grad(self, z: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """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.

    Parameters
    ----------
    z : torch.Tensor
        Flat unconstrained position, shape ``(D,)``.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The detached scalar log-density and its detached
        gradient with respect to ``z`` (shape ``(D,)``).

    Raises
    ------
    Exception
        Any error `log_density` propagates: an error from the
        program or its data rather than a position outside the
        support.
    """
    self._counts[1] += 1
    if z.numel() == 0:
        # Every latent is held outside the flat vector (a model a
        # GibbsKernel samples alone): there is nothing to
        # differentiate with respect to.
        with torch.no_grad():
            return self.log_density(z).detach(), torch.zeros_like(z)
    z_leaf = z.detach().clone().requires_grad_(True)
    with torch.enable_grad():
        ld = self.log_density(z_leaf)
        if not torch.isfinite(ld):
            return ld.detach(), torch.zeros_like(z)
        grad = torch.autograd.grad(
            ld, z_leaf, create_graph=False, allow_unused=False
        )[0]
    if grad is None or not torch.isfinite(grad).all():
        return ld.detach(), torch.zeros_like(z)
    return ld.detach(), grad.detach()

value_and_grad_batch

value_and_grad_batch(positions: Tensor) -> tuple[Tensor, Tensor]

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 (B, D).

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The detached log-densities, shape (B,), and the detached gradients, shape (B, D).

RAISES DESCRIPTION
ValueError

If positions does not have shape (B, D), or a plate is subsampled.

UnbatchableProgramError

As log_density_batch raises it.

Exception

Any error log_density_batch raises.

Source code in src/quivers/inference/mcmc/kernel.py
def value_and_grad_batch(
    self, positions: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """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.

    Parameters
    ----------
    positions : torch.Tensor
        Flat unconstrained positions, shape ``(B, D)``.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The detached log-densities, shape ``(B,)``, and the detached
        gradients, shape ``(B, D)``.

    Raises
    ------
    ValueError
        If ``positions`` does not have shape ``(B, D)``, or a plate is
        subsampled.
    UnbatchableProgramError
        As `log_density_batch` raises it.
    Exception
        Any error `log_density_batch` raises.
    """
    self._counts[1] += 1
    if positions.numel() == 0:
        with torch.no_grad():
            values = self.log_density_batch(positions)
        return values.detach(), torch.zeros_like(positions)
    leaf = positions.detach().clone().requires_grad_(True)
    with torch.enable_grad():
        values = self.log_density_batch(leaf)
        inside = torch.isfinite(values)
        if not bool(inside.any()):
            return values.detach(), torch.zeros_like(positions)
        grad = torch.autograd.grad(values[inside].sum(), leaf)[0]
    usable = inside & torch.isfinite(grad).all(dim=-1)
    return values.detach(), torch.where(
        usable.unsqueeze(-1), grad, torch.zeros_like(grad)
    ).detach()

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:g, with event shape (D,) and no batch shape, over the registry's flat unconstrained vector.

TYPE: Distribution

defensive

The defensive component :math:d, shaped as distribution.

TYPE: Distribution DEFAULT: None

defensive_weight

The weight :math:w of defensive, in (0, 1). Default 0.1; ignored without defensive.

TYPE: float DEFAULT: 0.1

RAISES DESCRIPTION
ValueError

If a distribution has a batch shape or an event shape other than a vector, or defensive_weight is outside (0, 1).

Source code in src/quivers/inference/mcmc/metropolis.py
def __init__(
    self,
    distribution: Distribution,
    defensive: Distribution | None = None,
    defensive_weight: float = 0.1,
) -> None:
    for name, dist in (("distribution", distribution), ("defensive", defensive)):
        if dist is None:
            continue
        if tuple(dist.batch_shape) != () or len(dist.event_shape) != 1:
            raise ValueError(
                f"IndependenceProposal: {name} must have event shape (D,) and "
                f"no batch shape; got batch {tuple(dist.batch_shape)}, event "
                f"{tuple(dist.event_shape)}"
            )
    if defensive is not None and not 0.0 < defensive_weight < 1.0:
        raise ValueError(
            "IndependenceProposal: defensive_weight must be in (0, 1), "
            f"got {defensive_weight}"
        )
    if defensive is not None and defensive.event_shape != distribution.event_shape:
        raise ValueError(
            "IndependenceProposal: defensive and distribution have event shapes "
            f"{tuple(defensive.event_shape)} and {tuple(distribution.event_shape)}"
        )
    self._distribution = distribution
    self._defensive = defensive
    self._weight = defensive_weight

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
def configuration(self) -> 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
    -------
    dict[str, StateValue]
        The configuration.
    """
    dim = int(self._distribution.event_shape[0])
    probes = (torch.zeros(dim), torch.linspace(-1.0, 1.0, dim))
    return {
        **super().configuration(),
        "distribution": type(self._distribution).__qualname__,
        "defensive": None
        if self._defensive is None
        else type(self._defensive).__qualname__,
        "defensive_weight": self._weight if self._defensive is not None else None,
        "log_prob_probes": [float(self.log_prob(point)) for point in probes],
    }

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: LatentRegistry

RAISES DESCRIPTION
ValueError

If the event shape is not (D,).

Source code in src/quivers/inference/mcmc/metropolis.py
def bind(self, registry: LatentRegistry) -> None:
    """Check the proposal's event shape against the flat vector.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.

    Raises
    ------
    ValueError
        If the event shape is not ``(D,)``.
    """
    dim = registry.total_unconstrained_dim
    if tuple(self._distribution.event_shape) != (dim,):
        raise ValueError(
            "IndependenceProposal: the distribution has event shape "
            f"{tuple(self._distribution.event_shape)}; the flat vector has "
            f"length {dim}"
        )

log_prob

log_prob(value: Tensor) -> Tensor

The proposal's log-density.

PARAMETER DESCRIPTION
value

A flat position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The scalar :math:\log q(\text{value}).

Source code in src/quivers/inference/mcmc/metropolis.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """The proposal's log-density.

    Parameters
    ----------
    value : torch.Tensor
        A flat position, shape ``(D,)``.

    Returns
    -------
    torch.Tensor
        The scalar :math:`\\log q(\\text{value})`.
    """
    log_g = self._distribution.log_prob(value)
    if self._defensive is None:
        return log_g
    log_d = self._defensive.log_prob(value)
    return torch.logaddexp(
        math.log1p(-self._weight) + log_g, math.log(self._weight) + log_d
    )

propose

propose(position: Tensor, generator: Generator | None) -> tuple[Tensor, Tensor]

Draw from the proposal, independently of position.

PARAMETER DESCRIPTION
position

The current position, shape (D,).

TYPE: Tensor

generator

The chain-local generator; the component choice and the draw both come from it.

TYPE: Generator | None

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The candidate and log q(position) - log q(candidate).

Source code in src/quivers/inference/mcmc/metropolis.py
def propose(
    self, position: torch.Tensor, generator: torch.Generator | None
) -> tuple[torch.Tensor, torch.Tensor]:
    """Draw from the proposal, independently of ``position``.

    Parameters
    ----------
    position : torch.Tensor
        The current position, shape ``(D,)``.
    generator : torch.Generator | None
        The chain-local generator; the component choice and the
        draw both come from it.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The candidate and ``log q(position) - log q(candidate)``.
    """
    source = self._distribution
    if self._defensive is not None:
        pick = torch.rand((), generator=generator).item()
        if pick < self._weight:
            source = self._defensive
    candidate = _with_generator(generator, lambda: source.sample())
    candidate = candidate.to(position.dtype)
    return candidate, self.log_prob(position) - self.log_prob(candidate)

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: Proposal

Source code in src/quivers/inference/mcmc/metropolis.py
def __init__(self, proposal: Proposal) -> None:
    self._proposal = proposal

proposal property

proposal: Proposal

The proposal the kernel draws candidates from.

tune

tune(population: Tensor) -> None

Forward a population to the proposal (Proposal.tune).

PARAMETER DESCRIPTION
population

Flat positions, shape (N, D).

TYPE: Tensor

Source code in src/quivers/inference/mcmc/metropolis.py
def tune(self, population: torch.Tensor) -> None:
    """Forward a population to the proposal (`Proposal.tune`).

    Parameters
    ----------
    population : torch.Tensor
        Flat positions, shape ``(N, D)``.
    """
    self._proposal.tune(population)

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
def configuration(self) -> dict[str, StateValue]:
    """The class and the proposal's configuration.

    Returns
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {**super().configuration(), "proposal": self._proposal.configuration()}

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
def state_dict(self) -> dict[str, StateValue]:
    """Whether the kernel is adapting, and the proposal's state.

    Returns
    -------
    dict[str, StateValue]
        The state.
    """
    return {**super().state_dict(), "proposal": self._proposal.state_dict()}

load_state_dict

load_state_dict(state: dict[str, StateValue]) -> None

Restore what state_dict returned.

PARAMETER DESCRIPTION
state

A dictionary state_dict produced.

TYPE: dict[str, StateValue]

RAISES DESCRIPTION
ValueError

If an entry is missing or has the wrong type.

Source code in src/quivers/inference/mcmc/metropolis.py
def load_state_dict(self, state: dict[str, StateValue]) -> None:
    """Restore what `state_dict` returned.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.

    Raises
    ------
    ValueError
        If an entry is missing or has the wrong type.
    """
    super().load_state_dict(state)
    proposal = state.get("proposal")
    if not isinstance(proposal, dict):
        raise ValueError("MetropolisKernel.load_state_dict: bad proposal state")
    self._proposal.load_state_dict(proposal)

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: LatentRegistry

model

The model (unused; the potential carries it).

TYPE: MonadicProgram

x

The input (unused).

TYPE: Tensor

observations

The data (unused).

TYPE: dict[str, Tensor]

initial_position

The starting position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
KernelState

The starting state; its log-density and gradient are evaluated by the first transition.

RAISES DESCRIPTION
ValueError

If initial_position has the wrong shape or a non-finite value, or the proposal refuses the registry.

Source code in src/quivers/inference/mcmc/metropolis.py
def init(
    self,
    registry: LatentRegistry,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    initial_position: torch.Tensor,
) -> KernelState:
    """Bind the proposal and build the chain's first state.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.
    model : MonadicProgram
        The model (unused; the potential carries it).
    x : torch.Tensor
        The input (unused).
    observations : dict[str, torch.Tensor]
        The data (unused).
    initial_position : torch.Tensor
        The starting position, shape ``(D,)``.

    Returns
    -------
    KernelState
        The starting state; its log-density and gradient are
        evaluated by the first transition.

    Raises
    ------
    ValueError
        If ``initial_position`` has the wrong shape or a non-finite
        value, or the proposal refuses the registry.
    """
    del model, x, observations
    dim = registry.total_unconstrained_dim
    if initial_position.shape != (dim,):
        raise ValueError(
            f"MetropolisKernel.init: initial_position must have shape ({dim},); "
            f"got {tuple(initial_position.shape)}"
        )
    if not bool(torch.isfinite(initial_position).all()):
        raise ValueError(
            "MetropolisKernel.init: initial_position must contain only finite "
            "values"
        )
    self.is_adapting = False
    self._proposal.bind(registry)
    return KernelState(
        position=initial_position.clone(),
        log_density=torch.tensor(0.0),
        grad_log_density=torch.zeros(dim),
    )

step

step(state: KernelState, potential: PotentialFn) -> KernelState

Run one Metropolis-Hastings transition.

PARAMETER DESCRIPTION
state

The current state.

TYPE: KernelState

potential

The target, conditioned on the state's Gibbs values.

TYPE: PotentialFn

RETURNS DESCRIPTION
KernelState

The next state, with stats holding "accepted" and "accept_prob".

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
def step(self, state: KernelState, potential: PotentialFn) -> KernelState:
    """Run one Metropolis-Hastings transition.

    Parameters
    ----------
    state : KernelState
        The current state.
    potential : PotentialFn
        The target, conditioned on the state's Gibbs values.

    Returns
    -------
    KernelState
        The next state, with ``stats`` holding ``"accepted"`` and
        ``"accept_prob"``.

    Raises
    ------
    ValueError
        If the proposal returns a candidate of the wrong shape or a
        correction that is not a scalar.
    """
    state = self._evaluate_first(state, potential)
    candidate, log_correction = self._proposal.propose(
        state.position, self._generator
    )
    if candidate.shape != state.position.shape:
        raise ValueError(
            f"MetropolisKernel: the proposal returned a candidate of shape "
            f"{tuple(candidate.shape)}; the position has shape "
            f"{tuple(state.position.shape)}"
        )
    if log_correction.numel() != 1:
        raise ValueError(
            "MetropolisKernel: the proposal's log Hastings correction must be a "
            f"scalar; got shape {tuple(log_correction.shape)}"
        )
    candidate = candidate.detach()
    with torch.no_grad():
        log_density = potential.log_density(candidate)
    current_log_density, current_grad = state.density()
    log_alpha = float(
        log_density - current_log_density + log_correction.reshape(())
    )
    if math.isnan(log_alpha):
        log_alpha = -math.inf
    accept_prob = math.exp(min(0.0, log_alpha))
    uniform = torch.rand((), generator=self._generator).item()
    accepted = uniform < accept_prob
    if accepted:
        new_log_density, new_grad = potential.value_and_grad(candidate)
        position = candidate
    else:
        new_log_density, new_grad = current_log_density, current_grad
        position = state.position
    return KernelState(
        position=position,
        log_density=new_log_density,
        grad_log_density=new_grad,
        step_count=state.step_count + 1,
        accept_count=state.accept_count + int(accepted),
        diverged=False,
        extras={**state.extras, "accept_prob": accept_prob},
        stats={"accepted": float(accepted), "accept_prob": accept_prob},
        gibbs_values=state.gibbs_values,
    )

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: LatentRegistry

Source code in src/quivers/inference/mcmc/metropolis.py
def bind(self, 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.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.
    """
    del registry

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 (N, D).

TYPE: Tensor

Source code in src/quivers/inference/mcmc/metropolis.py
def tune(self, population: torch.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.

    Parameters
    ----------
    population : torch.Tensor
        Flat positions, shape ``(N, D)``.
    """
    del population

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
def configuration(self) -> 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
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {"proposal": f"{type(self).__module__}.{type(self).__qualname__}"}

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
def state_dict(self) -> 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
    -------
    dict[str, StateValue]
        The state.
    """
    return {}

load_state_dict

load_state_dict(state: dict[str, StateValue]) -> None

Restore what state_dict returned, after bind.

PARAMETER DESCRIPTION
state

A dictionary state_dict produced.

TYPE: dict[str, StateValue]

Source code in src/quivers/inference/mcmc/metropolis.py
def load_state_dict(self, state: dict[str, StateValue]) -> None:
    """Restore what `state_dict` returned, after `bind`.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.
    """
    del state

propose abstractmethod

propose(position: Tensor, generator: Generator | None) -> tuple[Tensor, Tensor]

Draw a candidate and its log Hastings correction.

PARAMETER DESCRIPTION
position

The current flat unconstrained position, shape (D,).

TYPE: Tensor

generator

The chain-local generator every random draw must use.

TYPE: Generator | None

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The candidate, shape (D,), and the scalar log q(position | candidate) - log q(candidate | position), zero for a symmetric proposal.

Source code in src/quivers/inference/mcmc/metropolis.py
@abstractmethod
def propose(
    self, position: torch.Tensor, generator: torch.Generator | None
) -> tuple[torch.Tensor, torch.Tensor]:
    """Draw a candidate and its log Hastings correction.

    Parameters
    ----------
    position : torch.Tensor
        The current flat unconstrained position, shape ``(D,)``.
    generator : torch.Generator | None
        The chain-local generator every random draw must use.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The candidate, shape ``(D,)``, and the scalar
        ``log q(position | candidate) - log q(candidate | position)``,
        zero for a symmetric proposal.
    """

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:\sigma, a positive float or a (D,) tensor of positive per-coordinate scales.

TYPE: float | Tensor

RAISES DESCRIPTION
ValueError

If a scale is not positive and finite.

Source code in src/quivers/inference/mcmc/metropolis.py
def __init__(self, scale: float | torch.Tensor) -> None:
    scale_t = torch.as_tensor(scale, dtype=torch.get_default_dtype())
    if not bool(torch.isfinite(scale_t).all()) or not bool((scale_t > 0).all()):
        raise ValueError(
            f"RandomWalkProposal: scale must be positive and finite, got {scale}"
        )
    self._scale = scale_t

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 (N, D), with N >= 2.

TYPE: Tensor

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
def tune(self, population: torch.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>`_).

    Parameters
    ----------
    population : torch.Tensor
        Flat positions, shape ``(N, D)``, with ``N >= 2``.

    Raises
    ------
    ValueError
        If the population has fewer than two rows or a coordinate
        with no spread.
    """
    if population.dim() != 2 or population.shape[0] < 2:
        raise ValueError(
            "RandomWalkProposal.tune: the population must have shape (N, D) "
            f"with N >= 2; got {tuple(population.shape)}"
        )
    spread = population.std(dim=0)
    if not bool((spread > 0).all()):
        raise ValueError(
            "RandomWalkProposal.tune: a coordinate of the population has no "
            "spread, so no scale can be read from it"
        )
    self._scale = 2.38 / math.sqrt(population.shape[1]) * spread

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
def configuration(self) -> dict[str, StateValue]:
    """The class and the step scale.

    Returns
    -------
    dict[str, StateValue]
        The configuration.
    """
    return {**super().configuration(), "scale": self._scale.tolist()}

state_dict

state_dict() -> dict[str, StateValue]

The step scale, which tune may have changed.

RETURNS DESCRIPTION
dict[str, StateValue]

The scale.

Source code in src/quivers/inference/mcmc/metropolis.py
def state_dict(self) -> dict[str, StateValue]:
    """The step scale, which `tune` may have changed.

    Returns
    -------
    dict[str, StateValue]
        The scale.
    """
    return {"scale": self._scale.clone()}

load_state_dict

load_state_dict(state: dict[str, StateValue]) -> None

Restore the step scale.

PARAMETER DESCRIPTION
state

A dictionary state_dict produced.

TYPE: dict[str, StateValue]

RAISES DESCRIPTION
ValueError

If the scale is missing.

Source code in src/quivers/inference/mcmc/metropolis.py
def load_state_dict(self, state: dict[str, StateValue]) -> None:
    """Restore the step scale.

    Parameters
    ----------
    state : dict[str, StateValue]
        A dictionary `state_dict` produced.

    Raises
    ------
    ValueError
        If the scale is missing.
    """
    scale = state.get("scale")
    if not isinstance(scale, torch.Tensor):
        raise ValueError("RandomWalkProposal.load_state_dict: bad scale")
    self._scale = scale.clone()

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: LatentRegistry

RAISES DESCRIPTION
ValueError

If scale is a vector of the wrong length.

Source code in src/quivers/inference/mcmc/metropolis.py
def bind(self, registry: LatentRegistry) -> None:
    """Check a per-coordinate scale against the flat vector's length.

    Parameters
    ----------
    registry : LatentRegistry
        The registry whose flat vector the chain walks.

    Raises
    ------
    ValueError
        If ``scale`` is a vector of the wrong length.
    """
    dim = registry.total_unconstrained_dim
    if self._scale.dim() > 0 and tuple(self._scale.shape) != (dim,):
        raise ValueError(
            f"RandomWalkProposal: scale has shape {tuple(self._scale.shape)}; "
            f"the flat vector has length {dim}"
        )

propose

propose(position: Tensor, generator: Generator | None) -> tuple[Tensor, Tensor]

Draw position + scale * N(0, I).

PARAMETER DESCRIPTION
position

The current position, shape (D,).

TYPE: Tensor

generator

The chain-local generator.

TYPE: Generator | None

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The candidate and a zero correction.

Source code in src/quivers/inference/mcmc/metropolis.py
def propose(
    self, position: torch.Tensor, generator: torch.Generator | None
) -> tuple[torch.Tensor, torch.Tensor]:
    """Draw ``position + scale * N(0, I)``.

    Parameters
    ----------
    position : torch.Tensor
        The current position, shape ``(D,)``.
    generator : torch.Generator | None
        The chain-local generator.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The candidate and a zero correction.
    """
    noise = torch.randn(position.shape, generator=generator, dtype=position.dtype)
    return position + self._scale * noise, torch.zeros((), dtype=position.dtype)

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: str

run_seed

The run seed the worker derived its chain streams from.

TYPE: int

states

Each chain's record, as a checkpoint stores it, keyed by chain index.

TYPE: Mapping[int, dict[str, StateValue]] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

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: tuple[int, ...]

RETURNS DESCRIPTION
ChainStates

Their records.

Source code in src/quivers/inference/mcmc/parallel.py
def __call__(self, chains: tuple[int, ...]) -> ChainStates:
    """Run the assigned chains.

    Parameters
    ----------
    chains : tuple[int, ...]
        Chain indices.

    Returns
    -------
    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
def find_reasonable_step_size(
    log_density: Callable[[torch.Tensor], torch.Tensor],
    grad_log_density: Callable[[torch.Tensor], torch.Tensor],
    z0: torch.Tensor,
    initial_step: float = 1.0,
    target_log_accept: float = math.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.
    """
    eps = initial_step
    z = z0.clone()
    ld0 = log_density(z)
    g0 = grad_log_density(z)
    p = torch.randn_like(z)
    h0 = ld0 - 0.5 * (p * p).sum()
    # One leapfrog step at eps.
    z1 = z + eps * p + 0.5 * eps * eps * g0
    g1 = grad_log_density(z1)
    p1 = p + 0.5 * eps * (g0 + g1)
    ld1 = log_density(z1)
    h1 = ld1 - 0.5 * (p1 * p1).sum()
    log_accept = float(h1 - h0)
    if not math.isfinite(log_accept):
        log_accept = -float("inf")
    direction = 1 if log_accept > target_log_accept else -1
    for _ in range(100):
        eps = eps * (2.0**direction)
        if eps < 1e-10 or eps > 1e10:
            break
        z1 = z + eps * p + 0.5 * eps * eps * g0
        g1 = grad_log_density(z1)
        p1 = p + 0.5 * eps * (g0 + g1)
        ld1 = log_density(z1)
        h1 = ld1 - 0.5 * (p1 * p1).sum()
        new_log_accept = float(h1 - h0)
        if not math.isfinite(new_log_accept):
            new_log_accept = -float("inf")
        crossed = (direction == 1 and new_log_accept < target_log_accept) or (
            direction == -1 and new_log_accept > target_log_accept
        )
        log_accept = new_log_accept
        if crossed:
            break
    return eps

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: MCMC

model

The parent's program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

parts

Every worker's records.

TYPE: Sequence[ChainStates]

RETURNS DESCRIPTION
MCMCResult

The result MCMC.run returns for the same seed.

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
def assemble_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    parts: Sequence[ChainStates],
) -> MCMCResult:
    """Assemble the result of a run from its chains' records.

    Parameters
    ----------
    mcmc : MCMC
        The parent's driver.
    model : MonadicProgram
        The parent's program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    parts : Sequence[ChainStates]
        Every worker's records.

    Returns
    -------
    MCMCResult
        The result `MCMC.run` returns for the same seed.

    Raises
    ------
    ValueError
        If a worker rebuilt a different program or data, used another run
        seed, or the parts do not cover every chain exactly once.
    """
    run_seed = mcmc._run_seed()
    setup = mcmc._setup(model, x, observations, "MCMC.run", run_seed)
    fingerprint = mcmc._header(setup, run_seed).model_fingerprint
    records: dict[int, _ChainRecord] = {}
    for part in parts:
        if part.fingerprint != fingerprint or part.run_seed != run_seed:
            raise ValueError(
                "parallel chains: a worker rebuilt a different program, data, or "
                "seed than the parent; the run recipe is not reproducible"
            )
        for chain, state in part.states.items():
            if chain in records:
                raise ValueError(f"parallel chains: chain {chain} ran twice")
            records[chain] = _ChainRecord.from_state_dict(state, setup.site_names)
    if sorted(records) != list(range(mcmc.num_chains)):
        raise ValueError(
            f"parallel chains: chains {sorted(records)} ran, expected "
            f"0..{mcmc.num_chains - 1}"
        )
    return mcmc._result(setup, [records[chain] for chain in range(mcmc.num_chains)])

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: MCMC

model

The parent's program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

worker

Picklable recipe rebuilding the run in a worker.

TYPE: ChainWorker

cores

Maximum worker processes (brms cores).

TYPE: int

RETURNS DESCRIPTION
MCMCResult

The run's result.

RAISES DESCRIPTION
ValueError

If cores is not a positive integer, the driver has no seed or has a checkpoint, callback, or generator, or the worker cannot be pickled or refers to an object defined in the caller's main module.

RuntimeError

If a worker process fails; the remaining workers are stopped.

Source code in src/quivers/inference/mcmc/parallel.py
def parallel_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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)``.

    Parameters
    ----------
    mcmc : 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.
    model : MonadicProgram
        The parent's program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    worker : ChainWorker
        Picklable recipe rebuilding the run in a worker.
    cores : int
        Maximum worker processes (brms ``cores``).

    Returns
    -------
    MCMCResult
        The run's result.

    Raises
    ------
    ValueError
        If ``cores`` is not a positive integer, the driver has no seed or
        has a checkpoint, callback, or generator, or the worker cannot be
        pickled or refers to an object defined in the caller's main module.
    RuntimeError
        If a worker process fails; the remaining workers are stopped.
    """
    if isinstance(cores, bool) or not isinstance(cores, int) or cores < 1:
        raise ValueError("cores must be a positive integer")
    if mcmc.seed is None or mcmc.generator is not None:
        raise ValueError(
            "parallel chains need an explicit integer seed shared by every worker"
        )
    if mcmc.checkpoint is not None or mcmc.callback is not None:
        raise ValueError(
            "parallel chains cannot checkpoint or call back from worker "
            "processes; run with cores=1"
        )
    count = min(cores, mcmc.num_chains)
    assignments = [
        tuple(range(start, mcmc.num_chains, count)) for start in range(count)
    ]
    # Workers start in fresh interpreters that never import the caller's
    # script, so a script needs no ``if __name__ == "__main__":`` guard.
    parts = run_worker_processes(worker, assignments, torch.get_num_threads())
    return assemble_chains(mcmc, model, x, observations, parts)

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: MCMC

model

The program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

chains

Chain indices to run.

TYPE: Sequence[int]

guide

Guide for init_strategy="guide".

TYPE: Guide or None DEFAULT: None

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
def run_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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.

    Parameters
    ----------
    mcmc : MCMC
        The driver, with a seed and no checkpoint or callback.
    model : MonadicProgram
        The program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    chains : Sequence[int]
        Chain indices to run.
    guide : Guide or None
        Guide for ``init_strategy="guide"``.

    Returns
    -------
    ChainStates
        The chains' records and the model fingerprint.

    Raises
    ------
    ValueError
        If a chain index is out of range.
    """
    if any(not 0 <= chain < mcmc.num_chains for chain in chains):
        raise ValueError(
            f"run_chains: chain indices {list(chains)} are outside "
            f"0..{mcmc.num_chains - 1}"
        )
    run_seed = mcmc._run_seed()
    setup = mcmc._setup(model, x, observations, "MCMC.run", run_seed)
    header = mcmc._header(setup, run_seed)
    records: list[_ChainRecord | None] = [None] * mcmc.num_chains
    states: dict[int, dict[str, StateValue]] = {}
    for chain in chains:
        generator = mcmc._chain_generator(run_seed, chain)
        record = mcmc._start_chain(setup, chain, generator, guide)
        records[chain] = record
        mcmc._advance(setup, header, records, chain, record, generator)
        states[chain] = record.state_dict()
    return ChainStates(
        fingerprint=header.model_fingerprint, run_seed=run_seed, states=states
    )

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: str

run_seed

The run seed the worker derived its chain streams from.

TYPE: int

states

Each chain's record, as a checkpoint stores it, keyed by chain index.

TYPE: Mapping[int, dict[str, StateValue]] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

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: tuple[int, ...]

RETURNS DESCRIPTION
ChainStates

Their records.

Source code in src/quivers/inference/mcmc/parallel.py
def __call__(self, chains: tuple[int, ...]) -> ChainStates:
    """Run the assigned chains.

    Parameters
    ----------
    chains : tuple[int, ...]
        Chain indices.

    Returns
    -------
    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: MCMC

model

The program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

chains

Chain indices to run.

TYPE: Sequence[int]

guide

Guide for init_strategy="guide".

TYPE: Guide or None DEFAULT: None

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
def run_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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.

    Parameters
    ----------
    mcmc : MCMC
        The driver, with a seed and no checkpoint or callback.
    model : MonadicProgram
        The program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    chains : Sequence[int]
        Chain indices to run.
    guide : Guide or None
        Guide for ``init_strategy="guide"``.

    Returns
    -------
    ChainStates
        The chains' records and the model fingerprint.

    Raises
    ------
    ValueError
        If a chain index is out of range.
    """
    if any(not 0 <= chain < mcmc.num_chains for chain in chains):
        raise ValueError(
            f"run_chains: chain indices {list(chains)} are outside "
            f"0..{mcmc.num_chains - 1}"
        )
    run_seed = mcmc._run_seed()
    setup = mcmc._setup(model, x, observations, "MCMC.run", run_seed)
    header = mcmc._header(setup, run_seed)
    records: list[_ChainRecord | None] = [None] * mcmc.num_chains
    states: dict[int, dict[str, StateValue]] = {}
    for chain in chains:
        generator = mcmc._chain_generator(run_seed, chain)
        record = mcmc._start_chain(setup, chain, generator, guide)
        records[chain] = record
        mcmc._advance(setup, header, records, chain, record, generator)
        states[chain] = record.state_dict()
    return ChainStates(
        fingerprint=header.model_fingerprint, run_seed=run_seed, states=states
    )

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: MCMC

model

The parent's program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

parts

Every worker's records.

TYPE: Sequence[ChainStates]

RETURNS DESCRIPTION
MCMCResult

The result MCMC.run returns for the same seed.

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
def assemble_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    parts: Sequence[ChainStates],
) -> MCMCResult:
    """Assemble the result of a run from its chains' records.

    Parameters
    ----------
    mcmc : MCMC
        The parent's driver.
    model : MonadicProgram
        The parent's program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    parts : Sequence[ChainStates]
        Every worker's records.

    Returns
    -------
    MCMCResult
        The result `MCMC.run` returns for the same seed.

    Raises
    ------
    ValueError
        If a worker rebuilt a different program or data, used another run
        seed, or the parts do not cover every chain exactly once.
    """
    run_seed = mcmc._run_seed()
    setup = mcmc._setup(model, x, observations, "MCMC.run", run_seed)
    fingerprint = mcmc._header(setup, run_seed).model_fingerprint
    records: dict[int, _ChainRecord] = {}
    for part in parts:
        if part.fingerprint != fingerprint or part.run_seed != run_seed:
            raise ValueError(
                "parallel chains: a worker rebuilt a different program, data, or "
                "seed than the parent; the run recipe is not reproducible"
            )
        for chain, state in part.states.items():
            if chain in records:
                raise ValueError(f"parallel chains: chain {chain} ran twice")
            records[chain] = _ChainRecord.from_state_dict(state, setup.site_names)
    if sorted(records) != list(range(mcmc.num_chains)):
        raise ValueError(
            f"parallel chains: chains {sorted(records)} ran, expected "
            f"0..{mcmc.num_chains - 1}"
        )
    return mcmc._result(setup, [records[chain] for chain in range(mcmc.num_chains)])

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: MCMC

model

The parent's program.

TYPE: MonadicProgram

x

One-row input.

TYPE: Tensor

observations

Data.

TYPE: dict[str, Tensor]

worker

Picklable recipe rebuilding the run in a worker.

TYPE: ChainWorker

cores

Maximum worker processes (brms cores).

TYPE: int

RETURNS DESCRIPTION
MCMCResult

The run's result.

RAISES DESCRIPTION
ValueError

If cores is not a positive integer, the driver has no seed or has a checkpoint, callback, or generator, or the worker cannot be pickled or refers to an object defined in the caller's main module.

RuntimeError

If a worker process fails; the remaining workers are stopped.

Source code in src/quivers/inference/mcmc/parallel.py
def parallel_chains(
    mcmc: MCMC,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.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)``.

    Parameters
    ----------
    mcmc : 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.
    model : MonadicProgram
        The parent's program.
    x : torch.Tensor
        One-row input.
    observations : dict[str, torch.Tensor]
        Data.
    worker : ChainWorker
        Picklable recipe rebuilding the run in a worker.
    cores : int
        Maximum worker processes (brms ``cores``).

    Returns
    -------
    MCMCResult
        The run's result.

    Raises
    ------
    ValueError
        If ``cores`` is not a positive integer, the driver has no seed or
        has a checkpoint, callback, or generator, or the worker cannot be
        pickled or refers to an object defined in the caller's main module.
    RuntimeError
        If a worker process fails; the remaining workers are stopped.
    """
    if isinstance(cores, bool) or not isinstance(cores, int) or cores < 1:
        raise ValueError("cores must be a positive integer")
    if mcmc.seed is None or mcmc.generator is not None:
        raise ValueError(
            "parallel chains need an explicit integer seed shared by every worker"
        )
    if mcmc.checkpoint is not None or mcmc.callback is not None:
        raise ValueError(
            "parallel chains cannot checkpoint or call back from worker "
            "processes; run with cores=1"
        )
    count = min(cores, mcmc.num_chains)
    assignments = [
        tuple(range(start, mcmc.num_chains, count)) for start in range(count)
    ]
    # Workers start in fresh interpreters that never import the caller's
    # script, so a script needs no ``if __name__ == "__main__":`` guard.
    parts = run_worker_processes(worker, assignments, torch.get_num_threads())
    return assemble_chains(mcmc, model, x, observations, parts)

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

  1. chooses the next temperature by bisection, as the largest :math:\beta' \le 1 at which the conditional effective sample size of the incremental weights :math:L(z_i)^{\beta' - \beta} is at least target_ess times 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>);
  2. reweights by those increments, adding the log of their weighted mean to the log-evidence estimate;
  3. resamples by the chosen ResamplingScheme;
  4. rejuvenates every particle by num_mcmc_steps transitions 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

ResamplingScheme = Literal['multinomial', 'systematic', 'stratified', 'residual']

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": N independent draws from the weights;
  • "stratified": one uniform draw in each of N equal strata of the cumulative weights;
  • "systematic": one uniform offset shared by the N strata;
  • "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: MonadicProgram

registry

The latent registry.

TYPE: LatentRegistry

x

The one-row input.

TYPE: Tensor

observations

The data.

TYPE: dict[str, Tensor]

temperature

The inverse temperature :math:\beta \in [0, 1]. Default 1.0.

TYPE: float DEFAULT: 1.0

RAISES DESCRIPTION
ValueError

If temperature is outside [0, 1], or the input or data are refused as by PotentialFn, or an opaque joint override prevents role decomposition.

Source code in src/quivers/inference/smc.py
def __init__(
    self,
    model: MonadicProgram,
    registry: LatentRegistry,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
    temperature: float = 1.0,
) -> None:
    _require_partitionable_joint(model)
    super().__init__(model, registry, x, observations)
    self._temperature = _check_temperature(temperature)
    self._potential_scores = model.potential_sites

temperature property

temperature: float

The inverse temperature :math:\beta.

at_temperature

at_temperature(temperature: float) -> 'TemperedPotential'

The same potential at another temperature.

PARAMETER DESCRIPTION
temperature

The inverse temperature, in [0, 1].

TYPE: float

RETURNS DESCRIPTION
TemperedPotential

A copy sharing the model, data, conditioning, and evaluation counts.

RAISES DESCRIPTION
ValueError

If temperature is outside [0, 1].

Source code in src/quivers/inference/smc.py
def at_temperature(self, temperature: float) -> "TemperedPotential":
    """The same potential at another temperature.

    Parameters
    ----------
    temperature : float
        The inverse temperature, in ``[0, 1]``.

    Returns
    -------
    TemperedPotential
        A copy sharing the model, data, conditioning, and evaluation
        counts.

    Raises
    ------
    ValueError
        If ``temperature`` is outside ``[0, 1]``.
    """
    tempered = copy.copy(self)
    tempered._temperature = _check_temperature(temperature)
    return tempered

log_prior_and_likelihood

log_prior_and_likelihood(z: Tensor) -> tuple[Tensor, Tensor]

The two parts of the log joint at a position.

PARAMETER DESCRIPTION
z

Flat unconstrained position, shape (D,).

TYPE: Tensor

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

:math:\log p(z) (with the log-Jacobian) and :math:\log L(z), scalars; both -inf for a position outside the model's support, and the likelihood -inf where the data are impossible.

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
def log_prior_and_likelihood(
    self, z: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """The two parts of the log joint at a position.

    Parameters
    ----------
    z : torch.Tensor
        Flat unconstrained position, shape ``(D,)``.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        :math:`\\log p(z)` (with the log-Jacobian) and
        :math:`\\log L(z)`, scalars; both ``-inf`` for a position
        outside the model's support, and the likelihood ``-inf``
        where the data are impossible.

    Raises
    ------
    Exception
        Any error the program raises other than one marking the
        position as outside its support.
    """
    _require_partitionable_joint(self._model)
    refuse_subsampling("TemperedPotential")
    self._counts[0] += 1
    minus_inf = torch.tensor(float("-inf"), device=z.device, dtype=z.dtype)
    try:
        log_prior, log_likelihood = self._parts(z)
    except (ValueError, RuntimeError) as error:
        if not rejects_position(error):
            raise
        return minus_inf, minus_inf
    if not torch.isfinite(log_prior):
        return minus_inf, minus_inf
    if torch.isnan(log_likelihood):
        return log_prior, minus_inf
    return log_prior, log_likelihood

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 (num_particles, *constrained_shape).

TYPE: dict[str, Tensor]

log_evidence

The log of the evidence estimate :math:\prod_t \sum_i W_i^{(t)} L(z_i)^{\beta_t - \beta_{t-1}}, for the declared target's normalizing constant. It estimates data evidence when the prior and sampling law have that interpretation.

TYPE: float

temperatures

The ladder :math:\beta_0 = 0 < \dots < \beta_T = 1, shape (T + 1,).

TYPE: Tensor

ess

The effective sample size, as a fraction of the population, of the weights at each temperature before resampling, shape (T,).

TYPE: Tensor

acceptance

The mean acceptance of the rejuvenation moves at each temperature, shape (T,).

TYPE: Tensor

log_evidence_increments

The log mean incremental weight at each temperature, shape (T,); their sum is log_evidence.

TYPE: Tensor

log_likelihoods

:math:\log L at each final particle, shape (num_particles,).

TYPE: Tensor

num_evaluations

Potential evaluations over the run.

TYPE: int

num_particles property

num_particles: int

The population size.

num_temperatures property

num_temperatures: int

The number of tempering steps T.

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: MCMCKernel

num_particles

Population size. Default 1024.

TYPE: int DEFAULT: 1024

num_mcmc_steps

Rejuvenation transitions per particle per temperature. Default 5.

TYPE: int DEFAULT: 5

target_ess

The conditional effective sample size, as a fraction of the population, each temperature step is chosen to keep. Default 0.5.

TYPE: float DEFAULT: 0.5

resampling

The resampling scheme. Default "systematic".

TYPE: ResamplingScheme DEFAULT: 'systematic'

num_pilot_steps

Adaptation transitions of the discarded pilot run that tunes the kernel at each temperature; 0 uses the kernel as tuned to the population alone. Default 50.

TYPE: int DEFAULT: 50

seed

Seed of the run's generator. A run with the same seed is reproducible and leaves Torch's global RNG alone.

TYPE: int DEFAULT: None

generator

Caller-owned CPU generator from which each run draws its seed; mutually exclusive with seed.

TYPE: Generator DEFAULT: None

RAISES DESCRIPTION
ValueError

If a count is out of range, target_ess is outside (0, 1), resampling is unknown, or both seed and generator are given.

Source code in src/quivers/inference/smc.py
def __init__(
    self,
    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: torch.Generator | None = None,
) -> None:
    if num_particles < 2:
        raise ValueError(f"SMC: num_particles must be >= 2, got {num_particles}")
    if num_mcmc_steps < 1:
        raise ValueError(f"SMC: num_mcmc_steps must be >= 1, got {num_mcmc_steps}")
    if num_pilot_steps < 0:
        raise ValueError(
            f"SMC: num_pilot_steps must be >= 0, got {num_pilot_steps}"
        )
    if not 0.0 < target_ess < 1.0:
        raise ValueError(f"SMC: target_ess must be in (0, 1), got {target_ess}")
    if resampling not in ("multinomial", "systematic", "stratified", "residual"):
        raise ValueError(f"SMC: unknown resampling scheme {resampling!r}")
    if seed is not None and generator is not None:
        raise ValueError("SMC: seed and generator are mutually exclusive")
    self.kernel = kernel
    self.num_particles = num_particles
    self.num_mcmc_steps = num_mcmc_steps
    self.target_ess = target_ess
    self.resampling: ResamplingScheme = resampling
    self.num_pilot_steps = num_pilot_steps
    self.seed = seed
    self.generator = generator

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: MonadicProgram

x

A one-row input; as for MCMC.run, an input of several rows is several independent runs, and the sampler targets one.

TYPE: Tensor

observations

Observed-site values and host data.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
SMCResult

The final particles, the evidence estimate, and the ladder.

RAISES DESCRIPTION
ValueError

If x has more than one row, the data are outside their support, the kernel's Gibbs sites do not fit the model or are host data, which have no prior to draw particles from, a plate is subsampled, an explicit prior potential has unknown mass, or an opaque joint override prevents role decomposition.

RuntimeError

If no temperature step keeps the target ESS.

Source code in src/quivers/inference/smc.py
def run(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> SMCResult:
    """Run the sampler from the prior to the posterior.

    Parameters
    ----------
    model : MonadicProgram
        The model.
    x : torch.Tensor
        A one-row input; as for `MCMC.run`, an input of several rows
        is several independent runs, and the sampler targets one.
    observations : dict[str, torch.Tensor]
        Observed-site values and host data.

    Returns
    -------
    SMCResult
        The final particles, the evidence estimate, and the ladder.

    Raises
    ------
    ValueError
        If ``x`` has more than one row, the data are outside their
        support, the kernel's Gibbs sites do not fit the model or are
        host data, which have no prior to draw particles from, a plate
        is subsampled, an explicit prior potential has unknown mass,
        or an opaque joint override prevents role decomposition.
    RuntimeError
        If no temperature step keeps the target ESS.
    """
    host_sites = sorted(self.kernel.host_sites)
    if host_sites:
        raise ValueError(
            f"SMC.run: the kernel's Gibbs sites {host_sites} are host data; "
            "SMC draws every particle from the prior, and the program "
            "declares no prior for them"
        )
    _require_partitionable_joint(model)
    _require_one_run(x, "SMC.run")
    refuse_subsampling("SMC.run")
    from quivers.inference.prior import _ancestral_program

    prior_program = _ancestral_program(model)
    _check_observed_support(model, observations, "SMC.run")
    base = self._run_seed()
    # The run that fixes the latents draws from a stream of its own
    # derived from the run's seed, so a seeded run records the same
    # latents whatever Torch's global RNG holds, and leaves it as it was.
    recording = MCMC._chain_generator(base, -1)
    with torch.random.fork_rng(devices=[]):
        torch.random.set_rng_state(recording.get_state())
        recorded = trace(model, x, observations=observations)
    gibbs_sites = self.kernel.gibbs_sites
    gibbs_morphisms = _check_gibbs_sites(recorded, gibbs_sites)
    registry = LatentRegistry.from_trace(model, recorded, exclude=gibbs_sites)
    potential = TemperedPotential(model, registry, x, observations, 0.0)
    generator = MCMC._chain_generator(base, 0)
    self.kernel._set_generator(generator)

    positions, gibbs = self._prior_particles(
        prior_program, x, observations, registry, gibbs_sites, generator
    )
    log_likelihoods = self._log_likelihoods(potential, positions, gibbs)
    n = self.num_particles
    log_weights = torch.full((n,), -math.log(n), dtype=torch.float64)
    temperature = 0.0
    temperatures = [0.0]
    ess: list[float] = []
    acceptance: list[float] = []
    increments_log: list[float] = []
    while temperature < 1.0:
        following = self._next_temperature(
            temperature, log_weights, log_likelihoods
        )
        increments = _increments(log_likelihoods, following - temperature)
        increment = self._log_evidence_increment(log_weights, increments)
        increments_log.append(float(increment))
        log_weights = log_weights + increments
        log_weights = log_weights - torch.logsumexp(log_weights, 0)
        ess.append(float(torch.exp(-torch.logsumexp(2.0 * log_weights, 0))) / n)
        ancestors = resample(torch.exp(log_weights), self.resampling, generator)
        positions = positions[ancestors]
        gibbs = [gibbs[int(i)] for i in ancestors]
        log_weights = torch.full((n,), -math.log(n), dtype=torch.float64)
        temperature = following
        temperatures.append(temperature)
        tempered = potential.at_temperature(temperature)
        positions, gibbs, accepted = self._rejuvenate(
            model, x, observations, registry, tempered, positions, gibbs, generator
        )
        acceptance.append(accepted)
        log_likelihoods = self._log_likelihoods(potential, positions, gibbs)

    samples = self._samples(registry, positions, gibbs, gibbs_morphisms)
    return SMCResult(
        samples=samples,
        log_evidence=float(sum(increments_log)),
        temperatures=torch.tensor(temperatures, dtype=torch.float64),
        ess=torch.tensor(ess, dtype=torch.float64),
        acceptance=torch.tensor(acceptance, dtype=torch.float64),
        log_evidence_increments=torch.tensor(increments_log, dtype=torch.float64),
        log_likelihoods=log_likelihoods,
        num_evaluations=potential.num_evaluations,
    )

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 (N,), not all zero; they need not be normalized.

TYPE: Tensor

scheme

The resampling scheme.

TYPE: ResamplingScheme

generator

The generator every uniform draw comes from.

TYPE: Generator DEFAULT: None

RETURNS DESCRIPTION
Tensor

N ancestor indices, int64, in increasing order for the stratified, systematic, and residual schemes.

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
def resample(
    weights: torch.Tensor,
    scheme: ResamplingScheme,
    generator: torch.Generator | None = None,
) -> torch.Tensor:
    """Draw ancestor indices for a weighted population.

    Parameters
    ----------
    weights : torch.Tensor
        Non-negative weights, shape ``(N,)``, not all zero; they need not
        be normalized.
    scheme : ResamplingScheme
        The resampling scheme.
    generator : torch.Generator, optional
        The generator every uniform draw comes from.

    Returns
    -------
    torch.Tensor
        ``N`` ancestor indices, ``int64``, in increasing order for the
        stratified, systematic, and residual schemes.

    Raises
    ------
    ValueError
        If the weights are not a non-negative vector with a positive
        finite sum, or the scheme is unknown.
    """
    if weights.dim() != 1 or weights.numel() == 0:
        raise ValueError(
            f"resample: weights must be a non-empty vector, got {tuple(weights.shape)}"
        )
    w = weights.to(torch.float64)
    total = float(w.sum())
    if bool((w < 0).any()) or not math.isfinite(total) or total <= 0.0:
        raise ValueError("resample: weights must be non-negative with a positive sum")
    w = w / total
    n = w.numel()
    if scheme == "multinomial":
        return torch.multinomial(w, n, replacement=True, generator=generator)
    if scheme == "residual":
        copies = torch.floor(n * w).to(torch.int64)
        remaining = n - int(copies.sum())
        base = torch.repeat_interleave(torch.arange(n), copies)
        if remaining == 0:
            return base
        residual = n * w - copies.to(torch.float64)
        extra = torch.multinomial(
            residual / residual.sum(), remaining, replacement=True, generator=generator
        )
        return torch.sort(torch.cat([base, extra])).values
    if scheme == "stratified":
        offsets = torch.rand(n, generator=generator, dtype=torch.float64)
    elif scheme == "systematic":
        offsets = torch.rand((), generator=generator, dtype=torch.float64).expand(n)
    else:
        raise ValueError(f"resample: unknown scheme {scheme!r}")
    points = (torch.arange(n, dtype=torch.float64) + offsets) / n
    cumulative = torch.cumsum(w, 0)
    return torch.searchsorted(cumulative, points, right=True).clamp_max(n - 1)

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

\[ w_t=\frac{\psi_t C_t}{q_t C_{t-1}}. \]

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

\[ \mathbb E[U_T(f)] = \sum_a f(a) \prod_t \psi_t(a_{1:t}) \]

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: Tensor

target_log_scores

The cumulative original log potentials along each returned history, with gradients through the chosen target states.

TYPE: Tensor

log_probabilities

Detached normalized terminal importance weights in log space.

TYPE: Tensor

log_normalizer

The detached log of the product of mean incremental weights.

TYPE: Tensor

candidate_count

The number of candidate slots evaluated across the stages.

TYPE: int

score_surrogate

score_surrogate(event: Tensor | None = None) -> Tensor

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: Tensor or None DEFAULT: None

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
def score_surrogate(self, event: torch.Tensor | None = None) -> torch.Tensor:
    """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.

    Parameters
    ----------
    event : torch.Tensor or None
        One Boolean indicator per returned history. The event is
        a fixed function of the path. None includes every history.

    Returns
    -------
    torch.Tensor
        A scalar surrogate whose derivative is the estimate. Its
        value is a weighted sum of log scores.

    Raises
    ------
    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.
    """
    if event is not None and (
        not isinstance(event, torch.Tensor)
        or event.shape != self.log_probabilities.shape
        or event.dtype != torch.bool
        or event.device != self.log_probabilities.device
    ):
        raise ValueError(
            "the event requires one Boolean per particle on its device"
        )
    log_weights = (self.log_normalizer + self.log_probabilities).detach()
    if event is not None:
        log_weights = log_weights.masked_fill(~event, -torch.inf)
    weights = log_weights.exp()
    active_weights = weights if event is None else weights[event]
    if not bool(((active_weights > 0) & torch.isfinite(active_weights)).all()):
        raise OverflowError(
            "unnormalized particle weights exceed the evaluation range"
        )
    value = torch.dot(weights, self.target_log_scores)
    if not bool(torch.isfinite(value)):
        raise OverflowError(
            "the particle score surrogate exceeds the evaluation range"
        )
    return value

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: Tensor

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: Callable

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: Callable

steps

Positive length shared by every admitted history.

TYPE: int

particles

Positive fixed population size.

TYPE: int

actions

Positive number of candidate action positions per step.

TYPE: int

max_candidates

Limit on the total number of evaluated candidate slots, including structurally forbidden ones.

TYPE: int

max_state_elements

Limit on the number of scalar entries in one candidate-state batch. Callback-internal work and buffers are caller-owned.

TYPE: int

generator

The generator for proposal draws and multinomial ancestry.

TYPE: Generator or None DEFAULT: None

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
def sequence_particle_filter(
    initial_state: torch.Tensor,
    advance: Callable[[int, torch.Tensor], tuple[torch.Tensor, torch.Tensor]],
    propose: Callable[
        [int, torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor]
    ],
    *,
    steps: int,
    particles: int,
    actions: int,
    max_candidates: int,
    max_state_elements: int,
    generator: torch.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.

    Parameters
    ----------
    initial_state : torch.Tensor
        One dense, finite float64 state vector, copied across slots by
        broadcasting. The callbacks treat state arguments as read-only.
    advance : Callable
        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.
    propose : Callable
        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.
    steps : int
        Positive length shared by every admitted history.
    particles : int
        Positive fixed population size.
    actions : int
        Positive number of candidate action positions per step.
    max_candidates : int
        Limit on the total number of evaluated candidate slots,
        including structurally forbidden ones.
    max_state_elements : int
        Limit on the number of scalar entries in one candidate-state
        batch. Callback-internal work and buffers are caller-owned.
    generator : torch.Generator or None
        The generator for proposal draws and multinomial ancestry.

    Returns
    -------
    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
    ------
    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.
    """
    if any(type(size) is not int or size < 1 for size in (steps, particles, actions)):
        raise ValueError("steps, particles, and actions must be positive integers")
    if any(
        type(limit) is not int or limit < 0
        for limit in (max_candidates, max_state_elements)
    ):
        raise ValueError("particle work limits must be nonnegative integers")
    if (
        not isinstance(initial_state, torch.Tensor)
        or initial_state.ndim != 1
        or initial_state.numel() == 0
        or initial_state.dtype != torch.float64
        or initial_state.layout != torch.strided
        or not bool(torch.isfinite(initial_state).all())
    ):
        raise ValueError("the initial state must be a finite dense float64 vector")

    width = initial_state.numel()
    slots = particles * actions
    candidate_count = steps * slots
    state_elements = slots * width
    if max(candidate_count, state_elements) > torch.iinfo(torch.int64).max:
        raise ValueError("sequence particle dimensions exceed the Int range")
    if candidate_count > max_candidates:
        raise ValueError("sequence particle filtering exceeds max_candidates")
    if state_elements > max_state_elements:
        raise ValueError("sequence particle filtering exceeds max_state_elements")

    positions = torch.arange(particles, device=initial_state.device)
    states = initial_state.expand(particles, width)
    path_scores = initial_state.new_zeros(particles)
    previous_twist = initial_state.new_zeros(particles)
    log_normalizer = initial_state.new_zeros(())
    log_probabilities = initial_state.new_full((particles,), -log(particles))
    choices: list[torch.Tensor] = []
    ancestry: list[torch.Tensor] = []
    row_shape = (particles, actions)
    for step in range(steps):
        candidates, log_target = advance(step, states)
        _check_tensor(
            "candidate states", candidates, (*row_shape, width), initial_state
        )
        _check_tensor("target log potentials", log_target, row_shape, initial_state)
        if not bool(torch.isfinite(candidates).all()):
            raise ValueError("candidate states must be finite")

        final_step = step == steps - 1
        with torch.no_grad():
            eligible = torch.isfinite(log_target)
            if not bool((eligible | torch.isneginf(log_target)).all()):
                raise ValueError("target log potentials must be finite or -inf")
            if not bool(eligible.any(dim=1).all()):
                raise ValueError("an active path has no eligible action")
            logits, twist = propose(step, candidates.detach(), log_target.detach())
            _check_tensor("proposal logits", logits, row_shape, initial_state)
            _check_tensor("log twists", twist, row_shape, initial_state)
            if not torch.equal(torch.isfinite(logits), eligible) or not bool(
                torch.isneginf(logits[~eligible]).all()
            ):
                raise ValueError("proposal support must equal target support")
            log_twists = twist[eligible]
            if not bool(torch.isfinite(log_twists).all()):
                raise ValueError("eligible log twists must be finite")
            if final_step and bool((log_twists != 0).any()):
                raise ValueError("terminal log twists must be zero")

            log_q = torch.log_softmax(logits, dim=1)
            probabilities = log_q.exp()
            if not bool((probabilities[eligible] > 0).all()):
                raise OverflowError("the proposal underflowed on its positive support")
            delta = log_target + twist - previous_twist[:, None] - log_q
            if not bool(
                torch.isfinite(delta[eligible]).all()
                & torch.isfinite((path_scores[:, None] + log_target)[eligible]).all()
            ):
                raise OverflowError(
                    "an eligible particle extension exceeds the evaluation range"
                )

            selected = torch.multinomial(probabilities, 1, generator=generator)[:, 0]
            incremental = delta[positions, selected]
            log_mean_weight = torch.logsumexp(incremental, dim=0) - log(particles)
            log_normalizer = log_normalizer + log_mean_weight
            log_probabilities = torch.log_softmax(incremental, dim=0)
            weights = log_probabilities.exp()
            if not bool(torch.isfinite(log_normalizer) & (weights > 0).all()):
                raise OverflowError(
                    "a particle normalizer or weight exceeds the evaluation range"
                )
            choices.append(selected)
            parent = None if final_step else resample(weights, "multinomial", generator)
            if parent is not None:
                ancestry.append(parent)
                previous_twist = twist[positions, selected].index_select(0, parent)

        path_scores = path_scores + log_target[positions, selected]
        if parent is not None:
            states = candidates[positions, selected].index_select(0, parent)
            path_scores = path_scores.index_select(0, parent)

    histories = [choices[-1]]
    for selected, parent in zip(
        reversed(choices[:-1]), reversed(ancestry), strict=True
    ):
        positions = parent.index_select(0, positions)
        histories.append(selected.index_select(0, positions))
    return SequenceParticleResult(
        torch.stack(histories[::-1], dim=1),
        path_scores,
        log_probabilities,
        log_normalizer,
        candidate_count,
    )

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 Guide subclass; AutoMultivariateNormalGuide is the canonical pick because its learned Cholesky factor directly seeds the dense mass matrix of HMC's adaptation.

TYPE: Guide

kernel

Markov kernel for the sampling phase (typically HMCKernel or NUTSKernel).

TYPE: MCMCKernel

svi_steps

Number of SVI steps in the warmup phase.

TYPE: int

svi_lr

Learning rate for the SVI optimizer. Default 1e-2.

TYPE: float DEFAULT: 0.01

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: int

mcmc_samples

Number of post-warmup MCMC samples per chain.

TYPE: int

num_chains

Number of MCMC chains.

TYPE: int DEFAULT: 2

objective

SVI objective. Default ELBO.

TYPE: Objective DEFAULT: None

Source code in src/quivers/inference/warmup.py
def __init__(
    self,
    guide: Guide,
    kernel: MCMCKernel,
    svi_steps: int,
    mcmc_warmup: int,
    mcmc_samples: int,
    num_chains: int = 2,
    svi_lr: float = 1e-2,
    objective: Objective | None = None,
) -> None:
    if svi_steps < 1:
        raise ValueError(f"WarmupThenHMC: svi_steps must be >= 1, got {svi_steps}")
    if mcmc_warmup < 0:
        raise ValueError(
            f"WarmupThenHMC: mcmc_warmup must be >= 0, got {mcmc_warmup}"
        )
    if mcmc_samples < 1:
        raise ValueError(
            f"WarmupThenHMC: mcmc_samples must be >= 1, got {mcmc_samples}"
        )
    self.guide = guide
    self.kernel = kernel
    self.svi_steps = svi_steps
    self.svi_lr = svi_lr
    self.mcmc_warmup = mcmc_warmup
    self.mcmc_samples = mcmc_samples
    self.num_chains = num_chains
    self.objective = objective if objective is not None else ELBO()

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
def fit_guide(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> list[float]:
    """Run the SVI warmup phase and return the per-step losses."""
    optim = torch.optim.Adam(
        list(model.parameters()) + list(self.guide.parameters()),
        lr=self.svi_lr,
    )
    svi = SVI(model, self.guide, optim, self.objective)
    losses: list[float] = []
    for _ in range(self.svi_steps):
        losses.append(svi.step(x, observations))
    return losses

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
def run_mcmc(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> MCMCResult:
    """Run the post-warmup MCMC phase. Chains are seeded from
    the fitted guide via `MCMC.run`'s ``init_strategy='guide'``."""
    driver = MCMC(
        kernel=self.kernel,
        num_warmup=self.mcmc_warmup,
        num_samples=self.mcmc_samples,
        num_chains=self.num_chains,
        init_strategy="guide",
    )
    return driver.run(model, x, observations, guide=self.guide)

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
def run(
    self,
    model: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, torch.Tensor],
) -> tuple[list[float], MCMCResult]:
    """Convenience: SVI warmup, then MCMC sampling.

    Returns ``(svi_losses, mcmc_result)``.
    """
    losses = self.fit_guide(model, x, observations)
    result = self.run_mcmc(model, x, observations)
    return losses, result

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.