quivers.effects¶
Effect handlers run one probabilistic program under different
interpretations of its requests
(Plotkin and Pretnar, 2009; Ścibior et al., 2018; Nguyen et al., 2023): a draw can be sampled, fixed to
an observation, or replayed from a trace, and a score can be scaled or masked. Each handler is a
lexically scoped handler of the random, score, or param instance of the program's
Quivers Indexed Effect Core (QIEC) computation, so the order and scope of
handlers matter: each
can change what the next one receives.
effects
¶
Algebraic effect handlers for probabilistic programs.
Effect handlers in the Pyro poutine / NumPyro handlers shape,
grounded in the algebraic-effects calculus of
Plotkin and Pretnar 2009
and its probabilistic application in
Scibior et al. 2018 and
Nguyen et al. 2023, and
executed as lexical handlers of the Quivers Indexed Effect Core: a
MonadicProgram runs on the reference machine as the kernel computation
quivers.effects.program_module encodes it to, and every handler here
is a handler of that computation's random, score, or param
instance.
The EffectHandler ABC and the thread-local handler stack live in
quivers.effects.base. Concrete handlers (TraceHandler,
ClampHandler, DoHandler, MaskHandler, ScaleHandler,
BlockHandler, ReplayHandler, LiftHandler, CollapseHandler)
live in per-file modules and are re-exported here along with their
short-name factories. The reparam subpackage collects the
reparameterisation strategies.
The clamp handler is the effect-stack analogue of Pyro's
condition; the name avoids collision with the top-level
quivers.inference.conditioning.condition
factory, which returns a
Conditioned
model wrapper. Both compose observations onto a model; pick
clamp when writing a handler stack, condition when writing a
top-level Conditioned object.
The handler-aware interpreter run_program lives in
quivers.effects.interpreter; the thin quivers.inference.trace.trace
wrapper stacks a TraceHandler on and returns the recorded trace.
CONJUGATE_SOLVERS
module-attribute
¶
CONJUGATE_SOLVERS: Mapping[tuple[str, str], Solver] = {('Normal', 'Normal'): normal_normal, ('Beta', 'Bernoulli'): beta_bernoulli, ('Gamma', 'Poisson'): gamma_poisson, ('Dirichlet', 'Categorical'): dirichlet_categorical}
The closed-form solvers, keyed by (prior family, likelihood family).
SiteKey
¶
The dynamic address of one occurrence of a site: its static identity, its dynamic address frames, and its resumption path.
Solver
¶
Solver = Callable[[Mapping[str, Tensor], Tensor, TorchSampleable, Tensor], Tensor]
A closed-form marginal: given the parent's parameters, the parent's drawn value, the child's sampleable at that value, and the child's value, the log marginal density of the child's value.
SiteAddress
¶
The kernel's dynamic address of one occurrence of a site.
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
PositionLayoutError
¶
Bases: ValueError
A value of a batched callable does not lead with the position axis.
A callable declared batched keeps the position axis leading every
value that depends on the position. A result that does not, or a
validator that refuses a value whose leading axis is not the position
axis, cannot be read per position.
BatchingObstacle
didactic-model
¶
Bases: ValueModel
A step that cannot be evaluated at many positions, and why.
| ATTRIBUTE | DESCRIPTION |
|---|---|
step |
The step: its kind and the names it binds.
TYPE:
|
reason |
Why it cannot.
TYPE:
|
UnbatchableProgramError
¶
UnbatchableProgramError(obstacles: tuple[BatchingObstacle, ...])
Bases: ValueError
A program that cannot be scored at many positions in one pass.
| PARAMETER | DESCRIPTION |
|---|---|
obstacles
|
The steps standing in the way, in program order, and why each does.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
obstacles |
The same.
TYPE:
|
Source code in src/quivers/effects/batching.py
BlockHandler
¶
Bases: EffectHandler
Hide sites from outer handlers.
| PARAMETER | DESCRIPTION |
|---|---|
hide
|
Site names to hide; every site when both arguments are absent.
TYPE:
|
expose
|
Site names to leave visible, hiding every other.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If both |
Source code in src/quivers/effects/block.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install a blocking handler of the random instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The blocking handler. |
Source code in src/quivers/effects/block.py
CheckedProgram
¶
CheckedProgram(domain: AnySpace, codomain: AnySpace, module: QiecModule, name: str, refusal: Exception | None = None, *, prior: bool = False)
Bases: MonadicProgram
A program run as its checked computation on the reference machine.
| PARAMETER | DESCRIPTION |
|---|---|
domain
|
The program's declared domain.
TYPE:
|
codomain
|
The program's declared codomain.
TYPE:
|
module
|
The checked module holding the program's entry point.
TYPE:
|
name
|
The program's name.
TYPE:
|
refusal
|
Why the compiled runtime does not run the program: the located
diagnostic of the call it could not lower to steps;
TYPE:
|
prior
|
Whether the program drops the scores of its observations, which leaves its prior; otherwise each observation with a law is a site, conditioned when it is given and drawn when it is not.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
weights |
The learned weights the program's
TYPE:
|
work |
The work of the last call: its
TYPE:
|
vectorization_obstacle |
Why the last call made one pass per run, or
TYPE:
|
Source code in src/quivers/effects/checked_program.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
refusal
property
¶
Why the compiled runtime does not run the program.
| RETURNS | DESCRIPTION |
|---|---|
Exception
|
The located diagnostic the compiler recorded for the call it could not lower, or one naming the program. |
steps_list_sites
property
¶
No: the sites are those a run of the checked computation reaches.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
module
property
¶
module: QiecModule
The checked module the program runs in.
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The module. |
entry
property
¶
entry: ProgramEntry
The program's elaborated entry point.
| RETURNS | DESCRIPTION |
|---|---|
ProgramEntry
|
The entry. |
kept_data
property
¶
The observations that stay data the program must be given.
| RETURNS | DESCRIPTION |
|---|---|
Mapping[str, str]
|
Each observation the program scores but cannot draw, with why. |
potentials
property
¶
The scores of the program that no law of a site accounts for.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
The structural path, dotted, of every |
potential_sites
property
¶
The trace names of the program's own scores, every one a potential.
| RETURNS | DESCRIPTION |
|---|---|
frozenset[str]
|
|
observed_names
property
¶
The names the program observes.
| RETURNS | DESCRIPTION |
|---|---|
set[str]
|
The labels of its |
prior_program
¶
prior_program() -> CheckedProgram
The program without the scores of its observations.
| RETURNS | DESCRIPTION |
|---|---|
CheckedProgram
|
The program over the same module and learned weights, every observation's density dropped and every draw kept. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an observation's density is added where no bind of the program's body can drop it: inside a computation it calls, or under a branch. |
Source code in src/quivers/effects/checked_program.py
rsample
¶
rsample(x: Tensor, sample_shape: Size = Size(), observations: Mapping[str, object] | None = None) -> Tensor
Run the program forward under the handler stack.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Program input. Shape
TYPE:
|
sample_shape
|
Additional leading sample dimensions; each element is one independent call. |
observations
|
The program's data by parameter name, and the values of the
sites the runs are given, by label or
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The returned values, shape |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the program returns a value that is not a tensor. |
Source code in src/quivers/effects/checked_program.py
has_conditional_density
¶
No: a program's density at its output marginalizes its draws.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Always |
Source code in src/quivers/effects/checked_program.py
log_prob
¶
Log-probability is not defined for a program's output alone.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Program input.
TYPE:
|
y
|
Program output.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
NotImplementedError
|
Always: the density at the output marginalizes every draw. |
Source code in src/quivers/effects/checked_program.py
log_joint
¶
The joint log density at given values for every site.
| PARAMETER | DESCRIPTION |
|---|---|
x
|
Program input. Shape
TYPE:
|
intermediates
|
The program's data by parameter name and a value for every
site the runs reach, by label, or by
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The log joint of each run, shape |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If a site a run reaches is given no value. |
Source code in src/quivers/effects/checked_program.py
__repr__
¶
The program's name and spaces.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The representation. |
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:
|
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:
|
Source code in src/quivers/effects/clamp.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install a conditioning handler of the random instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| 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
CollapseHandler
¶
Bases: EffectHandler
Integrate conjugate parents out of the joint.
| PARAMETER | DESCRIPTION |
|---|---|
pairs
|
Parent site name to child site name.
TYPE:
|
Source code in src/quivers/effects/collapse.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install the collapsing handler of the random instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared, whose observations supply each child's value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The handler, which draws parents without scoring them and scores children under the pair's marginal. |
Source code in src/quivers/effects/collapse.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
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:
|
Source code in src/quivers/effects/do.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The intervening handler. |
Source code in src/quivers/effects/do.py
LiftHandler
¶
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:
|
Source code in src/quivers/effects/lift.py
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:
|
| 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
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
TYPE:
|
Source code in src/quivers/effects/mask.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install a masking transformer of the score instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The transformer. |
Source code in src/quivers/effects/mask.py
ObservationScoringHandler
¶
Bases: EffectHandler
Choose whether declared observations and likelihood factors contribute.
Latent draws and explicit score potentials retain their ordinary scores. Recorded values and raw likelihoods are unchanged; disabling likelihood scoring avoids evaluating that likelihood at all.
| PARAMETER | DESCRIPTION |
|---|---|
enabled
|
Include likelihood scores when true; omit them when false.
TYPE:
|
Source code in src/quivers/effects/observation_scoring.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Set this execution's policy, with innermost scopes taking precedence.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
Isolated per-run state, shared by its native host steps.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
No effect is replaced; existing host boundaries read the policy. |
Source code in src/quivers/effects/observation_scoring.py
HostStep
didactic-model
¶
HostStep(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), kind: str, spec: Step | None = field(opaque=True, extras=OPAQUE_BY_IDENTITY), environment: tuple[str, ...], answer_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), site: str | None, program: MonadicProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), scanned: bool, position: int)
Bases: QiecModel
One host part of the program, as the runtime provider serves it.
Kernel types and effect identities compare by value. The executable program and its step specification retain their runtime identities.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The
TYPE:
|
effect
|
The applied
TYPE:
|
kind
|
TYPE:
|
spec
|
The step record the host part serves, or
TYPE:
|
environment
|
The names of the locals the step reads, in the order the environment tuple carries them.
TYPE:
|
answer_type
|
The type the host part returns.
TYPE:
|
site
|
The site label of a draw step or a site address, else
TYPE:
|
program
|
The program
TYPE:
|
scanned
|
Whether the step runs once per position of a scan.
TYPE:
|
position
|
The step's position among the kernel's host steps.
TYPE:
|
ProgramKernel
didactic-model
¶
ProgramKernel(*, module: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), program: MonadicProgram = field(opaque=True, extras=OPAQUE_BY_IDENTITY), steps: tuple[HostStep, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), sites: tuple[str, ...], site_types: dict[str, TypeExpr] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), data: tuple[str, ...], random: NamedEffectInstance = field(opaque=True, extras=OPAQUE_BY_VALUE), score: NamedEffectInstance = field(opaque=True, extras=OPAQUE_BY_VALUE), param: NamedEffectInstance = field(opaque=True, extras=OPAQUE_BY_VALUE), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), locals: dict[str, Local] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), scanned: frozenset[str] = field(default=frozenset(), opaque=True, extras=OPAQUE_BY_VALUE), site_morphisms: dict[str, ContinuousMorphism] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), site_events: dict[str, tuple[int, ...]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: QiecModel
A program's computation with the record the runtime needs to serve it.
The checked module, host-step records, and effect instances compare by value. Live programs, morphisms, and lookup tables retain identity.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The kernel module: the interfaces, the instances, the entry computation first, and the helper computation of each scan, without handlers; a run adds its own.
TYPE:
|
program
|
The program encoded.
TYPE:
|
steps
|
The host steps, in body order.
TYPE:
|
sites
|
The site label of every draw, in order; a site reached once per scan position is listed once, under its label.
TYPE:
|
site_types
|
The value type of each site, by label.
TYPE:
|
data
|
The names of the host data inputs after the program's input, in parameter order.
TYPE:
|
random
|
The canonical
TYPE:
|
score
|
The canonical
TYPE:
|
param
|
The canonical
TYPE:
|
result_type
|
The entry computation's result type.
TYPE:
|
locals
|
The entry computation's local for each name the program binds.
TYPE:
|
scanned
|
The labels of the sites reached once per scan position, whose
occurrences are addressed
TYPE:
|
site_morphisms
|
The morphism each site draws from, by label.
TYPE:
|
site_events
|
The event shape of one value of each site, by label:
TYPE:
|
ReplayHandler
¶
ReplayHandler(trace: Trace)
Bases: EffectHandler
Replay the values of a recorded trace.
| PARAMETER | DESCRIPTION |
|---|---|
trace
|
The trace whose site values are reinstalled.
TYPE:
|
Source code in src/quivers/effects/replay.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install a scoring replay handler of the random instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| 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
ScaleHandler
¶
Bases: EffectHandler
Multiply every density contribution by a scalar.
| PARAMETER | DESCRIPTION |
|---|---|
factor
|
The multiplier.
TYPE:
|
Source code in src/quivers/effects/scale.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install a scaling transformer of the score instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The transformer. |
Source code in src/quivers/effects/scale.py
TorchSampleable
¶
TorchSampleable(*, morphism: ContinuousMorphism, input: Tensor, declared: ContinuousMorphism | None = None, raw_morphism: ContinuousMorphism | None = None)
Bases: ValueModel
A morphism applied to an input, offered to the kernel as a sampleable.
| PARAMETER | DESCRIPTION |
|---|---|
morphism
|
The morphism the site draws from, under whatever parameters the
run's
TYPE:
|
input
|
The input tensor the morphism is conditioned on, carrying the batch axis.
TYPE:
|
declared
|
The morphism as the program declares it, which a trace records and a strategy reads the family of; the drawing morphism itself when no parameter store rebinds it.
TYPE:
|
raw_morphism
|
The parameterized response distribution before likelihood weighting or observation subsampling, used for raw likelihood extraction.
TYPE:
|
Construct a sampleable holding live runtime references by identity.
| PARAMETER | DESCRIPTION |
|---|---|
morphism
|
The morphism used for sampling and scoring.
TYPE:
|
input
|
The tensor conditioning the morphism.
TYPE:
|
declared
|
The declared site morphism, defaulting to the sampling morphism.
TYPE:
|
raw_morphism
|
The unweighted response morphism, defaulting to the sampling morphism.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValidationError
|
If the runtime fields have incompatible types. |
Source code in src/quivers/effects/sites.py
rsample
¶
rsample() -> Tensor
Draw a reparameterised sample.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
One draw per batch row. |
log_prob
¶
parameters
¶
parameters() -> dict[str, Tensor]
The distribution parameters the morphism computes at the input.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Tensor]
|
The named parameters of the torch distribution the morphism
builds, or |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the morphism exposes neither a distribution builder nor a location-scale pair. |
Source code in src/quivers/effects/sites.py
raw_log_prob_pointwise
¶
Read the response density before likelihood weighting or subsampling.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The observed response values.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Raw log densities, one per observation row when the family has a plate, with event dimensions reduced. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the site is the response of a marginalized block, whose density the units of the block's score hold. |
Source code in src/quivers/effects/sites.py
UnfactoredObservationError
¶
Bases: TypeError
An observation's rows have no log likelihoods of their own.
The message says why the rows do not factor, and which program has a log likelihood per row.
SiteUnits
didactic-model
¶
SiteUnits(*, factorization: UnitFactorization = field(opaque=True, extras=OPAQUE_BY_VALUE), environment: dict[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), occurrence: str = '')
Bases: ValueModel
The units of one score site, at the values of one run.
| PARAMETER | DESCRIPTION |
|---|---|
factorization
|
What the score step declares.
TYPE:
|
environment
|
The run's values the factorization reads.
TYPE:
|
occurrence
|
The suffix of the site's occurrence,
TYPE:
|
axes
property
¶
The objects whose product indexes the units.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
The names, outermost first; empty for a score with one unit. |
sizes
property
¶
The extent of each unit axis.
| RETURNS | DESCRIPTION |
|---|---|
tuple[int, ...]
|
The extents. |
responses
property
¶
The labels of the responses whose rows the units hold.
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
The labels, in the order the program observes them. |
log_weights
¶
log_weights() -> Tensor
The log weight of each unit, as the site scored it.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The weights, of shape |
Source code in src/quivers/effects/units.py
log_likelihood
¶
log_likelihood() -> Tensor
The log density of each unit's rows given the run's latents.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The log densities, of shape |
| RAISES | DESCRIPTION |
|---|---|
UnfactoredObservationError
|
If the score's weights are not log densities. |
Source code in src/quivers/effects/units.py
row_units
¶
row_units(response: str) -> Tensor
The unit each row of a response belongs to.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The response's label.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the score reads no such response. |
Source code in src/quivers/effects/units.py
row_log_likelihood
¶
row_log_likelihood(response: str) -> Tensor
The log likelihood of each row of a response, where it exists.
A row has one when its unit holds that row and no other row of any response of the score. The log likelihood of the row is then the log weight of its unit.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The response's label.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the score reads no such response. |
UnfactoredObservationError
|
If a unit holds several rows, or the score's weights are not log densities. |
Source code in src/quivers/effects/units.py
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 (
TYPE:
|
index
|
The rows scored: a nonempty one-dimensional integer tensor of distinct rows in increasing order.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/effects/subsample.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Register the plate's subset on the run.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| 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
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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
One forwarding observer of the |
Source code in src/quivers/effects/trace_handler.py
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:
|
output
|
The program's output, which the trace does not read; the
wrapper that stacks this handler sets
TYPE:
|
Source code in src/quivers/effects/trace_handler.py
total_log_joint
¶
Sum every site's density into the joint, one per run.
| PARAMETER | DESCRIPTION |
|---|---|
device
|
Device the accumulator seeds on.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The joint log-density of each run, shape |
Source code in src/quivers/effects/trace_handler.py
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:
|
morphism
|
The distribution morphism (
TYPE:
|
value
|
The sampled, observed, or computed tensor. A site drawn from a finite structured law keeps its one typed point as a value.
TYPE:
|
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:
|
is_observed
|
Whether this site was conditioned on an observed value.
TYPE:
|
is_deterministic
|
Whether this is a let binding, a score step, or an intervened site.
TYPE:
|
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:
|
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:
|
metadata
|
Annotations handlers attached to the site.
TYPE:
|
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:
|
is_structured
property
¶
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:
|
output
|
The program's return value.
TYPE:
|
log_joint
|
Sum of log-densities across all sites. Shape
TYPE:
|
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. |
ConjugateReparam
¶
Bases: Reparam
Score a child site under the conjugate marginal of its parent.
Applied to the child site of a conjugate pair, the strategy answers
the site with the run's observation for it, or a draw from the
child's own sampleable when there is none, and scores it under the
closed-form marginal that integrates the parent out, read from the
parent's parameters as the orchestrator saw them. The parent's own
density is left in the joint; collapse the parent with
quivers.effects.collapse when the marginal joint is wanted.
| PARAMETER | DESCRIPTION |
|---|---|
parent
|
The parent site's name.
TYPE:
|
parent_family
|
The parent's family.
TYPE:
|
child_family
|
The child's family.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the pair has no registered marginal. |
Source code in src/quivers/effects/reparam/conjugate.py
apply
¶
apply(site: SiteRequest) -> tuple[Tensor, Tensor]
Rewrite the child site.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The child site.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The value and its marginal log density. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the orchestrator has not seen the parent site. |
ValueError
|
If the parent or the child is not of the declared family. |
Source code in src/quivers/effects/reparam/conjugate.py
LocScaleReparam
¶
Bases: Reparam
Non-centred rewrite for location-scale sample sites.
The site's morphism must expose a _get_params(x) method returning
(loc, scale) tensors of the same shape, the convention every
ConditionalNormal-shaped family in
quivers.continuous.families follows.
| PARAMETER | DESCRIPTION |
|---|---|
centered
|
Interpolation between fully centred (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/effects/reparam/loc_scale.py
apply
¶
apply(site: SiteRequest) -> tuple[Tensor, Tensor]
Rewrite one site.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The site.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The value and its log density under |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the site's morphism exposes no |
Source code in src/quivers/effects/reparam/loc_scale.py
NeuTraReparam
¶
NeuTraReparam(guide: AutoNormalizingFlow)
Bases: Reparam
Reparameterise sites through a trained normalizing-flow guide.
One strategy object serves every site of the guide it is installed
on, as in reparam({"a": neutra, "b": neutra}): within a run the
sites share one draw (NeuTraDraw), taken at the first covered site
the run reaches and discarded when the next run begins
(Reparam.begin_run). A site the guide does not cover, or a site
whose value an enclosing handler fixed, is drawn or taken as given
and scored under its own density.
| PARAMETER | DESCRIPTION |
|---|---|
guide
|
A trained flow guide (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
Source code in src/quivers/effects/reparam/neutra.py
current_draw
property
¶
current_draw: NeuTraDraw | None
The draw the current run's covered sites take.
| RETURNS | DESCRIPTION |
|---|---|
NeuTraDraw | None
|
The draw, or |
begin_run
¶
push
¶
push(base: Tensor) -> NeuTraDraw
Map a base point to the guide's sites.
| PARAMETER | DESCRIPTION |
|---|---|
base
|
The base point :math:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NeuTraDraw
|
The sites' values :math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/effects/reparam/neutra.py
draw
¶
draw() -> NeuTraDraw
Draw a base point from the standard Normal and push it.
| RETURNS | DESCRIPTION |
|---|---|
NeuTraDraw
|
The draw. |
Source code in src/quivers/effects/reparam/neutra.py
apply
¶
apply(site: SiteRequest) -> tuple[Tensor, Tensor]
Rewrite one site.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The site.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The site's value, from the run's draw for a covered site whose value is not given, shaped as the site's own draws; and its log density under the site's sampleable. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a covered site's input has more than one row, since one run draws it once. |
Source code in src/quivers/effects/reparam/neutra.py
Reparam
¶
Bases: ABC
Base class for site-level reparameterisation strategies.
A strategy is a policy, not a handler. The ReparamOrchestrator
handler dispatches each covered site to the matching strategy and
installs the strategy's value and density on the site. Subclasses
override :meth:apply.
begin_run
¶
Start a run of the program.
The ReparamOrchestrator calls this once per run, before the
run's first site, for every strategy it holds. A strategy whose
sites share one draw within a run (NeuTraReparam) discards the
previous run's draw here; a strategy without per-run state has
nothing to do, which this default states.
Source code in src/quivers/effects/reparam/base.py
apply
abstractmethod
¶
apply(site: SiteRequest) -> tuple[Tensor, Tensor]
Rewrite one site.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The site, with a value fixed when one is given.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The value the site takes, in the site's original space so downstream sites see the intended value, and the density a downstream sampler should score the site with. |
Source code in src/quivers/effects/reparam/base.py
ReparamOrchestrator
¶
ReparamOrchestrator(strategies: dict[str, Reparam])
Bases: EffectHandler
Dispatch sample sites to per-site reparam strategies.
| PARAMETER | DESCRIPTION |
|---|---|
strategies
|
Site name to strategy.
TYPE:
|
Source code in src/quivers/effects/reparam/base.py
install
¶
install(run: RunContext) -> tuple[Installation, ...]
Install the dispatching handler of the random instance.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
The run being prepared.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Installation, ...]
|
The handler, which answers covered sites and forwards the rest. |
Source code in src/quivers/effects/reparam/base.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
SiteRequest
didactic-model
¶
SiteRequest(*, name: str, sampleable: TorchSampleable = field(opaque=True, extras=OPAQUE_BY_VALUE), given: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), seen: Mapping[str, TorchSampleable] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), observation: Tensor | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
What a strategy is given for one sample site.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The site's name.
TYPE:
|
sampleable
|
The site's distribution at its input.
TYPE:
|
given
|
A value the site is to take, when an enclosing strategy or a
caller fixed one;
TYPE:
|
seen
|
The sampleables of the sites the orchestrator saw before this one, by name, so a strategy may read a parent's parameters.
TYPE:
|
observation
|
The run's observation for the site, if any.
TYPE:
|
with_value
¶
with_value(value: Tensor) -> SiteRequest
The same request with a value fixed.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The value the site is to take.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SiteRequest
|
The request with |
Source code in src/quivers/effects/reparam/base.py
TransformReparam
¶
TransformReparam(bijector: Bijector)
Bases: Reparam
Reparameterise a sample site through a fixed bijector.
The reparameterised base sample lives in the bijector's domain and the site's value in its codomain. The joint density remains that of the original distribution: the strategy scores the value under the site's own sampleable, and the bijector reshapes the sampling geometry a downstream sampler works in.
| PARAMETER | DESCRIPTION |
|---|---|
bijector
|
The measurable bijection
TYPE:
|
Source code in src/quivers/effects/reparam/transform.py
apply
¶
apply(site: SiteRequest) -> tuple[Tensor, Tensor]
Rewrite one site.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The site.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
The value, drawn from the site's sampleable unless given, and its log density under the sampleable. |
Source code in src/quivers/effects/reparam/transform.py
batching_obstacles
¶
batching_obstacles(program: MonadicProgram, latents: Collection[str], given: Collection[str]) -> tuple[BatchingObstacle, ...]
The steps of a program that cannot be evaluated at many positions.
| PARAMETER | DESCRIPTION |
|---|---|
program
|
The program.
TYPE:
|
latents
|
The sites whose values the position gives.
TYPE:
|
given
|
The sites and host data whose values every position shares.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[BatchingObstacle, ...]
|
One entry per step, in the order the program runs them, those of the programs it calls and scans included. Empty for a program that can be scored at many positions. |
Source code in src/quivers/effects/batching.py
machine_value_admitted
¶
Whether a handler's answer is a value the machine holds.
Every number the machine holds is a tensor, so an answer that is a Python number would enter the computation without the run's dtype and without a gradient; it is refused where it enters.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The answer.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
Source code in src/quivers/effects/checked_program.py
family_of
¶
family_of(sampleable: TorchSampleable) -> str
The registry family a sampleable's morphism draws from.
| PARAMETER | DESCRIPTION |
|---|---|
sampleable
|
The sampleable.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The family's registry name. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the morphism's class is registered for no family. |
Source code in src/quivers/effects/conjugate.py
normal_normal
¶
normal_normal(parent: Mapping[str, Tensor], parent_value: Tensor, child: TorchSampleable, value: Tensor) -> Tensor
The marginal of y ~ Normal(z, tau) under z ~ Normal(mu, sigma).
| PARAMETER | DESCRIPTION |
|---|---|
parent
|
The parent's
TYPE:
|
parent_value
|
The parent's drawn value.
TYPE:
|
child
|
The child at the parent's drawn value, whose
TYPE:
|
value
|
The child's value.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the child's location is not the parent's value. |
Source code in src/quivers/effects/conjugate.py
beta_bernoulli
¶
beta_bernoulli(parent: Mapping[str, Tensor], parent_value: Tensor, child: TorchSampleable, value: Tensor) -> Tensor
The marginal of y ~ Bernoulli(z) under z ~ Beta(a, b).
| PARAMETER | DESCRIPTION |
|---|---|
parent
|
The parent's
TYPE:
|
parent_value
|
The parent's drawn value.
TYPE:
|
child
|
The child at the parent's drawn value.
TYPE:
|
value
|
The child's value, zero or one.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the child's probability is not the parent's value. |
Source code in src/quivers/effects/conjugate.py
gamma_poisson
¶
gamma_poisson(parent: Mapping[str, Tensor], parent_value: Tensor, child: TorchSampleable, value: Tensor) -> Tensor
The marginal of y ~ Poisson(z) under z ~ Gamma(alpha, beta).
| PARAMETER | DESCRIPTION |
|---|---|
parent
|
The parent's
TYPE:
|
parent_value
|
The parent's drawn value.
TYPE:
|
child
|
The child at the parent's drawn value.
TYPE:
|
value
|
The child's count.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The negative binomial log mass with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the child's rate is not the parent's value. |
Source code in src/quivers/effects/conjugate.py
dirichlet_categorical
¶
dirichlet_categorical(parent: Mapping[str, Tensor], parent_value: Tensor, child: TorchSampleable, value: Tensor) -> Tensor
The marginal of y ~ Categorical(z) under z ~ Dirichlet(alpha).
| PARAMETER | DESCRIPTION |
|---|---|
parent
|
The parent's
TYPE:
|
parent_value
|
The parent's drawn value.
TYPE:
|
child
|
The child at the parent's drawn value.
TYPE:
|
value
|
The child's category.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the child's probabilities are not the parent's value. |
Source code in src/quivers/effects/conjugate.py
conjugate_solver
¶
conjugate_solver(parent_family: str, child_family: str) -> Solver
The solver of a conjugate pair.
| PARAMETER | DESCRIPTION |
|---|---|
parent_family
|
The parent's family.
TYPE:
|
child_family
|
The child's family.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Solver
|
The closed-form marginal. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the pair has no registered marginal. |
Source code in src/quivers/effects/conjugate.py
run_program
¶
run_program(program: MonadicProgram, x: Tensor, observations: Mapping[str, Tensor] | None = None) -> Tensor | dict[str, Tensor]
Execute a program on the reference machine under the handler stack.
An input of B rows is B independent runs of the whole program.
Each run reads its slice of every value given one per run (a leading
axis of length B) and the whole of every value the runs share;
the handlers on the stack are installed on every run, and the runs'
outputs stack along a leading run axis.
| PARAMETER | DESCRIPTION |
|---|---|
program
|
Program to execute.
TYPE:
|
x
|
Program input. Shape
TYPE:
|
observations
|
Values to condition observed sites on, keyed by site name. Undeclared keys are host data the program's steps read by name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or dict[str, Tensor]
|
The program's return value: the single returned variable, or the returned variables keyed by their labels. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an observation names one variable of a destructuring draw, or a value is given for an occurrence of a scanned site the run never reaches. |
Source code in src/quivers/effects/interpreter.py
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 | |
observations_scored
¶
observations_scored(run: RunContext) -> bool
Read the innermost scoring policy installed for this execution.
| PARAMETER | DESCRIPTION |
|---|---|
run
|
Isolated execution annotations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether observation likelihoods contribute. |
Source code in src/quivers/effects/observation_scoring.py
program_kernel
¶
program_kernel(program: MonadicProgram, data: Sequence[str] = ()) -> ProgramKernel
Encode a program as a kernel module.
| PARAMETER | DESCRIPTION |
|---|---|
program
|
The program.
TYPE:
|
data
|
The names of the host data inputs a run supplies beside the program's input, in parameter order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ProgramKernel
|
The module and the record the runtime serves it by. |
Source code in src/quivers/effects/program_module.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.
Adam Ścibior, Ohad Kammar, and Zoubin Ghahramani. Functional Programming for Modular Bayesian Inference. Proceedings of the ACM on Programming Languages, 2(ICFP):83:1–83:29, 2018. URL: https://doi.org/10.1145/3236778, doi:10.1145/3236778.
Minh Nguyen, Roly Perera, Meng Wang, and Steven Ramsay. Effect Handlers for Programmable Inference. In Proceedings of the 16th ACM SIGPLAN International Haskell Symposium. ACM, 2023. URL: https://doi.org/10.1145/3609026.3609729, doi:10.1145/3609026.3609729.