Skip to content

Program encoding

This module encodes a MonadicProgram as a Quivers Indexed Effect Core (QIEC) computation. Each step's Python part is a request on the prelude's Compute interface over the values it reads, and each draw is a Random.sample request on the sampleable that part returns. Running the encoding on the reference machine, the library's interpreter for QIEC, collects the program's results and scores (runtime providers).

program_module

The kernel encoding of a MonadicProgram.

A MonadicProgram is a sequence of host steps: a draw from a torch morphism at an input built from earlier bindings, a deterministic binding computed by a host closure, or a score contributed by one. The kernel has no term for a host function, and does not need one: each step's host part is an instance of the prelude's Compute interface, performed on the values it reads (the arguments of a draw, the names a closure declares, or every value bound so far when it declares none), and each draw is the canonical Random.sample request on the sampleable the host part returns.

The computation this module builds therefore makes the program's data flow and effect structure explicit while every tensor operation stays in the host, behind a handler a runtime provider installs. The user's effect handlers are lexical handlers of the same random and score instances, so conditioning, intervention, replay, reweighting, and tracing compose by the kernel's own rules.

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)

space_type

space_type(space: SetObject | ContinuousSpace) -> TypeExpr

The kernel type of a value of a space.

PARAMETER DESCRIPTION
space

A program's domain, codomain, or a morphism's codomain.

TYPE: SetObject | ContinuousSpace

RETURNS DESCRIPTION
TypeExpr

Int for a finite set, Real[Fin dim] for a continuous space of that dimension, and the product of the component types for a product space.

Source code in src/quivers/effects/program_module.py
def space_type(space: SetObject | ContinuousSpace) -> TypeExpr:
    """The kernel type of a value of a space.

    Parameters
    ----------
    space : SetObject | ContinuousSpace
        A program's domain, codomain, or a morphism's codomain.

    Returns
    -------
    TypeExpr
        ``Int`` for a finite set, ``Real[Fin dim]`` for a
        continuous space of that dimension, and the product of the
        component types for a product space.
    """
    if isinstance(space, ProductSpace):
        return product_type(*(space_type(component) for component in space.components))
    if isinstance(space, ContinuousSpace):
        return tensor_type(REAL, (IndexLiteral(value=int(space.dim), sort=NAT),))
    return INT

scanned_sites

scanned_sites(program: MonadicProgram) -> frozenset[str]

The labels of the sites a program reaches once per scan position.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
frozenset[str]

The labels of the sites its scans' step programs reach, through the programs those call, at any depth.

Source code in src/quivers/effects/program_module.py
def scanned_sites(program: MonadicProgram) -> frozenset[str]:
    """The labels of the sites a program reaches once per scan position.

    Parameters
    ----------
    program : MonadicProgram
        The program.

    Returns
    -------
    frozenset[str]
        The labels of the sites its scans' step programs reach, through
        the programs those call, at any depth.
    """
    found: set[str] = set()
    for spec in program.steps:
        if isinstance(spec, Scan):
            assert isinstance(spec.step, MonadicProgram)
            found |= _reached_sites(spec.step)
        elif isinstance(spec, CallStep):
            assert isinstance(spec.program, MonadicProgram)
            found |= scanned_sites(spec.program)
    return frozenset(found)

reversed_scan_sites

reversed_scan_sites(program: MonadicProgram) -> frozenset[str]

The labels of the sites a reversed scan reaches once per position.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
frozenset[str]

The labels of the sites the step programs of its reversed scans reach, through the programs its steps call, at any depth. A reversed scan reaches them first at its last position.

Source code in src/quivers/effects/program_module.py
def reversed_scan_sites(program: MonadicProgram) -> frozenset[str]:
    """The labels of the sites a reversed scan reaches once per position.

    Parameters
    ----------
    program : MonadicProgram
        The program.

    Returns
    -------
    frozenset[str]
        The labels of the sites the step programs of its reversed scans
        reach, through the programs its steps call, at any depth. A
        reversed scan reaches them first at its last position.
    """
    found: set[str] = set()
    for spec in program.steps:
        if isinstance(spec, Scan) and spec.reverse:
            assert isinstance(spec.step, MonadicProgram)
            found |= _reached_sites(spec.step)
        elif isinstance(spec, CallStep):
            assert isinstance(spec.program, MonadicProgram)
            found |= reversed_scan_sites(spec.program)
    return frozenset(found)

once_sites

once_sites(program: MonadicProgram) -> frozenset[str]

The labels of the sites a program reaches at most once per run.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
frozenset[str]

Its own draw and observe labels and those of the programs its calls run, but none a scan reaches.

Source code in src/quivers/effects/program_module.py
def once_sites(program: MonadicProgram) -> frozenset[str]:
    """The labels of the sites a program reaches at most once per run.

    Parameters
    ----------
    program : MonadicProgram
        The program.

    Returns
    -------
    frozenset[str]
        Its own draw and observe labels and those of the programs its
        calls run, but none a scan reaches.
    """
    found: set[str] = set()
    for spec in program.steps:
        if isinstance(spec, Draw | Observe):
            found.add(_step_sites(spec))
        elif isinstance(spec, CallStep):
            assert isinstance(spec.program, MonadicProgram)
            found |= once_sites(spec.program)
    return frozenset(found)

derived_bindings

derived_bindings(program: MonadicProgram) -> tuple[frozenset[str], frozenset[str]]

The names a run computes and a caller may not supply a value for.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

RETURNS DESCRIPTION
tuple[frozenset[str], frozenset[str]]

The names the program's own call and scan steps bind, which the run computes from the sites those reach; and the names bound inside its scans' step programs, which the run computes once per position.

Source code in src/quivers/effects/program_module.py
def derived_bindings(program: MonadicProgram) -> tuple[frozenset[str], frozenset[str]]:
    """The names a run computes and a caller may not supply a value for.

    Parameters
    ----------
    program : MonadicProgram
        The program.

    Returns
    -------
    tuple[frozenset[str], frozenset[str]]
        The names the program's own call and scan steps bind, which the
        run computes from the sites those reach; and the names bound
        inside its scans' step programs, which the run computes once
        per position.
    """
    once: set[str] = set()
    per_position: set[str] = set()
    for spec in program.steps:
        if isinstance(spec, CallStep):
            once.add(spec.name)
            assert isinstance(spec.program, MonadicProgram)
            _, inner_scanned = derived_bindings(spec.program)
            per_position |= inner_scanned
        elif isinstance(spec, Scan):
            once.add(spec.name)
            assert isinstance(spec.step, MonadicProgram)
            per_position |= _bindings(spec.step)
    return frozenset(once), frozenset(per_position)

site_label

site_label(label: str, occurrence: int) -> str

The address of one occurrence of a site reached once per position.

PARAMETER DESCRIPTION
label

The site's label.

TYPE: str

occurrence

How many times the run reached the site before, counted from zero.

TYPE: int

RETURNS DESCRIPTION
str

"<label>@<occurrence>".

Source code in src/quivers/effects/program_module.py
def site_label(label: str, occurrence: int) -> str:
    """The address of one occurrence of a site reached once per position.

    Parameters
    ----------
    label : str
        The site's label.
    occurrence : int
        How many times the run reached the site before, counted from zero.

    Returns
    -------
    str
        ``"<label>@<occurrence>"``.
    """
    return f"{label}@{occurrence}"

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()