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
¶
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:
|
role
|
What the contribution was for, from the emitting handler's provenance: a scored draw, a conditioned observation, a replay.
TYPE:
|
weight
|
The contribution as it arrived, after every transformer.
TYPE:
|
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:
|
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:
|
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:
|
validator
|
The host value validator every handler's clauses check with.
TYPE:
|
contributions
|
The score contributions that reached the accumulator, in order.
TYPE:
|
interventions
|
The sites an intervention fixed, by address.
TYPE:
|
fixed
|
The labels of the same sites, an occurrence of a site a scan
reaches once per position as
TYPE:
|
annotations
|
Per-site annotations handlers attach, keyed by site label.
TYPE:
|
parameters
|
The learned parameters of the program's morphisms by qualified name, as the parameter store answers them.
TYPE:
|
observations
|
The run's observations at declared sites, by site label. A checked finite law may observe a typed structured value.
TYPE:
|
supplied
|
Values standing in for let bindings, by name, which their steps read rather than compute.
TYPE:
|
occurrences
|
How many times the run has reached each site a scan reaches once per position, by label.
TYPE:
|
reached
|
The addresses
TYPE:
|
run_index
|
The position of this run among the runs of one call: an input of
TYPE:
|
runs
|
The number of runs the call makes,
TYPE:
|
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:
|
carries_run_axis
|
Whether a binding of a program, by name, carries this run's leading axis of length one.
TYPE:
|
site_carries_run_axis
|
Whether a site's value in this run, by label, carries the run's leading axis of length one.
TYPE:
|
vectorized
|
Whether this execution carries all
TYPE:
|
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
TYPE:
|
subsamples
|
The rows of each subsampled plate the run scores, by plate name,
as the
TYPE:
|
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:
|
Source code in src/quivers/effects/base.py
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;
TYPE:
|
| 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
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:
|
| 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
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
TYPE:
|
runtime
|
The executable handler, whose definition joins the run's module.
TYPE:
|
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:
|
| 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
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; |
__enter__
¶
Push the handler on the thread's stack.
| RETURNS | DESCRIPTION |
|---|---|
Self
|
The handler, so |
__exit__
¶
Pop the handler off the thread's stack.
| PARAMETER | DESCRIPTION |
|---|---|
exc_type
|
The exception type leaving the block, if any.
TYPE:
|
exc
|
The exception, if any.
TYPE:
|
tb
|
Its traceback, if any.
TYPE:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The handlers, each naming the instance it handles. |
Source code in src/quivers/effects/base.py
finish
¶
finish(run: RunContext, output: object) -> None
Observe the completed run.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run, with every contribution the accumulator received.
TYPE:
|
output
|
The program's output.
TYPE:
|
Source code in src/quivers/effects/base.py
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:
|
inner
|
The computation handled.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Computation
|
The nested |
Source code in src/quivers/effects/base.py
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; |
Source code in src/quivers/effects/base.py
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.