Skip to content

Handlers

These handlers cover conditioning, intervention, reweighting, subsampling, blocking, replay, and lifting. Conditioning fixes a site's value and adds its likelihood to the score. Intervention (do) replaces the mechanism that generates a site, which changes which density terms belong to the model. Replay takes values from an earlier trace, scaling multiplies score terms, and subsample scores a plate's sites at a subset of its rows, rescaled, for minibatch stochastic variational inference.

clamp

Clamp handler: condition named sample sites on given values.

ClampHandler is the effect-stack analogue of Pyro's condition. A site whose name appears in its data is answered with the given value and scored under its own distribution, so the value contributes the site's density to the joint and the trace records the site as observed. The name avoids collision with the top-level quivers.inference.conditioning.condition factory, which returns a Conditioned model wrapper.

ClampHandler

ClampHandler(data: dict[str, Tensor], *, missing: MissingValuePolicy = FORWARD)

Bases: EffectHandler

Condition named sample sites on given values.

PARAMETER DESCRIPTION
data

Site name to the value the site is clamped to. Other sites pass through untouched under the default missing-value policy.

TYPE: dict[str, Tensor]

missing

Whether an unprovided random request is forwarded or refused. ERROR also consults the run's declared observations, including computed and scanned values, and refuses a genuinely missing random value.

TYPE: MissingValuePolicy DEFAULT: FORWARD

Source code in src/quivers/effects/clamp.py
def __init__(
    self,
    data: dict[str, torch.Tensor],
    *,
    missing: MissingValuePolicy = MissingValuePolicy.FORWARD,
) -> None:
    self.data = dict(data)
    self.missing = missing

install

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

Install a conditioning handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The conditioning handler with the selected missing-value policy. Values at sites the program never samples are ignored.

Source code in src/quivers/effects/clamp.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a conditioning handler of the ``random`` instance.

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

    Returns
    -------
    tuple[Installation, ...]
        The conditioning handler with the selected missing-value policy.
        Values at sites the program never samples are ignored.
    """
    kernel = run.kernel
    return (
        Installation(
            instance=kernel.random,
            runtime=condition_handler(
                cast(
                    Mapping[object, object],
                    ChainMap(
                        {
                            name: run.slice_value(name, value)
                            for name, value in self.data.items()
                        },
                        run.observations
                        if self.missing is MissingValuePolicy.ERROR
                        else {},
                    ),
                ),
                score_instance=kernel.score.entry.instance,
                result_validator=run.validator,
                missing=self.missing,
                extra=ExtraValuePolicy.IGNORE,
                answer_type=run.result_type,
                key=f"clamp-{id(self):x}",
                at_run=run.select_run,
            ),
        ),
    )

clamp

clamp(data: dict[str, Tensor]) -> ClampHandler

Return a ClampHandler conditioning on the given site values.

PARAMETER DESCRIPTION
data

Site name to value.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
ClampHandler

The handler.

Source code in src/quivers/effects/clamp.py
def clamp(data: dict[str, torch.Tensor]) -> ClampHandler:
    """Return a `ClampHandler` conditioning on the given site values.

    Parameters
    ----------
    data : dict[str, torch.Tensor]
        Site name to value.

    Returns
    -------
    ClampHandler
        The handler.
    """
    return ClampHandler(data)

do

Intervention handler: fix named sites without scoring them.

DoHandler implements Pearl's do operator on the effect stack. A site whose name appears in its data is answered with the given value and contributes nothing to the joint: under intervention its distribution is replaced by a point mass. Downstream sites see the intervened value, and a trace records the site as deterministic.

DoHandler

DoHandler(data: dict[str, Tensor])

Bases: EffectHandler

Intervene on named sites.

An intervened site takes the value given and contributes no factor of its own to the joint. A response whose factor a score step holds loses that factor in the score: the rest of its block, the class prior and the other responses, keeps its own.

PARAMETER DESCRIPTION
data

Site name to the value the site is fixed to.

TYPE: dict[str, Tensor]

Source code in src/quivers/effects/do.py
def __init__(self, data: dict[str, torch.Tensor]) -> None:
    self.data = dict(data)

site_values property

site_values: dict[str, Tensor]

The sites the handler fixes, which is all it does.

RETURNS DESCRIPTION
dict[str, Tensor]

Site name to value.

install

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

Install an intervening handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared; each intervened site's address is recorded on it, so a trace marks the site deterministic.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The intervening handler.

Source code in src/quivers/effects/do.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install an intervening handler of the ``random`` instance.

    Parameters
    ----------
    run : RunContext
        The run being prepared; each intervened site's address is
        recorded on it, so a trace marks the site deterministic.

    Returns
    -------
    tuple[Installation, ...]
        The intervening handler.
    """

    def mark(request: RuntimeRequest, value: object) -> None:
        """Record an intervened site on the run.

        Parameters
        ----------
        request : RuntimeRequest
            The site's request.
        value : object
            The value fixed, unused.
        """
        del value
        run.intervene(request)

    return (
        Installation(
            instance=run.kernel.random,
            runtime=intervene_handler(
                {
                    name: run.slice_value(name, value)
                    for name, value in self.data.items()
                },
                result_validator=run.validator,
                on_intervene=mark,
                answer_type=run.result_type,
                key=f"do-{id(self):x}",
                at_run=run.select_run,
            ),
        ),
    )

do

do(data: dict[str, Tensor]) -> DoHandler

Return a DoHandler intervening on the given site values.

PARAMETER DESCRIPTION
data

Site name to value.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
DoHandler

The handler.

Source code in src/quivers/effects/do.py
def do(data: dict[str, torch.Tensor]) -> DoHandler:
    """Return a `DoHandler` intervening on the given site values.

    Parameters
    ----------
    data : dict[str, torch.Tensor]
        Site name to value.

    Returns
    -------
    DoHandler
        The handler.
    """
    return DoHandler(data)

scale

Scale handler: multiply every density contribution by a factor.

ScaleHandler is a transformer of the program's score instance: every contribution any site makes passes through it on the way to the run's accumulator, multiplied by the factor. Stacking scale with mask composes the two elementwise products.

ScaleHandler

ScaleHandler(factor: float)

Bases: EffectHandler

Multiply every density contribution by a scalar.

PARAMETER DESCRIPTION
factor

The multiplier.

TYPE: float

Source code in src/quivers/effects/scale.py
def __init__(self, factor: float) -> None:
    self.factor = float(factor)

install

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

Install a scaling transformer of the score instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The transformer.

Source code in src/quivers/effects/scale.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a scaling transformer of the ``score`` instance.

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

    Returns
    -------
    tuple[Installation, ...]
        The transformer.
    """
    factor = self.factor

    def scaled(weight: object) -> object:
        """Scale one contribution.

        Parameters
        ----------
        weight : object
            The contribution.

        Returns
        -------
        object
            The contribution times the factor.
        """
        return torch.as_tensor(weight) * factor

    return (
        Installation(
            instance=run.kernel.score,
            runtime=reweight_handler(
                scaled,
                score_instance=run.kernel.score.entry.instance,
                answer_type=run.result_type,
                key=f"scale-{id(self):x}",
            ),
        ),
    )

scale

scale(factor: float) -> ScaleHandler

Return a ScaleHandler with the given factor.

PARAMETER DESCRIPTION
factor

The multiplier.

TYPE: float

RETURNS DESCRIPTION
ScaleHandler

The handler.

Source code in src/quivers/effects/scale.py
def scale(factor: float) -> ScaleHandler:
    """Return a `ScaleHandler` with the given factor.

    Parameters
    ----------
    factor : float
        The multiplier.

    Returns
    -------
    ScaleHandler
        The handler.
    """
    return ScaleHandler(factor)

mask

Mask handler: gate every density contribution elementwise.

MaskHandler is a transformer of the program's score instance: the mask is broadcast against every contribution on its way to the run's accumulator. A boolean mask switches entries; a float mask scales them.

MaskHandler

MaskHandler(mask_tensor: Tensor)

Bases: EffectHandler

Gate every density contribution elementwise.

PARAMETER DESCRIPTION
mask_tensor

The mask, broadcast against each contribution. For a call on an input of B > 1 rows, a mask whose leading axis has length B gates each run by its own entry; any other mask applies to every run.

TYPE: Tensor

Source code in src/quivers/effects/mask.py
def __init__(self, mask_tensor: torch.Tensor) -> None:
    self.mask = mask_tensor

install

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

Install a masking transformer of the score instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The transformer.

Source code in src/quivers/effects/mask.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a masking transformer of the ``score`` instance.

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

    Returns
    -------
    tuple[Installation, ...]
        The transformer.
    """
    mask = self.mask
    if (
        not run.vectorized
        and run.runs > 1
        and mask.dim() >= 1
        and int(mask.shape[0]) == run.runs
    ):
        # A mask laid out one entry per run gates each run by its own.
        mask = mask[run.run_index : run.run_index + 1]

    def masked(weight: object) -> object:
        """Mask one contribution.

        Parameters
        ----------
        weight : object
            The contribution.

        Returns
        -------
        object
            The contribution times the mask.
        """
        return torch.as_tensor(weight) * mask.to(torch.as_tensor(weight).dtype)

    return (
        Installation(
            instance=run.kernel.score,
            runtime=reweight_handler(
                masked,
                score_instance=run.kernel.score.entry.instance,
                answer_type=run.result_type,
                key=f"mask-{id(self):x}",
            ),
        ),
    )

mask

mask(mask_tensor: Tensor) -> MaskHandler

Return a MaskHandler with the given mask.

PARAMETER DESCRIPTION
mask_tensor

The mask.

TYPE: Tensor

RETURNS DESCRIPTION
MaskHandler

The handler.

Source code in src/quivers/effects/mask.py
def mask(mask_tensor: torch.Tensor) -> MaskHandler:
    """Return a `MaskHandler` with the given mask.

    Parameters
    ----------
    mask_tensor : torch.Tensor
        The mask.

    Returns
    -------
    MaskHandler
        The handler.
    """
    return MaskHandler(mask_tensor)

subsample

Subsampled plates: score a plate's sites at a subset of its rows, rescaled.

A program whose observations live in a plate scores every row of the plate on every run. Stochastic variational inference (Hoffman et al. 2013) scores a random subset of the rows instead and multiplies their contribution by the plate's size over the subset's size, which keeps the objective and its gradient unbiased.

SubsampleHandler does this for one plate. Within its block, every site whose batch axes include the plate, a plate latent or an observation, is scored at the subset's rows only, and its contribution is multiplied by N / B for a plate of N rows and a subset of B. A site outside the plate, a global latent among them, is scored in full and unscaled, and so is a score step that declares no units, which is a factor of the whole run. Handlers for several plates compose: a site in two subsampled plates is scored at the product of the two subsets and scaled by the product of the two factors, and a site in one of two sibling plates by its own plate's factor alone.

A score step that declares its units (UnitFactorization) is a sum over them, and a subsampled plate keeps a subset of the units when the plate is a unit axis or no unit has rows both inside and outside the subset. Each unit kept is scaled by the number of units over the number kept (see unit_coefficients). A subset that splits a unit is refused: the joint score of rows that share a summed-out latent is not a sum over them.

Within a run a subsampled plate keeps its declared extent: its latents are drawn at every row and the program's lets compute every row, so the rows outside the subset keep well-defined values and only their scores are left out. An observation may be given at the plate's extent or at the subset's size, its rows then read in the order of the index; a plate latent is given at the plate's extent.

The guides that factor over a plate's rows score a latent in a subsampled plate at the same rows with the same factor (AutoNormalGuide, AmortizedGuide, whose encoder still reads every row of its datum, and AutoDeltaGuide, whose density is constant); every other guide refuses such a latent, since its density does not split over the rows. MCMC, the Laplace approximation, annealed importance sampling, and the Bayesian lift target the exact posterior and refuse to run inside the block.

SubsampleHandler

SubsampleHandler(plate: str, index: Tensor)

Bases: EffectHandler

Score one plate's sites at a subset of its rows, rescaled.

PARAMETER DESCRIPTION
plate

The plate's name: the object its sites range over, as the program declares it (Item for observe y : Item <- ...).

TYPE: str

index

The rows scored: a nonempty one-dimensional integer tensor of distinct rows in increasing order.

TYPE: Tensor

RAISES DESCRIPTION
ValueError

If index is not a nonempty one-dimensional tensor of distinct nonnegative integers in increasing order.

Source code in src/quivers/effects/subsample.py
def __init__(self, plate: str, index: torch.Tensor) -> None:
    rows = torch.as_tensor(index)
    if rows.dim() != 1 or rows.numel() == 0:
        raise ValueError(
            f"subsample({plate!r}): the index must be a nonempty "
            f"one-dimensional tensor of rows, got shape {tuple(rows.shape)}"
        )
    if (
        rows.dtype.is_floating_point
        or rows.dtype.is_complex
        or (rows.dtype == torch.bool)
    ):
        raise ValueError(
            f"subsample({plate!r}): the index must hold integer rows, "
            f"got dtype {rows.dtype}"
        )
    rows = rows.long()
    if int(rows.min()) < 0:
        raise ValueError(f"subsample({plate!r}): the index holds a negative row")
    if rows.numel() > 1 and not bool((rows[1:] > rows[:-1]).all()):
        raise ValueError(
            f"subsample({plate!r}): the index must list distinct rows in "
            "increasing order, so that a value given at the subset's size "
            "reads its rows unambiguously"
        )
    self.plate = plate
    self.index = rows

install

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

Register the plate's subset on the run.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

No lexical handler: the run scores the plate's sites at the subset as it builds them.

RAISES DESCRIPTION
ValueError

If another handler on the stack subsamples the same plate, no site of the program ranges over the plate, or the index leaves the plate.

Source code in src/quivers/effects/subsample.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Register the plate's subset on the run.

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

    Returns
    -------
    tuple[Installation, ...]
        No lexical handler: the run scores the plate's sites at the
        subset as it builds them.

    Raises
    ------
    ValueError
        If another handler on the stack subsamples the same plate, no
        site of the program ranges over the plate, or the index
        leaves the plate.
    """
    if self.plate in run.subsamples:
        raise ValueError(
            f"subsample({self.plate!r}) is active twice; a plate takes one "
            "subset per run"
        )
    extents = plate_extents(run)
    if self.plate not in extents:
        known = ", ".join(repr(name) for name in sorted(extents)) or "none"
        raise ValueError(
            f"subsample({self.plate!r}): no site of the program ranges over "
            f"a plate of that name (its plates: {known}). A program compiled "
            "from QVR records each site's plates in `site_plates`; a "
            "program built in Python records them there by hand"
        )
    extent = extents[self.plate]
    if int(self.index.max()) >= extent:
        raise ValueError(
            f"subsample({self.plate!r}): the index holds row "
            f"{int(self.index.max())}, beyond the plate's {extent} rows"
        )
    run.subsamples[self.plate] = self.index
    return ()

plate_extents

plate_extents(run: RunContext) -> dict[str, int]

The extent of every plate a run's sites range over.

PARAMETER DESCRIPTION
run

The run.

TYPE: RunContext

RETURNS DESCRIPTION
dict[str, int]

Each plate's number of rows, by name, read from the MonadicProgram.site_plates of the programs the run executes and from the units their score steps declare.

RAISES DESCRIPTION
ValueError

If two sites give one plate different extents.

Source code in src/quivers/effects/subsample.py
def plate_extents(run: RunContext) -> dict[str, int]:
    """The extent of every plate a run's sites range over.

    Parameters
    ----------
    run : RunContext
        The run.

    Returns
    -------
    dict[str, int]
        Each plate's number of rows, by name, read from the
        `MonadicProgram.site_plates` of the programs the run executes and
        from the units their score steps declare.

    Raises
    ------
    ValueError
        If two sites give one plate different extents.
    """
    extents: dict[str, int] = {}
    for step in run.kernel.steps:
        plates: tuple[tuple[str, int | None], ...] = ()
        if step.kind == "draw" and isinstance(step.spec, Draw | Observe):
            plates = site_plates(step.program, step.spec)
        elif isinstance(step.spec, Score) and step.spec.units is not None:
            units = step.spec.units
            plates = (
                *zip(units.axes, units.sizes, strict=True),
                *((item.plate, item.extent) for item in units.members),
            )
        for name, extent in plates:
            if extent is None:
                continue
            if extents.setdefault(name, extent) != extent:
                raise ValueError(
                    f"plate {name!r} has {extents[name]} rows at one site and "
                    f"{extent} at another"
                )
    return extents

site_plates

site_plates(program: MonadicProgram, spec: Draw | Observe) -> tuple[tuple[str, int | None], ...]

The plates a draw or observe step's site ranges over.

PARAMETER DESCRIPTION
program

The program the step belongs to.

TYPE: MonadicProgram

spec

The step.

TYPE: Draw | Observe

RETURNS DESCRIPTION
tuple[tuple[str, int], ...]

The site's plate axes, outermost first, as (name, extent) pairs, the extent None where the program leaves it to its data; empty for a site in no plate.

Source code in src/quivers/effects/subsample.py
def site_plates(
    program: MonadicProgram, spec: Draw | Observe
) -> tuple[tuple[str, int | None], ...]:
    """The plates a draw or observe step's site ranges over.

    Parameters
    ----------
    program : MonadicProgram
        The program the step belongs to.
    spec : Draw | Observe
        The step.

    Returns
    -------
    tuple[tuple[str, int], ...]
        The site's plate axes, outermost first, as ``(name, extent)``
        pairs, the extent ``None`` where the program leaves it to its
        data; empty for a site in no plate.
    """
    return program.site_plates.get(spec.names[0], ())

subsampled_rows

subsampled_rows(site: str, axes: tuple[tuple[str, int | None], ...], subsets: dict[str, Tensor]) -> tuple[tuple[Tensor, ...], float] | None

The rows a site is scored at, and its factor, under subsampled plates.

PARAMETER DESCRIPTION
site

The site's label, for the diagnostic.

TYPE: str

axes

The site's plate axes, outermost first, as site_plates gives them.

TYPE: tuple[tuple[str, int | None], ...]

subsets

The rows kept of each subsampled plate, by name.

TYPE: dict[str, Tensor]

RETURNS DESCRIPTION
tuple[tuple[Tensor, ...], float] | None

One index per plate axis (the subset's rows along a subsampled axis, every row along another) and the product over the subsampled axes of the axis's extent over the subset's size; None for a site in no subsampled plate.

RAISES DESCRIPTION
ValueError

If a subsampled plate of the site has no fixed extent, or the subset leaves it.

Source code in src/quivers/effects/subsample.py
def subsampled_rows(
    site: str,
    axes: tuple[tuple[str, int | None], ...],
    subsets: dict[str, torch.Tensor],
) -> tuple[tuple[torch.Tensor, ...], float] | None:
    """The rows a site is scored at, and its factor, under subsampled plates.

    Parameters
    ----------
    site : str
        The site's label, for the diagnostic.
    axes : tuple[tuple[str, int | None], ...]
        The site's plate axes, outermost first, as `site_plates` gives
        them.
    subsets : dict[str, torch.Tensor]
        The rows kept of each subsampled plate, by name.

    Returns
    -------
    tuple[tuple[torch.Tensor, ...], float] | None
        One index per plate axis (the subset's rows along a subsampled
        axis, every row along another) and the product over the
        subsampled axes of the axis's extent over the subset's size;
        ``None`` for a site in no subsampled plate.

    Raises
    ------
    ValueError
        If a subsampled plate of the site has no fixed extent, or the
        subset leaves it.
    """
    if not any(name in subsets for name, _ in axes):
        return None
    rows: list[torch.Tensor] = []
    factor = 1.0
    for name, extent in axes:
        if extent is None:
            raise ValueError(
                f"site {site!r} ranges over plate {name!r}, whose extent the "
                "program leaves to its data; a subsampled plate needs a fixed "
                "number of rows"
            )
        index = subsets.get(name)
        if index is None:
            rows.append(torch.arange(extent))
            continue
        if int(index.max()) >= extent:
            raise ValueError(
                f"subsample({name!r}): the index holds row {int(index.max())}, "
                f"beyond the {extent} rows of the plate at site {site!r}"
            )
        rows.append(index)
        factor *= extent / int(index.numel())
    return tuple(rows), factor

active_subsets

active_subsets() -> dict[str, Tensor]

The rows kept of each plate the current thread's stack subsamples.

RETURNS DESCRIPTION
dict[str, Tensor]

The index of each subsampled plate, by name.

RAISES DESCRIPTION
ValueError

If two active handlers subsample one plate.

Source code in src/quivers/effects/subsample.py
def active_subsets() -> dict[str, torch.Tensor]:
    """The rows kept of each plate the current thread's stack subsamples.

    Returns
    -------
    dict[str, torch.Tensor]
        The index of each subsampled plate, by name.

    Raises
    ------
    ValueError
        If two active handlers subsample one plate.
    """
    subsets: dict[str, torch.Tensor] = {}
    for handler in active_subsamples():
        if handler.plate in subsets:
            raise ValueError(
                f"subsample({handler.plate!r}) is active twice; a plate takes "
                "one subset per run"
            )
        subsets[handler.plate] = handler.index
    return subsets

subsample

subsample(plate: str, index: Tensor) -> SubsampleHandler

Return a SubsampleHandler scoring a plate at a subset of its rows.

PARAMETER DESCRIPTION
plate

The plate's name.

TYPE: str

index

The rows scored, distinct and in increasing order.

TYPE: Tensor

RETURNS DESCRIPTION
SubsampleHandler

The handler, used as a context manager around the calls that score the program (an SVI.step, a trace, a log_joint).

Source code in src/quivers/effects/subsample.py
def subsample(plate: str, index: torch.Tensor) -> SubsampleHandler:
    """Return a `SubsampleHandler` scoring a plate at a subset of its rows.

    Parameters
    ----------
    plate : str
        The plate's name.
    index : torch.Tensor
        The rows scored, distinct and in increasing order.

    Returns
    -------
    SubsampleHandler
        The handler, used as a context manager around the calls that
        score the program (an `SVI.step`, a `trace`, a `log_joint`).
    """
    return SubsampleHandler(plate, index)

active_subsamples

active_subsamples() -> tuple[SubsampleHandler, ...]

The subsample handlers on the current thread's stack, outer first.

RETURNS DESCRIPTION
tuple[SubsampleHandler, ...]

The active handlers.

Source code in src/quivers/effects/subsample.py
def active_subsamples() -> tuple[SubsampleHandler, ...]:
    """The subsample handlers on the current thread's stack, outer first.

    Returns
    -------
    tuple[SubsampleHandler, ...]
        The active handlers.
    """
    return tuple(
        handler for handler in _handler_stack() if isinstance(handler, SubsampleHandler)
    )

refuse_subsampling

refuse_subsampling(consumer: str) -> None

Refuse a subsampled plate in a consumer of the exact posterior.

PARAMETER DESCRIPTION
consumer

The consumer's name, for the diagnostic.

TYPE: str

RAISES DESCRIPTION
ValueError

If any subsample handler is active.

Source code in src/quivers/effects/subsample.py
def refuse_subsampling(consumer: str) -> None:
    """Refuse a subsampled plate in a consumer of the exact posterior.

    Parameters
    ----------
    consumer : str
        The consumer's name, for the diagnostic.

    Raises
    ------
    ValueError
        If any subsample handler is active.
    """
    active = active_subsamples()
    if active:
        plates = ", ".join(repr(handler.plate) for handler in active)
        raise ValueError(
            f"{consumer} targets the exact posterior, but the plate(s) {plates} "
            "are subsampled: a subsampled plate gives an unbiased estimate of "
            "the log joint, which only a stochastic objective such as the ELBO "
            "under SVI can use. Run it outside the subsample block"
        )

block

Block handler: hide sites from the handlers outside it.

BlockHandler answers hidden sites itself, drawing and scoring them exactly as the run's default handler would, so no handler outside it sees their requests: an outer trace does not record them and an outer clamp cannot condition them. Every other site forwards.

BlockHandler

BlockHandler(hide: list[str] | None = None, expose: list[str] | None = None)

Bases: EffectHandler

Hide sites from outer handlers.

PARAMETER DESCRIPTION
hide

Site names to hide; every site when both arguments are absent.

TYPE: list[str] or None DEFAULT: None

expose

Site names to leave visible, hiding every other.

TYPE: list[str] or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If both hide and expose are given.

Source code in src/quivers/effects/block.py
def __init__(
    self, hide: list[str] | None = None, expose: list[str] | None = None
) -> None:
    if hide is not None and expose is not None:
        raise ValueError(
            "BlockHandler: pass at most one of `hide` and `expose`, not both."
        )
    self.hide = list(hide) if hide is not None else None
    self.expose = list(expose) if expose is not None else None

install

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

Install a blocking handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The blocking handler.

Source code in src/quivers/effects/block.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a blocking handler of the ``random`` instance.

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

    Returns
    -------
    tuple[Installation, ...]
        The blocking handler.
    """
    kernel = run.kernel
    return (
        Installation(
            instance=kernel.random,
            runtime=block_handler(
                self._should_block,
                score_instance=kernel.score.entry.instance,
                result_validator=run.validator,
                answer_type=run.result_type,
                key=f"block-{id(self):x}",
            ),
        ),
    )

block

block(hide: list[str] | None = None, expose: list[str] | None = None) -> BlockHandler

Return a BlockHandler hiding or exposing the named sites.

PARAMETER DESCRIPTION
hide

Site names to hide.

TYPE: list[str] or None DEFAULT: None

expose

Site names to leave visible.

TYPE: list[str] or None DEFAULT: None

RETURNS DESCRIPTION
BlockHandler

The handler.

Source code in src/quivers/effects/block.py
def block(
    hide: list[str] | None = None,
    expose: list[str] | None = None,
) -> BlockHandler:
    """Return a `BlockHandler` hiding or exposing the named sites.

    Parameters
    ----------
    hide : list[str] or None
        Site names to hide.
    expose : list[str] or None
        Site names to leave visible.

    Returns
    -------
    BlockHandler
        The handler.
    """
    return BlockHandler(hide=hide, expose=expose)

replay

Replay handler: reinstall the values a trace recorded.

ReplayHandler answers sites with their recorded values unless the current run gives an explicit value at the site. It scores each replayed value under the site's current distribution.

ReplayHandler

ReplayHandler(trace: Trace)

Bases: EffectHandler

Replay the values of a recorded trace.

PARAMETER DESCRIPTION
trace

The trace whose site values are reinstalled.

TYPE: Trace

Source code in src/quivers/effects/replay.py
def __init__(self, trace: Trace) -> None:
    self._trace = trace

install

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

Install a scoring replay handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The replay handler, which forwards sites already given to the run and sites the trace lacks. It ignores recorded sites the program never samples.

Source code in src/quivers/effects/replay.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a scoring replay handler of the ``random`` instance.

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

    Returns
    -------
    tuple[Installation, ...]
        The replay handler, which forwards sites already given to
        the run and sites the trace lacks. It ignores recorded sites
        the program never samples.
    """
    kernel = run.kernel
    values = {
        name: run.slice_value(name, site.value)
        for name, site in self._trace.sites.items()
        if name not in run.observations
        and (not site.is_deterministic or site.morphism is not None)
    }
    return (
        Installation(
            instance=kernel.random,
            runtime=replay_handler(
                values,
                result_validator=run.validator,
                policy=ReplayPolicy.CLAMP_AND_SCORE,
                score_instance=kernel.score.entry.instance,
                extra=ExtraValuePolicy.IGNORE,
                answer_type=run.result_type,
                key=f"replay-{id(self):x}",
                at_run=run.select_run,
            ),
        ),
    )

replay

replay(trace: Trace) -> ReplayHandler

Return a ReplayHandler replaying the given trace.

PARAMETER DESCRIPTION
trace

The trace.

TYPE: Trace

RETURNS DESCRIPTION
ReplayHandler

The handler.

Source code in src/quivers/effects/replay.py
def replay(trace: Trace) -> ReplayHandler:
    """Return a `ReplayHandler` replaying the given trace.

    Parameters
    ----------
    trace : Trace
        The trace.

    Returns
    -------
    ReplayHandler
        The handler.
    """
    return ReplayHandler(trace)

lift

Lift handler: draw every learned parameter from a prior.

LiftHandler handles the program's param instance: each parameter a morphism reads through Param.get is answered with a draw from a Normal(value, prior_scale) prior centred on its current value, one draw per parameter per run, and the morphism runs under the drawn values. The draws are kept in sampled_params keyed by the site and the parameter's qualified name.

LiftHandler

LiftHandler(prior_scale: float = 1.0)

Bases: EffectHandler

Draw every reachable parameter from a Normal prior.

PARAMETER DESCRIPTION
prior_scale

Standard deviation of the Normal prior around each parameter's current value.

TYPE: float DEFAULT: 1.0

Source code in src/quivers/effects/lift.py
def __init__(self, prior_scale: float = 1.0) -> None:
    self.prior_scale = float(prior_scale)
    self.sampled_params: dict[str, torch.Tensor] = {}

install

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

Install a prior-drawing handler of the param instance.

PARAMETER DESCRIPTION
run

The run being prepared, whose parameter store holds each parameter's current value.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The handler, which answers each parameter's first read with a fresh draw and later reads with the same draw.

Source code in src/quivers/effects/lift.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install a prior-drawing handler of the ``param`` instance.

    Parameters
    ----------
    run : RunContext
        The run being prepared, whose parameter store holds each
        parameter's current value.

    Returns
    -------
    tuple[Installation, ...]
        The handler, which answers each parameter's first read with
        a fresh draw and later reads with the same draw.
    """
    scale = self.prior_scale
    sampled = self.sampled_params

    def draw(name: str, request: RuntimeRequest) -> object:
        """Answer a parameter read with its prior draw.

        Parameters
        ----------
        name : str
            The parameter's qualified name.
        request : RuntimeRequest
            The read, unused.

        Returns
        -------
        object
            The draw made for the name on this run.
        """
        del request
        if name not in sampled:
            current = run.parameters[name]
            sampled[name] = current.detach() + scale * torch.randn_like(current)
        return sampled[name]

    return (
        Installation(
            instance=run.kernel.param,
            runtime=param_handler(
                draw,
                result_validator=run.validator,
                total=False,
                answer_type=run.result_type,
                key=f"lift-{id(self):x}",
            ),
        ),
    )

reset

reset() -> None

Clear the draws so the next run makes fresh ones.

Source code in src/quivers/effects/lift.py
def reset(self) -> None:
    """Clear the draws so the next run makes fresh ones."""
    self.sampled_params.clear()

lift

lift(prior_scale: float = 1.0) -> LiftHandler

Return a LiftHandler with the given prior scale.

PARAMETER DESCRIPTION
prior_scale

Standard deviation of the prior.

TYPE: float DEFAULT: 1.0

RETURNS DESCRIPTION
LiftHandler

The handler.

Source code in src/quivers/effects/lift.py
def lift(prior_scale: float = 1.0) -> LiftHandler:
    """Return a `LiftHandler` with the given prior scale.

    Parameters
    ----------
    prior_scale : float
        Standard deviation of the prior.

    Returns
    -------
    LiftHandler
        The handler.
    """
    return LiftHandler(prior_scale)