Skip to content

Prior sampling

prior_draws generates independent joint draws from a program's retained conditional priors. It uses the same named draw laws and data dependencies as fitting, including normalized measure-valued draw boundaries. Its dependency projection omits downstream responses without evaluating their likelihoods.

import torch
from quivers.dsl import loads
from quivers.inference import prior_draws

program = loads("""object R : Real 1
program model : R -> R
    sample scale <- LogNormal(loc=0.0, scale=0.3)
    sample b <- Normal(loc=0.0, scale=scale)
    observe y <- Normal(loc=b, scale=1.0)
    return b
export model
""").morphism
draws = prior_draws(program, torch.zeros(1, 1), num_samples=8, seed=12)
assert draws.samples["b"].shape == (1, 8)

The singleton leading axis of PriorDraws preserves the common output layout; it is not a Markov chain. Prior views reuse predictive, likelihood, and summary methods and do not report MCMC convergence statistics for independent samples.

An authored score is a global potential. Independent forward sampling cannot normalize an arbitrary potential, so the ancestral method refuses it. Pass a configured MCMC driver to prior_draws(..., method=driver) to perform factor-conditioned prior-only inference; the returned MCMCResult then has genuine chain provenance and the driver's own budgets.

prior

Independent ancestral prior draws and explicit factor-conditioned alternatives.

PriorMode

PriorMode = Literal['no', 'yes', 'only']

Fit observations, additionally retain independent priors, or fit priors only.

PriorDraws didactic-model

PriorDraws(*, samples: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), num_samples: int)

Bases: ValueModel

Independent ancestral samples, without MCMC convergence statistics.

PARAMETER DESCRIPTION
samples

Constrained latent samples with axes (1, draw, *event_shape). The leading singleton is an output-layout axis, not a Markov chain.

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

num_samples

Number of independently generated joint prior draws.

TYPE: int

num_chains property

num_chains: int

Return the singleton layout axis, which has no chain diagnostics.

RETURNS DESCRIPTION
int

One independent-draw layout axis, not a Markov chain.

prior_draws

prior_draws(model: MonadicProgram, input: Tensor, observations: Mapping[str, Tensor] | None = None, *, num_samples: int = 100, seed: int = 0, method: Literal['ancestral'] | MCMC = 'ancestral') -> PriorDraws | MCMCResult

Sample the retained prior without evaluating observation likelihoods.

Ancestral sampling draws every proper conditional prior once per joint draw. Arbitrary explicit score potentials require the explicitly selected MCMC alternative because their normalized law is not an ancestral kernel. Existing measure-valued draw boundaries retain their normalizing semantics.

PARAMETER DESCRIPTION
model

Compiled model with its original priors and support constraints.

TYPE: MonadicProgram

input

One execution's input.

TYPE: Tensor

observations

Covariates and retained observations needed by data-dependent priors.

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

num_samples

Positive number of independent draws under the ancestral method.

TYPE: int DEFAULT: 100

seed

Isolated CPU random stream; the caller's state is restored.

TYPE: int DEFAULT: 0

method

Independent forward sampling, or a configured Markov-chain driver for priors containing explicit potentials. The latter retains its budgets.

TYPE: 'ancestral' DEFAULT: "ancestral"

RETURNS DESCRIPTION
PriorDraws or MCMCResult

Samples with honest provenance and constrained event coordinates.

RAISES DESCRIPTION
ValueError

If the independent budget is invalid or an active potential precludes independent ancestral sampling.

TypeError

If an unsupported sampling method is requested.

Source code in src/quivers/inference/prior.py
def prior_draws(
    model: MonadicProgram,
    input: torch.Tensor,
    observations: Mapping[str, torch.Tensor] | None = None,
    *,
    num_samples: int = 100,
    seed: int = 0,
    method: Literal["ancestral"] | MCMC = "ancestral",
) -> PriorDraws | MCMCResult:
    """Sample the retained prior without evaluating observation likelihoods.

    Ancestral sampling draws every proper conditional prior once per joint
    draw. Arbitrary explicit score potentials require the explicitly selected
    MCMC alternative because their normalized law is not an ancestral kernel.
    Existing measure-valued draw boundaries retain their normalizing semantics.

    Parameters
    ----------
    model : MonadicProgram
        Compiled model with its original priors and support constraints.
    input : torch.Tensor
        One execution's input.
    observations : Mapping[str, torch.Tensor] or None
        Covariates and retained observations needed by data-dependent priors.
    num_samples : int
        Positive number of independent draws under the ancestral method.
    seed : int
        Isolated CPU random stream; the caller's state is restored.
    method : {"ancestral"} or MCMC
        Independent forward sampling, or a configured Markov-chain driver for
        priors containing explicit potentials. The latter retains its budgets.

    Returns
    -------
    PriorDraws or MCMCResult
        Samples with honest provenance and constrained event coordinates.

    Raises
    ------
    ValueError
        If the independent budget is invalid or an active potential precludes
        independent ancestral sampling.
    TypeError
        If an unsupported sampling method is requested.
    """
    from quivers.inference._posterior import collect_site_draws, sample_count
    from quivers.inference._prior_projection import project_prior_sites
    from quivers.inference._response import response_rng
    from quivers.inference.mcmc.driver import MCMC
    from quivers.inference.registry import _require_one_run, _trace_latent_values
    from quivers.inference.trace import trace

    if method != "ancestral" and not isinstance(method, MCMC):
        raise TypeError("prior method must be 'ancestral' or a configured MCMC driver")
    _require_one_run(input, "prior_draws")
    data = dict(observations or {})
    with observation_scoring(False):
        if isinstance(method, MCMC):
            return method.run(project_prior_sites(model), input, data)
        count = sample_count(num_samples)
        projected = _ancestral_program(model)
        with (
            response_rng(
                seed,
                chain(
                    (input,), data.values(), projected.parameters(), projected.buffers()
                ),
            ),
            torch.no_grad(),
        ):

            def values():
                """Yield one independent constrained joint draw.

                Yields
                ------
                dict[str, torch.Tensor]
                    Named latent values without the program run axis.
                """
                for _ in range(count):
                    recorded = trace(projected, input, data)
                    yield _trace_latent_values(recorded)

            samples = collect_site_draws(values(), (1, count))
    return PriorDraws(samples=samples, num_samples=count)