Skip to content

Traces

TraceHandler records each sample site a run reaches, with its value and log density, for inspection or later replay. A trace describes one run, so a different input or handler stack can change its values.

trace_handler

Trace handler: records every site the program visits.

TraceHandler installs an observing handler of the program's random instance and of its let and score steps at its position on the stack, so it records each site's value as the handlers outside it answered it and sees no site a handler inside it hid. A site's density is read after the run from the contributions that reached the run's accumulator under the site's provenance, after every score transformer on the stack. The thin quivers.inference.trace.trace wrapper stacks this handler on and returns its accumulated Trace.

TraceHandler

TraceHandler()

Bases: EffectHandler

Record every site visited during a program's execution.

Produces a Trace whose sites dict is keyed by variable name, whose output is the program's return value, and whose log_joint is the sum of every site's log_prob. A call on an input of B rows makes B independent runs: the trace records each run's sites and lays them out along a leading run axis, so a site's log_prob holds one density per run, shape (B,), and its value holds one value per run (a plated site's rows after the run axis). A TraceHandler is single-use: run the program under one instance, read trace, then discard. The handler takes no configuration.

Source code in src/quivers/effects/trace_handler.py
def __init__(self) -> None:
    self.trace: Trace = Trace()
    self._recorder = TraceRecorder()
    self._steps: dict[object, HostStep] = {}
    self._occurrences: dict[object, int] = {}
    self._run_sites: list[dict[str, SampleSite]] = []
    self._run_axes: dict[str, bool] = {}
    self._vectorized_runs = 0

install

install(run: RunContext) -> tuple[Installation, ...]

Install observers of the sites and of the let and score steps.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

One forwarding observer of the random instance and one of each let and score step's Compute instance.

Source code in src/quivers/effects/trace_handler.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install observers of the sites and of the let and score steps.

    Parameters
    ----------
    run : RunContext
        The run being prepared.

    Returns
    -------
    tuple[Installation, ...]
        One forwarding observer of the ``random`` instance and one of
        each let and score step's ``Compute`` instance.
    """
    kernel = run.kernel
    self._recorder = TraceRecorder()
    self._occurrences = {}
    installations = [
        Installation(
            instance=kernel.random,
            runtime=trace_handler(
                RANDOM,
                (RANDOM_SAMPLE,),
                self._recorder,
                validators={RANDOM_SAMPLE: run.validator},
                answer_type=run.result_type,
                key=f"trace-random-{id(self):x}",
            ),
        )
    ]
    for step in kernel.steps:
        if step.kind not in ("let", "score"):
            continue
        instance = next(
            item
            for item in kernel.module.instances
            if item.entry.instance == step.instance
        )
        self._steps[step.instance] = step
        installations.append(
            Installation(
                instance=instance,
                runtime=trace_handler(
                    step.effect,
                    (COMPUTE_APPLY,),
                    self._recorder,
                    validators={COMPUTE_APPLY: run.validator},
                    answer_type=run.result_type,
                    key=f"trace-step-{instance.name}-{id(self):x}",
                ),
            )
        )
    return tuple(installations)

finish

finish(run: RunContext, output: object) -> None

Build the trace from the recorded events and the run's contributions.

PARAMETER DESCRIPTION
run

The run, with every contribution the accumulator received.

TYPE: RunContext

output

The program's output, which the trace does not read; the wrapper that stacks this handler sets trace.output from the value it returns.

TYPE: object

Source code in src/quivers/effects/trace_handler.py
def finish(self, run: RunContext, output: object) -> None:
    """Build the trace from the recorded events and the run's contributions.

    Parameters
    ----------
    run : RunContext
        The run, with every contribution the accumulator received.
    output : object
        The program's output, which the trace does not read; the
        wrapper that stacks this handler sets ``trace.output`` from
        the value it returns.
    """
    del output
    events = self._recorder.events
    drawn = [
        self._record_site(run, event)
        for event in events
        if event.operation == RANDOM_SAMPLE
    ]
    for score in self._program_scores(run):
        drawn.append(score)
        self._run_axes[score.name] = False
    named = iter(zip(drawn, _occurrences(drawn), strict=True))
    sites: dict[str, SampleSite] = {}
    # The joint adds site densities in trace order. Keep each host
    # score at its recorded position relative to the draws.
    for event in events:
        if event.operation == RANDOM_SAMPLE:
            recorded, site = next(named)
            self._run_axes[site.name] = self._run_axes[recorded.name]
            sites[site.name] = site
        else:
            self._record_step(run, event, sites)
    for recorded, site in named:
        self._run_axes[site.name] = self._run_axes[recorded.name]
        sites[site.name] = site
    self._run_sites.append(sites)
    if run.vectorized:
        self._vectorized_runs = run.runs
    if run.run_index == run.runs - 1:
        self._merge_runs()

total_log_joint

total_log_joint(device: device) -> Tensor

Sum every site's density into the joint, one per run.

PARAMETER DESCRIPTION
device

Device the accumulator seeds on.

TYPE: device

RETURNS DESCRIPTION
Tensor

The joint log-density of each run, shape (B,).

Source code in src/quivers/effects/trace_handler.py
def total_log_joint(self, device: torch.device) -> torch.Tensor:
    """Sum every site's density into the joint, one per run.

    Parameters
    ----------
    device : torch.device
        Device the accumulator seeds on.

    Returns
    -------
    torch.Tensor
        The joint log-density of each run, shape ``(B,)``.
    """
    runs = self._vectorized_runs or len(self._run_sites)
    total = torch.zeros(runs, device=device)
    for site in self.trace.sites.values():
        total = total + site.log_prob
    return total