Skip to content

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

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.

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

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

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: 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

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

BatchingObstacle(*, step: str, reason: str)

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: str

reason

Why it cannot.

TYPE: str

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: tuple[BatchingObstacle, ...]

ATTRIBUTE DESCRIPTION
obstacles

The same.

TYPE: tuple[BatchingObstacle, ...]

Source code in src/quivers/effects/batching.py
def __init__(self, obstacles: tuple[BatchingObstacle, ...]) -> None:
    self.obstacles = obstacles
    listed = "; ".join(f"{item.step}: {item.reason}" for item in obstacles)
    super().__init__(
        f"the program cannot be scored at many positions in one pass: {listed}"
    )

BlockHandler

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

Bases: EffectHandler

Hide sites from outer handlers.

PARAMETER DESCRIPTION
hide

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

TYPE: list[str] or None DEFAULT: None

expose

Site names to leave visible, hiding every other.

TYPE: list[str] or None DEFAULT: None

RAISES DESCRIPTION
ValueError

If both hide and expose are given.

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

install

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

Install a blocking handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The blocking handler.

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

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

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

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: AnySpace

codomain

The program's declared codomain.

TYPE: AnySpace

module

The checked module holding the program's entry point.

TYPE: QiecModule

name

The program's name.

TYPE: str

refusal

Why the compiled runtime does not run the program: the located diagnostic of the call it could not lower to steps; None gives one naming the program.

TYPE: Exception | None DEFAULT: None

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: bool DEFAULT: False

ATTRIBUTE DESCRIPTION
weights

The learned weights the program's Param instance answers, by name, registered so an optimizer sees them. A name it does not hold reads as zero.

TYPE: ParameterDict

work

The work of the last call: its iterations are the machine passes it made, one for a call whose runs were made together and one per run otherwise.

TYPE: WorkReport

vectorization_obstacle

Why the last call made one pass per run, or None when it made one pass, or had one run.

TYPE: str or None

Source code in src/quivers/effects/checked_program.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    module: QiecModule,
    name: str,
    refusal: Exception | None = None,
    *,
    prior: bool = False,
) -> None:
    super().__init__(domain, codomain, (), (name,))
    self._module = module
    self._name = name
    self._entry: ProgramEntry = program_entry(module, name)
    self._computation = _computation(module, self._entry)
    self._refusal = refusal
    self.input_contract = self._entry
    self.weights = nn.ParameterDict()
    random = _instance(module, "Random")
    score = _instance(module, "Score")
    if random is None or score is None:
        raise ValueError(
            f"program {name!r} has no canonical random and score instances"
        )
    self._random = random
    self._score = score
    self._prior = prior
    # Each observation scored at the top of the body under a law of its
    # own becomes a draw of that law at its site, or, for the prior,
    # leaves the program; the prior, and a run whose likelihood a
    # handler turns off, drop every other observation density too.
    self._laws = observation_variant(
        module,
        self._computation,
        self._entry,
        random,
        score.entry.instance,
        drop=prior,
        likelihoods=not prior,
    )
    self._unscored = observation_variant(
        module,
        self._computation,
        self._entry,
        random,
        score.entry.instance,
        drop=prior,
        likelihoods=False,
    )
    self._param = _instance(module, "Param")
    # A program that reads no learned weight performs no Param
    # instance; the kernel's is then one the program never performs,
    # so nothing installed on it reaches the run.
    param = self._param or NamedEffectInstance(
        name=PARAM_INSTANCE,
        entry=instantiate_effect(
            PARAM, module=module.module, lexical_path=("instances", PARAM_INSTANCE)
        ),
        origin=SourceOrigin(
            module=module.module,
            structural_path=("instances", PARAM_INSTANCE),
            role="effect-instance",
            source_protocol=module.source_protocol,
        ),
    )
    self._kernel = ProgramKernel(
        module=module,
        program=self,
        steps=(),
        sites=tuple(site.name for site in self._entry.sites),
        site_types={},
        data=tuple(parameter.name for parameter in self._entry.parameters),
        random=random,
        score=score,
        param=param,
        result_type=self._computation.type.result,
    )
    self._run_modules: dict[
        tuple[object, ...], tuple[QiecModule, KernelRegistry]
    ] = {}
    self._provider = CoreRuntimeProvider()
    self._foreign = CoreRuntimeProvider(
        options={
            "handlers": foreign_handler_configuration(
                module, reached=reached_handlers(module, self._computation.id)
            )
        }
    )
    self._kernels: dict[tuple[StaticArgument, ...], ProgramKernel] = {}
    self.work = WorkReport(phase=Phase.EXECUTION)
    self.vectorization_obstacle: str | None = None

refusal property

refusal: Exception

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

steps_list_sites: bool

No: the sites are those a run of the checked computation reaches.

RETURNS DESCRIPTION
bool

False; how many sites a run reaches, and which, may depend on the values it draws.

module property

module: QiecModule

The checked module the program runs in.

RETURNS DESCRIPTION
QiecModule

The module.

name property

name: str

The program's name.

RETURNS DESCRIPTION
str

The name.

entry property

entry: ProgramEntry

The program's elaborated entry point.

RETURNS DESCRIPTION
ProgramEntry

The entry.

kept_data property

kept_data: Mapping[str, str]

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

potentials: tuple[str, ...]

The scores of the program that no law of a site accounts for.

RETURNS DESCRIPTION
tuple[str, ...]

The structural path, dotted, of every Score request a run makes, in the program's computation or one it calls, that adds neither the density of an observe site's law nor a value computed from such densities, as a marginalization block's total is. Empty when the computation performs no score at all.

potential_sites property

potential_sites: frozenset[str]

The trace names of the program's own scores, every one a potential.

RETURNS DESCRIPTION
frozenset[str]

"score:<path>" for each score the program adds that is not an observation's density: a trace records such a score as a deterministic site of that name, and it belongs to the prior.

observed_names property

observed_names: set[str]

The names the program observes.

RETURNS DESCRIPTION
set[str]

The labels of its observe sites.

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
def prior_program(self) -> CheckedProgram:
    """The program without the scores of its observations.

    Returns
    -------
    CheckedProgram
        The program over the same module and learned weights, every
        observation's density dropped and every draw kept.

    Raises
    ------
    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.
    """
    if self._unscored.unremoved:
        raise ValueError(_unremoved(self._name, self._unscored.unremoved))
    prior = CheckedProgram(
        self.domain,
        self.codomain,
        self._module,
        self._name,
        self._refusal,
        prior=True,
    )
    prior.weights = self.weights
    return prior

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 (batch, ...): one run per row.

TYPE: Tensor

sample_shape

Additional leading sample dimensions; each element is one independent call.

TYPE: Size DEFAULT: Size()

observations

The program's data by parameter name, and the values of the sites the runs are given, by label or "<label>@<n>"; a value leading with the run axis is one per run. Every other site is drawn.

TYPE: Mapping[str, object] or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The returned values, shape (*sample_shape, batch, ...), with the gradient of every tensor the runs were given.

RAISES DESCRIPTION
TypeError

If the program returns a value that is not a tensor.

Source code in src/quivers/effects/checked_program.py
def rsample(  # type: ignore[override]
    self,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
    observations: Mapping[str, object] | None = None,
) -> torch.Tensor:
    """Run the program forward under the handler stack.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``: one run per row.
    sample_shape : torch.Size
        Additional leading sample dimensions; each element is one
        independent call.
    observations : Mapping[str, object] or None
        The program's data by parameter name, and the values of the
        sites the runs are given, by label or ``"<label>@<n>"``; a
        value leading with the run axis is one per run. Every other
        site is drawn.

    Returns
    -------
    torch.Tensor
        The returned values, shape ``(*sample_shape, batch, ...)``,
        with the gradient of every tensor the runs were given.

    Raises
    ------
    TypeError
        If the program returns a value that is not a tensor.
    """
    given = dict(observations or {})
    # Draws differ between the runs of one pass, so the runs of a call
    # are one pass unless a handler on the stack may watch each run.
    apart = OBSERVED_APART if _handler_stack() else None
    calls = [
        self._calls(x, given, joint=False, apart=apart)
        for _ in range(max(math.prod(sample_shape), 1))
    ]
    stacked = torch.stack(calls)
    if not sample_shape:
        return stacked[0]
    return stacked.reshape((*sample_shape, *stacked.shape[1:]))

has_conditional_density

has_conditional_density() -> bool

No: a program's density at its output marginalizes its draws.

RETURNS DESCRIPTION
bool

Always False; log_joint scores the draws themselves.

Source code in src/quivers/effects/checked_program.py
def has_conditional_density(self) -> bool:
    """No: a program's density at its output marginalizes its draws.

    Returns
    -------
    bool
        Always ``False``;
        [`log_joint`][quivers.effects.checked_program.CheckedProgram.log_joint]
        scores the draws themselves.
    """
    return False

log_prob

log_prob(x: Tensor, y: Tensor) -> Tensor

Log-probability is not defined for a program's output alone.

PARAMETER DESCRIPTION
x

Program input.

TYPE: Tensor

y

Program output.

TYPE: Tensor

RAISES DESCRIPTION
NotImplementedError

Always: the density at the output marginalizes every draw.

Source code in src/quivers/effects/checked_program.py
def log_prob(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    """Log-probability is not defined for a program's output alone.

    Parameters
    ----------
    x : torch.Tensor
        Program input.
    y : torch.Tensor
        Program output.

    Raises
    ------
    NotImplementedError
        Always: the density at the output marginalizes every draw.
    """
    del x, y
    raise NotImplementedError(
        "log_prob is not supported for programs; computing p(y | x) "
        "requires marginalizing over all intermediate draws. Use "
        "log_joint with a value for every site."
    )

log_joint

log_joint(x: Tensor, intermediates: Mapping[str, object]) -> Tensor

The joint log density at given values for every site.

PARAMETER DESCRIPTION
x

Program input. Shape (batch, ...): one run per row.

TYPE: Tensor

intermediates

The program's data by parameter name and a value for every site the runs reach, by label, or by "<label>@<n>" for a site a run reaches more than once.

TYPE: Mapping[str, object]

RETURNS DESCRIPTION
Tensor

The log joint of each run, shape (batch,), with the gradient of every value given.

RAISES DESCRIPTION
KeyError

If a site a run reaches is given no value.

Source code in src/quivers/effects/checked_program.py
def log_joint(
    self, x: torch.Tensor, intermediates: Mapping[str, object]
) -> torch.Tensor:
    """The joint log density at given values for every site.

    Parameters
    ----------
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``: one run per row.
    intermediates : Mapping[str, object]
        The program's data by parameter name and a value for every
        site the runs reach, by label, or by ``"<label>@<n>"`` for a
        site a run reaches more than once.

    Returns
    -------
    torch.Tensor
        The log joint of each run, shape ``(batch,)``, with the
        gradient of every value given.

    Raises
    ------
    KeyError
        If a site a run reaches is given no value.
    """
    if fixed_site_values() is not None:
        # The stack only fixes sites, so the joint is what each run's
        # accumulator receives, and no run's values are recorded.
        return self._calls(x, dict(intermediates), joint=True, apart=None)
    with TraceHandler() as handler:
        self.rsample(x, observations=intermediates)
    for name, site in handler.trace.sites.items():
        if (
            site.sampleable is not None
            and not site.is_observed
            and not site.is_deterministic
        ):
            raise KeyError(name)
    return handler.total_log_joint(x.device)

__repr__

__repr__() -> str

The program's name and spaces.

RETURNS DESCRIPTION
str

The representation.

Source code in src/quivers/effects/checked_program.py
def __repr__(self) -> str:
    """The program's name and spaces.

    Returns
    -------
    str
        The representation.
    """
    return f"CheckedProgram({self._name!r}: {self.domain!r} -> {self.codomain!r})"

ClampHandler

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

Bases: EffectHandler

Condition named sample sites on given values.

PARAMETER DESCRIPTION
data

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

TYPE: dict[str, Tensor]

missing

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

TYPE: MissingValuePolicy DEFAULT: FORWARD

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

install

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

Install a conditioning handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

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

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

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

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

CollapseHandler

CollapseHandler(pairs: dict[str, str] | None = None)

Bases: EffectHandler

Integrate conjugate parents out of the joint.

PARAMETER DESCRIPTION
pairs

Parent site name to child site name. None collapses nothing and only carries the solver registry for introspection.

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

Source code in src/quivers/effects/collapse.py
def __init__(self, pairs: dict[str, str] | None = None) -> None:
    self.pairs = dict(pairs) if pairs is not None else {}
    self.registry = CONJUGATE_SOLVERS

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: RunContext

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
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Install the collapsing handler of the ``random`` instance.

    Parameters
    ----------
    run : RunContext
        The run being prepared, whose observations supply each
        child's value.

    Returns
    -------
    tuple[Installation, ...]
        The handler, which draws parents without scoring them and
        scores children under the pair's marginal.
    """
    kernel = run.kernel
    children = {child: parent for parent, child in self.pairs.items()}
    parents: dict[str, tuple[TorchSampleable, torch.Tensor]] = {}
    score_instance = kernel.score.entry.instance
    definition = _handler_def(
        "Random.collapse",
        RANDOM,
        ((RANDOM_SAMPLE, ResumptionGrade.LINEAR),),
        key=f"collapse-{id(self):x}",
        input_type=run.result_type,
        output_type=run.result_type,
        introduced=EffectRow(
            entries=(RowEntry(instance=score_instance, effect=SCORE),)
        ),
        total=False,
    )

    def sample(
        request: RuntimeRequest, resume: Resumption, context: ClauseContext
    ) -> object:
        """Answer a parent by an unscored draw and a child by its marginal.

        Parameters
        ----------
        request : RuntimeRequest
            The request being answered and its arguments.
        resume : Resumption
            The continuation.
        context : ClauseContext
            Runtime services available to the clause.

        Returns
        -------
        object
            What the resumed computation produced, or a `Forward`
            for a site the pairs do not name.

        Raises
        ------
        InvalidHandlerError
            If a child is reached before its parent, or the run has
            no observation for it.
        """
        site, sampleable = _site_and_sampleable(request, definition.name)
        assert isinstance(site, str)
        assert isinstance(sampleable, TorchSampleable)
        if site in self.pairs:
            value = sampleable.rsample()
            parents[site] = (sampleable, value)
            run.annotations.setdefault(site, {})["collapse"] = self.pairs[site]
            run.intervene(request)
            return resume(value)
        if site in children:
            parent_name = children[site]
            if parent_name not in parents:
                raise InvalidHandlerError(
                    f"collapse reached child {site!r} before its parent "
                    f"{parent_name!r}"
                )
            if site not in run.observations:
                raise InvalidHandlerError(
                    f"collapse needs an observation for child {site!r}"
                )
            parent_sampleable, parent_value = parents[parent_name]
            solver = conjugate_solver(
                family_of(parent_sampleable), family_of(sampleable)
            )
            value = run.observations[site]
            weight = solver(
                parent_sampleable.parameters(), parent_value, sampleable, value
            )
            _emit_score(
                context,
                request,
                score_instance,
                weight,
                run.validator,
                role="condition-score",
            )
            return resume(value)
        return Forward()

    runtime = RuntimeHandler(
        definition=definition,
        clauses={
            RANDOM_SAMPLE: RuntimeClause(
                invoke=sample, result_validator=run.validator
            )
        },
    )
    return (Installation(instance=kernel.random, runtime=runtime),)

DoHandler

DoHandler(data: dict[str, Tensor])

Bases: EffectHandler

Intervene on named sites.

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

PARAMETER DESCRIPTION
data

Site name to the value the site is fixed to.

TYPE: dict[str, Tensor]

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

site_values property

site_values: dict[str, Tensor]

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

RETURNS DESCRIPTION
dict[str, Tensor]

Site name to value.

install

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

Install an intervening handler of the random instance.

PARAMETER DESCRIPTION
run

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

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The intervening handler.

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

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

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

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

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

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

LiftHandler

LiftHandler(prior_scale: float = 1.0)

Bases: EffectHandler

Draw every reachable parameter from a Normal prior.

PARAMETER DESCRIPTION
prior_scale

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

TYPE: float DEFAULT: 1.0

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

install

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

Install a prior-drawing handler of the param instance.

PARAMETER DESCRIPTION
run

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

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

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

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

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

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

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

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

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

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

reset

reset() -> None

Clear the draws so the next run makes fresh ones.

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

MaskHandler

MaskHandler(mask_tensor: Tensor)

Bases: EffectHandler

Gate every density contribution elementwise.

PARAMETER DESCRIPTION
mask_tensor

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

TYPE: Tensor

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

install

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

Install a masking transformer of the score instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The transformer.

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

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

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

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

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

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

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

ObservationScoringHandler

ObservationScoringHandler(enabled: bool = True)

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: bool DEFAULT: True

Source code in src/quivers/effects/observation_scoring.py
def __init__(self, enabled: bool = True) -> None:
    if type(enabled) is not bool:
        raise TypeError("observation scoring requires a Boolean policy")
    self.enabled = enabled

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: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

No effect is replaced; existing host boundaries read the policy.

Source code in src/quivers/effects/observation_scoring.py
def install(self, run: RunContext) -> tuple[Installation, ...]:
    """Set this execution's policy, with innermost scopes taking precedence.

    Parameters
    ----------
    run : RunContext
        Isolated per-run state, shared by its native host steps.

    Returns
    -------
    tuple[Installation, ...]
        No effect is replaced; existing host boundaries read the policy.
    """
    run.annotations.setdefault(_POLICY, {})["enabled"] = self.enabled
    return ()

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 Compute instance the step performs on.

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

effect

The applied Compute[X, A] interface of the instance.

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

kind

"input" for the program's parameter split, "draw" for a morphism applied to its input, "apply" for a categorical morphism's tensor contracted against its input, "bind" for a destructuring split, "let" for a deterministic binding, "score" for a scored binding, "pack" for a called program's input assembled from its parameters, "site" for the address of a site reached once per scan position, "scan_length" and "scan_initial" for a scan's sequence length and initial state, "scan_entry" for the entry at a scan position, "scan_state" for the state a scan's step returns, and "scan_states" and "scan_collect" for the states a scan with outputs="all" gathers, before its first position and after each.

TYPE: str

spec

The step record the host part serves, or None for the input split and an input pack.

TYPE: Step | None DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

environment

The names of the locals the step reads, in the order the environment tuple carries them.

TYPE: tuple[str, ...]

answer_type

The type the host part returns.

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

site

The site label of a draw step or a site address, else None.

TYPE: str | None

program

The program spec belongs to: the encoded program, or one a call or a scan runs in place.

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

scanned

Whether the step runs once per position of a scan.

TYPE: bool

position

The step's position among the kernel's host steps.

TYPE: int

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: QiecModule DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

program

The program encoded.

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

steps

The host steps, in body order.

TYPE: tuple[HostStep, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

sites

The site label of every draw, in order; a site reached once per scan position is listed once, under its label.

TYPE: tuple[str, ...]

site_types

The value type of each site, by label.

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

data

The names of the host data inputs after the program's input, in parameter order.

TYPE: tuple[str, ...]

random

The canonical Random instance.

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

score

The canonical Score instance.

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

param

The canonical Param instance.

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

result_type

The entry computation's result type.

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

locals

The entry computation's local for each name the program binds.

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

scanned

The labels of the sites reached once per scan position, whose occurrences are addressed "<label>@<n>".

TYPE: frozenset[str] DEFAULT: field(default=frozenset(), opaque=True, extras=OPAQUE_BY_VALUE)

site_morphisms

The morphism each site draws from, by label.

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

site_events

The event shape of one value of each site, by label: (dim,) for a continuous codomain, () otherwise.

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

ReplayHandler

ReplayHandler(trace: Trace)

Bases: EffectHandler

Replay the values of a recorded trace.

PARAMETER DESCRIPTION
trace

The trace whose site values are reinstalled.

TYPE: Trace

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

install

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

Install a scoring replay handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

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

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

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

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

ScaleHandler

ScaleHandler(factor: float)

Bases: EffectHandler

Multiply every density contribution by a scalar.

PARAMETER DESCRIPTION
factor

The multiplier.

TYPE: float

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

install

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

Install a scaling transformer of the score instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The transformer.

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

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

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

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

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

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

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

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 Param handlers answered.

TYPE: ContinuousMorphism

input

The input tensor the morphism is conditioned on, carrying the batch axis.

TYPE: Tensor

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: ContinuousMorphism | None DEFAULT: None

raw_morphism

The parameterized response distribution before likelihood weighting or observation subsampling, used for raw likelihood extraction.

TYPE: ContinuousMorphism | None DEFAULT: None

Construct a sampleable holding live runtime references by identity.

PARAMETER DESCRIPTION
morphism

The morphism used for sampling and scoring.

TYPE: ContinuousMorphism

input

The tensor conditioning the morphism.

TYPE: Tensor

declared

The declared site morphism, defaulting to the sampling morphism.

TYPE: ContinuousMorphism or None DEFAULT: None

raw_morphism

The unweighted response morphism, defaulting to the sampling morphism.

TYPE: ContinuousMorphism or None DEFAULT: None

RAISES DESCRIPTION
ValidationError

If the runtime fields have incompatible types.

Source code in src/quivers/effects/sites.py
def __init__(
    self,
    *,
    morphism: ContinuousMorphism,
    input: torch.Tensor,
    declared: ContinuousMorphism | None = None,
    raw_morphism: ContinuousMorphism | None = None,
) -> None:
    """Construct a sampleable holding live runtime references by identity.

    Parameters
    ----------
    morphism : ContinuousMorphism
        The morphism used for sampling and scoring.
    input : torch.Tensor
        The tensor conditioning the morphism.
    declared : ContinuousMorphism or None
        The declared site morphism, defaulting to the sampling morphism.
    raw_morphism : ContinuousMorphism or None
        The unweighted response morphism, defaulting to the sampling morphism.

    Raises
    ------
    didactic.ValidationError
        If the runtime fields have incompatible types.
    """
    initialize = cast("Callable[..., None]", super().__init__)
    initialize(
        morphism=morphism,
        input=input,
        declared=morphism if declared is None else declared,
        raw_morphism=morphism if raw_morphism is None else raw_morphism,
    )

rsample

rsample() -> Tensor

Draw a reparameterised sample.

RETURNS DESCRIPTION
Tensor

One draw per batch row.

Source code in src/quivers/effects/sites.py
def rsample(self) -> torch.Tensor:
    """Draw a reparameterised sample.

    Returns
    -------
    torch.Tensor
        One draw per batch row.
    """
    return self.morphism.rsample(self.input)

sample

sample() -> Tensor

Draw a sample.

RETURNS DESCRIPTION
Tensor

One draw per batch row.

Source code in src/quivers/effects/sites.py
def sample(self) -> torch.Tensor:
    """Draw a sample.

    Returns
    -------
    torch.Tensor
        One draw per batch row.
    """
    return self.morphism.rsample(self.input)

log_prob

log_prob(value: Tensor) -> Tensor

Score a value under the morphism at the input.

PARAMETER DESCRIPTION
value

The value, one per batch row.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The log density per batch row.

Source code in src/quivers/effects/sites.py
def log_prob(self, value: torch.Tensor) -> torch.Tensor:
    """Score a value under the morphism at the input.

    Parameters
    ----------
    value : torch.Tensor
        The value, one per batch row.

    Returns
    -------
    torch.Tensor
        The log density per batch row.
    """
    return self.morphism.log_prob(self.input, value)

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 loc and scale for a morphism that exposes only a location-scale pair.

RAISES DESCRIPTION
TypeError

If the morphism exposes neither a distribution builder nor a location-scale pair.

Source code in src/quivers/effects/sites.py
def parameters(self) -> dict[str, torch.Tensor]:
    """The distribution parameters the morphism computes at the input.

    Returns
    -------
    dict[str, torch.Tensor]
        The named parameters of the torch distribution the morphism
        builds, or ``loc`` and ``scale`` for a morphism that exposes
        only a location-scale pair.

    Raises
    ------
    TypeError
        If the morphism exposes neither a distribution builder nor a
        location-scale pair.
    """
    get_dist = getattr(self.morphism, "_get_dist", None)
    if callable(get_dist):
        distribution = get_dist(self.input)
        return {
            name: getattr(distribution, name)
            for name in distribution.arg_constraints
            if hasattr(distribution, name)
        }
    get_params = getattr(self.morphism, "_get_params", None)
    if callable(get_params):
        loc, scale = get_params(self.input)
        return {"loc": loc, "scale": scale}
    raise TypeError(
        f"{type(self.morphism).__name__} exposes no distribution parameters"
    )

raw_log_prob_pointwise

raw_log_prob_pointwise(value: Tensor) -> Tensor

Read the response density before likelihood weighting or subsampling.

PARAMETER DESCRIPTION
value

The observed response values.

TYPE: Tensor

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
def raw_log_prob_pointwise(self, value: torch.Tensor) -> torch.Tensor:
    """Read the response density before likelihood weighting or subsampling.

    Parameters
    ----------
    value : torch.Tensor
        The observed response values.

    Returns
    -------
    torch.Tensor
        Raw log densities, one per observation row when the family has
        a plate, with event dimensions reduced.

    Raises
    ------
    TypeError
        If the site is the response of a marginalized block, whose
        density the units of the block's score hold.
    """
    if isinstance(self.declared, MarginalizedFactor):
        raise TypeError(
            "this observation has no density of its own: the score of the "
            "block that sums its latent out holds it, by unit"
        )
    pointwise = getattr(self.raw_morphism, "log_prob_pointwise", None)
    if callable(pointwise):
        result = pointwise(self.input, value)
        assert isinstance(result, torch.Tensor)
        return result
    return self.raw_morphism.log_prob(self.input, value)

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: UnitFactorization DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

environment

The run's values the factorization reads.

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

occurrence

The suffix of the site's occurrence, "@<n>" for a score a scan reaches once per position, else empty.

TYPE: str DEFAULT: ''

axes property

axes: tuple[str, ...]

The objects whose product indexes the units.

RETURNS DESCRIPTION
tuple[str, ...]

The names, outermost first; empty for a score with one unit.

sizes property

sizes: tuple[int, ...]

The extent of each unit axis.

RETURNS DESCRIPTION
tuple[int, ...]

The extents.

responses property

responses: tuple[str, ...]

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 sizes. They sum to the score the step contributes, before any score transformer on the stack.

Source code in src/quivers/effects/units.py
def log_weights(self) -> torch.Tensor:
    """The log weight of each unit, as the site scored it.

    Returns
    -------
    torch.Tensor
        The weights, of shape `sizes`. They sum to the score the step
        contributes, before any score transformer on the stack.
    """
    return self.factorization.weights(self.environment).reshape(self.sizes)

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 sizes, without likelihood powers.

RAISES DESCRIPTION
UnfactoredObservationError

If the score's weights are not log densities.

Source code in src/quivers/effects/units.py
def log_likelihood(self) -> torch.Tensor:
    """The log density of each unit's rows given the run's latents.

    Returns
    -------
    torch.Tensor
        The log densities, of shape `sizes`, without likelihood powers.

    Raises
    ------
    UnfactoredObservationError
        If the score's weights are not log densities.
    """
    self._require_density()
    return self.factorization.raw_weights(self.environment).reshape(self.sizes)

row_units

row_units(response: str) -> Tensor

The unit each row of a response belongs to.

PARAMETER DESCRIPTION
response

The response's label.

TYPE: str

RETURNS DESCRIPTION
Tensor

(rows,), counted row-major over the unit axes.

RAISES DESCRIPTION
KeyError

If the score reads no such response.

Source code in src/quivers/effects/units.py
def row_units(self, response: str) -> torch.Tensor:
    """The unit each row of a response belongs to.

    Parameters
    ----------
    response : str
        The response's label.

    Returns
    -------
    torch.Tensor
        ``(rows,)``, counted row-major over the unit axes.

    Raises
    ------
    KeyError
        If the score reads no such response.
    """
    for label, item in zip(self.responses, self.factorization.rows, strict=True):
        if label == response:
            return item.units(self.environment)
    raise KeyError(response)

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: str

RETURNS DESCRIPTION
Tensor

(rows,), without likelihood powers.

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
def row_log_likelihood(self, response: str) -> torch.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.

    Parameters
    ----------
    response : str
        The response's label.

    Returns
    -------
    torch.Tensor
        ``(rows,)``, without likelihood powers.

    Raises
    ------
    KeyError
        If the score reads no such response.
    UnfactoredObservationError
        If a unit holds several rows, or the score's weights are not
        log densities.
    """
    self._require_density()
    rows = self.row_units(response)
    units = max(1, int(torch.tensor(self.sizes).prod()) if self.sizes else 1)
    counts = torch.zeros(units, dtype=torch.long, device=rows.device)
    for label in self.responses:
        held = self.row_units(label)
        counts = counts + torch.bincount(held, minlength=units)
    shared = counts[rows] > 1
    if bool(shared.any()):
        raise UnfactoredObservationError(
            self._refusal(response, rows, counts, int(rows[shared][0]))
        )
    return self.log_likelihood().reshape(-1)[rows]

SubsampleHandler

SubsampleHandler(plate: str, index: Tensor)

Bases: EffectHandler

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

PARAMETER DESCRIPTION
plate

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

TYPE: str

index

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

TYPE: Tensor

RAISES DESCRIPTION
ValueError

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

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

install

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

Register the plate's subset on the run.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

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

RAISES DESCRIPTION
ValueError

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

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

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

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

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

TraceHandler

TraceHandler()

Bases: EffectHandler

Record every site visited during a program's execution.

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

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

install

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

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

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

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

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

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

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

finish

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

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

PARAMETER DESCRIPTION
run

The run, with every contribution the accumulator received.

TYPE: RunContext

output

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

TYPE: object

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

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

total_log_joint

total_log_joint(device: device) -> Tensor

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

PARAMETER DESCRIPTION
device

Device the accumulator seeds on.

TYPE: device

RETURNS DESCRIPTION
Tensor

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

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

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

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

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: str

morphism

The distribution morphism (None for let bindings and scores).

TYPE: ContinuousMorphism or None DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

value

The sampled, observed, or computed tensor. A site drawn from a finite structured law keeps its one typed point as a value.

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

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: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

is_observed

Whether this site was conditioned on an observed value.

TYPE: bool DEFAULT: False

is_deterministic

Whether this is a let binding, a score step, or an intervened site.

TYPE: bool DEFAULT: False

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: TorchSampleable or FiniteSampleable or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

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: SiteAddress or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

metadata

Annotations handlers attached to the site.

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

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: tuple[SiteUnits, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

is_structured property

is_structured: bool

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: dict[str, SampleSite] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

output

The program's return value.

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

log_joint

Sum of log-densities across all sites. Shape (batch,).

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

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

ConjugateReparam(parent: str, parent_family: str, child_family: str)

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: str

parent_family

The parent's family.

TYPE: str

child_family

The child's family.

TYPE: str

RAISES DESCRIPTION
KeyError

If the pair has no registered marginal.

Source code in src/quivers/effects/reparam/conjugate.py
def __init__(self, parent: str, parent_family: str, child_family: str) -> None:
    self.parent = parent
    self.parent_family = parent_family
    self.child_family = child_family
    self.solver = conjugate_solver(parent_family, child_family)

apply

apply(site: SiteRequest) -> tuple[Tensor, Tensor]

Rewrite the child site.

PARAMETER DESCRIPTION
site

The child site.

TYPE: SiteRequest

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
def apply(self, site: SiteRequest) -> tuple[torch.Tensor, torch.Tensor]:
    """Rewrite the child site.

    Parameters
    ----------
    site : SiteRequest
        The child site.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The value and its marginal log density.

    Raises
    ------
    KeyError
        If the orchestrator has not seen the parent site.
    ValueError
        If the parent or the child is not of the declared family.
    """
    try:
        parent = site.seen[self.parent]
    except KeyError as error:
        raise KeyError(
            f"ConjugateReparam: parent site {self.parent!r} was not seen "
            f"before child {site.name!r}"
        ) from error
    if family_of(parent) != self.parent_family:
        raise ValueError(
            f"ConjugateReparam: parent {self.parent!r} draws from "
            f"{family_of(parent)!r}, not {self.parent_family!r}"
        )
    if family_of(site.sampleable) != self.child_family:
        raise ValueError(
            f"ConjugateReparam: child {site.name!r} draws from "
            f"{family_of(site.sampleable)!r}, not {self.child_family!r}"
        )
    if site.given is not None:
        value = site.given
    elif site.observation is not None:
        value = site.observation
    else:
        value = site.sampleable.rsample()
    parent_value = site.sampleable.input
    return value, self.solver(
        parent.parameters(), parent_value, site.sampleable, value
    )

LocScaleReparam

LocScaleReparam(centered: float = 0.0)

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 (1.0) and fully non-centred (0.0) parameterisations. Values in between produce a partial reparam, matching the centered parameter of Pyro's LocScaleReparam.

TYPE: float DEFAULT: 0.0

RAISES DESCRIPTION
ValueError

If centered is outside [0, 1].

Source code in src/quivers/effects/reparam/loc_scale.py
def __init__(self, centered: float = 0.0) -> None:
    if not 0.0 <= centered <= 1.0:
        raise ValueError(
            f"LocScaleReparam: centered must be in [0, 1], got {centered}."
        )
    self.centered = float(centered)

apply

apply(site: SiteRequest) -> tuple[Tensor, Tensor]

Rewrite one site.

PARAMETER DESCRIPTION
site

The site.

TYPE: SiteRequest

RETURNS DESCRIPTION
tuple[Tensor, Tensor]

The value and its log density under Normal(loc, scale), summed over the trailing feature axis.

RAISES DESCRIPTION
TypeError

If the site's morphism exposes no _get_params.

Source code in src/quivers/effects/reparam/loc_scale.py
def apply(self, site: SiteRequest) -> tuple[torch.Tensor, torch.Tensor]:
    """Rewrite one site.

    Parameters
    ----------
    site : SiteRequest
        The site.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The value and its log density under ``Normal(loc, scale)``,
        summed over the trailing feature axis.

    Raises
    ------
    TypeError
        If the site's morphism exposes no ``_get_params``.
    """
    morphism = site.sampleable.morphism
    get_params = getattr(morphism, "_get_params", None)
    if get_params is None:
        raise TypeError(
            f"LocScaleReparam: site '{site.name}' morphism "
            f"{type(morphism).__name__} does not expose `_get_params(x)`; "
            f"LocScaleReparam requires a Normal-family morphism."
        )
    loc, scale = get_params(site.sampleable.input)
    # Partial centring interpolates the effective scale used to
    # push the base sample forward: ``centered=1`` recovers the
    # original sample-then-score path, ``centered=0`` the fully
    # non-centred rewrite.
    effective = scale.pow(self.centered)
    base_scale = scale / effective
    if site.given is None:
        eps = torch.randn_like(loc)
        y_raw = effective * eps
        y = loc + base_scale * y_raw
    else:
        y = site.given
    residual = (y - loc) / scale
    log_p = -0.5 * residual.pow(2) - scale.log() - 0.5 * math.log(2 * math.pi)
    return y, log_p.sum(dim=-1)

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 (AutoNormalizingFlow, AutoIAFGuide, or AutoNeuralSplineGuide), whose law is the pushforward of a standard Normal.

TYPE: AutoNormalizingFlow

RAISES DESCRIPTION
TypeError

If guide is not a flow guide.

Source code in src/quivers/effects/reparam/neutra.py
def __init__(self, guide: AutoNormalizingFlow) -> None:
    if not isinstance(guide, AutoNormalizingFlow):
        raise TypeError(
            f"NeuTraReparam: the guide is a {type(guide).__name__}; NeuTra "
            "needs a flow guide (AutoNormalizingFlow, AutoIAFGuide, or "
            "AutoNeuralSplineGuide), whose law is a pushforward of a "
            "standard Normal"
        )
    self.guide = guide
    self._draw: NeuTraDraw | None = None

current_draw property

current_draw: NeuTraDraw | None

The draw the current run's covered sites take.

RETURNS DESCRIPTION
NeuTraDraw | None

The draw, or None before the run reaches a covered site.

begin_run

begin_run() -> None

Discard the previous run's draw.

Source code in src/quivers/effects/reparam/neutra.py
def begin_run(self) -> None:
    """Discard the previous run's draw."""
    self._draw = None

push

push(base: Tensor) -> NeuTraDraw

Map a base point to the guide's sites.

PARAMETER DESCRIPTION
base

The base point :math:u, shape (D,), D the guide's total unconstrained dimension.

TYPE: Tensor

RETURNS DESCRIPTION
NeuTraDraw

The sites' values :math:B(T(u)) and the log Jacobian of the map.

RAISES DESCRIPTION
ValueError

If base is not of shape (D,).

Source code in src/quivers/effects/reparam/neutra.py
def push(self, base: torch.Tensor) -> NeuTraDraw:
    """Map a base point to the guide's sites.

    Parameters
    ----------
    base : torch.Tensor
        The base point :math:`u`, shape ``(D,)``, ``D`` the guide's
        total unconstrained dimension.

    Returns
    -------
    NeuTraDraw
        The sites' values :math:`B(T(u))` and the log Jacobian of the
        map.

    Raises
    ------
    ValueError
        If ``base`` is not of shape ``(D,)``.
    """
    registry = self.guide.registry
    width = registry.total_unconstrained_dim
    if tuple(base.shape) != (width,):
        raise ValueError(
            f"NeuTraReparam.push: the base point has shape {tuple(base.shape)}; "
            f"the guide's flow takes ({width},)"
        )
    z, flow_log_det = self.guide.push_forward(base)
    constrained, log_abs_dets = registry.to_constrained(
        registry.unflatten_unconstrained(z)
    )
    log_det = flow_log_det
    for terms in log_abs_dets.values():
        log_det = log_det + terms.sum()
    return NeuTraDraw(base=base, sites=constrained, log_abs_det=log_det)

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
def draw(self) -> NeuTraDraw:
    """Draw a base point from the standard Normal and push it.

    Returns
    -------
    NeuTraDraw
        The draw.
    """
    loc = self.guide.get_buffer("base_loc")
    return self.push(torch.randn_like(loc))

apply

apply(site: SiteRequest) -> tuple[Tensor, Tensor]

Rewrite one site.

PARAMETER DESCRIPTION
site

The site.

TYPE: SiteRequest

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
def apply(self, site: SiteRequest) -> tuple[torch.Tensor, torch.Tensor]:
    """Rewrite one site.

    Parameters
    ----------
    site : SiteRequest
        The site.

    Returns
    -------
    tuple[torch.Tensor, torch.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
    ------
    ValueError
        If a covered site's input has more than one row, since one
        run draws it once.
    """
    registry = self.guide.registry
    if site.given is not None:
        value = site.given
    elif site.name not in registry:
        value = site.sampleable.rsample()
    else:
        if self._draw is None:
            self._draw = self.draw()
        value = self._draw.sites[site.name]
        latent = registry[site.name]
        if not latent.is_plate:
            rows = (
                site.sampleable.input.shape[0] if site.sampleable.input.dim() else 1
            )
            if rows != 1:
                raise ValueError(
                    f"NeuTraReparam: site {site.name!r} has an input of {rows} "
                    "rows in one run; a run draws the guide's sites once"
                )
            codomain = site.sampleable.morphism.codomain
            event = (
                tuple(codomain.event_shape)
                if isinstance(codomain, ContinuousSpace)
                else ()
            )
            value = value.reshape(1, *event)
    return value, site.sampleable.log_prob(value)

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

begin_run() -> None

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
def begin_run(self) -> None:
    """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.
    """

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: SiteRequest

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
@abstractmethod
def apply(self, site: SiteRequest) -> tuple[torch.Tensor, torch.Tensor]:
    """Rewrite one site.

    Parameters
    ----------
    site : SiteRequest
        The site, with a value fixed when one is given.

    Returns
    -------
    tuple[torch.Tensor, torch.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.
    """

ReparamOrchestrator

ReparamOrchestrator(strategies: dict[str, Reparam])

Bases: EffectHandler

Dispatch sample sites to per-site reparam strategies.

PARAMETER DESCRIPTION
strategies

Site name to strategy.

TYPE: dict[str, Reparam]

Source code in src/quivers/effects/reparam/base.py
def __init__(self, strategies: dict[str, Reparam]) -> None:
    self.strategies = dict(strategies)

install

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

Install the dispatching handler of the random instance.

PARAMETER DESCRIPTION
run

The run being prepared.

TYPE: RunContext

RETURNS DESCRIPTION
tuple[Installation, ...]

The handler, which answers covered sites and forwards the rest.

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

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

    Returns
    -------
    tuple[Installation, ...]
        The handler, which answers covered sites and forwards the
        rest.
    """
    kernel = run.kernel
    score_instance = kernel.score.entry.instance
    seen: dict[str, TorchSampleable] = {}
    for strategy in {id(s): s for s in self.strategies.values()}.values():
        strategy.begin_run()
    definition = _handler_def(
        "Random.reparam",
        RANDOM,
        ((RANDOM_SAMPLE, ResumptionGrade.LINEAR),),
        key=f"reparam-{id(self):x}",
        input_type=run.result_type,
        output_type=run.result_type,
        introduced=EffectRow(
            entries=(RowEntry(instance=score_instance, effect=SCORE),)
        ),
        total=False,
    )

    def sample(
        request: RuntimeRequest, resume: Resumption, context: ClauseContext
    ) -> object:
        """Answer a covered site with its strategy's value and density.

        Parameters
        ----------
        request : RuntimeRequest
            The request being answered and its arguments.
        resume : Resumption
            The continuation.
        context : ClauseContext
            Runtime services available to the clause.

        Returns
        -------
        object
            What the resumed computation produced, or a `Forward`
            for a site no strategy covers.
        """
        site, sampleable = _site_and_sampleable(request, definition.name)
        assert isinstance(site, str)
        assert isinstance(sampleable, TorchSampleable)
        strategy = self.strategies.get(site)
        if strategy is None:
            seen[site] = sampleable
            return Forward()
        value, log_prob = strategy.apply(
            SiteRequest(
                name=site,
                sampleable=sampleable,
                seen=dict(seen),
                observation=run.observations.get(site),
            )
        )
        seen[site] = sampleable
        _emit_score(
            context,
            request,
            score_instance,
            log_prob,
            run.validator,
            role="draw-score",
        )
        return resume(value)

    runtime = RuntimeHandler(
        definition=definition,
        clauses={
            RANDOM_SAMPLE: RuntimeClause(
                invoke=sample, result_validator=run.validator
            )
        },
    )
    return (Installation(instance=kernel.random, runtime=runtime),)

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: str

sampleable

The site's distribution at its input.

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

given

A value the site is to take, when an enclosing strategy or a caller fixed one; None when the strategy draws.

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

seen

The sampleables of the sites the orchestrator saw before this one, by name, so a strategy may read a parent's parameters.

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

observation

The run's observation for the site, if any.

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

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: Tensor

RETURNS DESCRIPTION
SiteRequest

The request with given set.

Source code in src/quivers/effects/reparam/base.py
def with_value(self, value: torch.Tensor) -> SiteRequest:
    """The same request with a value fixed.

    Parameters
    ----------
    value : torch.Tensor
        The value the site is to take.

    Returns
    -------
    SiteRequest
        The request with ``given`` set.
    """
    return self.with_(given=value)

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 b the site's geometry is reshaped through.

TYPE: Bijector

Source code in src/quivers/effects/reparam/transform.py
def __init__(self, bijector: Bijector) -> None:
    self.bijector = bijector

apply

apply(site: SiteRequest) -> tuple[Tensor, Tensor]

Rewrite one site.

PARAMETER DESCRIPTION
site

The site.

TYPE: SiteRequest

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
def apply(self, site: SiteRequest) -> tuple[torch.Tensor, torch.Tensor]:
    """Rewrite one site.

    Parameters
    ----------
    site : SiteRequest
        The site.

    Returns
    -------
    tuple[torch.Tensor, torch.Tensor]
        The value, drawn from the site's sampleable unless given, and
        its log density under the sampleable.
    """
    y = site.given if site.given is not None else site.sampleable.rsample()
    return y, site.sampleable.log_prob(y)

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: MonadicProgram

latents

The sites whose values the position gives.

TYPE: Collection[str]

given

The sites and host data whose values every position shares.

TYPE: Collection[str]

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
def batching_obstacles(
    program: MonadicProgram,
    latents: Collection[str],
    given: Collection[str],
) -> tuple[BatchingObstacle, ...]:
    """The steps of a program that cannot be evaluated at many positions.

    Parameters
    ----------
    program : MonadicProgram
        The program.
    latents : Collection[str]
        The sites whose values the position gives.
    given : Collection[str]
        The sites and host data whose values every position shares.

    Returns
    -------
    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.
    """
    found: list[BatchingObstacle] = []
    depends = frozenset(latents)
    bound = frozenset({*latents, *given})
    for step in program.steps:
        names = _bound_names(step)
        inner = (
            step.program
            if isinstance(step, Call)
            else step.step
            if isinstance(step, Scan)
            else None
        )
        if isinstance(inner, MonadicProgram):
            own = inner_names(inner)
            found.extend(batching_obstacles(inner, depends | own, own))
        declared = _declaration(program, step)
        reason = declared.obstacle
        varying = sorted(declared.shared & depends)
        if reason is None and varying:
            reason = (
                f"it needs the same value of {varying} at every position, and that "
                "value depends on a latent"
            )
        if (
            reason is None
            and isinstance(step, Draw | Observe)
            and not bound.issuperset(names)
        ):
            reason = "its site is given no value, so every evaluation draws one"
        if reason is not None:
            found.append(
                BatchingObstacle(
                    step=f"{step.kind} step {', '.join(map(repr, names))}",
                    reason=reason,
                )
            )
        bound = bound.union(names)
        if not isinstance(step, Draw | Observe) and _positional(step, depends):
            depends = depends.union(names)
    return tuple(found)

machine_value_admitted

machine_value_admitted(value: object) -> bool

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: object

RETURNS DESCRIPTION
bool

False for a Python number or a tuple holding one.

Source code in src/quivers/effects/checked_program.py
def machine_value_admitted(value: object) -> bool:
    """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.

    Parameters
    ----------
    value : object
        The answer.

    Returns
    -------
    bool
        ``False`` for a Python number or a tuple holding one.
    """
    if isinstance(value, bool | int | float):
        return False
    if isinstance(value, tuple):
        return all(machine_value_admitted(item) for item in value)
    return True

family_of

family_of(sampleable: TorchSampleable) -> str

The registry family a sampleable's morphism draws from.

PARAMETER DESCRIPTION
sampleable

The sampleable.

TYPE: TorchSampleable

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
def family_of(sampleable: TorchSampleable) -> str:
    """The registry family a sampleable's morphism draws from.

    Parameters
    ----------
    sampleable : TorchSampleable
        The sampleable.

    Returns
    -------
    str
        The family's registry name.

    Raises
    ------
    TypeError
        If the morphism's class is registered for no family.
    """
    inner = sampleable.declared
    assert inner is not None
    for name, meta in FAMILY_META.items():
        if meta.quivers_class is not None and isinstance(inner, meta.quivers_class):
            return name
    get_dist = getattr(inner, "_get_dist", None)
    if callable(get_dist):
        distribution = get_dist(sampleable.input)
        for name, meta in FAMILY_META.items():
            if type(distribution) is meta.distribution_class:
                return name
    raise TypeError(
        f"{type(inner).__name__} draws from no registered family; a conjugate "
        "marginal needs the parent's and the child's families"
    )

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 loc and scale.

TYPE: Mapping[str, Tensor]

parent_value

The parent's drawn value.

TYPE: Tensor

child

The child at the parent's drawn value, whose scale is tau.

TYPE: TorchSampleable

value

The child's value.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

log Normal(y; mu, sqrt(sigma^2 + tau^2)) summed over the event.

RAISES DESCRIPTION
ValueError

If the child's location is not the parent's value.

Source code in src/quivers/effects/conjugate.py
def normal_normal(
    parent: Mapping[str, torch.Tensor],
    parent_value: torch.Tensor,
    child: TorchSampleable,
    value: torch.Tensor,
) -> torch.Tensor:
    """The marginal of ``y ~ Normal(z, tau)`` under ``z ~ Normal(mu, sigma)``.

    Parameters
    ----------
    parent : Mapping[str, torch.Tensor]
        The parent's ``loc`` and ``scale``.
    parent_value : torch.Tensor
        The parent's drawn value.
    child : TorchSampleable
        The child at the parent's drawn value, whose ``scale`` is ``tau``.
    value : torch.Tensor
        The child's value.

    Returns
    -------
    torch.Tensor
        ``log Normal(y; mu, sqrt(sigma^2 + tau^2))`` summed over the event.

    Raises
    ------
    ValueError
        If the child's location is not the parent's value.
    """
    _identity_link(child, "loc", parent_value)
    tau = child.parameters()["scale"].reshape(parent["scale"].shape)
    scale = torch.sqrt(parent["scale"] ** 2 + tau**2)
    residual = (value - parent["loc"]) / scale
    log_density = -0.5 * residual**2 - scale.log() - 0.5 * math.log(2 * math.pi)
    return log_density.sum(dim=-1) if log_density.dim() > 1 else log_density

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 concentration1 and concentration0.

TYPE: Mapping[str, Tensor]

parent_value

The parent's drawn value.

TYPE: Tensor

child

The child at the parent's drawn value.

TYPE: TorchSampleable

value

The child's value, zero or one.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

log(a / (a + b)) for one and log(b / (a + b)) for zero.

RAISES DESCRIPTION
ValueError

If the child's probability is not the parent's value.

Source code in src/quivers/effects/conjugate.py
def beta_bernoulli(
    parent: Mapping[str, torch.Tensor],
    parent_value: torch.Tensor,
    child: TorchSampleable,
    value: torch.Tensor,
) -> torch.Tensor:
    """The marginal of ``y ~ Bernoulli(z)`` under ``z ~ Beta(a, b)``.

    Parameters
    ----------
    parent : Mapping[str, torch.Tensor]
        The parent's ``concentration1`` and ``concentration0``.
    parent_value : torch.Tensor
        The parent's drawn value.
    child : TorchSampleable
        The child at the parent's drawn value.
    value : torch.Tensor
        The child's value, zero or one.

    Returns
    -------
    torch.Tensor
        ``log(a / (a + b))`` for one and ``log(b / (a + b))`` for zero.

    Raises
    ------
    ValueError
        If the child's probability is not the parent's value.
    """
    _identity_link(child, "probs", parent_value)
    a = parent["concentration1"]
    b = parent["concentration0"]
    probability = a / (a + b)
    log_density = torch.where(
        value.to(probability.dtype) > 0.5, probability.log(), (1 - probability).log()
    )
    return log_density.sum(dim=-1) if log_density.dim() > 1 else log_density

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 concentration and rate.

TYPE: Mapping[str, Tensor]

parent_value

The parent's drawn value.

TYPE: Tensor

child

The child at the parent's drawn value.

TYPE: TorchSampleable

value

The child's count.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The negative binomial log mass with alpha successes and success probability beta / (beta + 1).

RAISES DESCRIPTION
ValueError

If the child's rate is not the parent's value.

Source code in src/quivers/effects/conjugate.py
def gamma_poisson(
    parent: Mapping[str, torch.Tensor],
    parent_value: torch.Tensor,
    child: TorchSampleable,
    value: torch.Tensor,
) -> torch.Tensor:
    """The marginal of ``y ~ Poisson(z)`` under ``z ~ Gamma(alpha, beta)``.

    Parameters
    ----------
    parent : Mapping[str, torch.Tensor]
        The parent's ``concentration`` and ``rate``.
    parent_value : torch.Tensor
        The parent's drawn value.
    child : TorchSampleable
        The child at the parent's drawn value.
    value : torch.Tensor
        The child's count.

    Returns
    -------
    torch.Tensor
        The negative binomial log mass with ``alpha`` successes and
        success probability ``beta / (beta + 1)``.

    Raises
    ------
    ValueError
        If the child's rate is not the parent's value.
    """
    _identity_link(child, "rate", parent_value)
    alpha = parent["concentration"]
    beta = parent["rate"]
    count = value.to(alpha.dtype)
    log_density = (
        torch.lgamma(alpha + count)
        - torch.lgamma(alpha)
        - torch.lgamma(count + 1)
        + alpha * (beta.log() - torch.log1p(beta))
        - count * torch.log1p(beta)
    )
    return log_density.sum(dim=-1) if log_density.dim() > 1 else log_density

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 concentration.

TYPE: Mapping[str, Tensor]

parent_value

The parent's drawn value.

TYPE: Tensor

child

The child at the parent's drawn value.

TYPE: TorchSampleable

value

The child's category.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

log(alpha_y / sum(alpha)).

RAISES DESCRIPTION
ValueError

If the child's probabilities are not the parent's value.

Source code in src/quivers/effects/conjugate.py
def dirichlet_categorical(
    parent: Mapping[str, torch.Tensor],
    parent_value: torch.Tensor,
    child: TorchSampleable,
    value: torch.Tensor,
) -> torch.Tensor:
    """The marginal of ``y ~ Categorical(z)`` under ``z ~ Dirichlet(alpha)``.

    Parameters
    ----------
    parent : Mapping[str, torch.Tensor]
        The parent's ``concentration``.
    parent_value : torch.Tensor
        The parent's drawn value.
    child : TorchSampleable
        The child at the parent's drawn value.
    value : torch.Tensor
        The child's category.

    Returns
    -------
    torch.Tensor
        ``log(alpha_y / sum(alpha))``.

    Raises
    ------
    ValueError
        If the child's probabilities are not the parent's value.
    """
    _identity_link(child, "probs", parent_value)
    alpha = parent["concentration"]
    probabilities = alpha / alpha.sum(dim=-1, keepdim=True)
    index = value.long().unsqueeze(-1)
    return probabilities.gather(-1, index).squeeze(-1).log()

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: str

child_family

The child's family.

TYPE: str

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
def conjugate_solver(parent_family: str, child_family: str) -> Solver:
    """The solver of a conjugate pair.

    Parameters
    ----------
    parent_family : str
        The parent's family.
    child_family : str
        The child's family.

    Returns
    -------
    Solver
        The closed-form marginal.

    Raises
    ------
    KeyError
        If the pair has no registered marginal.
    """
    try:
        return CONJUGATE_SOLVERS[(parent_family, child_family)]
    except KeyError as error:
        registered = ", ".join(f"{a}-{b}" for a, b in CONJUGATE_SOLVERS)
        raise KeyError(
            f"no conjugate marginal is registered for ({parent_family}, "
            f"{child_family}); the registered pairs are {registered}"
        ) from error

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: MonadicProgram

x

Program input. Shape (batch, ...).

TYPE: Tensor

observations

Values to condition observed sites on, keyed by site name. Undeclared keys are host data the program's steps read by name.

TYPE: Mapping[str, Tensor] or None DEFAULT: None

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
def run_program(
    program: MonadicProgram,
    x: torch.Tensor,
    observations: Mapping[str, torch.Tensor] | None = None,
) -> torch.Tensor | dict[str, torch.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.

    Parameters
    ----------
    program : MonadicProgram
        Program to execute.
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.
    observations : Mapping[str, torch.Tensor] or None
        Values to condition observed sites on, keyed by site name.
        Undeclared keys are host data the program's steps read by name.

    Returns
    -------
    torch.Tensor or dict[str, torch.Tensor]
        The program's return value: the single returned variable, or the
        returned variables keyed by their labels.

    Raises
    ------
    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.
    """
    sites, supplied, data = _split_observations(program, observations or {})
    runs = int(x.shape[0]) if x.dim() else 1
    per_run_data = check_host_data(program, data, runs=runs if x.dim() else None)
    kernel = _cached_kernel(program, tuple(sorted(data)))
    _check_sequence_layouts(kernel, observations or {})
    if runs <= 1:
        run_sites = {
            label: _run_slice(kernel, label, value, 1, 0)
            for label, value in sites.items()
        }
        output, _ = _run_once(
            program, kernel, x, run_sites, supplied, data, per_run_data, 0, 1
        )
        return output
    vectorized = _vectorized_sites(program, kernel, sites, supplied, data, runs)
    if vectorized is not None:
        output, _ = _run_once(
            program,
            kernel,
            x,
            vectorized,
            supplied,
            data,
            per_run_data,
            runs - 1,
            runs,
            vectorized=True,
        )
        return output
    outputs: list[torch.Tensor | dict[str, torch.Tensor]] = []
    axis: _RunAxis | None = None
    for index in range(runs):
        run_sites = {
            label: _run_slice(kernel, label, value, runs, index)
            for label, value in sites.items()
        }
        run_supplied = {
            name: _per_run_value(name, value, runs, index)
            for name, value in supplied.items()
        }
        run_data = {
            name: value[index : index + 1] if per_run_data.get(name, False) else value
            for name, value in data.items()
        }
        output, axis = _run_once(
            program,
            kernel,
            x[index : index + 1],
            run_sites,
            run_supplied,
            run_data,
            per_run_data,
            index,
            runs,
        )
        outputs.append(output)
    assert axis is not None
    return _stack_runs(program, outputs, axis)

observations_scored

observations_scored(run: RunContext) -> bool

Read the innermost scoring policy installed for this execution.

PARAMETER DESCRIPTION
run

Isolated execution annotations.

TYPE: RunContext

RETURNS DESCRIPTION
bool

Whether observation likelihoods contribute.

Source code in src/quivers/effects/observation_scoring.py
def observations_scored(run: RunContext) -> bool:
    """Read the innermost scoring policy installed for this execution.

    Parameters
    ----------
    run : RunContext
        Isolated execution annotations.

    Returns
    -------
    bool
        Whether observation likelihoods contribute.
    """
    return bool(run.annotations.get(_POLICY, {}).get("enabled", True))

program_kernel

program_kernel(program: MonadicProgram, data: Sequence[str] = ()) -> ProgramKernel

Encode a program as a kernel module.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

data

The names of the host data inputs a run supplies beside the program's input, in parameter order.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION
ProgramKernel

The module and the record the runtime serves it by.

Source code in src/quivers/effects/program_module.py
def program_kernel(program: MonadicProgram, data: Sequence[str] = ()) -> ProgramKernel:
    """Encode a program as a kernel module.

    Parameters
    ----------
    program : MonadicProgram
        The program.
    data : Sequence[str]
        The names of the host data inputs a run supplies beside the
        program's input, in parameter order.

    Returns
    -------
    ProgramKernel
        The module and the record the runtime serves it by.
    """
    return _Builder(program, data).build()

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.