Skip to content

Trace

An execution trace records the random choices of one run of a program, with the value and log density of each site (Wingate et al., 2011). The sum of those log densities is the run's log joint density, which inference uses to weight, optimize, or accept proposed latent values. trace(program, x, observations) stacks a TraceHandler and runs the program.

trace

Execution trace for monadic programs.

A Trace records every sample site visited during program execution, capturing the morphism, sampled or observed value, and log-density at each site. This is the foundation for all inference algorithms: SVI uses traces to compute the ELBO, and conditioning operates by clamping trace sites to observed data.

The trace(program, x, observations) free function is a thin wrapper on top of the effect-handler machinery: it pushes a quivers.effects.trace_handler.TraceHandler onto the active handler stack, runs the program forward once by its own rsample (a compiled program on its kernel encoding, a checked program on its checked computation), and returns the accumulated Trace. Any other handlers active in the enclosing scope compose with TraceHandler in the standard outer-to-inner order.

The SampleSite and Trace data types are defined in quivers.effects.trace_types and re-exported here.

SampleSite didactic-model

SampleSite(*, name: str, morphism: ContinuousMorphism | None = field(opaque=True, extras=OPAQUE_BY_IDENTITY), value: object = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_prob: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), is_observed: bool = False, is_deterministic: bool = False, sampleable: TorchSampleable | FiniteSampleable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), address: SiteAddress | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), metadata: dict[str, HeldValue] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), units: tuple[SiteUnits, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Record of a single site in a program trace.

Values and morphisms retain their runtime identity. Field updates use with_ and preserve their autograd connections.

PARAMETER DESCRIPTION
name

Variable name bound at this site.

TYPE: str

morphism

The distribution morphism (None for let bindings and scores).

TYPE: ContinuousMorphism or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

value

The sampled, observed, or computed tensor. A site drawn from a finite structured law keeps its one typed point as a value.

TYPE: object DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

log_prob

The density the site contributed to the run's score, after every score transformer on the stack. Zero for let bindings and for intervened sites.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

is_observed

Whether this site was conditioned on an observed value.

TYPE: bool DEFAULT: False

is_deterministic

Whether this is a let binding, a score step, or an intervened site.

TYPE: bool DEFAULT: False

sampleable

The sampleable the site's request carried. A tensor law records its morphism and input. A structured law records its typed support. Let bindings and scores have no sampleable.

TYPE: TorchSampleable or FiniteSampleable or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

address

The kernel's dynamic address of the site's request, which is one identity for the run's trace and for every handler that answered it.

TYPE: SiteAddress or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

metadata

Annotations handlers attached to the site.

TYPE: dict[str, HeldValue] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

units

For a score step that declares a factorization, its units in each of the runs the trace holds; empty for any other site.

TYPE: tuple[SiteUnits, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

is_structured property

is_structured: bool

Whether the site's value is a single point of a structured law.

RETURNS DESCRIPTION
bool

True when the sampleable is a finite typed law.

Trace didactic-model

Trace(*, sites: dict[str, SampleSite] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), output: Tensor | dict[str, Tensor] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), log_joint: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

Complete execution trace of a monadic program.

The sites mapping grows as the program executes. Finalizing a trace uses with_ to attach its output and joint density.

PARAMETER DESCRIPTION
sites

All sites keyed by variable name.

TYPE: dict[str, SampleSite] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

output

The program's return value.

TYPE: Tensor or dict[str, Tensor] DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

log_joint

Sum of log-densities across all sites. Shape (batch,).

TYPE: Tensor DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

stochastic_sites property

stochastic_sites: dict[str, SampleSite]

The sites that are not deterministic.

RETURNS DESCRIPTION
dict[str, SampleSite]

Every sampled or observed site.

latent_sites property

latent_sites: dict[str, SampleSite]

The sites that are neither observed nor deterministic.

RETURNS DESCRIPTION
dict[str, SampleSite]

Every sampled latent site.

observed_sites property

observed_sites: dict[str, SampleSite]

The observed sites.

RETURNS DESCRIPTION
dict[str, SampleSite]

Every site conditioned on an observation.

trace

trace(program: MonadicProgram, x: Tensor, observations: dict[str, object] | None = None) -> Trace

Execute a program and record all sample sites.

A thin wrapper around the handler-aware interpreter: pushes a quivers.effects.trace_handler.TraceHandler onto the active handler stack, runs the program forward once by its own rsample, and returns the accumulated Trace (with output and log_joint filled in). Any other handlers already on the stack compose with trace in the standard outer-to-inner order.

PARAMETER DESCRIPTION
program

The program to trace.

TYPE: MonadicProgram

x

Program input, shape (B, ...): B independent runs of the program.

TYPE: Tensor

observations

Data and clamped values by name. Tensor values may have a leading run axis of length B, or be shared across runs. Checked programs can accept typed host data, including a finite structured law as an argument and one of its points as a site value.

TYPE: dict[str, object] or None DEFAULT: None

RETURNS DESCRIPTION
Trace

Complete execution trace with densities and joint on the run axis. A tensor site lays its value out on that axis. A finite structured site holds its typed value directly and requires one run.

Source code in src/quivers/inference/trace.py
def trace(
    program: MonadicProgram,
    x: torch.Tensor,
    observations: dict[str, object] | None = None,
) -> Trace:
    """Execute a program and record all sample sites.

    A thin wrapper around the handler-aware interpreter: pushes a
    `quivers.effects.trace_handler.TraceHandler` onto the active
    handler stack, runs the program forward once by its own
    ``rsample``, and returns the
    accumulated `Trace` (with ``output`` and ``log_joint`` filled
    in). Any other handlers already on the stack compose with
    trace in the standard outer-to-inner order.

    Parameters
    ----------
    program : MonadicProgram
        The program to trace.
    x : torch.Tensor
        Program input, shape ``(B, ...)``: ``B`` independent runs of
        the program.
    observations : dict[str, object] or None
        Data and clamped values by name. Tensor values may have a leading
        run axis of length ``B``, or be shared across runs. Checked programs
        can accept typed host data, including a finite structured law as
        an argument and one of its points as a site value.

    Returns
    -------
    Trace
        Complete execution trace with densities and joint on the run
        axis. A tensor site lays its value out on that axis. A finite
        structured site holds its typed value directly and requires one run.
    """
    with TraceHandler() as handler:
        output = program.rsample(
            x, torch.Size(), cast(dict[str, torch.Tensor] | None, observations)
        )
    handler.trace = handler.trace.with_(
        output=output, log_joint=handler.total_log_joint(x.device)
    )
    return handler.trace

Exports of the package

quivers.inference also re-exports the variational guides of quivers.inference.guides and the kernels and runner of quivers.inference.mcmc, so that from quivers.inference import AutoNormalGuide, NUTSKernel works. Each class is documented in full under Guides or MCMC.

AutoNormal module-attribute

AutoNormal = AutoNormalGuide

AutoMultivariateNormal module-attribute

AutoMultivariateNormal = AutoMultivariateNormalGuide

AutoLowRankMVN module-attribute

AutoDelta module-attribute

AutoDelta = AutoDeltaGuide

AutoLaplace module-attribute

AutoIAFNormal module-attribute

AutoIAFNormal = AutoIAFGuide

Guide

GuideDraw didactic-model

GuideDraw(*, sites: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_weight: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

AutoNormalGuide

AutoNormalGuide(model: MonadicProgram, observed_names: set[str], init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None, initial_values: Mapping[str, Tensor | float] | None = None)

AutoMultivariateNormalGuide

AutoMultivariateNormalGuide(model: MonadicProgram, observed_names: set[str], init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoLowRankMultivariateNormalGuide

AutoLowRankMultivariateNormalGuide(model: MonadicProgram, observed_names: set[str], rank: int = 5, init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoDeltaGuide

AutoDeltaGuide(model: MonadicProgram, observed_names: set[str], init_value: float = 0.0, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoLaplaceApproximation

AutoLaplaceApproximation(model: MonadicProgram, observed_names: set[str], init_value: float = 0.0, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoNormalizingFlow

AutoNormalizingFlow(model: MonadicProgram, observed_names: set[str], transforms: list[TransformModule], *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoIAFGuide

AutoIAFGuide(model: MonadicProgram, observed_names: set[str], num_flows: int = 4, hidden_dim: int | None = None, num_hidden_layers: int = 2, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoNeuralSplineGuide

AutoNeuralSplineGuide(model: MonadicProgram, observed_names: set[str], num_flows: int = 4, num_bins: int = 8, tail_bound: float = 3.0, hidden_dim: int | None = None, num_hidden_layers: int = 2, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

AutoMixtureGuide

AutoMixtureGuide(components: list[Guide])

AutoGuideList

AutoGuideList(parts: dict[str, Guide])

AutoStructured

AutoStructured(model: MonadicProgram, observed_names: set[str], conditionals: ConditionalSpec, dependencies: DependencySpec | None = None, init_scale: float = 0.1, *, x: Tensor | None = None, observations: dict[str, Tensor] | None = None)

MCMCKernel

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)

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)

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)

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))

Cited sources

David Wingate, Andreas Stuhlmueller, and Noah Goodman. Lightweight Implementations of Probabilistic Programming Languages Via Transformational Compilation. In Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics, volume 15 of Proceedings of Machine Learning Research, 770–778. PMLR, 2011. URL: https://proceedings.mlr.press/v15/wingate11a.html.