Skip to content

Checked programs

A CheckedProgram is a program morphism that runs its checked Quivers Indexed Effect Core (QIEC) computation on the reference machine, the library's interpreter for QIEC (running and scoring). The compiler produces one for a program whose calls it cannot turn into compiled steps. It runs under the effect handler stack with tensor values. Inference methods such as MCMC and SVI read the latents from a trace and use the same log joint and its gradients (runtime providers).

The evaluator shares a pass across runs when the control flow and handlers permit it. Its work report counts the passes, and a sampling run that reaches a different set of sites from its trace raises an error.

checked_program

A program that runs its checked computation on the reference machine.

A program that calls a named computation the compiler cannot reduce to compiled runtime steps (a recursive call, a branch whose arms draw different sites, a handler that is not discharged, a case) compiles to a CheckedProgram. It is a MonadicProgram with no host steps, whose body is the program's computation in its checked module, run on the reference machine with every number a tensor.

A run installs the handlers on the effect handler stack exactly as a run of a compiled program does: each handler's installations go on the module's canonical random, score and Param instances, around the computation, under a drawing handler that draws and scores every site nobody else answers and a replay that conditions every site given a value. Draws and densities go through the tensor backend, so the log joint, a reparameterized draw and the value keep the gradient of every tensor the run was given, through calls, recursion and handler clauses. A trace, log_joint, rsample, and every inference consumer built on them read the program as they read a compiled one.

A site reached more than once in a run, inside a recursion or a repeated call, is one site per occurrence; a trace names its occurrences "<label>@<n>" in the order the run reaches them, as a replay takes them.

RUN module-attribute

RUN = '__checked_run'

The name of the computation a run wraps the program in.

OBSERVED_APART module-attribute

OBSERVED_APART = "a handler on the stack is installed in each run and may watch its sites as the run reaches them, and in a pass over every run at once a site's value is every run's"

Why the forward runs of a call under handlers are made one by one.

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})"

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