Skip to content

Program runtime

sample_program and run_program run a program's entry point on the reference machine and return its value and log joint density. sample_program draws the sites it is not given, and run_program replays a value for every site.

program_runtime

Running program entry points on the reference machine.

An elaborated program is a named computation whose row names the module's canonical random and score instances. Running it means choosing handlers for the two: this module wraps the entry point in a scoring replay of Random and an accumulating Score, so a program applied to data and to a value for each of its sites yields the value it returns and the log joint density the sites and observations accumulate. The wrapper is an ordinary computation added to a copy of the module, so the kernel checks it like any other before it runs.

ProgramRun didactic-model

ProgramRun(*, value: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_joint: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), result: ExecutionResult = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

What running a program on the reference machine produced.

PARAMETER DESCRIPTION
value

The value the program returned, as the machine holds it.

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

log_joint

The log joint density: every replayed site's log density under its distribution plus every observation's and score's weight, a scalar tensor of the run's real dtype with the gradient of every tensor the run was given.

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

result

The underlying execution result, with its trace.

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

DeductionRun didactic-model

DeductionRun(*, weight: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), result: ExecutionResult = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

The outcome of running a deduction on the reference machine.

PARAMETER DESCRIPTION
weight

The inside weight of the goal in the deduction's semiring: a log weight, a Boolean, or a count; or, when an iteration stopped by a control and the caller asked for it, the last iterate held as Unestablished, which no weight-taking code accepts.

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

result

The machine's full result, with its trace when one was recorded.

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

program_entry

program_entry(module: QiecModule, name: str) -> ProgramEntry

Find a program's entry point in a module.

PARAMETER DESCRIPTION
module

The module.

TYPE: QiecModule

name

The program's name.

TYPE: str

RETURNS DESCRIPTION
ProgramEntry

The entry.

RAISES DESCRIPTION
KeyError

If the module has no program of that name.

Source code in src/quivers/qiec/program_runtime.py
def program_entry(module: QiecModule, name: str) -> ProgramEntry:
    """Find a program's entry point in a module.

    Parameters
    ----------
    module : QiecModule
        The module.
    name : str
        The program's name.

    Returns
    -------
    ProgramEntry
        The entry.

    Raises
    ------
    KeyError
        If the module has no program of that name.
    """
    for entry in module.entries:
        if entry.name == name:
            return entry
    raise KeyError(f"module {module.module!r} has no program {name!r}")

joint_module

joint_module(module: QiecModule, name: str) -> tuple[QiecModule, str]

Extend a module with a computation scoring one program's log joint.

PARAMETER DESCRIPTION
module

The module holding the program.

TYPE: QiecModule

name

The program's name.

TYPE: str

RETURNS DESCRIPTION
tuple[QiecModule, str]

The extended module and the wrapper computation's name. The wrapper takes the program's parameters, handles its score instance with an accumulating handler and its random instance with a replaying one, and returns the program's value paired with the accumulated log weight.

RAISES DESCRIPTION
KeyError

If the module has no such program.

Source code in src/quivers/qiec/program_runtime.py
def joint_module(module: QiecModule, name: str) -> tuple[QiecModule, str]:
    """Extend a module with a computation scoring one program's log joint.

    Parameters
    ----------
    module : QiecModule
        The module holding the program.
    name : str
        The program's name.

    Returns
    -------
    tuple[QiecModule, str]
        The extended module and the wrapper computation's name. The
        wrapper takes the program's parameters, handles its ``score``
        instance with an accumulating handler and its ``random``
        instance with a replaying one, and returns the program's value
        paired with the accumulated log weight.

    Raises
    ------
    KeyError
        If the module has no such program.
    """
    return _wrapped_module(module, name, sampling=False)

sample_module

sample_module(module: QiecModule, name: str) -> tuple[QiecModule, str]

Extend a module with a computation running one program forward.

PARAMETER DESCRIPTION
module

The module holding the program.

TYPE: QiecModule

name

The program's name.

TYPE: str

RETURNS DESCRIPTION
tuple[QiecModule, str]

The extended module and the wrapper computation's name. The wrapper takes the program's parameters, handles its random instance with a conditioning replay of the given sites inside a scoring draw of every other site, its score instance with an accumulating handler, and returns the program's value paired with the accumulated log weight: the log joint of the draws it made and the sites it was given.

RAISES DESCRIPTION
KeyError

If the module has no such program.

Source code in src/quivers/qiec/program_runtime.py
def sample_module(module: QiecModule, name: str) -> tuple[QiecModule, str]:
    """Extend a module with a computation running one program forward.

    Parameters
    ----------
    module : QiecModule
        The module holding the program.
    name : str
        The program's name.

    Returns
    -------
    tuple[QiecModule, str]
        The extended module and the wrapper computation's name. The
        wrapper takes the program's parameters, handles its ``random``
        instance with a conditioning replay of the given sites inside a
        scoring draw of every other site, its ``score`` instance with an
        accumulating handler, and returns the program's value paired
        with the accumulated log weight: the log joint of the draws it
        made and the sites it was given.

    Raises
    ------
    KeyError
        If the module has no such program.
    """
    return _wrapped_module(module, name, sampling=True)

broadcast_shared_data

broadcast_shared_data(entry: ProgramEntry, data: Mapping[str, object]) -> dict[str, object]

Spread each shared datum across the plate of the draw it fills.

A parameter that fills a family parameter of a plated draw directly (ProgramParameter.per_row) is typed with the draw's plate as its leading axis. A datum supplied without that axis is one value every row shares, and is replicated once per row so that it inhabits the checked type.

PARAMETER DESCRIPTION
entry

The program's entry point.

TYPE: ProgramEntry

data

The host value of each parameter, by name.

TYPE: Mapping[str, object]

RETURNS DESCRIPTION
dict[str, object]

The data, each shared datum replicated across its plate.

Source code in src/quivers/qiec/program_runtime.py
def broadcast_shared_data(
    entry: ProgramEntry, data: Mapping[str, object]
) -> dict[str, object]:
    """Spread each shared datum across the plate of the draw it fills.

    A parameter that fills a family parameter of a plated draw directly
    (`ProgramParameter.per_row`) is typed with the draw's plate as its
    leading axis. A datum supplied without that axis is one value every
    row shares, and is replicated once per row so that it inhabits the
    checked type.

    Parameters
    ----------
    entry : ProgramEntry
        The program's entry point.
    data : Mapping[str, object]
        The host value of each parameter, by name.

    Returns
    -------
    dict[str, object]
        The data, each shared datum replicated across its plate.
    """
    spread = dict(data)
    for parameter in entry.parameters:
        if not parameter.per_row or parameter.name not in spread:
            continue
        shape = tensor_shape(parameter.type)
        if shape is None or not shape[1]:
            continue
        plate = shape[1][0]
        value = spread[parameter.name]
        if (
            isinstance(plate, IndexLiteral)
            and isinstance(plate.value, int)
            and _host_rank(value) == len(shape[1]) - 1
        ):
            spread[parameter.name] = (
                value.expand(plate.value, *value.shape)
                if isinstance(value, torch.Tensor)
                else tuple(value for _ in range(plate.value))
            )
    return spread

static_arguments_for

static_arguments_for(entry: ProgramEntry, data: Mapping[str, object], given: Sequence[StaticArgument] = ()) -> tuple[StaticArgument, ...]

Read a program's static extents off the data it is applied to.

PARAMETER DESCRIPTION
entry

The program's entry point, whose telescope names the extents.

TYPE: ProgramEntry

data

The host value of each parameter, by name.

TYPE: Mapping[str, object]

given

Static arguments supplied explicitly, one per telescope binder in telescope order, or none. A template's object parameter is an extent no data fixes, so a run of the template supplies it; a binder the data does fix must agree with what is supplied.

TYPE: Sequence[StaticArgument] DEFAULT: ()

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

One index literal per telescope binder, in telescope order: the length of the axis of the first parameter whose tensor type is shaped by the binder, else the supplied argument.

RAISES DESCRIPTION
KeyError

If a binder shapes no parameter and none is supplied, or the parameter is not given or has too few axes, or a supplied argument disagrees with the data, or the supplied arguments do not number the telescope.

Source code in src/quivers/qiec/program_runtime.py
def static_arguments_for(
    entry: ProgramEntry,
    data: Mapping[str, object],
    given: Sequence[StaticArgument] = (),
) -> tuple[StaticArgument, ...]:
    """Read a program's static extents off the data it is applied to.

    Parameters
    ----------
    entry : ProgramEntry
        The program's entry point, whose telescope names the extents.
    data : Mapping[str, object]
        The host value of each parameter, by name.
    given : Sequence[StaticArgument]
        Static arguments supplied explicitly, one per telescope binder
        in telescope order, or none. A template's object parameter is
        an extent no data fixes, so a run of the template supplies it;
        a binder the data does fix must agree with what is supplied.

    Returns
    -------
    tuple[StaticArgument, ...]
        One index literal per telescope binder, in telescope order: the
        length of the axis of the first parameter whose tensor type is
        shaped by the binder, else the supplied argument.

    Raises
    ------
    KeyError
        If a binder shapes no parameter and none is supplied, or the
        parameter is not given or has too few axes, or a supplied
        argument disagrees with the data, or the supplied arguments do
        not number the telescope.
    """
    if given and len(given) != len(entry.telescope):
        raise KeyError(
            f"program {entry.name!r} binds {len(entry.telescope)} extent(s); "
            f"{len(given)} static argument(s) were given"
        )
    affine_equations: list[tuple[IndexTerm, int]] = []
    for parameter in entry.parameters:
        shape = tensor_shape(parameter.type)
        if shape is None or parameter.name not in data:
            continue
        for depth, dimension in enumerate(shape[1]):
            if isinstance(dimension, IndexSum | IndexVariable):
                try:
                    observed = _extent_of(data[parameter.name], depth)
                except KeyError as error:
                    raise KeyError(
                        f"cannot infer extent from input {parameter.name!r}: {error}"
                    ) from error
                affine_equations.append((dimension, observed))
    inferred: dict[str, int] = {}
    if affine_equations or given:
        from quivers.qiec.index_arithmetic import infer_index_extents

        supplied_extents = {
            binder.name: int(value.value)
            for binder, value in zip(entry.telescope, given)
            if isinstance(binder, IndexBinder)
            and isinstance(value, IndexLiteral)
            and isinstance(value.value, int)
        }
        try:
            inferred = infer_index_extents(affine_equations, supplied_extents)
        except (TypeError, ValueError) as error:
            raise KeyError(
                f"program {entry.name!r} has invalid shape evidence: {error}"
            ) from error
    arguments: list[StaticArgument] = []
    for position, binder in enumerate(entry.telescope):
        supplied = given[position] if given else None
        found: int | None = inferred.get(binder.name)
        if found is None:
            if supplied is None:
                raise KeyError(
                    f"program {entry.name!r} has an extent {binder.name!r} that "
                    "no parameter fixes; supply it as a static argument"
                )
            arguments.append(supplied)
            continue
        literal = IndexLiteral(value=found, sort=binder.sort)  # type: ignore[arg-type]
        if supplied is not None and supplied != literal:
            raise KeyError(
                f"static argument {binder.name!r} of program {entry.name!r} is "
                f"given as {render_static(supplied)}, but its data fix it at "
                f"{found}"
            )
        arguments.append(literal)
    return tuple(arguments)

run_program

run_program(module: QiecModule, name: str, *, data: Mapping[str, object], sites: Mapping[str, object], parameters: Mapping[str, object] | None = None, static_arguments: Sequence[StaticArgument] = (), fuel: int | None = None, observer: TraceObserver | None = None, providers: tuple[RuntimeProvider, ...] = (), numbers: NumberDomain | None = None, distributions: DistributionBackend | None = None) -> ProgramRun

Run a program with every site replayed and score its log joint.

PARAMETER DESCRIPTION
module

The module holding the program.

TYPE: QiecModule

name

The program's name.

TYPE: str

data

A host value for each of the program's parameters, by name: its data, observations, index maps, and map numbers.

TYPE: Mapping[str, object]

sites

A host value for each sampled site, by label, or by label and occurrence as "<label>@<n>" for a site a recurrence reaches at every position. Every site the program reaches must be given, and every given site reached.

TYPE: Mapping[str, object]

parameters

The learned weights a deduction the program calls reads, by name; an absent weight reads as zero.

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

static_arguments

The program's static extents, one per telescope binder, for an extent no data fixes (a template's object parameter); empty when the data fix every extent.

TYPE: Sequence[StaticArgument] DEFAULT: ()

fuel

A step budget for the run.

TYPE: int | None DEFAULT: None

observer

A callback receiving every trace event as it is emitted.

TYPE: TraceObserver | None DEFAULT: None

providers

Additional typed providers used by computations the program calls.

TYPE: tuple[RuntimeProvider, ...] DEFAULT: ()

numbers

The dtype and device of the run's numbers; float64 on the CPU, the precision of Python numbers, when None. Data, sites and weights are converted to it where they enter, and a tensor keeps its gradient.

TYPE: NumberDomain | None DEFAULT: None

distributions

The backend that samples and scores the program's distributions; the installed backend when None.

TYPE: DistributionBackend | None DEFAULT: None

RETURNS DESCRIPTION
ProgramRun

The returned value and the log joint.

RAISES DESCRIPTION
KeyError

If the module has no such program, a parameter is not given, or an open extent cannot be read off the data.

ExecutionFailure

If the run fails, a site is missing, or a value does not inhabit its type.

Source code in src/quivers/qiec/program_runtime.py
def run_program(
    module: QiecModule,
    name: str,
    *,
    data: Mapping[str, object],
    sites: Mapping[str, object],
    parameters: Mapping[str, object] | None = None,
    static_arguments: Sequence[StaticArgument] = (),
    fuel: int | None = None,
    observer: TraceObserver | None = None,
    providers: tuple[RuntimeProvider, ...] = (),
    numbers: NumberDomain | None = None,
    distributions: DistributionBackend | None = None,
) -> ProgramRun:
    """Run a program with every site replayed and score its log joint.

    Parameters
    ----------
    module : QiecModule
        The module holding the program.
    name : str
        The program's name.
    data : Mapping[str, object]
        A host value for each of the program's parameters, by name:
        its data, observations, index maps, and map numbers.
    sites : Mapping[str, object]
        A host value for each sampled site, by label, or by label and
        occurrence as ``"<label>@<n>"`` for a site a recurrence reaches
        at every position. Every site the program reaches must be
        given, and every given site reached.
    parameters : Mapping[str, object] | None
        The learned weights a deduction the program calls reads, by
        name; an absent weight reads as zero.
    static_arguments : Sequence[StaticArgument]
        The program's static extents, one per telescope binder, for an
        extent no data fixes (a template's object parameter); empty
        when the data fix every extent.
    fuel : int | None
        A step budget for the run.
    observer : TraceObserver | None
        A callback receiving every trace event as it is emitted.
    providers : tuple[RuntimeProvider, ...]
        Additional typed providers used by computations the program calls.
    numbers : NumberDomain | None
        The dtype and device of the run's numbers; ``float64`` on the CPU,
        the precision of Python numbers, when ``None``. Data, sites and
        weights are converted to it where they enter, and a tensor keeps
        its gradient.
    distributions : DistributionBackend | None
        The backend that samples and scores the program's distributions;
        the installed backend when ``None``.

    Returns
    -------
    ProgramRun
        The returned value and the log joint.

    Raises
    ------
    KeyError
        If the module has no such program, a parameter is not given, or
        an open extent cannot be read off the data.
    ExecutionFailure
        If the run fails, a site is missing, or a value does not inhabit
        its type.
    """
    entry = program_entry(module, name)
    extended, wrapper_name = joint_module(module, name)
    configured: dict[str, object] = {
        REPLAY_HANDLER: {
            "kind": "replay",
            "values": dict(sites),
            "score_instance": entry.score_instance,
        },
        ACCUMULATE_HANDLER: {"kind": "score"},
    }
    return _run_wrapped(
        module,
        extended,
        wrapper_name,
        entry,
        configured,
        data=data,
        parameters=parameters,
        static_arguments=static_arguments,
        fuel=fuel,
        observer=observer,
        providers=providers,
        numbers=numbers,
        distributions=distributions,
    )

sample_program

sample_program(module: QiecModule, name: str, *, data: Mapping[str, object], sites: Mapping[str, object] | None = None, parameters: Mapping[str, object] | None = None, static_arguments: Sequence[StaticArgument] = (), fuel: int | None = None, observer: TraceObserver | None = None, providers: tuple[RuntimeProvider, ...] = (), numbers: NumberDomain | None = None, distributions: DistributionBackend | None = None) -> ProgramRun

Run a program forward, drawing every site it is not given.

PARAMETER DESCRIPTION
module

The module holding the program.

TYPE: QiecModule

name

The program's name.

TYPE: str

data

A host value for each of the program's parameters, by name: its data, observations, index maps, and map numbers.

TYPE: Mapping[str, object]

sites

A host value for each conditioned site, by label, or by label and occurrence as "<label>@<n>"; every other site is drawn from its distribution. A given site the program never reaches is an error.

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

parameters

The learned weights a deduction the program calls reads, by name; an absent weight reads as zero.

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

static_arguments

The program's static extents, one per telescope binder, for an extent no data fixes; empty when the data fix every extent.

TYPE: Sequence[StaticArgument] DEFAULT: ()

fuel

A step budget for the run.

TYPE: int | None DEFAULT: None

observer

A callback receiving every trace event as it is emitted.

TYPE: TraceObserver | None DEFAULT: None

providers

Additional typed providers used by computations the program calls.

TYPE: tuple[RuntimeProvider, ...] DEFAULT: ()

numbers

The dtype and device of the run's numbers; float64 on the CPU, the precision of Python numbers, when None. Data, sites and weights are converted to it where they enter, and a tensor keeps its gradient.

TYPE: NumberDomain | None DEFAULT: None

distributions

The backend that samples and scores the program's distributions; the installed backend when None.

TYPE: DistributionBackend | None DEFAULT: None

RETURNS DESCRIPTION
ProgramRun

The returned value and the log joint of the drawn and given sites together with the program's observations and scores.

RAISES DESCRIPTION
KeyError

If the module has no such program, a parameter is not given, or an open extent cannot be read off the data.

ExecutionFailure

If the run fails or a value does not inhabit its type.

Source code in src/quivers/qiec/program_runtime.py
def sample_program(
    module: QiecModule,
    name: str,
    *,
    data: Mapping[str, object],
    sites: Mapping[str, object] | None = None,
    parameters: Mapping[str, object] | None = None,
    static_arguments: Sequence[StaticArgument] = (),
    fuel: int | None = None,
    observer: TraceObserver | None = None,
    providers: tuple[RuntimeProvider, ...] = (),
    numbers: NumberDomain | None = None,
    distributions: DistributionBackend | None = None,
) -> ProgramRun:
    """Run a program forward, drawing every site it is not given.

    Parameters
    ----------
    module : QiecModule
        The module holding the program.
    name : str
        The program's name.
    data : Mapping[str, object]
        A host value for each of the program's parameters, by name:
        its data, observations, index maps, and map numbers.
    sites : Mapping[str, object] | None
        A host value for each conditioned site, by label, or by label
        and occurrence as ``"<label>@<n>"``; every other site is drawn
        from its distribution. A given site the program never reaches
        is an error.
    parameters : Mapping[str, object] | None
        The learned weights a deduction the program calls reads, by
        name; an absent weight reads as zero.
    static_arguments : Sequence[StaticArgument]
        The program's static extents, one per telescope binder, for an
        extent no data fixes; empty when the data fix every extent.
    fuel : int | None
        A step budget for the run.
    observer : TraceObserver | None
        A callback receiving every trace event as it is emitted.
    providers : tuple[RuntimeProvider, ...]
        Additional typed providers used by computations the program calls.
    numbers : NumberDomain | None
        The dtype and device of the run's numbers; ``float64`` on the CPU,
        the precision of Python numbers, when ``None``. Data, sites and
        weights are converted to it where they enter, and a tensor keeps
        its gradient.
    distributions : DistributionBackend | None
        The backend that samples and scores the program's distributions;
        the installed backend when ``None``.

    Returns
    -------
    ProgramRun
        The returned value and the log joint of the drawn and given
        sites together with the program's observations and scores.

    Raises
    ------
    KeyError
        If the module has no such program, a parameter is not given, or
        an open extent cannot be read off the data.
    ExecutionFailure
        If the run fails or a value does not inhabit its type.
    """
    entry = program_entry(module, name)
    extended, wrapper_name = sample_module(module, name)
    configured: dict[str, object] = {
        CONDITION_HANDLER: {
            "kind": "replay",
            "values": dict(sites or {}),
            "score_instance": entry.score_instance,
        },
        DRAW_HANDLER: {"kind": "draw-scoring", "score_instance": entry.score_instance},
        ACCUMULATE_HANDLER: {"kind": "score"},
    }
    return _run_wrapped(
        module,
        extended,
        wrapper_name,
        entry,
        configured,
        data=data,
        parameters=parameters,
        static_arguments=static_arguments,
        fuel=fuel,
        observer=observer,
        providers=providers,
        numbers=numbers,
        distributions=distributions,
    )

passed_data_notes

passed_data_notes(module: QiecModule, name: str) -> dict[str, str]

Where each datum a program passes straight to a computation goes.

A free name passed only as a call's argument takes the type of the parameter it fills; a call does not map the computation over the entries of a tensor. When a datum of another shape is supplied, the refusal says which call fixed the datum's type and what to write instead.

PARAMETER DESCRIPTION
module

The module holding the program.

TYPE: QiecModule

name

The program's name.

TYPE: str

RETURNS DESCRIPTION
dict[str, str]

For each data parameter some call reads as a whole argument, a located note naming the call, the parameter it fills, and the remedy: declare the parameter as a tensor and map over it inside the computation.

Source code in src/quivers/qiec/program_runtime.py
def passed_data_notes(module: QiecModule, name: str) -> dict[str, str]:
    """Where each datum a program passes straight to a computation goes.

    A free name passed only as a call's argument takes the type of the
    parameter it fills; a call does not map the computation over the
    entries of a tensor. When a datum of another shape is supplied, the
    refusal says which call fixed the datum's type and what to write
    instead.

    Parameters
    ----------
    module : QiecModule
        The module holding the program.
    name : str
        The program's name.

    Returns
    -------
    dict[str, str]
        For each data parameter some call reads as a whole argument, a
        located note naming the call, the parameter it fills, and the
        remedy: declare the parameter as a tensor and ``map`` over it
        inside the computation.
    """
    entry = program_entry(module, name)
    data = {
        parameter.name
        for parameter in entry.parameters
        if parameter.role in ("data", "index_map")
    }
    body = _computation(module, entry.computation).body
    notes: dict[str, str] = {}
    pending: list[Computation] = [body]
    while pending:
        node = pending.pop()
        if not isinstance(node, Bind):
            continue
        pending.append(node.then)
        first = node.first
        if isinstance(first, Bind):
            pending.append(first)
            continue
        if not isinstance(first, Call):
            continue
        callee = _computation(module, first.callee)
        for argument, parameter in zip(first.arguments, callee.parameters):
            if not isinstance(argument, Var) or argument.local.name not in data:
                continue
            datum = argument.local.name
            where = (
                f"line {first.origin.line}, col {first.origin.column}: "
                if first.origin.line
                else ""
            )
            notes.setdefault(
                datum,
                f"{where}`let {node.binder.name} <- {first.name}(...)` passes "
                f"{datum!r} to the parameter `{parameter.name} : "
                f"{render_static(parameter.type)}` of `{first.name}`, which "
                f"fixes its type; a call does not map a computation over a "
                f"tensor's entries: declare the parameter as a tensor and "
                f"`map` over it inside the computation",
            )
    return notes

foreign_handler_configuration

foreign_handler_configuration(module: QiecModule, *, on_failure: FailurePolicy = REFUSE, reports: list[AccuracyReport] | None = None, reached: frozenset[HandlerId] | None = None) -> dict[str, object]

The runtime configuration of a module's foreign handlers.

Every foreign handler whose declaration states what it computes is served by that statement: the enumerations and collectors of marginalization blocks, and the searches, collectors and settlements of deductions. Nothing is read off a handler's name.

PARAMETER DESCRIPTION
module

The module.

TYPE: QiecModule

on_failure

What a settlement does with a stop by a control: refuse, or record the report and resume with the value.

TYPE: FailurePolicy DEFAULT: REFUSE

reports

Where the settlements record the reports of unestablished stops.

TYPE: list of AccuracyReport or None DEFAULT: None

reached

The handlers a run may install, so a run configures those and no other declaration of its module; None configures every one.

TYPE: frozenset of HandlerId or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, object]

The configuration of each such handler, by name.

Source code in src/quivers/qiec/program_runtime.py
def foreign_handler_configuration(
    module: QiecModule,
    *,
    on_failure: FailurePolicy = FailurePolicy.REFUSE,
    reports: list[AccuracyReport] | None = None,
    reached: frozenset[HandlerId] | None = None,
) -> dict[str, object]:
    """The runtime configuration of a module's foreign handlers.

    Every foreign handler whose declaration states what it computes is
    served by that statement: the enumerations and collectors of
    marginalization blocks, and the searches, collectors and
    settlements of deductions. Nothing is read off a handler's name.

    Parameters
    ----------
    module : QiecModule
        The module.
    on_failure : FailurePolicy
        What a settlement does with a stop by a control: refuse, or
        record the report and resume with the value.
    reports : list of AccuracyReport or None
        Where the settlements record the reports of unestablished stops.
    reached : frozenset of HandlerId or None
        The handlers a run may install, so a run configures those and no
        other declaration of its module; ``None`` configures every one.

    Returns
    -------
    dict[str, object]
        The configuration of each such handler, by name.
    """
    configured: dict[str, object] = {}
    for handler in module.handlers:
        if handler.implementation != "foreign" or handler.foreign is None:
            continue
        if reached is not None and handler.id not in reached:
            continue
        options: dict[str, object] = {"kind": "declared"}
        if isinstance(handler.foreign, Settlement):
            options["on_failure"] = on_failure
            options["reports"] = reports
        configured[handler.name] = options
    return configured

run_deduction

run_deduction(module: QiecModule, name: str, *, tokens: Sequence[str] | None = None, axioms: Sequence[object] | None = None, axiom_weights: Sequence[object] | None = None, parameters: Mapping[str, object] | None = None, observer: TraceObserver | None = None, record_trace: bool = False, fuel: int | None = None, on_failure: FailurePolicy = REFUSE) -> DeductionRun

Run a deduction's entry on the reference machine.

A deduction whose derivations may repeat an item iterates to a fixed point. A stop is certified when the arithmetic is exact (a fixed point reached from below is the least one) or when the iteration found no further derivation; a stop because two iterates agree within the declared tolerance, or agree in rounded arithmetic while derivations keep growing, certifies nothing, and the run refuses it or returns it as unestablished, as on_failure says.

PARAMETER DESCRIPTION
module

The module holding the deduction.

TYPE: QiecModule

name

The deduction's name.

TYPE: str

tokens

The sentence, for a deduction with a lexicon.

TYPE: Sequence[str] | None DEFAULT: None

axioms

The axiom items, for a deduction without one; runtime constructor values of its item family.

TYPE: Sequence[object] | None DEFAULT: None

axiom_weights

One weight per axiom in the semiring's carrier.

TYPE: Sequence[object] | None DEFAULT: None

parameters

The learned weights by name; an absent weight reads as zero.

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

observer

A callback receiving every trace event as the machine emits it.

TYPE: TraceObserver | None DEFAULT: None

record_trace

Whether the result keeps every event. The search enumerates derivations, so its events grow with the number of derivation steps while its live state grows with the sentence; they are kept only when asked for.

TYPE: bool DEFAULT: False

fuel

A step budget for the run. A run that spends it is refused.

TYPE: int | None DEFAULT: None

on_failure

What a stop by a control does: refuse, or return the value as Unestablished with the report that says why.

TYPE: FailurePolicy DEFAULT: REFUSE

RETURNS DESCRIPTION
DeductionRun

The goal's inside weight.

RAISES DESCRIPTION
KeyError

If the module has no such deduction.

ValueError

If the input does not fit the deduction: tokens for one that takes axioms, or the reverse.

ContractNotMet

If an iteration stopped by a control and the policy refuses.

ExecutionFailure

If the run fails.

Source code in src/quivers/qiec/program_runtime.py
def run_deduction(
    module: QiecModule,
    name: str,
    *,
    tokens: Sequence[str] | None = None,
    axioms: Sequence[object] | None = None,
    axiom_weights: Sequence[object] | None = None,
    parameters: Mapping[str, object] | None = None,
    observer: TraceObserver | None = None,
    record_trace: bool = False,
    fuel: int | None = None,
    on_failure: FailurePolicy = FailurePolicy.REFUSE,
) -> DeductionRun:
    """Run a deduction's entry on the reference machine.

    A deduction whose derivations may repeat an item iterates to a
    fixed point. A stop is certified when the arithmetic is exact (a
    fixed point reached from below is the least one) or when the
    iteration found no further derivation; a stop because two iterates
    agree within the declared tolerance, or agree in rounded arithmetic
    while derivations keep growing, certifies nothing, and the run
    refuses it or returns it as unestablished, as ``on_failure`` says.

    Parameters
    ----------
    module : QiecModule
        The module holding the deduction.
    name : str
        The deduction's name.
    tokens : Sequence[str] | None
        The sentence, for a deduction with a lexicon.
    axioms : Sequence[object] | None
        The axiom items, for a deduction without one; runtime
        constructor values of its item family.
    axiom_weights : Sequence[object] | None
        One weight per axiom in the semiring's carrier.
    parameters : Mapping[str, object] | None
        The learned weights by name; an absent weight reads as zero.
    observer : TraceObserver | None
        A callback receiving every trace event as the machine emits it.
    record_trace : bool
        Whether the result keeps every event. The search enumerates
        derivations, so its events grow with the number of derivation
        steps while its live state grows with the sentence; they are kept
        only when asked for.
    fuel : int | None
        A step budget for the run. A run that spends it is refused.
    on_failure : FailurePolicy
        What a stop by a control does: refuse, or return the value as
        `Unestablished` with the report that says why.

    Returns
    -------
    DeductionRun
        The goal's inside weight.

    Raises
    ------
    KeyError
        If the module has no such deduction.
    ValueError
        If the input does not fit the deduction: tokens for one that
        takes axioms, or the reverse.
    ContractNotMet
        If an iteration stopped by a control and the policy refuses.
    ExecutionFailure
        If the run fails.
    """
    entry_name = member_name(name, "derive")
    if not any(item.name == entry_name for item in module.computations):
        raise KeyError(f"module {module.module!r} has no deduction {name!r}")
    computation = next(
        item for item in module.computations if item.name == member_name(name, "run")
    )
    takes_tokens = len(computation.parameters) == 1
    if takes_tokens and (tokens is None or axioms is not None):
        raise ValueError(f"deduction {name!r} takes a sentence of tokens")
    if not takes_tokens and (
        axioms is None or axiom_weights is None or tokens is not None
    ):
        raise ValueError(f"deduction {name!r} takes its axioms and their weights")
    extended, wrapper_name = _deduction_wrapper(module, computation)
    if takes_tokens:
        assert tokens is not None
        arguments: tuple[object, ...] = (tuple(tokens),)
        extent = len(tokens)
    else:
        assert axioms is not None and axiom_weights is not None
        arguments = (tuple(axioms), tuple(axiom_weights))
        extent = len(axioms)
    binder = computation.telescope[0]
    assert isinstance(binder, IndexBinder)
    configured: dict[str, object] = {}
    if wrapper_name != computation.name:
        configured[PARAMS_HANDLER] = {"kind": "param", "values": dict(parameters or {})}
    reports: list[AccuracyReport] = []
    configured.update(
        foreign_handler_configuration(
            module,
            on_failure=on_failure,
            reports=reports,
            reached=_reached(extended, wrapper_name),
        )
    )
    result = run_named(
        extended,
        wrapper_name,
        arguments,
        static_arguments=(IndexLiteral(value=extent, sort=binder.sort),),  # type: ignore[arg-type]
        runtime=RuntimeConfiguration(
            selections=(
                RuntimeSelection(provider="core", options={"handlers": configured}),
            )
        ),
        observer=observer,
        record_trace=record_trace,
        fuel=fuel,
    )
    if reports:
        (report,) = reports
        return DeductionRun(
            weight=Unestablished(value=result.value, report=report), result=result
        )
    return DeductionRun(weight=result.value, result=result)

deduction_item

deduction_item(module: QiecModule, name: str, symbol: str, *fields: object) -> RuntimeConstructor

Build an item of a deduction's family as a host value.

PARAMETER DESCRIPTION
module

The module holding the deduction.

TYPE: QiecModule

name

The deduction's name.

TYPE: str

symbol

The atom or constructor symbol, as the deduction spells it.

TYPE: str

*fields

The constructor's fields: integers for position slots, items for the rest; numbers become the machine's tensors.

TYPE: object DEFAULT: ()

RETURNS DESCRIPTION
RuntimeConstructor

The item, which run_deduction takes among the axioms of a deduction without a lexicon.

RAISES DESCRIPTION
KeyError

If the deduction declares no such symbol.

ValueError

If the field count differs from the constructor's arity.

Source code in src/quivers/qiec/program_runtime.py
def deduction_item(
    module: QiecModule, name: str, symbol: str, *fields: object
) -> RuntimeConstructor:
    """Build an item of a deduction's family as a host value.

    Parameters
    ----------
    module : QiecModule
        The module holding the deduction.
    name : str
        The deduction's name.
    symbol : str
        The atom or constructor symbol, as the deduction spells it.
    *fields : object
        The constructor's fields: integers for position slots, items for
        the rest; numbers become the machine's tensors.

    Returns
    -------
    RuntimeConstructor
        The item, which ``run_deduction`` takes among the axioms of a
        deduction without a lexicon.

    Raises
    ------
    KeyError
        If the deduction declares no such symbol.
    ValueError
        If the field count differs from the constructor's arity.
    """
    constructor_name = member_name(name, symbol)
    constructor = next(
        (item for item in module.constructors if item.name == constructor_name), None
    )
    if constructor is None:
        raise KeyError(f"deduction {name!r} declares no symbol {symbol!r}")
    if len(fields) != len(constructor.fields):
        raise ValueError(
            f"{symbol!r} of deduction {name!r} takes {len(constructor.fields)} "
            f"field(s), not {len(fields)}"
        )
    family = next(item for item in module.families if item.id == constructor.family)
    numbers = NumberDomain()
    return RuntimeConstructor(
        constructor=constructor.id,
        static_arguments=(),
        fields=tuple(
            machine_value(declared.type, field, numbers)
            for declared, field in zip(constructor.fields, fields, strict=True)
        ),
        result_type=TypeApplication(constructor=family.type_constructor, arguments=()),
    )