Skip to content

Handler base

An EffectHandler describes a handler of a program's random or score instance (Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). Entering it as a context manager pushes it on a thread-local handler stack, and a run installs every handler on the stack around the program, so that each sample request passes through the active handlers before it receives a value. The module gives the handler stack, the run context, and the installation record. Conditioning, tracing, and the other common behaviors are concrete handlers.

base

Effect handlers for probabilistic programs, as lexical kernel handlers.

A MonadicProgram runs on the reference machine as the kernel computation :mod:quivers.effects.program_module encodes it to, whose sites are Random.sample requests on the program's random instance and whose densities are Score.add requests on its score instance. An EffectHandler is a description of a handler of one of those instances: entering it as a context manager pushes it on a thread-local stack, and quivers.effects.interpreter.run_program installs every handler on the stack as a lexical handler around the program, in the order the stack gives, so the composition rules are the kernel's own. The design descends from the Pyro poutine and NumPyro handlers shape (Pyro poutine docs) and from the operational account of handlers in Plotkin and Pretnar (2009); its application to probabilistic programming follows Scibior et al. (2018).

Two rules govern how a stack composes. A handler of the random instance sees a site's request before any handler outside it, and sees the outer answer flow back through its resumption, so an inner trace records what an outer clamp or intervention decided. The density a site contributes is a Score.add the answering handler emits outward, so every handler of the score instance on the stack transforms every site's density on its way to the run's accumulator, and a trace reads a site's density from what reached the accumulator under that site's provenance.

SiteKey

SiteKey = tuple[str, tuple[tuple[str, str | int], ...], tuple[int, ...]]

The dynamic address of one occurrence of a site: its static identity, its dynamic address frames, and its resumption path.

Contribution didactic-model

Contribution(*, key: SiteKey = field(opaque=True, extras=OPAQUE_BY_VALUE), role: str, weight: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), path: tuple[str | int, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), derived: bool = False)

Bases: QiecModel

One score contribution that reached the run's accumulator.

The address and path compare by value; the tensor retains identity.

PARAMETER DESCRIPTION
key

The address of the site the contribution was derived from.

TYPE: SiteKey DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

role

What the contribution was for, from the emitting handler's provenance: a scored draw, a conditioned observation, a replay.

TYPE: str

weight

The contribution as it arrived, after every transformer.

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

path

The structural path of the request's origin; a score step of the program has the path of its step, a derived contribution the path it was generated at.

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

derived

Whether a handler derived the contribution from a site (the density of a draw, an observation, a replay), rather than the program scoring it.

TYPE: bool DEFAULT: False

RunContext didactic-model

RunContext(*, kernel: ProgramKernel = field(opaque=True, extras=OPAQUE_BY_VALUE), validator: RuntimeValidator = field(opaque=True, extras=OPAQUE_BY_IDENTITY), contributions: list[Contribution] = field(default_factory=list, opaque=True, extras=OPAQUE_BY_IDENTITY), interventions: set[SiteKey] = field(default_factory=set, opaque=True, extras=OPAQUE_BY_IDENTITY), fixed: set[str] = field(default_factory=set, opaque=True, extras=OPAQUE_BY_IDENTITY), annotations: dict[str, dict[str, HeldValue]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), parameters: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), observations: dict[str, Tensor | RuntimeConstructor | str | None] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), supplied: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), occurrences: dict[str, int] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), reached: set[str] = field(default_factory=set, opaque=True, extras=OPAQUE_BY_IDENTITY), run_index: int = 0, runs: int = 1, slice_value: Callable[[str, Tensor], Tensor] = field(default=_shared_value, opaque=True, extras=OPAQUE_BY_IDENTITY), carries_run_axis: Callable[[MonadicProgram, str], bool] = field(default=_no_run_axis, opaque=True, extras=OPAQUE_BY_IDENTITY), site_carries_run_axis: Callable[[str], bool] = field(default=_no_site_run_axis, opaque=True, extras=OPAQUE_BY_IDENTITY), vectorized: bool = False, select_run: Callable[[object, object], object] = field(default=_as_given, opaque=True, extras=OPAQUE_BY_IDENTITY), subsamples: dict[str, Tensor] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

What one run shares with the handlers installed on it.

The checked kernel compares by value. Mutable per-run collections and executable callbacks retain identity, including the shared parameter store.

PARAMETER DESCRIPTION
kernel

The program's kernel encoding.

TYPE: ProgramKernel DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

validator

The host value validator every handler's clauses check with.

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

contributions

The score contributions that reached the accumulator, in order.

TYPE: list[Contribution] DEFAULT: field(default_factory=list, opaque=True, extras=OPAQUE_BY_IDENTITY)

interventions

The sites an intervention fixed, by address.

TYPE: set[SiteKey] DEFAULT: field(default_factory=set, opaque=True, extras=OPAQUE_BY_IDENTITY)

fixed

The labels of the same sites, an occurrence of a site a scan reaches once per position as "<label>@<n>".

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

annotations

Per-site annotations handlers attach, keyed by site label.

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

parameters

The learned parameters of the program's morphisms by qualified name, as the parameter store answers them.

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

observations

The run's observations at declared sites, by site label. A checked finite law may observe a typed structured value.

TYPE: dict[str, Tensor | RuntimeConstructor | str | None] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

supplied

Values standing in for let bindings, by name, which their steps read rather than compute.

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

occurrences

How many times the run has reached each site a scan reaches once per position, by label.

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

reached

The addresses "<label>@<n>" of the occurrences reached.

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

run_index

The position of this run among the runs of one call: an input of B rows runs the program once per row, 0 to B - 1.

TYPE: int DEFAULT: 0

runs

The number of runs the call makes, B.

TYPE: int DEFAULT: 1

slice_value

Maps a site label and a value given for every run of the call to this run's value: the run's slice of a value laid out one per run, or the value itself when every run shares it.

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

carries_run_axis

Whether a binding of a program, by name, carries this run's leading axis of length one.

TYPE: Callable[[MonadicProgram, str], bool] DEFAULT: field(default=_no_run_axis, opaque=True, extras=OPAQUE_BY_IDENTITY)

site_carries_run_axis

Whether a site's value in this run, by label, carries the run's leading axis of length one.

TYPE: Callable[[str], bool] DEFAULT: field(default=_no_site_run_axis, opaque=True, extras=OPAQUE_BY_IDENTITY)

vectorized

Whether this execution carries all runs runs of the call at once, every value leading with the run axis of length runs.

TYPE: bool DEFAULT: False

select_run

Given a value handed to a handler for every run of the call and the sampleable of the site it is used at, this run's value. A compiled run slices its values by slice_value before the run and takes each as it is here; a run that learns a site's shape only when it reaches the site slices here.

TYPE: Callable[[object, object], object] DEFAULT: field(default=_as_given, opaque=True, extras=OPAQUE_BY_IDENTITY)

subsamples

The rows of each subsampled plate the run scores, by plate name, as the SubsampleHandler entries on the stack register them.

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

result_type property

result_type: TypeExpr

The type of the program's result.

RETURNS DESCRIPTION
TypeExpr

The entry computation's result type, which every transparent handler answers with.

intervene

intervene(request: RuntimeRequest) -> None

Record that a site's own factor is not part of the joint.

PARAMETER DESCRIPTION
request

The site's sample request, whose first argument is its label.

TYPE: RuntimeRequest

Source code in src/quivers/effects/base.py
def intervene(self, request: RuntimeRequest) -> None:
    """Record that a site's own factor is not part of the joint.

    Parameters
    ----------
    request : RuntimeRequest
        The site's sample request, whose first argument is its label.
    """
    self.interventions.add(self.key_of(request))
    label = request.arguments[0]
    assert isinstance(label, str)
    self.fixed.add(label)

conditions

conditions(occurrence: Callable[[str], str] | None = None) -> RunConditions

What the run does to the factors of a score.

PARAMETER DESCRIPTION
occurrence

From a site's label to the address a step of a scan reads it at; None for a step outside any scan.

TYPE: Callable[[str], str] or None DEFAULT: None

RETURNS DESCRIPTION
RunConditions

The responses fixed, by the names a step reads them under, and the subsets of the subsampled plates.

Source code in src/quivers/effects/base.py
def conditions(
    self, occurrence: Callable[[str], str] | None = None
) -> RunConditions:
    """What the run does to the factors of a score.

    Parameters
    ----------
    occurrence : Callable[[str], str] or None
        From a site's label to the address a step of a scan reads it
        at; ``None`` for a step outside any scan.

    Returns
    -------
    RunConditions
        The responses fixed, by the names a step reads them under, and
        the subsets of the subsampled plates.
    """
    if occurrence is None:
        fixed = frozenset(self.fixed)
    else:
        bases = {label.rpartition("@")[0] for label in self.fixed}
        fixed = frozenset(
            name for name in bases if name and occurrence(name) in self.fixed
        )
    return RunConditions(fixed=fixed, subsets=dict(self.subsamples))

key_of

key_of(request: RuntimeRequest) -> SiteKey

The address of the site a request belongs to.

PARAMETER DESCRIPTION
request

A sample request, or a score request derived from one.

TYPE: RuntimeRequest

RETURNS DESCRIPTION
SiteKey

The request's own address for a sample request; for a derived request, the address of the site it was derived from.

Source code in src/quivers/effects/base.py
def key_of(self, request: RuntimeRequest) -> SiteKey:
    """The address of the site a request belongs to.

    Parameters
    ----------
    request : RuntimeRequest
        A sample request, or a score request derived from one.

    Returns
    -------
    SiteKey
        The request's own address for a sample request; for a derived
        request, the address of the site it was derived from.
    """
    static, dynamic, path = request.address
    parents = request.core.origin.parents
    if parents:
        # A derived request's declared dynamic path is the address of
        # the site it was derived from.
        static = str(parents[0])
        dynamic = tuple(
            (frame.scope, frame.key) for frame in request.core.origin.dynamic_path
        )
    return (static, dynamic, path)

Installation didactic-model

Installation(*, instance: NamedEffectInstance = field(opaque=True, extras=OPAQUE_BY_VALUE), runtime: RuntimeHandler = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

One lexical handler a stack entry installs on a run.

The effect instance compares by value; the executable handler retains identity.

PARAMETER DESCRIPTION
instance

The instance the handler handles: the program's random, score, or param instance.

TYPE: NamedEffectInstance DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

runtime

The executable handler, whose definition joins the run's module.

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

named

named(name: str) -> Installation

The installation with its handler declared under a name.

A module's handler names and identities are unique, while the prelude factories name every handler of a kind alike and derive its identity from the stack entry that made it; a run renames each installation it makes and derives its identity from the name, so two runs installing the same kinds of handler in the same order build the same module.

PARAMETER DESCRIPTION
name

The declaration's name, unique within the run.

TYPE: str

RETURNS DESCRIPTION
Installation

The installation with the renamed declaration, the rename carried into any per-installation factory the handler has.

Source code in src/quivers/effects/base.py
def named(self, name: str) -> Installation:
    """The installation with its handler declared under a name.

    A module's handler names and identities are unique, while the
    prelude factories name every handler of a kind alike and derive
    its identity from the stack entry that made it; a run renames
    each installation it makes and derives its identity from the
    name, so two runs installing the same kinds of handler in the
    same order build the same module.

    Parameters
    ----------
    name : str
        The declaration's name, unique within the run.

    Returns
    -------
    Installation
        The installation with the renamed declaration, the rename
        carried into any per-installation factory the handler has.
    """
    definition = _named_definition(self.runtime.definition, name)
    runtime = self.runtime.with_(definition=definition)
    factory = self.runtime.context_factory
    if factory is not None:

        def context_factory() -> RuntimeHandler:
            """Build a fresh installation under the renamed declaration.

            Returns
            -------
            RuntimeHandler
                The handler the original factory builds, renamed.
            """
            return factory().with_(definition=definition)

        runtime = runtime.with_(context_factory=context_factory)
    return Installation(instance=self.instance, runtime=runtime)

EffectHandler

Bases: ABC

A handler of a program's canonical instances, stacked by with.

Subclasses implement :meth:install, which builds the lexical handlers the entry contributes to one run, and may implement :meth:finish, which runs after the program returns with the run's context. The handler activates by being used as a context manager:

with clamp({"z": z_val}):
    samples = predictive.rsample(x)

Nested with blocks stack handlers outer-first; the innermost handler of an instance is installed closest to the program.

site_values property

site_values: Mapping[str, Tensor] | None

The values the handler fixes sites to, when it does nothing else.

RETURNS DESCRIPTION
Mapping[str, Tensor] or None

The value of each site, by label, for a handler whose only effect is to answer those sites without scoring them; None for any other handler.

__enter__

__enter__() -> Self

Push the handler on the thread's stack.

RETURNS DESCRIPTION
Self

The handler, so with handler as h binds it.

Source code in src/quivers/effects/base.py
def __enter__(self) -> Self:
    """Push the handler on the thread's stack.

    Returns
    -------
    Self
        The handler, so ``with handler as h`` binds it.
    """
    _handler_stack().append(self)
    return self

__exit__

__exit__(exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> None

Pop the handler off the thread's stack.

PARAMETER DESCRIPTION
exc_type

The exception type leaving the block, if any.

TYPE: type[BaseException] | None

exc

The exception, if any.

TYPE: BaseException | None

tb

Its traceback, if any.

TYPE: object

RAISES DESCRIPTION
RuntimeError

If the handler is not the top of the stack, which means the blocks were exited out of order.

Source code in src/quivers/effects/base.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc: BaseException | None,
    tb: object,
) -> None:
    """Pop the handler off the thread's stack.

    Parameters
    ----------
    exc_type : type[BaseException] | None
        The exception type leaving the block, if any.
    exc : BaseException | None
        The exception, if any.
    tb : object
        Its traceback, if any.

    Raises
    ------
    RuntimeError
        If the handler is not the top of the stack, which means the
        blocks were exited out of order.
    """
    del exc_type, exc, tb
    stack = _handler_stack()
    if not stack or stack[-1] is not self:
        raise RuntimeError(
            "EffectHandler.__exit__: handler stack corruption; "
            "handlers must be entered / exited in strict LIFO order."
        )
    stack.pop()

install abstractmethod

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

Build the lexical handlers this entry installs on a run.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The handlers, each naming the instance it handles.

Source code in src/quivers/effects/base.py
@abstractmethod
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Build the lexical handlers this entry installs on a run.

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

    Returns
    -------
    tuple[Installation, ...]
        The handlers, each naming the instance it handles.
    """

finish

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

Observe the completed run.

PARAMETER DESCRIPTION
run

The run, with every contribution the accumulator received.

TYPE: RunContext

output

The program's output.

TYPE: object

Source code in src/quivers/effects/base.py
def finish(self, run: RunContext, output: object) -> None:
    """Observe the completed run.

    Parameters
    ----------
    run : RunContext
        The run, with every contribution the accumulator received.
    output : object
        The program's output.
    """
    del run, output

handle_chain

handle_chain(installations: list[Installation], inner: Computation) -> Computation

Nest handler installations around a computation, outermost first.

PARAMETER DESCRIPTION
installations

The installations, outermost first.

TYPE: list[Installation]

inner

The computation handled.

TYPE: Computation

RETURNS DESCRIPTION
Computation

The nested Handle terms.

Source code in src/quivers/effects/base.py
def handle_chain(installations: list[Installation], inner: Computation) -> Computation:
    """Nest handler installations around a computation, outermost first.

    Parameters
    ----------
    installations : list[Installation]
        The installations, outermost first.
    inner : Computation
        The computation handled.

    Returns
    -------
    Computation
        The nested ``Handle`` terms.
    """
    body = inner
    for installation in reversed(installations):
        body = Handle(
            instance=installation.instance.entry.instance,
            handler=installation.runtime.definition.id,
            computation=body,
            static_arguments=(),
        )
    return body

fixed_site_values

fixed_site_values() -> dict[str, Tensor] | None

The sites the current stack fixes, when it does nothing else.

RETURNS DESCRIPTION
dict[str, Tensor] or None

The value of each fixed site, the innermost handler's where several fix one; None when a handler on the stack does anything besides fixing sites.

Source code in src/quivers/effects/base.py
def fixed_site_values() -> dict[str, torch.Tensor] | None:
    """The sites the current stack fixes, when it does nothing else.

    Returns
    -------
    dict[str, torch.Tensor] or None
        The value of each fixed site, the innermost handler's where
        several fix one; ``None`` when a handler on the stack does
        anything besides fixing sites.
    """
    fixed: dict[str, torch.Tensor] = {}
    for handler in _handler_stack():
        values = handler.site_values
        if values is None:
            return None
        fixed.update(values)
    return fixed

Cited sources

Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.

Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.