Skip to content

Interpreter

run_program runs a MonadicProgram on the reference machine under the handler stack (Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). It encodes the program as a Quivers Indexed Effect Core (QIEC) computation, installs the stacked handlers as lexically scoped handlers of the program's random and score instances, and runs the program's Python steps through Compute handlers over PyTorch. A draw receives its value from its handler, and an observation adds its score as the handler interprets it. A caller that wants an execution trace stacks a TraceHandler first.

interpreter

Running a MonadicProgram on the reference machine under a handler stack.

run_program encodes the program as a kernel computation, installs the handlers on the thread-local stack as lexical handlers of the program's random and score instances, serves the program's host steps through Compute handlers over torch, and evaluates the whole on the reference machine. The value it returns is the program's output; handlers accumulate state on the side. A caller that wants a Trace stacks a TraceHandler before run_program and reads its trace attribute afterwards; the thin quivers.inference.trace.trace wrapper does exactly this.

The nesting of the installed handlers, outermost first, is fixed by the kernel's rules rather than by the order of the stack alone: the run's score accumulator, then every stack handler of the score instance in stack order, then the default scoring draw and the run's observations, then every stack handler of the random instance in stack order, then the parameter store with every stack handler of the param instance inside it, then the host steps. A density is a Score.add the answering handler emits outward, so a score transformer anywhere on the stack reaches every site, and an inner random handler sees the answer an outer one gives.

HostValue

HostValue = Tensor | int | float | bool | str | TorchSampleable | tuple[HostValue, ...] | None

A value a host step produces or consumes: a tensor, a number, a string, a sampleable, None, or a tuple of such values.

RunValue

RunValue = Tensor | tuple[RunValue, ...]

A let or score value computed from one run's bindings: a tensor or a tuple of them.

host_value

host_value(value: object) -> TypeIs[HostValue]

Whether a value is one a host step may produce or consume.

PARAMETER DESCRIPTION
value

The value.

TYPE: object

RETURNS DESCRIPTION
bool

True for tensors, numbers, strings, sampleables, None, and tuples of such values. The kernel checks the terms statically; the host convention is that every tensor carries the batch axis in front of the shape its type names.

Source code in src/quivers/effects/interpreter.py
def host_value(value: object) -> TypeIs[HostValue]:
    """Whether a value is one a host step may produce or consume.

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

    Returns
    -------
    bool
        True for tensors, numbers, strings, sampleables, ``None``, and
        tuples of such values. The kernel checks the terms statically;
        the host convention is that every tensor carries the batch axis
        in front of the shape its type names.
    """
    if isinstance(value, tuple):
        return all(host_value(item) for item in value)
    return value is None or isinstance(
        value, torch.Tensor | int | float | bool | str | TorchSampleable
    )

check_host_data

check_host_data(program: MonadicProgram | CheckedProgram, data: Mapping[str, object], runs: int | None = None) -> dict[str, bool]

Refuse host data that does not inhabit the program's checked types.

The checked elaboration types every free name a program reads, and every target the module renders to reads the name at that type. A datum whose shape or element type differs would make the run compute a model the checked module does not describe, so it is refused. A dimension the checked type leaves as an extent variable takes the length of the first datum it shapes, and every later datum it shapes must agree. A run over an input batch replicates the whole program once per batch entry, so a datum may also carry one leading axis of the batch's length, one value of its checked type per run. A datum that fills a parameter of a plated draw directly, listed in the program's host_data_shared, may also omit the plate axis its checked type leads with: it is then one value every row shares.

PARAMETER DESCRIPTION
program

The program, whose host_data_types give the checked types.

TYPE: MonadicProgram or CheckedProgram

data

The supplied host data, by name.

TYPE: Mapping[str, object]

runs

The length of the input batch, whose axis a datum may lead with; None admits no such axis.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, bool]

For each checked datum supplied, whether it leads with the input batch's axis, one value per run, rather than one value every run shares.

RAISES DESCRIPTION
ValueError

If a datum's shape differs from the shape its checked type names, or an extent variable is fixed at two different lengths.

TypeError

If a datum's element type is not the one its checked type names.

Source code in src/quivers/effects/interpreter.py
def check_host_data(
    program: MonadicProgram | CheckedProgram,
    data: Mapping[str, object],
    runs: int | None = None,
) -> dict[str, bool]:
    """Refuse host data that does not inhabit the program's checked types.

    The checked elaboration types every free name a program reads, and
    every target the module renders to reads the name at that type. A
    datum whose shape or element type differs would make the run compute
    a model the checked module does not describe, so it is refused. A
    dimension the checked type leaves as an extent variable takes the
    length of the first datum it shapes, and every later datum it shapes
    must agree. A run over an input batch replicates the whole program
    once per batch entry, so a datum may also carry one leading axis of
    the batch's length, one value of its checked type per run. A datum
    that fills a parameter of a plated draw directly, listed in the
    program's ``host_data_shared``, may also omit the plate axis its
    checked type leads with: it is then one value every row shares.

    Parameters
    ----------
    program : MonadicProgram or CheckedProgram
        The program, whose ``host_data_types`` give the checked types.
    data : Mapping[str, object]
        The supplied host data, by name.
    runs : int | None
        The length of the input batch, whose axis a datum may lead with;
        ``None`` admits no such axis.

    Returns
    -------
    dict[str, bool]
        For each checked datum supplied, whether it leads with the input
        batch's axis, one value per run, rather than one value every run
        shares.

    Raises
    ------
    ValueError
        If a datum's shape differs from the shape its checked type names,
        or an extent variable is fixed at two different lengths.
    TypeError
        If a datum's element type is not the one its checked type names.
    """
    from quivers.qiec.types import IndexSum
    from quivers.qiec.index_arithmetic import infer_index_extents

    extents: dict[str, tuple[int, str]] = {}
    affine_equations: list[tuple[IndexTerm, int]] = []
    per_run_data: dict[str, bool] = {}
    nonnegative = (
        {
            parameter.name
            for parameter in program.input_contract.parameters
            if parameter.constraint == "nonnegative"
        }
        if program.input_contract is not None
        else set()
    )
    for name, expected in program.host_data_types.items():
        if name not in data:
            continue
        split = tensor_shape(expected)
        element, dimensions = (expected, ()) if split is None else split
        rendered = render_static(expected)
        if element == STRING:
            # Text has no tensor form: a sentence is a sequence of tokens,
            # a corpus a sequence of equally long sentences.
            supplied = _string_shape(name, data[name], rendered)
            value = None
        else:
            try:
                value = torch.as_tensor(data[name])
            except (TypeError, ValueError, RuntimeError) as error:
                raise TypeError(
                    f"host datum {name!r} cannot be read at checked type {rendered}"
                ) from error
            supplied = tuple(value.shape)
        layouts = [tuple(dimensions)]
        if name in program.host_data_shared and dimensions:
            layouts.append(tuple(dimensions[1:]))
        per_run, layout = _matching_layout(supplied, layouts, runs)
        if layout is None:
            admissible = " or ".join(_rendered_shape(item) for item in layouts)
            shared = (
                ", the second a value every row of the plate shares"
                if len(layouts) > 1
                else ""
            )
            note = program.host_data_notes.get(name)
            raise ValueError(
                f"host datum {name!r} has shape {supplied}, but the checked "
                f"program reads it at type {rendered}, of shape "
                f"{admissible}{shared}; supply data of that shape"
                + ("" if note is None else f". {note}")
            )
        per_run_data[name] = per_run != supplied
        dimensions = layout
        for dimension, extent in zip(dimensions, per_run):
            if isinstance(dimension, IndexSum):
                affine_equations.append((dimension, extent))
            if not isinstance(dimension, IndexVariable):
                continue
            fixed = extents.setdefault(dimension.name, (extent, name))
            if fixed[0] != extent:
                raise ValueError(
                    f"host datum {name!r} fixes extent {dimension.name!r} at "
                    f"{extent}, but {fixed[1]!r} fixes it at {fixed[0]}"
                )
        if value is not None and not _element_admits(element, value):
            raise TypeError(
                f"host datum {name!r} has dtype {value.dtype}, but the checked "
                f"program reads it at type {rendered}, whose elements are "
                f"{render_static(element)}"
            )
        if value is not None and name in nonnegative and bool((value < 0).any()):
            raise ValueError(f"host datum {name!r} must be a nonnegative integer")
    if affine_equations:
        for name, extent in infer_index_extents(
            affine_equations, {key: value for key, (value, _) in extents.items()}
        ).items():
            extents.setdefault(name, (extent, "checked affine shapes"))
    for name, bounds in program.host_index_bounds.items():
        if name not in data:
            continue
        value = torch.as_tensor(data[name])
        for bound in bounds:
            if isinstance(bound, IndexLiteral):
                size = bound.value
            elif isinstance(bound, IndexVariable) and bound.name in extents:
                size = extents[bound.name][0]
            elif isinstance(bound, IndexSum) and all(
                term.name in extents for term in bound.terms
            ):
                size = bound.constant + sum(
                    extents[term.name][0] for term in bound.terms
                )
            else:
                continue
            if bool(((value < 0) | (value >= size)).any()):
                raise ValueError(
                    f"index datum {name!r} must contain indices in [0, {size})"
                )
    return per_run_data

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)

sample_program

sample_program(program: MonadicProgram, x: Tensor, sample_shape: Size = Size(), observations: Mapping[str, Tensor] | None = None) -> Tensor | dict[str, Tensor]

Run a program forward under the handler stack, with sample dimensions.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

x

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

TYPE: Tensor

sample_shape

Leading sample dimensions. Each element of the shape is one independent run of the program; the returned values stack the runs ahead of their batch axis.

TYPE: Size DEFAULT: Size()

observations

Values to condition observed sites on, keyed by site name, and host data the steps read by name.

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

RETURNS DESCRIPTION
Tensor or dict[str, Tensor]

The program's return value, with sample_shape in front.

Source code in src/quivers/effects/interpreter.py
def sample_program(
    program: MonadicProgram,
    x: torch.Tensor,
    sample_shape: torch.Size = torch.Size(),
    observations: Mapping[str, torch.Tensor] | None = None,
) -> torch.Tensor | dict[str, torch.Tensor]:
    """Run a program forward under the handler stack, with sample dimensions.

    Parameters
    ----------
    program : MonadicProgram
        The program.
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.
    sample_shape : torch.Size
        Leading sample dimensions. Each element of the shape is one
        independent run of the program; the returned values stack the
        runs ahead of their batch axis.
    observations : Mapping[str, torch.Tensor] or None
        Values to condition observed sites on, keyed by site name, and
        host data the steps read by name.

    Returns
    -------
    torch.Tensor or dict[str, torch.Tensor]
        The program's return value, with ``sample_shape`` in front.
    """
    if not sample_shape:
        return run_program(program, x, observations)
    count = 1
    for extent in sample_shape:
        count *= int(extent)
    runs = [run_program(program, x, observations) for _ in range(count)]
    first = runs[0]
    if isinstance(first, torch.Tensor):
        stacked = torch.stack([run for run in runs if isinstance(run, torch.Tensor)])
        return stacked.reshape(*sample_shape, *first.shape)
    assert isinstance(first, dict)
    return {
        key: torch.stack([cast_dict(run)[key] for run in runs]).reshape(
            *sample_shape, *first[key].shape
        )
        for key in first
    }

cast_dict

cast_dict(value: Tensor | dict[str, Tensor]) -> dict[str, Tensor]

Read a program's dictionary return.

PARAMETER DESCRIPTION
value

A program's return value.

TYPE: Tensor | dict[str, Tensor]

RETURNS DESCRIPTION
dict[str, Tensor]

The value, which is a dictionary.

RAISES DESCRIPTION
TypeError

If the value is a single tensor.

Source code in src/quivers/effects/interpreter.py
def cast_dict(value: torch.Tensor | dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
    """Read a program's dictionary return.

    Parameters
    ----------
    value : torch.Tensor | dict[str, torch.Tensor]
        A program's return value.

    Returns
    -------
    dict[str, torch.Tensor]
        The value, which is a dictionary.

    Raises
    ------
    TypeError
        If the value is a single tensor.
    """
    if isinstance(value, dict):
        return value
    raise TypeError("the program returns a single tensor, not named values")

log_joint

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

The joint log density of a program at values for all of its draws.

The program runs on the reference machine under the handler stack with every draw conditioned on its given value. An input of B rows is B independent runs of the whole program, and the joint is one number per run: the sum of that run's site densities. The joint of all the runs together is the sum of the result.

PARAMETER DESCRIPTION
program

The program.

TYPE: MonadicProgram

x

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

TYPE: Tensor

intermediates

A value for every draw the program makes, keyed by variable name or by return label, together with any host data its steps read by name. A value is given either once per run, along a leading axis of length B, or once for every run to share.

TYPE: Mapping[str, Tensor]

RETURNS DESCRIPTION
Tensor

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

RAISES DESCRIPTION
KeyError

If a draw the program makes is given no value.

Source code in src/quivers/effects/interpreter.py
def log_joint(
    program: MonadicProgram,
    x: torch.Tensor,
    intermediates: Mapping[str, torch.Tensor],
) -> torch.Tensor:
    """The joint log density of a program at values for all of its draws.

    The program runs on the reference machine under the handler stack
    with every draw conditioned on its given value. An input of ``B``
    rows is ``B`` independent runs of the whole program, and the joint
    is one number per run: the sum of that run's site densities. The
    joint of all the runs together is the sum of the result.

    Parameters
    ----------
    program : MonadicProgram
        The program.
    x : torch.Tensor
        Program input. Shape ``(batch, ...)``.
    intermediates : Mapping[str, torch.Tensor]
        A value for every draw the program makes, keyed by variable
        name or by return label, together with any host data its steps
        read by name. A value is given either once per run, along a
        leading axis of length ``B``, or once for every run to share.

    Returns
    -------
    torch.Tensor
        The joint log density of each run, shaped ``(B,)``.

    Raises
    ------
    KeyError
        If a draw the program makes is given no value.
    """
    values = dict(intermediates)
    if program._return_labels:
        for label, name in zip(
            program._return_labels, program._return_vars, strict=True
        ):
            if label in values and name not in values:
                values[name] = values[label]
    mapped = _mapped_joint(program, x, values)
    if mapped is not None:
        return mapped
    with TraceHandler() as handler:
        run_program(program, x, values)
    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)

Cited sources

Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.

Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.